title,body,link,tags,view_count,is_answered,score,answer_count
Unit Testing GetxController,"<p>I'm a beginner with tdd so please forgive me if it's a dumb question.</p>
<p>I'm having difficulty unit testing GetxControllers.  Does anyone know a simple way of doing this?
Whenever I do I get errors since Get is calling onStart and it doesn't like the result Mockito's giving it.  I've tried using Mockito 5.0.1's auto generated code as well as the older syntax, class MockController extends Mock implements Controller{}, as well as extends Fake.</p>
<p>The auto generated code has build errors, since Mockito is trying to use _InternalFinalCallback, but it's not being imported as it's private.  I tried just copy pasting that part of the code into my generated file (and switching off pub build watch) but first that's a short term solution with it's own issues, 2nd it still doesn't work since the onStart and onDelete functions now tell me they're not valid overrides.</p>
<p>Also, I can see the get_test package but it's documentation is basically 0, and in the examples the controller is just used directly -- there's never a mocked controller.</p>
<p>I tried setting Get.testMode = true; but again that doesn't seem to do anything.  And while I found that property in the docs, I didn't find how to use it correctly.</p>
<p>Any help would be appreciated,</p>
<p>Here's my code but the issue seems to be with the GetxControllers, so I don't think it's relevant much:</p>
<pre><code>class FakeAuthController extends Fake implements AuthController {}

@GenerateMocks([AuthController])
void main() {
  TestWidgetsFlutterBinding.ensureInitialized();
  late MockAuthController mockAuthController;
  late FakeAuthController fakeAuthController;
  late SessionController sessionController;

  setUp(() {
    Get.testMode = true;
    mockAuthController = MockAuthController();
    fakeAuthController = FakeAuthController();
    Get.put&lt;AuthController&gt;(mockAuthController);

    sessionController = SessionController();
  });

  tearDown(() {
    Get.delete&lt;AuthController&gt;();
  });

  group('getSessionInfo', () {
    test('Calls authFacade getSignedInUserId', () async {
      await sessionController.getSessionInfo();

      when(Get.find&lt;AuthController&gt;()).thenReturn(fakeAuthController);

      verify(mockAuthController.getSignedInUserId());
    });
  });
}
</code></pre>
<p>There really isn't anything in my AuthController and session controller, but code is as follows:</p>
<pre><code>import 'package:get/get.dart';

class AuthController extends GetxController {
  String getSignedInUserId() {
    // await Future.delayed(Duration(milliseconds: 1));
    return '1';
  }
}


import 'package:get/get.dart';

import '../../auth/controllers/auth_controller.dart';
import '../models/session_info.dart';

class SessionController extends GetxController {
  final AuthController authController = Get.find&lt;AuthController&gt;();

  Rx&lt;SessionInfo&gt; sessionInfo = Rx&lt;SessionInfo&gt;();

  Future&lt;void&gt; getSessionInfo() async {
    // authController.getSignedInUserId();

    // sessionInfo.value = SessionInfo(userId: userId);
  }
}

</code></pre>
<p>And the auto-generated, buggy mock controller:</p>
<pre><code>// Mocks generated by Mockito 5.0.1 from annotations
// in smart_locker_controller/test/shared/controllers/session_controller_test.dart.
// Do not manually edit this file.

import 'dart:ui' as _i4;

import 'package:get/get_instance/src/lifecycle.dart' as _i2;
import 'package:get/get_state_manager/src/simple/list_notifier.dart' as _i5;
import 'package:mockito/mockito.dart' as _i1;
import 'package:smart_locker_controller/auth/controllers/auth_controller.dart'
    as _i3;

// ignore_for_file: comment_references
// ignore_for_file: unnecessary_parenthesis

class _Fake_InternalFinalCallback&lt;T&gt; extends _i1.Fake
    implements _i2._InternalFinalCallback&lt;T&gt; {}

/// A class which mocks [AuthController].
///
/// See the documentation for Mockito's code generation for more information.
class MockAuthController extends _i1.Mock implements _i3.AuthController {
  MockAuthController() {
    _i1.throwOnMissingStub(this);
  }

  @override
  int get notifierVersion =&gt;
      (super.noSuchMethod(Invocation.getter(#notifierVersion), returnValue: 0)
          as int);
  @override
  int get notifierMicrotask =&gt;
      (super.noSuchMethod(Invocation.getter(#notifierMicrotask), returnValue: 0)
          as int);
  @override
  bool get hasListeners =&gt;
      (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false)
          as bool);
  @override
  int get listeners =&gt;
      (super.noSuchMethod(Invocation.getter(#listeners), returnValue: 0)
          as int);
  @override
  _i2._InternalFinalCallback&lt;void&gt; get onStart =&gt;
      (super.noSuchMethod(Invocation.getter(#onStart),
              returnValue: _Fake_InternalFinalCallback&lt;void&gt;())
          as _i2._InternalFinalCallback&lt;void&gt;);
  @override
  _i2._InternalFinalCallback&lt;void&gt; get onDelete =&gt;
      (super.noSuchMethod(Invocation.getter(#onDelete),
              returnValue: _Fake_InternalFinalCallback&lt;void&gt;())
          as _i2._InternalFinalCallback&lt;void&gt;);
  @override
  bool get initialized =&gt;
      (super.noSuchMethod(Invocation.getter(#initialized), returnValue: false)
          as bool);
  @override
  bool get isClosed =&gt;
      (super.noSuchMethod(Invocation.getter(#isClosed), returnValue: false)
          as bool);
  @override
  String getSignedInUserId() =&gt;
      (super.noSuchMethod(Invocation.method(#getSignedInUserId, []),
          returnValue: '') as String);
  @override
  void update([List&lt;Object&gt;? ids, bool? condition = true]) =&gt;
      super.noSuchMethod(Invocation.method(#update, [ids, condition]),
          returnValueForMissingStub: null);
  @override
  void refreshGroup(Object? id) =&gt;
      super.noSuchMethod(Invocation.method(#refreshGroup, [id]),
          returnValueForMissingStub: null);
  @override
  void removeListener(_i4.VoidCallback? listener) =&gt;
      super.noSuchMethod(Invocation.method(#removeListener, [listener]),
          returnValueForMissingStub: null);
  @override
  void removeListenerId(Object? id, _i4.VoidCallback? listener) =&gt;
      super.noSuchMethod(Invocation.method(#removeListenerId, [id, listener]),
          returnValueForMissingStub: null);
  @override
  _i5.Disposer addListener(_i5.GetStateUpdate? listener) =&gt;
      (super.noSuchMethod(Invocation.method(#addListener, [listener]),
          returnValue: () {}) as _i5.Disposer);
  @override
  _i5.Disposer addListenerId(Object? key, _i5.GetStateUpdate? listener) =&gt;
      (super.noSuchMethod(Invocation.method(#addListenerId, [key, listener]),
          returnValue: () {}) as _i5.Disposer);
  @override
  void disposeId(Object? id) =&gt;
      super.noSuchMethod(Invocation.method(#disposeId, [id]),
          returnValueForMissingStub: null);
}
</code></pre>
",https://stackoverflow.com/questions/66685369/unit-testing-getxcontroller,"['flutter', 'unit-testing', 'flutter-getx']",8933,True,14,2
Unit testing Htmx?,"<p>How do you write unit tests for <a href=""https://Htmx.org"" rel=""nofollow noreferrer"">Htmx</a>?</p>
<p>Stack overflow isn't letting me post such a short question, so this paragraph says that I didn't see docs or a library about this.</p>
<p><strong>EDIT</strong>: Specifically, I wish to unit test in Django.</p>
",https://stackoverflow.com/questions/67133382/unit-testing-htmx,"['unit-testing', 'htmx']",644,True,6,2
Airflow unit testing,"<p>I would like to be able to unit test my airflow operators without having to run airflow db init before the tests.
Is there a way to do this ?</p>
<p>Thank you very much for your help !</p>
",https://stackoverflow.com/questions/68049095/airflow-unit-testing,"['python', 'unit-testing', 'airflow']",1488,True,3,2
Unit testing ngAfterViewInit,"<blockquote>
<p>Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has
changed after it was checked. Previous value for 'dataSource':
'undefined'. Current value: '[object Object]'.</p>
</blockquote>
<p>In my component.ts I am getting this error. due to having code in ngafterviewinit.</p>
<pre><code>  ngAfterViewInit(): void {
    this.role = this.aut.getuser();
    if (this.role ===  undefined) {
      this.router.navigate(['/']);
    }

    this.ELEMENT_DATA_RED_MALE = this.resul.fetchresults('red', 'male');
    this.dataSourceRedMale = this.ELEMENT_DATA_RED_MALE;
    this.ELEMENT_DATA_RED_FEMALE = this.resul.fetchresults('red', 'female');
    this.dataSourceRedFemale = this.ELEMENT_DATA_RED_FEMALE;
  
    this.ELEMENT_DATA_YELLOW_MALE = this.resul.fetchresults('yellow', 'male');
    this.dataSourceYellowMale = this.ELEMENT_DATA_YELLOW_MALE;
    this.ELEMENT_DATA_YELLOW_FEMALE = this.resul.fetchresults('yellow', 'female');
    this.dataSourceYellowFemale = this.ELEMENT_DATA_YELLOW_FEMALE;
  
    this.ELEMENT_DATA_BLUE_MALE = this.resul.fetchresults('blue', 'male');
    this.dataSourceBlueMale = this.ELEMENT_DATA_BLUE_MALE;
    this.ELEMENT_DATA_BLUE_FEMALE = this.resul.fetchresults('blue', 'female');
    this.dataSourceBlueFemale = this.ELEMENT_DATA_BLUE_FEMALE;
  
    this.ELEMENT_DATA_GREEN_MALE = this.resul.fetchresults('green', 'male');
    this.dataSourceGreenMale = this.ELEMENT_DATA_GREEN_MALE;
    this.ELEMENT_DATA_GREEN_FEMALE = this.resul.fetchresults('green', 'female');
    this.dataSourceGreenFemale = this.ELEMENT_DATA_GREEN_FEMALE;
  }
</code></pre>
<p>Please guide me about testing ngAfterviewInit, I am new to jasmine karma test.</p>
",https://stackoverflow.com/questions/68362753/unit-testing-ngafterviewinit,"['angular', 'unit-testing', 'jestjs', 'karma-jasmine', 'angular-unit-test']",2518,True,2,1
IFeatureManager Unit Testing,"<p>I have a Feature Flag in the Azure portal, used from some controllers in a .NET Core Web App.</p>
<p>At runtime, it works correctly switching on and off the FF on the real portal.</p>
<p>I should write 2 Unit tests, simulating when the Feature Flag is On and when Off.</p>
<p>For the Off, I can write</p>
<pre><code>var featMan = new Mock&lt;IFeatureManager&gt;().Object;
</code></pre>
<p>And it works, the problem is to simulate when On.</p>
<p>I found this page, <a href=""https://github.com/microsoft/FeatureManagement-Dotnet/issues/19#issue-517953297"" rel=""nofollow noreferrer"">https://github.com/microsoft/FeatureManagement-Dotnet/issues/19#issue-517953297</a> , but in the downloadable code there is no StubFeatureManagerWithFeatureAOn definition.</p>
",https://stackoverflow.com/questions/69269748/ifeaturemanager-unit-testing,"['azure', 'unit-testing', 'asp.net-core', 'azure-feature-manager']",1551,True,1,1
Unit Testing WeakReference,"<p>It seems the following code to unit test <code>WeakReference</code> does not work correctly/reliably:</p>
<pre><code>object realObject = new object();
WeakReference weakReference = new WeakReference(realObject);
Assert.NotNull(weakReference.Target);
realObject = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.Null(weakReference.Target);
</code></pre>
<p>The testing is run targeting both net461 and net5.0, for both DEBUG and RELEASE mode. The best result:</p>
<ul>
<li><p>Targeting net461: the above code runs successfully, for both DEBUG and RELEASE mode.</p>
</li>
<li><p>Targeting net5.0: the above code fails for both DEBUG and RELEASE mode at first. After reading this post (<a href=""https://stackoverflow.com/questions/69616548/garbage-collection-behaviour-difference-between-netframework-4-8-and-net-5"">Garbage collection behaviour difference between .NetFramework 4.8 and .Net 5</a>) it works running in RELEASE mode by adding <code>&lt;TieredCompilation&gt;false&lt;/TieredCompilation&gt;</code> to <code>.csproj</code>.</p>
</li>
</ul>
<p>So the problem narrows down to <strong>targeting net5.0 DEBUG mode</strong>.</p>
<p>I also came across the following posts but it seems they're not very helpful mostly because they're out-of-date:</p>
<ul>
<li><a href=""https://stackoverflow.com/questions/15062308/unit-testing-code-with-weakreference"">Unit Testing Code with WeakReference</a></li>
<li><a href=""https://stackoverflow.com/questions/5912797/testing-verifying-a-weakreference"">Testing/Verifying a WeakReference</a></li>
</ul>
<p>Worth to mention the answer from @Eric Lippert for <a href=""https://stackoverflow.com/questions/37462378/why-c-sharp-garbage-collection-behavior-differs-for-release-and-debug-executable"">Why C# Garbage Collection behavior differs for Release and Debug executables?</a> says: You <strong>absolutely cannot</strong> rely on the garbage collector having <strong>any particular behaviour whatsoever</strong> with respect to the lifetime of a local, which suggests testing a WeakReference cannot be done reliably.</p>
<p>Edit: More information about the context of why using a <code>WeakReference</code>:</p>
<p>I'm developing a framework providing class <code>Entity&lt;T&gt;</code> and <code>Record&lt;T&gt;</code> similar to <code>System.Data.DataRow</code> and <code>System.Data.DataRowView</code>, with the most significance that the prior one is strongly typed. Entity is the model provides its own event to notify changes, <code>Record&lt;T&gt;</code> is a viewmodel that wraps <code>Entity&lt;T&gt;</code> to translate the change event into <code>INotifyPropertyChanged</code> plus other things such as databinding, validations, etc. <code>Entity&lt;T&gt;</code> should not aware the existence of <code>Record&lt;T&gt;</code>. To avoid memory leak, <code>Record&lt;T&gt;</code> should be GC reclaimed when only Entity is still referenced.</p>
<p>The example code for the event hookup:</p>
<p><code>IEntityListener</code> Implemented by <code>Record&lt;T&gt;</code> class:</p>
<pre><code>internal interface IEntityListener
{
    void OnFieldUpdated(FieldUpdatedEventArgs e);
}
</code></pre>
<p><code>WeakEntityListner</code> to do the event hookup:</p>
<pre><code>internal sealed class WeakEntityListener
{
    private readonly WeakReference&lt;IEntityListener&gt; _weakListener;
    private readonly Entity _entity;

    internal WeakEntityListener(Entity entity, IEntityListener listener)
    {
        _entity = entity;
        _weakListener = new (listener);
        _entity.FieldUpdated += OnFieldUpdated;
    }

    private void OnFieldUpdated(object? sender, FieldUpdatedEventArgs e)
    {
        if (_weakListener.TryGetTarget(out var listener))
            listener.OnFieldUpdated(e);
        else
            CleanUp();
    }

    private void CleanUp()
    {
        _entity.FieldUpdated -= OnFieldUpdated;
    }
}
</code></pre>
<p>I would like to have method <code>OnFieldUpdated</code> and <code>CleanUp</code> fully covered by unit test.</p>
",https://stackoverflow.com/questions/70060061/unit-testing-weakreference,"['c#', '.net', '.net-core', 'garbage-collection', 'weak-references']",291,True,1,3
Unit-testing datetime,"<p>Can someone help me to unit test this line of code?</p>
<pre><code>from datetime import datetime, timedelta, timezone

def get_timestamp_plus_100_year():
    return int((datetime.now(timezone.utc) + timedelta(days=100 * 365)).timestamp())
</code></pre>
<p>I try this, but I don't know how to assign the values:</p>
<pre><code>@patch(&quot;src.shared.utils.timedelta&quot;)
@patch(&quot;src.shared.utils.datetime&quot;)
def test_get_timestamp_now_plus_100_years(self, mock_datetime, mock_timedelta):
    mock_datetime.now.return_value = 2021-09-14 15:54:25.284087+00:00
    mock_timedelta.return_value = 36500 days, 0:00:00

    self.assertEqual(
        get_timestamp_plus_100_year(),
        int((mock_datetime.now.return_value 
             + mock_timedelta.return_value).timestamp_return_value ),
    )
</code></pre>
",https://stackoverflow.com/questions/69181127/unit-testing-datetime,"['python', 'python-3.x', 'python-unittest', 'python-datetime', 'python-unittest.mock']",1174,True,1,1
Unit Testing Flux.doOnNext(),"<p>I have a method which takes a Flux as a parameter.  Inside the method it then configures the Flux and another method subscribes to it.</p>
<pre><code>public class StringProcessor {

  private final stringParsingService stringParsingService;

  public void subscribeStringFlux(Flux&lt;String&gt; stringFlux) {
    fluxConfiguration(stringFlux)
        .subscribe();
  }

  Flux&lt;String&gt; fluxConfiguration(Flux&lt;String&gt; stringFlux) {
    return stringFlux
        .filter(stringValidatorr::isValidString)
        .doOnNext(itemString -&gt; {
          List&lt;String&gt; values = stringParsingService.parseValues(itemString);
        })
        .onErrorContinue((e,object) -&gt; log.error(e.getClass().toString()+&quot; &quot;+e.getMessage()));
  }
}
</code></pre>
<p>I am trying to test that the code in doOnNext is executed.  I've tried to use StepVerifier (with Mockito for the service) however it never seems to enter the code during the test when I put breakpoints in stringParsingService.parseValue().  However, the code does run and execute as expected though when not being run in a test with real data.</p>
<p>My question is, how do you write tests that cover actions taken in a Flux.doOnNext()?  Is there a way to use StepVerifier that will get it to execute code in doOnNext()? I've searched for days, and tried multiple approaches and so far none of them have worked.</p>
<p>The only way I've found so far that even comes close is to do the following (however this of course doesn't count for code coverage):</p>
<pre><code>    Flux&lt;String&gt; testStringFlux = Flux.just(&quot;a_test_string&quot;);

    StepVerifier.create(testStringFlux)
        .consumeNextWith(itemString -&gt; {
           List&lt;String&gt; values = stringParsingService.parseValues(itemString);
        })
        .verifyComplete();
</code></pre>
",https://stackoverflow.com/questions/68572102/unit-testing-flux-doonnext,"['java', 'spring-boot', 'unit-testing', 'spring-webflux', 'project-reactor']",1480,True,0,2
Pyqt unit testing,"<p>I have written small desktop app which save, quit and pop up window. I would like to write unit test for them I have gone through Qt unit testing but Qt unit testing has very costly unit test framework. is it possible to any opensource along with example to test functionality.</p>
",https://stackoverflow.com/questions/69554290/pyqt-unit-testing,['pyqt5'],18,False,0,0
Angular unit testing,"<p>I have this error:</p>
<blockquote>
<p>Error: Uncaught (in promise): NullInjectorError: R3InjectorError(DynamicTestModule)[UserInfoService -&gt; UsersService -&gt; AuthService -&gt; InjectionToken auth0.client -&gt; InjectionToken auth0.client]:            NullInjectorError: No provider for InjectionToken auth0.client!         NullInjectorError:</p>
</blockquote>
<p>My spec.ts file:</p>
<pre><code>describe('IssuingInformationComponent', () =&gt; {
let component: IssuingInformationComponent;
let fixture: ComponentFixture&lt;IssuingInformationComponent&gt;;

beforeEach(waitForAsync(() =&gt; {
    TestBed.configureTestingModule({
        imports: [ReactiveFormsModule, FormsModule, HttpClientTestingModule
             ,AuthModule.forRoot({
            domain: 'dgfgfg',
            clientId: 'fgggfg',
         }),
        ],
     
        declarations: [IssuingInformationComponent],
        schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
    }).compileComponents().then(() =&gt; {
        fixture = TestBed.createComponent(IssuingInformationComponent);
        component = fixture.componentInstance;
        component.ngOnInit();
        fixture.detectChanges();

    });
}));`
</code></pre>
",https://stackoverflow.com/questions/70015016/angular-unit-testing,['unit-testing'],139,False,0,0
Android Unit testing dataStore,"<p>I'm trying to write a test for my view model that gets the data from datastore but I can't figure it out. this is my data store implementation. I save the user data such as email and token when user is sign up or sign in :</p>
<pre><code>    class FlowAuthenticationDataStore(context: Context) : AuthenticationDataStore {
    private val dataStore = context.createDataStore(name = &quot;user_auth&quot;)
    private val userEmailKey = preferencesKey&lt;String&gt;(name = &quot;USER_EMAIL&quot;)
    private val userTokenKey = preferencesKey&lt;String&gt;(name = &quot;USER_TOKEN&quot;)
    private val userNameKey = preferencesKey&lt;String&gt;(name = &quot;USER_NAME&quot;)
    private val userIsLoginKey = preferencesKey&lt;Boolean&gt;(name = &quot;USER_IS_LOGIN&quot;)

    override suspend fun updateUser(userDataStore: UserDataStoreModel) {
        dataStore.edit {
            it[userEmailKey] = userDataStore.email
            it[userTokenKey] = userDataStore.token
            it[userNameKey] = userDataStore.name
            it[userIsLoginKey] = userDataStore.isLogin
        }
    }

    override fun observeUser(): Flow&lt;UserDataStoreModel&gt; {
        return dataStore.data.catch {
            if (it is IOException) {
                emit(emptyPreferences())
            } else {
                throw it
            }
        }.map {
            UserDataStoreModel(
                it[userIsLoginKey]!!,
                it[userNameKey]!!,
                it[userEmailKey]!!,
                it[userTokenKey]!!
            )
        }
    }
}
</code></pre>
<p>and this is my view model. I observe the user data store and if its success and has a data then I update my live data. If there is not data and user is first time to register then my live data is equal to default value from data class :</p>
<pre><code>    class SplashScreenViewModel(
    private val flowOnBoardingDataStore: FlowAuthenticationDataStore,
    private val contextProvider: CoroutineContextProvider,
) :
    ViewModel() {
    private val _submitState = MutableLiveData&lt;UserDataStoreModel&gt;()
    val submitState: LiveData&lt;UserDataStoreModel&gt; = _submitState

    fun checkUserLogin() {
        viewModelScope.launch {
            kotlin.runCatching {
                withContext(contextProvider.io) {
                        flowOnBoardingDataStore.observeUser().collect {
                            _submitState.value = it
                        }
                }
            }.onFailure {
                _submitState.value = UserDataStoreModel()
            }
        }

    }
}
</code></pre>
<p>and this is my test class:</p>
<pre><code>    @ExperimentalCoroutinesApi
class SplashScreenViewModelTest {
    private val dispatcher = TestCoroutineDispatcher()

    @get:Rule
    val rule = InstantTaskExecutorRule()

    @get:Rule
    val coroutineTestRule = CoroutineTestRule(dispatcher)

    @RelaxedMockK
    lateinit var flowOnBoardingDataStore: FlowAuthenticationDataStore

    private fun createViewModel()=SplashScreenViewModel(flowOnBoardingDataStore,
        CoroutineContextProvider(dispatcher,dispatcher)
    )

    @Before
    fun setup() {
        MockKAnnotations.init(this)
    }

    @After
    fun tearDown() {
        unmockkAll()
    }

    @Test
    fun `when user is already sign in, then state should return model`()=dispatcher.runBlockingTest {
        val viewModel=createViewModel()
        val userDataStoreModel= UserDataStoreModel(true,&quot;test&quot;,&quot;test&quot;,&quot;test&quot;)
        flowOnBoardingDataStore.updateUser(userDataStoreModel)
        viewModel.checkUserLogin()
        assertEquals(userDataStoreModel,viewModel.submitState.value)
    }
}
</code></pre>
<p>This is the result of my test function:</p>
<pre><code>    junit.framework.AssertionFailedError: 
Expected :UserDataStoreModel(isLogin=true, name=test, email=test, token=test)
Actual   :null
</code></pre>
",https://stackoverflow.com/questions/65856930/android-unit-testing-datastore,"['android', 'kotlin']",2272,True,6,1
Unit testing with get_current_context,"<p>I want to build a unit test for a function which uses get_current_context in Apache Airflow. The function is used within multiple tasks to create a filename used to read and write to the file from these different tasks.</p>
<p>Here is an example of the function:</p>
<pre><code>def get_filename():
    from airflow.operators.python import get_current_context

    context = get_current_context()
    dag_id = context['dag'].__dict__['_dag_id']
    log_time = context['data_interval_start'].strftime(&quot;%Y-%m-%d_%H-%M-%S&quot;)
    log_file = f'/path/logs/{dag_id}/{log_time}.txt'
    return log_file
</code></pre>
<p>How do I set the context in the unit test so that the function is executable? I don't even know where to begin.</p>
",https://stackoverflow.com/questions/70298337/unit-testing-with-get-current-context,"['python', 'unit-testing', 'airflow']",1039,True,5,1
Angular unit testing window.location.href,"<pre><code>login() {
  const endPoint = environment.myEndPoint;
  window.location.href = endPoint + '/myPath/login';
}
</code></pre>
<p>I am having angular service file with above code written in it to redirect to login URL. Now, I have written the below code in spec file to unit test it.</p>
<pre><code>it('should call login method',() =&gt; {
  service.digitalssologin();
});
</code></pre>
<p>This test case sometimes covers the login method and executes successfully, while sometimes it fails and karma tool disconnects, so other test cases also stops executing. Is there any other way to write test case for this method?</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/69537614/angular-unit-testing-window-location-href,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",12681,True,4,1
unit testing static objects,"<p>I have classes that are configurable via composition.</p>
<p>For example:</p>
<h5>objects.cpp:</h5>
<pre><code>dog::config cfg = { .bark = loud; }
static dog my_dog(cfg);
</code></pre>
<p>In order to be MISRA compliant (3-4-1), the object <code>dog</code> requires the <code>static</code> storage specifier.</p>
<p>It is easy to unit test the <em>class</em> <code>dog</code>, and I can provide it with whatever configuration I want.</p>
<p>The problem is, in my production project, I want to test <code>my_dog</code> to ensure it was configured correctly, and that the way in which it was configured works as expected. In addition, this will allow <code>dog</code> to interact with other configurable objects such as <code>newspaper</code>, and allow for some higher-level testing.</p>
<p>I am not sure if this is possible without modifying the <code>objects.cpp</code> to include test code, which I don't want to do. If I were to remove <code>static</code> it would be easy, but I can't do that. I also have multiple instances of <code>dog</code> with different configurations, so I don't make the configuration variables reside internally somehow.</p>
<p>Any ideas?</p>
",https://stackoverflow.com/questions/69132321/unit-testing-static-objects,"['c++', 'unit-testing']",82,False,2,1
Nestjs -Middleware unit testing,"<p>I am working on a Nestjs application, and i would like to make a unit test for the following middleware:</p>
<pre class=""lang-js prettyprint-override""><code>@Injectable()
export class LocaleMiddleware implements NestMiddleware {
    use(req: Request, res: Response, next: () =&gt; void) {
        if (!req.headers['accept-language'] || !(req.headers['accept-language']! in LocaleEnum)) {
            req.headers['accept-language'] = LocaleEnum.en;
        }
        next();
    }
}
</code></pre>
<p>How can mock the request and check that accept-language is assigned correctly ??</p>
",https://stackoverflow.com/questions/68392337/nestjs-middleware-unit-testing,"['unit-testing', 'localization', 'nestjs', 'middleware']",301,False,2,0
Node.js BigQuery unit testing,"<p>I'm new to writing mocha unit tests and would like to ask how the unit test for the following code would look like (especially for the BigQuery part). The code is in a PubSub triggered Cloud Function and inserts rows into a BigQuery table:</p>
<pre><code>/**
 * Triggered from a message on a Cloud Pub/Sub topic.
 *
 * @param {!Object} event Event payload.
 * @param {!Object} context Metadata for the event.
 */
const {BigQuery} = require('@google-cloud/bigquery');
const bigqueryClient = new BigQuery();

const dataset = 'dataset_name';
const table = 'table_name';

exports.sendtobigquery = (event, context) =&gt; {
  const pubsubMessage = Buffer.from(event.data, 'base64').toString();
  BigQueryInsert(pubsubMessage, dataset, table);
};

async function BigQueryInsert(pubsubMessage, dataset, table) {
  const date = new Date().toISOString();                // new date
  const rows = [{field1: pubsubMessage, field2: date}]; // new field2
  await bigqueryClient
    .dataset(dataset)
    .table(table)
    .insert(rows);
}

</code></pre>
<p>I've seen here <a href=""https://stackoverflow.com/questions/62492844/mocking-es6-bigquery-class"">Mocking ES6 BigQuery class</a> that sinon and proxyquire should be used but I don't understand how to do that for my code exactly.</p>
<p>Any help is appreciated.</p>
<p><strong>Update:</strong>
I added a new date field as part of the row but I'm having trouble here too when it comes to the unit test. For the date I tried using <code>sinon.useFakeTimers</code> in the <code>index.test.js</code> from the answer like that</p>
<pre><code>describe('66267929', () =&gt; {
  const now = new Date();
  const date = sinon.useFakeTimers(now.getTime());
  beforeEach(() =&gt; {
    sinon.restore();
  });
  afterEach(() =&gt; {
    sinon.restore();
  });
  it('should pass', async () =&gt; {
    ...  // same code
    ...  // same code
    sinon.assert.calledWithExactly(bigqueryClientStub.insert, [{ field1: 'teresa teng', field2: date }]);
  });
});
</code></pre>
<p>but that resulted in &quot;AssertError: expected stub to be called once but was called 0 times&quot;. How can this be done?</p>
",https://stackoverflow.com/questions/66267929/node-js-bigquery-unit-testing,"['node.js', 'unit-testing', 'google-bigquery', 'sinon']",1157,True,1,1
Unit testing dependency injections,"<p>I want to mock dependencies in a class but I cannot find the right way to achieve that. Using sinon for the unit testing. For example:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>const { classB } = require(""./classes/classB"");
const { classC } = require(""./classes/classC"");
const sinon = require(""sinon"");

class classA {
    constructor() {
        this.classB = new classB();
        this.classC = new classC();
    }
 
    doSomething() {
        const data = this.classB.getInfo();
        const processed = processInfo(data);
        this.classC.processedData(processed);
        
    }
    
    processInfo(data) {
        // doesSomeProcessing
    }
}

module.exports = {
    classA
};

describe(""classA"", () =&gt; {
    describe(""when instantiated"", () =&gt; {
        it(""calls classB's getInfo once, classC's processedData data once."", () =&gt; {
            sinon.stub(classB);
            let clsA = new classA();
            sinon.assert.calledOnce(classB.getInfo);
            sinon.assert.calledOnce(classC.processedData);
            // Also can we do something like this?
            // when classB.getinfo.then(provideMockData) 
            // so that we can mock the calls being made to avoid actual calls?
        });
    });
});</code></pre>
</div>
</div>
</p>
<p>I tried doing research around this but could not find a workable solution. Any insight will be super helpful! Thanks in advance and apologies for any trouble caused!</p>
",https://stackoverflow.com/questions/66751571/unit-testing-dependency-injections,"['javascript', 'unit-testing', 'mocking', 'sinon', 'sinon-chai']",185,True,1,1
CameraX unit testing Android,"<p>I`m begginer in unit testing. The more I read, the less I understand what to do.
I'm trying to write unit tests for the cameraX, but I'm having trouble figuring it out. Here is my code now</p>
<p>My method:</p>
<pre><code>  fun startCamera() {
    val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
    cameraProviderFuture.addListener(
        {
            cameraProvider = cameraProviderFuture.get()

            val cameraSelector = CameraSelector.Builder()
                .requireLensFacing(cameraSelectorOption)
                .build()

            setCameraConfig(cameraProvider, cameraSelector)

        }, ContextCompat.getMainExecutor(requireContext())
    )
}
</code></pre>
<p>My unit test:</p>
<pre><code>@RunWith(MockitoJUnitRunner::class)
</code></pre>
<p>class CameraFragmentTest {</p>
<pre><code>@get:Rule
val permissionRule = GrantPermissionRule.grant(
    Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
    Manifest.permission.READ_EXTERNAL_STORAGE
)

@get:Rule
val activityRule: ActivityTestRule&lt;MainActivity&gt; = ActivityTestRule(MainActivity::class.java)

@Mock
lateinit var cameraProviderFuture: ProcessCameraProvider
lateinit var processCameraProvider: ProcessCameraProvider
private lateinit var mockContext: Context

@Test
fun useAppContext() {
    val context = ApplicationProvider.getApplicationContext() as Context
    assertEquals(&quot;com.android.example.studyprojectrnc&quot;, context.packageName)
}

@Test
fun testStartCamera() {

    //init
    val cameraFragment : CameraFragment = mock()

    //work
    val result = cameraFragment.startCamera()

    //assert
    Assert.assertEquals(result)
}
</code></pre>
<p>}</p>
<p>I would be very grateful for an example of test writing</p>
<p>Also maybe you can recommend what else I can read or any courses on testing (although a lot of information in my head is already making me crazy)</p>
<p>So... Please help me understand this т_т</p>
",https://stackoverflow.com/questions/70123690/camerax-unit-testing-android,"['android', 'unit-testing', 'testing', 'camera', 'android-camerax']",540,False,1,1
MSTest Unit Testing Controller,"<p><strong>Learning MSTest</strong> -- trying to unit test a REST function:  <em>AccountController</em> (which I believe will work) I want to start with <em>Register</em>.  I can't get the Mocks setup for some reason.  (Moq is installed).
Also, I'm confused as to how this could possibly be of any use; if I mock all the controller inputs, I'm not going to get anything back?  Your Advice?</p>
<p>AccountController - target of the unit test:</p>
<pre><code>namespace API.Controllers
{
    public class AccountController : BaseApiController
    {
        private readonly UserManager&lt;AppUser&gt; _userManager;
        private readonly SignInManager&lt;AppUser&gt; _signInManager;
        private readonly RoleManager&lt;IdentityRole&gt; _roleManager;
        private readonly ITokenService _tokenService;
        private readonly IMapper _mapper;
        public AccountController(
            UserManager&lt;AppUser&gt; userManager,
            SignInManager&lt;AppUser&gt; signInManager,
            RoleManager&lt;IdentityRole&gt; roleManager,
            ITokenService tokenService,
            IMapper mapper)
        {
            _signInManager = signInManager;
            _roleManager = roleManager;
            _mapper = mapper;
            _tokenService = tokenService;
            _userManager = userManager;
        }

    [HttpPost(&quot;register&quot;)]
    // [Authorize]
    [Authorize(Roles = &quot;Admin&quot;)]
    public async Task&lt;ActionResult&lt;UserDto&gt;&gt; Register(RegisterDto registerDto)
    {
        if (await this.UserExistsAsync(registerDto.Username)) return BadRequest(&quot;Username is taken&quot;);

        var user = _mapper.Map&lt;AppUser&gt;(registerDto);
        user.UserName = registerDto.Username.ToLower();
        var result = await _userManager.CreateAsync(user, registerDto.Password);

        if (!result.Succeeded) return BadRequest(result.Errors);

        var roleResult = await _userManager.AddToRoleAsync(user, &quot;User&quot;);
        if (!roleResult.Succeeded) return BadRequest(result.Errors);

        return new UserDto
        {
            Username = user.UserName,
            Token = await _tokenService.CreateToken(user),
            KnownAs = user.KnownAs
        };
    }
</code></pre>
<p>BTW BaseController is simply:</p>
<pre><code>{
    [ApiController]
    [Route(&quot;api/[controller]&quot;)]
    public class BaseApiController : ControllerBase
    {      
    }
}
</code></pre>
<p>The Unit Test so far is:</p>
<pre><code>namespace API.Controllers.Tests
{
    [TestClass()]
    public class AccountControllerTests
    {
        [TestMethod()]
        public async void AccountController_Register()
        {
            var _userManager = new Mock&lt;UserManager&lt;AppUser&gt;&gt;();
            var _signInManager = new Mock&lt;SignInManager&lt;AppUser&gt;&gt;();
            var _roleManager = new Mock&lt;RoleManager&lt;IdentityRole&gt;&gt;();
            ITokenService tokenService;
            IMapper mapper;

            RegisterDto userDto = new RegisterDto()
            {
                Username = &quot;Admin&quot;,
                Password = &quot;Secret1234&quot;,
                FirstName = &quot;Johnny&quot;,
                LastName = &quot;Appleseed&quot;,
                Phone1 = &quot;6175551212&quot;,
                Phone2 = &quot;&quot;,
                KnownAs = &quot;Dude&quot;,
                EmailAddress = &quot;Dude@Somewhere.com&quot;,
                Question = &quot;ask&quot;,
                Answer = &quot;answer&quot;,
            };

            AccountController accountController = new AccountController(_userManager, 
                                                    _signInManager, 
                                                    _roleManager, 
                                                    tokenService, 
                                                    mapper);
            await accountController.Register(userDto);

            Assert.Fail(); &lt;&lt;---- this will be replaced obviously
        }
</code></pre>
<p>The compiler error looks like this:
<a href=""https://i.stack.imgur.com/EwAAk.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/EwAAk.jpg"" alt=""enter image description here"" /></a></p>
<p>Other arguments have a similar error message.</p>
<p>Your Advice OR point me to a tutorial somewhere that covers MSTest Mocks :-)
Thanks in advance.</p>
<p>Chuck</p>
",https://stackoverflow.com/questions/67888919/mstest-unit-testing-controller,"['c#', 'unit-testing', '.net-core', 'moq', 'mstest']",495,True,1,1
Android Biometric unit testing,"<p>I need to write Unit test cases for Android Biometric prompt. I tried to search many links but didn't get the proper direction. Need to write unit test cases for UI Biometric is visible or not. Do I have permission to show biometric or not etc. Can someone please provide the suggestions?</p>
",https://stackoverflow.com/questions/66268666/android-biometric-unit-testing,"['android', 'unit-testing', 'junit', 'robolectric', 'android-unit-testing']",459,False,1,0
Skaffold/K8s Unit testing,"<p>I'm trying to unit test my microservices before deployment, however in the Skaffold pipeline images are tested before deployment. The issue here is that the code in my images are dependent on configs and credentials that are mounted from k8s configmaps and secrets, therefore tests will always fail if unit tests are run before deployment.</p>
<p>How do I run unit tests for microservices with skaffold? How are unit tests normally run for microservices? Looking around the net, no one seems to have a straight answer.</p>
<p>Any guidance will be much appreciated.</p>
",https://stackoverflow.com/questions/70256073/skaffold-k8s-unit-testing,"['unit-testing', 'kubernetes', 'pytest', 'devops', 'skaffold']",604,True,1,1
Unit testing mirkoORM entities,"<p>I'm trying to unit test a method in a MikroORM entity and thus to populate a mikroORM <code>collection</code> field with test data. (I use jest) :</p>
<pre class=""lang-js prettyprint-override""><code>describe('Team Tests', () =&gt; {
    it('isLeader should return true when given user is the team leader', () =&gt; {
       // Given
        const team = new Team('Test team');
        const user = new User('Test User', 'test@test.fr');

        team.members.add(new TeamMember(user, TeamRole.Leader));

        // When
        const result = team.isLeader(user.userId);

        // Then
        expect(result).toBe(true);
    });
});
</code></pre>
<p>However, when I run my test, I hit the following error when adding the data to the collection :</p>
<pre><code>Cannot read properties of undefined (reading 'properties')
TypeError: Cannot read properties of undefined (reading 'properties')
    at Collection.get property [as property] (C:\Users\arsen\git\HorizonWeb\api\node_modules\@mikro-orm\core\entity\ArrayCollection.js:123:44)
    at Collection.validateItemType (C:\Users\arsen\git\HorizonWeb\api\node_modules\@mikro-orm\core\entity\Collection.js:317:71)
    at C:\Users\arsen\git\HorizonWeb\api\node_modules\@mikro-orm\core\entity\Collection.js:111:40
    at Array.forEach (&lt;anonymous&gt;)
    at Collection.add (C:\Users\arsen\git\HorizonWeb\api\node_modules\@mikro-orm\core\entity\Collection.js:111:19)
    at Object.&lt;anonymous&gt; (C:\Users\arsen\git\HorizonWeb\api\src\teams\team.entity.spec.ts:11:22)
    at Promise.then.completed (C:\Users\arsen\git\HorizonWeb\api\node_modules\jest-circus\build\utils.js:390:28)
    at new Promise (&lt;anonymous&gt;)
    at callAsyncCircusFn (C:\Users\arsen\git\HorizonWeb\api\node_modules\jest-circus\build\utils.js:315:10)
    at _callCircusTest (C:\Users\arsen\git\HorizonWeb\api\node_modules\jest-circus\build\run.js:218:40)
</code></pre>
<p>Any idea of how to properly unit test a MikroORM entity ?</p>
",https://stackoverflow.com/questions/69924546/unit-testing-mirkoorm-entities,"['node.js', 'typescript', 'unit-testing', 'jestjs', 'mikro-orm']",1513,False,1,1
Unit Testing context manager,"<p>I have the below class. How could I write a unit test for the load_config_from_yaml method? I have written unit tests before but never with a context manager involved (in the tested side).</p>
<pre><code>import logging.config
import yaml

# Config for the root logger
class RootLogger:
    def __init__(self):
        self.root_logger = self.load_config_from_yaml()

    @staticmethod
    def load_config_from_yaml():
        &quot;&quot;&quot;
        Fetch the config in the yaml file to set up the console and file handlers
        Returns:
            logger object
        &quot;&quot;&quot;
        with open('mylogger_config.yml', 'r') as config_yaml:
            config = yaml.safe_load(config_yaml.read())
            logging.config.dictConfig(config)
            return logging.getLogger(__name__)
</code></pre>
<p>This is mylogger_config.yaml:</p>
<pre><code>version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
loggers:
  sampleLogger:
    level: DEBUG
    handlers: [console]
    propagate: no
root:
  level: DEBUG
  handlers: [console]
</code></pre>
",https://stackoverflow.com/questions/70331314/unit-testing-context-manager,"['python', 'unit-testing']",270,False,1,0
Laravel Feature/Unit Testing,"<p>Since I am still rather a beginner in Laravel, I just stumbled upon an interesting issue with testing and need a second opinion.</p>
<p>I wrote models, controllers, views, factories, seeders and then (feature) tests. Tests do cover a lot (won't say all), but I just found out an issue which was not caught by tests, despite it should. Tests are mostly done by calling HTTP endpoints, so in theory it should show, add, edit and delete the data as user would. Factories are making sure that the entered data is about the same as user would enter (please let's leave out fraudulent users for this talk, that can change HTTP POST request).</p>
<p>So the issue was that model's attribute accepts <code>true</code> or <code>false</code>, factory only generates these two values for that attribute, but in controller when editing I wrongly set that if value is false or not present, it sets value to <code>null</code>. Strangely, despite I ran a lot of tests, this issue never showed up before, it only showed when I manually tried to update the model.</p>
<p>So, my questions:</p>
<ul>
<li>why the tests didn't catch this issue, despite in some cases my edit call did send a <code>false</code> for that attribute?</li>
<li>how detailed are you writing the tests for your code? Are you testing ever possible outcome, with valid and invalid data, making a huge number of tests? Because testing all possible combinations will make number of tests huge.</li>
</ul>
<p>Some code, since I know some of you will ask (note that I will only add relevant parts, not everything):</p>
<p>migration:</p>
<pre><code>class CreateClientsTable extends Migration
{
    public function up()
    {
        Schema::create('clients', function (Blueprint $table) {
            $table-&gt;id();
            ...
            $table-&gt;boolean('invoice_details')-&gt;default(false);
            ...
        });
    }
    public function down()
    {
        Schema::dropIfExists('clients');
    }
}
</code></pre>
<p>model:</p>
<pre><code>class Client extends Model
{
    use HasFactory;

    protected $fillable = [
        ...
        'invoice_details',
        ...
    ];

    ...

    protected static function newFactory(): Factory
    {
        return ClientFactory::new();
    }
}
</code></pre>
<p>controller:</p>
<pre><code>class ClientController extends Controller
{
    ...
    
    public function edit(int $id): View
    {
        $data = Client::findOrFail($id);
        return view('client::edit', compact('data'));
    }

    public function update(UpdateClientRequest $request, int $id)
    {
        $client = Client::findOrFail($id);

        $response = $client-&gt;update([
            ...
            'invoice_details' =&gt; $request-&gt;invoice_details ?? null, // NOTE THE NULL, THIS TRIGGERED THE ERROR
            ...
        ]);

        ...
        
        return CustomResponse::resource($request, 'update', $response, route('client.index'), Client::findOrFail($id));
    }
}
</code></pre>
<p>factory:</p>
<pre><code>class ClientFactory extends Factory
{
    protected $model = Client::class;

    public function definition(): array
    {
        $details = [
            ...
            'invoice_details' =&gt; $this-&gt;faker-&gt;randomElement([true, false]),
        ];

        if ($details['invoice_details']) {
            ...
        }

        return $details;
    }
}
</code></pre>
<p>seeder:</p>
<pre><code>class ClientsSeeder extends Seeder
{
    public function run()
    {
        $client = Client::factory()-&gt;create();
    }
}
</code></pre>
<p>Error:</p>
<blockquote>
<p>SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'invoice_details' cannot be null (SQL: update <code>clients</code> set <code>invoice_details</code> = ?, <code>clients</code>.<code>updated_at</code> = 2021-06-23 13:14:15 where <code>id</code> = 1)</p>
</blockquote>
",https://stackoverflow.com/questions/68101737/laravel-feature-unit-testing,"['laravel', 'laravel-testing']",255,True,1,1
Unit testing for ServiceBusReceivedMessage,"<p>My project is in java, I am moving from &quot;com.microsoft.azure:azure-servicebus&quot; to &quot;com.azure:azure-messaging-servicebus&quot;.
The migration was successful, but I am facing issues in writing unit tests.
I wanted to create a object of ServiceBusReceivedMessage but not able to do so.</p>
<ol>
<li>Constructor of this is private.</li>
<li>Some site suggest to use - ServiceBusModelFactory to create object of ServiceBusReceivedMessage but I could not find that in java SDK.</li>
<li>Could not mock it with easy mock as the class is final.</li>
</ol>
<p>Any idea's on how to write unit test of this.</p>
",https://stackoverflow.com/questions/68254641/unit-testing-for-servicebusreceivedmessage,"['azure', 'azureservicebus', 'azure-servicebus-queues']",2269,False,1,1
Espresso Unit Testing NullPointerException,"<p>I'm have a problem with my unit testing.
when set favorite value from unit testing, but return always NullPointerException.</p>
<p>this is my repository:</p>
<pre><code>class FakeFilmRepository(
    private val remoteDataSource: RemoteDataSource,
    private val localDataSource: LocalDataSource,
    private val appExecutors: AppExecutors) : FilmDataSource {

    override fun setFilmFavorite(film: FilmEntity, state: Boolean) =
        appExecutors.diskIO().execute { localDataSource.setFilmFavorite(film, state) }}
</code></pre>
<p>And this is my unit testing:</p>
<pre><code>class FilmRepositoryTest {

@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()

private val remote = mock(RemoteDataSource::class.java)
private val local = mock(LocalDataSource::class.java)
private val appExecutors = mock(AppExecutors::class.java)
private val filmRepository = FakeFilmRepository(remote, local, appExecutors)

private val movieResponses = DataDummy.generateRemoteDummyMovies()
private val movieId = movieResponses[0].id
private val movieCastResponses = DataDummy.generateRemoteDummyCasts(movieId)

@Mock
private lateinit var observer: Observer&lt;FilmWithCast&gt;

@Test
fun setFavoriteFilm() {
    val dummyFilmWithCast = Resource.success(DataDummy.generateDummyFilmWithCasts(DataDummy.generateDummyMovies()[0], false))
    val film = MutableLiveData&lt;Resource&lt;FilmWithCast&gt;&gt;()
    film.value = dummyFilmWithCast
    `when`(filmRepository.getFilmWithCasts(movieId)).thenReturn(film)

    val castResource = film.value
    if (castResource != null) {
        val filmWithCast = castResource.data
    
        if (filmWithCast != null) {
            val filmEntity = filmWithCast.mFilm
            val newState = !filmEntity.favorite
            filmRepository.setFilmFavorite(DataDummy.generateDummyMovies()[0], newState) //ERROR NULL
        }
    }

    verify(observer).onChanged(dummyFilmWithCast.data)
} }
</code></pre>
<p>Result ERROR NULL:</p>
<pre><code>java.lang.NullPointerException
at com.pamungkasrizall.films.data.FakeFilmRepository.setFilmFavorite(FakeFilmRepository.kt:188)
at com.pamungkasrizall.films.data.FilmRepositoryTest.setFavoriteFilm(FilmRepositoryTest.kt:115)
</code></pre>
<p>How to fix it?</p>
",https://stackoverflow.com/questions/66435859/espresso-unit-testing-nullpointerexception,"['android', 'unit-testing', 'kotlin']",189,False,1,1
Unit Testing for pgxpool,"<p>I am looking to write unit tests for Go code that uses pgxpool to interact with a postgres database. Is there a test framework that will stand up a dummy or mock database to test on?</p>
<p>I am aware of a package called <code>pgxpoolmock</code>. The problem is, there is no way to test actual production code, as a pool from <code>pgxpool</code> cannot be casted to the type <code>pgxpoolmock</code> (or can it?)</p>
",https://stackoverflow.com/questions/69400355/unit-testing-for-pgxpool,"['postgresql', 'unit-testing', 'go']",1182,False,1,1
Unit testing - Comparing environment,"<p>I would like to implement unit testing in R by comparing list of objects in an environment stored as rds with the current environment. I am sharing some of the codes I was trying to implement to provide an idea on what I would want</p>
<pre><code>
library(rlang)

a = FALSE
b = &quot;a&quot;
c = 2.3
d = 1:3


saveRDS(mget(ls()), file = &quot;unit.rds&quot;)

# unit_t &lt;- readRDS(file = &quot;unit.rds&quot;)

env &lt;- new_environment(readRDS(file = &quot;unit.rds&quot;))

identical(global_env(), current_env())

identical(new_environment(readRDS(file = &quot;unit.rds&quot;)), global_env())

identical(mget(ls()), list(readRDS(file = &quot;unit.rds&quot;)))

</code></pre>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/67823642/unit-testing-comparing-environment,"['r', 'unit-testing']",24,False,1,0
Unit testing in go,"<p>I want to test the API function but arguments give the problem.</p>
<pre><code> func SetAPIConfigHandler(w http.ResponseWriter, r *http.Request) {
    var apiConfig model.Configuration
    err := json.NewDecoder(r.Body).Decode(&amp;apiConfig)
    if err != nil {
        responderror(w, http.StatusBadRequest, err.Error())
    } else {
        utils.Domain = apiConfig.Domain
        utils.BaseURL = apiConfig.BaseURL
        utils.Tenant = apiConfig.Tenant
        respondJSON(w, http.StatusOK, apiConfig)
    }
}
</code></pre>
",https://stackoverflow.com/questions/68015802/unit-testing-in-go,"['api', 'go', 'code-coverage', 'go-testing']",51,True,-2,1
Unit-testing expect script,"<p>I have an expect script that I would like to do unit-tests for, but I'm unsure how to go about it.</p>
<p>My initial thought was to override <code>keychain</code>, <code>lpass</code> and <code>bw</code> somehow, but I have no idea how to do this without modifying the original script, in my other tests I have overridden functions with shell function stubs and set <code>PATH=''</code> in some cases. I guess I could test all the 3 executed commands manually, but that doesn't really test the project as a whole and leaves some code untested which is vital to the functionality.</p>
<pre><code>#!/usr/bin/expect --
set manager [lindex $argv 0]
# strip manager part
set argv [lrange $argv 1 end]
spawn -noecho keychain --quick --quiet --agents ssh {*}$argv
foreach key $argv {
  if {$manager == &quot;lastpass&quot;} {
    set pass [exec lpass show --name $key --field=Passphrase | tr -d '\n']
  }
  if {$manager == &quot;bitwarden&quot;} {
    set pass [exec bw get password $key | tr -d '\n']
  }
  expect &quot;:&quot;
  send &quot;$pass\r&quot;
}
interact
</code></pre>
<p>Any suggestions would be be highly appreciated!</p>
",https://stackoverflow.com/questions/67576106/unit-testing-expect-script,"['testing', 'tcl', 'expect']",249,True,0,1
Unit testing suspend coroutine,"<p>a bit new to Kotlin and testing it... I am trying to test a dao object wrapper with using a suspend method which uses an awaitFirst() for an SQL return object. However, when I wrote the unit test for it, it is just stuck in a loop. And I would think it is due to the awaitFirst() is not in the same scope of the testing</p>
<p>Implementation:</p>
<pre><code>suspend fun queryExecution(querySpec: DatabaseClient.GenericExecuteSpec): OrderDomain {
        var result: Map&lt;String, Any&gt;?
        try {
            result = querySpec.fetch().first().awaitFirst()
        } catch (e: Exception) {
            if (e is DataAccessResourceFailureException)
                throw CommunicationException(
                    &quot;Cannot connect to &quot; + DatabaseConstants.DB_NAME +
                        DatabaseConstants.ORDERS_TABLE + &quot; when executing querySelect&quot;,
                    &quot;querySelect&quot;,
                    e
                )
            throw InternalException(&quot;Encountered R2dbcException when executing SQL querySelect&quot;, e)
        }

        if (result == null)
            throw ResourceNotFoundException(&quot;Resource not found in Aurora DB&quot;)

        try {
            return OrderDomain(result)
        } catch (e: Exception) {
            throw InternalException(&quot;Exception when parsing to OrderDomain entity&quot;, e)
        } finally {
            logger.info(&quot;querySelect;stage=end&quot;)
        }
    }
</code></pre>
<p>Unit Test:</p>
<pre><code>@Test
    fun `get by orderid id, null`() = runBlocking {
        // Assign
        Mockito.`when`(fetchSpecMock.first()).thenReturn(monoMapMock)
        Mockito.`when`(monoMapMock.awaitFirst()).thenReturn(null)

        // Act &amp; Assert
        val exception = assertThrows&lt;ResourceNotFoundException&gt; {
            auroraClientWrapper.queryExecution(
                databaseClient.sql(&quot;SELECT * FROM orderTable WHERE orderId=:1&quot;).bind(&quot;1&quot;, &quot;123&quot;) orderId
            )
        }
        assertEquals(&quot;Resource not found in Aurora DB&quot;, exception.message)
    }
</code></pre>
<p>I noticed this issue on <a href=""https://github.com/Kotlin/kotlinx.coroutines/issues/1204"" rel=""nofollow noreferrer"">https://github.com/Kotlin/kotlinx.coroutines/issues/1204</a> but none of the work around has worked for me...</p>
<p>Using runBlocking within Unit Test just causes my tests to never complete. Using runBlockingTest explicitly throws an error saying &quot;Job never completed&quot;... Anyone has any idea? Any hack at this point?</p>
<p>Also I fairly understand the point of you should not be using suspend with a block because that kinda defeats the purposes of suspend since it is releasing the thread to continue later versus blocking forces the thread to wait for a result... But then how does this work?</p>
<pre><code>private suspend fun queryExecution(querySpec: DatabaseClient.GenericExecuteSpec): Map {
        var result: Map&lt;String, Any&gt;?
        try {
            result = withContext(Dispatchers.Default) {
                querySpec.fetch().first().block()
            }
return result
}
</code></pre>
<p>Does this mean withContext will utilize a new thread, and re-use the old thread elsewhere? Which then doesnt really optimize anything since I will still have one thread that is being blocked regardless of spawning a new context?</p>
",https://stackoverflow.com/questions/67525221/unit-testing-suspend-coroutine,"['unit-testing', 'kotlin', 'kotlin-coroutines']",3020,True,0,1
unit testing express middleware,"<p>I have the following middleware function in my express app,</p>
<pre><code>const { getEmployerId } = require(&quot;./employerApi&quot;);

const setEmployerDetails = (employerId) =&gt; {
    return (req, res, next) =&gt; {
        getEmployerId(req, res, next, employerId);
    }
}

module.exports = setEmployerDetails
</code></pre>
<p>I wanting to unit test this middleware, but I am not sure how, the function basically returns whatever the API returns, the API is already unit tested. How would I go about unit testing this function with something like chai?</p>
<p>So far I have,</p>
<pre><code>describe('setEmployerDetails`, () =&gt; {
   it('should be a function', () =&gt; expect(setEmployerDetails).to.be.a('function'));
   it('should take 1 argument', () =&gt; expect(setEmployerDetails.length).to.equal(1));
});`
</code></pre>
",https://stackoverflow.com/questions/66798873/unit-testing-express-middleware,"['javascript', 'node.js', 'express', 'unit-testing', 'chai']",446,False,0,1
Unit testing Solidity JS,"<p>I want to test these 3 different require in my mint function with Javascript.</p>
<pre><code>function mint(uint256 _mintAmount) public payable {
    require(_mintAmount &gt; 0, &quot;need to mint at least 1 NFT&quot;);
    require(_mintAmount &lt;= maxMintAmount, &quot;max mint amount per session exceeded&quot;);
    require(supply + _mintAmount &lt;= maxSupply, &quot;max NFT limit exceeded&quot;);
</code></pre>
<p>I'm really new to testing so I tried something like this. obviously its wrong but how can I test that _mintAmount &lt;= maxMintAmount in a function like this</p>
<pre><code>it('mint amount', async () =&gt;{
    _mintAmount &gt; 0;
    _mintAmount &lt;= maxMintAmount;
    supply + _mintAmount &lt;= maxSupply;
})
</code></pre>
",https://stackoverflow.com/questions/70456482/unit-testing-solidity-js,"['javascript', 'solidity', 'truffle']",62,True,0,1
Unit testing practical scenarios,"<p>Hopefully this question is allowed as it is subjective.
But I'm struggling to discover a real world example as to why you need to do unit testing in Angular? All the example videos I see are basic in the nature of what they're testing for. Most are testing to see if a button is on the page or whatever. But that seems to be a pretty pointless test. Could someone please give me an example?</p>
",https://stackoverflow.com/questions/70156711/unit-testing-practical-scenarios,['angular'],27,True,0,1
Unit testing toString method,"<p>I try to unit tes a Tostring method:</p>
<p>So I have this code:</p>
<pre><code>public class Parcel
{
 //Working
}
</code></pre>
",https://stackoverflow.com/questions/68993510/unit-testing-tostring-method,"['c#', 'unit-testing', 'nunit']",570,True,0,2
functional interface unit testing,"<p>How do you test classes that are using functional interfaces. So how could i test the two concrete classes below:</p>
<pre><code>@FunctionalInterface
public interface Test {
    int sumTwoValues(int x, int y);
}


public class UseTestExample {

   public int useTest(int z, Test test) {
     int returnValue = test.sumTwoValues(z, 10);

     return returnValue;
   }

}


public class MainTest {

  public void clientCall() {
    UseTestExample testExample = new UseTestExample();
   
    testExample.useTest(10, (x,y) -&gt; {
        return x+y;
    });
  }
}
</code></pre>
<p>I can see that UseTestExample, I could pass in an implementation during unit test and check what i get back is correct?</p>
<p>But the MainTest class, how would i be able to test that?</p>
",https://stackoverflow.com/questions/67688508/functional-interface-unit-testing,"['java', 'functional-interface']",356,False,0,0
Unit testing and mocking,"<p>I am new to ASP.NET Core MVC and I was wondering if any one could help me with the unit testing to remove a user from the database</p>
<p>Controller</p>
<pre><code>public async Task&lt;ActionResult&gt; RemoveIdAsync(string Id)
{
        try
        {
            var result = await _udService.RemoveId(Id);
            return Ok(result);
        }
        catch (ServiceException)
        {
            return _internalServerErrorStatusCode;
        }
}
</code></pre>
",https://stackoverflow.com/questions/66428652/unit-testing-and-mocking,"['c#', 'unit-testing', 'asp.net-core', 'graphql', 'mocking']",380,True,-1,2
Angular unit testing functions,"<p>I have just started exploring unit testing in angular.
I have a function in .ts file</p>
<pre><code>onValueChange(val: number): void {
this.formGroup.get(this.controlName).setValue(val);
}
</code></pre>
<p>I am trying to test if the controlName has the value passed in the onValueChange parameters</p>
<p>I tried this in the spec.ts file</p>
<pre><code>it('form value should update from form changes', fakeAsync(() =&gt; {
onValueChange(5);
expect(component.formGroup.get(component.controlName)).toEqual(5); 
}));
function onValueChange(val: number): void {
component.formGroup.get(component.controlName).setValue(val);
}
</code></pre>
<p>what am I doing wrong</p>
",https://stackoverflow.com/questions/66438919/angular-unit-testing-functions,"['angular', 'jasmine', 'angular-test']",410,True,0,1
Unit Testing Case Statements,"<p>I appreciate this probably isn't the place to ask, if there is a better place please let me know.</p>
<p>I have a legacy Stored Procedure that selects some data and inserts into a table.  However there are quite a few case statements that I would like to test and I wondered how that should be done.</p>
<pre><code>insert into [dbo].[utb_ITP]
...
case when [sme].[Reporting Countries] = 'Multiple Countries'
     then 'United Kingdom-Multiple Countries'
     when patindex('%-$',[sme].[Reporting Countries) &gt; 1
     then left([sme].[Reporting countries], (pat index('%-%', [sme].[Reporting Countries]) - 1 ))
     else [sme].[Reporting Countries]
end as [SVC_COUNTRY]
</code></pre>
<p>I think the samples I have seen have all been mocking data and testing functions, but I haven't really seen examples like a case statement.  Do I test the final output or the component parts? So I would first test</p>
<pre><code>[sme].[Reporting Countries] = 'Multiple Countries'
     then 'United Kingdom-Multiple Countries'
</code></pre>
<p>In that I would use an AssertEqualsTable where the Expected value would be 'United Kingdom-Multiple Countries' and then the insert into the Actual would run the first part of the case, something like:</p>
<pre><code>insert into #Expected values ('United Kingdom-Multiple Countries')

insert into #Actual
select case [sme].[Reporting Countries] = 'Multiple Countries'
            then 'United Kingdom-Multiple Countries'
end
from   [SourceTable] as [sme]
where [sme].[Reporting Countries] = 'Multiple Countries'

exec AssertEqualsTable ...
</code></pre>
",https://stackoverflow.com/questions/69954692/unit-testing-case-statements,"['tdd', 'tsqlt']",76,False,0,1
Go unit testing Bcrypt,"<p>I am performing unit tests for a service where request dto's are validated and user passwords are hashed using Go's <a href=""https://pkg.go.dev/golang.org/x/crypto/bcrypt"" rel=""nofollow noreferrer"">Bcrypt package</a> before being passed to a repository for insertion into the DB.</p>
<p>I don't know how my mock functions should return a dummy response which should match with the service's hashing.</p>
<pre class=""lang-golang prettyprint-override""><code>func Test_should_create_new_account(t *testing.T) {
    // Arrange
    teardown := setup(t)
    defer teardown()

    // ** Focus here **
    hashedpassword, err := AppCrypto.HashAndSalt([]byte(&quot;securepassword&quot;))

    request := dto.RegisterRequest{
        Email:    &quot;test@test.com&quot;,
        Password: &quot;securepassword&quot;,
        RoleID:   1,
    }

    account := realDomain.Account{
        Email:    request.Email,
        Password: hashedpassword,
        RoleID:   request.RoleID,
    }

    accountWithID := account
    accountWithID.AccountID = 1

    mockRepo.EXPECT().Create(account).Return(&amp;accountWithID, nil)
    // Act
    res, err := service.RegisterAccount(request)

    // Assert
    if err != nil {
        t.Error(&quot;Failed while creating account&quot;)
    }
    if !res.Created {
        t.Error(&quot;Failed while creating account&quot;)
    }
}
</code></pre>
<p><code>HashAndSalt</code> simply hashed a given string.</p>
<pre class=""lang-golang prettyprint-override""><code>// HashAndSalt Hashes a given string
func HashAndSalt(pwd []byte) (string, *errs.AppError) {

    // Use GenerateFromPassword to hash &amp; salt pwd.
    // MinCost is just an integer constant provided by the bcrypt
    // package along with DefaultCost &amp; MaxCost.
    // The cost can be any value you want provided it isn't lower
    // than the MinCost (4)
    hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
    if err != nil {
        return &quot;&quot;, errs.NewUnexpectedError(&quot;An unexpected error ocurred while hashing the password&quot; + err.Error())
    } // GenerateFromPassword returns a byte slice so we need to
    // convert the bytes to a string and return it
    return string(hash), nil
}
</code></pre>
<p>This is the service's <code>RegisterAccount</code></p>
<pre class=""lang-golang prettyprint-override""><code>func (d DefaultAccountService) RegisterAccount(request dto.RegisterRequest) (*dto.RegisterResponse, *errs.AppError) {
    err := request.Validate()
    if err != nil {
        return nil, err
    }
    // Hash the request's password
    hashedpassword, err := AppCrypto.HashAndSalt([]byte(request.Password))

    if err != nil {
        return nil, err
    }
    // Assign the hashed password to the request obj
    request.Password = hashedpassword
    a := request.ToDomainObject()

    _, err = d.repo.Create(a)
    if err != nil {
        return nil, err
    }
    response := dto.RegisterResponse{
        Created: true,
    }
    return &amp;response, nil
}
</code></pre>
<p>This is the thrown error, notice the <code>want</code> and <code>got</code> blocks where the mock request does not match with the given request.</p>
<pre><code>accountService.go:34: Unexpected call to *domain.MockAccountRepository.Create([{0 test@test.com 1 $2a$04$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}]) at /home/dio/Documents/Code/go-beex-backend/auth-server/mocks/domain/accountRepositoryDB.go:40 because: 
        expected call at /home/dio/Documents/Code/go-beex-backend/auth-server/service/accountService_test.go:52 doesn't match the argument at index 0.
        Got: {0 test@test.com 1 $2a$04$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}
        Want: is equal to {0 test@test.com 1 $2a$04$Bah8tCOzf7Z9Suw55DfyHOvnsBbXLyJEWV8QZ.owCBUOxxomAuEM2 false}
</code></pre>
<p>Hope my explanation makes sense, unit testing was not discussed in <a href=""https://medium.com/@jcox250/password-hash-salt-using-golang-b041dc94cb72"" rel=""nofollow noreferrer"">the article</a> I am basing my code from.</p>
",https://stackoverflow.com/questions/66093942/go-unit-testing-bcrypt,"['unit-testing', 'go', 'bcrypt', 'go-testing']",1741,True,0,1
Issues with unit testing,"<p>I want to test a function, but I am definitely struggling at this one. The function loops through boards last row if NO_PLayer is valid location.</p>
<pre><code>def validLocations(board):

    validLocationsArr = []

    column = 0
    row = 0
    while column &lt; 6:

        if (board[5][column] == NO_PLAYER):
                validLocationsArr.append(column)

        column += 1

    return validLocationsArr
</code></pre>
<p>I worked on it, and tried it, but:</p>
<pre><code>def test_validLocations(self):
    from agents.common import validLocations

    ret = validLocations(board)
    assert np.all(ret == NO_PLAYER)
</code></pre>
<p>Can anyone help me?
Many thanks in advance!</p>
",https://stackoverflow.com/questions/66317883/issues-with-unit-testing,"['python', 'testing', 'encoding', 'monte-carlo-tree-search']",23,False,0,1
Unit testing .NET Core,"<p>im trying to write a unit test where i want to use my MockRepository for my products and filter the products by Category Id. However i am fairly new to all of this and dont really know how i can do this.</p>
<p>This is my MockRepo for the producuts:</p>
<pre><code>public class MockProductRepository : IProductsRepository
    {
        private readonly ICategoryRepository _categoryRepository = new MockCategoryRepository();



        public IEnumerable&lt;Products&gt; AllProducts =&gt;
            new List&lt;Products&gt;
            {
                new Products {ProductId = 1, ProductName=&quot;Ek Stol&quot;, ProductPrice=150, ProductDescription=&quot;En fin stol&quot;, Category = _categoryRepository.AllCategories.ToList()[0],ImageUrl=&quot;https://cdn.pixabay.com/photo/2017/02/19/14/39/antique-2079936_960_720.jpg&quot;, ImageThumbnailUrl=&quot;https://gillcleerenpluralsight.blob.core.windows.net/files/strawberrypiesmall.jpg&quot;},
                new Products {ProductId = 2, ProductName=&quot;Bord!&quot;, ProductPrice=250, ProductDescription=&quot;Ett fint vardagsbrod.&quot;, Category = _categoryRepository.AllCategories.ToList()[1],ImageUrl=&quot;https://cdn.pixabay.com/photo/2015/03/07/20/11/dinner-table-663435_960_720.jpg&quot;, ImageThumbnailUrl=&quot;https://gillcleerenpluralsight.blob.core.windows.net/files/cheesecakesmall.jpg&quot;},
                new Products {ProductId = 3, ProductName=&quot;skål&quot;, ProductPrice=350, ProductDescription=&quot;Grym frukost skål!&quot;, Category = _categoryRepository.AllCategories.ToList()[0],ImageUrl=&quot;https://cdn.pixabay.com/photo/2016/03/22/12/06/sunflower-seeds-1272736_960_720.jpg&quot;, ImageThumbnailUrl=&quot;https://gillcleerenpluralsight.blob.core.windows.net/files/rhubarbpiesmall.jpg&quot;},
                new Products {ProductId = 4, ProductName=&quot;Lådbil&quot;, ProductPrice=450,  ProductDescription=&quot;Snabbaste kärran i stan!&quot;, Category = _categoryRepository.AllCategories.ToList()[2],ImageUrl=&quot;https://cdn.pixabay.com/photo/2018/06/23/08/04/soapbox-3492256_960_720.jpg&quot;, ImageThumbnailUrl=&quot;https://gillcleerenpluralsight.blob.core.windows.net/files/pumpkinpiesmall.jpg&quot;}
            };



        public Products GetProductById(int ProductId)
        {
            return AllProducts.FirstOrDefault(p =&gt; p.ProductId == ProductId);
        }
    }
}
</code></pre>
<p>This is my MockCategory repo:</p>
<pre><code>namespace uppfinnaren_MarcusR91.Models
{
    public class MockCategoryRepository : ICategoryRepository
    {
        public IEnumerable&lt;Category&gt; AllCategories =&gt;
            new List&lt;Category&gt;
        {
            new Category { CategoryId = 1, CategoryName = &quot;Stolar&quot;, Description = &quot;Alla stolar!&quot;},
            new Category { CategoryId = 2, CategoryName = &quot;Bord&quot;, Description = &quot;Alla bord!&quot;},
            new Category { CategoryId = 3, CategoryName = &quot;Lådbilar&quot;, Description = &quot;Snabbaste lådbilarna i stan!&quot;} 
        };
    }
}

</code></pre>
<p>And what i want to do is write a unit test where i check if i can filter the products by categoryId.
This is what i have written so far in my unit tets:</p>
<pre><code>namespace TestProjectUppfinnaren
{
    public class UnitTest1
    {
        [Fact]
        public void TestFilteringProductsByCategory()
        {
            var mockData = new MockProductRepository();
            
            var products =  mockData.AllProducts.Where(x =&gt; x.CategoryId == 2);
 
        } 
    }
}
</code></pre>
<p>I need some sort of assert i believe that will make sure that the products and the categoryId im trying to filter should be the same. Anyone have any ideas?</p>
",https://stackoverflow.com/questions/70462950/unit-testing-net-core,"['c#', 'asp.net', 'linq', 'unit-testing', 'asp.net-core']",112,False,0,0
Exceptions in unit testing,"<p>I copied a unit test that was in a book. exactly the same. There is no problem in compiler but when it runs there are some exceptions. Is there any problem in my codes? if no so what is the reason and what is the solution?</p>
<p>This is my class:</p>
<pre class=""lang-java prettyprint-override""><code>package Testing;

public class MessageUtil {

    private String message;

    public MessageUtil(String message) {
        this.message = message;
    }

    public String printMessage() {
        System.out.println(message);
        return message;
    }
    public static void main(String[] args) {
        
    }
}
</code></pre>
<p>This is test case:</p>
<pre class=""lang-java prettyprint-override""><code>package Testing;

import org.junit.Test;

import junit.framework.TestCase;

public class TestJunit extends TestCase {
    String message = &quot;Hello World&quot;;
    MessageUtil messageUtil = new MessageUtil(message);

    @Test
    public void testPrintMessage() {
        assertEquals(message,messageUtil.printMessage());
    }
}
</code></pre>
<p>This is test runner:</p>
<pre class=""lang-java prettyprint-override""><code>package Testing;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {

    public static void main(String[] args) {
        
        Result result = JUnitCore.runClasses(TestJunit.class);
        for (Failure failure : result.getFailures()) {
            System.out.println(failure.toString());
        }
        System.out.println(result.wasSuccessful());
    }
}
</code></pre>
<p>This is printed exceptions:</p>
<pre><code>Exception in thread &quot;main&quot; java.lang.NoClassDefFoundError: junit/framework/TestCase
at java.base/java.lang.ClassLoader.defineClass1(Native Method)
at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:825)
at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:723)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:646)
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:604)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
at Testing.TestRunner.main(TestRunner.java:11)
Caused by: java.lang.ClassNotFoundException: junit.framework.TestCase
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 10 more
</code></pre>
",https://stackoverflow.com/questions/67073868/exceptions-in-unit-testing,"['java', 'unit-testing', 'junit5', 'noclassdeffounderror']",555,True,0,1
Unit Testing newRelic.increment Metric,"<p>I have a controller that calls <code>newrelic.incrementMetric()</code> and I want to write an assert that checks that its called with the properly</p>
<p>my controller looks like</p>
<pre><code>const newrelic = require('newrelic')

async index() {
  // some stuff here
  newrelic.incrementMetric('hello', 1)
}
</code></pre>
<p>I tried this in my test</p>
<pre><code>const newrelic = require('newrelic')

// describe block here...
  it('should call newRelic', async () =&gt; {
    newrelic.incremetentMetric = jest.fn().mockResolvedValueOnce({});
    expect (newrelic.incrementMetric).toHaveBeenCalledWith('hello', 1)
  });
</code></pre>
<p>Whats the proper way to do this?</p>
<p>My code has an error</p>
<pre><code>    Matcher error: received value must be a mock or spy function

    Received has type:  function
    Received has value: [Function incrementMetric]
    ```
</code></pre>
",https://stackoverflow.com/questions/67204983/unit-testing-newrelic-increment-metric,"['typescript', 'jestjs', 'newrelic']",459,True,0,1
Clojure unit testing issue,"<p>I've currently got a function in my main file which squares every number in the list, now that works perfectly with no errors but my unit tests keeps on throwing errors and I cant seem to figure out why.</p>
<pre><code> (ns squareone.core-test
 (:require [clojure.test :refer :all]
        [squareone.core :refer :all]))

(deftest Squaring
  (testing &quot;Squaring test&quot;
    (is (= [1 16] (square [1 4])))))
  That is everything in my test file 
</code></pre>
<p>And this is what is in my main file minus the actual squaring function</p>
<pre><code>(ns squareone.core)
(:require '[clojure.string :as string])
(require '['clojure.string :as 'str])
</code></pre>
<p>And I get this error</p>
<pre><code>Syntax error (ClassCastException) compiling at 
(C:\Users\public\squareone\src\squareone\core.clj:3:1).
class clojure.lang.PersistentList cannot be cast to class clojure.lang.Symbol 
(clojure.lang.PersistentList and clojure.lang.Symbol are in unnamed module of loader 'app')
</code></pre>
<p>Very unsure on how to proceed, any help is appreciated :)</p>
",https://stackoverflow.com/questions/65766841/clojure-unit-testing-issue,['clojure'],74,True,0,1
Unit Testing firebase_auth and firestore,"<p>I am trying to setup flutter scripts for testing my classes that interface with my firestore database.</p>
<p>My current struggles are:</p>
<ul>
<li>It seems that in order to use firebase_auth, I have to have a widget tree. I'm new to both flutter and firebase I am slowly building up my expertise by building classes one at a time, writing tests for them and then moving to the next class. Requiring the widget tree means I can't test the authorization logic independent of the GUI (e.g. What happens if I call signOut twice in my code even though the GUI logic only lets you press the button once?).</li>
<li>Mocking is insufficient. In order to mock, you need to know the expected behaviour for the tests to be representative. I've spent a lot of time trying to troubleshoot issues with futures, changing signed in states, and incorrect data formats. If I had written mocks, they wouldn't have matched how the real functions actually behave.</li>
<li>Mocking doesn't help me as I am also learning about the security rules for the database. I've definitely got code that works with lax security rules but there's something wrong with the current security rules.</li>
</ul>
<p>Is there any way to write unit/integration tests for firebase_auth or firestore without mocking? I'm even happy using a local emulator/export of my database if that's a thing that's even possible.</p>
<p>Here are a number of the articles I have reviewed that are not what I am looking for:</p>
<ul>
<li><a href=""https://bendyworks.com/blog/a-month-of-flutter-mocking-firebase-auth-in-tests"" rel=""noreferrer"">A month of Flutter: mocking Firebase Auth in tests</a></li>
<li><a href=""https://stackoverflow.com/questions/64476408/setup-unit-test-for-firebase-user-authentication-with-mockito"">Setup Unit test for Firebase User authentication with Mockito</a></li>
<li><a href=""https://stackoverflow.com/questions/56612501/how-to-create-integration-test-for-app-with-firebase-auth"">How to create integration test for app with Firebase Auth?</a></li>
<li><a href=""https://www.youtube.com/watch?v=225MFHjQokw"" rel=""noreferrer"">Flutter Testing [4] - Firebase Auth App - Unit Testing</a></li>
<li><a href=""http://Mocking%20In%20Integration%20Tests%20with%20Flutter"" rel=""noreferrer"">Mocking In Integration Tests with Flutter</a></li>
<li><a href=""https://utkarshkore.medium.com/writing-unit-tests-in-flutter-with-firebase-firestore-72f99be85737"" rel=""noreferrer"">Writing Unit Tests in Flutter with Firebase Firestore</a></li>
<li><a href=""https://github.com/flutter/flutter/issues/15245"" rel=""noreferrer"">Tutorial how to test with firebase #15245</a></li>
</ul>
",https://stackoverflow.com/questions/68745007/unit-testing-firebase-auth-and-firestore,"['firebase', 'flutter', 'unit-testing', 'firebase-authentication', 'flutter-test']",610,False,6,1
EventHubProducerClient unit testing in c#,"<p>I find that EventHubProducerClient is not unit test friendly (not mockable) in c# and how do you go about testing it, like <code>SendEventsAsync</code> method?</p>
",https://stackoverflow.com/questions/67275134/eventhubproducerclient-unit-testing-in-c,"['c#', 'unit-testing', 'azure-eventhub']",1729,True,5,2
Unit testing in GNU Prolog,"<p>I'm trying to migrate my SWI Prolog application into the GNU Prolog. Unfortunately I have a problem with unit tests. In SWIPL we can simply use <a href=""https://www.swi-prolog.org/pldoc/doc_for?object=section(%27packages/plunit.html%27)"" rel=""nofollow noreferrer"">plunit</a> module and write the test cases like the following one:</p>
<pre><code>:- begin_tests(my_tests).
test(my_predicate_test) :- my_predicate(Result), assertion(Result == [foo, bar]).
test(second_test) :- foo(10, X), assertion(X == &quot;hello world&quot;).
:- end_tests(my_tests).
</code></pre>
<p>But how to implement unit tests in GNU Prolog? Even some additional libraries like <a href=""https://github.com/khueue/crisp"" rel=""nofollow noreferrer"">crisp</a> are not available for gprolog.</p>
",https://stackoverflow.com/questions/65844487/unit-testing-in-gnu-prolog,"['unit-testing', 'prolog', 'gnu-prolog']",263,True,4,1
Jest Unit testing onClick event,"<p>I have a Component and want to unit test it with react jest... I want to test onClick event.. I've tried many cases but they don't cover onClick statement</p>
<p><strong>This my Component</strong></p>
<pre><code>export default class HeaderCreate extends Component {

  render() {
    const { name, description, closeRightSection } = this.props;
    return (
      &lt;div className=&quot;header&quot;&gt;
        &lt;h1 className=&quot;header-text&quot; title={name} data-testid=&quot;header&quot;&gt;{name}&lt;/h1&gt;
        &lt;p data-testid= &quot;description-para&quot;&gt;{description}&lt;/p&gt;

        &lt;Tooltip title=&quot;Close Section&quot;&gt;
          &lt;div className=&quot;icon-close&quot;&gt;
            &lt;i className=&quot;material-icons&quot; onClick={() =&gt; closeRightSection()} data-testid=&quot;id&quot;&gt;close&lt;/i&gt;
          &lt;/div&gt;
        &lt;/Tooltip&gt;
      &lt;/div&gt;
    )
  }
}; 
</code></pre>
<p><strong>This is my test.js</strong></p>
<pre><code>import React from 'react'
import { render } from &quot;@testing-library/react&quot;;

import HeaderCreate from '../components/createHeader';

test(&quot;render header correctly&quot;, () =&gt; {
    const { getByTestId } = render(&lt;HeaderCreate name=&quot;My Name is Test&quot;&gt;&lt;/HeaderCreate&gt;);
    expect(getByTestId('header').textContent).toBe('My Name is Test')
});

test(&quot;render Description Paragraph correctly&quot;, () =&gt; {
    const { getByTestId } = render(&lt;HeaderCreate description=&quot;Hi I am Description box&quot;&gt;&lt;/HeaderCreate&gt;);
    expect(getByTestId('description-para').textContent).toBe('Hi I am Description box')
});

test(&quot;render close tooltip correctly&quot;, () =&gt; {
    const { getByTestId } = render(&lt;HeaderCreate closeRightSection=&quot;&quot;&gt;&lt;/HeaderCreate&gt;);
    expect(getByTestId('id')).toBeTruthy();
}); 
</code></pre>
<p>In Coverage it is show all onClick event as statement not covered.. and statement coverage is 66.67%. How can I make it 100%..? I am new to Reactjs. So I am Confused what to do now.. I have search on various place but didn't got any solution. Please suggest me where I am wrong</p>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/68918060/jest-unit-testing-onclick-event,"['javascript', 'reactjs', 'unit-testing', 'onclicklistener', 'react-testing-library']",26919,True,4,1
Unit testing AWS Lambda CDK,"<p>I'm having issues unit testing a lambda function module that is dependent on a package inside the referenced lambda layer.</p>
<p>My module looks like so</p>
<pre><code>/lambda/function/orderIdGenerator.ts
</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-js lang-js prettyprint-override""><code>import { Order } from './structs';
import { generateHashedId } from '/opt/nodejs/node_modules/package_name/common';

export const orderIdGenerator = (order: Order): string =&gt; {
  const orderValues = Object.values(order);
  return generateHashedId(orderValues);
};</code></pre>
</div>
</div>
</p>
<p>To then test this function I want to mock the module being imported.
My attempt...</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>jest.mock('package_name/common');
import { Order } from 'lambda/function/structs';
import { orderIdGenerator } from '../../../lambda/function/orderIdGenerator';
import { generateHashedId } from '/opt/nodejs/node_modules/package_name/common';

describe('orderIdGenerator', () =&gt; {
  it('should call generateHashedId', () =&gt; {
    // GIVEN
    const fn = orderIdGenerator;
    // WHEN
    fn(({ foo: 'bar' } as unknown) as Order);
    // THEN
    expect(generateHashedId).toHaveBeenCalled();
  });

  it('should call generateHashedId with Order', () =&gt; {
    // GIVEN
    const fn = orderIdGenerator;
    // WHEN
    fn({} as Order);
    // THEN
    expect(generateHashedId).toHaveBeenCalledWith({});
  });
});</code></pre>
</div>
</div>
</p>
<p>But of course Jest is not able to mock a module it cannot find.</p>
<p>My tsconfig.json</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>{
  ""compilerOptions"": {
    ""target"": ""ES2018"",
    ""module"": ""commonjs"",
    ""lib"": [""es2018""],
    ""declaration"": true,
    ""strict"": true,
    ""noImplicitAny"": true,
    ""strictNullChecks"": true,
    ""noImplicitThis"": true,
    ""alwaysStrict"": true,
    ""noUnusedLocals"": false,
    ""noUnusedParameters"": false,
    ""noImplicitReturns"": true,
    ""noFallthroughCasesInSwitch"": false,
    ""inlineSourceMap"": true,
    ""inlineSources"": true,
    ""experimentalDecorators"": true,
    ""strictPropertyInitialization"": false,
    ""typeRoots"": [
      ""./node_modules/@types"",
      ""./layer/nodejs/node_modules/@types""
    ],
    ""baseUrl"": ""."",
    ""paths"": {
      ""/opt/nodejs/*"": [""layer/nodejs/*""]
    }
  },
  ""exclude"": [""cdk.out""]
}</code></pre>
</div>
</div>
</p>
<p>I even through this is my package.json</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>  ""jest"": {
    ""modulePaths"": [
      ""&lt;rootDir&gt;/node_modules/"",
      ""&lt;rootDir&gt;/layers/nodejs/node_modules/""
    ]
  }</code></pre>
</div>
</div>
</p>
<p>Any ideas would be appreciated.</p>
<p>Thanks !</p>
",https://stackoverflow.com/questions/66337969/unit-testing-aws-lambda-cdk,"['typescript', 'unit-testing', 'aws-lambda', 'jestjs', 'aws-cdk']",1102,False,2,0
Unit Testing Flask-Admin modules?,"<p>I was wondering, is there any way to test a given defined BaseView? can I just integrate it with the Flask testing facilities? I had been looking around and I couldn't find anything about unit testing Flask-Admin views.</p>
<p>I will appreciate any guidance.</p>
",https://stackoverflow.com/questions/65945685/unit-testing-flask-admin-modules,"['flask', 'flask-admin']",76,False,2,0
React Unit Testing State Updates,"<p>I'm in the middle of trying to get as close to 100% unit test coverage with my React application as possible, however I'm in a bit of a pickle with trying to get test coverage on the <code>useAsync</code> hook. I took the following code from <a href=""https://usehooks.com/useAsync/"" rel=""nofollow noreferrer"">use react hooks</a>:</p>
<pre class=""lang-js prettyprint-override""><code>import { useState, useEffect, useCallback } from 'react';

const useAsync = (asyncFunction, immediate = true) =&gt; {
  const [status, setStatus] = useState('idle');
  const [value, setValue] = useState(null);
  const [error, setError] = useState(null);

  // The execute function wraps asyncFunction and
  // handles setting state for pending, value, and error.
  // useCallback ensures the below useEffect is not called
  // on every render, but only if asyncFunction changes.
  const execute = useCallback(() =&gt; {
    setStatus('pending');
    setValue(null);
    setError(null);

    return asyncFunction()
      .then(response =&gt; {
        setValue(response);
        setStatus('success');
      })
      .catch(error =&gt; {
        setError(error);
        setStatus('error');
      });
  }, [asyncFunction]);

  // Call execute if we want to fire it right away.
  // Otherwise execute can be called later, such as
  // in an onClick handler.
  useEffect(() =&gt; {
    if (immediate) {
      execute();
    }
  }, [execute, immediate]);

  return { execute, status, value, error };
};
</code></pre>
<p>And it works fine. I've not done anything funky or included any additional testing libraries/dependencies on top of what you'd get when you run <code>npx create-react-app ...</code>.</p>
<p>Because I couldn't find a suitable solution for my team to test react hooks without relying on additional dependencies, i.e. <a href=""https://github.com/testing-library/react-hooks-testing-library"" rel=""nofollow noreferrer"">react-hooks-testing-library</a>, I created a mock component to wrap the hook in, then I just test the different possible states like so:</p>
<pre class=""lang-js prettyprint-override""><code>import React from &quot;react&quot;;
import { render, cleanup } from &quot;@testing-library/react&quot;;
import { useAsync } from &quot;../../hooks&quot;;

afterEach(cleanup);

const MockComponent = (props) =&gt; {
  const { status } = useAsync(props.callback, props.immediate);
  return &lt;p id=&quot;test&quot;&gt;{status}&lt;/p&gt;
};

const defaultCallback = () =&gt; {
  new Promise((resolve) =&gt; { 
    setTimeout(() =&gt; {
      resolve(&quot;Success!&quot;);
    }, 1000)
  });
};

// Example of a test that runs fine, no problem at all!
test(&quot;useAsync gets to a pending state&quot;, () =&gt; {
  const { container } = render(&lt;MockComponent callback={defaultCallback} immediate={true} /&gt;
  const pTag = container.querySelector(&quot;p#test&quot;);
  expect(pTag.textContent).toBe(&quot;idle&quot;);
});

// This is where I get my issue...
test(&quot;useAsync gets to a success state&quot;, (done) =&gt; {
  const { container } = render(&lt;MockComponent callback={defaultCallback} immediate={true} /&gt;
  const pTag = container.querySelector(&quot;p#test&quot;);
  setTimeout(() =&gt; {
    expect(pTag.textContent).toBe(&quot;success&quot;);
    done();
  }, 2000);
});

// Some other tests...

</code></pre>
<p>When I run these two tests that I've included above, they actually run fine and if I look at the code coverage report(s) that are generated, it's 100% coverage. In the console, though, when running these tests, when I run the second one, I get the following error and I'm not sure how to resolve it. I have tried to wrap the entire body of the test in <code>act</code>, but that made no difference, so I'm not entirely sure what the best approach may be here.</p>
<p>Here's the console output:</p>
<pre><code>console.error
 Warning: An update to MockComponent inside a tests 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. Learn more at https://reactjs.org/link/wrap-tests-with-act 
  at MockComponent....
</code></pre>
<p>As I've said, I've tried to wrap my entire test(s) with an act, but I've had no luck there. What I have found interesting is that in the console output, when it apparently errors, it also highlights this snippet of the hook:</p>
<pre class=""lang-js prettyprint-override""><code>      .then(response =&gt; {
        setValue(response);
        // ^
        setStatus('success');
        // ^
      })
      .catch(error =&gt; {
        setError(error);
</code></pre>
<p>Should I perhaps ignore this issue? After all when all of my tests are run, no tests/test suite fails or anything.</p>
",https://stackoverflow.com/questions/65807464/react-unit-testing-state-updates,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",153,True,1,1
unit testing a tkinter application,"<p>Someone can suggest how you can make simple tests here.
This is a simple keyboard trainer on tkinter, a window appears where you can select the difficulty level and start the game.</p>
<p>Or if you can give a link to a resource with explanations</p>
<pre><code>from tkinter import *
import sys
import time
from random import choices
root = Tk()  # Создаем основное окно
top = Toplevel()  # Создаем окно для выбора сложности
# добавляем виджеты в окно выбора сложности
var = IntVar()
Radiobutton(top, text='Легкая', variable=var, value=0).pack()
Radiobutton(top, text='Нормальная', variable=var, value=1).pack()
Radiobutton(top, text='Сложная', variable=var, value=2).pack()
button1 = Button(top, text=&quot;Играть&quot;, command=lambda: command()).pack()
button2 = Button(top, text=&quot;Выйти&quot;, command=lambda: command2()).pack()
def command():
    global test_words1
    if var.get() == 0:
        with open(&quot;words.txt&quot;, &quot;r&quot;) as words:
            test_words1 = choices(list(words), k=1)
            dif()


    elif var.get() == 1:
        with open(&quot;words.txt&quot;, &quot;r&quot;) as words:
            test_words1 = choices(list(words), k=2)
            dif()

    elif var.get() == 2:
        with open(&quot;words.txt&quot;, &quot;r&quot;) as words:
            test_words1 = choices(list(words), k=3)
            dif()

pos = 0
b = 0
mistakes = 0
correct_presses = 0


def key_type(e):
    if e.keycode != 16:
        global pos, text_widget, b, mistakes, correct_presses
        if (test_text[pos] != e.char):
            text_widget.tag_add(&quot;wrong&quot;, str(1) + &quot;.&quot; + str(b))
            mistakes += 1
        if (test_text[pos] == e.char):
            text_widget.tag_add(&quot;correct&quot;, str(1) + &quot;.&quot; + str(b))
            correct_presses += 1
        b += 1
        pos += 1
        if (pos == len(test_text)):
            end_time = time.time()
            rav=end_time-start_time

            label1 = Label(root2,text=&quot;NICE!&quot;, fg=&quot;#eee&quot;, bg=&quot;#957&quot;)
            label1.pack()

            label2 = Label(root2, text=&quot;TIME:&quot;, fg=&quot;#eee&quot;, bg=&quot;#957&quot;)
            label2.pack()

            label0 = Label(root2,text=rav, fg=&quot;#eee&quot;, bg=&quot;#957&quot;)
            label0.pack()
def dif():
    root.withdraw()
    top.destroy()  # Уничтожаем окно выбора сложност
    global root2
    root2 = Tk()  # Создаем основное окно
    root2.deiconify()  # Показываем основное окно
    top.destroy()  # Уничтожаем окно выбора сложности
    global start_time
    start_time = time.time()
    global test_text
    global text_widget

    len_word_list = [len(word.strip()) for word in test_words1]

    index_nostrip1 = 6
    end_of_line1 = 0
    final_word_list1 = []
    lines_list1 = []
    line1 = &quot;&quot;

    for i in range(len(test_words1)):
        if end_of_line1 == index_nostrip1 - 1:
            final_word_list1.append(test_words1[i])
            line1 += test_words1[i].strip()
            lines_list1.append(line1)
            line1 = &quot;&quot;
            end_of_line1 = 0
        else:
            final_word_list1.append(test_words1[i].strip())
            line1 += f&quot;{test_words1[i].strip()} &quot;
            end_of_line1 += 1

        # create the final string to be used in the test
        test_text = &quot; &quot;.join(final_word_list1)

    text_widget = Text(root2, height=10, width=100,
                           padx=20, pady=20, font=(&quot;Arial &quot;, 16))
    text_widget.insert(END, test_text)
    text_widget.configure(state=&quot;disabled&quot;)
    text_widget.tag_config(&quot;correct&quot;, background=&quot;green&quot;, foreground=&quot;white&quot;)
    text_widget.tag_config(&quot;wrong&quot;, background=&quot;red&quot;, foreground=&quot;white&quot;)

    text_widget.bind(&quot;&lt;KeyPress&gt;&quot;, key_type)
    text_widget.focus()
    text_widget.pack()

    message = Label(root,
                    text=&quot;Start typing&quot;,
                    font=(&quot;Arial &quot;, 24))
    message.pack()
    root2.mainloop()


# эта команда выполняется по кнопке Выйти
def command2():
    top.destroy()  # Уничтожаем окно выбора сложности
    root.destroy()  # Уничтожаем основное окно
    sys.exit()  # Выходим из программы
root.withdraw()  # Скрываем основное окно, пока показываем окно выбора сложности
root.mainloop()
</code></pre>
<p><em>I have already tried to write something similar, but the tests do not pass</em></p>
<pre><code>class TKinterTestCase(unittest.TestCase):
    def setUp(self):
        self.root=tkinter.Tk()
        self.pump_events()

    def tearDown(self):
        if self.root:
            self.root.destroy()
            self.pump_events()

    def pump_events(self):
        while self.root.mainloop(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
            pass

if __name__ == '__main__':
    unittest.main()
</code></pre>
",https://stackoverflow.com/questions/68428433/unit-testing-a-tkinter-application,"['python', 'tkinter', 'python-unittest']",329,False,1,0
Unit Testing ViewModel + Coroutine + LiveData,"<p>I have a problem testing the following ViewModel with coroutines. Even though I inject a TestCoroutineDispatcher() in the viewModel for testing and runs the code inside a runBlocking block the call to fetchInitialData seems to be executed on another thread and my test fails due to assertion being made before fetchInitialData method completes</p>
<pre><code>class MyViewModel(
    private val dispatcher: CoroutineDispatcher,
    private val repository: MyRepository
) : ViewModel() {

fun fetchInitialData() {
    viewModelScope.launch(dispatcher) {
        _loading.postValue(true)
        // do some heavy work
        _loading.postValue(false)
        _myList.postValue(result)
    }
}
</code></pre>
<p>My test is as follow:</p>
<pre><code>@Test
fun myTest() runBlocking {
    server.mockJsonResponse(&quot;a-json-response.json&quot;)
    viewModel = MyViewModel(
        testCoroutineDispatcher,
        MyRepository(service)
    )
    viewModel.fetchInitialData() // this block doesn't stop it's asynchronous
    // my assertions comes here
}
</code></pre>
",https://stackoverflow.com/questions/66683378/unit-testing-viewmodel-coroutine-livedata,"['android', 'unit-testing', 'android-livedata', 'kotlin-coroutines', 'android-viewmodel']",152,False,1,1
Unit testing in nest js,"<p>I am having an error that <strong>cannot read property find of undefined</strong> when I am trying to pass a mongoose model(UserGroup.name) when writing a unit test case for a service.</p>
<pre><code>service.spec.ts
const module: TestingModule = await Test.createTestingModule({

      providers: [
        { provide: getModelToken(User.name), useValue: Model },
        { provide: getModelToken(UserGroup.name), useValue: { find: jest.fn(() =&gt; userGroupResp) } },
        { provide: getModelToken(UserCredential.name), useValue: Model },
        { provide: getModelToken(ActivityLog.name), useValue: Model },
        LoggerService,
        I18nRequestScopeService,
        { provide: I18nService, useValue: option },
        productServiceProvider,
        UserMongoService,

      ],
    }).compile();

service.ts
  constructor(
    @InjectModel(&quot;User&quot;) private readonly userModel: Model&lt;IUser&gt;,
    @InjectModel(UserGroup.name) private readonly userGroupModel: Model&lt;IUserGroup&gt;,
    @InjectModel(&quot;UserCredential&quot;) private readonly userCredentialModel: Model&lt;any&gt;,
    @InjectModel(&quot;ActivityLog&quot;) private readonly activityLogModel: Model&lt;any&gt;,
    private readonly logger: LoggerService,
    private readonly i18n: I18nRequestScopeService,
    private productMongoService: ProductMongoService
  ) { }

async getUserGroups()
{
 userGroups = await this.userGroupModel.find(  // having undefined error at this line.
          {
            productId: currentProduct,
          },
        );

}
</code></pre>
<p>the error is only while testing otherwise it is working fine.</p>
",https://stackoverflow.com/questions/69535938/unit-testing-in-nest-js,"['node.js', 'unit-testing', 'mongoose', 'jestjs', 'nestjs']",269,False,1,0
unit testing with pytest parametrize,"<p>I have the following test code:</p>
<pre><code>class TestMyCode(unittest.TestCase):
    @pytest.mark.parametrize('item', [5,4,10])
    def test_valid_range(self, item):
        self.assertTrue(1 &lt;= item &lt;= 1000)
</code></pre>
<p>This is not my real test this is just a minimal reproduce example.</p>
<p>I need to parameterised only the input which is checked against the same code.</p>
<p>For some reason this doesn't work I always get:</p>
<pre><code> TypeError: test_valid_range() missing 1 required positional argument: 'item'
</code></pre>
<p>How can I fix it?</p>
",https://stackoverflow.com/questions/69315594/unit-testing-with-pytest-parametrize,"['python', 'pytest']",1385,True,1,1
Jest Unit Testing for Cron,"<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>//How to write Unit Test Case for the following Cron Job

index.js

import cron from 'node-cron'
export const cronJob = cron.schedule(pattern , async()=&gt; {
  // do something
}

index.spec.js

import { cron } from 'node-cron';
import {cronJob} from '.'
jest.mock('node-cron', () =&gt; {
    return {
      schedule: jest.fn(),
    };
 });
 describe(""Run Cron"" , async()=&gt; {
    await cronJob.start()
    await cronJob.destroy()
 }
 </code></pre>
</div>
</div>
</p>
<p>This above code is not getting covered by TC
Do need a help thank you
The TC is covered 0% of the Code i dont know why</p>
",https://stackoverflow.com/questions/70083057/jest-unit-testing-for-cron,"['javascript', 'node.js', 'unit-testing', 'jestjs', 'cron']",386,False,1,2
Headless unit testing for WebView2,"<p>I'm writing unit tests for a class that wraps the WebView2 browser control (WPF version if it matters).</p>
<p>Is there a way to run WebView2 in the equivalent of a headless mode so I don't have to actually load a window in order to test it? I've tried passing <code>--headless</code> in as an additional browser argument but <code>EnsureCoreWebView2Async</code> still spins forever so I assume it's one of the ignored arguments.</p>
",https://stackoverflow.com/questions/68885599/headless-unit-testing-for-webview2,"['.net', 'wpf', 'webview2', '.net-4.6.1']",866,False,1,0
Unit testing a JSON formatter?,"<p>I'm building a library, that takes a JSON string in and formats it according to template and specification, selected by the user.</p>
<p>I've recently started on writing Unit Tests for this library, and found that creating data I can assert against in some cases takes a lot of code, and in most cases makes the tests hard to read.</p>
<p>Just as an example of what the package does:</p>
<p>Input json:</p>
<pre><code>{
   &quot;id&quot;: 1,
   &quot;name&quot;: &quot;abc&quot;,
   &quot;barId&quot;: 5
}
</code></pre>
<p>Output json:</p>
<pre><code>{
   &quot;href&quot;: &quot;/foo/1&quot;,
   &quot;name&quot;: &quot;abc&quot;,
   &quot;_children&quot;: [
      &quot;bar&quot;: {
         &quot;href&quot;: &quot;/bar/5&quot;
      }
   ]
}
</code></pre>
<p>So the parsed json can potentially be deeply nested, based on user configuration.</p>
<p>For now I've build a generator that uses Newtonsoft.Json to generate the objects to assert against, but all of that work got me thinking if there maybe is a better way to do it.</p>
<p>Some of the test I need to do is for example:</p>
<ul>
<li>checking if the returned json contains &quot;_children&quot; when it should</li>
<li>if the href is empty, null or not there at all</li>
<li>if the properties are passed through properly</li>
<li>if the children have their properties passed through properly</li>
</ul>
<ul>
<li>all the variations based on the configuration.</li>
</ul>
<p>So, back to the question is there some clean way to perform this kind of asserts? Is there a faster way to build the expected json, other than building it by hand?</p>
",https://stackoverflow.com/questions/68181729/unit-testing-a-json-formatter,"['c#', 'json', 'api', 'xunit']",597,True,1,1
Angular window.parent.postMessage jasmine unit testing,"<p>How can I test this method with postMessage</p>
<pre class=""lang-js prettyprint-override""><code>navigateTo = (): void =&gt; {
    window.parent.postMessage('NESTED_NAVIGATION', 'target_origin');
}
</code></pre>
<p>I want to check if the postMessage event is fired when I call the <code>navigateTo</code> method</p>
<p>I tried this but didn't work</p>
<pre class=""lang-js prettyprint-override""><code>it('should post message on click', async () =&gt; {
   spyOn(component, 'navigateTo');
   let postMessageSpy = spyOn(window.parent, 'postMessage');
   component.navigateTo();
   expect(postMessageSpy).toHaveBeenCalled();
});
</code></pre>
",https://stackoverflow.com/questions/70440045/angular-window-parent-postmessage-jasmine-unit-testing,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",1126,True,1,1
Unit Testing for Linq Method,"<p>I have a method for which I have to write a Unit Test. This method uses Database context to retrieve details from database.</p>
<p>Now I am thinking of ways to mock this database context and test remaining LINQ code.</p>
<p>Similarly I have other methods which has some logic and some LINQ queries I want to Unit test them as well.</p>
<pre><code>public class OrderService
{
    private DataContext _context;

    public OrderService(DataContext context)
    {
        _context = context;
    }

    public int OrderCount(int orderId)
    {
        var count = _context.Orders.Where(x=&gt;x.orderId==orderId).ToList().Count;
    }
}
</code></pre>
<p>How should I approach this situation?</p>
<p>This is common scenario faced by developers still there is not much information available on this. Any suggestions would be appreciated.</p>
",https://stackoverflow.com/questions/69507597/unit-testing-for-linq-method,"['c#', 'linq', 'unit-testing', 'nunit', 'moq']",595,True,1,1
golang gin middleware unit testing,"<p>I have a middleware handler function and I would like to be able to write unit tests for this function. How might I go about doing this in GoLang? I would like to be able to verify when I call to add this middleware that the context will have the user id if successfully verifying jwt token or API key. And also confirm if the right error message gets sent if I have the wrong key for some reason.</p>
<p>Here is the function.</p>
<pre><code>// Middleware wraps the request with auth middleware
func Middleware(path string, cfg *cfg.Server, orm *orm.ORM) gin.HandlerFunc {
    logger.Info(&quot;[Auth.Middleware] Applied to path: %s&quot;, path)
    return gin.HandlerFunc(func(c *gin.Context) {
        // Check and authenticate with api key
        if a, err := parseAPIKey(c, cfg); err == nil {
            user, err := findUserByAPIKey(a, orm)
            if err != nil {
                authError(c, ErrForbidden)
            }
            if user != nil {
                c.Request = addToContext(c, consts.ProjectContextKeys.UserCtxKey, user)
                c.Request = addUserIdToContext(c, user.ID)
                logger.Debug(&quot;User authenticated via api: %s&quot;, user.ID)
            }
            c.Next()
        } else {
            if err != ErrEmptyAPIKeyHeader {
                authError(c, err)
            } else {
                // Authenticate via JWT Token
                t, err := parseToken(c, cfg)
                if err != nil {
                    authError(c, err)
                } else {
                    if claims, ok := t.Claims.(jwt.MapClaims); ok {
                        if claims[&quot;exp&quot;] != nil {
                            issuer := claims[&quot;iss&quot;].(string)
                            userid := claims[&quot;jti&quot;].(string)
                            email := claims[&quot;sub&quot;].(string)
                            if claims[&quot;aud&quot;] != nil {
                                audiences := claims[&quot;aud&quot;]
                                logger.Warn(&quot;\n\naudiences: %s\n\n&quot;, audiences)
                            }
                            if claims[&quot;alg&quot;] != nil {
                                algo := claims[&quot;alg&quot;].(string)
                                logger.Warn(&quot;\n\nalgo: %s\n\n&quot;, algo)
                            }
                            if user, err := findUserByJWT(email, issuer, userid, orm); err != nil {
                                authError(c, ErrForbidden)
                            } else {
                                if user != nil {
                                    c.Request = addToContext(c, consts.ProjectContextKeys.UserCtxKey, user)
                                    c.Request = addUserIdToContext(c, user.ID)
                                    logger.Debug(&quot;User: %s&quot;, user.ID)
                                }
                                c.Next()
                            }
                        } else {
                            authError(c, ErrMissingExpField)
                        }
                    } else {
                        authError(c, err)
                    }
                }
            }
        }
    })
}
</code></pre>
<p>and here is me trying to figure out how to get started with the tests</p>
<pre><code>func TestMiddleware(t *testing.T) {
    // TODO Need to update test
    t.Run(&quot;middleware api key from header&quot;, func(t *testing.T) {
        findUserByAPIKey = func(apiKey string, o *orm.ORM) (*models.User, error) {
            return &amp;models.User{}, nil
        }
        parseAPIKey = func(c *gin.Context, sc *cfg.Server) (apiKey string, err error) {
            return &quot;api_key&quot;, nil
        }
        svc := &amp;cfg.Server{}
        Middleware(&quot;/test&quot;, svc, &amp;orm.ORM{})
    })
    // TODO Need to update test
    t.Run(&quot;middleware jwt key from header&quot;, func(t *testing.T) {
        findUserByJWT = func(email, provider, userID string, o *orm.ORM) (*models.User, error) {
            return &amp;models.User{}, nil
        }

        parseToken = func(c *gin.Context, sc *cfg.Server) (t *jwt.Token, err error) {
            return &amp;jwt.Token{}, nil
        }
        svc := &amp;cfg.Server{}
        Middleware(&quot;/test&quot;, svc, &amp;orm.ORM{})
    })
}
</code></pre>
",https://stackoverflow.com/questions/69893767/golang-gin-middleware-unit-testing,"['unit-testing', 'go', 'go-gin']",323,False,1,0
unit testing for clr library,"<p>I have been trying to create UnitTest project for my C++ clr library. The UnitTest project has TESTCLASS and TESTMETHOD attributes class and methods. The library that I need to test is a clr library. Now I need to change the settings for test project to Advanced-&gt;CLR support - yes
Once I change this setting the testmethods fail to appear in the Test Explorer and if I don't the tested library is not accessible in the test project.
Is there a way to test the clr libraries using the UnitTest framework.</p>
",https://stackoverflow.com/questions/68667783/unit-testing-for-clr-library,"['unit-testing', 'nunit', 'clr']",139,False,1,0
Unit Testing Graph SDK PageIterator,"<p>I am creating a service that uses Microsofts Graph SDK which has a method for retrieving all applications from Active Directory. Originally I wrote the method with only a single page in mind and successfully mocked out the call in unit tests like below.</p>
<p><strong>Method</strong></p>
<pre class=""lang-cs prettyprint-override""><code>public async Task&lt;IList&lt;Application&gt;&gt; GetAllApplicationsAsync()
{
    var applicationFirstPage = await _graphServiceClient.Applications
            .Request()
            .GetAsync();

    return applicationFirstPage;
}
</code></pre>
<p><strong>Unit Test</strong></p>
<pre class=""lang-cs prettyprint-override""><code>[Test]
public async Task GetAllApplicationsAsync_NoApplications_ReturnsEmptyAsync()
{
    // Arrange
    var graphServiceClientMock = new Mock&lt;IGraphServiceClient&gt;();

    // Create an empty page of applications
    GraphServiceApplicationsCollectionPage page = new GraphServiceApplicationsCollectionPage { };

    graphServiceClientMock.Setup(m =&gt; m.Applications.Request().GetAsync()).ReturnsAsync(() =&gt; page);
    var graphClient = new GraphClient(graphServiceClientMock.Object);

    // Act
    var apps = await graphClient.GetAllApplicationsAsync();

    // Assert
    Assert.That(apps, Is.Empty);
}
</code></pre>
<p>I then proceeded to extend the method from the default query and loop through all pages to get a list of all applications. I used <code>PageIterator</code> as outlined in the <a href=""https://learn.microsoft.com/en-us/graph/sdks/paging?tabs=csharp"" rel=""nofollow noreferrer"">docs</a>. When I went to update the unit tests I've struggled to adapt them to include <code>PageIterator</code>.</p>
<p>Calling <code>await pageIterator.IterateAsync();</code> throws a null ref exception, and I cannot think of how I'd mock or get around that.</p>
<p><strong>Extended Method</strong></p>
<pre class=""lang-cs prettyprint-override""><code>public async Task&lt;IList&lt;Application&gt;&gt; GetAllApplicationsAsync()
{
    var applicationFirstPage = await _graphServiceClient.Applications
            .Request()
            .GetAsync();

    List&lt;Application&gt; applications = new List&lt;Application&gt;();
    var pageIterator = PageIterator&lt;Application&gt;
        .CreatePageIterator(_graphServiceClient, applicationFirstPage, (a) =&gt;
        {
            applications.Add(a);
            return true;
        });

    await pageIterator.IterateAsync();

    return applications;
}
</code></pre>
<p>I'd appreciate any help or advice on how to cover this method with unit tests. Thanks in advance.</p>
",https://stackoverflow.com/questions/66268527/unit-testing-graph-sdk-pageiterator,"['c#', 'unit-testing', 'microsoft-graph-api', 'microsoft-graph-sdks']",802,True,0,1
Spring-boot-jdbcTemplate Unit-testing,"<p>I am new to Spring and only somewhat experienced with JUnit I have the following method which requires a unit test</p>
<pre><code>@Override
public List&lt;Map&lt;String, Object&gt;&gt; executeSqlQuery(String sql) {
        List&lt;Map&lt;String, Object&gt;&gt; downloadRequest = jdbcTemplate.queryForList(sql);
        return downloadRequest;

}
</code></pre>
<p>Does anyone have any suggestions on how I might achieve this using JUni?
Thank you very much in advance!</p>
",https://stackoverflow.com/questions/68767189/spring-boot-jdbctemplate-unit-testing,"['spring-boot', 'unit-testing', 'junit', 'junit5', 'jdbctemplate']",2207,False,0,1
Laravel unit testing json response,"<p>I have the following test in my app. However the response isn't passing the test, and I can't see why...</p>
<pre><code>public function test_get()
{
    $user = $this-&gt;signInAsUser();
    
    $product = factory('App\Models\Product')-&gt;create();

    factory('App\Models\Stock')-&gt;create([
        'product_id' =&gt; $product-&gt;id,
        'qty' =&gt; $qty = rand(1, 100),
    ]);

    $this-&gt;json('GET', '/api/stock', , ['Accept' =&gt; 'application/json'])
        -&gt;assertStatus(200)
        -&gt;assertJson([
            'data' =&gt; [
                'product_id' =&gt; &quot;$product-&gt;id&quot;,
                'stock' =&gt; &quot;$qty&quot;
            ]
        ]);
}
</code></pre>
<p>This produces the following from PHPUnit:</p>
<pre><code>Unable to find JSON: 

[{
    &quot;data&quot;: {
        &quot;product_id&quot;: &quot;1&quot;,
        &quot;stock&quot;: &quot;55&quot;
    }
}]

within response JSON:

[{
    &quot;data&quot;: [
        {
            &quot;product_id&quot;: &quot;1&quot;,
            &quot;stock&quot;: &quot;55&quot;
        }
    ]
}].


Failed asserting that an array has the subset Array &amp;0 (
    'data' =&gt; Array &amp;1 (
        'product_id' =&gt; '1'
        'stock' =&gt; '55'
    )
).
</code></pre>
<p>The assertion is failing the test and I can't see why as the JSON looks the same to me...</p>
",https://stackoverflow.com/questions/70392498/laravel-unit-testing-json-response,"['php', 'laravel', 'phpunit']",1239,True,0,1
Unit testing with legacy library,"<p>I`m developing a C# small app which consumes data from a legacy library and I was wondering the best way to unit test. The legacy library is essentially a function which is connected with a remote server and returns a big object that I have to process in my app.</p>
<p>My first thought was to create three classes:</p>
<ul>
<li>A: for store the object properties I'm interested in</li>
<li>B: for isolate the legacy function (just one method which returns an instance of A)</li>
<li>C: My &quot;real&quot; app (Calls B method and process the A instance)</li>
</ul>
<p>So, in order to test my app the natural way seems to create a mock which implements the B interface and returns an instance of A with the right properties for each test but... I realized that 90% of code I wrote is on A and B (function call, error handling, A instance creation and filling,...) instead of C (the class I was designing to be testable) and, more than that, the code which is really important to test was in B.</p>
<p>To fix this, I decided to move as much code as possible to C, but even with that, 70% of code was still in A and B (A has a lot of properties to be filled when created).</p>
<p>So, I tried to remove A and return the whole object that legacy function returns but, sadly, this object can not be instantiated, so it can not be created in mock implementation of B.</p>
<p>Finally, I decided to implement a (unit?) test which calls the B method in order to validate the B implementation but, obviously, B is consuming data from a remote server which is not always available (it will not work in my CI build server...)</p>
<p>Is there any better approach for this? Any way of isolate the function of the rest of the code I wrote?</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/70473178/unit-testing-with-legacy-library,"['c#', 'unit-testing', 'oop']",51,False,0,0
Angular unit testing - injection failing,"<p>I'm trying my hand at creating an Angular unit test, but failing right off the bat.</p>
<p>I've taken a look at <a href=""https://stackoverflow.com/questions/53769401/angular-6-nullinjectorerror-no-provider-for-httpclient-in-unit-tests"">this</a> and <a href=""https://stackoverflow.com/questions/53769401/angular-6-nullinjectorerror-no-provider-for-httpclient-in-unit-tests"">this</a> this SO, which seems to be exactly what I'm struggling with, but after attempting the fixes mentioned there, I am still not coming right.</p>
<p>This is my code :</p>
<pre><code>import { TestBed } from '@angular/core/testing';

import { ContactsService } from './contacts.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { HttpClient } from '@angular/common/http';

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


   beforeEach(() =&gt; {
     TestBed.configureTestingModule({
       imports: [ HttpClientTestingModule, ContactsService, HttpClient],
  })
  .compileComponents();
  });


});
</code></pre>
<p>When I run an ng test, I get this error :</p>
<blockquote>
<p>NullInjectorError: R3InjectorError(DynamicTestModule)[ContactsService -&gt; HttpClient -&gt; HttpClient]:
NullInjectorError: No provider for HttpClient!</p>
</blockquote>
<p>My .ts, for completeness :</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Entry } from '../classes/entry';
import { EntrySearch } from '../classes/entrySearch';

@Injectable({
  providedIn: 'root'
})
export class ContactsService {

  constructor(private http: HttpClient) { }

}
</code></pre>
",https://stackoverflow.com/questions/66336549/angular-unit-testing-injection-failing,"['angular', 'unit-testing']",404,False,0,2
unit testing a vue component,"<p>I have a component that looks like this,</p>
<pre><code>&lt;template&gt;
&lt;!-- eslint-disable vue/no-v-html --&gt;
&lt;div class=&quot;c-dialog&quot; :class=&quot;{'u-block': show}&quot; @triggerOpen=&quot;handleOpen&quot;&gt;
    &lt;div class=&quot;c-dialog__background&quot; @click=&quot;handleClose&quot;&gt;
        &lt;div class=&quot;c-dialog__wrapper u-mt-4 u-mb-1&quot;&gt;
            &lt;div class=&quot;c-dialog__action u-flex&quot;&gt;
                &lt;button class=&quot;c-dialog__close u-bg-denim-blue u-border-0 u-text-white&quot; @click=&quot;handleClose&quot;&gt;Close&lt;/button&gt;
            &lt;/div&gt;
            &lt;div class=&quot;c-dialog__main u-px-2 u-py-4 u-border u-bg-white&quot;&gt;
                &lt;h4&gt;{{ content.title }}&lt;/h4&gt;
                &lt;div class=&quot;c-dialog__content u-mt-2&quot; v-html=&quot;content.content&quot; /&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p>I am wanting to unit test it, but I am very rusty when it comes to unit testing, the component is very simple, it is either show or hidden based on data value (show: true/false).</p>
<p>I assume that I would need 1 test for asserting that the component is hidden when show = false and another for asserting that modal is visible when show = true. But in a component that is so simple should I be unit testing anything else? There are 2 methods in the component <code>handleClose</code> (sets show to false) and handleOpen (sets show to true), does these methods need there own tests also? So far my test looks like,</p>
<pre><code>import { shallowMount } from '@vue/test-utils'
import Dialog from './Dialog.vue'

test('Dialog', () =&gt; {

});
</code></pre>
",https://stackoverflow.com/questions/69286803/unit-testing-a-vue-component,"['javascript', 'vue.js', 'unit-testing']",522,False,0,1
Angular input event unit testing,"<p>I have unit test case to test global filter function with input event in angular application. I'm not sure if this is an angular version problem or if I'm missing anything from the test case.</p>
<p>Environment : Angular CLI: 12.2.6 Node: 14.17.6</p>
<p>Here's the error;</p>
<pre><code>TypeError: Cannot read properties of null (reading 'nativeElement')
</code></pre>
<p><strong>Home.component.ts</strong></p>
<pre><code>  filterGlobal(dt: any, event){
    dt.filterGlobal(event.target.value, 'contains')
  }
</code></pre>
<p><strong>Home.component.html</strong></p>
<pre><code>&lt;p-table class=&quot;filterTable&quot; #dt [columns]=&quot;cols&quot; [value]=&quot;cars&quot;&gt;
    &lt;ng-template pTemplate=&quot;caption&quot;&gt;
        &lt;div style=&quot;text-align: right&quot;&gt;
            &lt;i class=&quot;pi pi-search&quot; style=&quot;margin:4px 4px 0 0&quot;&gt;&lt;/i&gt;
            &lt;input type=&quot;text&quot; class=&quot;globalFilter&quot; pInputText size=&quot;50&quot; placeholder=&quot;Global Filter&quot; (input)=&quot;dt.filterGlobal($event.target.value, 'contains')&quot; style=&quot;width:auto&quot;&gt;
        &lt;/div&gt;
    &lt;/ng-template&gt;
    &lt;ng-template pTemplate=&quot;header&quot; let-columns&gt;
        &lt;tr&gt;
            &lt;th *ngFor=&quot;let col of columns&quot;&gt;
                {{col.header}}
            &lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;th *ngFor=&quot;let col of columns&quot; [ngSwitch]=&quot;col.field&quot;&gt;
                &lt;input *ngSwitchCase=&quot;'brand'&quot; class=&quot;brandFilter&quot; pInputText type=&quot;text&quot; (input)=&quot;dt.filter($event.target.value, col.field, col.filterMatchMode)&quot;&gt;
            &lt;/th&gt;
        &lt;/tr&gt;
    &lt;/ng-template&gt;
    &lt;ng-template pTemplate=&quot;body&quot; let-rowData let-columns=&quot;columns&quot;&gt;
        &lt;tr&gt;
            &lt;td *ngFor=&quot;let col of columns&quot;&gt;
                {{rowData[col.field]}}
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/ng-template&gt;
&lt;/p-table&gt;
</code></pre>
<p><strong>Home.component.spec.ts</strong></p>
<pre><code>it('should use global filter and show 1 items', fakeAsync(() =&gt; {
    fixture = TestBed.createComponent(HomeComponent);
    app = fixture.debugElement.componentInstance;
    fixture.detectChanges();

    const globalFilter = fixture.debugElement.query(By.css(&quot;.globalFilter&quot;));
    globalFilter.nativeElement.value = &quot;dsad231ff&quot;;
    globalFilter.nativeElement.dispatchEvent(new Event(&quot;input&quot;));
    tick(300);
    fixture.detectChanges();

    const tableEl = fixture.debugElement.query(By.css(&quot;.filterTable&quot;));
    const bodyRows = tableEl.query(By.css('.p-datatable-tbody')).queryAll(By.css('tr'));
    expect(bodyRows.length).toEqual(1);
}));
</code></pre>
<p>I tried this as well, still it didn't work for me</p>
<pre><code>it('should click Send button with fakeAsync', fakeAsync(() =&gt; {
  let buttonElement = fixture.debugElement.query(By.css('.globalFilter'));
    
  spyOn(component, 'globalFilter');
  //Trigger click event after spyOn
  buttonElement.triggerEventHandler('put', null);
    
  tick();
  expect(component.globalFilter).toHaveBeenCalled();
})); 
</code></pre>
<p>ERROR:</p>
<pre><code>TypeError: Cannot read properties of null (reading 'triggerEventHandler')
</code></pre>
<p>Appreciated if any help</p>
",https://stackoverflow.com/questions/70100959/angular-input-event-unit-testing,"['javascript', 'angular', 'unit-testing', 'karma-jasmine']",2250,False,0,1
Python unit testing import problems,"<p>I have a product with several features. At a high level, I'm trying to figure out how to structure my directories and do my imports such that all of the following are true.</p>
<ol>
<li>The directory structure has a separate directory for each feature.</li>
<li>Each feature directory has a <code>src</code> directory that contains the code that will be deployed to the server.</li>
<li>Each feature directory has a <code>test</code> directory that contains the unit tests for the modules in the <code>src</code> folder.</li>
<li>We can use automatic test discovery from the <code>unittest</code> module.</li>
</ol>
<p>For example, my <code>scifi</code> project has an <code>antigravity</code> feature and a <code>ftl</code> feature. The tree presently looks like this; when I started I had no <code>__init__.py</code> files.</p>
<pre><code>~/Projects/scifi $ tree
.
├── antigravity
│   ├── __init__.py
│   ├── src
│   │   ├── antigravity.py
│   │   ├── gravity.py
│   │   └── __init__.py
│   └── test
│       ├── __init__.py
│       └── test_antigravity.py
└── ftl
    ├── ...
    └── ...
</code></pre>
<p>The antigravity module imports from gravity module</p>
<pre><code>~/Projects/scifi $ cat antigravity/src/gravity.py 
def fall():
    return 9.8

~/Projects/scifi $ cat antigravity/src/antigravity.py
# absolute import
from gravity import fall

def fly():
    return -fall()
</code></pre>
<p>Now I write a test module and find that it cannot import the antigravity module to test it.</p>
<pre><code>~/Projects/scifi $ cat antigravity/test/test_antigravity.py 
from antigravity.src.antigravity import fly
import unittest

class TestAntigravity(unittest.TestCase):

    def test_my_subtract_one(self):
        self.assertEqual(fly(), -9.8)

~/Projects/scifi $ python -m unittest
E
======================================================================
ERROR: antigravity.test.test_antigravity (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: antigravity.test.test_antigravity
Traceback (most recent call last):
  File &quot;/usr/local/lib/python3.8/unittest/loader.py&quot;, line 436, in _find_test_path
    module = self._get_module_from_name(name)
  File &quot;/usr/local/lib/python3.8/unittest/loader.py&quot;, line 377, in _get_module_from_name
    __import__(name)
  File &quot;[~/Projects/scifi]/antigravity/test/test_antigravity.py&quot;, line 1, in &lt;module&gt;
    from antigravity.src.antigravity import fly
  File &quot;[~/Projects/scifi]/antigravity/src/antigravity.py&quot;, line 1, in &lt;module&gt;
    from gravity import fall
ModuleNotFoundError: No module named 'gravity'


----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)
</code></pre>
<p>This is where I added the <code>__int__.py</code> files, and then got the same error. After that I made one small change to <code>antigravity.py</code> and ran my tests again</p>
<pre><code>~/Projects/scifi $ cat antigravity/src/antigravity.py 
# relative import
from .gravity import fall

def fly():
    return -fall()

~/Projects/scifi $ python -m unittest
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
</code></pre>
<p>Great, so now <code>antigravity</code> can import <code>gravity</code> for testing, but I soon find that the import fails any other time.</p>
<pre><code>~/Projects/scifi $ python antigravity/src/antigravity.py 
Traceback (most recent call last):
  File &quot;antigravity/src/antigravity.py&quot;, line 1, in &lt;module&gt;
    from .gravity import fall
ImportError: attempted relative import with no known parent package
</code></pre>
<p>So an absolute package reference gets me <code>ModuleNotFoundError</code> while testing and a relative package reference gets me an <code>ImportError</code> any other time. How do I get the import to work in both situations?</p>
<p>Here's a <a href=""https://github.com/Adam-Hoelscher/scifi_testing"" rel=""nofollow noreferrer"">copy of this example on Github</a> so that nobody has to copy/paste to get my example.</p>
",https://stackoverflow.com/questions/68718173/python-unit-testing-import-problems,"['python', 'unit-testing', 'python-import']",199,False,0,0
Quarkus unit-testing and properties,"<p>I have a basic question about Quarkus testing, I would like to execute the command <code>./mvnw clean test</code> but I need to use a token to init the application.</p>
<p>I have configured <code>application-test.properties</code> file to store the token:</p>
<p><code>discord.token=XYZ</code></p>
<p>So, in my code I was expecting to be able to retrieve the value of the <code>discord.token</code> property:</p>
<pre class=""lang-java prettyprint-override""><code>@ConfigProperty(name = &quot;discord.token&quot;)
private String token;
</code></pre>
<p>Is it possible? if not, how can I do this?</p>
<p>thanks</p>
",https://stackoverflow.com/questions/70049356/quarkus-unit-testing-and-properties,"['unit-testing', 'quarkus', 'system-properties']",1408,False,0,2
Unit testing classes in Python,"<p>I have a few classes in Python that I would like to unit test, each of them has an <code>__init__()</code> method that instantiates a dictionary and have a method that depending on the arguments passed to them return either an error or the required return value. My question is as the dictionary is hardcoded in, am I ok to just unittest with just those values? Or should I consider that these values could be changed in the future? As far as I know only values will be added to them. If this is the case, would I need to use mock? As how would I override instantiation. An example of one class is like follows:</p>
<pre><code>class TeamLocation:

    def __init__(self):
        self._types_location = {
            &quot;New York&quot;: {
                &quot;id&quot;: 1,
                &quot;team_id&quot;: 1

            },
            &quot;LA&quot;: {
                &quot;id&quot;: 2,
                &quot;team_id&quot;: 2
            }
        }

    def get_user_team_id(self, location):
        team_id_item = self._types_location.get(location, None)
        if not team_id_item:
            raise CityNotSupportedException(f&quot;Location: {location} does not exist.&quot;)
        return team_id_item[&quot;team_id&quot;]

def test_team_location_ok():

    team_location = TeamLocation()
    assert team_location.get_user_team_id('New York') == 1


def test_team_location_not_ok():

    team_location = TeamLocation()
    with pytest.raises(ValueError) as excinfo:
        team_location.get_user_team_id('Boston')
    assert excinfo.value.message == 'Location: Boston does not exist.'
</code></pre>
",https://stackoverflow.com/questions/69405516/unit-testing-classes-in-python,"['python', 'unit-testing', 'pytest']",52,False,0,0
Unit Testing With Mediatr pipelines,"<p>I have an api controller which uses Mediatr for a variety of operations. For some of these operations, I need to verify the user has the correct level of access, so I use an authorisation pipeline:</p>
<pre><code>public class AuthorisationPipeline&lt;TRequest, TResponse&gt; : IPipelineBehavior&lt;TRequest, TResponse&gt;
    where TRequest : IAuthorisedRequest&lt;TResponse&gt;
{
    public AuthorisationPipeline()
    {   }

    public async Task&lt;TResponse&gt; Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate&lt;TResponse&gt; next)
    {
         //Verify User
    }
}


{
    public interface IAuthorisedRequest : IAuthorisedRequest&lt;Unit&gt;
    { }

    public interface IAuthorisedRequest&lt;out TResponse&gt; : IRequest&lt;TResponse&gt;
    {
        Actor Actor { get; set; }
    }
}
</code></pre>
<p>So any request that needs to be authorised inherits the <code>IAuthorisedRequest</code> interface.</p>
<p>This works fine when running the API, however, I've been trying to set up unit tests which run an api call end to end (or functional tests or subcutaneous tests or whatever you want to call them). When I try to run those tests, any request which doesn't inherit IAuthorisedRequest throws the following exception:</p>
<p><code>    System.ArgumentException : GenericArguments[0], 'UpdateUsers+Command', on 'AuthorisationPipeline2[TRequest,TResponse]' violates the constraint of type 'TRequest'.</code></p>
<p>This can be fixed if I remove <code>where TRequest : IAuthorisedRequest&lt;TResponse&gt;</code>, but then this pipeline will run for every request, which I would rather avoid. Is there a better way around this issue? What is causing it?</p>
",https://stackoverflow.com/questions/65779455/unit-testing-with-mediatr-pipelines,"['.net', 'xunit', 'mediatr']",2641,True,0,1
Android. Unit testing for SpannableString,"<p>For testing my business logic I'm using mockk library. But I also have a few helper classes that contain methods that use SpannableString, ForegroundColorSpan etc. I need to write tests for these methods as well. However, I do not quite understand how to write such tests correctly, since before that I wrote tests only for business logic. Can I write for testing a SpannableString test using mockk . Unfortunately, I have not found any good examples to demonstrate how to write such tests. Please help me.
Here is example of code for which i need to write tests:</p>
<pre><code>fun formatSum(sum: Double): SpannableString {
    return SpannableString(sum.toString()).apply {
        if (ceil(sum)!= sum) {
            setSpan(
                ForegroundColorSpan(getColor(R.color.red)),
                sum.toString().length - 2,
                sum.toString().length,
                0
            )
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/70504529/android-unit-testing-for-spannablestring,"['android', 'unit-testing', 'spannablestring', 'mockk', 'android-spannable']",151,False,0,0
NgRx store selector unit testing,"<pre><code>ngOnInit(): void {
        this.format = this.store.select(selectUserSettings).pipe(
          filter(
            (userSettings: UserSettingsState) =&gt;
              Boolean(userSettings) &amp;&amp; !userSettings.errors &amp;&amp; !userSettings.isLoading &amp;&amp; !!userSettings.localizationProfile
          ),
          map((userSettings: UserSettingsState) =&gt;
            userSettings.localizationProfile.dateFormat.toLocaleLowerCase().replace('mm', 'MM')
          ),
          takeUntil(this.destroy)
        );
      }
</code></pre>
<p>How can I write the unit test for this function? I tried to mock the selector like <code>mockUserSettingsSelector = store.overrideSelector(selectUserSettings, initialState.userSettings);</code> ,
and the test</p>
<pre><code>    describe('OverdueTableComponent', () =&gt; {
  let component: OverdueTableComponent;
  let fixture: ComponentFixture&lt;OverdueTableComponent&gt;;
  let store: MockStore;
  const initialState: SettingsState = new SettingsInitialState();
  let mockUserSettingsSelector: MemoizedSelector&lt;SettingsState, UserSettingsState&gt;;

  beforeEach(
    waitForAsync(() =&gt; {
      TestBed.configureTestingModule({
        declarations: [OverdueTableComponent, OverdueEventTypeTranslationComponent],
        imports: [SimplebarAngularModule, StoreModule.forRoot({}), StoreModule.forFeature('settings', settingsReducer)],
        providers: [OverdueTableComponent, OverdueEventTypeTranslationComponent, provideMockStore({ initialState })],
      }).compileComponents();
    })
  );

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(OverdueTableComponent);
    component = fixture.componentInstance;
    store = TestBed.inject(MockStore);
    mockUserSettingsSelector = store.overrideSelector(selectUserSettings, initialState.userSettings);
    fixture.detectChanges();
  });

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

  it('format should not be null', () =&gt; {
    mockUserSettingsSelector.setResult({
      errors: undefined,
      isLoading: false,
      localizationProfile: {
        currency: 'dummy-currency',
        currencySymbol: 'dummy-currency-symbol',
        dateFormat: 'dd/MM/yyyy',
        language: 'English (British)',
        timezone: 'dummy-timezone',
      },
      successfullyUpdated: false,
    });
    store.refreshState();
    fixture.detectChanges();
    component.ngOnInit();
    expect(component.format).not.toBe(null);
  });
});
</code></pre>
<p>but without any result.</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/65597041/ngrx-store-selector-unit-testing,"['angular', 'unit-testing', 'selector', 'ngrx', 'store']",983,True,0,1
Hyperledger fabric 2.3 unit testing,"<p>I'm new to hyperledger fabric and I'm trying to write unit tests for my chaincode. Im using version 2.3 with the contract.api for writing my chaincode. Now i try to unit test this but all the resources i find are outdated and use the deprecated shimtest or deprecated shim versions.</p>
<p>What is the correct  up to date method of unit testing chaincode? Is there a example or tutorial i can follow? I did take a look at the hyperledger fabric examples. They refer to a ChaincodeStubInterface, but there is no further explanation on how to use this. I also noticed that many (recent) examples have a mock folder with generated files in it, that they use for their tests. But how these get generated, I have no clue.</p>
<p>Help is much appreciated!</p>
",https://stackoverflow.com/questions/67485816/hyperledger-fabric-2-3-unit-testing,"['unit-testing', 'hyperledger-fabric', 'chaincode']",300,False,0,1
Running Unit testing in Django,"<p>I'm running a unit test in Django but keep getting an error</p>
<pre><code>File &quot;C:\****\views.py&quot;, line 21, in post 
 s = str(points['string_points']) 
KeyError: 'string_points'
</code></pre>
<p><strong>Command Used:</strong></p>
<pre><code>python manage.py test
</code></pre>
<p>The structure of my test code looks as follows:</p>
<pre><code>class TestSetUp(APITestCase):
    
    def setUp(self):
        self.getClosestDistance_url = reverse('getClosestDistance')
        self.calculateClosestDistance_url = reverse('calcClosestDistance')
        
        points = {
            &quot;string_points&quot;: &quot;(2,3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)&quot;
        }
        return super().setUp()
    
    def tearDown(self):
        return super().tearDown()

class TestViews(TestSetUp):

    def test_getClosestPoints_with_no_data(self):
        res = self.client.post(self.calculateClosestDistance_url)
        import pdb # python debugger
        pdb.set_trace()
        self.assertEqual(res.status_code, 400)
</code></pre>
<p>Structure of my <strong>views.py</strong> file is as follows:</p>
<pre><code>class closestDistanceValue(APIView):

    def get(self, request): 
        points = Points.objects.all()
        serializer = PointsSerializer(points, many=True)  

        return Response(serializer.data)

    def post(self, request, format=None):
        points=request.data # user input
        s = str(points['string_points']) 
        closestPoint = getClosestDistance(s) 
        data = {
            'point': s,
            'closestPoint': closestPoint
        } 
        
        serializer = PointsSerializer(data=data) 
        if serializer.is_valid(): 
            serializer.save() 
            return Response(serializer.data, status=status.HTTP_200_OK) 
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) 
</code></pre>
<p>JSON Body for <strong>POST</strong> request. Keyed in as user input</p>
<pre><code>{
    &quot;string_points&quot;: &quot;(2,3), (12, 30), (40, 50), (5, 1), (12, 10), (3, 4)&quot;
}
</code></pre>
<p>What I'm I missing?</p>
",https://stackoverflow.com/questions/68679746/running-unit-testing-in-django,"['python', 'django', 'unit-testing']",34,True,0,1
Unit testing Hapi Server Methods,"<p>I have an app that's making heavy use of Hapi's <a href=""https://hapi.dev/tutorials/servermethods/?lang=en_US"" rel=""nofollow noreferrer"">Server Methods</a>. The methods are being applied via an exported <code>register</code> function, and the code that's being executed for the method is in the same file and thus not exported. I'm trying to write tests for these methods without exporting the functions that they call in the simplest possible way, but I haven't found any examples of how to do so.</p>
<pre><code>export function register(server) {
  server.method(
    'methodNameA',
    async (path, {}) =&gt; {
      // Some code here
      return something; // I want to test this result
    },
    {
      cache: methodCache.halfDay,
      generateKey(path, { ... } = {}) {
        return something;
      },
    }
  );
};
</code></pre>
<p>Abstracting that logic is an option, but I'd rather not expose it just for a test. I'd also prefer to not test an entire route just to validate this bit of logic (though that may be the ultimate solution here).</p>
",https://stackoverflow.com/questions/67093784/unit-testing-hapi-server-methods,"['javascript', 'unit-testing', 'hapi']",421,True,0,1
Unit testing for React JS,"<p>I have a component of buttons..</p>
<pre><code>export default class ButtonAction extends Component {

  render() {

    const { id, disabled, onClose, onSave, onRemove, isDelete } = this.props;

    return (

      &lt;div className=&quot;footer&quot;&gt;
        &lt;div className=&quot;button-container&quot;&gt;
          &lt;button data-testid=&quot;cancel&quot; onClick={() =&gt; onClose()}&gt; Cancel &lt;/button&gt;
          {
            isDelete
              ? &lt;button data-testid=&quot;remove&quot; disabled={!disabled} onClick={() =&gt; onRemove()} className='primary'&gt; Yes &lt;/button&gt;
              : &lt;button data-testid=&quot;save&quot; disabled={!disabled} onClick={() =&gt; onSave()} className={disabled ? 'primary' : 'disabled'}&gt; { id ? 'Update' : 'Save' } &lt;/button&gt;
          }
        &lt;/div&gt;
      &lt;/div&gt;
    )
  }
}
</code></pre>
<p>This is how I have made components. I am trying to do unit testing but test case does not pass..</p>
<pre><code>test(&quot;id exists&quot;, () =&gt; {
  const { getByTestId } = render(&lt;ButtonAction id={''} isDelete={false} /&gt;);
  expect(getByTestId('cancel')).toBeTruthy();
});

test(&quot;delete button exists&quot;, () =&gt; {
  const { getByTestId } = render(&lt;ButtonAction id={'remove'} isDelete={true} /&gt;);

  expect(getByTestId('cancel').textContent).toBe(' Yes ')
});

test('save button exists', () =&gt; {
  const { getByTestId } = render(&lt;ButtonAction id={''} isDelete={false} /&gt;)

  expect(getByTestId('save').textContent).toBe(' Save ')
})

test('calling render with the same component on the same container does not remount', () =&gt; {
  const { getByTestId } = render(&lt;ButtonAction id={'1'} isDelete={false} /&gt;)

  expect(getByTestId('save').textContent).toBe(' Update ')
})
</code></pre>
<p>This my unit test case.. None of my test case pass.. i HAVE REFERED MY other sources but couldn't help. I am new to react.. please help me to resolve this..</p>
<pre><code>The error below may be caused by using the wrong test environment, see jestjs.io/docs/configuration#testenvironment-string. Consider using the &quot;jsdom&quot; test environment. ReferenceError: document is not defined
</code></pre>
<p>This is the error I am getting</p>
",https://stackoverflow.com/questions/68888477/unit-testing-for-react-js,"['javascript', 'reactjs', 'unit-testing', 'react-testing-library']",297,True,0,1
Dependency Formik form Unit testing,"<p>I want to write the unit test for React formik form fields.</p>
<p>Related packages versions are bellow</p>
<p><strong>React version</strong> <code>^16.9.0</code></p>
<p><strong>Formik version</strong> <code>^1.5.8</code></p>
<p><strong>Jest version</strong> <code>^23.0.0</code></p>
<p><strong>jest-enzyme version</strong> <code>^7.1.2</code></p>
<p><strong>Enzyme version</strong> <code>^3.11.0</code></p>
<p><em>Component.js</em></p>
<pre><code>const formInitialValues = {
  frequency: null,
  weekType: null'
};

&lt;Formik
  enableReinitialize
  initialValues={formInitialValues}
  onSubmit={(values, actions) =&gt; {
    console.log(values);
  }}
  validate={values =&gt; {
    // validation here
  }}
  render={props =&gt; (
    &lt;Form
       onSubmit={props.handleSubmit}
       data-test=&quot;smart-cabinet-add-doc-form&quot;
    &gt;
      &lt;Row&gt;
        &lt;div className=&quot;form-group col-md-6 &quot;&gt;
          &lt;label htmlFor=&quot;frequency&quot; data-test=&quot;frequency-label&quot;&gt;
            Frequency
          &lt;/label&gt;

          &lt;CustomSelect
            id=&quot;frequency&quot;
            name=&quot;frequency&quot;
            className=&quot;form-control col-sm-10&quot;
            options={SmartCabinetHelper.ADD_DOCUMENT_FREQUENCY_OPTIONS}
            onChange={(name, value) =&gt; {
              setFieldValue(name, value);
              formatDueDate(values);
            }}
            onBlur={setFieldTouched}
            placeholder=&quot;Select Frequency&quot;
            setFieldValue={setFieldValue}
            value={values.frequency}
            isDisabled={isNull(values.uploadedBy)}
            data-test=&quot;frequency-field&quot;
          /&gt;
          &lt;div className=&quot;error-message&quot;&gt;
            &lt;ErrorMessage name=&quot;frequency&quot; /&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/Row&gt;

      {!isNull(values.frequency) &amp;&amp; (
        &lt;Row&gt;
          &lt;div className=&quot;form-group col-md-12 &quot;&gt;
            &lt;CustomSelect
              id=&quot;weekType&quot;
              name=&quot;weekType&quot;
              className=&quot;form-control&quot;
              options={QuickLinkModalHelper.WEEKS_TYPES.slice(0, -1)}
              onChange={(name, value) =&gt; {
                setFieldValue(name, value);
                formatDueDate(values);
              }}
              onBlur={setFieldTouched}
              isSearchable={false}
              placeholder=&quot;&quot;
              setFieldValue={setFieldValue}
              value={values.weekType}
              data-test=&quot;weekType-field&quot;
            /&gt;
          &lt;/div&gt;
        &lt;/Row&gt;
      )}
    &lt;/form&gt;
  )}
/&gt;
</code></pre>
<p>In the <em>componentTest.js</em> file I can test the <code>frequency</code> element, but I can't test the <code>weekType</code> element because that element depends on the <code>frequency</code> value.
<code>{!isNull(values.frequency) &amp;&amp; (</code></p>
<p>When the unit test runs, according to the <code>formInitialValues</code>, of formik form <code>frequency</code> value is <code>Null</code>. So I can't check <code>weekType</code>, It occurs an error. Test fails.</p>
<p><em>ComponentTest.js</em></p>
<pre><code>const setup = () =&gt; {
  return mount(
    &lt;Component /&gt;
  );
};

describe('Test form elements', () =&gt; {
  let wrapper;

  beforeEach(() =&gt; {
    wrapper = setup(defaultProps);
  });

  test('test frequency field', () =&gt; {
    const frequencyField = findByTestAttr(
      wrapper,
      'frequency-field'
    );

    expect(frequencyField.length).toBe(1); // This test passes
  });

  test('test weekType field', () =&gt; {
    const weekTypeField = findByTestAttr(
      wrapper,
      'weekType-field'
    );

    expect(weekTypeField.length).toBe(1); // This test fails, because frequency value = null
  });
});
</code></pre>
<p>I tried too many ways to figure that. But couldn't. Is there any way to change <code>formInitialValues</code> in the testing file? Thank you.</p>
",https://stackoverflow.com/questions/66366945/dependency-formik-form-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'formik']",388,True,0,1
StencilJS unit testing keyboard event?,"<p>I want to write unit tests for my custom web-components in stencilJs but have no idea how to do it the right way. Here's what I did so far!</p>
<p>.tsx</p>
<pre><code>...

  valueFormat(event: Event): void {
    const val = (event.target as HTMLInputElement).value;
    const format = Number.parseInt(val, 10);
    const newVal = format.toLocaleString(undefined, {
      minimumFractionDigits: 2,
    });
    this.value = newVal;
  }
</code></pre>
<p>.spec.tsx</p>
<pre><code>it('should format value', async () =&gt; {
    const comp = new MyComponent();
    const spy = jest.spyOn(comp, 'valueFormat');

    comp.myInputEvent.emit();

    expect(spy).toHaveBeenCalled();
  });

</code></pre>
<p>I want to test the case, when I type a number in the input field that it format it. So my valueFormat() method, I spying on should be called when a Keyboard event is firing. I hope you can help me out!</p>
",https://stackoverflow.com/questions/70007313/stenciljs-unit-testing-keyboard-event,"['reactjs', 'jestjs', 'event-handling', 'stenciljs']",567,False,0,1
Unit testing angular mat-form,"<p>I am new at Angular Testing.</p>
<p>I want to test all the scenarios with a form (valid form, required form, etc)</p>
<p>That's my html:</p>
<pre><code>&lt;div class=&quot;content&quot; *ngIf=&quot;!recordsFound&quot;&gt;
  &lt;div class=&quot;alert&quot;&gt;
    &lt;span&gt;OOOPS! No recordings found. You can add a new one:&lt;/span&gt;
  &lt;/div&gt;
  &lt;form [formGroup]=&quot;recordingForm&quot; #formDirective=&quot;ngForm&quot; id=&quot;recordingForm&quot;&gt;
    &lt;div&gt;
      &lt;div&gt;
        &lt;mat-form-field&gt;
          &lt;mat-label&gt;Artist*&lt;/mat-label&gt;
          &lt;input matInput placeholder=&quot;Artist&quot; formControlName=&quot;artist&quot; /&gt;
          &lt;mat-error&gt;Required input&lt;/mat-error&gt;
        &lt;/mat-form-field&gt;
      &lt;/div&gt;
      &lt;div&gt;
        &lt;mat-form-field&gt;
          &lt;mat-label&gt;Title*&lt;/mat-label&gt;
          &lt;input matInput placeholder=&quot;Title&quot; formControlName=&quot;title&quot; /&gt;
          &lt;mat-error&gt;Required input&lt;/mat-error&gt;
        &lt;/mat-form-field&gt;
      &lt;/div&gt;
      &lt;div&gt;
        &lt;mat-form-field&gt;
          &lt;mat-label&gt;ISRC&lt;/mat-label&gt;
          &lt;input matInput placeholder=&quot;ISRC&quot; formControlName=&quot;isrc&quot; /&gt;
        &lt;/mat-form-field&gt;
      &lt;/div&gt;
      &lt;div&gt;
        &lt;mat-form-field&gt;
          &lt;mat-label&gt;Duration&lt;/mat-label&gt;
          &lt;input matInput placeholder=&quot;Duration&quot; formControlName=&quot;duration&quot; /&gt;
        &lt;/mat-form-field&gt;
      &lt;/div&gt;
      &lt;button mat-stroked-button color=&quot;primary&quot; (click)=&quot;save()&quot; [disabled]=&quot;!recordingForm.valid&quot;&gt;
        Add recording &lt;mat-icon&gt;music_note&lt;/mat-icon&gt;
      &lt;/button&gt;
    &lt;/div&gt;
  &lt;/form&gt;
&lt;/div&gt;
</code></pre>
<p>Example, test check if form is valid and fields required are not empty:</p>
<pre><code>  it ('check if form is valid and required fields not empty',() =&gt;{
    const fixture = TestBed.createComponent(AddRecordingComponent);
    const formArtistElement: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#recordingForm').querySelectorAll('input')[0];
    const formTitleElement: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#recordingForm').querySelectorAll('input')[1];
    formArtistElement.value='Rihanna';
    formTitleElement.value='Umbrella';
    formArtistElement.dispatchEvent(new Event('input'));
    formTitleElement.dispatchEvent(new Event('input'));
    const isFormValid = fixture.componentInstance.recordingForm.valid;
    
    fixture.whenStable().then(() =&gt; {
      expect(isFormValid).toBeTruthy();
    })
  
  });
</code></pre>
<p>I am getting this error: <code>TypeError: Cannot read property 'querySelectorAll' of null</code>
How I can access to the form through the spec file?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/68497629/unit-testing-angular-mat-form,"['angular', 'unit-testing', 'testing', 'karma-jasmine']",1322,True,0,1
Unit testing lists with CollectionAssert.AreEquivalent(),"<p>First, I would like to let you know that this is part of a homework exercise over Unit Testing.</p>
<p>What I need the test to do: I need to test that the list &quot;actual&quot; is equivalent to the list &quot;expected&quot;.</p>
<p>This test fails and I receive this message:</p>
<p><em>CreatePurchasableList_IncludesExpectedItems
Source: GrandTotal.UnitTests.cs line 13
Duration: 30 ms
Message:
CollectionAssert.AreEquivalent failed. The expected collection contains 1 occurrence(s) of &lt;GrandTotal_exercise.Appointment&gt;. The actual collection contains 0 occurrence(s).
Stack Trace:
ProgramTests.CreatePurchasableList_IncludesExpectedItems() line 51</em></p>
<p><strong>The method we want to test...</strong></p>
<pre class=""lang-cs prettyprint-override""><code>public static List&lt;IPurchasable&gt; CreatePurchasableList()
{
    var appointment = new Appointment()
    {
        Name = &quot;James&quot;,
        StartDateTime = DateTime.Now.AddHours(1),
        EndDateTime = DateTime.Now.AddHours(2),
        Price = 100D
    };
    var book = new Book()
    {
        Title = &quot;Welcome to Advanced C#&quot;,
        Price = 50D,
        TaxRate = 0.0825D,
        ShippingRate = 5D
     };
     var snack = new Snack()
     {
         Price = 2D
     };
     var tshirt = new TShirt()
     {
         Size = &quot;2X&quot;,
         Price = 25D,
         TaxRate = 0.0625D,
         ShippingRate = 2
     };

     var items = new List&lt;IPurchasable&gt;();
     items.Add(appointment);
     items.Add(book);
     items.Add(snack);
     items.Add(tshirt);

     return items;
}
</code></pre>
<p><strong>TestMethod...</strong></p>
<pre><code>[TestMethod]
public void CreatePurchasableList_IncludesExpectedItems()
{
    //Arrange
    var appointment = new Appointment()
    {
        Name = &quot;James&quot;,
        StartDateTime = DateTime.Now.AddHours(1),
        EndDateTime = DateTime.Now.AddHours(2),
        Price = 100D
    };
    var book = new Book()
    {
        Title = &quot;Welcome to Advanced C#&quot;,
        Price = 50D,
        TaxRate = 0.0825D,
        ShippingRate = 5D
    };
    var snack = new Snack()
    {
         Price = 2D
    };
    var tshirt = new TShirt()
    {
        Size = &quot;2X&quot;,
        Price = 25D,
        TaxRate = 0.0625D,
        ShippingRate = 2
    };
    var expectedList = new List&lt;IPurchasable&gt;();         
    var purchasableListActual = Program.CreatePurchasableList();
            
    //Act
    expectedList.Add(appointment);
    expectedList.Add(book);
    expectedList.Add(snack);
    expectedList.Add(tshirt);
    //Assert
    CollectionAssert.AreEquivalent(expectedList, purchasableListActual);
}
</code></pre>
<p>To be more clear I want to ensure that both tests include &quot;appointment&quot;, &quot;book&quot;, &quot;snack&quot;, and &quot;t-shirt&quot;.</p>
<p>I do not care what is inside of these objects or the order that they are in.</p>
",https://stackoverflow.com/questions/66198649/unit-testing-lists-with-collectionassert-areequivalent,"['c#', 'unit-testing', 'mstest']",156,False,0,0
Quasar unit testing for vue3,"<p>I am using quasar for developing a vue app. I am using vue 3.0.7. I have installed jest and created the jest.config File.</p>
<p>The jest config file contains the following:</p>
<pre><code>clearMocks: true,

  moduleFileExtensions: [
    &quot;js&quot;,
    &quot;jsx&quot;,
    &quot;ts&quot;,
    &quot;vue&quot;
  ],
 
  testMatch: [
    &quot;**/__tests__/**/*.[jt]s?(x)&quot;,
    &quot;**/?(*.)+(spec|test).[tj]s?(x)&quot;
  ],
  
  transform: {
    &quot;^.+\\.js$&quot;: &quot;babel-jest&quot;,
    &quot;.*\\.(vue)$&quot;: &quot;vue-jest&quot;
  },

  transformIgnorePatterns: [
    &quot;\\\\node_modules\\\\&quot;,
    &quot;\\.pnp\\.[^\\\\]+$&quot;
  ],
</code></pre>
<p>I am writing the following test for a demo vue component:</p>
<pre><code>import { shallowMount} from &quot;@vue/test-utils&quot;
import  ComponentVueTest from &quot;./ComponentVueTest&quot;

describe('ComponentVueTest', ()=&gt;{
    test(&quot;Text shoudl be in the html&quot; , () =&gt; {
        let wrapper = shallowMount(ComponentVueTest);
        expect(wrapper.html).toContain('JustTesting');
    })
})
</code></pre>
<p>The component that is being tested:</p>
<pre><code>&lt;template&gt;
  JustTesting
&lt;/template&gt;

&lt;script&gt;
import { defineComponent } from '@vue/composition-api'

export default defineComponent({
    setup() {
        
    },
})
&lt;/script&gt;

&lt;style&gt;

&lt;/style&gt;
</code></pre>
<p>and also the package.json dependencies:</p>
<pre><code> &quot;dependencies&quot;: {
    &quot;@quasar/extras&quot;: &quot;^1.0.0&quot;,
    &quot;@typescript-eslint/eslint-plugin&quot;: &quot;^4.29.1&quot;,
    &quot;@typescript-eslint/parser&quot;: &quot;^4.29.1&quot;,
    &quot;@vue/composition-api&quot;: &quot;^1.0.6&quot;,
    &quot;cordova&quot;: &quot;^10.0.0&quot;,
    &quot;core-js&quot;: &quot;^3.6.5&quot;,
    &quot;quasar&quot;: &quot;^2.0.0&quot;,
    &quot;vue&quot;: &quot;^2.6.14&quot;,
    &quot;vue-loader&quot;: &quot;^16.5.0&quot;,
    &quot;vue-template-compiler&quot;: &quot;^2.6.14&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;^7.15.0&quot;,
    &quot;@babel/eslint-parser&quot;: &quot;^7.13.14&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.15.0&quot;,
    &quot;@quasar/app&quot;: &quot;^3.0.0&quot;,
    &quot;@quasar/quasar-app-extension-testing&quot;: &quot;^1.0.3&quot;,
    &quot;@quasar/quasar-app-extension-testing-unit-jest&quot;: &quot;^2.2.2&quot;,
    &quot;@vue/test-utils&quot;: &quot;^2.0.0-rc.12&quot;,
    &quot;babel-core&quot;: &quot;^7.0.0-bridge.0&quot;,
    &quot;babel-jest&quot;: &quot;^27.0.6&quot;,
    &quot;eslint&quot;: &quot;^7.32.0&quot;,
    &quot;eslint-config-prettier&quot;: &quot;^8.1.0&quot;,
    &quot;eslint-plugin-jest&quot;: &quot;^24.1.0&quot;,
    &quot;eslint-plugin-vue&quot;: &quot;^7.0.0&quot;,
    &quot;eslint-webpack-plugin&quot;: &quot;^2.4.0&quot;,
    &quot;jest&quot;: &quot;^27.0.6&quot;,
    &quot;vue-jest&quot;: &quot;^3.0.7&quot;
  },
</code></pre>
<p>When i run  the npm run test (&quot;test&quot;: &quot;npx jest&quot;) i get the following error:</p>
<pre><code>FAIL  src/__tests__/Demo.spec.js
  ● Test suite failed to run

    TypeError: Vue.defineComponent is not a function

    &gt; 1 | import { shallowMount} from &quot;@vue/test-utils&quot;
        | ^
      2 | import  ComponentVueTest from &quot;./ComponentVueTest&quot;
      3 |
      4 | describe('ComponentVueTest', ()=&gt;{

      at Object.&lt;anonymous&gt; (node_modules/@vue/test-utils/dist/vue-test-utils.cjs.js:7856:26)
      at Object.&lt;anonymous&gt; (src/__tests__/Demo.spec.js:1:1)
</code></pre>
<p>I have been trying for hours to fix it and can't seem to understand what is wrong</p>
",https://stackoverflow.com/questions/68863144/quasar-unit-testing-for-vue3,"['vue.js', 'testing', 'jestjs', 'quasar']",1592,False,0,2
react js jest unit testing,"<p>Inside the <code>Login</code> functional component I have a function <code>validateForm</code> which checks that <code>username</code> and <code>password</code> lengths are greater than zero.</p>
<pre><code>function validateForm() {
  return username.length &gt; 0 &amp;&amp; password.length &gt; 0;
}
</code></pre>
<p>I use Jest as unit testing tool.</p>
<pre><code>import React from &quot;react&quot;;
import Login, { validateForm } from &quot;./Login&quot;;
import { render, screen } from &quot;@testing-library/react&quot;;

describe(&quot;LoginUser&quot;, () =&gt; {
  test(&quot;validate username and password should be greater than 0&quot;, () =&gt; {
    var username = &quot;name&quot;;
    var password = &quot;pass&quot;;
    expect(validateForm(username.length)).toBeGreaterThan(0);
  });
});
</code></pre>
<pre class=""lang-none prettyprint-override""><code>TypeError: (0 , _Login.validateForm) is not a function
</code></pre>
<p>I'm facing the above error while running the test case. How to solve this error?</p>
",https://stackoverflow.com/questions/70163320/react-js-jest-unit-testing,"['reactjs', 'react-hooks', 'jestjs', 'ts-jest']",316,False,0,1
unit testing using jasmine marbles,"<p>I am trying to do a simple test using <code>jasmine-marbles</code> but getting errors</p>
<p>This is my test code:</p>
<pre><code>describe('MarbleTestingComponent', () =&gt; {
  it('should test marble syntax', () =&gt; {
    const provided = search('e');
    const expected = cold('(e|)', {e: 'e'});
    console.log(expected, provided);
    expect(provided).toBeObservable(expected);
  })   

});
</code></pre>
<p>and this is the error I am getting:</p>
<pre><code>Error: 
            Expected: (e|),
            Received: (?|),
            
            Expected:
            [{&quot;frame&quot;:0,&quot;notification&quot;:{&quot;kind&quot;:&quot;N&quot;,&quot;value&quot;:&quot;e&quot;,&quot;hasValue&quot;:true}},{&quot;frame&quot;:0,&quot;notification&quot;:{&quot;kind&quot;:&quot;C&quot;,&quot;hasValue&quot;:false}}]
            
            Received:
            [{&quot;frame&quot;:0,&quot;notification&quot;:{&quot;kind&quot;:&quot;N&quot;,&quot;value&quot;:&quot;e&quot;}},{&quot;frame&quot;:0,&quot;notification&quot;:{&quot;kind&quot;:&quot;C&quot;}}],
</code></pre>
<p>if I use the <code>jest</code> framework, the above code works, but I want to get it working withe default test framework that comes with Angular setup</p>
<p>Any help to sort this error is appreciated
Thanks</p>
",https://stackoverflow.com/questions/68222027/unit-testing-using-jasmine-marbles,"['angular', 'rxjs', 'jasmine-marbles']",1259,True,0,2
Unit testing Ngrx select angular,"<p>I have something like this</p>
<pre><code>  ngOnInit(): void {
    this.store.select('loggedUser').pipe(take(1))
      .subscribe(user =&gt; {
        this.loggedUser = user;
      });
  }

  it('should init well', () =&gt; {
    // GIVEN
    const store = spyOn(component.store, 'select').and.callThrough();
    // WHEN
    component.ngOnInit();
    // THEN
    expect(store).toHaveBeenCalledTimes(1);
    expect(component.loggedUser).toBe(initialState.loggedUser);
  });
</code></pre>
<p>Sorry I dont have some example, but I dont know how even to start unit test this, thanks</p>
",https://stackoverflow.com/questions/68879569/unit-testing-ngrx-select-angular,"['typescript', 'jasmine', 'ngrx', 'angular-ngrx-data']",169,False,0,1
Unit testing a snake game,"<p>I need help with a test method to see if the snake is/or isn't moving in the right direction, aka &quot;==/!=&quot;.
I also need to check if the snake has food on the console or not.</p>
<p>I've tried to call the &quot;starter class&quot; that I have almost all the code in. But I can't try to predict where it will go correctly and assert from there.</p>
<p>How should I go about doing so?  [Only need tips!]</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Snake
{
    /// &lt;summary&gt;
    /// Start class, everything goes from here.
    /// &lt;/summary&gt;
   public class Starter : InterF
    { 
        public static object Key { get; private set; }

        static void Main(string[] args)
        {
            
            Console.ForegroundColor = ConsoleColor.Green;
            bool loopC = true;
            while (loopC)
            {
                string mystring = null; Console.WriteLine(&quot;Welcome to Snake.\nPress S+Enter to start or press Q+Enter to exit.&quot;);
                mystring = Console.ReadLine();
                switch (mystring)
                {
                    case &quot;Q&quot;:
                        Environment.Exit(0);
                        break;
                    case &quot;S&quot;:
                        Console.WriteLine(&quot;Starting game!&quot;);
                        System.Threading.Thread.Sleep(4000);
                        loopC = false;
                        break;
                    default:
                        Console.WriteLine(&quot;Invalid Entry.. Try again.&quot;);
                        break;
                }

            }

            //Call for GameSense if
            //they want to play.
            GameSense(); 

        }


      
        /// &lt;summary&gt;
        /// Game object!
        /// &lt;/summary&gt;
        public static void GameSense()

        {
            //Game console height/width.
            Console.WindowHeight = 30;
            Console.WindowWidth = 70;
            int screenwidth = Console.WindowWidth;
            int screenheight = Console.WindowHeight;
            Random randomnummer = new Random();
            //Lenght of tail == current score.
            int score = 2;
            int gameover = 0;
            //Gather positions from pixel class.
            pixel positions = new pixel();
            positions.xpos = screenwidth / 2;
            positions.ypos = screenheight / 2;
            positions.Black = ConsoleColor.Red;
            string movement = &quot;RIGHT&quot;;
            //Position manegment.
            List&lt;int&gt; xpos = new List&lt;int&gt;();
            List&lt;int&gt; ypos = new List&lt;int&gt;();
            int berryx = randomnummer.Next(0, screenwidth);
            int berryy = randomnummer.Next(0, screenheight);
            //Time manegment.
            DateTime time1 = DateTime.Now;
            DateTime time2 = DateTime.Now;
            string buttonpressed = &quot;no&quot;;

            
            //Draw world from GameWorld.cs.
            GameWorld.DrawBorder(screenwidth, screenheight);

            while (true)
            {
                GameWorld.ClearConsole(screenwidth, screenheight);
                if (positions.xpos == screenwidth - 1 || positions.xpos == 0 || positions.ypos == screenheight - 1 || positions.ypos == 0)
                {
                    gameover = 1;
                }

                Console.ForegroundColor = ConsoleColor.Green;
                if (berryx == positions.xpos &amp;&amp; berryy == positions.ypos)
                {
                    score++;
                    berryx = randomnummer.Next(1, screenwidth - 2);
                    berryy = randomnummer.Next(1, screenheight - 2);
                }
                for (int i = 0; i &lt; xpos.Count(); i++)
                {
                    Console.SetCursorPosition(xpos[i], ypos[i]);
                    Console.Write(&quot;*&quot;);
                    if (xpos[i] == positions.xpos &amp;&amp; ypos[i] == positions.ypos)
                    {
                        gameover = 1;
                    }
                }
                if (gameover == 1)
                {
                    break;
                }
                Console.SetCursorPosition(positions.xpos, positions.ypos);
                Console.ForegroundColor = positions.Black;
                Console.Write(&quot;*&quot;);
                //Food color &amp; position.
                Console.SetCursorPosition(berryx, berryy);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.Write(&quot;*&quot;);
                Console.CursorVisible = false;
                time1 = DateTime.Now;
                buttonpressed = &quot;no&quot;;
                while (true)
                {
                    time2 = DateTime.Now;
                    if (time2.Subtract(time1).TotalMilliseconds &gt; 500) { break; }
                    if (Console.KeyAvailable)
                    {
                        ConsoleKeyInfo info = Console.ReadKey(true);
                        
                        if (info.Key.Equals(ConsoleKey.UpArrow) &amp;&amp; movement != &quot;DOWN&quot; &amp;&amp; buttonpressed == &quot;no&quot;)
                        {
                            movement = &quot;UP&quot;;
                            buttonpressed = &quot;yes&quot;;
                        }
                        if (info.Key.Equals(ConsoleKey.DownArrow) &amp;&amp; movement != &quot;UP&quot; &amp;&amp; buttonpressed == &quot;no&quot;)
                        {
                            movement = &quot;DOWN&quot;;
                            buttonpressed = &quot;yes&quot;;
                        }
                        if (info.Key.Equals(ConsoleKey.LeftArrow) &amp;&amp; movement != &quot;RIGHT&quot; &amp;&amp; buttonpressed == &quot;no&quot;)
                        {
                            movement = &quot;LEFT&quot;;
                            buttonpressed = &quot;yes&quot;;
                        }
                        if (info.Key.Equals(ConsoleKey.RightArrow) &amp;&amp; movement != &quot;LEFT&quot; &amp;&amp; buttonpressed == &quot;no&quot;)
                        {
                            movement = &quot;RIGHT&quot;;
                            buttonpressed = &quot;yes&quot;;
                        }
                    }
                }
                xpos.Add(positions.xpos);
                ypos.Add(positions.ypos);
                switch (movement)
                {
                    case &quot;UP&quot;:
                        positions.ypos--;
                        break;
                    case &quot;DOWN&quot;:
                        positions.ypos++;
                        break;
                    case &quot;LEFT&quot;:
                        positions.xpos--;
                        break;
                    case &quot;RIGHT&quot;:
                        positions.xpos++;
                        break;
                }
                if (xpos.Count() &gt; score)
                {
                    xpos.RemoveAt(0);
                    ypos.RemoveAt(0);
                }
            }
            Console.SetCursorPosition(screenwidth / 5, screenheight / 2);
            Console.WriteLine(&quot;Game over, Score: &quot; + score);
            Console.SetCursorPosition(screenwidth / 5, screenheight / 2 + 1);
            System.Threading.Thread.Sleep(1000);
            restart();
            
        }

        /// &lt;summary&gt;
        /// Restarter.
        /// &lt;/summary&gt;
        public static void restart()
        {
        
            string Over = null; Console.WriteLine(&quot;\nWould you like to start over? Y/N&quot;);
            bool O = true;

            while (O)
            {
                Over = Console.ReadLine();
                switch (Over)
                {
                    case &quot;Y&quot;:
                        Console.WriteLine(&quot;\nRestarting!&quot;);
                        System.Threading.Thread.Sleep(2000);
                        break;
                    case &quot;N&quot;:
                        Console.WriteLine(&quot;\nThank you for playing!&quot;);
                        Environment.Exit(0);
                        break;
                    default:
                        Console.WriteLine(&quot;Invalid Entry.. Try again.&quot;);
                        break;
                }
            }

        }
        /// &lt;summary&gt;
        /// Set/get pixel position.
        /// &lt;/summary&gt;
        class pixel
        {
            public int xpos { get; set; }
            public int ypos { get; set; }
            public ConsoleColor Black { get; set; }
        }
    }
}
</code></pre>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using NUnit.Framework;
using Snake;
using System;
using System.Collections.Generic;
using System.Text;

namespace Snake.Tests
{
    [TestClass()]
    public class StarterTests
    {
        [TestMethod()]
        public void test()
        {
            
        }


    }
}
</code></pre>
",https://stackoverflow.com/questions/66364165/unit-testing-a-snake-game,"['c#', 'unit-testing']",728,True,0,1
Angular unit testing a function variable,"<p>I want to test a variable function of a void function. How can I get that local variable in the test?
function:</p>
<pre><code>save(){
const stringTest=&quot;test&quot;;
}
</code></pre>
<p>test:</p>
<pre><code>test(&quot;variable should be equal to &quot;test&quot; &quot;, () =&gt; {
    component.save();
    //test stringTest from save function that is equal to &quot;test&quot;
  });
</code></pre>
",https://stackoverflow.com/questions/69223633/angular-unit-testing-a-function-variable,"['angular', 'typescript', 'unit-testing', 'testing']",3009,True,3,1
Unit testing with user inputs - Python,"<p>im trying to create a unit test to check a function that includes user input.
Im very new to unit testing and this is one seems a little complex for me. Basically the function takes coordinates of user input and places a &quot;ship&quot; of &quot;o&quot; in a 2d array of points.</p>
<p>example:</p>
<pre><code>[[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;O&quot;,&quot;O&quot;,&quot;O&quot;,&quot;.&quot;], [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]]
</code></pre>
<p>The test i wrote is not checking how the arrays match because id basically have to build another 2d array to check if my 2d array is built properly.... Is there a way to write this unit test to properly check the output?</p>
<p>What am i missing here?</p>
<p>Here is the code:</p>
<pre><code>def set_ship_coordinates():
        letterArray = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;]
        board = GameBoard().gameboard
        
        while True:
        
            while True:
                direction_input = input(&quot;Which direction? Horizontal 'H' or Vertical 'V': &quot;)
                upper_direction = direction_input.upper() #uppercase the input for the function check
                
                if upper_direction == &quot;H&quot; or upper_direction == &quot;V&quot;:
                    break
                else:
                    print(&quot;That is not a valid input, please enter H or V&quot;)
                    print(&quot; &quot;)
            
            while True: 
                row_input = input(&quot;Which row? (Between 1 and 8): &quot;)
                try:
                    int_row = int(row_input)
                    if int_row &gt;= 1 and int_row &lt;=8:
                        break
                    else:
                        print(&quot;That is not a valid input, please enter between 1 and 8&quot;)
                        print(&quot; &quot;)
                except ValueError:
                    print(&quot;This is not a valid response&quot;)
                    
            while True: 
                column_input = input(&quot;Which Column? (Between A and H): &quot;)
                upper_column = column_input.upper() #uppercase the input for loop check
                
                if upper_column in letterArray:
                    column_choice = letterArray.index(upper_column)
                    break
                else:
                    print(&quot;That is not a valid input, please enter letter between A and H&quot;)
                    print(&quot; &quot;)
            
            dir = upper_direction
            row = int_row - 1 #remove one here to account for 0 in list 
            column = column_choice #this is already an index value and does not need to -1
            
            if dir == &quot;H&quot;:
                #if horizontal, column cannot be 0 or 7 at center or ship is out of bounds
                if column != 0 and column != 7:
                    #center of ship
                    board[row][column] = &quot;O&quot;
                    #front and back of ship
                    board[row][column - 1] = &quot;O&quot;
                    board[row][column + 1] = &quot;O&quot;
                    return board
                else: 
                    print(&quot;Can't place ship here, try again&quot;)
            elif dir == &quot;V&quot;:
                #if vertical, row cannot be 0 or 7 at center or ship is out of bounds
                if row != 0 and row != 7:
                    #center of ship
                    board[row][column] = &quot;O&quot;
                    #front and back of ship
                    board[row - 1][column] = &quot;O&quot;
                    board[row + 1][column] = &quot;O&quot;
                    return board
                else: 
                    print(&quot;Can't place ship here, try again&quot;)
            else:
                print(&quot;Something went wrong&quot;)
</code></pre>
<p>Unit test:</p>
<pre><code>from unittest import mock
from unittest import TestCase
import unittest
from player import Player

class test_set_ship_coordinates(TestCase):
    @mock.patch(&quot;player.Player.set_ship_coordinates.input&quot;, create=True)
    def test_set_coordinates_correct(self, mocked_input):
        mocked_input.side_effect = [&quot;h&quot;, '2', 'c']
        result = Player.set_ship_coordinates()
        self.assertEqual(result, {'h', 1, 2})
        
if __name__ == &quot;__main__&quot;:
    unittest.main()
</code></pre>
",https://stackoverflow.com/questions/70431269/unit-testing-with-user-inputs-python,"['python', 'unit-testing']",171,False,3,0
Unit testing with Spring Session JDBC,"<p>I developed a Java servlet that allows 2-Factor authentication.
First, I set up an endpoint (Web/authenticate/credentials) that accepts user credentials, checks if they exist in the database, in which case it returns the corresponding user challenge in the response, and set the user account ID in the session attribute.</p>
<p>Then, when the user receives the challenge, they provide a secret and send a request to a different endpoint (Web/authenticate/secret), which first checks if the requests is associated with any session, and then retrieves the user account ID from the session attribute to complete the authentication.</p>
<p>All this works well, when testing with Postman, but when I write some unit tests with MockMvc, a new session is always created as I send the secret to the second endpoint (Web/authenticate/secret), even when I explicitly set the SESSION cookie header.</p>
<p>Below is a snippet of the unit test that fails:</p>
<pre><code>   MvcResult preAuthMvcResult = preAuthenticateUser(deviceAlias, userPin);//This calls the first endpoint

    // Get session cookie to send in next request header
    String sessionCookie = preAuthMvcResult.getResponse().getHeader(HttpHeaders.SET_COOKIE);


    JSONObject userCredentialsJson = new JSONObject();
    userCredentialsJson.put(&quot;secret&quot;, secret);

    // HTTP request
    HttpHeaders httpHeader = new HttpHeaders();
    httpHeader.add(&quot;x-api-key&quot;, apiKey);
    httpHeader.add(PRE_AUTH_HEADER, accountIdHash);
    httpHeader.add(HttpHeaders.COOKIE, sessionCookie);


    // Act
    MvcResult mvcResult = mockMvc
        .perform(post(&quot;/Web/authenticate/secret&quot;).contentType(MediaType.APPLICATION_JSON_VALUE)
            .headers(httpHeader).content(userCredentialsJson.toString()))
        .andReturn();

    // Assert
    int responseStatus = mvcResult.getResponse().getStatus();

// This fails the test because a new session is created, and the authication cannot proceed, as the server lost track of the authenticating user
    assertThat(responseStatus == HttpStatus.OK.value()).isTrue();
</code></pre>
",https://stackoverflow.com/questions/67351387/unit-testing-with-spring-session-jdbc,"['spring', 'unit-testing', 'session', 'jdbc', 'mockmvc']",149,False,2,0
unit testing an infinite polling method,"<p>I have a method that is started in a new task when the application starts up, and stops when it ends. The method performs some logic every half a second. I am so lost on how I should test it - any leads?</p>
<pre><code>public async Task StartPoll(CancellationToken token)
{
  while(!token.IsCancellationRequested)
  {
    try 
    {
       var dict = dependecy.getDictionary();
       var model = Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(dict));
       udpDistributer.Send(model, model.Length, _distributionEndPoint);
    }
    finally
    {
      await Task.Delay(500, Token);
    }
  }
}
</code></pre>
<p>where <code>udpDistributer</code> is a <code>new UdpClient(0)</code> that comes from DI and <code>_distributionEndPoint</code> is an <code>IPEndPoint</code></p>
<p>Basically I want to check that the logic works and that the right data is sent at  the proper interval. How can I do this using xunit?</p>
<p><strong>EDIT</strong></p>
<p>I have gotten as far as this:</p>
<pre><code>   // arrange
   ...
   cts = new CancellationTokenSource(timeout);

   //act
   await sut.StartPoll(cts.Token);

   // assert
   mockUdpDistributer.Verify(x =&gt; x.Send(expectedModel, expectedModel.length,
             It.IsAny&lt;IPEndPoint&gt;()), Times.Exactly(expectedTimes));
</code></pre>
<p>However, this causes the test to fail with a <code>TaskCanceledException</code></p>
",https://stackoverflow.com/questions/66241895/unit-testing-an-infinite-polling-method,"['c#', 'asynchronous', 'xunit']",792,True,2,4
Java HttpClient unit testing with Mockito,"<p>I am trying to create some unit tests for a service that I created in Java 11 using the <code>java.net.http.HttpClient</code> API.
The code works fine but I am getting <code>java.lang.reflect.InaccessibleObjectException</code> error when running the unit tests.</p>
<p>The Service class:</p>
<pre><code>@Stateless
public class MyWebService {

    @Inject
    private HttpClient httpClient;

    public void makeHttpCall(){

        final HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(&quot;https://someurl.com&quot;))
            .headers(CONTENT_TYPE, &quot;application/json&quot;)
            .GET()
            .build();

        final HttpResponse&lt;String&gt; response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

      // business logic
    }
}
</code></pre>
<p>The test class is as follows:</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class MyWebServiceTest {

    @InjectMocks
    private MyWebService service;

    @Mock
    private HttpClient httpClient;

    @Test
    public void shouldMakeHttpCallTest(){

        service.makeHttpCall();
        
        //asserts
    }
}
</code></pre>
<p>Am I doing something wrong? I've seen that many people instantiate a new instance of the httpClient within the method itself, however, I am not sure if it is testable that way.</p>
<p>What I was trying to achieve is something like</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class JdkHttpClientServiceShould {

@InjectMocks
private JdkHttpClientService victim;
@Mock
private HttpClient httpClient;

@Test
@SuppressWarnings({&quot;unchecked&quot;, &quot;rawtypes&quot;})
public void executeRequest() throws Exception {
    HttpResponse httpResponse = mock(HttpResponse.class);
    when(httpClient.send(any(HttpRequest.class), any(HttpResponse.BodyHandler.class))).thenReturn(httpResponse);
    when(httpResponse.statusCode()).thenReturn(200);
    when(httpResponse.body()).thenReturn(&quot;Hello&quot;);

    ArgumentCaptor&lt;HttpRequest&gt; httpRequestArgumentCaptor = ArgumentCaptor.forClass(HttpRequest.class);
    ArgumentCaptor&lt;HttpResponse.BodyHandler&lt;String&gt;&gt; bodyHandlerArgumentCaptor = ArgumentCaptor.forClass(HttpResponse.BodyHandler.class);

    ClientResponse clientResponse = victim.executeRequest(HTTP_URL);

    assertThat(clientResponse.getStatusCode()).isEqualTo(200);
    assertThat(clientResponse.getResponseBody()).isEqualTo(&quot;Hello&quot;);

    verify(httpClient, times(1)).send(httpRequestArgumentCaptor.capture(), bodyHandlerArgumentCaptor.capture());
    assertThat(httpRequestArgumentCaptor.getValue().uri().toString()).isEqualTo(HTTP_URL);
    assertThat(httpRequestArgumentCaptor.getValue().method()).isEqualTo(GET_METHOD);
    assertThat(httpRequestArgumentCaptor.getValue().headers().map()).containsExactly(Assertions.entry(HEADER_KEY_CLIENT_TYPE, Collections.singletonList(JDK_HTTP_CLIENT.getValue())));
    assertThat(bodyHandlerArgumentCaptor.getValue()).isEqualTo(HttpResponse.BodyHandlers.ofString());
}
</code></pre>
<p>}</p>
<p>Any help would be great. Thank you</p>
<p>The full stack trace is:</p>
<pre><code>java.lang.reflect.InaccessibleObjectException: Unable to make protected java.net.http.HttpClient() accessible: module java.net.http does not &quot;opens java.net.http&quot; to unnamed module @595b007d

    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:340)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:280)
    at java.base/java.lang.reflect.Constructor.checkCanSetAccessible(Constructor.java:189)
    at java.base/java.lang.reflect.Constructor.setAccessible(Constructor.java:182)
    at org.mockito.internal.creation.cglib.ClassImposterizer.setConstructorsAccessible(ClassImposterizer.java:86)
    at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:56)
    at org.mockito.internal.creation.cglib.ClassImposterizer.imposterise(ClassImposterizer.java:49)
    at org.mockito.internal.creation.cglib.CglibMockMaker.createMock(CglibMockMaker.java:24)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:33)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:59)
    at org.mockito.Mockito.mock(Mockito.java:1285)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:33)
    at org.mockito.internal.configuration.MockAnnotationProcessor.process(MockAnnotationProcessor.java:16)
    at org.mockito.internal.configuration.DefaultAnnotationEngine.createMockFor(DefaultAnnotationEngine.java:43)
    at org.mockito.internal.configuration.DefaultAnnotationEngine.process(DefaultAnnotationEngine.java:66)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.processIndependentAnnotations(InjectingAnnotationEngine.java:71)
    at org.mockito.internal.configuration.InjectingAnnotationEngine.process(InjectingAnnotationEngine.java:55)
    at org.mockito.MockitoAnnotations.initMocks(MockitoAnnotations.java:108)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl$1.withBefores(JUnit45AndHigherRunnerImpl.java:27)
    at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:319)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
    at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:221)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)

</code></pre>
",https://stackoverflow.com/questions/67487210/java-httpclient-unit-testing-with-mockito,"['java', 'mockito', 'java-11']",8237,True,2,2
Force_authenticate superuser django rest unit testing,"<p>I have structured my api so that only the superuser can delete accounts. I am trying to force authenticate a superuser in my unit test but I am running into issues.</p>
<p>Unit test:</p>
<pre><code>class PrivateUserApiTests(TestCase):
  &quot;&quot;&quot;Test the users API (private)&quot;&quot;&quot;

  def setUp(self):
    self.user = create_user(
      email='tes111t@test.com',
      password='test123',
      name='name',
    )
    self.user.is_superuser = True
    self.client = APIClient()
    self.client.force_authenticate(user=self.user)

  def test_user_successful_delete(self):
    &quot;&quot;&quot;Test that user was succesfully deleted&quot;&quot;&quot;
    payload = {'email': 'test@test123.com', 'password': 'test123'}
    user = create_user(**payload)
    res = self.client.delete(reverse('user:delete_user', kwargs={'pk': user.id}))

    self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)
</code></pre>
<p>ERROR:</p>
<pre><code>Traceback (most recent call last):
  File &quot;/app/user/tests/test_user_api.py&quot;, line 152, in test_user_successful_delete
    self.assertEqual(res.status_code, status.HTTP_204_NO_CONTENT)
AssertionError: 403 != 204
</code></pre>
<p>Am I using the <code>force_authenticate()</code> method wrong? How can I create a user that is a superuser</p>
",https://stackoverflow.com/questions/65754865/force-authenticate-superuser-django-rest-unit-testing,"['python', 'django', 'unit-testing', 'django-rest-framework']",1029,True,2,1
Reference version differences when Unit Testing,"<p>I have a project that uses a Nuget package that references some Solidworks dll's version 28.1.0.74. I have a newer version of Solidworks installed on this workstation. My project seems to run fine.</p>
<p>I am trying to use unit tests that tests certain classes in my project. My unit tests need to run Solidworks to get certain tests done. I am running into issues with versions. If I add a reference in my testing project to the installed version of Solidworks I get the following error when I run my unit tests:</p>
<blockquote>
<p>System.IO.FileNotFoundException: Could not load file or assembly
'SolidWorks.Interop.sldworks, Version=28.1.0.74, Culture=neutral,
PublicKeyToken=7c4797c3e4eeac03' or one of its dependencies. The
system cannot find the file specified.</p>
</blockquote>
<p>This is clearly looking for the older version of Solidworks.</p>
<p>If I remove the references to the installed version of Solidworks and add references to the version that comes with the NuGet package My project build OK but I get the following when I try to run the unit tests:</p>
<blockquote>
<p>Initialization method
TestEntityDB.SolidworksFeatureTreeTests.StartTestEnvironment threw
exception. System.Runtime.InteropServices.COMException: Retrieving the
COM class factory for component with CLSID
{D134B411-3689-497D-B2D7-A27CB1066648} failed due to the following
error: 80040154 Class not registered (Exception from HRESULT:
0x80040154 (REGDB_E_CLASSNOTREG))..</p>
</blockquote>
<p>What is the proper answer to this situation? Register the dll's manually? Would doing so screw up any other installations I may have?</p>
",https://stackoverflow.com/questions/69713115/reference-version-differences-when-unit-testing,"['c#', 'unit-testing']",104,False,1,0
Unit Testing with quarkus-smallrye-graphql,"<p>In a quarkus project with quarkus-smallrye-graphql lib, is there a way to unit test a GraphQL resource object like this one :</p>
<pre><code>@GraphQLApi
public class ProductResource {

    @Inject
    private ProductRepository productRepository;

    @Query(&quot;products&quot;)
    @Description(&quot;Get all Products&quot;)
    @RolesAllowed({&quot;USER&quot;,&quot;ADMIN&quot;})
    public List&lt;Product&gt; findAll() {
        return this.productRepository.findAll().list();
    }

    @Mutation
    @Description(&quot;Create a new Product&quot;)
    @RolesAllowed(&quot;ADMIN&quot;)
    public Boolean createProduct(String name, Double price) {
        return this.productRepository.createProduct(name, price);
    }
}
</code></pre>
<p>I want to be able to send a GraphQL query (with Authentication inactivated/or not) in unit testing in order to validate my annotations but I don't find any documented way to do it.</p>
",https://stackoverflow.com/questions/66545573/unit-testing-with-quarkus-smallrye-graphql,"['unit-testing', 'graphql', 'quarkus']",1158,True,1,3
Unit testing input event in Angular,"<p>I have unit test case to test global filter function in angular application. I'm not sure if this is an angular version problem or if I'm missing anything from the test case.</p>
<p>Environment : Angular CLI: 12.2.6 Node: 14.17.6</p>
<p>Here's the error;</p>
<pre><code>TypeError: Cannot read properties of null (reading 'nativeElement')
</code></pre>
<p><strong>Home.component.ts</strong></p>
<pre><code>  filterGlobal(dt: any, event){
    dt.filterGlobal(event.target.value, 'contains')
  }
</code></pre>
<p><strong>Home.component.html</strong></p>
<pre><code>&lt;p-table class=&quot;filterTable&quot; #dt [columns]=&quot;cols&quot; [value]=&quot;cars&quot;&gt;
    &lt;ng-template pTemplate=&quot;caption&quot;&gt;
        &lt;div style=&quot;text-align: right&quot;&gt;
            &lt;i class=&quot;pi pi-search&quot; style=&quot;margin:4px 4px 0 0&quot;&gt;&lt;/i&gt;
            &lt;input type=&quot;text&quot; class=&quot;globalFilter&quot; pInputText size=&quot;50&quot; placeholder=&quot;Global Filter&quot; (input)=&quot;dt.filterGlobal($event.target.value, 'contains')&quot; style=&quot;width:auto&quot;&gt;
        &lt;/div&gt;
    &lt;/ng-template&gt;
    &lt;ng-template pTemplate=&quot;header&quot; let-columns&gt;
        &lt;tr&gt;
            &lt;th *ngFor=&quot;let col of columns&quot;&gt;
                {{col.header}}
            &lt;/th&gt;
        &lt;/tr&gt;
        &lt;tr&gt;
            &lt;th *ngFor=&quot;let col of columns&quot; [ngSwitch]=&quot;col.field&quot;&gt;
                &lt;input *ngSwitchCase=&quot;'brand'&quot; class=&quot;brandFilter&quot; pInputText type=&quot;text&quot; (input)=&quot;dt.filter($event.target.value, col.field, col.filterMatchMode)&quot;&gt;
            &lt;/th&gt;
        &lt;/tr&gt;
    &lt;/ng-template&gt;
    &lt;ng-template pTemplate=&quot;body&quot; let-rowData let-columns=&quot;columns&quot;&gt;
        &lt;tr&gt;
            &lt;td *ngFor=&quot;let col of columns&quot;&gt;
                {{rowData[col.field]}}
            &lt;/td&gt;
        &lt;/tr&gt;
    &lt;/ng-template&gt;
&lt;/p-table&gt;
</code></pre>
<p><strong>Home.component.spec.ts</strong></p>
<pre><code>it('should use global filter and show 1 items', fakeAsync(() =&gt; {
    fixture = TestBed.createComponent(HomeComponent);
    app = fixture.debugElement.componentInstance;
    fixture.detectChanges();

    const globalFilter = fixture.debugElement.query(By.css(&quot;.globalFilter&quot;));
    globalFilter.nativeElement.value = &quot;dsad231ff&quot;;
    globalFilter.nativeElement.dispatchEvent(new Event(&quot;input&quot;));
    tick(300);
    fixture.detectChanges();

    const tableEl = fixture.debugElement.query(By.css(&quot;.filterTable&quot;));
    const bodyRows = tableEl.query(By.css('.p-datatable-tbody')).queryAll(By.css('tr'));
    expect(bodyRows.length).toEqual(1);
}));
</code></pre>
<p>Appreciated if any help</p>
",https://stackoverflow.com/questions/70072248/unit-testing-input-event-in-angular,"['angular', 'unit-testing', 'primeng', 'angular-directive', 'primeng-datatable']",212,False,1,0
Unit testing middleware after express-validator,"<p>I have my routes.js like</p>
<pre><code>app.get('/', userRules(), validate, mycontroller)
</code></pre>
<pre><code>const { query } = require('express-validator');

module.exports = {
  userRules: () =&gt; [query('team_id').optional().isInt(),
    query('active_team').optional().isBoolean()],
};
</code></pre>
<p>and my validate function looks like</p>
<pre><code>const { validationResult } = require('express-validator');
const { createMessage } = require('../helpers/index');
module.exports = {
  validate: (req, res, next) =&gt; {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      const message = createMessage(errors.array());
      return res.status(400).json({ error: true, message });
    }
    return next();
  },
}
</code></pre>
<p>What I want to achieve is to UnitTest that validate function in order to understand the behaviour</p>
<pre><code>const httpMocks = require('node-mocks-http');
const { userRules } = require('../../router/validation');
const { validateUsers } = require('../index');
    it('should return a 400', () =&gt; {
      const req = httpMocks.createRequest({
        query: {
          active_team: 'aaaa',
        },
      });
      myStub(req, userRules());
      const res = httpMocks.createResponse();
      validateUsers(req, res, next);
      expect(res.statusCode).toBe(400);
    });
</code></pre>
<p>What I'm expecting is a 400 but I got a 200 and the next() function is getting called everytime</p>
<p>Is there any way to do this?
I know I can use supertest but I don't really want it.</p>
",https://stackoverflow.com/questions/66803658/unit-testing-middleware-after-express-validator,"['javascript', 'node.js', 'express', 'jestjs', 'express-validator']",306,False,2,0
$router.push not triggering in unit testing,"<p>I have the following problem while trying to unit test my Vue application.
Even spying and mocking $router.push, I still can't make it to be called while inside unit testing:</p>
<p>This is my unit testing (<strong>Home.spec.js</strong>)</p>
<pre><code>const localVue = createLocalVue();

localVue.use(Vuex);
localVue.use(VueRouter);

describe('Home.vue', () =&gt; {
  let actions;
  let getters;
  let store;
  let router;

  beforeEach(() =&gt; {
    actions = {
        [FETCH_USER_REPOSITORIES]: jest.fn()
    };

    getters = {
       getTopThreeRepositories: jest.fn(repositoryMock.getRepositories)
    };

    store = new Vuex.Store({ getters, actions });
    router = new VueRouter();
  });

  it('should redirect when 404 status code received', async () =&gt; {
    jest.spyOn(store, 'dispatch').mockRejectedValue({ statusCode: 404 });
    jest.spyOn(router, 'push').mockResolvedValue({});

    const wrapper = await shallowMount(Home, {
        store,
        localVue,
        router
    });
    
    expect(router.push).toHaveBeenCalledWith('/not-found');
});
</code></pre>
<p>});</p>
<p>Now, this is my <strong>Home.vue</strong>:</p>
<pre><code>import { mapGetters } from 'vuex';
  import { FETCH_USER_REPOSITORIES } from &quot;../store/actions&quot;;

  import RepositoryList from &quot;@/components/RepositoryList&quot;;
  import Card from &quot;@/components/Card&quot;;

  export default {
    name: 'view-home',
    components: {
      Card,
      RepositoryList
    },

    async beforeMount() {
      try {
        await this.$store.dispatch(FETCH_USER_REPOSITORIES, 'some-repo');
      } catch(err) {
        console.log(this.$router);
        await this.$router.push('/not-found');
      }
    },

    computed: {
      ...mapGetters([&quot;getTopThreeRepositories&quot;])
    }
  }
</code></pre>
<p>The console log shows the $router correctly, with the spy.
If I force the calling inside the unit testing, it works, but the expects always fails giving me back that $router.push hasn't been called.</p>
<p>Can anyone help me, please?
Thanks!</p>
",https://stackoverflow.com/questions/67046602/router-push-not-triggering-in-unit-testing,"['vue.js', 'jestjs', 'vue-router']",1369,False,1,1
Unit testing in Django for CreateView,"<p>I have a CreateView with which I create new blog posts, I want to test it in order to check if everything is ok but something is wrong with my test and I can't understand what exactly. it gives me 2 errors, for the first method I get this error:</p>
<pre><code>Traceback (most recent call last):
  File &quot;C:\Users\Bularu Lilian\Desktop\EcoMon\blog\tests\test_views.py&quot;, line 73, in test_post_create_view_GET
    self.assertEquals(response.status_code, 200)
AssertionError: 302 != 200
</code></pre>
<p>and for the second one is this error:</p>
<pre><code> File &quot;C:\Users\Bularu Lilian\Desktop\EcoMon\blog\tests\test_views.py&quot;, line 78, in test_post_create_view_POST_success
    post = Post.objects.get(title=self.post['title'])
  File &quot;C:\Users\Bularu Lilian\Desktop\Environments\ecomon\lib\site-packages\django\db\models\manager.py&quot;, line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File &quot;C:\Users\Bularu Lilian\Desktop\Environments\ecomon\lib\site-packages\django\db\models\query.py&quot;, line 429, in get
    raise self.model.DoesNotExist(
blog.models.Post.DoesNotExist: Post matching query does not exist.
</code></pre>
<p>This is my Test class:</p>
<pre><code>class TestPostCreateViews(BaseTest):

    def test_post_create_view_GET(self):
        response = self.client.get(self.add_post_url)
        self.assertEquals(response.status_code, 200)
        self.assertTemplateUsed(response, 'blog/add_post.html')

    def test_post_create_view_POST_success(self):
        response = self.client.post(self.add_post_url, self.post, author=self.user, format='text/html')
        post = Post.objects.get(title=self.post['title'])
        self.assertEquals(response.status_code, 302)
        self.assertEquals(post.title, 'test post')
</code></pre>
<p>my CreateView:</p>
<pre><code>class PostCreateView(LoginRequiredMixin, IsSuperuserOrStaffMixin, CreateView):
    template_name = 'blog/add_post.html'
    form_class = PostCreateForm

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

</code></pre>
<p>my url path:</p>
<pre><code>path('new/post/', PostCreateView.as_view(), name='add-post'),
</code></pre>
<p>my form:</p>
<pre><code>class PostCreateForm(forms.ModelForm):
    title = forms.CharField(widget=forms.TextInput(), max_length=200)
    content = forms.CharField(widget=forms.Textarea(attrs={'rows': 25, 'cols': 50}))

    class Meta:
        model = Post
        exclude = ['author', 'slug', 'published_date', 'updated_date']

</code></pre>
<p>and my model:</p>
<pre><code>class Post(models.Model):

    class PostCategory(models.TextChoices):
        FAMILY = 'FAMILY', _('Family')
        BUSINESS  = 'BUSINESS', _('Business')
        MWRKETING = 'MARKETING', _('Marketing')
        SPENDINGS = 'SPENDINGS', _('Spendings')

    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(_('Title'), max_length=200, unique=True)
    content = models.TextField(_('Content'))
    category = models.CharField(_('Category'), max_length=9, choices=PostCategory.choices, default=PostCategory.BUSINESS)
    slug = models.SlugField(_('Slug'), max_length=200, blank=True, null=False, unique=True)
    tags = TaggableManager(_('Tags'))
    published_date = models.DateTimeField(_('Published Date/Time'), auto_now_add=True)
    updated_date = models.DateTimeField(_('Updated Date/Time'), auto_now=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)
        super().save(*args, **kwargs)

    @property
    def comments_count(self):
        return self.comments.count()

    def get_absolute_url(self):
        return reverse('blog')

</code></pre>
<p>for any help I would be greatefull</p>
",https://stackoverflow.com/questions/65790933/unit-testing-in-django-for-createview,"['python', 'django']",528,False,1,1
Unit testing vuejs methods using Jest,"<p>I'm trying to test the methods in jest framework. For javascript methods i was able to import the methods from file using require() function and test it (expect(addition(1,2).toBe(3))).
But unable to replicate the same in VueJS methods.</p>
<pre><code>  // VueJS
  export default defineComponent({
  name: &quot;App&quot;,
  components: {
    HelloWorld,
  },
  methods: {
    addition(a: number, b: number) {
      return a + b;
    },
    subtraction(a: number, b: number) {
      return a - b;
    },
    multiplication(a: number, b: number) {
      return a * b;
    },
  },
});
</code></pre>
<p>test file</p>
<pre><code>import addition from &quot;./App.vue&quot;
describe(&quot;HelloWorld.vue&quot;, () =&gt; {
  it(&quot;testing vue method&quot;, () =&gt; {
    expect(addition(1,2).toBe(3));
  });
});

//error on line 4 states &quot;Value of type 'DefineComponent&lt;{}, {}, any, ComputedOptions, MethodOptions, ComponentOptionsMixin, 
// ComponentOptionsMixin, ... 4 more ..., {}&gt;' is not callable. Did you mean to include 'new'?&quot;
</code></pre>
",https://stackoverflow.com/questions/68260455/unit-testing-vuejs-methods-using-jest,"['javascript', 'vue.js', 'unit-testing', 'jestjs']",1343,True,1,1
Unit testing Flask application API endpoints,"<p>I have a Flask application and my routes are divided into Blueprints. I want to test my endpoints.</p>
<p>Is unit testing a single method enough for testing an endpoint? I guess not. Because my endpoints perform operations inside LXC container and then update DB and finally return JSON response. If I want to test if the functionality executed as expected, would it be called e2e test for an endpoint? If yes, should I only test the returned response in unit tests of methods?</p>
",https://stackoverflow.com/questions/66581352/unit-testing-flask-application-api-endpoints,"['python-3.x', 'unit-testing', 'flask', 'testing', 'pytest']",63,False,1,0
Unit testing DelegateCommand using Rhino Mock,"<p>I am trying to unit test a command execution for a command that displays a dialog, however I keep getting NullReferenceException and I do not know why. Any suggestion would be appreciated.</p>
<p>The viewmodel being used by view snippet:</p>
<pre><code>public class ConvertFileDialogViewModel:IConvertFileDialogViewModel
{
    private string _inputFolderPath;

    public DelegateCommand SelectInputFolderCommand { get;set; }
        
    public ConvertFileDialogViewModel()
    {
        SelectInputFolderCommand = new DelegateCommand(SelectInputFolderDialog);
    }

    public string InputFolderPath
    {
        get =&gt; _inputFolderPath;
        set
        {
            _inputFolderPath = value;
            OnPropertyChanged(nameof(InputFolderPath));
        }
    }
        

    public void SelectInputFolderDialog()
    {
        using (var fbd = new FolderBrowserDialog())
        {
            DialogResult result = fbd.ShowDialog();

            if (result == DialogResult.OK &amp;&amp; !string.IsNullOrWhiteSpace(fbd.SelectedPath))
            {
                InputFolderPath = fbd.SelectedPath;
            }
        }
    }
}    
</code></pre>
<p>Interface snippet:</p>
<pre><code>public interface IConvertInterviewDialogViewModel
{
    string InputFolderPath { get; set; }
    DelegateCommand SelectInputFolderCommand { get;set; }
    
}
</code></pre>
<p>Unit-Test snippet:</p>
<pre><code>[TestMethod]
public void SelectInputFolderCommandTest()
{
    var model = MockRepository.GenerateMock&lt;IConvertFileDialogViewModel&gt;();
    model.SelectInputFolderCommand.Execute();
    model.AssertWasCalled(vm=&gt;vm.SelectInputFolderCommand);
}
</code></pre>
<p>Error:</p>
<p><code>ConvertInterviewDialogViewModelTests.SelectInputFolderCommandTest threw exception:  System.NullReferenceException: Object reference not set to an instance of an object.</code></p>
",https://stackoverflow.com/questions/69354215/unit-testing-delegatecommand-using-rhino-mock,"['c#', 'wpf', 'unit-testing', 'mvvm', 'rhino-mocks']",85,True,1,1
Unit Testing Specific Part Of Application,"<p>I am trying to test a part of our application. I know I can limit the tests by using fit, fdescribe, and changing the require.context in the test.ts file. However, I would like a way to test a specific folder, and all files under it, plus a couple of services outside of this folder.</p>
<pre><code>src
   app
      folder1
      folder2
      folder3
          services
             service1.service.ts
             service2.service.ts
</code></pre>
<p>As an example, I would like test test folder2, its children, and service2.service.ts.</p>
<p>Do you have any suggestions for doing such? By doing this, we will be able to automate our unit testing and be able to test grouped together pieces of functionality that are in different folders.</p>
<p>Note: I am using jasmine and karma for unit testing.</p>
",https://stackoverflow.com/questions/70282614/unit-testing-specific-part-of-application,"['angular', 'unit-testing', 'karma-jasmine', 'angular-unit-test']",797,True,1,2
spark unit testing with SharedSparkSession (org.apache.spark.sql.test.SharedSparkSession.eventually),"<p>I tried to write a simple unit for Spark join from the tutorial - <a href=""https://medium.com/@eugene_lopatkin/apache-spark-unit-testing-part-2-spark-sql-35c76ed592b0"" rel=""nofollow noreferrer"">Apache Spark Unit Testing Part 2 — Spark SQL</a>.
Added all dependencies from reference and</p>
<pre><code>  &quot;org.apache.spark&quot; %% &quot;spark-core&quot; % &quot;2.4.7&quot; % Test,
  &quot;org.apache.spark&quot; %% &quot;spark-core&quot; % &quot;2.4.7&quot; % Test classifier &quot;tests&quot;,
  &quot;org.scalatest&quot; %% &quot;scalatest&quot; % &quot;3.2.3&quot; % Test,
</code></pre>
<p>but can't add extended QueryTest because it involves AnyFunSuite in private class. Now the code looks like</p>
<pre><code>class TestScalaCheck extends AnyFunSuite with SharedSparkSession {
  import testImplicits._

  test(&quot;join - join using&quot;) {
    val df = Seq(1, 2, 3).map(i =&gt; (i, i.toString)).toDF(&quot;int&quot;, &quot;str&quot;)
    val df2 = Seq(1, 2, 3).map(i =&gt; (i, (i + 1).toString)).toDF(&quot;int&quot;, &quot;str&quot;)

    checkAnswer(
      df.join(df2, &quot;int&quot;),
      Row(1, &quot;1&quot;, &quot;2&quot;) :: Row(2, &quot;2&quot;, &quot;3&quot;) :: Row(3, &quot;3&quot;, &quot;5&quot;) :: Nil)
  }
</code></pre>
<p>And it generates the exception message:</p>
<pre><code>An exception or error caused a run to abort: org.apache.spark.sql.test.SharedSparkSession.eventually(Lorg/scalatest/concurrent/PatienceConfiguration$Timeout;Lorg/scalatest/concurrent/PatienceConfiguration$Interval;Lscala/Function0;Lorg/scalactic/source/Position;)Ljava/lang/Object; 
java.lang.NoSuchMethodError: org.apache.spark.sql.test.SharedSparkSession.eventually(Lorg/scalatest/concurrent/PatienceConfiguration$Timeout;Lorg/scalatest/concurrent/PatienceConfiguration$Interval;Lscala/Function0;Lorg/scalactic/source/Position;)Ljava/lang/Object;
    at org.apache.spark.sql.test.SharedSparkSession.afterEach(SharedSparkSession.scala:135)
    at org.apache.spark.sql.test.SharedSparkSession.afterEach$(SharedSparkSession.scala:129)
    at lesson2.TestScalaCheck.afterEach(TestScalaCheck.scala:14)
    at org.scalatest.BeforeAndAfterEach.$anonfun$runTest$1(BeforeAndAfterEach.scala:247)
    at org.scalatest.Status.$anonfun$withAfterEffect$1(Status.scala:377)
    at org.scalatest.Status.$anonfun$withAfterEffect$1$adapted(Status.scala:373)
    at org.scalatest.SucceededStatus$.whenCompleted(Status.scala:462)
    at org.scalatest.Status.withAfterEffect(Status.scala:373)
    at org.scalatest.Status.withAfterEffect$(Status.scala:371)
    at org.scalatest.SucceededStatus$.withAfterEffect(Status.scala:434)
    at org.scalatest.BeforeAndAfterEach.runTest(BeforeAndAfterEach.scala:246)
    at org.scalatest.BeforeAndAfterEach.runTest$(BeforeAndAfterEach.scala:227)
    at lesson2.TestScalaCheck.runTest(TestScalaCheck.scala:14)
    at org.scalatest.funsuite.AnyFunSuiteLike.$anonfun$runTests$1(AnyFunSuiteLike.scala:233)
    at org.scalatest.SuperEngine.$anonfun$runTestsInBranch$1(Engine.scala:413)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:401)
    at org.scalatest.SuperEngine.runTestsInBranch(Engine.scala:396)
    at org.scalatest.SuperEngine.runTestsImpl(Engine.scala:475)
    at org.scalatest.funsuite.AnyFunSuiteLike.runTests(AnyFunSuiteLike.scala:233)
    at org.scalatest.funsuite.AnyFunSuiteLike.runTests$(AnyFunSuiteLike.scala:232)
    at org.scalatest.funsuite.AnyFunSuite.runTests(AnyFunSuite.scala:1563)
    at org.scalatest.Suite.run(Suite.scala:1112)
    at org.scalatest.Suite.run$(Suite.scala:1094)
    at org.scalatest.funsuite.AnyFunSuite.org$scalatest$funsuite$AnyFunSuiteLike$$super$run(AnyFunSuite.scala:1563)
    at org.scalatest.funsuite.AnyFunSuiteLike.$anonfun$run$1(AnyFunSuiteLike.scala:237)
    at org.scalatest.SuperEngine.runImpl(Engine.scala:535)
    at org.scalatest.funsuite.AnyFunSuiteLike.run(AnyFunSuiteLike.scala:237)
    at org.scalatest.funsuite.AnyFunSuiteLike.run$(AnyFunSuiteLike.scala:236)
    at lesson2.TestScalaCheck.org$scalatest$BeforeAndAfterAll$$super$run(TestScalaCheck.scala:14)
    at org.scalatest.BeforeAndAfterAll.liftedTree1$1(BeforeAndAfterAll.scala:213)
    at org.scalatest.BeforeAndAfterAll.run(BeforeAndAfterAll.scala:210)
    at org.scalatest.BeforeAndAfterAll.run$(BeforeAndAfterAll.scala:208)
    at lesson2.TestScalaCheck.run(TestScalaCheck.scala:14)
    at org.scalatest.tools.SuiteRunner.run(SuiteRunner.scala:45)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13(Runner.scala:1320)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13$adapted(Runner.scala:1314)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:1314)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24(Runner.scala:993)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24$adapted(Runner.scala:971)
    at org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:1480)
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:971)
    at org.scalatest.tools.Runner$.run(Runner.scala:798)
    at org.scalatest.tools.Runner.run(Runner.scala)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2or3(ScalaTestRunner.java:38)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:25)
 
</code></pre>
<p>Could you help me to resolve it?</p>
<p>The original code is - <a href=""https://github.com/apache/spark/blob/master/sql/core/src/test/scala/org/apache/spark/sql/DataFrameJoinSuite.scala"" rel=""nofollow noreferrer"">DataFrameJoinSuite.scala</a></p>
",https://stackoverflow.com/questions/65915911/spark-unit-testing-with-sharedsparksession-org-apache-spark-sql-test-sharedspar,['apache-spark'],497,False,1,0
Unit Testing Links With Only Jest,"<p>I was wondering if there was a way to unit test links with jest alone to make sure they go to the correct place. All other resources I have looked up have used enzyme or additional applications.</p>
<p>For example:
Ensuring <code>&lt;Link to '/homepage&gt;</code> or <code>&lt;NavLink to '/homepage'&gt;</code> actually goes to the homepage.</p>
<p>Any additional resources to read would also be helpful and appreciated.</p>
",https://stackoverflow.com/questions/70535778/unit-testing-links-with-only-jest,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'react-router-dom']",239,False,1,1
Unit testing controller with dbcontext parameter,"<p>At the moment I'm (unsuccessfully) trying to unit test my ToDoItem controller.
This is the ToDoItem class:</p>
<pre><code>public class TodoItem
{
    public long Id { get; set; }
    public string Name { get; set; }
    public bool IsComplete { get; set; }

    public TodoItem()
    {

    }
}
</code></pre>
<p>This class is used in the DbContext class, like so</p>
<pre><code>public class ToDoContext : DbContext
{
    public ToDoContext(DbContextOptions&lt;ToDoContext&gt; options)
        : base(options)
    {
    }
    public DbSet&lt;TestApp.Data.TodoItem&gt; TodoItem { get; set; }

}
</code></pre>
<p>Now this is the to be tested GET function of ToDoItemsController:</p>
<pre><code>[Route(&quot;api/[controller]&quot;)]
[ApiController]
public class TodoItemsController : ControllerBase
{
    private readonly ToDoContext _context;

    public TodoItemsController(ToDoContext context)
    {
        _context = context;
    }

    // GET: api/TodoItems/5
    [HttpGet(&quot;{id}&quot;)]
    public async Task&lt;ActionResult&lt;TodoItem&gt;&gt; GetTodoItem(long id)
    {
        var todoItem = await _context.TodoItem.FindAsync(id);

        if (todoItem == null)
        {
            return NotFound();
        }

        return todoItem;
    }
</code></pre>
<p>Executing this XUnit test:</p>
<pre><code>    [Fact]
    public async Task GetTodoItem_WithUnexistingItem_ReturnsNotFound()
    {
        // Arrange
        var dbContextStub = new Mock&lt;ToDoContext&gt;();
        dbContextStub.Setup(context =&gt; context.TodoItem.FindAsync(It.IsAny&lt;long&gt;()))
            .ReturnsAsync((TodoItem)null);

        var controller = new TodoItemsController(dbContextStub.Object);

        // Act
        var result = await controller.GetTodoItem(long.MinValue);

        // Assert
        Assert.IsType&lt;NotFoundResult&gt;(result.Result);
    }
</code></pre>
<p>Provides this error:
<a href=""https://i.stack.imgur.com/gS5fV.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gS5fV.png"" alt=""enter image description here"" /></a></p>
<p>My thoughts were that it has to do with the actual DB connection, but I'm not too sure.
Can anyone help me to get this UT to work?</p>
",https://stackoverflow.com/questions/69801873/unit-testing-controller-with-dbcontext-parameter,"['.net', 'xunit']",70,False,1,0
Unit testing SAF file/directory operations,"<p>I am trying to implement unit tests for Android code that utilizes <code>DocumentFile</code> instances for file/directory operations. Normally it would be possible to initiate these tests by picking a location using <code>ACTION_OPEN_DOCUMENT_TREE</code>, but I am unable to get an instance of <code>DocumentFile</code> as part of such unit test (without needing user interaction).</p>
<p>It would be perfectly sufficient for my use case if I were able to convert a location in application's private storage to <code>DocumentFile</code>, but converting a <code>file://</code> URI of a directory to <code>DocumentFile</code> does not seem possible.</p>
",https://stackoverflow.com/questions/66624622/unit-testing-saf-file-directory-operations,"['android', 'storage-access-framework', 'scoped-storage']",147,True,1,1
Unit testing theories on collections xUnit,"<h2>Original question</h2>
<p>Let's say I have a class method <code>GetAge(DateTime dateOfBirth)</code> and I want to test if the age that comes out is correct. To do this, I create a helper method called <code>GenerateDateOfBirth(int age)</code> that returns a date of birth that should yield an age of <code>age</code>.</p>
<p>However, I don't know if my <code>GenerateDateOfBirth</code> method works, so I would like to bulk test a collection of ages to feed into <code>GenerateDateOfBirth</code>, where each generated date of birth should yield the original age when fed back into <code>GetAge</code>, something along the lines of:</p>
<pre class=""lang-cs prettyprint-override""><code>[Fact]
public void CrossTestGetAgeAndGenerateDateOfBirth()
{
    var ages = new List&lt;int&gt;(); // A reasonably large list of possible ages
    var rng = new Random();
    for (int i = 0; i &lt; 1_000_000; i++)
    {
        ages.Add(rng.Next(0, 1000)); // Arbitrary upper bound on a person's age
    }
    foreach (var realAge in ages)
    {
        var dateOfBirth = GenerateDateOfBirth(realAge);
        var calculatedAge = GetAge(dateOfBirth);
        Assert.Equal(realAge, calculatedAge); // If false, at least one of the methods is bugged
    }
}
</code></pre>
<p>I have seen that xUnit allows testing on data, by using attributes such as <code>InlineData</code> and <code>MemberData</code>, so I was wondering if I could generate a list of integers an then do a data-driven test on all of the &quot;age&quot; values like so:</p>
<pre class=""lang-cs prettyprint-override""><code>public List&lt;int&gt; Ages { get; set; } = GetAges(0, 1000, 1_000_000); // Same arbitrary bounds as above
public List&lt;int&gt; GetAges(int minAge, int maxAge, int count)
{
    var ages = new List&lt;int&gt;();
    var rng = new Random();
    for (int i = 0; i &lt; count; i++)
    {
        ages.Add(rng.Next(minAge, maxAge));
    }
    return ages;
}

[Theory]
[/* something with Ages */]
public void AgeFromDateOfBirthFromAge(/* what goes here? */)
{
    var randomDateOfBirth = GenerateDateOfBirth(age); // Where age comes from Ages
    var calculatedAge = GetAge(randomDateOfBirth);
    Assert.Equal(age, calculatedAge);
}
</code></pre>
<p>This seems more concise and readable and it does the same thing still. My goal (before I can write actual unit tests), is to sniff out any possible edge cases by bombarding both methods with a ton of random data. Once one of the methods <em>seems</em> to work well enough, ideally I can use it to fix the other and then do a final review of the (hopefully) few edge cases that might remain. Is there a way to do this?</p>
<h2>Current implementations of both methods</h2>
<h3>Method to get age</h3>
<pre class=""lang-cs prettyprint-override""><code>public int GetAge(DateTime dob)
{
    var now = DateTime.Now;

    // Time difference up to the day
    int deltaDays = now.Day - dob.Day;
    int deltaMonths = now.Month - dob.Month;
    int deltaYears = now.Year - dob.Year;
    int age = (deltaDays + 100 * deltaMonths + 10000 * deltaYears) / 10000;

    // Check if time of day has also been reached
    var timeNotReached = now.TimeOfDay.Ticks &lt; dob.TimeOfDay.Ticks;

    return (deltaDays == 0 &amp;&amp; deltaMonths == 0 &amp;&amp; timeNotReached) ? age - 1 : age;
}
</code></pre>
<h3>Method to generate a date of birth</h3>
<pre class=""lang-cs prettyprint-override""><code>public DateTime GenerateDateOfBirth(int age = 18)
{
    var rng = new Random();
    var now = DateTime.Now;

    // Get allowed values for birth date
    var maxMonth = now.Month + 1;
    var maxDay = now.Day + 1;
    var maxHour = now.Hour + 1;
    var maxMinute = now.Minute + 1;
    var maxSecond = now.Second + 1;
    var maxMillisecond = now.Millisecond;

    // Choose random allowed values
    var birthYear = now.Year - age;
    var birthMonth = rng.Next(1, maxMonth);
    var birthDay = birthMonth != now.Month ? rng.Next(1, DateTime.DaysInMonth(birthYear, birthMonth) + 1) : rng.Next(1, maxDay);
    var birthHour = rng.Next(1, maxHour);
    var birthMinute = rng.Next(1, maxMinute);
    var birthSecond = rng.Next(1, maxSecond);
    var birthMillisecond = rng.Next(maxMillisecond);

    var dateOfBirth = new DateTime(
        birthYear,
        birthMonth,
        birthDay,
        birthHour,
        birthMinute,
        birthSecond,
        birthMillisecond
    );
    return dateOfBirth;
}

</code></pre>
",https://stackoverflow.com/questions/66122731/unit-testing-theories-on-collections-xunit,"['c#', 'unit-testing', 'testing', '.net-core', 'xunit']",199,False,1,0
Serialize zeep object for unit testing,"<p>I'd like to test the logic of a program that uses zeep without actually making any external calls. For this, it would be nice to serialize a proper response object, or failing that, be able to construct an object exactly like zeep would.</p>
<p>For example, while I'm online writing tests (<code>serialize</code> and <code>deserialize</code> are the made up functions that I need):</p>
<pre class=""lang-py prettyprint-override""><code>result = zeep.Client(url).service.getFood()
print(food.Flavor)  # prints &quot;bitter&quot;
open('result', 'w').write(result.serialize())
</code></pre>
<p>Then later in a unit test run separately</p>
<pre class=""lang-py prettyprint-override""><code>result = zeep.deserialize(open('result').read())
print(food.Flavor) # prints &quot;bitter&quot;
</code></pre>
<p>What I've tried:</p>
<ul>
<li>use <code>repr(result)</code> or <code>str(result)</code>, but these are native python types and specifically don't support <code>food.Flavor</code>, but <code>food['Flavor']</code></li>
<li><a href=""https://stackoverflow.com/questions/53914039/"">This answer</a>, but I don't really want to mock the whole world, just serialize the response</li>
</ul>
",https://stackoverflow.com/questions/66246788/serialize-zeep-object-for-unit-testing,['zeep'],243,False,1,0
Unit Testing Login Vue Jest ValidationProvider,"<p>I am new to Jest and I am trying to mock the store, an action and to assert that the method was indeed called. Basically I want to check the login function.</p>
<ol>
<li>I cannot query the button because I am retrieving only a part of the component and I don't know what I'm missing.</li>
</ol>
<p>Where my Vue component looks like:</p>
<blockquote>
 
</blockquote>
<pre><code>&lt;ValidationObserver id=&quot;observer&quot; v-slot=&quot;{ invalid }&quot; :class=&quot;['w-full h-full']&quot;&gt;
  &lt;form class=&quot;flex flex-col justify-around h-full&quot; @submit.prevent=&quot;onSubmit&quot;&gt;
    &lt;ValidationProvider v-slot=&quot;{ errors }&quot; name=&quot;accessCode&quot; :class=&quot;['w-full py-6']&quot;&gt;
      &lt;sd-field :class=&quot;['sd-field_secondary', { ['sd-invalid ']: errors &amp;&amp; errors.length &gt; 0 }]&quot;&gt;
        &lt;label for=&quot;email&quot;&gt;{{ $t(&quot;form.access-code&quot;) }}&lt;/label&gt;
        &lt;sd-input v-model=&quot;accessCode&quot; type=&quot;accessCode&quot; /&gt;
        &lt;span class=&quot;sd-error&quot;&gt;{{ errors[0] }}&lt;/span&gt;
      &lt;/sd-field&gt;
    &lt;/ValidationProvider&gt;

    &lt;div class=&quot;btn-group-y&quot;&gt;
      &lt;button class=&quot;btn btn-fixed btn-blueDark&quot; type=&quot;submit&quot;&gt;
        &lt;span&gt;{{ $t(&quot;account.login&quot;) }}&lt;/span&gt;
      &lt;/button&gt;
      &lt;!-- &lt;button class=&quot;btn btn-link&quot; type=&quot;&quot;&gt; //TODO: temporary hide
        &lt;span&gt;{{ $t(&quot;account.forgot_id&quot;) }}&lt;/span&gt;
      &lt;/button&gt; --&gt;
    &lt;/div&gt;
  &lt;/form&gt;
&lt;/ValidationObserver&gt;
</code></pre>
  
<pre><code> ***MY TEST FILE***
import login from &quot;../../pages/index/login&quot;;
import Vuex from &quot;vuex&quot;;
import { mount, createLocalVue } from &quot;@vue/test-utils&quot;;
const localVue = createLocalVue();
localVue.use(Vuex);

describe(&quot;Login form&quot;, () =&gt; {
  it(&quot;calls the login action correctly&quot;, () =&gt; {
    const loginMock = jest.fn(() =&gt; Promise.resolve());
    const store = new Vuex.Store({
      actions: {
        onSubmit: loginMock,
      },
    });
    const wrapper = mount(login, { localVue, store, stubs: { ValidationObserver: true } });
    console.log(wrapper.html());
   // wrapper.find(&quot;button&quot;).trigger(&quot;click&quot;);
  // expect(loginMock).toHaveBeenCalled();
  });
});
</code></pre>
<p>console.log(wrapper.html()) returns only a part of component</p>
<blockquote>
<pre><code> &lt;div class=&quot;h-full w-full&quot;&gt;&lt;validationobserver id=&quot;observer&quot;
    class=&quot;w-full h-full&quot;&gt; &lt;/validationobserver&gt; 
  &lt;/div&gt;
</code></pre>
</blockquote>
<p>With a warning also:</p>
<pre><code>&gt; console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
&gt;         [Vue warn]: Unknown custom element: &lt;ValidationObserver&gt; - did you register the 
&gt;         component correctly? For recursive components, make sure to provide the &quot;name&quot; option.  
&gt;         found in
&gt;        ---&gt; &lt;Anonymous&gt;
&gt;            &lt;Root&gt;
</code></pre>
<p>I would like to understand how this works, I have tried to stub and other ways found but with no success.
I can get rid of the warning by adding the stubs: { ValidationObserver: true } to mount but I actually need to access the elements inside.
Thank you!</p>
",https://stackoverflow.com/questions/65922583/unit-testing-login-vue-jest-validationprovider,"['unit-testing', 'vue.js', 'jestjs', 'vuex', 'vue-test-utils']",356,False,1,0
Using Visual Studio&#39;s Unit Testing Framework,"<p>I am using Visual Studio's Unit Testing Framework (that uses cpp) to test some cases regarding my program.
I am getting error <code>E0304</code> and get the red squiggly line under <code>Assert::</code> (see screenshot at the end of the question).</p>
<p>This is my cpp code:</p>
<pre><code>TEST_METHOD(T001_TriangleAngleTest_EquilateralTriangle_true)
    {
        //float angles[3] = { 67, 60, 60 };
        //float sum = angles[0] + angles[1] + angles[2];

        //float* result = getTriangleAngles(angles[0], angles[1], angles[2]);
        //Assert::AreEqual(sum, angles);

        float angles[3] = {60, 60, 60};

        float* result = getTriangleAngles(angles[0], angles[1], angles[2]);

        float expected = 180;

        Assert::AreEqual(expected, result);

    }
</code></pre>
<p>And this is my C code(my actual program):</p>
<pre><code>float* getTriangleAngles(float side1, float side2, float side3)
float pi, s, area, R;

pi = acos(-1);

s = (side1 + side2 + side3) / 2;
area = sqrt(s * (s - side1) * (s - side2) * (s - side3));

R = (side1 * side2 * side3) / (4 * area);

float angles[3] = { 0.f, 0.f, 0.f };
angles[0] = (180 / pi) * asin(side1 / (2 * R));
angles[1] = (180 / pi) * asin(side2 / (2 * R));
angles[2] = (180 / pi) * asin(side3 / (2 * R));

printf(&quot;Angles: %6.2f %6.2f %6.2f\n&quot;, angles[0], angles[1], angles[2]);

float sum = angles[0] + angles[1] + angles[2];

return angles;
</code></pre>
<p>My problem is that while still learning (as you can see in my poorly written unit test), I am having a lot of trouble trying to come with a few test cases. My program essentially asks for user input on 3 sides and displays the type of triangle that it is (equilateral, scalene, isosceles) and, depending on what type of triangle and side factor, it will display the 3 angles.
My code works, it's just the unit testing that I am having problems with trying to make it work.</p>
<p>Please let me know what I can do or if you could point me into the right direction so I can learn.</p>
<p><a href=""https://i.stack.imgur.com/7Pns1.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7Pns1.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/70052555/using-visual-studios-unit-testing-framework,"['c++', 'c', 'visual-studio', 'unit-testing', 'testing']",55,False,1,0
Error with unit testing using selfassertAlmostEqual,"<p>right so I am getting an error with unit testing where I can't use selfassertAlmostEqual</p>
<pre><code>in assertAlmostEqual
    diff = abs(first - second)
TypeError: unsupported operand type(s) for -: 'list' and 'list
</code></pre>
<p>this is my unittest method where I am getting the error any ideas as to how could I fix it thank you.</p>
<pre><code>def test_method_04(self):
        self.set_up()
        actual = self.bookshop.method_4(self.orders)
        expected = [(1, 678.33),(2, 494.46),(3, 364.8),(4, 492.57)]
        self.assertAlmostEqual(actual, expected, places = 2)
        print(&quot;METHOD4 \nACTUAL:&quot;)
        for line in actual:
            print(line)
        print(&quot;EXPECTED:&quot;)
        for line in expected:
            print(line)
'
</code></pre>
",https://stackoverflow.com/questions/69980505/error-with-unit-testing-using-selfassertalmostequal,"['python', 'computer-science']",133,False,1,1
Unit testing in laravel using filesystems,"<p>I'm doing unit testing using the filesystems config. I want to map my file system disk to a testing directory where I will put my files(JSON, Excel, txt) to be used by the application for testing purposes. I don't want to use fake directories as I need to put the file in the 'import' location.</p>
<p>filesystems.php:</p>
<pre><code>'disks' =&gt; [
    'import' =&gt; [
        'driver' =&gt; 'local',
        'root' =&gt; '/import/clientname',
        'visibility' =&gt; 'private'
    ],
];
</code></pre>
<p>In the application, here is the function which i want to test:</p>
<pre><code>public function importFile(){
    $filesystem = Storage::disk('import');
    
    ...
}
</code></pre>
<p>The solution I was thinking is to use this location for my testing:</p>
<p><a href=""https://i.stack.imgur.com/JT5lt.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JT5lt.png"" alt=""enter image description here"" /></a></p>
<p>Is there a way to implement this solution?</p>
",https://stackoverflow.com/questions/66865458/unit-testing-in-laravel-using-filesystems,"['laravel', 'unit-testing', 'phpunit', 'filesystems']",702,True,1,1
Haskell: Multiple Assertions in Unit Testing?,"<p>I looked up a similar topic and found this snippet of code from here: <a href=""https://stackoverflow.com/a/21419654/14386048"">https://stackoverflow.com/a/21419654/14386048</a></p>
<p>To quote:<br>
Let's assume that we have module <code>SafePrelude.hs</code>:</p>
<pre><code>module SafePrelude where

safeHead :: [a] -&gt; Maybe a
safeHead []    = Nothing
safeHead (x:_) = Just x
</code></pre>
<p>we can put tests into <code>TestSafePrelude.hs</code> as follows:</p>
<pre><code>module TestSafePrelude where

import Test.HUnit
import SafePrelude

testSafeHeadForEmptyList :: Test
testSafeHeadForEmptyList = 
    TestCase $ assertEqual &quot;Should return Nothing for empty list&quot;
                           Nothing (safeHead ([]::[Int]))

testSafeHeadForNonEmptyList :: Test
testSafeHeadForNonEmptyList =
    TestCase $ assertEqual &quot;Should return (Just head) for non empty list&quot; (Just 1)
               (safeHead ([1]::[Int]))

main :: IO Counts
main = runTestTT $ TestList [testSafeHeadForEmptyList, testSafeHeadForNonEmptyList]
</code></pre>
<p>-- End Quote --<br>
Is it possible to have multiple assertions within, let's say, <code>testSafeHeadForEmptyList</code>? I'm trying to categorize my test samples of similar cases, but just different variations. I want to avoid something like this below (assume each assert equal has a different variation, but all should return nothing, for example):</p>
<pre><code>testSafeHeadForEmptyList :: Test
testSafeHeadForEmptyList = 
    TestCase $ assertEqual &quot;Should return Nothing for empty list&quot;
                           Nothing (safeHead ([]::[Int]))
testSafeHeadForEmptyList2 :: Test
testSafeHeadForEmptyList2 = 
    TestCase $ assertEqual &quot;Should return Nothing for empty list&quot;
                           Nothing (safeHead ([]::[Int]))
...
testSafeHeadForEmptyList99 :: Test
testSafeHeadForEmptyList99 = 
    TestCase $ assertEqual &quot;Should return Nothing for empty list&quot;
                           Nothing (safeHead ([]::[Int]))
</code></pre>
<p>Is this possible in Haskell?</p>
",https://stackoverflow.com/questions/67083434/haskell-multiple-assertions-in-unit-testing,"['unit-testing', 'haskell', 'testing', 'assertion', 'hunit']",334,True,1,1
Redux-Saga unit testing select function,"<p>I have a lot of select statements that follow the following format:</p>
<pre><code>const selector = (identifier) =&gt; (state) =&gt; state.getIn(['ui', identifier, 'object']);
</code></pre>
<p>The difference between the above and normal selectors, is I pass an identifier that populates the <code>getIn</code> call. So instead of doing <code>yield select(selector)</code> you do <code>yield select(selector(identifier))</code></p>
<p>This works fine, but I can't seem to unit test it.</p>
<p>Usually you can just have the expected effect <code>select(selector)</code> and assert equal to that, e.g.</p>
<pre><code>expect(generator.next().value).to.deep.equal(select(selector));
</code></pre>
<p>But that doesn't work when i'm trying to pass an identifier:</p>
<pre><code>expect(generator.next().value).to.deep.equal(select(selector(identifier)));
</code></pre>
<p>I assume its something to do with when i'm calling the function, it returns different instances? But I would've thought deep equal solves that. Unfortunately - the error message I get doesn't provide any help.</p>
<pre><code>AssertionError: expected { Object (@@redux-saga/IO, SELECT) } to deeply equal { Object (@@redux-saga/IO, SELECT) }
</code></pre>
<p>Has anyone tried the above? or suggestion on how I can test this?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/66581122/redux-saga-unit-testing-select-function,"['reactjs', 'redux', 'react-redux', 'redux-saga']",163,False,0,1
Angular unit testing for the promises,"<p>I am trying to write the test cases for below method :-
The below is the component code for adding the product</p>
<p><strong>COMPONENT:</strong></p>
<pre><code>import { HttpClient } from '@angular/common/http';
import { FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Observable } from 'rxjs';
import { Constants } from '../../../../../../utils/constants';
import { FileUploadService } from '../../../services/file-upload.service';
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ManagePackageService } from '../../../services/manage-package.service';
import { DomSanitizer } from '@angular/platform-browser';
import { Package } from '../../../models/package.model';
import { ProductPackageMapping } from '../../../models/product-package-mapping.model';
import { Product } from '../../../models/product.model';
import { NotificationAlertService } from '../../../../shared/services/notification-alert.service';
import { ManageProductService } from '../../../services/manage-product.service';
import { DocumentDTO } from '../../../models/document-dto';
import { saveAs } from 'file-saver';
import { ConfirmationDialogService } from '../../../../shared/services/confirmation-dialog.service';

@Component({
  selector: 'app-add-product',
  templateUrl: './add-product.component.html',
  styleUrls: ['./add-product.component.scss']
})

export class AddProductComponent implements OnInit {
  productDetailForm: FormGroup;
  addTitle: boolean = true;
  isView: boolean = true;
  submitted: boolean = false;
  status: boolean = true;
  check: boolean = false;
  changevar: string;
  @Input() id: Number;
  @Output() changeIndicator = new EventEmitter&lt;string&gt;();
  @Input() list: ProductPackageMapping;
  @Output() dataLoaded = new EventEmitter&lt;string&gt;();
  fileToUpload: File | null = null;
  fileArray: Array&lt;any&gt; = [];
  productData: any = [];
  productDataTemp: any[];
  fData = new FormData();
  packagePlan: Array&lt;any&gt; = [];
  productDto = new Product();
  packageDto = new Package();
  productPackageMappingDto = new ProductPackageMapping();
  documentDto: Array&lt;any&gt; = [];
  isDocId: boolean = false;
  productForm: FormGroup;
  activeStatus: boolean = true;
  requiredFileType: string;
  public NAME_MAX_LENGTH = 50;
  isValidFormSubmitted: boolean;
  @Input() allRolesFromParent: Product[] = [];
  selectedFiles?: FileList;
  message: string[] = [];
  fileInfos?: Observable&lt;any&gt;;
  documentList: Array&lt;any&gt; = [];
  ppm: any;
  fileUrl: any;
  constructor(private http: HttpClient,
    private formBuilder: FormBuilder,
    private uploadService: FileUploadService,
    private manageProduct: ManageProductService,
    private managePackageService: ManagePackageService,
    private sanitizer: DomSanitizer,
    private notifyService: NotificationAlertService,
    private confirmationDialogService: ConfirmationDialogService
  
  ) { }

  ngOnInit(): void {
    this.createForm();
    this.fileInfos = this.uploadService.getFiles();
    this.fData = new FormData();
    this.subscriptionPackages()
  }

  closeModal() {
    this.status = true;
    this.check = false;
    this.changevar = 'cancel';
    this.changeIndicator.emit(this.changevar);
    this.productForm.reset();
    this.fData.delete('ppm');
    this.fData.delete('file');
    this.emit();
  }

  closeEditModel() {
    this.status = true;
    this.documentList = [];
    this.changevar = &quot;cancel&quot;;
    this.changeIndicator.emit(this.changevar);
    this.addTitle = true;
    this.productForm.reset();
    this.fData.delete(&quot;ppm&quot;);
    this.fData.delete(&quot;file&quot;);
    this.emit();
  }

  
  onChangeSwitch(event) {
    if (event.target.checked == true) {
      this.activeStatus = true;
    } else {
      this.activeStatus = false;
    }
  }


  createForm() {
    this.productForm = new FormGroup({
      name: new FormControl(this.productDto.name, [
        Validators.required,
        Validators.maxLength(this.NAME_MAX_LENGTH),
        Validators.pattern(Constants.NO_WHITE_SPACE_PATTERN),
      ]),
      url: new FormControl(this.productDto.demoURL, Validators.required),
      version: new FormControl(this.productDto.productVersion, Validators.required),
      projectType: new FormControl(this.productDto.projectType, Validators.required),
      plansName: new FormControl(this.packageDto.id, Validators.required),
      desc: new FormControl(this.productDto.productDescription, Validators.required),
      active: new FormControl(this.productDto.active, Validators.required),
      documents: this.formBuilder.array([]),
    });
  }


  ngOnChanges() {
    this.productData = this.list;
    if (this.id) {
      this.addTitle = false;
      this.productDataTemp = this.productData.filter((vl) =&gt; (this.id == vl.id));
      this.productDataTemp.forEach(obj =&gt; {
        this.productDto.ppmId = obj.ppmId;
        this.productDto.id = obj.id;
        this.productDto.name = obj.name;
        this.productDto.demoURL = obj.demoURL;
        this.productDto.productDescription = obj.productDescription;
        this.productDto.projectType = obj.type;
        this.productDto.active = obj.active;
        this.productDto.productVersion = obj.version;
        this.packageDto.id = obj.pkgInfo.id;
        this.documentList = obj.listDocuments
      })
      this.createForm();
    } else {
      this.productDto = new Product();
      this.packageDto = new Package();
      this.documentDto = [];
      this.documentList = [];
    }
    this.documentList.length == 0 ? this.isDocId = false : this.isDocId = true;
  }

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

  choosePackages(e) {
    

  }

  subscriptionPackages() {
    this.managePackageService.getPackages().subscribe(
      (response) =&gt; {
        this.packagePlan = response;
      },
      (httpErrorRes) =&gt; {
      }
    );
  }

  get documentsFormArray(): FormArray {
    return this.f['documents'] as FormArray;
  }

  addDocument() {
    if (this.documentsFormArray.length &lt; 5) {
      this.documentsFormArray.push(this.formBuilder.group({
        id: new FormControl(''),
        docName: new FormControl('', Validators.required),
        docType: new FormControl('', Validators.required),
        attachment: new FormControl('', Validators.required)
      }))
    }
  }

  deleteRow(i: number) {

    if (this.id) {
      delete this.fileArray[i];
      this.documentsFormArray.removeAt(i);
      this.fileArray.splice(i, 1);
    }
    else {
      delete this.documentsFormArray[i];
      this.documentsFormArray.removeAt(i);
      this.fileArray.splice(i, 1);
    }
  }

  getFiles(fileArray) {
    this.fileArray.forEach(files =&gt; {
      this.fData.append(&quot;file&quot;, files);
    })
  }

  selectFiles(event): void {
    this.selectedFiles = event.target.files;
  }

  onFormSubmit() {
    this.submitted = true;
    if (this.fileArray.length &gt; 0) {
      this.getFiles(this.fileArray);
    }
    if (this.productForm.value.id === null) {
      this.productDto.id = null;
    }
    this.productDto.name = this.productForm.value.name;
    this.productDto.demoURL = this.productForm.value.url;
    this.productDto.productVersion = this.productForm.value.version;
    this.productDto.projectType = this.productForm.value.projectType;
    this.productDto.productDescription = this.productForm.value.desc;
    this.productDto.active = this.productForm.value.active;
    this.packageDto.id = this.productForm.value.plansName;
    if (this.documentsFormArray &amp;&amp; this.documentsFormArray.value &amp;&amp; this.documentsFormArray.value.length &gt; 0) {
      this.documentsFormArray.value.forEach(element =&gt; {
        this.documentDto.push(element);
      });
    }

    this.productPackageMappingDto.id = this.productDto.ppmId ? this.productDto.ppmId : null;
    this.productPackageMappingDto.products = this.productDto;
    this.productPackageMappingDto.packages = this.packageDto;
    this.productPackageMappingDto.document = this.documentDto;
    this.ppm = new Blob([JSON.stringify(this.productPackageMappingDto)], { type: &quot;application/json&quot; });
    this.fData.has(&quot;file&quot;) ? true : this.fData.append(&quot;file&quot;, '');
    this.fData.append(&quot;ppm&quot;, this.ppm);
    this.confirmationDialogService.confirm('Are you sure ?', 'Do you really want to Activate/ Deactivate Package ?')
      .then((confirmed) =&gt; {
        if (confirmed) {
          this.manageProduct.createProduct(this.fData).subscribe(
            (response) =&gt; {
              this.notifyService.showSuccess(&quot;Data saved successfully !!&quot;, &quot;Success&quot;)
              this.closeModal();
              this.fData.delete(&quot;ppm&quot;);
              this.fData.delete(&quot;file&quot;);
              this.productDto = new Product();
              this.packageDto = new Package();
              this.documentDto = [];
              this.documentList = [];
              this.fileArray = [];
              this.emit();
            },
            (httpErrorRes) =&gt; {
              this.fData.delete(&quot;ppm&quot;);
              this.fData.delete(&quot;file&quot;);
              this.notifyService.showError(httpErrorRes.error, &quot;Error&quot;);
            }
          );
        }
        else {
          this.fData.delete(&quot;ppm&quot;);
          this.fData.delete(&quot;file&quot;);
        }
      })

  }


  upload(event: any) {
    let files = event.target.files[0];
    this.fileArray.push(files);
  }

  downloadFile(fileData: DocumentDTO): void {
    this.manageProduct.download(fileData.fileName)
      .subscribe(blob =&gt; saveAs(blob, fileData.fileName));
  }


  emit() {
    this.dataLoaded.emit('AddProductComponent')
  }
}
</code></pre>
<p>The below is the spec file for the above component</p>
<p><strong>COMPONENT.SPEC.TS</strong></p>
<pre><code>import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { NgSelectModule } from '@ng-select/ng-select';
import { TranslateModule } from '@ngx-translate/core';
import { ToastrModule } from 'ngx-toastr';
import { Observable, of, throwError } from 'rxjs';
import { AppConfig } from '../../../../../app.config';
import { ConfirmationDialogService } from '../../../../configurations/services/confirmation-dialog.service';
import { NotificationAlertService } from '../../../../shared/services/notification-alert.service';
import { DocumentDTO } from '../../../models/document-dto';
import { ManagePackageService } from '../../../services/manage-package.service';
import { ManageProductService } from '../../../services/manage-product.service';
import { AddProductComponent } from './add-product.component';

describe('AddProductComponent', () =&gt; {
  let component: AddProductComponent;
  let fixture: ComponentFixture&lt;AddProductComponent&gt;;
  let packageServiceStub = jasmine.createSpyObj('ManagePackageService', ['getPackages']);
  let confirmationDialougeStub = jasmine.createSpyObj('ConfirmationDialogService', ['confirm']);
  let manageProductStub = jasmine.createSpyObj('ManageProductService', ['createProduct','download']);
  let notificationStub = jasmine.createSpyObj('NotificationAlertService', ['showSuccess', 'showError']);
  let fileData = new DocumentDTO()

  class MockUserService {
    getPackages() {
      return [{'name':'basic', 'id':1}, {'name':'advance', 'id':2}, {'name':'premium', 'id':3}];
    } 
  }

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [HttpClientTestingModule,ReactiveFormsModule,FormsModule,ToastrModule.forRoot(),
        TranslateModule.forRoot(), NgSelectModule],
      declarations: [ AddProductComponent ],
      providers :[AppConfig,
        { provide: ManageProductService, useValue: manageProductStub },
        { provide: ManagePackageService, useValue: packageServiceStub }]
    })
    .compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AddProductComponent);
    component = fixture.componentInstance;
    const mockpackageResponse = []; 
    packageServiceStub.getPackages.and.returnValue(of(mockpackageResponse));

    component.activeStatus  = true;
    component.productDataTemp = [{'ppmId': 2, 'id': 2, 'name': 'ttvrtv', 'productDescription': 'vttvt', 'projectType': null}]
    component.productData = [{'ppmId': 1, 'id': 1, 'name': 'tvrtv', 'productDescription': 'vtvt', 'projectType': null},
    {'ppmId': 2, 'id': 2, 'name': 'ttvrtv', 'productDescription': 'vttvt', 'projectType': null}]
    component.id  = 2;
    component.fileArray = ['dfdfdf','dfdsdf']
    component.packagePlan = [{'name':'basic', 'id':1}, {'name':'advance', 'id':2}, {'name':'premium', 'id':3}];
    fixture.detectChanges();
  });

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

  it('should create closeModal()', () =&gt; {
    const eventTrue = {
      target: {
        checked: true,
     }
    };
    const eventFalse = {
      target: {
        checked: false,
     }
    };
    component.closeModal();
    component.closeEditModel();
    component.onChangeSwitch(eventTrue)
    component.onChangeSwitch(eventFalse)
  });

  // it('should create ngOnChanges', () =&gt; {
  //   component.ngOnChanges();
  // });

  it('should create choosePackages', () =&gt; {
    const event = {};
    component.choosePackages(event);
  });

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

//   it('should handle error subscriptionPackages', () =&gt; {
//     spyOn(window, 'alert');
//     packageServiceStub.getPackages.and.returnValue(throwError({ error: 'some error'}));
//     component.subscriptionPackages();
// });

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

  it('should create deleteRow(i: number)', () =&gt; {
    component.id  = 1;
    component.deleteRow(1);
  });

  it('should create deleteRow(i: number) nullity check', () =&gt; {
    component.id  = null;
    component.deleteRow(null);
  });

  it('should create selectFiles', () =&gt; {
    const eventSelectFiles = {
      target: {
        files: 'ss',
     }
    };
    component.selectFiles(eventSelectFiles);
  });

  it('should create onFormSubmit length&gt;0', () =&gt; {
    component.fileArray.length = 2;
    component.onFormSubmit();
  });

  it('should create onFormSubmit nullity check', () =&gt; {
    component.productForm.value.id = null
    component.onFormSubmit();
  });

//   it('should create onFormSubmit else part', (done) =&gt; {
//     const confirmationResponse = {}; // Keep is as your response
//     let spy = spyOn( confirmationDialougeStub,'confirm').and.returnValue(Promise.resolve(true));
//   //   fixture.whenStable().then(confirmed =&gt; {
//   //     fixture.detectChanges();
//   //     component.onFormSubmit();
//   //  })

//   spy.calls.mostRecent().returnValue.then(() =&gt; {
//     fixture.detectChanges();
//     //component.onFormSubmit();
//     done();
// });
//   });

// it('should create onFormSubmit else part', () =&gt; {
//   confirmationDialougeStub.confirm.and.returnValue({
//     closePromise : {
//       then : function(callback) {
//         callback({value: true});
//       }
//     }
//   });
 
// });

  it('should create upload download', () =&gt; {
    const eventFile = {
      target: {
        files: true,
     }
    };
    component.upload(eventFile);
  });

});
</code></pre>
<p>PROBLEM :-  I have some below pointers regarding Jasmine and trying to figure it out the way to achieve the same.</p>
<ol>
<li><p>I am not able to figured out the way to cover or test what the promises return</p>
<p>this.confirmationDialogService.confirm('Are you sure ?', 'Do you really want to Activate/ Deactivate Package ?')
.then((confirmed) =&gt; {</p>
</li>
</ol>
<p>In the code coverage, the above lines are not covered and I don't know what went wrong, I have tried so many ways and referred many of the posts from stackoverflow itself but that weren't work for my use case.</p>
<ol start=""2"">
<li><p>how to write test cases for a method having <code>foreach()</code>, <code>filter()</code>, <code>map()</code></p>
</li>
<li><p>how to write test cases for a method having observables, subscribe and promises</p>
</li>
</ol>
<p>Please suggest the best practices.</p>
",https://stackoverflow.com/questions/69924875/angular-unit-testing-for-the-promises,"['jasmine', 'karma-runner']",260,False,0,1
Spring WebFlux: Unit testing of Mono,"<p>I have the following service</p>
<pre class=""lang-java prettyprint-override""><code>@Service
public class TestService {
    @Autowired
    TestService1 testService1;
    
    @Autowired
    TestService2 testService2;
    
    @Autowired
    TestService3 testService3;
    
    @Autowired
    TestService4 testService4;

    public Mono&lt;DataResponse&gt; getData() {
        Mono&lt;String&gt; ts1 = testService1.getMono();
        Mono&lt;String&gt; ts2 = testService2.getMono();
        Mono&lt;String&gt; ts3 = testService3.getMono();
        Mono&lt;String&gt; ts4 = testService4.getMono();
        
        return Mono.zip(ts1, ts2, ts3, ts4)
        .flatmap(resp -&gt; {
             // line XX
             return(Mono.just(new DataResponse(ts1, ts2, ts3, ts4)));
        });
    }
}
</code></pre>

<p>I'm trying to perform unit testing using Mockito and JUnit.</p>
<pre class=""lang-java prettyprint-override""><code>@SpringBootTest()
public class TestService {
    @InjectMocks
    TestService testService;

    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    TestService1 testService1;
    
    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    TestService2 testService2;
    
    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    TestService3 testService3;
    
    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    TestService4 testService4;
    
    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public Mono&lt;DataResponse&gt; getData() {
        when(testService1.getMono()).thenReturn(Mono.just(new String()));
        when(testService2.getMono()).thenReturn(Mono.just(new String()));
        when(testService3.getMono()).thenReturn(Mono.just(new String()));
        when(testService4.getMono()).thenReturn(Mono.just(new String()));
                
        Mono&lt;DataResponse&gt; res = testService.getData();
        
        Predicate&lt;DataResponse&gt; p = response -&gt; response != null;
        StepVerifier.create(res.log(), 1).expectNextMatches(p).verifyComplete();
    }
}
</code></pre>

<p>StepVerifier never executes expectNextMatches if I return Mono.zip(...) from the getData method and never executes code inside flatmap (line XX), the publisher is getting initialized but not able to subscribe to it. But if I return Mono.just() it is working fine.</p>
<p>Following are the logs</p>
<pre class=""lang-html prettyprint-override""><code>12:47:18.576 [main] INFO reactor.Mono.FlatMap.2 - | onSubscribe([Fuseable] MonoFlatMap.FlatMapMain)
12:47:18.587 [main] INFO reactor.Mono.FlatMap.2 - | request(1)
</code></pre>

<p>What would be the best approach to write unit test cases for this use case with 100% coverage?</p>
",https://stackoverflow.com/questions/69342710/spring-webflux-unit-testing-of-mono,"['unit-testing', 'junit', 'mockito', 'project-reactor']",1378,False,0,0
Unit Testing in API ASP.NET Core,"<p>I would like to make some unit-test about all my methods, (DELETE, PUT, POST ETC..) but i don't know how can i instanciate my clases in unit, now i have this in unit class:</p>
<pre><code> //Arrange
 var mockRepo = new Mock&lt;IRebelRepository&gt;();
 var controller = new RebelsController(mockRepo.Object);
 //Act
 var rebel = controller.Delete(2);
</code></pre>
<p>but now i want to check if the id is correct or not watching the response of my API (OK or BadResponse)</p>
<pre><code>public ActionResult&lt;Rebel&gt; Delete(int id)
        {
            _logger.LogInformation(&quot;Start of RebelsController.Delete()&quot;);
            var result = new ApiResult();
            ActionResult response = null;
            _logger.LogDebug($&quot;Trying to delete rebel ID: {id}&quot;);

            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.LogWarning(&quot;There was a problem deleting rebel, invalid data&quot;);
                    result.Message = &quot;Invalid rebel information.&quot;;
                    result.IsError = true;
                    response = BadRequest(result);
                }
                else
                {
                    if (id &gt; 0)
                    {
                        var filteredRebel = _rebelRepository.GetRebelById(id);

                        if (filteredRebel == null)
                        {
                            _logger.LogWarning($&quot;The rebel {id} was not found&quot;);
                            result.Message = $&quot;The rebel with id {id} has not been found&quot;;
                            result.IsError = true;

                            response = BadRequest(result);

                        }
                        else
                        {
                            _rebelRepository.DeleteRebel(filteredRebel);
                            result.Message = &quot;Rebel deleted correctly&quot;;
                            _logger.LogDebug($&quot;Rebel {id} sucessfully deleted&quot;);

                            response = Ok(result);
                        }
                    }
                }

            }catch(Exception ex)
            {
                _logger.LogError(&quot;An error occurred while Deleted method was running, error :&quot; + ex.Message);
                result.Message = &quot;Error on Delete&quot;;
                result.IsError = true;
                response = BadRequest(result);
            }

            _logger.LogInformation(&quot;End of RebelsController.Delete()&quot;);
            return response;
        }
</code></pre>
<p>How can i make unit testing in APIs?</p>
",https://stackoverflow.com/questions/66790791/unit-testing-in-api-asp-net-core,"['c#', 'api', 'asp.net-core']",200,True,0,1
Unit testing list extension function - Kotlin,"<p>I am new to unit testing, and facing issue with a extension function, which is kind of:</p>
<pre><code>fun List&lt;Water&gt;.getFileteredList() = return listOf(filteredWater)
</code></pre>
<p>Now if I want to test this function, how can I provide the list to the function while testing.</p>
<blockquote>
<p>Water is just and example in this scenario.</p>
</blockquote>
",https://stackoverflow.com/questions/69127385/unit-testing-list-extension-function-kotlin,"['android', 'unit-testing', 'kotlin', 'junit', 'extension-function']",180,False,0,0
Unit Testing Angular 11 + Karma + Pug,"<p>I'm writing unit tests for angular 11 application.
In the project I'm using .pug instead of .html.</p>
<p>I've tried with:</p>
<ul>
<li><a href=""https://www.npmjs.com/package/@angular-builders/custom-webpack#custom-webpack-config-object"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/@angular-builders/custom-webpack#custom-webpack-config-object</a></li>
<li><a href=""https://github.com/StoutLLC/karma-pug-preprocessor"" rel=""nofollow noreferrer"">https://github.com/StoutLLC/karma-pug-preprocessor</a></li>
<li><a href=""https://www.npmjs.com/package/karma-ng-pug2js-preprocessor/v/1.0.0-beta.0"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/karma-ng-pug2js-preprocessor/v/1.0.0-beta.0</a>
but none works.</li>
</ul>
<p>Tests are running, but rendered pug is just a text not proper html.
Build converts files from pug to html.
In the webpack config is added pug loader.</p>
<pre><code>&quot;dependencies&quot;: {
  &quot;ng-cli-pug-loader&quot;: &quot;^0.2.2&quot;,
}


&quot;devDependencies&quot;: {
  &quot;pug&quot;: &quot;^2.0.4&quot;,
  &quot;pug-loader&quot;: &quot;^2.4.0&quot;,
}
</code></pre>
<p>karma.conf.js</p>
<pre><code>plugins: [
  require('karma-jasmine'),
  require('karma-chrome-launcher'),
  require('karma-jasmine-html-reporter'),
  require('karma-coverage'),
  require('@angular-devkit/build-angular/plugins/karma'),
  require('karma-pug-preprocessor'),
],
files: [
  'src/**/*.pug',
],
preprocessors: {
  'src/**/*.pug': ['pug']
},
</code></pre>
",https://stackoverflow.com/questions/67103990/unit-testing-angular-11-karma-pug,"['angular', 'unit-testing', 'pug', 'karma-jasmine']",643,False,0,1
C#: P/Invoke and Unit Testing,"<p>I have been following the guidelines from:</p>
<ul>
<li><a href=""https://www.meziantou.net/stop-using-intptr-for-dealing-with-system-handles.htm"" rel=""nofollow noreferrer"">https://www.meziantou.net/stop-using-intptr-for-dealing-with-system-handles.htm</a></li>
</ul>
<p>So basically I have now a wrapper class on top of my native code as follow:</p>
<pre><code>public sealed class MyFileWrapper : IDisposable
{
    private readonly MySafeHandle _handle;
    // implement cstor and Dispose() as recommended

    public int ReadFile(byte[] bytes, int numBytesToRead) {
      int ret = NativeMethods.ReadFile(_handle...);
      // ...
      return numBytesRead;
    }
}
</code></pre>
<p>with:</p>
<pre><code>internal static class NativeMethods
{
[...]
    // Take a SafeHandle in parameter instead of IntPtr
    [DllImport(&quot;kernel32&quot;, SetLastError = true)]
    internal extern static int ReadFile(MySafeHandle handle, byte[] bytes, int numBytesToRead, out int numBytesRead, IntPtr overlapped_MustBeZero);
[...]
}
</code></pre>
<p>What would be a good practice to unit test this <code>ReadFile</code> function (using Xunit) ? It seems like the static class <code>NativeMethods</code> is <a href=""https://stackoverflow.com/a/1823750/136285"">against good practice</a> for unit testing, so I was wondering what people do in this case. It seems that hiding the implementation detail of <code>MySafeHandle</code> is part of the solution, so I suspect turning <code>NativeMethods</code> into an interface would expose too much of the low level.</p>
",https://stackoverflow.com/questions/68257341/c-p-invoke-and-unit-testing,['.net-core'],100,False,0,0
Unit Testing on Nginx custom Modules,"<p>I'd like to find a way to make unit testing on my custom nginx modules but failed. Could anyone provide some suggestions? I once found the Test::Nginx framework, but it works as system test. Some people told me that I can use ngx_lua_module to expose C function in nginx module by the way of FFI. Could anyone know how to do that?</p>
",https://stackoverflow.com/questions/68374844/unit-testing-on-nginx-custom-modules,"['unit-testing', 'nginx']",164,False,0,1
Jest - Unit Testing a Namespaced File,"<p>Is it possible to write a unit test with Jest for a JavaScript file that is namespaced using the below format?</p>
<pre><code>// utilities.js

var MyApp = MyApp || {};
MyApp.Common = MyApp.Common || {};
MyApp.Common.Utilities = new function(){
    this.getSomething = function(){  // Need to unit test this function
        return 'Something';
    }
}
</code></pre>
<p>If not, is there a better way to structure the namespaces to allow for unit testing?</p>
",https://stackoverflow.com/questions/69230785/jest-unit-testing-a-namespaced-file,"['javascript', 'unit-testing', 'jestjs']",44,True,0,1
Unit testing gui with gtk c#,"<p>How do I unit test gtk C#.
When I launch the gui it controls the thread. I have little experience in testing UI so any help would be appreciated. Also I'm using gtk (c#) for the first time.</p>
<p>This is what I am trying.</p>
<pre><code>    [TestFixture]
public class AddEmployeeWindowTest
{
    private AddEmployee window;
    private AddEmployeePresenter presenter;
    private TransactionContainer container;

     [Test]
    public void CreateWindow()
    {
        Application.Init();
        window = new AddEmployee();
        window.Show();
        Application.Run();
        window.Destroy();
        Application.Quit();
    }
}
</code></pre>
<p>My goal is to check when text boxes are updated and update the presenter accordingly.
Using Rider-linux so Windows Forms are not an option at the moment.
Also I am aware of the <a href=""https://github.com/PlasticSCM/GuiTestSharp"" rel=""nofollow noreferrer"">PlasticSCM</a> solution but would like to &quot;do it myself&quot; if I can.</p>
",https://stackoverflow.com/questions/68648024/unit-testing-gui-with-gtk-c,"['c#', 'monodevelop', 'gtk#']",192,False,0,0
Unit Testing with Router.events Angular 9,"<p>I am new to Angular and to unit testing in general and now I can't find a way to test the code in this service below. This is responsable for the creation of a breadcrumb menu. In the Routing Module I have added for every route --&gt; data:{breadcrumb:'custom name'}.</p>
<p>Here is the service code:</p>
<pre><code>import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {IBreadcrumbs} from '../breadcrumb/ibreadcrumbs';
import {ActivatedRouteSnapshot, Data, NavigationEnd, Router} from '@angular/router';
import {filter} from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class BreadcrumbService {

  /// Subject emitting the breadcrumb hierarchy
  private readonly breadcrumbsSub$ = new BehaviorSubject&lt;IBreadcrumbs[]&gt;([]);

  // Observable exposing the breadcrumb hierarchy
  readonly breadcrumbs$ = this.breadcrumbsSub$.asObservable();

  constructor(private router: Router) {
    this.router.events
      .pipe(
        // Filter the NavigationEnd events as the breadcrumb is updated only when the route reaches its end
        filter((event) =&gt; event instanceof NavigationEnd)
      )
      .subscribe((event) =&gt; {
        // Construct the breadcrumb hierarchy
        const root = this.router.routerState.snapshot.root;
        const breadcrumbs: IBreadcrumbs[] = [];


        this.addBreadcrumb(root, breadcrumbs);
        // Emit the new hierarchy
        this.breadcrumbsSub$.next(breadcrumbs);
      });
  }


  private addBreadcrumb(
    route: ActivatedRouteSnapshot | null,
    breadcrumbs: IBreadcrumbs[]
  ) {
    if (route) {
      // Add an element for the current route part
      if (route.data.breadcrumb) {
        const breadcrumb = {
          label: this.getLabel(route.data),
          url: route.url.toString()
        };
        breadcrumbs.push(breadcrumb);
      }
      // Add another element for the next route part
      this.addBreadcrumb(route.firstChild, breadcrumbs);
    }
  }

  private getLabel(data: Data) {
    // The breadcrumb can be defined as a static string or as a function to construct the breadcrumb element out of the route data
    return typeof data.breadcrumb === 'function'
      ? data.breadcrumb(data)
      : data.breadcrumb;
  }


}

</code></pre>
<p>And here is my spec.ts file</p>
<pre><code>import {TestBed} from '@angular/core/testing';

import {BreadcrumbService} from './breadcrumb.service';
import {RouterTestingModule} from '@angular/router/testing';
import {Router, RouterEvent} from '@angular/router';
import {ReplaySubject} from 'rxjs';


fdescribe('BreadcrumbService', () =&gt; {
  let service: BreadcrumbService;
  let routerEventRelaySubject: ReplaySubject&lt;RouterEvent&gt;;
  let routerMock;
  let router: Router;


  beforeEach(() =&gt; {
    routerEventRelaySubject = new ReplaySubject&lt;RouterEvent&gt;(1);
    routerMock = {
      events: routerEventRelaySubject.asObservable()
    };
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      providers: [{provide: Router, useValue: routerMock}]
    });
    service = TestBed.inject(BreadcrumbService);
  });

  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });

});
</code></pre>
<p>I need a coverage of 80% minimum, please help me achieve this.
Thank you in advance.</p>
",https://stackoverflow.com/questions/67670433/unit-testing-with-router-events-angular-9,"['angular', 'typescript', 'unit-testing']",267,False,0,2
React Unit Testing Jest History Push,"<p>I got this Method that I need to Test. I tried to mock the History but I couldn't get it working. I just want to check if there is a Button and if I click on it there should handle the DrawerToggle and push back to Path.</p>
<pre><code>imports...

export const SettingsSidebar = ({ listItems }) =&gt; {
  const gobackPath = (history.location.state as any)?.gobackPath;

some methods...

  return (
...some other Codes

          &lt;DrawerMenu&gt;
            &lt;GoBackButtonLg onClick={() =&gt; history.push(gobackPath)}&gt;Zurück zum Workspace&lt;/GoBackButtonLg&gt;
            &lt;SidebarList&gt;
              &lt;SidebarListItem
                goBackButton
                button
                key={'goback'}
                icon={&lt;GoBackButtonSm icon={faChevronLeft} /&gt;}
                onClick={() =&gt; handleMenuClick(gobackPath)}
              &gt;
                Zurück zum Workspace
              &lt;/SidebarListItem&gt;
              {listItems.map(res =&gt; (
                &lt;SidebarListItem
                  button
                  key={res.name}
                  icon={&lt;FontAwesomeIcon icon={res.icon} /&gt;}
                  onClick={() =&gt; handleMenuClick(res.path)}
                &gt;
                  {res.name}
                &lt;/SidebarListItem&gt;
              ))}
            &lt;/SidebarList&gt;
          &lt;/DrawerMenu&gt;
and so on...
  );
};

export default SettingsSidebar;
</code></pre>
<p><strong>The Test:</strong></p>
<pre><code>imports...

const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () =&gt; ({
  useHistory: () =&gt; ({ push: mockHistoryPush }),
}));

describe('SettingsSidebar', () =&gt; {
    const mockHandleDrawerToggle = jest.fn();
    beforeAll(() =&gt; {
      configure({ adapter: new Adapter() });
    });
 
    it('should have a button', () =&gt; {
      const wrapper = shallow(&lt;SettingsSidebar listItems/&gt;);
      const button = wrapper.find(GoBackButton);
      button.props().onClick();
      expect(mockHandleDrawerToggle).toHaveBeenCalledTimes(1);
    });
  });
</code></pre>
<p><strong>The Failed Message</strong></p>
<p><a href=""https://i.stack.imgur.com/XrwsW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/XrwsW.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/68086562/react-unit-testing-jest-history-push,"['javascript', 'unit-testing', 'jestjs', 'mocking', 'history']",1402,True,-1,1
Angular unit testing catchError in Promise,"<p>I'm testing catchError in Angular service</p>
<pre><code>public async getRegById(id, regId): Promise&lt;Reg&gt; {
    return this.httpClient
      .get&lt;Reg&gt;(
        `TestURL`,
        {
          observe: 'response'
        }
      ).pipe(
        map(response =&gt; {
          return response.body;
        }),
        catchError(err =&gt; {
          return throwError(() =&gt; err);
        }),
      ).toPromise();
  }

</code></pre>
<p>my test is:</p>
<pre><code>    it('it should throw error', async () =&gt; {
      const expectedUrl = `TestURL`;
      getHttpClientSpy.withArgs(expectedUrl, defaultOptions).and.throwError('Test error');
      try {
        await service.getRegById(null, 12);
      } catch (e) {
        expect(e.message).toEqual('Test error');
      }
    });
</code></pre>
<p>test runs as expected but when I run test coverage
it shows that catchError part of test is not covered</p>
<p><a href=""https://i.stack.imgur.com/RtBd9.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/RtBd9.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/69439511/angular-unit-testing-catcherror-in-promise,"['angular', 'unit-testing', 'jasmine']",2127,True,0,1
Unit testing promises triggered by $watch,"<p>I'm using Jasmine to try and test code which has the following pattern:</p>
<p>(this is essentially a paginated database table load)</p>
<pre><code>1. controller calls api on load
2. api.then updates $scope variable
3. controller $watch-es that $scope variable
  a. If new value meets criteria, call api again
  b. api.then updates $scope variable
  c. controller $watch-es the change
    i. eventually new value does not meet criteria and call chain is stopped
</code></pre>
<p>Right now my unit tests have 2 deferred promises. One to return a value that passes the $watch check, one to do the opposite. But, the 2nd promise's <code>then()</code> isn't invoked. Struggling to understand where I need to resolve promises and <code>$digest</code></p>
<p>Check out a simplified plunker: <a href=""https://plnkr.co/edit/543Q5vGJqTYzkSvh"" rel=""nofollow noreferrer"">https://plnkr.co/edit/543Q5vGJqTYzkSvh</a></p>
<p>I'm expecting the <code>$scope.$watch</code> method to log something after the 2nd api call.</p>
<p>What's missing in my unit tests</p>
",https://stackoverflow.com/questions/66272030/unit-testing-promises-triggered-by-watch,"['javascript', 'angularjs', 'unit-testing', 'jasmine']",30,False,0,1
Unit testing Flask-wtfoms with pytest,"<p>This is a follow up to my <a href=""https://stackoverflow.com/questions/68489027/sorting-and-deleting-a-1-to-many-relatiionship-in-sqlalchemy-and-flask"">previous question.</a> I have built the forms and pages and have moved onto testing it with unit testing. However when I try running my unit tests with a new SQLite database test.db it cannot find the tables within and if I use my main data.db it is unable to read the content of <a href=""https://i.stack.imgur.com/4XgSJ.png"" rel=""nofollow noreferrer"">homepage table</a></p>
<p>In my unit_test.py I have the following for the test base</p>
<pre><code>from flask_testing import TestCase
from flask_sqlalchemy import SQLAlchemy
from flask import url_for
import os

from application import app, db
from application.models import Company, Frankendama
class TestBase(TestCase):
def create_app(self):

    app.config.update(
        SQLALCHEMY_DATABASE_URI=&quot;sqlite:///test.db&quot;,
        SECRET_KEY='TEST_SECRET_KEY',
        DEBUG=True,
        WTF_CSRF_ENABLED=False
    )

    return app

def set_up(self):
    db.create_all()

    frank1 = Frankendama(
        title=&quot;Taps&quot;,
        description=&quot;A combo of damas designed for taps&quot;,
        tama=&quot;SK x Cereal STIK&quot;,
        sarado=&quot;Lomond Shape&quot;,
        sword=&quot;Lomond Shape&quot;,
        string=&quot;72&quot;,
        bearing=&quot;Yes&quot;
    )

    company1 = Company(name = &quot;CEREAL&quot;, frankendama_id = 1)
    company2 = Company(name = &quot;SK&quot;, frankendama_id = 1)

    db.session.add(frank1)
    db.session.add(company1)
    db.session.add(company2)

    db.session.commit()

def tear_down(self):

    db.session.remove()
    db.drop_all()
</code></pre>
<p>After the base I have 3 more test classes:</p>
<ul>
<li>TestRead</li>
<li>TestUpdate</li>
<li>TestDelete</li>
</ul>
<p>They look like this:</p>
<p>class TestRead(TestBase):</p>
<pre><code>def test_home(self):
    response = self.client.get(
        url_for('home'),
        follow_redirects= True
        )

    assert &quot;Taps&quot; in response.data.decode()
    assert &quot;Check updated task&quot; in response.data.decode()
    assert &quot;SK x Ceral STIK&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;72&quot; in response.data.decode()
    assert &quot;Yes&quot; in response.data.decode()
    assert &quot;CEREAL&quot; in response.data.decode()
    assert &quot;SK&quot; in response.data.decode()
</code></pre>
<p>class TestUpdate(TestBase):</p>
<pre><code>def test_update(self):
    response = self.client.post(
        url_for('update', id=1),
        data={&quot;description&quot;: &quot;Check updated task&quot;},
        follow_redirects= True
    )

    assert &quot;Taps&quot; in response.data.decode()
    assert &quot;Check updated task&quot; in response.data.decode()
    assert &quot;SK x Ceral STIK&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;72&quot; in response.data.decode()
    assert &quot;Yes&quot; in response.data.decode()
    assert &quot;CEREAL&quot; in response.data.decode()
    assert &quot;SK&quot; in response.data.decode()

    assert &quot;A combo of damas designed for taps&quot; not in response.data.decode()


def test_update_companies(self):
    response = self.client.post(
        url_for('update', id=1),
        data={&quot;companies&quot;: &quot;SWEETS&quot;},
        follow_redirects= True
    )

    assert &quot;Taps&quot; in response.data.decode()
    assert &quot;A combo of damas designed for taps&quot; in response.data.decode()
    assert &quot;SK x Ceral STIK&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;72&quot; in response.data.decode()
    assert &quot;Yes&quot; in response.data.decode()
    assert &quot;SWEETS&quot; in response.data.decode()
    assert &quot;SK&quot; not in response.data.decode()
    assert &quot;CEREAL&quot; not in response.data.decode()
</code></pre>
<p>class TestDelete(TestBase):</p>
<pre><code>def test_delete(self):
    response = self.client.get(
        url_for('delete', id=1),
        follow_redirects=True
    )

    assert &quot;Taps&quot; not in response.data.decode()
    assert &quot;A combo of damas designed for taps&quot; not in response.data.decode()
    assert &quot;SK x Ceral STIK&quot; not in response.data.decode()
    assert &quot;Lomond Shape&quot; not in response.data.decode()
    assert &quot;Lomond Shape&quot; not in response.data.decode()
    assert &quot;72&quot; not in response.data.decode()
    assert &quot;Yes&quot; not in response.data.decode()
</code></pre>
<p>Everytime I try run pytest --cov=app to see the coverage i get these errors:</p>
<pre><code>  sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: frankendama
  ======== 6 failed, 1 passed, 21 warnings in 5.72s =========
  
</code></pre>
<p>Overall I am super stumped, any suggestions are <em>hugely</em> welcome!</p>
",https://stackoverflow.com/questions/68501851/unit-testing-flask-wtfoms-with-pytest,"['python', 'flask-wtforms', 'pytest-cov']",78,True,0,1
PHP unit testing with external functions,"<p>I'm trying to write unit tests for a PHP Wordpress project, but I'm struggling to grasp some of the concepts when it comes to mocking up external function calls and I'm not really sure what I need to do.</p>
<p>Here is a very dumbed down version of the class I have created:</p>
<pre><code>class Module
{
   private $title;

   public __construct($id = false)
   {
      $this-&gt;title = get_the_title($id); // core wp function
   }

   public get_title()
   {
      return $this-&gt;title;
   }

}
</code></pre>
<p>And I want to test it like so:</p>
<pre><code>class ModuleTests extends TestCase
{
   public test_get_title_returns_title_if_id()
   {
      $module = new Module(1);
      $this-&gt;assertSame($module-&gt;get_title(), 'A Test Title'); // should equal true
   }

   public test_get_title_returns_empty_string_if_no_id()
   {
      $module = new Module();
      $this-&gt;assertSame($module-&gt;get_title(), ''); // should equal true
   }
}
</code></pre>
<p>Now obviously this doesn't work in isolation, because Module uses a core wordpress function in the constructor, so what is the correct method for testing in this scenario? Should I be replacing the global get_the_title() function with something that returns a hard coded value if the right arguments are passed to it? or is there some other way of doing this?</p>
<p>I'm trying to drag myself away from the old wordpress procedural style PHP to use some more OOP practices for the bigger projects I work on but I'm still very new to it, so if I'm doing something completely wrong feel free to give constructive critisism as well.</p>
<p>Also, I know that WP already has the template function the_title(), but I'm just using this as a simple example.</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/70073257/php-unit-testing-with-external-functions,"['php', 'wordpress', 'unit-testing', 'testing']",159,True,0,1
Unit-testing variables in the constructor,"<p>In my project I use angular.
Variables are initialized in the constructor of one of the components:</p>
<pre><code>constructor(
  private dialogRef: MatDialogRef&lt;MyComponent&gt;,
  @Inject(MAT_DIALOG_DATA) public data: any,
  private fb: FormBuilder
) {
  this.array1 = this.data.filter(item =&gt; item.active);
  this.array2 = this.data.filter(item =&gt; !item.active);
}
</code></pre>
<p>in component.spec.ts I have:</p>
<pre><code>class MatDialogRefMock {
  close() {
    return {};
  }
}

const matDialogDataMock = [
  {
    id: 1,
    name: 'name',
    active: true
  },
  {
    id: 2,
    name: 'name2',
    active: false
  }
];

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        TestComponent
      ],
      providers: [
        { provide: MAT_DIALOG_DATA, useValue: matDialogDataMock },
        { provide: MatDialogRef, useClass: MatDialogRefMock }
      ],
      imports: [
        FormsModule,
        ReactiveFormsModule,
        HttpClientTestingModule
      ]
    })
    .compileComponents();
  }));

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
<p>I get an error:</p>
<pre><code>TypeError: Cannot read property 'filter' of undefined
</code></pre>
<p>How I can mock the data and remove the error?</p>
<p>P.S. There is a definition of mock data <code>matDialogDataMock</code> and <code>MatDialogRefMock</code> in the code.</p>
<p>Off: I don't know why, when I edit the code, I get the message: 'It looks like your post is mostly code; please add some more details.'</p>
",https://stackoverflow.com/questions/66389665/unit-testing-variables-in-the-constructor,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",1274,True,0,2
Flutter: Unit Testing a Cubit issues,"<p>I have been trying to set up unit testing for my cubit but bloc test seems to be having issues. Just trying to check the initial state of the values works just fine with regular test but as soon as I try to the same thing with bloc test it spits out fail with the actual being an empty list at [0] and I'm not sure what I'm doing wrong. Nothing on the internet is helpful with this error.</p>
<pre><code>//passes
test('initial state of SettingsCubit', () {
  expect(
      settingsCubit.state,
      SettingsState(
          notificationsEnabled: false,
          gpsEnabled: false,
          celsiusEnabled: false,
          expandNavigation: false,
          breakingNewsNotifications: false,
          trendingNotifications: false,
          liveRemindersNotifications: false,
          sportsNotifications: false));
});

//fails
blocTest(
  'initial state of SettingsCubit',
  build: () =&gt; SettingsCubit(),
  expect: () =&gt; [
    SettingsState(
      expandNavigation: false,
      gpsEnabled: false,
      celsiusEnabled: false,
      notificationsEnabled: false,
      breakingNewsNotifications: false,
      trendingNotifications: false,
      liveRemindersNotifications: false,
      sportsNotifications: false,
    )
  ],
);
</code></pre>
<p>Error:</p>
<pre><code>package:bloc_test/src/bloc_test.dart 193:9   testBloc.&lt;fn&gt;
===== asynchronous gap ===========================
dart:async                                   _asyncThenWrapperHelper
package:bloc_test/src/bloc_test.dart         testBloc.&lt;fn&gt;
dart:async                                   runZonedGuarded
package:bloc_test/src/bloc_test.dart 172:9   testBloc
package:bloc_test/src/bloc_test.dart 140:11  blocTest.&lt;fn&gt;
package:bloc_test/src/bloc_test.dart 139:26  blocTest.&lt;fn&gt;
Expected: [
            SettingsState:SettingsState(expandNavigation: false, gpsEnabled: false, celsiusEnabled: false, notificationsEnabled: false,breakingNewsNotifications: false, trendingNotifications: false, liveRemindersNotifications: false, sportsNotifications: false)
          ]
  Actual: []
   Which: at location [0] is [] which shorter than expected
</code></pre>
<p>SettingsCubit and SettingsState code is at:
<a href=""https://stackoverflow.com/questions/68582768/flutter-bloc-test-failures"">Flutter BLoC Test failures</a></p>
",https://stackoverflow.com/questions/68667461/flutter-unit-testing-a-cubit-issues,"['flutter', 'unit-testing', 'bloc', 'bloc-test', 'flutter-cubit']",1484,True,0,1
Testing repository return NullPointerException - Unit Testing,"<p>I'm trying to do testing on a repository using mockito but i got this error
<a href=""https://i.stack.imgur.com/WfeAN.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/WfeAN.png"" alt=""error log"" /></a></p>
<p>this is my repository</p>
<pre><code>interface DiscoverRepository{
  suspend fun trendingMovie():ResultData&lt;Discover?&gt;
}
</code></pre>
<p>and here I wrote the implementation</p>
<pre><code>class RemoteDiscoverRepository @Inject constructor(private val retrofitServices: RetrofitServices) :
DiscoverRepository {

private suspend fun remote(remote:Response&lt;Discover&gt;) : ResultData&lt;Discover?&gt;{
    val request = withContext(Dispatchers.IO) { remote }

    return when(request.code()){
        200 -&gt; ResultData(
            true,
            null,
            request.body()
        )

        else -&gt; ResultData(
            false,
            request.body()?.status_message,
            null
        )
    }
}

override suspend fun trendingMovie(): ResultData&lt;Discover?&gt; {
    return remote(retrofitServices.discover().trendingMovieOfTheDay())
}
}
</code></pre>
<p>this is retrofitService</p>
<pre><code>interface RetrofitServices {
 fun discover(): DiscoverDao
}

class RetrofitServicesImpl @Inject constructor(private val retrofit: Retrofit):RetrofitServices{
  override fun discover(): DiscoverDao {
      return retrofit.create(DiscoverDao::class.java)
  }
}
</code></pre>
<p>and then my repository testing</p>
<pre><code>@RunWith(MockitoJUnitRunner::class)
class DiscoverRepositoryTest {
  @get:Rule
  var instantTaskExecutorRule = InstantTaskExecutorRule()

  @Mock
  private lateinit var discoverRepository: DiscoverRepository

  @Mock
  private lateinit var retrofitServices: RetrofitServices

  private lateinit var remote : RemoteDiscoverRepository

  private val dummy = DiscoverDummy.getDiscover()


  @Before
  fun setup(){
      remote = RemoteDiscoverRepository(retrofitServices)
  } 


  @Test
  fun trendingMovieTest() = runBlocking {
    `when`(remote.trendingMovie()).thenReturn(dummy)
    val trending = discoverRepository.trendingMovie()
    verify(remote).trendingMovie()
    assertNotNull(trending)
    assertEquals(dummy.data?.results?.size, trending.data?.results?.size)
  }
}
</code></pre>
<p>I've been trying to find a solution on the internet, it's been taking a lot of time, please help</p>
",https://stackoverflow.com/questions/68474858/testing-repository-return-nullpointerexception-unit-testing,"['android-studio', 'unit-testing', 'kotlin']",33,False,0,1
Nestjs overrideProvider vs provider in unit testing,"<p>I see two ways of mocking services in NestJS for unit testing, the first one is the same as we define providers in real modules like:</p>
<pre class=""lang-js prettyprint-override""><code>const module = await Test.createTestingModule({
  providers: [
    UserService,
    {
      provide: getRepositoryToken(User),
      useValue: mockUsersRepository,
    }
  ],
}).compile();
</code></pre>
<p>And the other way with <code>overrideProvider</code> method. As following:</p>
<pre class=""lang-js prettyprint-override""><code>const module = await Test.createTestingModule({
  imports: [UserModule]
})
.overrideProvider(getRepositoryToken(User))
.useValue(mockUsersRepository)
.compile();
</code></pre>
<p>What is the difference?</p>
",https://stackoverflow.com/questions/69000993/nestjs-overrideprovider-vs-provider-in-unit-testing,"['unit-testing', 'nestjs', 'nestjs-testing']",4197,True,7,2
JUnit4 with Mockito for unit testing,"<pre><code>public class DgiQtyAction extends DispatchAction {
    private final Logger mLog = Logger.getLogger(this.getClass());

    public ActionForward fnDgiQty(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        mLog.debug(request.getParameter(EcoConstants.ecopidid));
        ActionErrors errorMessage = new ActionErrors();
        if(request.getSession().getAttribute(EcoConstants.userBean)==null)
        {
            request.setAttribute(EcoConstants.ERROR_MESSAGE,EcoConstants.SESSION_TIMEOUT);
            errorMessage.add(Globals.MESSAGE_KEY, new ActionMessage(EcoConstants.error_message,EcoConstants.SESSION_TIMEOUT));
            saveMessages(request, errorMessage); 
            request.setAttribute(EcoConstants.errorMessageType,EcoConstants.errorMessageType);
            return mapping.findForward(EcoConstants.SESSION_FORWARD);
        }
        String ecoPidID = (String) request.getParameter(EcoConstants.ecopidid);
        String pidId = ESAPI.encoder().encodeForHTML((String) request.getParameter(EcoConstants.pidid));

        mLog.debug(&quot;pidid  --------&quot; + pidId);
        mLog.debug(&quot;ecopidpid  --------&quot; + ecoPidID);
        ArrayList dgiQty = new ArrayList();
        NeedDgiForm niForm = new NeedDgiForm();
        try {
            NeedDgiBD niBD = new NeedDgiBD();
            if (ecoPidID != null) {
                dgiQty = niBD.getDgiQty(ecoPidID);
                if (dgiQty.size() != 0) {
                    mLog.debug(dgiQty.get(0).toString());
                    if (dgiQty.get(0).toString().equals(EcoConstants.hundred)) {
                        niForm.setGlqtyList(new ArrayList());
                        request.setAttribute(EcoConstants.pidId, pidId);
                        return mapping.findForward(EcoConstants.SuccessInfo);
                    } else {
                        mLog.debug(&quot;fnBug 1----------------&gt; &quot; + dgiQty.get(0));
                        mLog.info(&quot;dgiQty         sizeeeee: :&quot; + dgiQty.size());
                        niForm.setGlqtyList(dgiQty);
                    }
                }
            }
        } catch (Exception e) {
            //log.error(&quot;General Exception in DgiQtyAction.fnDgiQty: &quot;
            //        + e.getMessage(), e);
            request.setAttribute(EcoConstants.ERROR_MESSAGE, e.getMessage());
            return mapping.findForward(EcoConstants.ERROR_PAGE);
        }
        mLog.debug(&quot;pidid  after wards--------&quot; + pidId);
        request.setAttribute(EcoConstants.pidId, pidId);
        request.setAttribute(mapping.getAttribute(), niForm);
        return mapping.findForward(EcoConstants.SuccessInfo);
    }
}
</code></pre>
<pre><code>public class DgiQtyActionTest {
    ActionMapping am;
    ActionForm af;
    DgiQtyAction dat;
    private MockHttpSession mocksession;
    private MockHttpServletRequest mockrequest;
    private MockHttpServletResponse mockresponse;
    
    @Test
    public void fnDgiQty() throws Exception
    {
        mocksession = new MockHttpSession();
        mockrequest = new MockHttpServletRequest();
        mockresponse = new MockHttpServletResponse();
        ((MockHttpServletRequest) mockrequest).setSession(mocksession);
        mocksession.setAttribute(&quot;userBean&quot;,&quot;userBean&quot;);
         RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(mockrequest));
         mockrequest.addParameter(&quot;ecopid&quot;,&quot;something&quot;);
         mockrequest.addParameter(&quot;pid&quot;,&quot;&lt;script&gt;&quot;);
         Encoder instance = ESAPI.encoder();
         assertEquals(&quot;something&quot;,mockrequest.getParameter(&quot;ecopid&quot;));
         assertEquals(&quot;&amp;lt;script&amp;gt;&quot;,instance.encodeForHTML(mockrequest.getParameter(&quot;pid&quot;)));
         dat=mock(DgiQtyAction.class);
         am=mock(ActionMapping.class);
         af=mock(ActionForm.class);
         dat.fnDgiQty(am,af,mockrequest,  mockresponse);
    }
}
</code></pre>
<p>I wrote the unit test case for above class. i ran this code through jenkins and used sonarqube as code coverage.I need to cover the ESAPi encoder for the parameter, it got build success but the coverage percentage doesn't increase. i couldn't found the mistake in it. pls help me guys. Thanks in Advance</p>
",https://stackoverflow.com/questions/68972257/junit4-with-mockito-for-unit-testing,"['session', 'junit', 'mockito', 'springmockito', 'activityunittestcase']",116,False,0,0
Unit testing for uncurry in ocaml,"<p>my implementation so far I cant seem to understand where is the issue</p>
<pre><code>let uncurry_test1 _test_ctxt =
    assert_equal
    uncurry  f  (4 3)
    7
    
</code></pre>
",https://stackoverflow.com/questions/70037523/unit-testing-for-uncurry-in-ocaml,"['ocaml', 'ounit']",150,False,-1,1
Issues while Unit testing in c#,"<p>I have a class Library project which will be consumed by some legacy code and some modernized code. briefly I would like to show what issues I am facing with.</p>
<pre><code>class ClasslibraryService
{
    private Dependency1 _dependency1;
    private Dependency2 _dependency2
    public  ClasslibraryService(Dependency1 dependency)
    {
        _dependency1 = dependency;
         // this dependency2 could be something like logger or Bearer token service which I do not want to expose to consuming application
        _dependency2 = new Dependency2(new Dependency3());
    }
    public int DoSomeOperation()
    {
        var res = _dependency2.DoSomething();
        return _dependency1.DoSomeOperation(res);
    }
} 
</code></pre>
<p>So basically I had to new up within constructor without injecting dependency using constructor.</p>
<p>Now while unit test this class , I have created another constructor which takes all dependency through constructor. This is working fine.</p>
<p>But question here is</p>
<ol>
<li>I know I am violating main objective of unit testing by creating another constructor.Actual code will not be using this constructor. But I could not find any other way too!!</li>
<li>If 1 is not correct solution , please suggest me one solution</li>
</ol>
<p>TIA</p>
",https://stackoverflow.com/questions/68643396/issues-while-unit-testing-in-c,"['c#', '.net', 'unit-testing', 'moq']",85,True,0,1
Unit testing lambda function with Jest,"<p>I am new to Jest (so I am still figuring everything out) and I am trying to unit test a lambda function to upload an object to s3. This works fine and the test passes.</p>
<pre><code>exports.lambdaHandler = async (event) =&gt; {

    // I need to be able to access the value of the &quot;upload&quot; variable 
    // directly from my test
    // Something like...
    // const returnValue = await S3Upload.lambdaHandler(mEvent).upload;

    const upload = await uploadToS3(event);

    // I will need to return other data from this lambda function which 
   // will be passed in the payload of my step function, instead of just 
   // returning &quot;upload&quot; simply so the test can access it. For example;

    return {
    name: name,
    age: age
  };
    
   Instead of...

    return upload;


};

async function uploadToS3(event) {

        let cat = {
            name : 'Bertie',
            breed : 'Cymric',
            color : 'white'
          }
    

        // Write the json version of the cat javascript object to S3
        const params = {
            Bucket: 'myBucket',
            Key: prefix, // file Key
            Body: JSON.stringify(cat),
            ServerSideEncryption: &quot;AES256&quot;,
            Tagging: 'myTags'
        };

     
        const key = await s3
            .putObject(params
            )
            .promise();

        return key;
}
</code></pre>
<p>...and the test</p>
<pre><code>const S3Upload = require('../../app');

const AWS = require('aws-sdk')
const s3 = new AWS.S3()

let cat1 = {
  name : 'Bertie',
  breed : 'Cymric',
  color : 'white'
}

jest.mock('aws-sdk', () =&gt; {
  const putObjectOutputMock = {
    promise: jest.fn(),
  };
  const putObjectMock = jest.fn(() =&gt; putObjectOutputMock);


  const mS3 = {
    putObject: putObjectMock,
  };
  return { S3: jest.fn(() =&gt; mS3) };
});

describe('61719699', () =&gt; {
  it('should put object', async () =&gt; {
    const mS3 = s3;
    const mPutObjectResponse = {
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': true,
      },
      body: undefined,
    };
    mS3.putObject().promise.mockResolvedValueOnce(mPutObjectResponse);

    const mEvent = { queryStringParameters: { value: 'test' }, body: { newStuff: 'stuff goes here', eventList: [] } };

    const returnValue = await S3Upload.lambdaHandler(mEvent);
    expect(returnValue).toEqual({
      statusCode: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Credentials': true,
      },
      body: undefined,
    });

    expect(mS3.putObject).toBeCalledWith({
      Bucket: 'myBucket',
      Key: 'myKey',
      Body: JSON.stringify(cat1),
      ServerSideEncryption: &quot;AES256&quot;,
      Tagging: 'myTags'
    });
  });
});
</code></pre>
<p>However, I need to return some other data in the handler's return statement, so I want my test to access the result of the &quot;uploadToS3&quot; function directly. I can't figure out how to do this from my test. If anyone could help me out, I'd really appreciate it.</p>
",https://stackoverflow.com/questions/67408352/unit-testing-lambda-function-with-jest,"['node.js', 'unit-testing', 'aws-lambda', 'jestjs']",1834,False,0,0
Unit testing of complex objects C#,"<p>I wrote a short application, but I ran into the problem of writing a unit test Method MaximumRowSum_DefectiveLines. Please tell me how I should act, my class for testing</p>
<pre><code>public class OutputtingStrings
{
    public class MaxSumLineResult
    {
        public int MaxSumLineIndex { get; set; }
        public List&lt;string&gt; DefectiveLines { get; set; }
        public override string ToString()
        {
            return $&quot;Line number with maximum sum of elements: { MaxSumLineIndex + 1}&quot;; /* + &quot;\n&quot; +
                 $&quot;Defective lines:{string.Join(&quot;\n&quot;, DefectiveLines)}&quot;;*/
        }
    }

    public static bool IsValidateFileExist(string filePath)
    {
        if (File.Exists(filePath))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public MaxSumLineResult MaximumRowSum_DefectiveLines(string[] fileData)
    {
        List&lt;string&gt; defectiveLines = new List&lt;string&gt;();
        int lineNumber = 0;
        var indexOfLines = new Dictionary&lt;int, double&gt;();
        foreach (var line in fileData)
        {
            NumberStyles style = NumberStyles.Number;
            CultureInfo culture = CultureInfo.CreateSpecificCulture(&quot;en-GB&quot;);

            var stringElements = line.Split(&quot;,&quot;,  StringSplitOptions.RemoveEmptyEntries);
            if (stringElements.Any(n =&gt; double.TryParse(n, style, culture, out var number)))
            {
                indexOfLines.Add(lineNumber, stringElements.Sum(n =&gt;
                {
                    return double.Parse(n, style, culture);
                }));
            }
             else  
            {
                 defectiveLines.Add(line);
            }

            lineNumber++;

        }
        var maxSumLineIndex = indexOfLines.FirstOrDefault(x =&gt;
           x.Value == indexOfLines.Values.Max()).Key;

        var resultLines = new MaxSumLineResult
        {
            MaxSumLineIndex = maxSumLineIndex,
            DefectiveLines = defectiveLines
        };

        return resultLines;
    }
}
</code></pre>
<p>My unit testing class:</p>
<pre><code>[TestClass]
public class UnitTestOutputtingStrings
{
    [TestMethod]
    public void Should_FindingMaximumRowSum_TheFileIsValidAndReadable()
    {
        /* Arrange*/
        var maxsumlineresult = new MaxSumLineResult();
        var sut = new OutputtingStrings();

        /* Act*/

        /* Assert*/
    }
}
</code></pre>
<p>I have read the book &quot;The Art of Unit Testing. With Examples in C#&quot;. I understand the principles, but I do not know how to work with complex classes. Thank you guys in advance, I will be glad to every answer or link to a source with materials on unit testing.</p>
",https://stackoverflow.com/questions/66854304/unit-testing-of-complex-objects-c,"['c#', '.net', 'unit-testing']",323,False,-1,1
Post request for CI4 Unit testing,"<p>I have the following code running in CI 4.1.2:</p>
<pre><code>public function testForgotten(){

    fwrite(STDERR,&quot;\n\nProcess Forgotten:\n&quot;);

    $_COOKIE[csrf_token()] = csrf_hash();

    $result = $this-&gt;post('site/forgotten',array(
        'Username'      =&gt; 'my@email.com',
        csrf_token()        =&gt; csrf_hash(),
    ));

    print'&lt;pre&gt;';print_r($result-&gt;response());print'&lt;/pre&gt;';

    $result-&gt;assertRedirect();
}
</code></pre>
<p>As you can see I simply want to check if the forgotten password form/page is working. However the output of <code>$result-&gt;response()</code> includes the unposted to page along with <code>&lt;form action=&quot;http://example.com/site/forgotten&quot; id=&quot;Config\Forms::reset&quot; enctype=&quot;multipart/form-data&quot; method=&quot;post&quot; accept-charset=&quot;utf-8&quot;&gt;</code> as part of the form (noting <strong>I've not put in the example.com - Codeigniter did that!</strong> So just wondering what I'm missing in terms of getting this test to run/work?</p>
<p>FYI I'm running under a PHAR file with <code>php punit.phar tests/app/Controllers/SiteTests.php</code> which works fine when running simple <code>get('/path/to/page');</code> calls.</p>
<p>I have since found the example.com can be changed in <code>phpunit.xml.dist</code> but this has still not fixed the assertRedirect issue.</p>
",https://stackoverflow.com/questions/67805700/post-request-for-ci4-unit-testing,"['codeigniter', 'codeigniter-4']",692,True,0,2
JEST unit testing for $.get request,"<p>I have a code in React</p>
<pre><code>$.get('/bin/data', (response) =&gt; {
            this.data = response;
        });
</code></pre>
<p>This is my test case:</p>
<pre><code>$document = {
            on: jest.fn().mockName('$document.on'),
        };

        expect(window.$).toBeUndefined(); 
        $ = jest.fn().mockName('$').mockReturnValue($document);
        $.get = () =&gt; {};
        jest.spyOn($, 'get').mockName('$.get').mockImplementation(response =&gt; jest.fn()); // not sure what to do here such that callback function is also covered

        window.$ = $;
</code></pre>
<p>Everything is working fine, but the callback function is not getting covered.</p>
",https://stackoverflow.com/questions/65829125/jest-unit-testing-for-get-request,"['javascript', 'reactjs', 'unit-testing', 'ecmascript-6', 'jestjs']",150,False,-1,1
Angular Unit testing ControlValueAccessor with ngFor,"<p>How to test ngFor elements when using inside of ControleValueAccessor.</p>
<pre><code>@Component({
  selector: 'checkbox-group',
  templateUrl: `
&lt;h3 class=&quot;tt&quot;&gt;s&lt;/h3&gt;
&lt;ng-container *ngFor=&quot;let item of _model;let i = index&quot; &gt;  &lt;h3&gt;s&lt;/h3&gt;
  &lt;div&gt;
      &lt;input type=&quot;checkbox&quot; id=&quot;c{{i}}&quot;/&gt;
  &lt;/div&gt;
&lt;/ng-container&gt;

`,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() =&gt; CheckboxGroupComponent),
      multi: true
    }
  ]
})

export class CheckboxGroupComponent implements ControlValueAccessor {
  constructor(private ref: ChangeDetectorRef) {
    ref.detach();
  }
  writeValue(value: any): void {
    this._model = value;
    if(value != null) { this.ref.detectChanges();
  }
}
</code></pre>
<p>And from parent settings.html this controle value accessor is imported:</p>
<pre><code>&lt;div&gt;
  &lt;checkbox-group [(ngModel)]=&quot;selectedItems&quot;&gt;&lt;/checkbox-group&gt;
&lt;/div&gt;
</code></pre>
<p>Now when I want to test it, it just has one child element. and just know  tag as first and last child element</p>
<p>setting.spec.ts:</p>
<pre><code>TestBed.configureTestingModule({
      declarations: [ SettingsPage, CheckboxGroupComponent ],
      imports: [IonicModule.forRoot()],
      providers: [
        {
          provide: NG_VALUE_ACCESSOR,
          useExisting: forwardRef(() =&gt; CheckboxGroupComponent),
          multi: true
        }
        // other providers
      ],
      schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents();

it('should get checkBoxGroup Childs', fakeAsync(() =&gt; {  
    let customComponent = fixture.nativeElement.querySelector('checkbox-group');
    component.selectedItems = [true,true,true];
    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; {
      customComponent.NgModule=[true,false,true];
      fixture.detectChanges();
      debugger;        
    }); 
}))
</code></pre>
<p>debug on customComponent:</p>
<p><a href=""https://i.stack.imgur.com/QIzx7.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/QIzx7.png"" alt=""debug on customComponent"" /></a></p>
",https://stackoverflow.com/questions/68473393/angular-unit-testing-controlvalueaccessor-with-ngfor,"['angular', 'jestjs', 'jasmine', 'angular-test', 'angular2-changedetection']",1095,False,0,1
Custom #define macro for unit testing,"<p>I have a function that is returning the condition of a macro, and for unit testing I want to be able to determine what this macros value is.</p>
<p>Currently I have,</p>
<pre class=""lang-c prettyprint-override""><code>#define READ_PORT ReadingPortStatus(SOME_OTHER_CONDITION)

#ifdef UNIT_TEST
bool READ_PORT_flag_UT;
#endif

void ReturnPortCondition()
{
#ifdef UNIT_TEST
#undef READ_PORT
    if (READ_PORT_flag_UT)
    {
        #define READ_PORT 1
    }
    else
    {
        #define READ_PORT 0
    }
#endif

    if (READ_PORT)
    {
        return(GOOD_READ);
    }
    else
    {
        return(BAD_READ);
    }
}
</code></pre>
<p>And in my unit test file I would use it as follows,</p>
<pre class=""lang-c prettyprint-override""><code>extern READ_PORT_flag_UT;

READ_PORT_flag_UT = true // Because I want ReturnPortCondition() to return true
bool result = ReturnPortCondition();
</code></pre>
<p>However, it is not working as I expect, it is only returning the last define of the port, which in this case is 0. the if else statements are not working in this context.</p>
",https://stackoverflow.com/questions/67940936/custom-define-macro-for-unit-testing,"['c', 'unit-testing']",688,True,0,1
Issue in .Net Core unit testing,"<p>I have a console app which contains 2 classes and create unit test project with it</p>
<pre><code>class Program
{
    
    static void Main(string[] args)
    {
        Console.Write(&quot;Triangle Type Test :-\n----------------------------\n\n&quot;);
        Trigonometric.TrianlgeSidesInput(12, 12, 12);
        Console.ReadLine();

        Trigonometric.TrianlgeSidesInput(12, 12, 15);
        Console.ReadLine();

        Trigonometric.TrianlgeSidesInput(12, 20, 25);
        Console.ReadLine();
    }
}

public static class Trigonometric
{
    public static double eqSide1, eqSide2, eqSide3;
    public static void TrianlgeSidesInput(double side1, double side2, double side3)
    {
        string TriangleType = &quot;&quot;;
        if ((side1 == side2) &amp;&amp; (side1 == side3))
        {
            TriangleType = &quot;Equilateral&quot;;
        }
        else if ((side1 == side2) || (side1 == side3) || (side2 == side3))
        {
            TriangleType = &quot;Isosceles&quot;;
            eqSide1 = side1; eqSide2 = side2; eqSide3 = side3;
        }
        else
        {
            TriangleType = &quot;Scalene&quot;;
        }

        switch (TriangleType)
        {
            case &quot;Equilateral&quot;:
                Console.WriteLine(&quot;It is Equilateral Traingle ! Reason: It's all sides are equal.\n\n\t i. e. {0}=={1}==                                 {2}&quot;, side1, side2, side3);
                Console.WriteLine(&quot;For Next : Press Enter \n&quot;);

                break;

            case &quot;Isosceles&quot;:
                Console.WriteLine(&quot;It is Isosceles Traingle ! Reason: It's two sides are equal.&quot;);
                Console.WriteLine(&quot;For Next : Press Enter \n&quot;);
                break;

            case &quot;Scalene&quot;:
                Console.WriteLine(&quot;It is Scalene Traingle ! Reason: It's all sides have different lenght !!&quot;);
                Console.WriteLine(&quot;For Next : Press Enter \n&quot;);
                break;

            default:
                Console.WriteLine(&quot;Sorry ! Try Again !&quot;);
                break;
        }

    }
}
</code></pre>
<p>packages in .csproject</p>
<pre><code>Microsoft.NET.Test.Sdk
MSTest.TestAdapter
MSTest.TestFramework
coverlet.collector
</code></pre>
<p>It is not recognizing Test Class and Test Method. The test project is created dotnet new mstest command and errors exists in build in template
kindly help me in resolving this issue</p>
",https://stackoverflow.com/questions/69419155/issue-in-net-core-unit-testing,"['c#', 'unit-testing', '.net-core', 'console-application']",60,False,-1,1
Unit testing : Why is it necessary,"<p>Hello I will try to explain what is my actual understanding of unit test and why I have problems to grasp it's utility.</p>
<p>Even if I try my hardest to understand the concept of TTD, unit test, integration test, etc. From the most articles that I read it explain HOW to do it (with a trivial example or a framework) and sometimes how the tests saved them hours of debug in certain situation. And I have two problems with that :</p>
<p><strong>First : the method</strong></p>
<p>Let's use a basic example for the explaination of how to do a unit test :</p>
<blockquote>
<p>You want to test that your add function works as expected so in your test files you write a mock of your function with an expected output lets say something like that :</p>
<pre><code>import add from ./calculate
function myTestingFunction() {
    add(3, 5)
    expectedOutput(8)
}
</code></pre>
</blockquote>
<p>Okay so you explain me how to do it but not why... and even with that, I have multiple questions :</p>
<ul>
<li>You're testing a function with another function ... so why did you stop there and test the function you just created ?</li>
<li>It's code, it has algorithm so how to be sure it is correctly written
?</li>
<li>And why stop with the expected output ? Why not testing that the
input are of the correct type, because if I give charcarters to my
add function it will fail, no ?</li>
</ul>
<p>And every article is basically like that. So with that questions in mind I cannot find the motivation to even try this methods : it's just don't seems logic.</p>
<p><strong>Second : Tests are time and money saving</strong></p>
<p>Let's say now I want to test the <em>Divide</em> function the same way and write and expected output of 3 for the input 9 and 3.</p>
<p>Okay so I write the same function than explained before.
But if the user tries to divide by 0 a serious bug will logically occur for him ... this test doesn't covers this case and I'm writing test to ensure my code works well (or at least give the correct outputs).</p>
<p>In real life I now see two situation :</p>
<ul>
<li>I had explained to my client that I will take more time to code (so he will pay me more) but as a result he will be sure that in final his functions are bullet proof. And here I'm saying to him &quot;Well ... sorry I didn't think about this use case&quot; &quot;So I pay you more because you said that the tests you've written will ensure a bug free app... but it's not ? And now I have to pay you to debug it ?&quot; (so no time and money save and a bad relation with my client)</li>
<li>I had coded the functionnality as explained and understood by me and my client. The new use case occur that we were'nt aware of. 'Kay no problem : I pull a branch to bug fix, fix the bug, push the hotfix, document the special use case if needed. And now in the future if I encounter an equivalent problematic I will have the algorithm already prepared because I faced the issue (time and money save for me and my client and a better relation overall)</li>
</ul>
<p>I don't know if I'm clear about my state of mind but I've discussed these elements with many of my colleagues (some even with more years of practice or a better school degree than me) and they had the same problem than me about test : even if we really want to understand this topic and implement a good way of working if needed, as of now i'ts seems like some sort of intelectual pride.</p>
",https://stackoverflow.com/questions/70536951/unit-testing-why-is-it-necessary,"['unit-testing', 'testing']",34,True,-1,1
unit testing: send parameters to endpoint,"<p>my question is how to send parameter to my endpoint.</p>
<p>test</p>
<pre><code>public function test_upgrade()
    {
       
        
        $billingChange3 = factory(Plan::class)-&gt;create([
            'user_id' =&gt; 1,
            'previous_price' =&gt; 150,
            'current_price' =&gt; 100,
        ]);
       
        $url = route(
            'users.filters'
        );
        $response = $this-&gt;actingAs($this-&gt;admin)-&gt;getJson($url,['search'=&gt;'upgrade']);
        $response-&gt;assertStatus(200);
        //till here correct 
        //but here it should return 2 since I have upgrade count 2  as correct it gives error
my api response is wrapped within data, so i have used data below
        $response-&gt;assertJsonCount(2,'data');
    }


   
</code></pre>
<p>my seach keyword can be any thing such as upgrade,downgrade<code>etc.  upgrade is when</code>current_price&gt;previous_price``` and I have logic for that in controller</p>
<p>My vue dev tool shows url as below:
first:<code>&quot;https://localhost:800/users/plan?filter=upgrade&amp;page=1&quot;</code>
In test I have passed params as getJson($url,['search'=&gt;'upgrade']
Is that the correct way to pass paramters?</p>
",https://stackoverflow.com/questions/68665789/unit-testing-send-parameters-to-endpoint,"['php', 'laravel', 'unit-testing']",289,True,0,1
Global Reliance Making Unit Testing Impossible,"<p>Background:
I am a hobbyist Python coder whose first and only project is a text-based Adventure Game <strong>Engine</strong> (<a href=""https://github.com/zig13/scenzig"" rel=""nofollow noreferrer"">https://github.com/zig13/scenzig</a>).
An Adventure Game is a common first project but I realised I didn't have the creativity to write an adventure so decided instead to write a framework so someone else could do the adventure bit.
It started out as a monolithic script with no functions - at one point 712 lines long - but as I have learnt Python it has been repeatedly rewritten.</p>
<p>I recently learned of the concepts of unit testing and logging and I think they would be really helpful to me going forward but I have hit a snag.
The majority of my functions need access to the Adventure files and/or Character file to function.
These are accessed as a dictionary (thanks to ConfigObj) and a reference to the dictionaries is passed among the modules like this:</p>
<pre><code>def GiveAdv(a) :
    global adv
    adv = a
    efunc.GiveAdv(a)
def GiveChar(c) :
    global char
    char = c
    argsolve.GiveChar(char)
    efunc.GiveChar(c)
</code></pre>
<p>i.e. After importing another module, a module passes on it's reference to the adventure files and character files. Later in the same module <code>adv.f['Actions'][str(action)]</code> is used to get the information on a specific action from the Actions file for example.</p>
<p>I've never liked this but it has been <em>fine</em> until now but is a problem now because:</p>
<ol>
<li>I am trying to merge two modules rewriting much from scratch in the process and I have no way of testing as I go as everything is so inter-connected</li>
<li>Unit testing relies on a function taking arguments and producing outputs but most of mine also expect to have access to information in addition to their arguments</li>
</ol>
<p>As I see it, Logging (using the logging module) would require somehow passing a reference to the log file around and I just can't believe that people would resort to my horrible &quot;Give&quot; function solution so there must be a better way.</p>
<p>What is the Pythonic way of giving disparate modules access to the same information, class instances and loggers?</p>
",https://stackoverflow.com/questions/66339916/global-reliance-making-unit-testing-impossible,"['python', 'python-3.x', 'unit-testing', 'logging']",246,False,0,0
flutter: unit testing dao in moor,"<p>I've started unit testing the first time. I'm following tutorials of <a href=""https://github.com/ResoCoder/flutter-tdd-clean-architecture-course"" rel=""nofollow noreferrer"">resoCoder</a></p>
<p>here is my test code where I'm mocking my dbManager class but I could not mock DAO's as they are auto-generated in moor and there is no setter method for them.</p>
<pre><code>class MockDbManager extends Mock implements DbManager{}

void main() {
  RecipeLocalDataSource dataSource;
  MockDbManager _dbManager;
  setUp(() {
    _dbManager = MockDbManager();
    dataSource = RecipeLocalDataSource(_dbManager);
  });

  group('Search Food Table', (){
    List&lt;FoodTableData&gt; getFoodTable(){
      var list = [];
      for(var i =1; i &lt;=5 ; i++){
        list.add(FoodTableData(id: i, name: 'item $i'));
      }
      return list;
    }
    var searchQuery = 'query';

    test('Should return foodTableData when query is successful', (){
      //arrange
      when(_dbManager.foodTableDao.searchFoods(searchQuery)).thenAnswer((realInvocation) async =&gt; getFoodTable());
      //act
      var result = dataSource.searchFoodTable('test');
      //assert
      verify(_dbManager.foodTableDao.searchFoods(searchQuery));
      expect(getFoodTable(), result);
    });
  });
}
</code></pre>
<p>I'm getting the following error</p>
<pre><code>NoSuchMethodError: The method 'searchFoods' was called on null.
Receiver: null
Tried calling: searchFoods(&quot;query&quot;)
</code></pre>
<p>I understood the error but don't know how to solve that.</p>
<p>Also, I'm getting a similar issue with preferenceManager class as well, where I'm having a getter for UserPrefs.</p>
<pre><code>UserPrefs get user =&gt; UserPrefs(_pref);
</code></pre>
<p>when I'm accessing <code>_prefManager.user.name</code> for the test, it throws the same error. How can I tackle that as well?</p>
",https://stackoverflow.com/questions/65561079/flutter-unit-testing-dao-in-moor,"['unit-testing', 'flutter', 'flutter-moor']",644,True,0,1
Unit testing an outgoing query message,"<p>I have adapted for Python an example taken from <a href=""https://www.youtube.com/watch?v=URSWYvyc42M&amp;t=1229s"" rel=""nofollow noreferrer"">&quot;The Magic Tricks of Testing&quot; by Sandi Metz</a>. Suppose I have this:</p>
<pre class=""lang-py prettyprint-override""><code>class Gear:
    def __init__(self, wheel=Wheel()):
        self.wheel = wheel

    def get_gear_inches(self):
        self._get_ratio() * self.wheel.get_diameter()
</code></pre>
<p>Now I want to write unit tests for the <code>get_gear_inches()</code> method.
In &quot;The Magic Tricks of Testing&quot;, Sandi Metz suggests not to set expectations on the return value of <code>wheel.get_diameter()</code> (which is an outgoing query), because this would bind us to the implementation, while we only care about the returned results. So we are just supposed to test the returned value, like this:</p>
<pre class=""lang-py prettyprint-override""><code>def test_get_gear_inches():
    gear = Gear()
    assert gear.get_gear_inches() == 12  # For example
</code></pre>
<p>But I'm a bit confused.</p>
<ol>
<li>Isn't this an integration test? It seems to me like we're testing the behaviour of two components (<code>Gear</code> and <code>Wheel</code>), not just one.</li>
<li>Also, what if this outgoing query (<code>self.wheel.get_diameter()</code>) is reaching the db and takes a long time?</li>
</ol>
<p><strong>What's the &quot;correct&quot; way to test this?</strong></p>
<hr />
<p>Note: my alternative would have been to set expectations and mock the behaviour of <code>Wheel.get_diameter()</code>, like this:</p>
<pre class=""lang-py prettyprint-override""><code>def test_get_gear_inches():
    wheel_mock = Mock()
    wheel_mock.get_diameter.return_value = 123  # We avoid calling the actual implementation
    gear = Gear(wheel_mock)
    
    assert Gear().get_gear_inches() == 12  # For example
</code></pre>
<p>But in the video this is discouraged as far as I understand.</p>
",https://stackoverflow.com/questions/69704952/unit-testing-an-outgoing-query-message,"['python', 'unit-testing', 'testing']",75,False,0,1
unit testing styled component in react,"<p>I have a HTML button styled using styled component library and I am writing a unit test for it. The POC code looks like this:</p>
<pre><code>const StyledButtonComponent = () =&gt; {
const [testText, setTestText] = React.useState();

const clickHandler = (e) =&gt; {
  e.preventDefault();
  setTestText('Lorem Ipsum')
  console.log('Button Clicked!');
}

return (
 &lt;&gt;
    &lt;TestButton onClick={clickHandler} data-test=&quot;component-styled-button&quot;&gt;
    Click Me!!
    &lt;/TestButton&gt;
   &lt;p data-test=&quot;text-tag&quot;&gt;{testText}&lt;/p&gt;
 &lt;/&gt;
);
}
</code></pre>
<p>Here TestButton is a styled component.</p>
<p>And my unit test code is:</p>
<pre><code>describe('Styled Button Component', () =&gt; {
let wrapper;
const setup = () =&gt; mount(&lt;StyledButtonComponent /&gt;)
const findByAttr = (wrapper, val) =&gt; {
   return wrapper.find(`[data-test='${val}']`)
}

beforeEach(() =&gt; {
  wrapper = setup();
});

it('should render the styled button component without errors', () =&gt; {
  const btnComponent = findByAttr(wrapper, 'component-styled-button');
  expect(btnComponent).toHaveLength(2);
});

it('should allow user to click on the styled button', () =&gt; {
  const btnComponent = findByAttr(wrapper, 'component-styled-button');
  btnComponent.simulate('click', { preventDefault() {}})
  const pTag = findByAttr(wrapper, 'text-tag');
  expect(pTag.render().text()).toBe('Lorem Ipsum')
});
});
</code></pre>
<p>But for the second test I am getting an error:</p>
<p>Method “simulate” is meant to be run on 1 node. 2 found instead.</p>
<p>So what is the correct way to test components rendered using Styled Component?</p>
",https://stackoverflow.com/questions/68204576/unit-testing-styled-component-in-react,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'enzyme']",90,True,0,1
Unit testing specific components in Angular,"<p>In My Angular project, I have an Angular project within a parent Angular project - So the second angular project(Child) is like a module app. When I test the application it always takes the parent <code>app.component.spec.ts</code> for tests within Jasmine Karma. I have tried navigating via the terminal to the specific folder and run <code>ng test</code> but still the parent <code>app.component.spec.ts</code> gets tested?</p>
<p>Any idea's how to just test specific components?</p>
",https://stackoverflow.com/questions/66592556/unit-testing-specific-components-in-angular,"['angular', 'unit-testing']",100,False,-1,1
Unit Testing Http Calls in Angular,"<p>I am using Angular 9+.</p>
<p>While <code>unit testing</code> services that implement <strong><code>httpClient</code></strong> and make http requests, I referred this <a href=""https://angular.io/guide/http#testing-http-requests"" rel=""nofollow noreferrer"">documentation</a> by Angular Team. I followed the process and got success in the unit tests also.
Following is the code (taken from the doc):</p>
<pre><code>it('can test HttpClient.get', () =&gt; {
  const testData: Data = {name: 'Test Data'};

  // Make an HTTP GET request
  httpClient.get&lt;Data&gt;(testUrl)
    .subscribe(data =&gt;
      // When observable resolves, result should match test data
      expect(data).toEqual(testData)
    );

  // The following `expectOne()` will match the request's URL.
  // If no requests or multiple requests matched that URL
  // `expectOne()` would throw.
  const req = httpTestingController.expectOne('/data');

  // Assert that the request is a GET.
  expect(req.request.method).toEqual('GET');

  // Respond with mock data, causing Observable to resolve.
  // Subscribe callback asserts that correct data was returned.
  req.flush(testData);

  // Finally, assert that there are no outstanding requests.
  httpTestingController.verify();
});
</code></pre>
<p>My question is:</p>
<ul>
<li><p>Since <code>http calls</code> are <code>asynchronous</code>, why is not fakeAsync() written in any of the tests provided in the docs? Like normally when unit testing <strong><code>asynchronous methods</code></strong> ( <code>setTimeout() , setInterval()</code> ), the docs provided in angular shows that we need a fake zone.js which appends all the async requests to an array and then we use flushMicrotasks() or tick() to further facilitate the calls.</p>
</li>
<li><p>How is the control flow happening when <code>req.flush()</code> is called? We have made a call to the function <code>httpClient.get&lt;Data&gt;(testUrl)</code> which subscribes to the observable and and <strong>flush</strong> is used to just resolve it. So the entire flow in the test spec is happening async / sync?</p>
</li>
</ul>
",https://stackoverflow.com/questions/66208828/unit-testing-http-calls-in-angular,"['angular', 'unit-testing', 'jasmine', 'httprequest']",2211,True,0,1
Unit testing Smtpclient mock Send method,"<p>Is there any way to mock <code>Send(System.Net.Mail.MailMessage message)</code> method to do nothing when called?
I'm creating SmtpClient using 2 parameters constructor and sending a message like</p>
<pre><code>using(var client = new SmtpClient(host, port)){
client.Send(message);
}
</code></pre>
<p>I don't really need to test it, just want to skip it and move on.
For testing, I'm using XUnit and Moq.</p>
",https://stackoverflow.com/questions/66143928/unit-testing-smtpclient-mock-send-method,"['c#', '.net', 'unit-testing', 'mocking', 'moq']",691,False,0,1
wicket 9: unit testing + mockito + httpSession,"<p><strong>A Situation</strong></p>
<p>I'm using wicket 9 for a web gui development. And now I'm trying to do some junit testing by mocking (mockito) methods that are not essential. One of those methods is</p>
<pre><code>httpSession.getAttribute(&quot;loginName&quot;);
</code></pre>
<p>which gets called like this:</p>
<pre><code>public class MyPanel {
         ...

     SecureWebSession session = (SecureWebSession) getSession(); &lt;--returns a SecuredWebSession
     Label username = new Label(&quot;loginName&quot;, session.getLoginName()); &lt;-- NullPointerException
        ...
}
</code></pre>
<p>Obviously, something is not right with how I'm mocking things. I expect it to return test, but all I get at all times is a NullPointerException.</p>
<p>My question is how can I bypass session.getLoginName() so, that the call would return
a login name test?</p>
<p>How to mock httpSession while testing wicket application?</p>
<p><strong>Details</strong></p>
<p>I have a securedWebSession class</p>
<pre><code>package com.my.app.application;

import com.my.app.service.signOnService;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.request.Request;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

public class SecureWebSession extends AuthenticatedWebSession {

    @SpringBean(name = &quot;authenticationManager&quot;)
    private AuthenticationManager authenticationManager;

    @SpringBean(name = &quot;signOnService&quot;)
    private SignOnService signOnService;

    private final HttpSession httpSession;

    private final Request request;

    public SecureWebSession(Request request) {
        super(request);
        this.request = request;
        //******************THIS I CANNOT BYPASS***************************************START
        this.httpSession = ((HttpServletRequest) request.getContainerRequest())
                .getSession(false);
        //******************THIS I CANNOT BYPASS******ALLWAYS RETURNS NULL*************END
        
        Injector.get().inject(this);
    }

    @Override
    public boolean authenticate(String username, String password) {
        return true;
    }

    private boolean hasSignedIn(Authentication authentication) {
        return authentication.isAuthenticated();
    }

    @Override
    public Roles getRoles() {
        Roles roles = new Roles();
        roles.add(&quot;SUPER_ADMIN&quot;);
        return roles;
    }

    public String getLoginName() {
     ********RETURNS NULL.getAttribute(&quot;loginName&quot;)******
        return (String) httpSession.getAttribute(&quot;loginName&quot;);
    }
}
</code></pre>
<p>I have a test setup as following</p>
<pre><code>@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = {
  MyWicketApplication.class
})
public class ApplicationTest {

  private WicketTester tester;

  private final WebApplication webApplication;

  @Autowired
  public SecuredWicketGuiApplicationTest(WebApplication application) {
    this.webApplication = application;
  }

  @BeforeEach
  public void setUp() {

    //**** ** * WORKS ** ** ** **
    // when authenticated is given
    Authentication authentication = Mockito.mock(Authentication.class);
    SecurityContext securityContext = Mockito.mock(SecurityContext.class);
    Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
    Mockito.when(authentication.isAuthenticated()).thenReturn(true);
    SecurityContextHolder.setContext(securityContext); 
    //** ** ** ** ** ** ** ** ** *

    // and secured session is provided
    SecureWebSession secureWebSession = Mockito.mock(SecureWebSession.class);

    //**** ** * WORKS ** ** ** **
    // and a superuser role is given
    Roles roles = new Roles();
    roles.add(&quot;SUPER_ADMIN&quot;);
    Mockito.when(secureWebSession.getRoles()).thenReturn(roles); 
    //** ** ** ** ** ** ** ** **

    // and session has loginName attribute
    HttpSession session = Mockito.mock(HttpSession.class);
    Mockito.when(session.getAttribute(&quot;loginName&quot;)).thenReturn(&quot;test&quot;);

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    Mockito.when(request.getSession()).thenReturn(session);

    tester = new WicketTester(webApplication);

    MockHttpSession mockHttpSession = new MockHttpSession(null);
    mockHttpSession.setAttribute(&quot;loginName&quot;, &quot;test&quot;);

    // and a requested initiated for a given session
    MockHttpServletRequest mockedRequest = new MockHttpServletRequest(
      tester.getApplication(), mockHttpSession, null) {
      @Override
      public HttpSession getSession(boolean createNew) {
        return mockHttpSession;
      }

      @Override
      public HttpSession getSession() {
        return mockHttpSession;
      }
    };

    // and a session object is created with a loginName attribute test
    tester.getRequest().getSession()
      .setAttribute(&quot;loginName&quot;, &quot;test&quot;);

    tester.setRequest(mockedRequest);
  }

  @Test
  public void HomePage_Renders_Successfully() {
    // then start and render the homePage page
    tester.startPage(HomePage.class);
    // assert rendered HomePage component
    tester.assertRenderedPage(HomePage.class);
  }
}
</code></pre>
<p>when I try to execute this test I get stuck on</p>
<pre><code>public class MyPanel {
     ...

 SecureWebSession session = (SecureWebSession) getSession(); &lt;--returns a SecuredWebSession
 Label username = new Label(&quot;loginName&quot;, session.getLoginName()); &lt;-- NullPointerException
    ...
}
</code></pre>
<p>Where method getLoginName is defined in securedWebSession</p>
<pre><code>public String getLoginName() {
 ********RETURNS NULL.getAttribute(&quot;loginName&quot;)******
    return (String) httpSession.getAttribute(&quot;loginName&quot;);
}
</code></pre>
",https://stackoverflow.com/questions/70258881/wicket-9-unit-testing-mockito-httpsession,"['unit-testing', 'wicket']",262,True,0,1
Android Compose Unit testing - Toggle a Switch,"<p>Given a button with a <code>Modifier</code>:</p>
<pre><code>TextButton(modified = Modifier.testTag(&quot;abc123&quot;))
</code></pre>
<p>when you want to create a test to click it, you do:</p>
<pre><code>composeTestRule.onNodeWithTag(&quot;abc123&quot;).performClick()
</code></pre>
<p>but when I'm having a:</p>
<pre><code>Switch(modifier = Modifier.testTag(&quot;abc123&quot;))
</code></pre>
<p>I'm trying every single perform gesture but I can't get the Switch to toggle, and can't get any documentation from Android.</p>
<p>What's the correct way to toggle it automatically in order to test it?</p>
",https://stackoverflow.com/questions/70307655/android-compose-unit-testing-toggle-a-switch,"['android', 'android-jetpack-compose']",1132,True,4,2
Replace DbContext in WebApplicationFactory for unit testing,"<p>I need to replace context in WebApplicationFactory. I have MyDbContext which I want to replace with SQLite context for testing.</p>
<p>The replace part works fine</p>
<pre><code>.ConfigureServices(services =&gt;
  {
    // Remove the app's ApplicationDbContext registration.
    var descriptor = services.SingleOrDefault(d =&gt; d.ServiceType == typeof(DbContextOptions&lt;MyDbContext&gt;));

    if (descriptor != null)
    {
      services.Remove(descriptor);
    }
    
    services.AddDbContext&lt;MyDbContext&gt;(builder =&gt;
    {
      builder.UseSqlite(CreateInMemoryDatabase());
    });
  });
</code></pre>
<p>But because I moved from Npgsql to SQLite in tests I need to override some default values in OnModelCreating. I created a new db context class</p>
<pre><code>public class MySqlLiteDbContext: MyDbContext
    {
        public MySqlLiteDbContext(DbContextOptions&lt;MyDbContext&gt; options) : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity&lt;Record&gt;()
                .Property(b =&gt; b.DateCreated)
                .HasDefaultValueSql(&quot;(datetime('now'))&quot;);

            ...
        }
    }
</code></pre>
<p>Is there any way to inject <code>MySqlLiteDbContext</code> instead of <code>MyDbContext</code> to force EnsureCreated use <code>OnModelCreating</code> for SQLite? Is extracting <code>IMyDbContext</code> an option? What else can I do to solve this problem?</p>
",https://stackoverflow.com/questions/67876503/replace-dbcontext-in-webapplicationfactory-for-unit-testing,"['unit-testing', 'asp.net-core', '.net-core', 'entity-framework-core']",1828,True,4,2
Unit testing for micro-frontend react application,"<p>I'm trying to write unit tests for a react spa web application that uses micro-frontend architecture. My first step is to write unit tests for the application container.</p>
<p>The application container react component uses a react-router containing a switch with subsequent routes to render the components in the main content area.</p>
<p>Each application is mounted to the application container using JavaScript runtime integration.</p>
<p>I'm using React-Testing-Library and Jest as part of my testing toolset.</p>
<p>I've searched high and low across the Internet and haven't found any useful articles on the issues I'm having. Most of them show a demo of testing a web application that doesn't relate to my scenario.</p>
<p>I have 3 problems that I would like some guidance on.</p>
<ol>
<li><p>Since Micro Frontends are composed of multiple layers of components chained together with authentication and other business logic. Should I be testing the &quot;page components&quot; only? Or should I be testing the entire application container starting from the App component? If neither is true, how should I be testing this application?</p>
</li>
<li><p>I tried to test on the page component level to avoid authentication issues and for simplicity sake, but the component contains a  component from React Router library, and Jest is complaining that I should not be using <code>&lt;Link&gt;</code> component that isn't enclosed within a <code>&lt;Router&gt;</code> component. However, the <code>&lt;Router&gt;</code> component is present at the parent component level when executed in runtime. How can I tell Jest to &quot;ignore&quot; this problem?</p>
<p>I could not find a configuration that allows me to ignore this error.</p>
</li>
<li><p>Due to issue #2, I tried to write unit tests by rendering the <code>&lt;App&gt;</code> component, but this component is passed into a Higher Order Component that performs authentication validation. How can I focus on testing the end result instead of the functionality of the authentication HOC just so I can get the component to render and for my tests to execute?</p>
</li>
</ol>
",https://stackoverflow.com/questions/68705755/unit-testing-for-micro-frontend-react-application,"['reactjs', 'micro-frontend', 'react-testing']",1446,True,3,1
How to do Unit Testing with gorm,"<p>I'm new in <code>Go</code> and <code>unit test</code>. In my project am using <code>Go</code> with <code>gorm</code> and connecting <code>mysql</code> database.</p>
<p>my queries is how to unit test my code:</p>
<p><strong>My code is below(main.go):</strong></p>
<pre><code>package main

import (
    &quot;encoding/json&quot;
    &quot;fmt&quot;
    &quot;net/http&quot;
    &quot;strconv&quot;
    &quot;time&quot;

    &quot;github.com/gorilla/mux&quot;
    &quot;github.com/jinzhu/gorm&quot;
    _ &quot;github.com/jinzhu/gorm/dialects/mysql&quot;
)

type Jobs struct {
    JobID                  uint   `json: &quot;jobId&quot; gorm:&quot;primary_key;auto_increment&quot;`
    SourcePath             string `json: &quot;sourcePath&quot;`
    Priority               int64  `json: &quot;priority&quot;`
    InternalPriority       string `json: &quot;internalPriority&quot;`
    ExecutionEnvironmentID string `json: &quot;executionEnvironmentID&quot;`
}

type ExecutionEnvironment struct {
    ID                     uint      `json: &quot;id&quot; gorm:&quot;primary_key;auto_increment&quot;`
    ExecutionEnvironmentId string    `json: &quot;executionEnvironmentID&quot;`
    CloudProviderType      string    `json: &quot;cloudProviderType&quot;`
    InfrastructureType     string    `json: &quot;infrastructureType&quot;`
    CloudRegion            string    `json: &quot;cloudRegion&quot;`
    CreatedAt              time.Time `json: &quot;createdAt&quot;`
}

var db *gorm.DB

func initDB() {
    var err error
    dataSourceName := &quot;root:@tcp(localhost:3306)/?parseTime=True&quot;
    db, err = gorm.Open(&quot;mysql&quot;, dataSourceName)

    if err != nil {
        fmt.Println(err)
        panic(&quot;failed to connect database&quot;)
    }
    //db.Exec(&quot;CREATE DATABASE test&quot;)
    db.LogMode(true)
    db.Exec(&quot;USE test&quot;)
    db.AutoMigrate(&amp;Jobs{}, &amp;ExecutionEnvironment{})
}

func GetAllJobs(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
    fmt.Println(&quot;Executing Get All Jobs function&quot;)

    var jobs []Jobs
    if err := db.Select(&quot;jobs.*, execution_environments.*&quot;).Joins(&quot;JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id&quot;).Find(&amp;jobs).Error; err != nil {
        fmt.Println(err)
    }
    fmt.Println()
    if len(jobs) == 0 {
        json.NewEncoder(w).Encode(&quot;No data found&quot;)
    } else {
        json.NewEncoder(w).Encode(jobs)
    }
}

// create job
func createJob(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
    fmt.Println(&quot;Executing Create Jobs function&quot;)
    var jobs Jobs
    json.NewDecoder(r.Body).Decode(&amp;jobs)
    db.Create(&amp;jobs)
    json.NewEncoder(w).Encode(jobs)
}

// get job by id
func GetJobById(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
    params := mux.Vars(r)
    jobId := params[&quot;jobId&quot;]

    //var job []Jobs
    //db.Preload(&quot;Items&quot;).First(&amp;job, jobId)
    var jobs []Jobs
    var executionEnvironments []ExecutionEnvironment
    if err := db.Table(&quot;jobs&quot;).Select(&quot;jobs.*, execution_environments.*&quot;).Joins(&quot;JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id&quot;).Where(&quot;job_id =?&quot;, jobId).Find(&amp;jobs).Scan(&amp;executionEnvironments).Error; err != nil {
        fmt.Println(err)
    }

    if len(jobs) == 0 {
        json.NewEncoder(w).Encode(&quot;No data found&quot;)
    } else {
        json.NewEncoder(w).Encode(jobs)
    }
}

// Delete Job By Id
func DeleteJobById(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    jobId := params[&quot;jobId&quot;]

    // check data
    var job []Jobs
    db.Table(&quot;jobs&quot;).Select(&quot;jobs.*&quot;).Where(&quot;job_id=?&quot;, jobId).Find(&amp;job)
    if len(job) == 0 {
        json.NewEncoder(w).Encode(&quot;Invalid JobId&quot;)
    } else {

        id64, _ := strconv.ParseUint(jobId, 10, 64)
        idToDelete := uint(id64)

        db.Where(&quot;job_id = ?&quot;, idToDelete).Delete(&amp;Jobs{})
        //db.Where(&quot;jobId = ?&quot;, idToDelete).Delete(&amp;ExecutionEnvironment{})

        json.NewEncoder(w).Encode(&quot;Job deleted successfully&quot;)
        w.WriteHeader(http.StatusNoContent)
    }

}

// create Execution Environments
func createEnvironments(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
    fmt.Println(&quot;Executing Create Execution Environments function&quot;)
    var executionEnvironments ExecutionEnvironment
    json.NewDecoder(r.Body).Decode(&amp;executionEnvironments)
    db.Create(&amp;executionEnvironments)
    json.NewEncoder(w).Encode(executionEnvironments)
}

// Get Job Cloud Region
func GetJobCloudRegion(w http.ResponseWriter, r *http.Request) {
    w.Header().Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
    fmt.Println(&quot;Executing Get Job Cloud Region function&quot;)

    params := mux.Vars(r)
    jobId := params[&quot;jobId&quot;]

    //var jobs []Jobs
    var executionEnvironment []ExecutionEnvironment

    db.Table(&quot;jobs&quot;).Select(&quot;execution_environments.*&quot;).Joins(&quot;JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id&quot;).Where(&quot;jobs.job_id =?&quot;, jobId).Find(&amp;executionEnvironment)

    var pUuid []string
    for _, uuid := range executionEnvironment {
        pUuid = append(pUuid, uuid.CloudRegion)
    }
    json.NewEncoder(w).Encode(pUuid)

}

func main() {
    // router
    router := mux.NewRouter()
    // Access URL
    router.HandleFunc(&quot;/GetAllJobs&quot;, GetAllJobs).Methods(&quot;GET&quot;)
    router.HandleFunc(&quot;/createJob&quot;, createJob).Methods(&quot;POST&quot;)
    router.HandleFunc(&quot;/GetJobById/{jobId}&quot;, GetJobById).Methods(&quot;GET&quot;)
    router.HandleFunc(&quot;/DeleteJobById/{jobId}&quot;, DeleteJobById).Methods(&quot;DELETE&quot;)

    router.HandleFunc(&quot;/createEnvironments&quot;, createEnvironments).Methods(&quot;POST&quot;)
    router.HandleFunc(&quot;/GetJobCloudRegion/{jobId}&quot;, GetJobCloudRegion).Methods(&quot;GET&quot;)

    // Initialize db connection
    initDB()

    // config port
    fmt.Printf(&quot;Starting server at 8000 \n&quot;)
    http.ListenAndServe(&quot;:8000&quot;, router)
}
</code></pre>
<p>I try to create unit test file below, but it is not running it shows like this
<a href=""https://i.stack.imgur.com/Kymus.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Kymus.png"" alt=""enter image description here"" /></a></p>
<p><strong>main_test.go:</strong></p>
<pre><code>package main

import (
    &quot;log&quot;
    &quot;os&quot;
    &quot;testing&quot;

    &quot;github.com/jinzhu/gorm&quot;
    _ &quot;github.com/jinzhu/gorm/dialects/mysql&quot;
)

func TestinitDB(m *testing.M) {
    dataSourceName := &quot;root:@tcp(localhost:3306)/?parseTime=True&quot;
    db, err := gorm.Open(&quot;mysql&quot;, dataSourceName)

    if err != nil {
        log.Fatal(&quot;failed to connect database&quot;)
    }
    //db.Exec(&quot;CREATE DATABASE test&quot;)
    db.LogMode(true)
    db.Exec(&quot;USE test111&quot;)
    os.Exit(m.Run())
}
</code></pre>
<p>Please help me to write unit test file</p>
",https://stackoverflow.com/questions/69299894/how-to-do-unit-testing-with-gorm,"['unit-testing', 'go', 'go-gorm']",10553,True,4,2
Unit Testing TelemetryProcessor and TelemetryInitializer (Application Insights)?,"<p>I've been looking around the web for a way to unit test my processor and initializer. So far, I have the following code setup from another article, yet I'm a bit lost in how to proceed.</p>
<pre><code>public class TelemetryClientTests
{
    private TelemetryClient telemetryClient;
    private List&lt;ITelemetry&gt; sendItems;

    [TestInitialize]
    public void TestInit()
    {
        var httpContext = Substitute.For&lt;IHttpContextAccessor&gt;();
        var configuration = new TelemetryConfiguration();
        //this.sendItems = new List&lt;ITelemetry&gt;();
        configuration.TelemetryChannel = new RequeteTelemtry();
        configuration.InstrumentationKey = Guid.NewGuid().ToString();
        configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
        this.telemetryClient = new TelemetryClient(configuration);
    }

    /// &lt;summary&gt;
    /// Ensure that context being propagated via async/await.
    /// &lt;/summary&gt;
    [TestMethod]
    public void ContextPropogatesThruAsyncAwait()
    {
        var task = this.TestAsync();
        task.Wait();
    }
}
</code></pre>
<p>I'm not sure where I should add my telemtryprocessor so that Application Inisight knows that I'm unit testing it. If anybody knows how to do it, it would be greatly appreciated.</p>
",https://stackoverflow.com/questions/68292097/unit-testing-telemetryprocessor-and-telemetryinitializer-application-insights,"['unit-testing', 'azure-application-insights', 'open-telemetry']",1146,True,3,1
Java unit testing Java NIO Files library?,"<p>Let's say I have a method like:</p>
<pre><code>public void copyAndMoveFiles() throws IOException {
    Path source = Paths.get(path1);
    Path target = Paths.get(path2);
    if (Files.notExists(target) &amp;&amp; target != null) {
        Files.createDirectories(Paths.get(target.toString()));
    }
    for (String fileInDirectory: Files.readAllLines(source.resolve(fileToRead))) {
        Files.copy(source.resolve(fileInDirectory), target.resolve(fileInDirectory), StandardCopyOption.REPLACE_EXISTING);          
    }
}
</code></pre>
<p>How would I do a unit test on this? I have tried looking at mockito but it doesn't return anything or have anything I can assert. I read about JimFs, but for some reason, I can't grasp my head around that.</p>
",https://stackoverflow.com/questions/69170117/java-unit-testing-java-nio-files-library,"['java', 'unit-testing', 'file']",790,True,3,1
Angular Unit Testing for HostListener (Window Resize),"<p>I have a component file that has below code</p>
<pre><code>@HostListener('window:resize', ['$event'])
onResize(event) {
    this.width = event.target.innerWidth;
}
</code></pre>
<p>I want to test it. I have tried with the below code in my spec file.</p>
<pre><code>window.dispatchEvent(new Event(&quot;resize&quot;);
expect(component.onResize).toHaveBeenCalled();
</code></pre>
<p>but it is not working. Any help will be appreciated.</p>
",https://stackoverflow.com/questions/68595194/angular-unit-testing-for-hostlistener-window-resize,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1983,True,3,1
.NET (core) 5.0: Unit testing hangs forever,"<p>Pretty simple: no matter what framework I use (xunit, mstest, nunit) they hang forever.</p>
<p>output:</p>
<pre><code>Determining projects to restore...
  All projects are up-to-date for restore.
  testapp -&gt; C:\Users\beene\Documents\coding\csharp\current_projects\testapp\testapp\bin\Debug\net5.0\testapp.dll
  TestProject1 -&gt; C:\Users\beene\Documents\coding\csharp\current_projects\testapp\TestProject1\bin\Debug\net5.0\TestProject1.dll
Test run for C:\Users\beene\Documents\coding\csharp\current_projects\testapp\TestProject1\bin\Debug\net5.0\TestProject1.dll (.NETCoreApp,Version=v5.0)
Microsoft (R) Test Execution Command Line Tool Version 16.11.0
Copyright (c) Microsoft Corporation.  All rights reserved.

Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
vstest.console process failed to connect to testhost process after 300 seconds. This may occur due to machine slowness, please set environment variable VSTEST_CONNECTION_TIMEOUT to increase timeout.

Test Run Aborted.
</code></pre>
<p>Rebuilding the solution yields no warnings or errors of any kind.  Re-running the test produces the same problem.</p>
<p>And it stays there until it times out.  The project is a test project, with a simple &quot;Hello World!&quot; console app and a simple function test to add one to a referenced integer.  That is it.  It's the simplest possible arrangement that reproduces this problem.</p>
<p>My research indicated that these frameworks do, in fact, support .net 5.  I am left only with .NET itself.</p>
<p>Has anyone encountered this problem?  If so I would greatly appreciate some assistance.</p>
<p>Anyone who needs more information or would like to run the offending projects can do so.  I published a basic test case project to github that reproduces this issue on both of my computers.  You can find it here:  <a href=""https://github.com/BeenEncoded/testproject"" rel=""nofollow noreferrer"">https://github.com/BeenEncoded/testproject</a></p>
",https://stackoverflow.com/questions/69483051/net-core-5-0-unit-testing-hangs-forever,"['.net', '.net-core', 'nunit', 'mstest', 'xunit']",1320,True,3,2
Error when unit testing child React component,"<p>I have the following React Component:</p>
<pre><code>import { getSeasonsalCode } from &quot;./DiscountCodes.js&quot;;
import React, { Component } from &quot;react&quot;;
import Rating from &quot;./Rating.js&quot;;
import ReactDOM from &quot;react-dom&quot;;
import &quot;regenerator-runtime/runtime&quot;;

class Product extends Component {
  constructor(props) {
    super(props);
    this.handleEvent = this.handleEvent.bind(this);

    this.state = {
      name: &quot;&quot;,
      rating: 0,
    };
  }

  setStarCount = (ct) =&gt; {
    this.setState({ rating: ct });
  };

  render() {
    var discount = getSeasonsalCode();
    return (
      &lt;div&gt;
        &lt;span&gt;{discount}&lt;/span&gt;
        &lt;Rating
          name=&quot;star_rating&quot;
          size=&quot;2x&quot;
          setStarCount={this.setStarCount}
        &gt;&lt;/Rating&gt;
      &lt;/div&gt;
    );
  }
}

export default connect(mapStateToProps, null)(Product);
</code></pre>
<p>And the following product.test.js. It tests the Rating child component, which requires a callback function from the parent component to set the rating value:</p>
<pre><code>import Rating from &quot;../src/Rating.js&quot;;
import Product from &quot;../src/Product.js&quot;;
import { shallow, mount } from &quot;enzyme&quot;;
import expect from &quot;expect&quot;;
import React from &quot;react&quot;;
import { Provider } from &quot;react-redux&quot;;
import { connect } from &quot;react-redux&quot;;
import rootReducer from &quot;../src/reducers/RootReducer.js&quot;;
import { createStore } from &quot;redux&quot;;

describe(&quot;Product test suite&quot;, () =&gt; {
  it(&quot;set rating&quot;, () =&gt; {
    const store = createStore(
      rootReducer,
      window.__REDUX_DEVTOOLS_EXTENSION__ &amp;&amp;
        window.__REDUX_DEVTOOLS_EXTENSION__()
    );

    const rf_wrapper = mount(
      &lt;Provider store={store}&gt;
        &lt;Product /&gt;
      &lt;/Provider&gt;
    ).dive();
    const rf_instance = rf_wrapper.instance();
    const sr_wrapper = shallow(
      &lt;Rating
        name=&quot;star_rating&quot;
        size=&quot;2x&quot;
        setStarCount={rf_instance.setStarCount()}
      /&gt;
    );

    sr_wrapper.find(&quot;#star4&quot;).simulate(&quot;click&quot;);
    expect(rf_wrapper.state(&quot;starcount&quot;)).toEqual(4);
  });
});
</code></pre>
<p>When I run the test, I get a TypeError saying discount is null or undefined at this line:</p>
<pre><code>&lt;span&gt;{discount}&lt;/span&gt;
</code></pre>
<p>What is causing this issue?</p>
",https://stackoverflow.com/questions/69534006/error-when-unit-testing-child-react-component,"['reactjs', 'jestjs', 'components', 'parent-child', 'enzyme']",405,True,2,1
Flutter: Unit testing Firebase Firestore through Repository,"<p>I have a purpose to test my Firestore repository methods. I found out a useful <a href=""https://pub.dev/packages/fake_cloud_firestore"" rel=""nofollow noreferrer"">fake_cloud_firestore</a> package, which helps to mock firestore.</p>
<p>I have a repository method that I want to test:</p>
<pre><code>@override
  Future&lt;Either&lt;UserFailure, UserDTO&gt;&gt; updateUser(FUser user) async {
    try {
      final UserDTO userDTO = UserDTO.fromDomainForUpdatingProfile(user);

      final Map&lt;String, dynamic&gt; userJson = userDTO.toJson();

      await _firestore
          .collection(FirestoreCollections.COLLECTION_USERS)
          .doc(user.id)
          .set(userJson, SetOptions(merge: true));

      return right(userDTO);
    } on FirebaseException catch (e) {
      if (e.message!.contains('PERMISSION_DENIED')) {
        return left(const UserFailure.insufficientPermission());
      } else {
        return left(const UserFailure.unexpected());
      }
    } on Exception {
      return left(const UserFailure.unexpected());
    }
  }
</code></pre>
<p>And a test:</p>
<pre><code>test('exception test', () async {
        final Map&lt;String, dynamic&gt; jsonMap = json.decode(
          fixture(&quot;user/full_domain_fuser.json&quot;),
        );

        final FUser fuser = FUser.fromJson(jsonMap);
        final userJson = UserDTO.fromDomainForUpdatingProfile(fuser).toJson();

        when(fakeFirebaseFirestore
                .collection(FirestoreCollections.COLLECTION_USERS)
                .doc(fuser.id)
                .set(userJson, SetOptions(merge: true)))
            .thenThrow(Exception());

        final result = await userRepository.updateUser(fuser);

        expect(result, const Left(UserFailure));
      });
    });
</code></pre>
<p>What I want to do is throw an Exception when calling Firestore and updating the document, but when() part is not being triggered. When running a test I get:</p>
<pre><code>Bad state: No method stub was called from within `when()`. Was a real method called, or perhaps an extension method?
</code></pre>
<p>FakeFirebaseFirestore and UserRepository construction:</p>
<pre><code>FakeFirebaseFirestore fakeFirebaseFirestore = FakeFirebaseFirestore();
UserRepository userRepository = UserRepository(fakeFirebaseFirestore);
</code></pre>
<p>It looks like that my firestore call looks the same in a test and also in repository method. What am I missing in this when() part?</p>
",https://stackoverflow.com/questions/68593688/flutter-unit-testing-firebase-firestore-through-repository,"['firebase', 'flutter', 'google-cloud-firestore', 'flutter-test']",416,True,2,1
Android: unit testing of LiveData and Flow,"<p>I'm trying to write unit testing for my ViewModel but I don't know how to deal with LiveData functions.</p>
<p>Specifically I'm not able to validate all the values that receive the LiveData <code>Observer</code>.</p>
<p>Regarding I have a Flow Use case that emit values and then is pased as a LiveData, what is the best approach to test <code>operation</code> function?</p>
<p>In the code below you can find that I'm only able to read the value <code>&quot;endLoading&quot;</code>, but I want to check all the values: <code>&quot;startLoading&quot;</code>, <code>&quot;Hello Dummy $input&quot;</code>, <code>&quot;endLoading&quot;</code></p>
<p>MainViewModel.kt</p>
<pre><code>class MainViewModel(val useCase: DummyUseCase = DummyUseCase()): ViewModel() {
    fun operation(value: Int): LiveData&lt;String&gt; = useCase.invoke(value)
        .transform { response -&gt;
            emit(response)
        }.onStart {
            emit(&quot;startLoading&quot;)
        }.catch {
            emit(&quot;ERROR&quot;)
        }.onCompletion {
            emit(&quot;endLoading&quot;)
        }.asLiveData(viewModelScope.coroutineContext)
}
</code></pre>
<p>MainViewModelTest.kt</p>
<pre><code>import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test

@ExperimentalCoroutinesApi
class MainViewModelTest {
    //region Setup
    @get:Rule
    val rule = InstantTaskExecutorRule()
    private val testDispatcher = TestCoroutineDispatcher()

    @MockK private lateinit var stateObserver: Observer&lt;String&gt;
    @MockK private lateinit var useCase: DummyUseCase
    private lateinit var viewModel: MainViewModel

    @Before
    fun setup() {
        MockKAnnotations.init(this, relaxUnitFun = true)
        Dispatchers.setMain(testDispatcher)
        viewModel = MainViewModel(useCase)
    }

    @After
    fun teardown() {
        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }
    //endregion

    @Test // AAA testing
    fun `when my flow succeeds, return a state String`() {
        runBlocking {
            //Arrange
            val input = 10
            coEvery { useCase.invoke(input) }.returns(flow {
                emit(&quot;Hello Dummy $input&quot;)
            })

            //Act
            val actual = viewModel.operation(input).apply {
                observeForever(stateObserver)
            }

            //Assert
            // I want to assert here every value received in the observer of the &quot;actual&quot; LiveData
            // How? :(
            assertNotNull(actual.value) // is always &quot;endLoading&quot;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/67169360/android-unit-testing-of-livedata-and-flow,"['kotlin', 'android-livedata', 'android-viewmodel', 'kotlin-coroutines']",1699,True,2,1
Unit testing nestjs guards Unknown authentication strategy,"<p>Trying to write unit tests as described <a href=""https://github.com/jmcdo29/testing-nestjs/blob/master/apps/complex-sample/src/cat/cat.guard.spec.ts"" rel=""nofollow noreferrer"">here</a> but no idea how to get around this error</p>
<pre><code>Exception has occurred: Error: Unknown authentication strategy &quot;test-jwt&quot;
  at attempt (/home/user/Workspace/project/node_modules/passport/lib/middleware/authenticate.js:190:39)
    at authenticate
</code></pre>
<p>auth file</p>
<pre><code>import { Injectable } from &quot;@nestjs/common&quot;;
import { AuthGuard } from &quot;@nestjs/passport&quot;;

@Injectable()
export class MyGuard extends AuthGuard('test-jwt') { }
</code></pre>
<p>test</p>
<pre><code>import { ExecutionContext } from &quot;@nestjs/common&quot;;
import { MyGuard } from &quot;./mygaurd&quot;;

it('test' () =&gt; {
    const context: ExecutionContext = {
      switchToHttp: () =&gt; context,
      getRequest: () =&gt; {
        return {
          headers: {
            authorization: `bearer ${jwt}` 
          }
        }
      },
      getResponse: () =&gt; { }
    } as unknown as ExecutionContext

    const guard = new MyGuard()

    expect(guard.canActivate(context)).toBeTrue();
})
</code></pre>
<p>The actual implementation works fine, I add it to a controller.</p>
<pre><code>@UseGuards(MyGuard)
export class MyController {
</code></pre>
<p>I don't even need to add it as a provider or anything in my setup so not sure what other code to include.</p>
<p>I implemented a custom strategy which may be related</p>
<pre><code>import { Strategy, ExtractJwt } from &quot;passport-jwt&quot;;
import { Injectable } from &quot;@nestjs/common&quot;;
import { PassportStrategy } from &quot;@nestjs/passport&quot;;

@Injectable()
export class MyStrategy extends PassportStrategy(Strategy, 'test-jwt') {
   
  constructor() {
    super({ 
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), 
      secretOrKey: 'secret'
    })
  }

  async validate(payload) {
    ...
  }
}
</code></pre>
<p>And of course <code>MyStrategy</code> is added as a provider in my app.</p>
<p>I have unit tests covering my custom strategy already so it is really just the guard left</p>
<p><strong>EDIT:</strong></p>
<p>Trying Jay's suggestion below gets me a little closer but i'm still struggling.</p>
<p>It seems <code>passport.use()</code> expects a name and Strategy rather than a function (so TS compilation fails) so I tried</p>
<pre><code>import passport, { Strategy } from &quot;passport&quot;;
...

passport.use('test-jwt', {
   authenticate: (payload) =&gt; true
} as Strategy);
</code></pre>
<p>and the error disappears, but the test now outputs</p>
<pre><code>expect(received).toBeTrue()

Expected value to be true:
  true
Received:
  {}
</code></pre>
<p>Any further suggestions?</p>
",https://stackoverflow.com/questions/67832906/unit-testing-nestjs-guards-unknown-authentication-strategy,"['unit-testing', 'testing', 'jestjs', 'passport.js', 'nestjs']",2085,True,2,1
StackOverflow error on unit testing API controllers?,"<p>I'm working on a Spring Boot MVC project and I'm getting the following error when unit testing my CRUD controllers :</p>
<pre><code>java.lang.StackOverflowError
at java.base/java.lang.Throwable.getOurStackTrace(Throwable.java:840)
at java.base/java.lang.Throwable.getStackTrace(Throwable.java:832)
at ch.qos.logback.classic.spi.ThrowableProxy.&lt;init&gt;(ThrowableProxy.java:55)
at ch.qos.logback.classic.spi.ThrowableProxy.&lt;init&gt;(ThrowableProxy.java:60)

java.lang.StackOverflowError
at java.base/java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:834)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:247)
at ch.qos.logback.classic.pattern.ThrowableProxyConverter.subjoinSTEPArray(ThrowableProxyConverter.java:216)
at ch.qos.logback.classic.pattern.ThrowableProxyConverter.recursiveAppend(ThrowableProxyConverter.java:161)
at ch.qos.logback.classic.pattern.ThrowableProxyConverter.recursiveAppend(ThrowableProxyConverter.java:168)
</code></pre>
<p>Here's one of the controllers unit test, the others follow the same logic.</p>
<pre><code>@Autowired
private MockMvc mockMvc;

@MockBean
private PessoaRepository pessoaRepository;

@Test
public void deletarPessoa_quandoDelete() throws Exception {
    Pessoa pessoa = new Pessoa();
    pessoa.setNome(&quot;Test Nome&quot;);
    pessoa.setId(89L);
    doNothing().when(pessoaRepository).delete(pessoa);
    mockMvc.perform(delete(&quot;/pessoas/&quot; + pessoa.getId().toString())
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());
}
</code></pre>
<p>What could this be? I have no idea why I'm getting this error.</p>
<p>EDIT : here's the controller, it basically calls for the repo to delete a Pessoa object</p>
<pre><code>@DeleteMapping(&quot;/{id}&quot;)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deletar(@ApiParam(value = &quot;ID&quot;, example = &quot;1&quot;) @PathVariable Long id) {
    Pessoa pessoaDeletada = pessoaRepository.getOne(id);
    pessoaRepository.delete(pessoaDeletada);
}
</code></pre>
",https://stackoverflow.com/questions/66765956/stackoverflow-error-on-unit-testing-api-controllers,"['java', 'spring', 'unit-testing', 'testing', 'stack-overflow']",432,False,1,0
How to Mock ClaimsPrincipal for unit testing,"<p>I have product controller and post method to create data and save in database and I need <code>ClaimsPrincipal</code> to check user in system and check user role, but when I was writing unit test I have problem how can I mock <code>ClaimsPrincipal</code>, btw for authorize I use jwt Bearer token. Sorry it is just test project I can't show real project.</p>
<pre><code>[Authorize]
[ApiController]
[Route(&quot;api/{controller}&quot;)]
public class ProductsContoller : ControllerBase
{   
    private readonly IProductsRepository _products;
    public ProductsContoller(IProductsRepository products)
    {
        _products = products;
    }

    [Authorize(Roles = &quot;root, admin, user&quot;)]
    [HttpPost]
    public async Task&lt;IActionResult&gt; Create([FromBody] Product product)
    {
        var result = await _products.CreateAsync(User, product);
        return Ok(result);
    }
}
</code></pre>
<p>And in products repository I check user using claims:</p>
<pre><code>public interface IProductsRepository
{
    Task&lt;Product&gt; CreateAsync(ClaimsPrincipal userClaims, Product product);
}

public class ProductsRepository
{
    private readonly UserManager&lt;IdentityUser&gt; _usermanager;
    private readonly AppDbContext _db;

    public ProductsRepository(AppDbContext db, UserManager&lt;IdentityUser&gt; usermanager)
    {
        _db = db;
    }

    public async Task&lt;Product&gt; CreateAsync(ClaimsPrincipal userClaims, Product product)
    {
        var user = await _usermanager.GetUserAsync(userClaims);
        if(user is null)
        {
            return null;
        }

        var userRole = await _usermanager.GetRolesAsync(user);
        if (userRole is null || userRole.Count == 0 || userRole[0] is null)
        {
            return null;
        }

        //Check deal and add to database
        await _db.Products.Add(product);
        await _db.SaveChangesAsync();

        return product;            
    }

}
</code></pre>
<p>I am tried to write unit test:</p>
<pre><code>[Fact]
public void Test1()
{   
    //Arrange
    var claims = new Mock&lt;ClaimsPrincipal&gt;();
    var p = new Product()
    {
        Id = 1,
        Name = &quot;Test&quot;,
    };

    var mockRepo = new Mock&lt;Test.Controllers.Repositories.IProductsRepository&gt;();
    mockRepo.Setup(repo =&gt; repo.CreateAsync(claims.Object, Product))
        .Returns(Task.CompletedTask);
    var controller = new ProductsConrtoller(mockRepo.Object);

    //Act
    var result = controller.CreateAsync(claims, p);

    //Assert
}
</code></pre>
",https://stackoverflow.com/questions/68983209/how-to-mock-claimsprincipal-for-unit-testing,"['c#', 'unit-testing', 'asp.net-core', 'xunit']",1008,False,1,0
ViewModel unit testing with Repository + LiveData + Coroutines,"<p>So I'm confused about how to implement the unit testing to my ViewModel. I'm using retrofit for my API fetching and using the repository.</p>
<p>ViewModel.kt</p>
<pre><code>@HiltViewModel
class MoviesViewModel @Inject constructor(private val moviesRepository: MoviesRepository) :
ViewModel() {
private val _navigatetoDetail = MutableLiveData&lt;Movies?&gt;()

fun getPopularMovies() = liveData(Dispatchers.Default) {
    emit(Resource.loading(null))
    try {
        emit(Resource.success(moviesRepository.getPopularMovies()))
    } catch (e: Exception) {
        emit(
            Resource.error(
                null,
                e.message ?: &quot;Unknown Error&quot;
            )
        )
        Log.e(&quot;viewModel&quot;, &quot;popularMovies error: ${e.message}&quot;)
    }
}

fun getMovieDetails(movie_id: String) = liveData(Dispatchers.Default) {
    emit(Resource.loading(null))
    try {
        emit(Resource.success(moviesRepository.getMovieDetails(movie_id)))
    } catch (e: Exception) {
        emit(
            Resource.error(
                null,
                e.message ?: &quot;Unknown Error&quot;
            )
        )
        Log.e(&quot;viewModel&quot;, &quot;movieDetails error: ${e.message}&quot;)
    }
}

fun navigatetoDetail(): LiveData&lt;Movies?&gt; {
    return _navigatetoDetail
}

fun onMovieClicked(movies: Movies?) {
    _navigatetoDetail.value = movies
}

fun onMovieDetailNavigated() {
    _navigatetoDetail.value = null
}
</code></pre>
<p>Repository.kt</p>
<pre><code>class MoviesRepository @Inject constructor(private var apiInterface: ApiInterface) {
init {
    apiInterface = ApiBuilder.createService()
}

suspend fun getPopularMovies() = apiInterface.getPopularMovies()

suspend fun getMovieDetails(movie_id: String) = apiInterface.getMovieDetails(movie_id)

suspend fun getPopularTvShows() = apiInterface.getPopularTvShows()

suspend fun getTvShowDetails(tvshow_id: String) = apiInterface.getTvShowDetails(tvshow_id)
</code></pre>
<p>apiInterface.kt</p>
<pre><code>interface ApiInterface {
@GET(&quot;/3/movie/popular?api_key=$API_KEY&amp;language=en-US&quot;)
suspend fun getPopularMovies(): Envelope&lt;List&lt;Movies&gt;&gt;

@GET(&quot;/3/movie/{movie_id}?api_key=$API_KEY&amp;language=en-US&quot;)
suspend fun getMovieDetails(@Path(&quot;movie_id&quot;) movie_id: String?): Movies

@GET(&quot;3/tv/popular?api_key=$API_KEY&amp;language=en-US&amp;page=1&quot;)
suspend fun getPopularTvShows(): Envelope&lt;List&lt;TvShows&gt;&gt;

@GET(&quot;/3/tv/{tvshow_id}?api_key=$API_KEY&amp;language=en-US&quot;)
suspend fun getTvShowDetails(@Path(&quot;tvshow_id&quot;) tvshow_id: String?): TvShows
</code></pre>
<p>I already tried to test my ViewModel by making it like this:</p>
<pre><code> @Test
fun testGetPopularMovies() = coroutinesTestRule.testDispatcher.runBlockingTest {
    val moviesList = viewModel.getPopularMovies().value
    viewModel.getPopularMovies().observeForever(observer)
    verify(observer).onChanged(argumentCaptor.capture())
    assertEquals(20, moviesList?.data?.results?.size)
}
</code></pre>
<p>but it return NullPointerException on <em><strong>viewModel.getPopularMovies().observeForever(observer)</strong></em></p>
",https://stackoverflow.com/questions/67613391/viewmodel-unit-testing-with-repository-livedata-coroutines,"['android', 'unit-testing', 'kotlin', 'retrofit']",1509,True,1,2
Mock Data from Redis unit testing python,"<p>I have a class</p>
<pre><code>class ReferenceData(celery.Task):
    def __init__(self):
        redis_pool = redis.ConnectionPool()
        self.redis = redis.StrictRedis(connection_pool=redis_pool)

    def get_agents(self,id):
        if condition:
            return self.agents.get(id)
        return self.agents.get(external_id
</code></pre>
<p>and there is celery task which calls up the following method</p>
<pre><code>def save_raisr_event(self, event):
    # Get attributes:
    transcriptions = []
    if trans is not None:
       transcriptions.append(trans)
        self.redis.append(f&quot;{crn}-transcription&quot;, ' ' + transcription)
        return 'transcription saved'
</code></pre>
<p>In the unit testing how to mock the redis connection and mock data from redis in this case the value pf transcription saved in redis</p>
",https://stackoverflow.com/questions/69351844/mock-data-from-redis-unit-testing-python,"['python', 'unit-testing', 'mocking', 'python-unittest']",670,True,1,1
Tenant Multi tenancy Laravel Unit Testing issue,"<p>Here is the test case that i created for category testing. I am getting 404 on this route while i have correctly configured the tenant test case and this route is exist on subdomain that was created on chrome browser.</p>
<pre><code>public function test_example()
{
    $response = $this-&gt;call('GET', '/categories/6/edit');
    $this-&gt;assertEquals(200, $response-&gt;getStatusCode(),$response-&gt;exception-&gt;getMessage());
}
</code></pre>
<p>My TestCase.php</p>
<pre><code>  protected $tenancy = false;

public function setUp(): void
{
    parent::setUp();
    if ($this-&gt;tenancy) {
        $this-&gt;initializeTenancy();
    }
}

public function initializeTenancy()
{
    $tenant = Tenant::create();
    tenancy()-&gt;initialize($tenant);
}
</code></pre>
<p>Documentation I am following
<a href=""https://tenancyforlaravel.com/docs/v3/testing"" rel=""nofollow noreferrer"">https://tenancyforlaravel.com/docs/v3/testing</a></p>
<p>Result:
I want 302 response means redirect to login code.</p>
",https://stackoverflow.com/questions/67004267/tenant-multi-tenancy-laravel-unit-testing-issue,"['php', 'laravel', 'multi-tenant', 'multi-database']",768,False,1,1
Unit testing Express endpoint with express-session,"<p>I've recently tried to write some unit tests for my basic CRUD REST API. Unfortunately, in this API I use Github's OAuth for authentication and express-session for storing sessions. How do I test this endpoint:</p>
<pre><code>export async function createProject(req: Request, res: Response) {
  try {
    const { name, repository_url, repository_provider, assets_path } = req.body;
    const newProject = await Project.create({
      owner_id: (req.user as User).id,
      name,
      repository_url,
      repository_provider,
      assets_path,
    });
    const newMember = await ProjectMember.create({
      project_id: newProject.id,
      member_id: (req.user as User).id,
      project_role: &quot;owner&quot;,
    });
    newProject.save();
    newMember.save();
    res.status(201).json(newProject);
  } catch (error) {
    res.status(400).json({ error: error.message || &quot;Unexpected error.&quot; });
  }
}
</code></pre>
<p>when I don't have <code>req.user</code> set, and I get this by logging into GitHub?</p>
<p>And here's my test suite for now. I use Jest for suites and TypeORM for manipulating the MySQL database.</p>
<pre><code>let server: Express;
let connection: Connection;

beforeAll(async () =&gt; {
  connection = await createConnection();
  server = await createServer();

  await connection.createQueryBuilder().delete().from(User).execute();
  await User.create({
    name: &quot;test&quot;,
    github_name: &quot;test&quot;,
  }).save();
});

afterAll(async () =&gt; {
  await connection.dropDatabase();
  await connection.close();
});

describe(&quot;POST /projects&quot;, () =&gt; {
  it(&quot;should return 201 &amp; create project &amp; valid response if not logged in&quot;, async (done) =&gt; {
    request(server)
      .post(&quot;/api/projects&quot;)
      .send({
        name: &quot;test&quot;,
        repository_url: &quot;https://github.com/test/test&quot;,
        repository_provider: &quot;github&quot;,
        assets_path: &quot;/assets/i18n&quot;
      })
      .expect(&quot;Content-Type&quot;, /json/)
      .expect(201)
      .end((err, res) =&gt; {
        if (err) return done(err);
        done();
      });
  });
});
</code></pre>
",https://stackoverflow.com/questions/65564132/unit-testing-express-endpoint-with-express-session,"['node.js', 'typescript', 'jestjs']",1246,True,1,2
Unit testing an authenticated user in Django,"<p>I am trying to test access as a logged in user. I'm having trouble with the <code>Client()</code>.</p>
<pre><code>def test_taking_too_much_time(self):
    my_client = Client()
    my_client.login(username='exampleuser', password='testing12345')
    response = my_client.get('/example/link/')
    self.assertEqual(response.status_code, 200)
</code></pre>
<blockquote>
<p>Okay could you also provide the whole stacktrace?</p>
</blockquote>
<p>I see, that friend has a similar problem. <a href=""https://stackoverflow.com/questions/69057055/django-testing-login-view-attributeerror-httprequest-object-has-no-attrib"">Django - Testing Login View - AttributeError: &#39;HttpRequest&#39; object has no attribute &#39;user&#39;</a>
After adding the 'user' instance in the argument and replacing with request.</p>
<pre><code>@receiver (user_logged_in, sender = Person)
def when_logging_in (request, sender, user, ** kwargs):
     messages.info (request, f '{user.username} hello.')
</code></pre>
<p>The trouble persists and the same thing appears, which is <code>AttributeError: 'HttpRequest' object has no attribute 'user'</code>. The <a href=""https://stackoverflow.com/a/70451317"">answer</a> below is an expansion of the topic.</p>
",https://stackoverflow.com/questions/70426709/unit-testing-an-authenticated-user-in-django,"['django', 'unit-testing', 'django-testing']",890,False,1,2
Unit testing Armeria&#39;s decorator using context.log().whenComplete(),"<p>I have a subclass of <code>SimpleDecoratingHttpService</code> that contains something like this:</p>
<pre class=""lang-kotlin prettyprint-override""><code>    override fun serve(ctx: ServiceRequestContext, req: HttpRequest): HttpResponse {
        ctx.log().whenComplete().thenAccept {
            if (it.responseCause() == ...) {
                // do stuff
            }
        }
        return unwrap().serve(ctx, req)
    }
</code></pre>
<p>I want to test the logic inside the <code>whenComplete()</code> callback. However, when writing tests like this:</p>
<pre class=""lang-kotlin prettyprint-override""><code>myDecorator.serve(context, request).aggregate().join()
</code></pre>
<p>the <code>log()</code> future never completes. What do I need to do to ensure that the <code>log()</code> future eventually completes?</p>
",https://stackoverflow.com/questions/68039718/unit-testing-armerias-decorator-using-context-log-whencomplete,['armeria'],195,True,1,1
Angular - Long Polling with Observables - Unit Testing,"<p>I'm quite new to unit testing observables, so far I found out that there are two ways of testing them either by using the subscribe and assert pattern or by using marble testing.</p>
<p>I do now have a task at hand where I need some sort of long polling implementation. The implementation is working fine, but writing the according unit test is a pain.</p>
<p>Here is the code I have so far:</p>
<p>long-polling.service.ts</p>
<pre class=""lang-js prettyprint-override""><code>// ...
/**
* Starts polling a long polling endpoint. Pass in any kind of observable stream
* to the method and eg. from the httpClient.get(). You can also configure a maximum
* number of retries in case the server might fail and the retry interval in ms.
* @param observableToPoll$
* @param maxRetrys
* @param retryIntervalOnError
*/
startPolling&lt;T&gt;(
  observableToPoll$: Observable&lt;T&gt;,
  maxRetrys: number = Infinity,
  retryIntervalOnError = 5000
): Observable&lt;T&gt; {
  if (this.poll$) {
    return this.poll$;
  }

  this.poll$ = observableToPoll$.pipe(
    longPollUntil(this.stopPolling$, maxRetrys, retryIntervalOnError)
  );

  return this.poll$;
}
//...
</code></pre>
<p>util.ts</p>
<pre class=""lang-js prettyprint-override""><code>export function longPollUntil&lt;T&gt;(
  isPollingActive: IsActiveCallback | Observable&lt;any&gt;,
  maxRetrys = Infinity,
  retryInterval = 5000
): MonoTypeOperatorFunction&lt;T&gt; {
  return (source$) =&gt; {
    const poll$ = source$.pipe(
      repeat(),
      retryWhen((errors) =&gt;
        errors.pipe(
          concatMap((e, i) =&gt;
            iif(
              () =&gt; i &gt;= maxRetrys,
              throwError(e),
              of(e).pipe(delay(retryInterval))
            )
          )
        )
      ),
      share()
    );

    if (isObservable(isPollingActive)) {
      return poll$.pipe(takeUntil(isPollingActive));
    }

    return poll$.pipe(takeWhile(isPollingActive as (res: T) =&gt; boolean, true));
  };
}
</code></pre>
<p>long-polling.service.spec.ts</p>
<pre class=""lang-js prettyprint-override""><code>// ...
it('should start polling and repeat after stream ends', fakeAsync((done) =&gt; {
  const httpClient = TestBed.inject(HttpClient);


  const polling = service.startPolling(
    httpClient.get('/sometest/test.json').pipe(
      // observeOn(scheduler),
      tap(() =&gt; {
        console.log('request fired');
      })
    )
  );
  let callCount = 0;
  polling.subscribe((data: any) =&gt; {
    if (callCount === 0) {
      expect(data.someMessage).toBe('Test message');
    } else {
      expect(data.someMessage).toBe('Another message');
    }

    callCount++;

    if (callCount &gt; 2) {
      done();
    }
  }, done.fail);
  const req = httpMock.match('/sometest/test.json');
  expect(req[0].request.method).toBe('GET');

  scheduler.flush();

  req[0].flush({
    someMessage: 'Test message',
  });
  scheduler.flush();

  //tick(70000);
  req[1].flush({
    someMessage: 'Another message',
  });
}));
// ...
</code></pre>
<p>As you can see I tried several approaches already. But the request is only fired once and does not repeat like it should do.</p>
<p>Does anyone have a clue how to test this?</p>
",https://stackoverflow.com/questions/67583101/angular-long-polling-with-observables-unit-testing,"['angular', 'typescript', 'unit-testing', 'rxjs']",269,False,1,0
ReactJs unit testing with jest and enzyme,"<p>I have the following return method in one of my components (AreaCodesTable):</p>
<pre class=""lang-js prettyprint-override""><code>&lt;&gt;
  &lt;Button
    id=&quot;create-email-template&quot;
    className=&quot;p-button-rounded p-button-text p-button-icon-only blubicon-plus&quot;
    onClick={() =&gt; this.toggleCreateAreaCodeModal()}
  &gt;&lt;/Button&gt;
  &lt;Tooltip target={'#create-email-template'} content={this.props.t('common.areaCode')} position={'left'} /&gt;
  &lt;DataTable dataKey=&quot;id&quot; id=&quot;area-codes-table&quot; value={this.props.rootStore.areaCodeStore.areaCodes}&gt;
    &lt;Column key=&quot;title&quot; field=&quot;title&quot; header={this.props.t('areaCodes.shared.title')} style={{ width: '11rem' }} /&gt;
    &lt;Column
      key=&quot;description&quot;
      field=&quot;description&quot;
      header={this.props.t('areaCodes.shared.description')}
      style={{ width: '11rem' }}
    /&gt;
    &lt;Column
      body={this.showButtons}
      headerStyle={{ width: '10%', minWidth: '8rem' }}
      bodyStyle={{ textAlign: 'center' }}
    &gt;&lt;/Column&gt;
  &lt;/DataTable&gt;

  &lt;DeleteModal
    deleteMode={this.state.showDeleteModal}
    confirmDeleteTemplate={this.confirmDeletion}
    discardDeleteTemplate={this.toggleDeleteAreaCodeModal}
    header={this.props.t('areaCodes.delete.header')}
  /&gt;

  {this.state.showEditModal &amp;&amp; (
    &lt;EditAreaCodeModal
      selectedAreaCode={this.state.selectedAreaCode}
      confirmEdit={this.confirmEdit}
      toggleEditAreaCodeModal={this.toggleEditAreaCodeModal}
      visible={this.state.showEditModal}
      rootStore={this.props.rootStore}
    /&gt;
  )}
  {this.state.showCreateModal &amp;&amp; (
    &lt;CreateAreaCodeModal
      rootStore={this.props.rootStore}
      toggleCreateAreaCode={this.toggleCreateAreaCodeModal}
      getAreaCodesRefresh={this.getAreaCodes}
    /&gt;
  )}
&lt;/&gt;
</code></pre>
<p>However I can't simulate a click in my unit tests.</p>
<pre class=""lang-js prettyprint-override""><code>describe('area codes table', () =&gt; {
  const backendBaseUrl = 'http://localhost:8081';
  const mockDataProvider = new DataProvider(backendBaseUrl);
  const rootStore = new RootStore(mockDataProvider);

  const props = {
    rootStore: rootStore,
    i18n: i18n,
    t: t,
  };

  const initialState = {
    showDeleteModal: false,
    showEditModal: false,
    showCreateModal: false,
    selectedAreaCode: null,
  };

  let reactComponent: ShallowWrapper&lt;IAreaCodesTableProps, IAreaCodesTableState&gt;;

  beforeEach(() =&gt; {
    reactComponent = shallow(&lt;AreaCodesTable {...props} /&gt;);
  });

  afterEach(() =&gt; {
    reactComponent.unmount();
  });

  it('should show create modal', () =&gt; {
    const createButton = reactComponent.find('button');
    createButton.simulate('click');
  });
});
</code></pre>
<p>Either I use reactComponent.find('#create-email-template') or .find('button') I get this error message: <code>Method “simulate” is meant to be run on 1 node. 0 found instead.</code> . For the first one I understand why- because we have to ids create-email-template, but for the second I dont know- I used Button, #button, #Button combinations as well, but didnt work.</p>
<p>This is the result from reactComponent.html():</p>
<pre class=""lang-html prettyprint-override""><code>&lt;button
  id=&quot;create-email-template&quot;
  class=&quot;p-button p-component p-button-rounded p-button-text p-button-icon-only blubicon-plus&quot;
&gt;
  &lt;span class=&quot;p-button-label p-c&quot;&gt;&amp;nbsp;&lt;/span&gt;
&lt;/button&gt;
&lt;div
  id=&quot;area-codes-table&quot;
  class=&quot;p-datatable p-component&quot;
  data-scrollselectors=&quot;.p-datatable-scrollable-body, .p-datatable-unfrozen-view .p-datatable-scrollable-body&quot;
&gt;
  &lt;div class=&quot;p-datatable-wrapper&quot;&gt;
    &lt;table role=&quot;grid&quot;&gt;
      &lt;thead class=&quot;p-datatable-thead&quot;&gt;
        &lt;tr role=&quot;row&quot;&gt;
          &lt;th role=&quot;columnheader&quot; class=&quot;p-sortable-disabled&quot; style=&quot;width:11rem&quot;&gt;
            &lt;span class=&quot;p-column-title&quot;&gt;&lt;/span&gt;
          &lt;/th&gt;
          &lt;th role=&quot;columnheader&quot; class=&quot;p-sortable-disabled&quot; style=&quot;width:11rem&quot;&gt;
            &lt;span class=&quot;p-column-title&quot;&gt;&lt;/span&gt;
          &lt;/th&gt;
          &lt;th role=&quot;columnheader&quot; class=&quot;p-sortable-disabled&quot; style=&quot;width:10%;min-width:8rem&quot;&gt;
            &lt;span class=&quot;p-column-title&quot;&gt;&lt;/span&gt;
          &lt;/th&gt;
        &lt;/tr&gt;
      &lt;/thead&gt;
      &lt;tbody class=&quot;p-datatable-tbody&quot;&gt;
        &lt;tr role=&quot;row&quot; class=&quot;p-datatable-emptymessage&quot;&gt;
          &lt;td role=&quot;cell&quot; colSpan=&quot;3&quot;&gt;
            No records found
          &lt;/td&gt;
        &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<p>Everything is here.</p>
",https://stackoverflow.com/questions/70301348/reactjs-unit-testing-with-jest-and-enzyme,"['reactjs', 'jestjs', 'enzyme']",52,False,1,0
Jest + Enzyme + ReduxForm unit testing render issue,"<p>I am working on getting some unit test around my redux form and running into a lot of issues with it. Currently my test looks like this</p>
<pre><code>describe('testing ForgotPassword functionality', () =&gt; {
let ForgotPasswordForm;
let defaultProps = {
    handleSubmit: (fn) =&gt; fn
}
let shallow;
let props = {
    forgotPassword: jest.fn()
}
let store = createStore(combineReducers({ form: formReducer, auth: authReducer }));

beforeEach(() =&gt; {
    shallow = createShallow({ dive: true })
    ForgotPasswordForm = shallow(
        &lt;Provider store={store}&gt;
            &lt;ForgotPassword {...defaultProps} {...props} /&gt;
        &lt;/Provider&gt;
    );
});

it('ForgotPassword renders correctly with email', () =&gt; {
    expect(ForgotPasswordForm).toMatchSnapshot();
});

it('check event on `Submit` button', () =&gt; {
    console.log(ForgotPasswordForm.debug())
    const emailField = ForgotPasswordForm.find('input[name=&quot;email&quot;]');
    emailField.simulate('change', { target: {value: 'test@123.com'} });
    const submitButton = ForgotPasswordForm.find(Button).find('button');
    submitButton.simulate('click').simulate('submit');
    expect(defaultProps.handleSubmit).toHaveBeenCalledTimes(10);
});
})
</code></pre>
<p>I am using material ui hence the use of createShallow. When I debug the shallow render</p>
<pre><code>&lt;Connect(ReduxForm) handleSubmit={[Function: handleSubmit]}
forgotPassword={[Function: mockConstructor] { _isMockFunction: true, getMockImplementation:
   [Function (anonymous)], mock: { calls: [], instances: [], invocationCallOrder: [], 
   results: [] }, mockClear: [Function (anonymous)], 
   mockReset: [Function (anonymous)], mockRestore: [Function (anonymous)], 
   mockReturnValueOnce: [Function (anonymous)], mockResolvedValueOnce: 
   [Function (anonymous)], mockRejectedValueOnce: [Function (anonymous)], 
   mockReturnValue: [Function (anonymous)], 
   mockResolvedValue: [Function (anonymous)], 
   mockRejectedValue: [Function (anonymous)], 
   mockImplementationOnce: [Function (anonymous)], 
   mockImplementation: [Function (anonymous)], 
   mockReturnThis: [Function (anonymous)], 
   mockName: [Function (anonymous)], getMockName: [Function (anonymous)] }} /&gt;
</code></pre>
<p>This creates an issue an issue with me trying to do the find because it doesn't find the html. I must be missing something obvious here. I have tried to dive again but that throws an error</p>
",https://stackoverflow.com/questions/65877553/jest-enzyme-reduxform-unit-testing-render-issue,"['reactjs', 'jestjs', 'material-ui', 'enzyme', 'redux-form']",72,False,1,0
Unit Testing for Conditional Rendering of Components,"<p>pretty new to the React World and would like to ask how to test for Conditional Rendering.</p>
<p>Home.js</p>
<pre><code>export default function Home() {
   const { user } = useAuth(); 
   
   return (
      &lt;&gt;
         &lt;Container className=&quot;pt-5 mt-5&quot;&gt;
            {user ? &lt;LoggedInHome /&gt; : &lt;LoggedOutHome /&gt;}
         &lt;/Container&gt;
      &lt;/&gt;
   ); 
}
</code></pre>
<p>Home.test.js</p>
<pre><code>import React from 'react'
import {shallow, configure} from 'enzyme'
import Adapter from &quot;enzyme-adapter-react-16&quot;;
import &quot;@testing-library/jest-dom/extend-expect&quot;;
import Home from &quot;../Home&quot;;
import LoggedInHome from &quot;../Dashboard&quot;;
import LoggedOutHome from &quot;../LoggedOutHome&quot;;
import { AuthContext } from &quot;../AuthContext&quot;;

let wrapper;
const user = { displayName: &quot;James&quot;, email: &quot;g@gmail.com&quot;, 
emailVerified: true };

describe(&quot;Homepage&quot;, () =&gt; {
  beforeEach(() =&gt; {
      wrapper = shallow(
        &lt;AuthContext.Provider value={user}&gt;
            &lt;Home /&gt;
        &lt;/AuthContext.Provider&gt;
   );
  });

  it(&quot;should display LoggedOutHome if not logged in&quot;, () =&gt; {
      expect(wrapper.find(LoggedOutHome)).toHaveLength(0)
  });

  it(&quot;should display LoggedInHome if logged in&quot;, () =&gt; {
      expect(wrapper.find(LoggedInHome)).toHaveLength(1);
  });
});
</code></pre>
<p>This is the error that I'm getting:</p>
<pre><code>expect(received).toHaveLength(expected)

Expected length: 1
Received length: 0
Received object: {}

  27 |
  28 |     it(&quot;should display LoggedInHome if logged in&quot;, () =&gt; {
&gt; 29 |         expect(wrapper.find(LoggedInHome)).toHaveLength(1);
     |                                         ^
  30 |     });
  31 | });
</code></pre>
<p>Seems like both LoggedInHome and LoggedOutHome both have length of 0. Not sure what is happening here. Thank you for the help!</p>
",https://stackoverflow.com/questions/68103386/unit-testing-for-conditional-rendering-of-components,"['reactjs', 'jestjs', 'conditional-statements', 'enzyme']",345,False,1,1
catch block not covered in unit testing,"<p>I have written a test case for the exception is passed but does not cover code coverage.</p>
<p>Please help me I tried many ways but doesn't resolve.</p>
<pre><code>public String checkJiraStatus(HttpURLConnection httpURLConnection) throws IOException {
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
        String inputLine;
        StringBuilder stringBuilder = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            stringBuilder.append(inputLine);
        }
        in.close();
        JSONObject jsonObject = new JSONObject(String.valueOf(stringBuilder));
        JSONObject fields = (JSONObject) jsonObject.get(&quot;fields&quot;);
        JSONObject status = (JSONObject) fields.get(&quot;status&quot;);
        return (String) status.get(&quot;name&quot;);
    }catch (IOException |JSONException ioException) {
        throw new IOException(&quot;Problem while fetching the data&quot;+ioException.getMessage());
    }
}
</code></pre>
<p>test case passes correctly but didn't give code coverage.</p>
<pre><code>@Test(expected = Exception.class)
public void testIoException() throws Exception {
    when(mockJiraFunctions.checkJiraStatus(any())).thenThrow(new 
            IOException(&quot;Problem while fetching the data&quot;));
    jiraFunctions.checkJiraStatus(any());
}
</code></pre>
",https://stackoverflow.com/questions/68086746/catch-block-not-covered-in-unit-testing,"['java', 'json', 'unit-testing', 'exception', 'junit']",1584,True,1,1
Asynchronous Unit Testing - async/await vs. Task.Result,"<p>My solution architect and I were discussing the correct way to unit test the asynchronous code.</p>
<p>He prefers using <code>void [Test]</code> methods, and asserting <code>Task.Result</code>, while I feel that asynchronous methods should be tested with <code>async/await [Test]</code> methods.</p>
<p>Somehow, I feel that using Task.Result is incorrect way to testing the asynchronous code, but can't justify or pin-point exactly why?</p>
<p>For example, given the below code:</p>
<pre><code>    public class SomeService 
    {
        public async Task&lt;bool&gt; ProcessSomething(string request)
        {
           return await Repository.Save(request);
        }
    }
</code></pre>
<p><strong>Method 1: Task.Result</strong></p>
<pre><code>    [Test]
    public void ServiceProcessTest()
    {          
       var sut = new SomeService();

       // Use Task.Result
       var unusedResult= sut.ProcessSomething(&quot;Hello world!&quot;).Result;
       
       A.CallTo(() =&gt; Repository.Save(A&lt;string&gt;&gt;.Ignored)).MustHaveHappenedOnceExactly();
    }
</code></pre>
<p><strong>Method 2: async/await</strong></p>
<pre><code>    [Test]
    public async Task ServiceProcessTest()
    {          
       var sut = new SomeService();

       // Use async/await
       var unusedResult= await sut.ProcessSomething(&quot;Hello world!&quot;);
       
       A.CallTo(() =&gt; Repository.Save(A&lt;string&gt;&gt;.Ignored)).MustHaveHappenedOnceExactly();
    }
</code></pre>
<p>Which once should we be using, and why?
If both are correct, then are there times when one is preferred over the other?</p>
",https://stackoverflow.com/questions/66957032/asynchronous-unit-testing-async-await-vs-task-result,"['c#', 'unit-testing', 'asynchronous', 'async-await', 'nunit']",952,True,1,1
Mocking Firebase function with Jest (Unit testing),"<p>I am creating unit tests, but I can find a way to mock firebase functions and spesify the return type when I call them. Below I posted the what I want to mock(account.service.ts) and what test I currenlty have. I want to mock and specify what is to be returned with admin... (aka set the resp object value).</p>
<p>import * as admin from 'firebase-admin';</p>
<p>account.service.ts</p>
<pre><code>    const resp = admin
        .auth()
        .createUser({
            email: registerDto.email,
            emailVerified: false,
            password: registerDto.password,
            displayName: registerDto.displayName,
            disabled: false,
        })
        .then(
            (userCredential): Account =&gt; ({
                uid: userCredential.uid,
                email: userCredential.email,
                emailVerified: userCredential.emailVerified,
                displayName: userCredential.displayName,
                message: 'User is successfully registered!',
            }),
        )
        .catch((error) =&gt; {
            // eslint-disable-next-line max-len
            throw new HttpException(`${'Bad Request Error creating new user: '}${error.message}`, HttpStatus.BAD_REQUEST);
        });
</code></pre>
<p>account.service.spec.ts</p>
<pre><code>describe('61396089', () =&gt; {
        afterEach(() =&gt; {
            jest.restoreAllMocks();
        });

        const obj = {
            uid: 'uid',
            email: 'email',
            emailVerified: 'emailVerified',
            displayName: 'displayName',
            message: 'User is successfully registered!',
        };

        const jestAdminMock = {
            admin: () =&gt; ({
                auth: () =&gt; ({
                    createUser: () =&gt; ({
                        then: () =&gt; ({
                            catch: () =&gt; obj,
                        }),
                    }),
                }),
            }),
        };

        it('should pass', () =&gt; {
            const mockDataTable = {
                admin: jest.fn().mockReturnThis(),
                auth: jest.fn().mockReturnThis(),
                createUser: jest.fn().mockReturnThis(),
                then: jest.fn().mockReturnThis(),
                catch: jest.fn().mockReturnValueOnce(obj),
            };
            jest.spyOn(jestAdminMock, 'admin').mockImplementationOnce(() =&gt; mockDataTable);
            const actual = service.registerUser(registerDTO);
            expect(actual).toBe(obj);
        });
    });
});
</code></pre>
",https://stackoverflow.com/questions/68715203/mocking-firebase-function-with-jest-unit-testing,"['node.js', 'typescript', 'firebase', 'unit-testing', 'jestjs']",2202,True,1,1
camunda unit testing with MockitoJUnitRunner and SpringRunner,"<p>I am writing test cases for Camunda workflows. I am using SpringRunner <code>@RunWith(SpringRunner.class)</code> and have the following properties in Test class required for the test execution</p>
<pre><code>        @Autowired
        private ProcessEngine processEngine;
    
        @Rule
        @ClassRule
        public static ProcessEngineRule rule;
    
        @PostConstruct
        void initRule() {
            rule = TestCoverageProcessEngineRuleBuilder.create(processEngine).withDetailedCoverageLogging().build();
        }
        @Mock
        ProcessScenario someProcessScenario;
</code></pre>
<p>Further, in each test I instantiate the ProcessInstance like this</p>
<pre><code>ProcessRunner.ExecutableRunner.StartingByStarter starter = Scenario.run(someProcessScenario)
            .startBy(() -&gt; {
                processInstance = rule.getRuntimeService().startProcessInstanceByKey(&quot;PROCESS_DEFINITION&quot;, properties);
                return processInstance;
            });

starter.engine(rule.getProcessEngine());
</code></pre>
<p>This configuration works fine and I assert using BpmnAwareTests and all tests pass. The dependencies that I have used in the pom are</p>
<pre><code>&lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm.assert&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-bpm-assert&lt;/artifactId&gt;
        &lt;version&gt;5.0.0&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm.extension&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-bpm-assert-scenario&lt;/artifactId&gt;
        &lt;version&gt;1.1.1&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm.extension&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-bpm-process-test-coverage&lt;/artifactId&gt;
        &lt;version&gt;0.3.2&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm.extension.mockito&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-bpm-mockito&lt;/artifactId&gt;
        &lt;scope&gt;test&lt;/scope&gt;
        &lt;version&gt;4.12.0&lt;/version&gt;
    &lt;/dependency&gt;
</code></pre>
<p>Since this setup instantiates the spring container for every test class, I thought to change few classes to run with MockitoJUnitRunner than SpringRunner.
So I changed those to <code>@RunWith(MockitoJUnitRunner.class)</code></p>
<p>and initialize the required properties like this:</p>
<pre><code>@Rule
public ProcessEngineRule rule = new ProcessEngineRule();

@Mock
ApplicationEventPublisher eventPublisher;

@Mock
ProcessScenario someOtherProcess;

@Mock
SomeClass someclass;


@Before
public void setUp() throws MyCustomiException {
    MockitoAnnotations.openMocks(this);
    MyDelegate myDelegate = new MyDelegate(someclass);
    Mocks.register(&quot;myDelegate&quot;, myDelegate);
    ......
}
</code></pre>
<p>ProcessInstance is instantiated in all test cases as above.
These tests also run smooth and pass independently.
However, when I run all tests (some which run with SpringRunner and others with MockitoJUnitRunner) they do not pass. All tests with SpringRunner fail and the ones that execute after SpringRunner also fail.
The error is <strong>java.lang.IllegalStateException: No ProcessEngine found to be registered with ProcessEngines!</strong></p>
",https://stackoverflow.com/questions/70366939/camunda-unit-testing-with-mockitojunitrunner-and-springrunner,"['spring-boot', 'junit', 'mockito', 'camunda', 'springrunner']",1734,False,1,2
Unit testing a c# Method using Moq,"<p>I'm new to unit testing and the language c sharp and I'm trying to unit test by mocking <code>ISessionStorageService</code> to test the <code>HasGlobaladminaccess</code>  function but my setup does not seem to work as expected.</p>
<pre class=""lang-cs prettyprint-override""><code>public class Context
{
    public asyncTask&lt;bool&gt;HasGlobalAdminAccessAsync(Blazored.SessionStorage.ISessionStorageService sessionStorage)
    {
        return await HasAccessAsync(sessionStorage, Config.Constants.HAS_GLOBALE_ADMIN_ACCESS);
    }

    private async Task&lt;bool&gt; HasAccessAsync(Blazored.SessionStorage.ISessionStorageService sessionStorage, string sessionStorageKey)
    {
        ILogger _logger = Log.ForContext&lt;ContextHelpers&gt;();

        try
        {
            _logger.Debug(&quot;HasAccessAsync({sessionStorageKey})&quot;, sessionStorageKey);
            var access = await sessionStorage.GetItemAsync&lt;bool&gt;(sessionStorageKey);
            _logger.Debug(&quot;HasAccessAsync({sessionStorageKey})::access={access}&quot;, sessionStorageKey, access);
            return access;
        }
        catch (Exception ex)
        {
            _logger.Debug(&quot;HasAccessAsync({sessionStorageKey})::exception={ex}&quot;, sessionStorageKey, ex.Message);
            return false;
        }
    }
}
</code></pre>
<p>My test method</p>
<pre class=""lang-cs prettyprint-override""><code>private readonly Mock&lt;ISessionStorageService&gt; MockStorage = new Mock&lt;ISessionStorageService&gt;();

[Fact()]
public async Task HasGlobalAdminAccessAsyncTest()
{
    string guid = System.Guid.NewGuid().ToString();
    Context context = new Context();
    MockStorage.Setup(foo =&gt; foo.GetItemAsync&lt;bool&gt;(guid)).ReturnsAsync(true);
    var person = await context.HasGlobalAdminAccessAsync(MockStorage.Object);
    Assert.True(person , guid);
}
</code></pre>
",https://stackoverflow.com/questions/68757431/unit-testing-a-c-method-using-moq,"['c#', 'unit-testing', 'moq']",156,True,1,1
Second function in unit testing isn&#39;t running,"<p>I am doing this simple unittesting and I am a newbie to python.  Heres the code</p>
<pre><code>caplet.py
    
def capeach(text):
        return text.capitalize()
</code></pre>
<p>and the unit testing code is below.</p>
<pre><code>UT.py

import unittest
import caplet


class TestCap(unittest.TestCase):
    
    def test_one_word(self):
        text = 'python'
        result = caplet.capeach(text)
        self.assertEqual(result,'Python')

    def multiple_words(self):
        text = 'python is good'
        result = caplet.capeach(text)
        self.assertEqual(result,'Python Is Good')


if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>When I run <code>UT.py</code>, I get <code>Ran 1 test in 0.001s</code>. Somehow second part of the code <code>multiple_words</code> is not running.</p>
<p>I am using Spyder IDE for running the code.  I also tried with the command line <code>python3 UT.py</code></p>
<p>I don't know what I am missing. Can anyone help. Thank you.</p>
",https://stackoverflow.com/questions/68486279/second-function-in-unit-testing-isnt-running,"['python-3.x', 'unit-testing']",22,False,1,0
Angular unit testing: Function not being called,"<p>I am trying to unit test my service and cannot seem to get it working.  The concept is that when <code>setEmployees()</code> is called with an empty array, the service fetches employees from the server.</p>
<p><strong>Service</strong></p>
<pre><code>  setEmployees( employees : Employee[] ) {
    console.log(&quot;Setting employees...&quot;, employees)
    if (employees &amp;&amp; employees.length) {
      this.employees.next(employees)
      this.storage.set('employees', employees);
    } else {
      this.getEmployees().subscribe()
    }
  }

  getEmployees() {
    console.log(&quot;getting employees...&quot;)
    let url = `${this.base_url}/employees`;
    return this.http.get&lt;Employee[]&gt;(url).pipe(
      tap(employees =&gt; {
        console.log(&quot;got em&quot;, employees)
        this.setEmployees(employees)
        this.storage.set('employees', employees)
      })
    )
  }

  returnEmployees() : IEmployee[] {
    return Object.assign([], this.employees.getValue())
  }
</code></pre>
<p><strong>Test</strong></p>
<pre><code>it('should set employees correctly', fakeAsync(() =&gt; {
  let dummy = [{id: 1, name: 'Jeremy'}, {id: 2, name: 'Paige'}]
  spyOn(employeeService, 'getEmployees').and.returnValue(of(dummy));
  employeeService.setEmployees([]);
  tick();
  expect(employeeService.returnEmployees()).toEqual(dummy)
}))
</code></pre>
<p><strong>Test Response</strong></p>
<pre><code>Expected $.length = 0 to equal 2.
Expected $[0] = undefined to equal Object({ id: 1, name: 'Jeremy' }).
Expected $[1] = undefined to equal Object({ id: 2, name: 'Paige' }).
</code></pre>
<p>It's also worth noting that the <code>console.log()</code> statements don't occur in the expected order.  When running this test I see the following in the console:</p>
<pre><code>getting employees...
Setting employees... []
</code></pre>
<p>...when I would've expected to see:</p>
<pre><code>Setting employees... []
getting employees...
got em [{id: 1, name: 'Jeremy'}, {id: 2, name: 'Paige'}]
Setting employees... [{id: 1, name: 'Jeremy'}, {id: 2, name: 'Paige'}]
</code></pre>
<p>Clearly something isn't firing as expected but I'm not sure where the issue lies.</p>
",https://stackoverflow.com/questions/70426779/angular-unit-testing-function-not-being-called,"['angular', 'unit-testing', 'karma-jasmine']",700,False,1,1
Vue 3 Unit Testing - Cannot find module,"<p>I'm pretty new to Unit Testing but have just started writing some in my Vue 3 application.</p>
<p>In the component I am testing I import some interface types from a models sub-folder like this:</p>
<pre><code>import { ITEM } from &quot;../models/product.models&quot;;
</code></pre>
<p>This all works fine when in the component but in my Unit Test I get this error:</p>
<pre><code>Cannot find module '../models/product.models' from 'Product.vue'


 &gt; 88 | import { ITEM } from &quot;../models/product.models&quot;;
         | ^

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
</code></pre>
<p>What do I need to do to get the test to evaluate that import correctly?</p>
<p>this is the config I have for jest:</p>
<pre><code>&quot;jest&quot;: {
    &quot;globals&quot;: {
      &quot;vue-jest&quot;: {
        &quot;hideStyleWarn&quot;: true
      }
    },
    &quot;preset&quot;: &quot;@vue/cli-plugin-unit-jest&quot;,
    &quot;testMatch&quot;: [
      &quot;**/src/**/*.spec.[jt]s?(x)&quot;
    ],
    &quot;transform&quot;: {
      &quot;^.+\\.vue$&quot;: &quot;vue-jest&quot;
    },
    &quot;transformIgnorePatterns&quot;: [
      &quot;&lt;rootDir&gt;/node_modules/(?!primevue/.*)&quot;
    ]
  }
</code></pre>
<p>tsconfig.js</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;esnext&quot;,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;strict&quot;: true,
    &quot;jsx&quot;: &quot;preserve&quot;,
    &quot;importHelpers&quot;: true,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;experimentalDecorators&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;noImplicitAny&quot;: false,
    &quot;esModuleInterop&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;sourceMap&quot;: true,
    &quot;baseUrl&quot;: &quot;.&quot;,
    &quot;types&quot;: [
      &quot;webpack-env&quot;,
      &quot;jest&quot;
    ],
    &quot;paths&quot;: {
      &quot;@/*&quot;: [
        &quot;src/*&quot;
      ]
    },
    &quot;lib&quot;: [
      &quot;esnext&quot;,
      &quot;dom&quot;,
      &quot;dom.iterable&quot;,
      &quot;scripthost&quot;
    ]
  },
  &quot;include&quot;: [
    &quot;src/**/*.ts&quot;,
    &quot;src/**/*.tsx&quot;,
    &quot;src/**/*.vue&quot;,
    &quot;tests/**/*.ts&quot;,
    &quot;tests/**/*.tsx&quot;],
  &quot;exclude&quot;: [
    &quot;node_modules&quot;
  ]
}
</code></pre>
",https://stackoverflow.com/questions/69925671/vue-3-unit-testing-cannot-find-module,"['vue.js', 'unit-testing']",1450,False,1,1
Rails unit testing: can&#39;t get edit path,"<p>I'm following The Ruby on Rails by Michael Hart. In chapter 10, I'm getting unexpected errors when running unit tests.
This is my error:</p>
<blockquote>
<p>ERROR UsersControllerTest#test_should_redirect_edit_when_not_logged_in (1.01s)
Minitest::UnexpectedError:         ActionController::UrlGenerationError: No route matches {:action=&gt;&quot;edit&quot;, :controller=&gt;&quot;users&quot;}, missing required keys: [:id]
test/controllers/users_controller_test.rb:16:in `block in class:UsersControllerTest'</p>
</blockquote>
<p>This is my routes:</p>
<pre><code>Rails.application.routes.draw do
  scope &quot;(:locale)&quot;, locale: /#{I18n.available_locales.join(&quot;|&quot;)}/ do
    root &quot;static_pages#home&quot;
    get &quot;/help&quot;, to: &quot;static_pages#help&quot;
    get &quot;/about&quot;, to: &quot;static_pages#about&quot;
    get &quot;/contact&quot;, to: &quot;static_pages#contact&quot;
    get &quot;/signup&quot;, to: &quot;users#new&quot;
    get &quot;/login&quot;, to: &quot;sessions#new&quot;
    post &quot;/login&quot;, to: &quot;sessions#create&quot;
    delete &quot;/logout&quot;, to: &quot;sessions#destroy&quot;
    resources :users
  end
end
</code></pre>
<p>This is my code in user_contrller_test</p>
<pre><code>require &quot;test_helper&quot;

class UsersControllerTest &lt; ActionDispatch::IntegrationTest
  
  def setup
    @user = users(:michael)
    @other_user = users(:archer)
  end
  
  test &quot;should get new&quot; do
    get signup_path
    assert_response :success
  end
  
  test &quot;should redirect edit when not logged in&quot; do
    get edit_user_path(@user)
    assert_not flash.empty?
    assert_redirected_to login_url
  end
end
</code></pre>
<p>I've defined Michael in fixtures. I try to use path like <code>get :edit, user_id: @user.id</code> but it's still an error. I've run the server and access URLs like &quot;/user/765/edit&quot;, it's successfully redirecting to the login URL.</p>
<p>How can I fix those.</p>
",https://stackoverflow.com/questions/68361627/rails-unit-testing-cant-get-edit-path,"['ruby-on-rails', 'unit-testing']",125,False,0,1
Unit testing Angular router.events.pipe followed by subscribe,"<p>I've following angular code:</p>
<pre><code>changeMetaTags() {
  let metaData: any;
  this.router.events.pipe(
    filter(event =&gt; event instanceof NavigationEnd),
    map(() =&gt; {
      let child = this.activatedRoute.firstChild;
      while (child) {
          if (child.firstChild) {
            child = child.firstChild;
          } else if (child.snapshot.data) {
            return child.snapshot.data;
          } else {
            return null;
          }
      }
      return null;
    })
  ).subscribe( (data: any) =&gt; {
    metaData = data;
    if (data['title']) {
      this.translate.get(data['title']).subscribe((data: string) =&gt; {
        this.seoService.updateTitle(data);
      })
    }
  });

  this.translate.onLangChange.subscribe((event: LangChangeEvent) =&gt; {
    if (metaData['title']) {
      this.translate.get(metaData['title']).subscribe((metaData: string) =&gt; {
        this.seoService.updateTitle(metaData);
      })
    }
  });
}
</code></pre>
<p>I'm trying to write unit test case for above function, but unable to make progress. Can anyone please help to write jasmine unit test for changeMetaTags() function.</p>
<p>Also please comment if you need more details about the code.</p>
<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/70069933/unit-testing-angular-router-events-pipe-followed-by-subscribe,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-runner']",531,False,0,1
Saving data to database in unit testing,"<p>Why it's impossible to create dummy data in unit testing like below?</p>
<pre><code>DB::table('users')-&gt;insert([
[
'name' =&gt; 'test',
],
</code></pre>
<p>I saw that in order to create data you need to create factory, but when I try to insert data like this:</p>
<pre><code>User::factory()-&gt;count(1)-&gt;create([
'name' =&gt; 'test'
]);
</code></pre>
<p>It also don't insert new data.
What is the easiest way to to that? Thank you</p>
",https://stackoverflow.com/questions/68665606/saving-data-to-database-in-unit-testing,"['laravel', 'unit-testing']",161,True,0,1
Write If else for unit testing jasmine,"<p>I just start learn using jasmine. I am confused if I need testing function which the value is the function as well, like this is the case
on <strong>component.ts</strong></p>
<pre><code> validationLoadListDownload() {
    if (this.getGroupId === 0) {
      this.loadListDownloadRequest();
    } else {
      this.loadListDownloadRequestGroup();
    }
  }
</code></pre>
<p>if like that, how do we write it on component.spec.ts? I am confused, thank you</p>
",https://stackoverflow.com/questions/68125555/write-if-else-for-unit-testing-jasmine,"['angular', 'jasmine', 'karma-jasmine']",48,True,0,1
Java Swing MVP unit testing with Mockito,"<p><strong>Description</strong></p>
<p>I have a simple Java Swing application implementing the Model-View-Presenter pattern. My aim is to be able to test the logic behind &quot;rendering&quot; the view.</p>
<p><a href=""https://i.stack.imgur.com/VgFCD.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VgFCD.png"" alt=""enter image description here"" /></a></p>
<p>Here is the presenter and associated interface:</p>
<pre><code>public class MainPresenter implements IViewListener
{
    private final IMainWindow _view;
    private final ITaxCalculator _model;

    public MainPresenter(IMainWindow view, ITaxCalculator model)
    {
        this._view = view;
        this._model = model;
    }

    @Override
    public void onCalculateButtonClicked(double amount)
    {
        // perform calculations
        this._model.setTotalSales(salesAmount);
        double countySalesTax = this._model.getCountySalesTax();
        double stateSalesTax = this._model.getStateSalesTax();
        double totalSalesTax = this._model.getTotalSalesTax();

        // update the view
        this._view.setCountySalesTaxField(countySalesTax);
        this._view.setStateSalesTaxField(stateSalesTax);
        this._view.setTotalSalesTaxField(totalSalesTax);
    }
}

public interface IViewListener
{
    public void onCalculateButtonClicked(double amount);
}
</code></pre>
<p>Here is the model and its associated interface:</p>
<pre><code>public interface ITaxCalculator
{
    public double getCountySalesTax();
    public double getStateSalesTax();
    public double getTotalSalesTax();
    public void setTotalSales(double totalSales);
}

public class TaxCalculator implements ITaxCalculator
{
    protected double _totalSales;
    
    public TaxCalculator()
    {
        
    }
    
    public TaxCalculator(double totalSales)
    {
        this._totalSales = totalSales;
    }
    
    public void setTotalSales(double totalSales)
    {
        this._totalSales = totalSales;
    }
    
    public double getCountySalesTax()
    {
        return 0.02 * this._totalSales;
    }
    
    public double getStateSalesTax()
    {
        return 0.04 * this._totalSales;
    }
    
    public double getTotalSalesTax()
    {
        return this.getCountySalesTax() + this.getStateSalesTax();
    }//getTotalSalesTax
}//class
</code></pre>
<p>Here is the interface which the view implements (I've omitted the actual view which extends JFrame, as that is quite a lot of code):</p>
<pre><code>public interface IMainWindow
{
    public void addListener(IViewListener listener);
    
    public double getSalesAmountEntered();
    public void setSalesAmountEntered(double amount);
    
    public double getCountySalesTaxField();
    public void setCountySalesTaxField(double amount);
    
    public double getStateSalesTaxField();
    public void setStateSalesTaxField(double amount);
    
    public double getTotalSalesTaxField();
    public void setTotalSalesTaxField(double amount);
    
    public void clear();
}
</code></pre>
<p><strong>Unit testing problems</strong></p>
<p>I'm using JUnit 4 and Mockito (here is an extract from my <code>pom.xml</code> file):</p>
<pre><code>&lt;dependency&gt;
        &lt;groupId&gt;junit&lt;/groupId&gt;
        &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;version&gt;4.13.2&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    
    &lt;dependency&gt;
        &lt;groupId&gt;org.mockito&lt;/groupId&gt;
        &lt;artifactId&gt;mockito-inline&lt;/artifactId&gt;
        &lt;version&gt;3.7.7&lt;/version&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;3.7.7&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
</code></pre>
<p>Now, I am trying to unit-test the presenter class. I normally work with C#, and only just started with Java. I've implemented a similar MVP pattern with WinForms before, using FakeItEasy for unit testing. In that situation, I might do something like the following, and it yields the expected results:</p>
<pre><code>// arrange
var fakeView = A.Fake&lt;IMainWindow&gt;();
A.CallTo(() =&gt; fakeView.GetAmount()).Returns(100);
var fakeModel = A.Fake&lt;ITaxCalculator&gt;();
var presenter = new MainPresenter(fakeView, fakeModel);

</code></pre>
<p>In this particular example, I am trying to achieve something similar with the following JUnit test.</p>
<pre><code>public class MainPresenter_Test
{
    @Mock
    IMainWindow mockView;
    
    @Mock
    ITaxCalculator mockModel;
    
    @Before
    public void setUp()
    {
        MockitoAnnotations.initMocks(this);
    }
    
    @Test
    public void onCalculateButtonClicked_Test()
    {
        // arrange
        double amount = 100;
        when(mockView.getSalesAmountEntered()).thenReturn(amount);
        when(mockModel.getCountySalesTax()).thenReturn(2.00);
        when(mockModel.getStateSalesTax()).thenReturn(4.00);
        when(mockModel.getTotalSalesTax()).thenReturn(6.00);
        MainPresenter presenter = new MainPresenter(mockView, mockModel);
        
        // act
        presenter.onCalculateButtonClicked(mockView.getSalesAmountEntered());
        double actualCountySalesTax = mockView.getCountySalesTaxField();
        double actualStateSalesTax = mockView.getStateSalesTaxField();
        double actualTotalSalesTax = mockView.getTotalSalesTaxField();
        
        // assert
        assertEquals(2.00, actualCountySalesTax, 0);
    }
</code></pre>
<p>However, the assert fails, because the actual value is always 0. Am I doing something wrong in the setup of the unit test?</p>
",https://stackoverflow.com/questions/68773316/java-swing-mvp-unit-testing-with-mockito,"['java', 'swing', 'unit-testing', 'user-interface', 'mockito']",98,False,0,0
Django unit testing authentication token not accepted,"<p>I've checked the DRF official documentation, have read the below posts and copy-pasted code from some answers to avoid any typo, but I still can't authenticate in my unit tests. I always get a 401 response code.</p>
<p>I have a custom User model that just has a couple of none required fields so far.</p>
<p>Can anyone see any logic issue, or error in the code?
Could the issue originate from having a proper local DB and a testing DB and the authentication mixing both up somehow?</p>
<p>I've had to use <code>self.client.force_authenticate(user=self.user, token=None)</code> to bypass the authentication issue. But that defeats the purpose of the tests.</p>
<p>Checked posts that did not solve the problem:</p>
<ul>
<li><a href=""https://www.django-rest-framework.org/api-guide/testing/#forcing-authentication"" rel=""nofollow noreferrer"">DRF documentation</a></li>
<li><a href=""https://stackoverflow.com/questions/54242535/how-do-i-pass-authentication-bearer-tokens-to-http-methods-in-django-test-client"">SO post 1</a></li>
<li><a href=""https://stackoverflow.com/questions/31377207/django-authenticate-unit-test"">SO post 2</a></li>
<li><a href=""https://stackoverflow.com/questions/66291815/cannot-authenticate-test-requests-with-both-user-token-and-api-key-in-django-res"">SO post 3</a></li>
</ul>
<p>So here's my code.</p>
<p>Unit test</p>
<pre class=""lang-py prettyprint-override""><code>from django.test.testcases import SimpleTestCase
from django.urls import reverse, resolve
from rest_framework import status
from rest_framework.test import APITestCase
from rest_framework.authtoken.models import Token
from test_project.models.user import *
from test_project.views import UserViewSet
# from django.contrib.auth.models import User
from test_project.models import *


class UserAPIViewTests(APITestCase):

  def setUp(self) -&gt; None:
    self.users_list_url = reverse('user-list')
    self.users_detail_url = reverse('user-detail', args=[1])
    self.user =User.objects.create(
      username=&quot;admin&quot;,
      password=&quot;admin&quot;,
      email=&quot;test@necktie.com&quot;,
      first_name=&quot;test first name&quot;,
      last_name=&quot;test last name&quot;,
      is_superuser=True,
      is_staff=True,
      is_active=True
    )
    self.token = Token.objects.create(user=user)
    self.client.credentials(HTTP_AUTHORIZATION='Bearer ' + self.token.key)

  # The testing DB is automatically torn down, no implementation required for those tests
  def tearDown(self) -&gt; None:
    pass


  def test_get_users_authenticated(self):
    &quot;&quot;&quot;
    Test that an authenticated user can get the users' list
    &quot;&quot;&quot;
    response = self.client.get(self.users_list_url)
    self.assertEquals(response.status_code, status.HTTP_200_OK)

</code></pre>
<p>User model</p>
<pre class=""lang-py prettyprint-override""><code>from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _

class User(AbstractUser):
  &quot;&quot;&quot;auth/login-related fields&quot;&quot;&quot;
  gender = models.CharField(_('gender'), max_length=50, null=True)
  nationality = models.CharField(_('nationality'), max_length=50, null=True)


  def __str__(self):
    return &quot;{} {}&quot;.format(self.first_name, self.last_name)

</code></pre>
<p>User View</p>
<pre class=""lang-py prettyprint-override""><code>from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import permissions
from ..models.user import User
from ..serializers.user import *
from ..permissions import *

class UserViewSet(viewsets.ModelViewSet):
  &quot;&quot;&quot;
  This viewset automatically provides `list`, `create`, `retrieve`,
  `update` and `destroy` actions.
  &quot;&quot;&quot;
  queryset = User.objects.all()
  serializer_class = UserSerializer

  def get_permissions(self):
    &quot;&quot;&quot;
    Method to apply permissions depending on request type (GET, PUT etc.)
    &quot;&quot;&quot;
    if self.request.method == 'GET':
      return [permissions.IsAuthenticated(), IsStaff()]
    else:
      return [permissions.IsAuthenticated(), IsSuperuser()]
</code></pre>
<p>User serializers</p>
<pre class=""lang-py prettyprint-override""><code>from rest_framework import serializers
from ..models.user import User


class UserSerializer(serializers.ModelSerializer):
  &quot;&quot;&quot;
  Serializer for all actions on User model
  &quot;&quot;&quot;

  class Meta:
    model = User
    fields = [
      'id',
      'username',
      'first_name',
      'last_name',
      'is_staff',
      'is_superuser',
      'is_active',
      'date_joined'
    ]

</code></pre>
<p>Thanks for the help!</p>
",https://stackoverflow.com/questions/69494821/django-unit-testing-authentication-token-not-accepted,"['django', 'unit-testing', 'authentication', 'django-rest-framework']",384,False,0,0
Combatting large data providers in unit testing,"<p>I am performing validation tests for numerous fields on an object, each of which has numerous  validation rules (<code>required</code>, <code>integer</code>, <code>unique</code> etc.). Rather than writing a test function for each <code>field</code> and <code>rule</code>, I have a <code>data provider</code> which is supplied to a <code>generic</code> test function.</p>
<p>A contrived example of the <code>data provider</code>:</p>
<pre class=""lang-php prettyprint-override""><code>public function validationErrorsProvider()
{
    return [
        [ 'field', 'input', 'error message' ],
        [ 'field', 'input', 'error message' ],
        [ 'field', 'input', 'error message' ],
    ];
}
</code></pre>
<p>The <code>data provider</code> is then used by a generic test method which asserts that for <code>field</code> with <code>input</code> it sees the <code>error message</code>.</p>
<pre class=""lang-php prettyprint-override""><code>/**
 * @test
 * @dataProvider validationErrorsProvider
 */
public function will_fail_with_errors_when_input_is_invalid($field, $input, $error)
{
    // do some stuff
}
</code></pre>
<p>This works fine but the <code>data provider</code> is becoming increasingly large as I add further fields and rules to be tested (20 - 30 elements in the <code>validationErrorsProvider</code> array). It appears more complicated that some of my tests.</p>
<p>Is this just something that happens, or is there an alternative? I have considered splitting the <code>data provider</code> into multiple <code>providers</code>, each holding just the data for a given <code>field</code>. This doesn't do anything other than make the <code>data provider</code> appear smaller.</p>
",https://stackoverflow.com/questions/68261407/combatting-large-data-providers-in-unit-testing,"['laravel', 'testing', 'phpunit']",185,True,0,1
Spring Boot Unit Testing MockMvc Null Body,"<p>I am having dificulties with using MockMvc.
Here I have simple Service and controller classes:</p>
<p>Service:</p>
<pre class=""lang-java prettyprint-override""><code>@Slf4j
@Service
public class EmployeeService {
    //...

    public Employee GetSample() {
    //...
    //filling Employee Entities
    return new Employee(
            &quot;Harriet&quot;
            , &quot;random&quot;
            , 25);
    }
}
</code></pre>
<p>controller:</p>
<pre class=""lang-java prettyprint-override""><code>@RestController
@RequestMapping(value = &quot;/info&quot;)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Validated
public class EmployeeController {
    private final EmployeeService employeeService;

    @PostMapping(&quot;/GetEmployee&quot;)
    public ResponseEntity&lt;Employee&gt; GetEmployee() {
       Employee employee = employeeService.GetSample();
       return new ResponseEntity&lt;&gt;(employee, HttpStatus.OK);
    }
}
</code></pre>
<p>Test:</p>
<pre class=""lang-java prettyprint-override""><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class EmployeeTestCase {
    private MockMvc mockMvc;

    @InjectMocks
    private EmployeeController EmployeeController;

    @Mock
    private EmployeeService employeeService;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.standaloneSetup(employeeController).build();
    }

    @Test
    public void getEmployee() throws Exception {
        this.mockMvc.perform(MockMvcRequestBuilders.post(&quot;/info/GetEmployee&quot;)).andDo(print());
    }
}
</code></pre>
<p><strong>when I try to use MockMvc I get null body. It seems employee is null. But I didn't understand why.</strong>
I thought that when test uses <code>perform</code>, it should initialise employee and later on it should't be null.
I tried to cut the code as much as possible. I hope it is not long.</p>
<p>Note : also tried to use <code>Mockito.when(employeeController.GetEmployee()).thenCallRealMethod();</code></p>
",https://stackoverflow.com/questions/69976097/spring-boot-unit-testing-mockmvc-null-body,"['spring-boot', 'unit-testing', 'mockmvc']",981,True,0,1
Visual Studio 2019 Live Unit Testing Crashes,"<p>I'm trying to use Live Unit Testing with my nUnit tests, but it crashes every time I start it.  It crashes whether I start it manually or on solution load.  I've restarted VS multiple times, reinstalled it, <a href=""https://stackoverflow.com/a/63955708/127888"">deleted the persisted data per this answer</a> and now I'm out of ideas.</p>
Output Window
<pre><code>[15:23:48.443 Info] Live Unit Testing started.
[15:23:48.471 Info] Building solution.
[15:23:52.493 Info] - BuildManager - Build performance issue: compiler called to produce 
 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\i\Wa531.SAR_Log\
   Debug\netstandard2.1\Wa531.SAR_Log.dll' 
again after build already succeeded.
[15:23:53.205 Info] Build completed with failures. Errors were logged under 
   'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\diag\'.
[15:23:58.971 Info] Started executing tests from 
   C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\t\Wa531.SAR_Log.Tests\
   Debug\netcoreapp3.1\Wa531.SAR_Log.Tests.dll. 
[15:24:00.741 Info] Finished executing tests. (Passed: 24, Failed: 0, Skipped: 0, Not Executed: 0)
[15:24:05.156 Error] Live Unit Testing is being turned off because a process that it depends on has
   either exited unexpectedly or encountered an unrecoverable exception. Restart Visual Studio before
   trying to start Live Unit Testing again.
[15:24:05.156 Error] Log files present in the '%Temp%\servicehub\logs' folder may contain information 
   that can help diagnose this problem.
[15:24:05.196 Info] Live Unit Testing stopped.
</code></pre>
%Temp%\servicehub\logs
<pre><code>01/02/2021 15:20:09 Pacific Standard Time: Warning : 14 :Aborting pending request &quot;2&quot; because 
   the connection was lost.
01/02/2021 15:20:09 Pacific Standard Time: Warning : 14 :Aborting pending request &quot;12&quot; because 
   the connection was lost.
</code></pre>
Build.log
<pre><code>[15:23:52.493 Info]
 - BuildManager - Build performance issue: compiler called to 
   produce 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\i\Wa531.SAR_Log\
   Debug\netstandard2.1\Wa531.SAR_Log.dll' again after build already succeeded.
[15:23:53.183 Verbose] 
- BuildManager - 
   C:\Users\willi\.nuget\packages\resizetizer.nt\0.2.0\buildTransitive\
   Resizetizer.NT.targets(155,3): error : One or more errors occurred.
[15:23:53.186 Verbose] 
- BuildManager - Some of the file paths defined in the 
   csproj under the Live Unit Testing build path are missing. Verify whether 
   these files should be present under the Live Unit Testing build path and if 
   necessary update the csproj definition to look these files up in a 
   different place.
[15:23:53.188 Verbose] 
- BuildManager - Item _OutputPathItem 
   'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\
   Wa531.SAR_Log.Android\bin\Debug\' evaluated via:
     _OutputPathItem: '$(OutDir)' @ C:\Program Files (x86)\Microsoft Visual 
       Studio\2019\Enterprise\MSBuild\Current\Bin\
       Microsoft.Common.CurrentVersion.targets:275
  OutDir: 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\
           Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\' 
           @ C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\
             Wa531.SAR_Log.Android.csproj:0
[15:23:53.188 Verbose] 
- BuildManager - Item AppConfigFileDestination 
    'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\
    Wa531.SAR_Log.Android\bin\Debug\Wa531.SAR_Log.Android.dll.config' 
    evaluated via:
     AppConfigFileDestination: '$(OutDir)$(TargetFileName).config' 
      @ C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild
\Current\Bin\Microsoft.Common.CurrentVersion.targets:306
  OutDir: 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\
     Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\' 
     @ C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\
       Wa531.SAR_Log.Android.csproj:0
  TargetFileName: '$(TargetName)$(TargetExt)' @ C:\Program Files (x86)\
    Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\
    Bin\Microsoft.Common.CurrentVersion.targets:213
  TargetName: '$(AssemblyName)' @ C:\Program Files (x86)\Microsoft Visual Studio\
    2019\Enterprise\MSBuild\Current\Bin\
    Microsoft.Common.CurrentVersion.targets:205
  AssemblyName: 'Wa531.SAR_Log.Android' @ 
      C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\
      Wa531.SAR_Log.Android.csproj:14
  TargetExt: '.dll' @ C:\Program Files (x86)\Microsoft Visual Studio\2019\
      Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets:184
[15:23:53.188 Verbose] 
- BuildManager - Item _DebugSymbolsOutputPath 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\Wa531.SAR_Log.Android.pdb' evaluated via:
_DebugSymbolsOutputPath: '@(_DebugSymbolsIntermediatePath-&gt;'$(OutDir)%(Filename)%(Extension)')' @ C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets:375
  OutDir: 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\' @ C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\Wa531.SAR_Log.Android.csproj:0
[15:23:53.188 Verbose] 
- BuildManager - Item _ApplicationManifestFinal 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\Native.Wa531.SAR_Log.Android.manifest' evaluated via:
_ApplicationManifestFinal: '$(OutDir)$(_DeploymentTargetApplicationManifestFileName)' @ C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets:413
  OutDir: 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\' @ C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\Wa531.SAR_Log.Android.csproj:0
  _DeploymentTargetApplicationManifestFileName: 'Native.$(AssemblyName).manifest' @ C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets:229
    AssemblyName: 'Wa531.SAR_Log.Android' @ C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\Wa531.SAR_Log.Android.csproj:14
</code></pre>
VS Info
<pre><code>Microsoft Visual Studio Enterprise 2019
Version 16.8.3
VisualStudio.16.Release/16.8.3+30804.86
Microsoft .NET Framework
Version 4.8.03752

Installed Version: Enterprise

Visual C++ 2019   00435-60000-00000-AA025
Microsoft Visual C++ 2019

ADL Tools Service Provider   1.0
ASA Service Provider   1.0
ASP.NET and Web Tools 2019   16.8.554.20160
ASP.NET Core Razor Language Services   16.1.0.2052803+84e121f1403378489b842e1797df2f3f5a49ac3c
ASP.NET Web Frameworks and Tools 2019   16.8.554.20160
Azure App Service Tools v3.0.0   16.8.554.20160
Azure Data Lake Node   1.0
Azure Data Lake Tools for Visual Studio   2.6.3000.0
Azure Functions and Web Jobs Tools   16.8.554.20160
Azure Stream Analytics Tools for Visual Studio   2.6.3000.0
C# Tools   3.8.0-5.20604.10+9ed4b774d20940880de8df1ca8b07508aa01c8cd
Common Azure Tools   1.10
Extensibility Message Bus   1.2.6 (master@34d6af2)
Fabric.DiagnosticEvents   1.0
GitHub.VisualStudio   2.11.106.19330
IntelliCode Extension   1.0
Microsoft Azure HDInsight Azure Node   2.6.3000.0
Microsoft Azure Hive Query Language Service   2.6.3000.0
Microsoft Azure Service Fabric Tools for Visual Studio   16.0
Microsoft Azure Stream Analytics Language Service   2.6.3000.0
Microsoft Azure Stream Analytics Node   1.0
Microsoft Azure Tools   2.9
Microsoft Continuous Delivery Tools for Visual Studio   0.4
Microsoft JVM Debugger   1.0
Microsoft Library Manager   2.1.113+g422d40002e.RR
Microsoft MI-Based Debugger   1.0
Microsoft Visual C++ Wizards   1.0
Microsoft Visual Studio Tools for Containers   1.1
Microsoft Visual Studio VC Package   1.0
Mono Debugging for Visual Studio   16.8.43 (00471f8)
Node.js Tools   1.5.20902.1 Commit Hash:b474efcb6f92db52a8f8e2e6a8cb9648476885cc
NuGet Package Manager   5.8.0
ProjectServicesPackage Extension   1.0
Snapshot Debugging Extension   1.0
SQL Server Data Tools   16.0.62010.06180
ToolWindowHostedEditor   1.0
TypeScript Tools   16.0.21016.2001
Visual Basic Tools   3.8.0-5.20604.10+9ed4b774d20940880de8df1ca8b07508aa01c8cd
Visual F# Tools   16.8.0-beta.20507.4+da6be68280c89131cdba2045525b80890401defd
Visual Studio Code Debug Adapter Host Package   1.0
Visual Studio Container Tools Extensions   1.0
Visual Studio Tools for Containers   1.0
Visual Studio Tools for Kubernetes   1.0
Visual Studio Tools for Unity   4.8.2.0
VisualStudio.DeviceLog   1.0
VisualStudio.Foo   1.0
VisualStudio.Mac   1.0
Xamarin   16.8.000.260 (d16-8@fd405a2)
Xamarin Designer   16.8.0.507 (remotes/origin/d16-8@e87b24884)
Xamarin Templates   16.8.112 (86385a3)
Xamarin.Android SDK   11.1.0.17 (d16-8/c0e2b8e)
Xamarin.Android Reference Assemblies and MSBuild support.
    Mono: be2226b
    Java.Interop: xamarin/java.interop/d16-8@79d9533
    ProGuard: Guardsquare/proguard/proguard6.2.2@ebe9000
    SQLite: xamarin/sqlite/3.32.1@1a3276b
    Xamarin.Android Tools: xamarin/xamarin-android-tools/d16-8@2fb1cbc
Xamarin.iOS and Xamarin.Mac SDK   14.6.0.15 (87a1b18d8)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.
</code></pre>
",https://stackoverflow.com/questions/65545295/visual-studio-2019-live-unit-testing-crashes,"['visual-studio', 'unit-testing', 'visual-studio-2019', 'live-unit-tests']",980,True,0,1
Why cannot read instance when unit testing?,"<p>*This app is for practice only.</p>
<p>I am trying to create multiple classes here that make up a chat room.</p>
<p>I create app instance as singleton instance.</p>
<p>App instance basically work as single module where it stores all users and rooms of the chat app.</p>
<p>This is what app instance looks like.</p>
<pre class=""lang-js prettyprint-override""><code>class App {
    constructor() {
        this.users = [];
        this.rooms = [];
    }

    addUser(user) {
        const duplicateUser = this.users.find(
            (appUser) =&gt; appUser.userName === user.userName
        );

        if (duplicateUser) {
            throw new Error(&quot;User already exists.&quot;);
        }

        this.users.push(user);
    }

    createUser(userName) {
        const newUser = new User(userName);
        this.addUser(newUser);
        return newUser;
    }

    getUser(userName) {
        return this.users.find((user) =&gt; user === userName);
    }

     ....
}

const app = new App();
// Object.freeze(app); Commented out for testing purpose. 


</code></pre>
<pre class=""lang-js prettyprint-override""><code>class User {
    constructor(userName) {
        this.userName = userName;
        this.joinedRoomName = null;
    }

    createRoom(roomName) {
        const duplicateRoom = app.getRoom(roomName);
        const duplicateUser = app.getUser(this.userName);

        if (duplicateRoom) {
            throw new Error(&quot;The room already exists.&quot;);
        }

        if (duplicateUser) {
            throw new Error(&quot;The user is already in another room&quot;);
        }

        const host = new Host(this.userName);
        const room = new Room(roomName, host);
        app.addRoom(room);
        return room;
    }

    ...other methods
</code></pre>
<p>I added a new user instance by using createUser above in the App.</p>
<p>When user creates an instance called room, as defined in user method,</p>
<p>it uses app's method(not static, but imported the instance) &quot;getRoom and getUser&quot;.</p>
<p>However I get reference error like so:</p>
<pre><code>TypeError: Cannot read property 'getRoom' of undefinedJest
</code></pre>
<p>Below is my jest code.</p>
<p>What is the issue here?</p>
<pre><code>beforeEach(() =&gt; app.reset());

describe(&quot;클래스 인스턴스 생성 테스트&quot;, () =&gt; {
    it(&quot;app 은 App 의 인스턴스여야 합니다.&quot;, () =&gt; {
        expect(app).toBeInstanceOf(App);
    });

    it(&quot;App 에서 새로운 유저를 만들었을 때 앱에 해당 유저가 등록되어야 합니다.&quot;, () =&gt; {
        const testUser = app.createUser(&quot;test&quot;);
        expect(testUser.userName).toEqual(app.users[0].userName);
    });
});

describe(&quot;방 개설과 방 참여 테스트&quot;, () =&gt; {
    it(&quot;방을 개설했을 때 방은 App 에 추가되어야 합니다.&quot;, () =&gt; {
        app.createUser(&quot;test&quot;);
        const testUser = app.users[0];
        const testRoom = testUser.createRoom(&quot;testRoom&quot;);

        expect(testRoom.roomName).toEqual(app.rooms[0].roomName);
    });
    it(&quot;방 개설을 했을 때 그 방의 호스트는 개설한 유저 자신이어야 합니다.&quot;, () =&gt; {});
    it(&quot;방 참여를 한다면 앱의 방에 해당 유저가 추가되어 있어야 합니다.&quot;, () =&gt; {});
    it(&quot;다른 방에 속해있는 유저는 새로운 방을 개설할 수 없습니다.&quot;, () =&gt; {});
    it(&quot;다른 방에 속해있는 유저는 새로운 방에 참여할 수 없습니다.&quot;, () =&gt; {});
    it(&quot;사용자는 대화방을 나갈 수 있어야 합니다.&quot;, () =&gt; {});
});
</code></pre>
",https://stackoverflow.com/questions/65894490/why-cannot-read-instance-when-unit-testing,"['javascript', 'unit-testing', 'class', 'oop', 'jestjs']",33,False,0,0
Flutter unit testing streams that do map,"<p>I did stuck with testing streams that do some transformations before returning the value. I am using Firestore as my data storage and have a separated data layer that performs some mapping from <code>DocumentSnapshot&lt;T&gt;</code> to my model. Here is an example of the repo:</p>
<pre class=""lang-dart prettyprint-override""><code>class RequestsRepository {
  final CollectionReference&lt;Request&gt; _requestsCollection =
      getIt&lt;FirebaseFirestore&gt;().collection('requests').withConverter&lt;Request&gt;(
          fromFirestore: (snapshot, _) =&gt; Request.fromJson(snapshot.data()!),
          toFirestore: (request, _) =&gt; request.toJson());

  Stream&lt;Request?&gt; observe(String id) {
    return _requestsCollection
        .doc(id)
        .snapshots()
        .map((snapshot) =&gt; snapshot.exists ? snapshot.data() : null);
    });
  }
}
</code></pre>
<p>And now I'd like to cover <code>observe(id)</code> function with tests. Here is the solution I came to and below I'll explain why:</p>
<pre class=""lang-dart prettyprint-override""><code>test('request exists', () async {
      // WHEN
      final stream = repository.observe(request.id);

      // expected events
      final events = [null, request, request..completed = true, null];
      var eventIndex = 0;

      // THEN
      stream.listen(expectAsync1((value) async {
        await Future.delayed(Duration(milliseconds: 100));
        expect(value, events[eventIndex]);
        eventIndex++;
      }, max: -1));

      // GIVEN
      await firestore
          .collection('requests')
          .doc(request.id)
          .set(request.toJson());

      request.completed = true;

      await firestore
          .collection('requests')
          .doc(request.id)
          .set(request.toJson());

      // reset request data
      request.completed = false;
    });
</code></pre>
<p>I tried <code>emitsInOrder</code> stream matcher however it fails, because I'm doing mapping inside the <code>observe(id)</code> function and that result in actually not <code>request</code> object but <code>_MapStream&lt;DocumentSnapshot&lt;Request?&gt;, Request?&gt;</code> instead because of the logic that stream map function follows:</p>
<pre class=""lang-dart prettyprint-override""><code>Stream&lt;S&gt; map&lt;S&gt;(S convert(T event)) {
    return new _MapStream&lt;T, S&gt;(this, convert);
  }
</code></pre>
<p>The solution I came to did work for this case but it did not for other tests and also the solution is smelly. Any suggestions how to tests these kind of streams?</p>
<p>UPDATE:</p>
<p>Per comment from @pskink here is the demo test that fails with the same reason:</p>
<pre class=""lang-dart prettyprint-override""><code>class Test {
  Stream&lt;B&gt; observe() {
    return Stream.periodic(Duration(milliseconds: 500), (i) =&gt; A(i * 10))
        .map((i) =&gt; B('s${i.a}'));
  }
}

class A {
  final int a;
  A(this.a);

  bool operator ==(o) =&gt; o is A &amp;&amp; a == o.a;
  int get hashCode =&gt; a.hashCode;
}

class B {
  final String b;
  B(this.b);

  bool operator ==(o) =&gt; o is B &amp;&amp; b == o.b;
  int get hashCode =&gt; b.hashCode;
}

void main() {
  test('mapped stream: A &gt; B', () async {
    final stream = Test().observe();
    expect(stream, emitsInOrder([B('s0'), B('s10'), B('s20'), B('s30')]));
  });
}
</code></pre>
<p>It passes with the test so far.</p>
",https://stackoverflow.com/questions/70271769/flutter-unit-testing-streams-that-do-map,"['flutter', 'testing', 'flutter-test']",417,False,0,1
Mock a database function for unit testing,"<p>I'm trying to make unit tests for a query. Inside this query I call an database function. This function is a CTE (Common-Table-Expression). For testing purposes I want to mock this CTE.</p>
<p>My question is, how am I mocking this database function in entity-framework-core?</p>
",https://stackoverflow.com/questions/66273944/mock-a-database-function-for-unit-testing,"['c#', 'unit-testing', 'entity-framework-core', 'mocking', 'xunit']",392,False,0,1
Unit Testing without a main static method?,"<p>I am starting to go through a tutorial on Unit Testing. I am using Visual Studio 2019 and I am trying to run the projects/ tests but keep getting these errors,</p>
<p>CS5001  Program does not contain a static 'Main' method suitable for an entry point</p>
<p>CS006   Metadata file 'C:(filepath)... .exe' could not be found</p>
<p>I know neither class has a main static method but the tutorial I am following along with doesn't either so I am not sure what the issue is. I have searched Stack Overflow and Google but can only find answers going over my head, any idea what how to fix this?</p>
<p>It is pretty simple code as I am just at the beginning so I think the problem is something else but am not sure (obviously)</p>
<p>UPDATE:
Here is a screen shot of the structure of my solution:
<a href=""https://i.stack.imgur.com/wRlrK.png"" rel=""nofollow noreferrer"">structure of solution</a>
The original project was a Console application, the I added a Test project to the solution.</p>
",https://stackoverflow.com/questions/66879462/unit-testing-without-a-main-static-method,"['c#', 'visual-studio', 'unit-testing']",637,True,0,2
Unit testing angular 11 service stub problem,"<p>I'm trying to run unit test of my component.</p>
<p>component.ts:</p>
<pre><code>async ngOnInit(): Promise&lt;void&gt; {
  await this.dataProviderService.getCurrencyCodesList().then(data =&gt; {
    this.currencyList = data;
  });
  this.currencyList.sort((a, b) =&gt; {
    return a.code &gt; b.code ? 1 : -1;
  });
// ...
}
</code></pre>
<p>Service method used:</p>
<pre><code>async getCurrencyCodesList(): Promise&lt;any[]&gt; {
    // ...
    const currencyCodes = currencyList.map(data =&gt; {
      return {code: data.code, currency: data.currency, table: data.table};
    });

    return currencyCodes;
  }
</code></pre>
<p>In spec.ts file I tried to create a stub</p>
<pre><code>//...
it('should have currencies in the list', () =&gt; {
    expect(component.currencyList.length).toBeGreaterThan(1);
});
});
class DataProviderServiceStub {
  async getCurrencyCodesList(): Promise&lt;Observable&lt;any[]&gt;&gt; {
    return of ([{code: 'PLN', table: 'A'},
                {code: 'EUR', table: 'A'}]);
  }
}

// then this:
class DataProviderServiceStub {
  async getCurrencyCodesList(): Promise&lt;any[]&gt; {
    return ([{code: 'PLN', table: 'none'},
             {code: 'EUR', table: 'A'}]);
  }
} 
//also tried return (of)([]), ([{}]) etc.
</code></pre>
<p>The problem is I'm getting such Karma error for using .sort on array I'm getting from stub:</p>
<pre><code>Error: Uncaught (in promise): TypeError: this.currencyList.sort is not a function
TypeError: this.currencyList.sort is not a function
</code></pre>
<p>It sometimes comes out as error, other time as AfterAll error and sometimes it says everything is fine. What am I doing wrong?</p>
<p>Test result failed: &quot;TypeError: Cannot read property 'length' of undefined&quot;</p>
",https://stackoverflow.com/questions/65531676/unit-testing-angular-11-service-stub-problem,"['angular', 'unit-testing', 'karma-jasmine', 'angular-test']",957,True,0,2
Unit testing xUnit with JSON files data,"<p>I want to unit test my technical analysis indicators. I have historical candle data downloaded in JSON format.</p>
<ol>
<li>What is the correct way to load the JSON data into xUnit and re-use it on multiple methods? All I want is to be able to use the historical data (<code>List&lt;OHLCV&gt;</code>) from all these methods in <code>IndicatorTests.cs</code>.</li>
<li>Is it important to move <code>Data()</code> into a fixture? Since my indicators will be tested in a same file <code>IndicatorTests.cs</code>?</li>
<li>How do I find the JSON files because they are inside the project and not in <code>/bin/Debug</code>. <code>AppDomain.CurrentDomain.BaseDirectory</code> is kinda looking for them in <code>/bin/Debug</code>, which is wrong.</li>
</ol>
<p><a href=""https://i.stack.imgur.com/w1CFH.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/w1CFH.png"" alt=""enter image description here"" /></a></p>
<pre class=""lang-cs prettyprint-override""><code>public class IndicatorTests
{
    public static IEnumerable&lt;object[]&gt; Data()
    {
        var filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @&quot;Data\TRX_USDT-5m.json&quot;);

        if (!File.Exists(filePath))
            throw new FileNotFoundException($&quot;The historical data file '{filePath}' was not found.&quot;);

        var data = File.ReadAllText(filePath);
        var deserializedData = JsonConvert.DeserializeObject&lt;List&lt;List&lt;decimal&gt;&gt;&gt;(data);

        var candles = deserializedData.Select(e =&gt; new OHLCV()
        {
            Timestamp = DateTimeOffset.FromUnixTimeMilliseconds((long)e[0]).DateTime,
            Open = e[1],
            High = e[2],
            Low = e[3],
            Close = e[4],
            Volume = e[5]
        });

        foreach (var candle in candles ?? Enumerable.Empty&lt;OHLCV&gt;())
        {
            yield return new[] { candle };
        }
    }

    [Theory]
    [MemberData(nameof(Data))]
    public void Test1(List&lt;OHLCV&gt; candle)
    {
        Console.WriteLine(candle);
    }

    [Theory]
    [MemberData(nameof(Data))]
    public void Test2(List&lt;OHLCV&gt; candle)
    {
        Console.WriteLine(candle);
    }

    [Theory]
    [MemberData(nameof(Data))]
    public void Test3(List&lt;OHLCV&gt; candle)
    {
        Console.WriteLine(candle);
    }
}
</code></pre>
",https://stackoverflow.com/questions/65846068/unit-testing-xunit-with-json-files-data,"['c#', 'xunit', '.net-5']",1401,False,0,0
Method unit testing: &quot;AttributeError for a module,"<p>I'm doing a unit test for each method of the program I am writing, starting off with creating the class then the constructor and I receive the error:</p>
<blockquote>
<p>AttributeError: module 'pandas' has no attribute 'dataframe'.</p>
</blockquote>
<p>Here is the code I have for this unit test:</p>
<pre class=""lang-py prettyprint-override""><code>import matplotlib.pyplot as plt
import pandas as pd
import csv

class CompanySales:
    def __init__(self, CompanyName, CompanyAddress, CSV):
        with open(CSV):
            df = pd.dataframe(CSV)
        self._dataframe = df
    

if __name__==&quot;__main__&quot;:
    Sales = CompanySales(&quot;ABC&quot;,&quot;3 River St. N.Y.,N.Y.&quot;, &quot;CompanySalesData.csv&quot;)
    print(Sales)
    Sales.setName(&quot;Dallas Store&quot;)
    Sales.setAddr(&quot;2929 First St., Dallas,Tx.&quot;)
    print (&quot;Company Name was changed to&quot;)
    print (Sales.getName())
    print (&quot;Company Address was changed to&quot;)
    print (Sales.getAddr())
</code></pre>
",https://stackoverflow.com/questions/70059518/method-unit-testing-attributeerror-for-a-module,"['python', 'pandas', 'dataframe']",38,False,0,0
Why cannot read instance when unit testing?,"<p>*This app is for practice only.</p>
<p>I am trying to create multiple classes here that make up a chat room.</p>
<p>I create app instance as singleton instance.</p>
<p>App instance basically work as single module where it stores all users and rooms of the chat app.</p>
<p>This is what app instance looks like.</p>
<pre class=""lang-js prettyprint-override""><code>class App {
    constructor() {
        this.users = [];
        this.rooms = [];
    }

    addUser(user) {
        const duplicateUser = this.users.find(
            (appUser) =&gt; appUser.userName === user.userName
        );

        if (duplicateUser) {
            throw new Error(&quot;User already exists.&quot;);
        }

        this.users.push(user);
    }

    createUser(userName) {
        const newUser = new User(userName);
        this.addUser(newUser);
        return newUser;
    }

    getUser(userName) {
        return this.users.find((user) =&gt; user === userName);
    }

     ....
}

const app = new App();
// Object.freeze(app); Commented out for testing purpose. 


</code></pre>
<pre class=""lang-js prettyprint-override""><code>class User {
    constructor(userName) {
        this.userName = userName;
        this.joinedRoomName = null;
    }

    createRoom(roomName) {
        const duplicateRoom = app.getRoom(roomName);
        const duplicateUser = app.getUser(this.userName);

        if (duplicateRoom) {
            throw new Error(&quot;The room already exists.&quot;);
        }

        if (duplicateUser) {
            throw new Error(&quot;The user is already in another room&quot;);
        }

        const host = new Host(this.userName);
        const room = new Room(roomName, host);
        app.addRoom(room);
        return room;
    }

    ...other methods
</code></pre>
<p>I added a new user instance by using createUser above in the App.</p>
<p>When user creates an instance called room, as defined in user method,</p>
<p>it uses app's method(not static, but imported the instance) &quot;getRoom and getUser&quot;.</p>
<p>However I get reference error like so:</p>
<pre><code>TypeError: Cannot read property 'getRoom' of undefinedJest
</code></pre>
<p>Below is my jest code.</p>
<p>What is the issue here?</p>
<pre><code>beforeEach(() =&gt; app.reset());

describe(&quot;클래스 인스턴스 생성 테스트&quot;, () =&gt; {
    it(&quot;app 은 App 의 인스턴스여야 합니다.&quot;, () =&gt; {
        expect(app).toBeInstanceOf(App);
    });

    it(&quot;App 에서 새로운 유저를 만들었을 때 앱에 해당 유저가 등록되어야 합니다.&quot;, () =&gt; {
        const testUser = app.createUser(&quot;test&quot;);
        expect(testUser.userName).toEqual(app.users[0].userName);
    });
});

describe(&quot;방 개설과 방 참여 테스트&quot;, () =&gt; {
    it(&quot;방을 개설했을 때 방은 App 에 추가되어야 합니다.&quot;, () =&gt; {
        app.createUser(&quot;test&quot;);
        const testUser = app.users[0];
        const testRoom = testUser.createRoom(&quot;testRoom&quot;);

        expect(testRoom.roomName).toEqual(app.rooms[0].roomName);
    });
    it(&quot;방 개설을 했을 때 그 방의 호스트는 개설한 유저 자신이어야 합니다.&quot;, () =&gt; {});
    it(&quot;방 참여를 한다면 앱의 방에 해당 유저가 추가되어 있어야 합니다.&quot;, () =&gt; {});
    it(&quot;다른 방에 속해있는 유저는 새로운 방을 개설할 수 없습니다.&quot;, () =&gt; {});
    it(&quot;다른 방에 속해있는 유저는 새로운 방에 참여할 수 없습니다.&quot;, () =&gt; {});
    it(&quot;사용자는 대화방을 나갈 수 있어야 합니다.&quot;, () =&gt; {});
});
</code></pre>
",https://stackoverflow.com/questions/65894490/why-cannot-read-instance-when-unit-testing,"['javascript', 'unit-testing', 'class', 'oop', 'jestjs']",33,False,0,0
Mock a database function for unit testing,"<p>I'm trying to make unit tests for a query. Inside this query I call an database function. This function is a CTE (Common-Table-Expression). For testing purposes I want to mock this CTE.</p>
<p>My question is, how am I mocking this database function in entity-framework-core?</p>
",https://stackoverflow.com/questions/66273944/mock-a-database-function-for-unit-testing,"['c#', 'unit-testing', 'entity-framework-core', 'mocking', 'xunit']",392,False,0,1
Flutter unit testing streams that do map,"<p>I did stuck with testing streams that do some transformations before returning the value. I am using Firestore as my data storage and have a separated data layer that performs some mapping from <code>DocumentSnapshot&lt;T&gt;</code> to my model. Here is an example of the repo:</p>
<pre class=""lang-dart prettyprint-override""><code>class RequestsRepository {
  final CollectionReference&lt;Request&gt; _requestsCollection =
      getIt&lt;FirebaseFirestore&gt;().collection('requests').withConverter&lt;Request&gt;(
          fromFirestore: (snapshot, _) =&gt; Request.fromJson(snapshot.data()!),
          toFirestore: (request, _) =&gt; request.toJson());

  Stream&lt;Request?&gt; observe(String id) {
    return _requestsCollection
        .doc(id)
        .snapshots()
        .map((snapshot) =&gt; snapshot.exists ? snapshot.data() : null);
    });
  }
}
</code></pre>
<p>And now I'd like to cover <code>observe(id)</code> function with tests. Here is the solution I came to and below I'll explain why:</p>
<pre class=""lang-dart prettyprint-override""><code>test('request exists', () async {
      // WHEN
      final stream = repository.observe(request.id);

      // expected events
      final events = [null, request, request..completed = true, null];
      var eventIndex = 0;

      // THEN
      stream.listen(expectAsync1((value) async {
        await Future.delayed(Duration(milliseconds: 100));
        expect(value, events[eventIndex]);
        eventIndex++;
      }, max: -1));

      // GIVEN
      await firestore
          .collection('requests')
          .doc(request.id)
          .set(request.toJson());

      request.completed = true;

      await firestore
          .collection('requests')
          .doc(request.id)
          .set(request.toJson());

      // reset request data
      request.completed = false;
    });
</code></pre>
<p>I tried <code>emitsInOrder</code> stream matcher however it fails, because I'm doing mapping inside the <code>observe(id)</code> function and that result in actually not <code>request</code> object but <code>_MapStream&lt;DocumentSnapshot&lt;Request?&gt;, Request?&gt;</code> instead because of the logic that stream map function follows:</p>
<pre class=""lang-dart prettyprint-override""><code>Stream&lt;S&gt; map&lt;S&gt;(S convert(T event)) {
    return new _MapStream&lt;T, S&gt;(this, convert);
  }
</code></pre>
<p>The solution I came to did work for this case but it did not for other tests and also the solution is smelly. Any suggestions how to tests these kind of streams?</p>
<p>UPDATE:</p>
<p>Per comment from @pskink here is the demo test that fails with the same reason:</p>
<pre class=""lang-dart prettyprint-override""><code>class Test {
  Stream&lt;B&gt; observe() {
    return Stream.periodic(Duration(milliseconds: 500), (i) =&gt; A(i * 10))
        .map((i) =&gt; B('s${i.a}'));
  }
}

class A {
  final int a;
  A(this.a);

  bool operator ==(o) =&gt; o is A &amp;&amp; a == o.a;
  int get hashCode =&gt; a.hashCode;
}

class B {
  final String b;
  B(this.b);

  bool operator ==(o) =&gt; o is B &amp;&amp; b == o.b;
  int get hashCode =&gt; b.hashCode;
}

void main() {
  test('mapped stream: A &gt; B', () async {
    final stream = Test().observe();
    expect(stream, emitsInOrder([B('s0'), B('s10'), B('s20'), B('s30')]));
  });
}
</code></pre>
<p>It passes with the test so far.</p>
",https://stackoverflow.com/questions/70271769/flutter-unit-testing-streams-that-do-map,"['flutter', 'testing', 'flutter-test']",417,False,0,1
odoo unit testing for customized project module,"<p>I am writing unit tests for custom addon developed on top of project (project.task) module which is also heavily customized. While writing unit test cases, its painful to create project.task model objects which involves creating multiple sub class objects before creating the actual task model object. This process is painful as each sub class object in turn has many fields. While creating a task from the user interface is lot easier as system creates all the sub class objects with necessary fields. Is there a better way of creating the necessary dummy objects for the sake of unit testing?</p>
",https://stackoverflow.com/questions/65567539/odoo-unit-testing-for-customized-project-module,"['unit-testing', 'odoo']",73,False,0,1
Unit Testing array structure with correct type,"<p>Suppose i have an array base structure</p>
<pre><code>$testData = [
    'key' =&gt; [
        'key2' =&gt; [
            'key3' =&gt; 'string',
            'key4' =&gt; 'int',
            'key5' =&gt; 'string',
            'key6' =&gt; 'float',
            'key7' =&gt; 'string',
            'key8' =&gt; 'int',
            'key9' =&gt; [
                'key10' =&gt; 'string',
                'key11' =&gt; 'string',
            ],
            'key12' =&gt; [
                'key13' =&gt; 'string',
            ],
        ]]];
</code></pre>
<p>I want to create a Unit Test to check if another array follows this structure with the respective types.</p>
<p>Is that doable?</p>
",https://stackoverflow.com/questions/68955722/unit-testing-array-structure-with-correct-type,"['php', 'unit-testing']",52,False,0,0
Unit testing concrete services extending generic service,"<p>Infrastructure I set up is based on generic service and generic repository. Right now I am trying to write unit tests and I am having some challenges. Here is the code:</p>
<p>IBaseRepository:</p>
<pre><code>public interface IBaseRepository&lt;T&gt; where T : class
{
    IEnumerable&lt;T&gt; GetAll();
    T Add(T entity, bool saveChanges = true);
    //more generic code
}
</code></pre>
<p>IServiceBase:</p>
<pre><code>public interface IServiceBase&lt;TEntity&gt;
{
    IEnumerable&lt;TEntity&gt; GetAll();
    TEntity Create(TEntity entity);
    //more generic code
}
</code></pre>
<p>BaseRepository:</p>
<pre><code>public class BaseRepository&lt;T&gt; : IBaseRepository&lt;T&gt; where T : class
{
    private readonly DatabaseContext _dbContext;

    public BaseRepository(DatabaseContext dbContext)
    {
        _dbContext = dbContext;
    }

    public IEnumerable&lt;T&gt; GetAll()
    {
        return _dbContext.Set&lt;T&gt;();
    }

    public T Add(T entity, bool saveChanges = true)
    {
        _dbContext.Set&lt;T&gt;().Add(entity);
        if (saveChanges) _dbContext.SaveChanges();
        return entity;
    }
}
</code></pre>
<p>ServiceBase:</p>
<pre><code>public abstract class ServiceBase&lt;TEntity, TRepository&gt; : IServiceBase&lt;TEntity&gt;
        where TEntity : class
        where TRepository : BaseRepository&lt;TEntity&gt;
{
    public TRepository Repository;

    public ServiceBase(BaseRepository&lt;TEntity&gt; rep)
    {
        Repository = (TRepository)rep;
    }

    public long Count(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition)
    {
        return Repository.GetAll().AsQueryable().Where(whereCondition).Count();
    }
}
</code></pre>
<p>AddressService (Concrete domain service):</p>
<pre><code> public class AddressService : ServiceBase&lt;Address, BaseRepository&lt;Address&gt;&gt;, IAddressService
 {
    public AddressService(BaseRepository&lt;Address&gt; rep) : base(rep)
    {
    }

    public VerifyAddress()
    {
        //custom logic...
    }
 }
</code></pre>
<p>Test:</p>
<pre><code>public class AddressTests
{
    [Fact]
    public void VerifyAddress()
    {
        var baseRepository = new Mock&lt;BaseRepository&lt;Address&gt;&gt;();
        var addressService = new AddressService(baseRepository.Object);            

        var test = addressService.Verify();
        Assert.NotNull(test);
    }
}
</code></pre>
<p>The error I get is <code>Message: Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: Repositories.Repositories.BaseRepository. Could not find a parameterless constructor.</code></p>
<p>I am aware why I am getting this error. The reason is because BaseRepository has constructor which expects <code>DatabaseContext</code> as a parameter.</p>
<p>My question would be is it possible to unit test <code>AddressService</code> with setup like this?</p>
",https://stackoverflow.com/questions/66122421/unit-testing-concrete-services-extending-generic-service,"['c#', '.net', 'unit-testing', 'asp.net-core', 'xunit']",45,True,0,1
C# unit testing using mocks without interfaces,"<p>In order to properly unit test some of my classes I need to mock the class objects being used by the main class being tested. This is a simple process if all the objects being used implements the interface <strong>and</strong> I only need to use the methods form that interface. However, and here is the problem:</p>
<p>Interfaces are a contract on what other developers should expect in that class. Therefore all interface methods, properties etc. are public. Any good code should also have good encapsulation. Therefore I don't want to make all methods in my class public and hence don't declare it in the interface. And as a result I can not mock and setup these internal method that is used in my main class.</p>
<p>Other options I looked into was using an abstract class that can have different access modifiers and I can have the correct methods in it be internal or private etc. But since I want the class being mocked to be available is a public property of interface type for other developers to use, I need it be an interface, but now its not compatible anymore since my main class cant call the internal method anymore as its defined as an interface. Catch 22. (In case you were wondering, using virtual for methods will have the same problem as using an abstract class).</p>
<p>I have searched for similar questions regarding C# mocking and did not find the same problem I have. And please don't be philosophical on &quot;C# isn't good language for testing&quot; or such stuff. That's not an answer.</p>
<p>Any ideas?</p>
<p>I added this code example to make it easier to see the problem described above.</p>
<pre><code>[assembly: InternalsVisibleTo(&quot;MyService.Tests&quot;)]

public interface IMyService
{
    MethodABC()
    ...
}

public class MyService : IMyService 
{
    public void MethodABC()
    {
        ...
    }
    
    internal void Initialize()
    {
        ...
    }
    ...
}

public sealed partial class MyMain
{
    public IMyService Service { get; private set; }
    private MyService _service;
    
    ...
    
    private void SomeMethod()
    {
        // This method is in interface and can be used outside the project when this assembly is referenced
        _service.MethodABC() 
        ...
        
        // This method is and internal method inside the class not to be seen or used outside the project. 
        // 1) When running this method through unit test that mocked the IMyService will fail here since initialize don't exist which is correct.
        // 2) Mocking the MyService will require &quot;virtual&quot; to be added to all methods used and don't provide a interface/template for a developers if 
        //    they want to swap the service out.
        // 3) Changing the interface to abstract class and mocking that allows for making this an internal method and also set it up in mock to do 
        //    something for unit test and provides contract other developers can implement and pass in to use a different service, but requires 
        //    &quot;override&quot; for all methods to be used from &quot;outside&quot; this assembly. This is best solution but require changes to code for sole purpose
        //    of testing which is an anti-pattern.
        _service.Initialize() 
        ...
    }
}

// Unit test method in test project

[TestClass]
public class MyMainTests
{

    private Mock&lt;IMyService&gt; _myServiceMock = new Mock&lt;IMyService&gt;();

    [TestMethod]
    public void MyMain_Test_SomeMethod()
    {
        ...
        SomeMethod()
        ...
    }
}
</code></pre>
",https://stackoverflow.com/questions/66609131/c-unit-testing-using-mocks-without-interfaces,"['c#', '.net', 'unit-testing', 'interface', 'moq']",1829,True,-1,4
Jasmine unit testing - mat-Autocomplete filter class,"<p>I'm writing jasmine unit tests for an angular app, coverage is pretty good, but struggling to find a good way to test observable filter classes for mat-autocomplete data population.</p>
<p>The ts class:</p>
<pre><code>  dataFilter(val: string): Observable&lt;any[]&gt; {
    return this.getAPI.get()
      .pipe(
        map(response =&gt; response.filter(option =&gt; {
          return option.foo.toLowerCase().includes(val.toLowerCase());
        }))
      );
   }
</code></pre>
<p>unit test for this class so far:</p>
<pre><code>  it('should test filtered data for autocomplete', () =&gt; {
    getApiSpy.get.and.returnValue(of(DATA));
    component.dataFilter(&quot;&quot;);
    expect(getApiSpy.get).toHaveBeenCalled();
  });
</code></pre>
<p>This covers the first return (return this.getAPI.get()) but everything from the .pipe down is not covered. Has anyone tested these type of classes before and has any tips, what is the right approach?</p>
<p>Thanks,
Ollie</p>
",https://stackoverflow.com/questions/70097635/jasmine-unit-testing-mat-autocomplete-filter-class,"['angular', 'unit-testing', 'angular-material', 'jasmine', 'observable']",547,False,0,1
Skip expensive methods from PHP unit testing,"<p>I would like to skip expensive method in production Lavavel project. This is how I skip</p>
<pre><code>class HomePageTest extends TestCase
{
   use WithFaker, RefreshDatabase;
    /** @test */
    public function something_testing()
    {
      if (  env('APP_ENV') == 'local' ) {
        $response = $this-&gt;get('/expensive-service');
        $response-&gt;assertStatus(200);
      } else {
         $this-&gt;assertTrue(true);
      }
    }
}


</code></pre>
<p>The above codes work. But, I feel that there would be elegant way to skip testing method for some states.</p>
",https://stackoverflow.com/questions/68736192/skip-expensive-methods-from-php-unit-testing,"['laravel', 'phpunit']",255,True,0,1
How do you do unit testing with Dapr?,"<p>I've got a class that I'm trying to unit test but it uses a DaprClient object (from the SDK), which doesn't work in my unit test envioronment.
I would like to create a mock and use that instead but the only interface DaprClient implements is IDisposable.</p>
<p>Is there a way to mock DaprClient for unit tests?</p>
<p>The only solution I can think of would be to wrap DaprClient in a class with an interface and use this wrapper everywhere. This just feels really messy and will need the wrapper to be updated every time I want to use a new method on the DaprClient.</p>
<p>I'm open to other solutions which might bypass the problem but I'd prefer a simple replace with mock type approach.</p>
<p>I'm using .Net 5, xUnit and Moq in Visual Studio 2019 on Windows (although some team members use Macs so it needs to work on both platforms).</p>
<p>In this particular instance, I'm using the <a href=""https://github.com/dapr/dotnet-sdk/blob/01cdc89710c16712442474afea97693f22c5852b/src/Dapr.Client/DaprClient.cs#L851"" rel=""nofollow noreferrer"">DaprClient.GetBulkSecretAsync</a> method but I'd like a solution that I can use elsewhere, if possible.</p>
",https://stackoverflow.com/questions/68362431/how-do-you-do-unit-testing-with-dapr,"['unit-testing', 'moq', 'xunit', '.net-5', 'dapr']",1658,True,5,2
Angular Unit-testing NullInjectorError: R3InjectorError(DynamicTestModule)[MatSnackBarComponent -&gt; MatSnackBarComponent]:,"<p>In my MainComponent I have entryComponent MatSnackBarComponent(custom component).
When I'm writing tests i get this Error:</p>
<p>NullInjectorError: R3InjectorError(DynamicTestModule)[MatSnackBarComponent -&gt; MatSnackBarComponent]:
NullInjectorError: No provider for MatSnackBarComponent!</p>
<pre><code>describe('MainComponent', () =&gt; {
  let component: MainComponent;
  let fixture: ComponentFixture&lt;MainComponent&gt;;
  let orderService: OrderService;

  const fakeMatDialogRef = jasmine.createSpyObj(['close']);

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        FormsModule,
        ReactiveFormsModule,
        HttpClientTestingModule,
        TranslateModule.forRoot()
      ],
      declarations: [MainComponent],
      providers: [
        OrderService,
        { provide: MatDialogRef, useValue: fakeMatDialogRef }, 
        { provide: MAT_DIALOG_DATA, useValue: {} }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(MainComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
</code></pre>
<p>What should I do to fix this problem?</p>
",https://stackoverflow.com/questions/69111109/angular-unit-testing-nullinjectorerror-r3injectorerrordynamictestmodulematsn,"['angular', 'unit-testing', 'jasmine']",18045,True,4,2
Unit testing the viewModel and livedata Mockito android,"<p>I am trying to implement unit test with Mockito for my View-Model,
When my debugger is going to assign the value to live data it is crashing with error NullPointerException i.e. We are not bale to assign value to live data</p>
<p>My View-Model-Test Class</p>
<pre><code>@Test
fun getNews() {

    Mockito.`when`(mainRepository.getNews()).thenReturn(Observable.just(getMockResponse()))
    //It is working good

    Mockito.`when`(networkHelper.isNetworkConnected()).thenReturn(true)
    //It is working good

    viewModel.getNews()

    assertEquals(Resource.success(getList()), viewModel.newsResponse.value)
}
</code></pre>
<p>My ViewModel</p>
<pre><code> val newsResponse by lazy { SingleLiveEvent&lt;Resource&lt;List&lt;RowsItem&gt;&gt;&gt;() }

        fun getNews() {
        if (!networkHelper.isNetworkConnected()) { //It is true as we macked in Test Clas
            newsResponse.value = Resource.error(AppError.NetworkError)
            return
        }
        newsResponse.value = Resource.loading() // Crashing here when we are assigning value to live data: newsResponse
        val api = mainRepository.getNews().map {
            it.rows
        }

        val disposable = api.subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                { result -&gt; handleResults(result) },
                { error -&gt; handleError(error) },
            )

        compositeDisposable.add(disposable)
    }


     private fun handleResults(list: ArrayList&lt;RowsItem&gt;?) {
         if (list != null) {
             newsResponse.value = Resource.success(list)
 
         } else {
             newsResponse.value = Resource.error(AppError.CommonError)
         }
     }

      private fun handleError(t: Throwable?) {
          newsResponse.value = Resource.error(t?.failureAppError() ?: AppError.CommonError)
      }
</code></pre>
<p>Error</p>
<p>java.lang.NullPointerException
at androidx.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:77)
at androidx.arch.core.executor.ArchTaskExecutor.isMainThread(ArchTaskExecutor.java:116)
at androidx.lifecycle.LiveData.assertMainThread(LiveData.java:486)
at androidx.lifecycle.LiveData.setValue(LiveData.java:306)
at androidx.lifecycle.MutableLiveData.setValue(MutableLiveData.java:50)
at com.lifex.proficiencyexercise.repo.utils.SingleLiveEvent.setValue(SingleLiveEvent.java:28)
at com.lifex.proficiencyexercise.ui.MainActivityViewModel.getNews(MainActivityViewModel.kt:37)
at com.lifex.proficiencyexercise.ui.MainActivityViewModelTest.getNews(MainActivityViewModelTest.kt:45)
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.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:54)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:99)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:105)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:40)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)</p>
<p>Process finished with exit code -1</p>
",https://stackoverflow.com/questions/67915945/unit-testing-the-viewmodel-and-livedata-mockito-android,"['android', 'unit-testing', 'mockito', 'android-livedata', 'android-viewmodel']",5249,True,3,2
Roslyn CodeFix - MSBuild Properties/metadata and Unit testing,"<p>I'm building a roslyn analyzer/code fix but I wan't to access the MSBuild Properties and metadata (both from Directory.build.props and the .csproj) in order to know how to apply the code fix. I only found documentation to do it in source generators but not for analyzers.</p>
<p>To be more specific I want to know if the project is configured to use the new ImplicitUsings, but it would be usefull to also have access to everything.</p>
<p>Also do we have any way to get all the project global usings?</p>
<p>And using the new Microsoft.CodeAnalysis.Testing how can I add the MSBuild property so I can actually test it?</p>
<p>Regards.</p>
",https://stackoverflow.com/questions/69215975/roslyn-codefix-msbuild-properties-metadata-and-unit-testing,"['roslyn', 'roslyn-code-analysis', 'microsoft.codeanalysis']",348,True,3,1
Angular/Jest Unit Testing with NGXS State/Router,"<p>I'm unit testing a handful of Angular components that can be navigated between using NGXS Store/Routing with Jest as my test framework.</p>
<ul>
<li>Angular v9.1.1</li>
<li>Jest v9.2.2</li>
<li>NGXS Router v3.7.1</li>
<li>NGXS Store v3.6.2</li>
</ul>
<p>Here's one of the tests in question:</p>
<pre><code>it('should move to page 2 by clicking the next button then go back to page 1 by clicking the back icon', async () =&gt; {
    let url = store.selectSnapshot(RouterState.url);
    expect(url).toEqual(page1Url);

    const nextButton = fixture.nativeElement.querySelector('.right-action-button');
    nextButton.click();
    fixture.detectChanges();
    await fixture.whenStable();
    url = store.selectSnapshot(RouterState.url);
    expect(url).toEqual(page2Url);

    const backButton = fixture.nativeElement.querySelector('.mat-icon-back');
    backButton.click();
    fixture.detectChanges();
    await fixture.whenStable();
    url = store.selectSnapshot(RouterState.url);
    expect(url).toEqual(page1Url);
  });
</code></pre>
<p>This fails at <code>expect(url).toEqual(page2Url);</code> so I know that <code>nextButton</code> is defined, however, clicking on it clearly isn't dispatching the new Store event which contains <code>page2Url</code>.</p>
<p><strong>[EDIT]</strong> - While the button was defined, it was also disabled so the click did nothing. I adjusted the test case to ensure the button would be enabled by the time it was clicked and the value of <code>RouterState.url</code> is now being updated, but not to the correct value. You can see from the last code snippet that the store dispatch should cause navigation to the &quot;side&quot; outlet followed by &quot;add/targets&quot;, &quot;add/details&quot;, etc. However, in reality the result is:</p>
<pre><code>Expected: &quot;/view/(list//side:add/targets)&quot;
Received: &quot;/view/list&quot;
</code></pre>
<p>Logging <code>RouterState.state</code> produces the following:</p>
<pre><code>    {
      root: {
        url: [],
        params: {},
        queryParams: {},
        fragment: undefined,
        data: {},
        outlet: 'primary',
        component: null,
        routeConfig: null,
        root: null,
        parent: null,
        firstChild: {
          url: [],
          params: {},
          queryParams: {},
          fragment: undefined,
          data: {},
          outlet: 'primary',
          component: null,
          routeConfig: null,
          root: null,
          parent: null,
          firstChild: [Object],
          children: [Array],
          pathFromRoot: null,
          paramMap: [ParamsAsMap],
          queryParamMap: [ParamsAsMap],
          toString: [Function]
        },
        children: [ [Object] ],
        pathFromRoot: null,
        paramMap: ParamsAsMap { params: {} },
        queryParamMap: ParamsAsMap { params: {} },
        toString: [Function]
      },
      url: '/view/list'
    }
</code></pre>
<p>Notice how the &quot;outlet&quot; field is &quot;primary&quot; in the &quot;firstChild&quot; object. I'd expect this to be &quot;side&quot; instead based on the code shown below.</p>
<p>[END EDIT]</p>
<p>I've got some set-up in the <code>beforeEach()</code> that resets the value of <code>RouterState.url</code> in the Store back to <code>page1Url</code> and you can see that that's working in the first expect. Here's  the set-up (imports, declarations, providers, etc. are in another <code>beforeEach()</code>):</p>
<pre><code>  beforeEach(() =&gt; {
    store = TestBed.inject(Store);
    store.reset({
      activityView: {
        creationData: {
          info: {},
          earthworks: {}
        }
      },
      router: {
        navigationId: 1,
        state: {
          root: {},
          url: page1Url
        },
        trigger: 'none'
      }
    });
    fixture = TestBed.createComponent(ActivityEditComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
</code></pre>
<p>In terms of the code being tested, it works as intended, but there seems to be some subtleties around testing a combination of NGXS Router/Store that I haven't quite got tied up. There also doesn't seem to be much about this sort of test either on the Angular/NGXS docs or anywhere else on Stack Overflow.</p>
<p>As some background on how the actual code is handling this navigation, I have a few methods in the Component that handle the various UI actions that can be taken, see below:</p>
<pre><code>  onCancel() {
    this.store.dispatch(new SetActivityCreationData(null));
    this.onClose();
  }

  onClose() {
    this.store.dispatch(new Navigate([{ outlets: { side: null } }], null, { relativeTo: this.route.parent }));
  }

  onNext() {
    this.page = 2;
    this.store.dispatch(new Navigate([{ outlets: { side: 'add/targets' } }], null, { relativeTo: this.route.parent }));
  }

  onBack() {
    this.page = 1;
    this.store.dispatch(new Navigate([{ outlets: { side: 'add/details' } }], null, { relativeTo: this.route.parent }));
  }
</code></pre>
<p>And again, this is working as intended but the test set-up seems to cause the relevant methods to not be called when one of the buttons is clicked.</p>
<p>This is getting pretty frustrating now so any guidance/suggestions would be much appreciated!</p>
",https://stackoverflow.com/questions/68744896/angular-jest-unit-testing-with-ngxs-state-router,"['angular', 'typescript', 'unit-testing', 'jestjs', 'ngxs']",458,False,2,0
System.Text.Json / NUnit - Unit testing custom Json converter / Utf8JsonReader,"<p>I have a series of test methods to verify whether my custom Json converter (System.Text.Json) throws expected exceptions. One of such method:</p>
<pre><code>[Test]
public void ReadJsonTokenNullThrows()
{
    // Arrange

    // Act &amp; Assert
    var exception = Assert.Throws&lt;JsonException&gt;(() =&gt;
    {
         var utf8JsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(&quot;null&quot;), false, new JsonReaderState(new JsonReaderOptions()));
         utf8JsonReader.Read();

         sut.Read(ref utf8JsonReader, typeof(DateTime), serializerOptions);
    });

    Assert.AreEqual(&quot;JSON value was a literal null&quot;, exception.Message);
}
</code></pre>
<p>I'd like to have only the line <code>sut.Read(...);</code> inside the <code>Assert.Throws..</code> code block, however when I move the Utf8JsonReader initialization and utf8JsonReader.Read() outside of it, I get the compiler error:</p>
<pre><code>Cannot use ref local 'utf8JsonReader' inside an anonymous method, lambda expression, or query expression.
</code></pre>
<p>Is there a way around to do this? Preferably without the try/catch</p>
",https://stackoverflow.com/questions/68342403/system-text-json-nunit-unit-testing-custom-json-converter-utf8jsonreader,"['c#', 'nunit', 'system.text.json']",1125,False,2,1
What functions should I mock during unit testing,"<p>I've been reading some articles, and posts here on Stack Overflow about when I should mock a function and when I shouldn't, but I have a case where I'm  not sure about what to do.</p>
<p>I have a UserService class which uses dependency injection concept to receive dependencies through its constructor.</p>
<pre><code>class UserService {

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

 async getUserByEmail(userEmail) {
    // would perform some validations to check if the value is an e-mail

    const user = await this.userRepository.findByEmail(email);

    return user;
 }

 async createUser(userData) {
    const isEmailInUse = await this.getUserByEmail(userData.email);

    if(isEmailInUse) {
        return &quot;error&quot;;
    } 

    const user = await this.userRepository.create(userData);

    return user;
 }

} 
</code></pre>
<p>I want to test if the createUser method works properly, and for my tests, I created a fake userRepository which is basically a object with mocked methods that I will use while instantiating UserService Class</p>
<pre><code>const UserService = require('./UserService.js');

describe(&quot;User Service tests&quot;, () =&gt; {

let userService;
let userRepository;

beforeEach(() =&gt; {
    userRepository = {
        findOne: jest.fn(),
        create: jest.fn(),
    }

    userService = new UserService(userRepository);
});

afterEach(() =&gt; {
    resetAllMocks();
});

describe(&quot;createUser&quot;, () =&gt; {

    it(&quot;should be able to create a new user&quot;, async () =&gt; {
        const newUserData = { name: 'User', email: 'user@test.com.br' }
        const user = { id: 1, name: 'User', email: 'user@test.com.br' }

        userRepository.create.mockResolvedValue(user);

        const result = await userService.createUser();

        expect(result).toStrictEqual(user);
    })
})
</code></pre>
<p>})</p>
<p>Note that in the createUser method, there is a call to the getUserByEmail method which is also a method of UserService class, and that is where I got confused.</p>
<p>Should I mock the getUserByEmail method even it is a method of the class I'm testing? If it is not the correct approach, what should I do?</p>
",https://stackoverflow.com/questions/66738500/what-functions-should-i-mock-during-unit-testing,"['javascript', 'unit-testing', 'jestjs', 'mocking']",1954,True,2,2
semantic commit message type for adding unit testing,"<p><strong>Question :</strong>
what semantic commit message type should i use for adding unit test cases? like <code>Udin.test.js</code>,
<code>feat</code> , <code>chore</code> , or <code>update</code> ?</p>
",https://stackoverflow.com/questions/67767381/semantic-commit-message-type-for-adding-unit-testing,"['git', 'conventional-commits']",3415,True,2,1
Kafka Unit Testing Transaction with MockProducer and MockConsumer,"<p>Kafka now supports atomic consume/transform/produce operation via producer transaction as you can see below. Is there a way to unit test this logic? There is a <code>MockConsumer</code> and <code>MockProducer</code> that allow testing I/O operations toward consumer and producers as a unit tests however mocked classes are completely independent of one another. The logic below requires consumer group coordinator support. Is there a way to test logic below as a unit test using mocks and <strong>not</strong> as an integration test?</p>
<pre><code> producer.beginTransaction()
 while(true){ 
   consumer.poll()
 }
 producer.sendOffsetsToTransaction(consumerOffsets, consumerGroupId)
 producer.commitTransaction()
</code></pre>
",https://stackoverflow.com/questions/69169209/kafka-unit-testing-transaction-with-mockproducer-and-mockconsumer,"['java', 'unit-testing', 'apache-kafka', 'kafka-consumer-api']",295,False,2,0
Mock Internal dependencies of unit while Unit testing?,"<p>I'm writing unit tests for a NestJs application (Node.js). Consider the classes below</p>
<pre><code>class CatService {

  constructor(private walkService:WalkService){
    //....
  }

  public function doSomething(){
    this.walkService.walk();
    this.doThis();
    this.doThat();
  }

  public function doThis(){
    //....
  }

  private function doThat(){
    //....
  }

}
</code></pre>
<p>Now the question is if I want to write test for this <code>CatService</code> Class, Which dependencies would be need to mock? Also would we be testing the <code>doThat</code> method <em>keeping in mind it is private function</em>?</p>
<p>while testing <code>doSomething</code></p>
<p><code>WalkService</code> dependency would be mocked for sure.</p>
<p>but what about <code>doThis</code> &amp; <code>doThat</code>?</p>
<p><em>Summary</em></p>
<p>Should we mock methods of the same class used by the method which is being tested?</p>
<p>If No then would it be unit testing? since a unit is a function here.</p>
",https://stackoverflow.com/questions/69017044/mock-internal-dependencies-of-unit-while-unit-testing,"['javascript', 'unit-testing', 'jestjs', 'nestjs']",146,False,1,0
Unit Testing Angular 12 HTTP Interceptor expectOne fails,"<p>I have an Angular project using Firebase for authentication. In order to authenticate to our server, we need the JWT from Firebase. The project is using Angular Fire to accomplish this.</p>
<p>We have an HTTP interceptor that intercepts any requests to the server, and adds the required Authorization header. The interceptor seems to work perfectly, but we would like to unit test it as well.</p>
<p>Our AuthService is responsible for delegating actions to Firebase. The <code>getCurrentUserToken</code> method retrieves the JWT as a promise, as Angular Fire will refresh the JWT if needed.</p>
<p>This complicates the interceptor slightly, since we need to asynchronously get the token and wrap it into the Observable from the request.</p>
<h2>token-interceptor.ts</h2>
<pre class=""lang-js prettyprint-override""><code>@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(
    req: HttpRequest&lt;unknown&gt;,
    next: HttpHandler
  ): Observable&lt;HttpEvent&lt;unknown&gt;&gt; {
    if (req.url.includes(environment.apiRoot)) {
      return defer(async () =&gt; {
        const token = await this.authService.getCurrentUserToken();
        const request = req.clone({
          headers: this.getDefaultHeaders(token),
          withCredentials: true,
        });
        return next.handle(request);
      }).pipe(mergeAll());
    } else {
      return next.handle(req);
    }
  }

  private getDefaultHeaders(accessToken: string): HttpHeaders {
    return new HttpHeaders()
      .set(
        'Access-Control-Allow-Origin',
        `${window.location.protocol}//${window.location.host}`
      )
      .set(
        'Access-Control-Allow-Headers',
        'Access-Control-Allow-Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Access-Control-Allow-Headers,Authorization,Accept,Content-Type,Origin,Host,Referer,X-Requested-With,X-CSRF-Token'
      )
      .set('Content-Type', 'application/json')
      .set('Accept', 'application/json')
      .set('Authorization', `Bearer ${accessToken}`);
  }
}
</code></pre>
<p>We provide the interceptor in our AppModule by importing <code>HttpClientModule</code> and providing the interceptor under the <code>HTTP_INTERCEPTORS</code> injection token with</p>
<pre class=""lang-js prettyprint-override""><code>  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true,
    },
</code></pre>
<p>The issue comes only in our unit test</p>
<h2>token-interceptor.spec.ts</h2>
<pre class=""lang-js prettyprint-override""><code>describe(`TokenInterceptor`, () =&gt; {
  let service: SomeService;
  let httpMock: HttpTestingController;
  let authServiceStub: AuthService;

  beforeEach(() =&gt; {
    authServiceStub = {
      getCurrentUserToken: () =&gt; Promise.resolve('some-token'),
    } as AuthService;

    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: TokenInterceptor,
          multi: true,
        },
        { provide: AuthService, useValue: authServiceStub },
      ],
    });

    service = TestBed.inject(SomeService);
    httpMock = TestBed.inject(HttpTestingController);
  });

  afterEach(() =&gt; {
    httpMock.verify();
  });

  it('should add an Authorization header', () =&gt; {
    service.sendSomeRequestToServer().subscribe((response) =&gt; {
      expect(response).toBeTruthy();
    });

    const httpRequest = httpMock.expectOne({});

    expect(httpRequest.request.headers.has('Authorization')).toEqual(true);
    expect(httpRequest.request.headers.get('Authorization')).toBe(
      'Bearer some-token'
    );

    httpRequest.flush({ message: &quot;SUCCESS&quot; });

    httpMock.verify();
  });
});
</code></pre>
<p>The test fails at the <code>httpMock.expectOne({})</code> statement with the message</p>
<pre><code>Error: Expected one matching request for criteria &quot;Match method: (any), URL: (any)&quot;, found none.
</code></pre>
<p>It seems that somehow our mock request was never sent at all.</p>
<p>However, if we remove the interceptor from the providers in the Testbed, the test instead fails at the expect statements, which shows that the mock request is being found.</p>
<pre><code>        Error: Expected false to equal true.
            at &lt;Jasmine&gt;
            at UserContext.&lt;anonymous&gt; (src/app/http-interceptors/token-interceptor.spec.ts:57:62)
            at ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:372:1)
            at ProxyZoneSpec.onInvoke (node_modules/zone.js/fesm2015/zone-testing.js:287:1)
        Error: Expected null to be 'Bearer some-token'.
            at &lt;Jasmine&gt;
            at UserContext.&lt;anonymous&gt; (src/app/http-interceptors/token-interceptor.spec.ts:58:62)
            at ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:372:1)
            at ProxyZoneSpec.onInvoke (node_modules/zone.js/fesm2015/zone-testing.js:287:1)
</code></pre>
<p>Why doesn't expectOne find the request being sent by our service? Is the issue in the interceptor itself or the way the test is constructed?</p>
",https://stackoverflow.com/questions/70382186/unit-testing-angular-12-http-interceptor-expectone-fails,"['angular', 'typescript', 'unit-testing', 'karma-jasmine', 'angular-http-interceptors']",806,True,1,1
Mock gRPC Response Stream for unit testing - C#,"<p>I have a function that calls a gRPC endpoint, converts the objects into POCO objects and returns them as a list.</p>
<pre><code>public class ActionPlanConnectionsService : IConnectionService
    {
            #region Fields
    
            /// &lt;summary&gt;
            /// Grpc client
            /// &lt;/summary&gt;
            private readonly ConnectionDb.ConnectionDbClient _client;
            #endregion
    
            public ActionPlanConnectionsService(ConnectionDb.ConnectionDbClient channel)
            {
                _client = channel;
            }
    
            public async Task&lt;IEnumerable&lt;Connection&gt;&gt; Get(int actionPlanId, int implementation)
            {
               List&lt;Connection&gt; diagramConnections = new List&lt;Connection&gt;();
               GetConnectionsByIdAndImplementationMessage message = new GetConnectionsByIdAndImplementationMessage
               {
                   ActionPlanId = actionPlanId,
                   Implementation = implementation
               };
    
               using var call = _client.GetAllConnections(message);
               await foreach (ConnectionServiceModel connection in call.ResponseStream.ReadAllAsync())
               {
                   // Never enters here as ResponseStream has no elements when unit testing!!
                   diagramConnections.Add(new Connection(
                       connection.FromActionPlanStepId, connection.ToActionPlanStepId, connection.ActionPlanId,
                       connection.Qualifier, connection.Implementation, connection.Path));
               }
    
               return diagramConnections;
           }
   }
</code></pre>
<p>I have been developing a unit test for this function but the list returned always has a count of zero.
This is because the ResponseStream has no elements inside of it.</p>
<p>How can I mock the ResponseStream?</p>
<p><strong>My unit test so far:</strong></p>
<pre><code>[Test]
        public async Task GetConnectionsTest()
        {
            // Arrange
            Mock&lt;ConnectionDb.ConnectionDbClient&gt; mockClient = new Mock&lt;ConnectionDb.ConnectionDbClient&gt;();
            Mock&lt;IAsyncStreamReader&lt;ConnectionServiceModel&gt;&gt; mockResponseStream
                = new Mock&lt;IAsyncStreamReader&lt;ConnectionServiceModel&gt;&gt;();

            List&lt;ConnectionServiceModel&gt; connectionServiceModels =
                new List&lt;ConnectionServiceModel&gt;
                {
                    new ConnectionServiceModel
                    {
                        ActionPlanId = 1,
                        FromActionPlanStepId = 1,
                        ToActionPlanStepId = 1,
                        Implementation = 0,
                        Qualifier = 1,
                        Path = &quot; 1;2;3;4;5;6;7;8;9;10;11;12;13;14&quot;
                    }
                };

            var fakeCall = TestCalls.AsyncServerStreamingCall
                (mockResponseStream.Object,
                Task.FromResult(new Metadata()), () =&gt; Status.DefaultSuccess,
                () =&gt; new Metadata(), () =&gt; { });

            mockClient.Setup(m =&gt; m.GetAllConnections(
                It.IsAny&lt;GetConnectionsByIdAndImplementationMessage&gt;(),
                null, null, CancellationToken.None)).Returns(fakeCall);

            // Act
            ActionPlanConnectionsService service = new ActionPlanConnectionsService(mockClient.Object);
            IEnumerable&lt;Connection&gt; connections = await service.Get(1, 1);

            // Assert
            
            // CONNECTIONS WILL ALWAYS HAVE 0 Elements as the response isn't setup for it.
        }
    }
</code></pre>
",https://stackoverflow.com/questions/65917871/mock-grpc-response-stream-for-unit-testing-c,"['c#', 'unit-testing', 'nunit', 'grpc']",3805,True,2,2
Ktor Unit Testing with JWT and Firebase Auth,"<p>I have Ktor Jwt authentication setup with Firebase Auth and working except in my unit testing. Getting <code>TRACE io.ktor.auth.jwt - Failed to get JWK: Failed to get key with kid null</code></p>
<p>I'm wondering if <code>FirebaseAuth.getInstance().createCustomToken(UUID.randomUUID().toString())</code> is not working.</p>
<p>Here is one of my unit tests:</p>
<pre><code>test(&quot;when register for game and userId is not found then NotFound is returned&quot;) {
    coEvery { userRepositoryMock.getUser(any()) } returns null
    withServer {
        val req = handleRequest(HttpMethod.Get, &quot;/api/game/1/2&quot;) {
            addJwtHeader()
        }
        req.response.status() shouldBe HttpStatusCode.NotFound
        req.response.content shouldBe &quot;Could not find user.&quot;
    }
}

private fun TestApplicationRequest.addJwtHeader() = addHeader(&quot;Authorization&quot;, &quot;Bearer ${getToken()}&quot;)

private fun getToken() = FirebaseAuth.getInstance().createCustomToken(UUID.randomUUID().toString())

private fun withServer(block: TestApplicationEngine.() -&gt; Unit) {
    withTestApplication({ module() }, block)
}
</code></pre>
",https://stackoverflow.com/questions/66056024/ktor-unit-testing-with-jwt-and-firebase-auth,"['firebase-authentication', 'jwt', 'ktor']",288,False,1,0
Unit testing IHttpActionResult with OkNegotiatedContentResult having anonymous types,"<p>I am using MS Test for Unit Testing my Web API Controller.</p>
<p>Below is my Web API Controller method with the return type:</p>
<pre><code>public IHttpActionResult MethodName(){ //Code logic 
    return Ok(new { Data = result, Total = (result.Count() &gt; 0 ? result.First().TotalCount : 0) });
}
</code></pre>
<p>In above code snippet:</p>
<ol>
<li>Data is of Type IEnumerable&lt;ViewModelName'&gt;</li>
<li>Total Count is of Type Int</li>
</ol>
<p>Now for testing above API method return type below is what I have tried :</p>
<pre><code>[TestMethod]
public void TestMethodName(){
var result = controller.MethodName();
//Below line is having issue and thus the contentResult is null 
var contentResult = result as OkNegotiatedContentResult&lt;List&lt;ViewModelName&gt;&gt;;
}
</code></pre>
<p>Adding Int to OkNegotiatedContentResult throws error as it only excepts single parameter &lt;T'&gt;</p>
<p>Below is the actual return type from the API:</p>
<p>{System.Web.Http.Results.OkNegotiatedContentResult&lt;&lt;&gt;f__AnonymousType0&lt;System.Collections.Generic.List&lt;ViewModel'&gt;, int&gt;&gt;}</p>
<p>How should I convert result so that I can use its content into Assert ?</p>
<p>Thank you in advance.
Code sample is appreciated.</p>
",https://stackoverflow.com/questions/69359128/unit-testing-ihttpactionresult-with-oknegotiatedcontentresult-having-anonymous-t,"['c#', 'unit-testing', 'asp.net-web-api', 'mstest']",897,True,1,2
Django Rest Framework - unit testing viewset extra actions,"<p>If I take the example from the official documentation:</p>
<pre><code>class UserViewSet(viewsets.ModelViewSet):
    &quot;&quot;&quot;
    A viewset that provides the standard actions
    &quot;&quot;&quot;
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @action(detail=True, methods=['post'])
    def set_password(self, request, pk=None):
        user = self.get_object()
        serializer = PasswordSerializer(data=request.data)
        if serializer.is_valid():
            user.set_password(serializer.data['password'])
            user.save()
            return Response({'status': 'password set'})
        else:
            return Response(serializer.errors,
                            status=status.HTTP_400_BAD_REQUEST)
</code></pre>
<p>How would I write my unit test to test the success of the action, and its failure?  I'm not sure what the syntax would be.</p>
",https://stackoverflow.com/questions/67317165/django-rest-framework-unit-testing-viewset-extra-actions,['django-rest-framework'],957,True,1,1
Unit Testing Firestore in Xcode is Not Working,"<p>Every time I run a test I get this error:</p>
<blockquote>
<p><em>Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'FIRESTORE INTERNAL ASSERTION FAILED: Failed to open DB: Internal: Failed to open LevelDB database</em></p>
</blockquote>
<p>The following is my code:</p>
<pre><code>import XCTest
import FirebaseCore
import FirebaseFirestore

class ViewModelTests: XCTestCase {
  
  override class func setUp() {
    super.setUp()
    FirebaseApp.configure()
  }
  
  func testFetchUsers() {
    Firestore
      .firestore()
      .collection(&quot;users&quot;)
      .addSnapshotListener { querySnapshot, error in
        // code...
      }
  }
}
</code></pre>
",https://stackoverflow.com/questions/68130909/unit-testing-firestore-in-xcode-is-not-working,"['ios', 'xcode', 'unit-testing', 'google-cloud-firestore']",147,False,1,0
Spring WebFlux; unit testing exception thrown in Mono.map(),"<p>I have some code that returns <code>Mono&lt;List&lt;UserObject&gt;&gt;</code>.  The first thing I want to do is check the List is not empty, and if it is, throw a <code>NoUsersFoundException</code>.  My code looks like this:</p>
<pre><code>IUserDao.java
Mono&lt;List&lt;UserAccount&gt;&gt; getUserProfiles(final Set&lt;UserQueryFilter&gt; filters,
                                       final Set&lt;String&gt; attributes);
</code></pre>
<pre><code>GetUserAccount.java
public Mono&lt;UserAccount&gt; doGetUserAccount() {
    return userDao.getUserProfiles(filters, attributes)
                      .map(list -&gt; {
                          if (CollectionUtils.isEmpty(list)) {
                              throw new NoUsersFoundException();
                           }
                           return list;
                       })
                       .map(this::removePermissions)
                       .map(this::removeDuplicates);
}
</code></pre>
<p>I want to write a unit test that will test that the <code>NoUsersFoundException</code> is thrown when <code>userDao.getUserProfiles(filters, attributes)</code> returns an empty list.  When I use <code>Mockito#when</code> with a <code>.thenReturn()</code>, the test will, as expected, return immediately once <code>userDao.getUserProfiles(...)</code> is called without continuing the flow into the <code>.map()</code> where the list is checked and exception thrown.</p>
<pre><code>@Mock
private IUserDao userDao;

private UserPolicies userPolicies;

@BeforeEach
public void init() {

    userPolicies = new UserPolicies(Set.of(&quot;XYZ&quot;, USER_AFF, &quot;123&quot;),
                                           Set.of(TestUserConstants.ID, TestUserConstants.SUBSCRIPTION_LEVEL));
}

@Test
void shouldThrowExceptionIfNoUsersFound() {

    final Set&lt;UserFilter&gt; filters = new UserFilterBuilder().withId(ID)
                                                           .withSubscription(PREMIUM)
                                                           .build();

    when(userDao.getUserProfiles(filters, userPolicies.getUserAttributeIds()))
                    .thenReturn(Mono.just(Collections.emptyList()));

    testClass = new GetUserAccount(userDao,
                                   userPolicies,
                                   filters,
                                   userPolicies.getUserAttributeIds());

    assertThatThrownBy(() -&gt; testClass.doGetUserAccount()).isInstanceOf(NoUsersFoundException.class);
}
</code></pre>
<p>I have tried <code>.thenAnswer()</code> but it essentially does the same thing as the method called is not a void:</p>
<pre><code>userDao.getUserProfiles(filters, userPolicies.getUserAttributeIds()))
                .thenAnswer((Answer&lt;Mono&lt;List&gt;&gt;) invocationOnMock -&gt; Mono.just(Collections.emptyList()));
</code></pre>
<p>I can't see how using <code>reactor.test.StepVerifier</code> would work for this case.</p>
",https://stackoverflow.com/questions/68925677/spring-webflux-unit-testing-exception-thrown-in-mono-map,"['junit', 'mockito', 'reactive-programming', 'spring-webflux', 'junit5']",2043,True,1,1
"Angular Unit Testing with RxJS, pipe, and subscribe","<p>I'm trying to write some unit test (Jasmine) for my Angular 11 Component. In ngOnInit() it calls two http ajax functions from the service that return data from the database. Both return a Subscription (rxjs), and I chained them with pipe() and switchMap().</p>
<p>It's something like this:</p>
<pre><code>ngOnInit(): void {
    const configID = 12345;
    this.service.getDataOne(configID)
        .pipe(
            switchMap(() =&gt; {
                return this.service.getDataTwo(configID);
            })
        )
        .subscribe(res =&gt; {
              if(res.SUCCESS) {
                    this.dataSource.data = res.DATA.RESULT;
              }
              else {
                  this.error = res.ERROR;
              }
         });
}
</code></pre>
<p>In my spec.ts:</p>
<pre><code>describe('MyComponent', () =&gt; {
let component: MyComponent;
let fixture: ComponentFixture&lt;MyComponent&gt;;
const serviceSpy = jasmine.createSpyObj('MyService', [ 'getDataOne', 'getDataTwo' ]);
const mockSuccessData1 = {
    SUCCESS: true
    , DATA: 'mock result 1';
}

const mockSuccessData2 = {
    SUCCESS: true 
    , DATA: 'mock result 2';
}

beforeEach(waitForAsync(() =&gt; {
    TestBed.configureTestingModule({
        declarations: [ MyComponent ]
        , imports: [ ]
        , providers : [
            { provide: MyService, useValue: serviceSpy }
        ]
    }).compileComponents();

    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    serviceSpy.getDataOne.and.returnValue(of(mockSuccessData1));

    fixture.detectChanges();
}));

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

});
</code></pre>
<p>What's the proper way to test this component and mock the subscriptions?
I tried <code>serviceSpy.getDataOne.and.returnValue(of(mockSuccessData1 ));</code>
But I got error &quot;Failed: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.&quot;</p>
<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/69489942/angular-unit-testing-with-rxjs-pipe-and-subscribe,"['angular', 'unit-testing', 'rxjs', 'jasmine', 'switchmap']",3587,True,1,1
Unit Testing regex to check for False Positives,"<p>so I have a Regex expression that I'm matching against a single string provided to check and match certain information. If it's matched, only the captured group is returned. I have made my function so that it removes any null strings from the returned array and finally, just gives the captured string as the output. This works great in unit testing for True Positives.</p>
<p>Now, I want to check for False Positives using the same expression, except I can't seem to figure out how to demonstrate it in a unit test. I have a few test strings in a file for which the Regex shouldn't match, and it does not. So my code works. But when I try to actually show that in a test case, as in check if a null string is returned, I can't.</p>
<p>I essentially want to check that if a match is not found, then it should return a null string. This is my code</p>
<pre><code>match = re.findall(combined, narration)
    result = list(filter(None, match[0]))
    if match:
        return result[0]
    else:
        result[0] = &quot;&quot;
        return result[0]
</code></pre>
<p>The first clause works fine for matched strings and returns a single string as output. In the second clause, I want to output a null string so I can check with the test case <code>.assertEqual</code> if the string is unmatched. But the function returns <code>list index out of range</code> error.</p>
<p>Can anybody tell me if there's a better way to check for an unmatched string with Regex and Unit Tests?</p>
<p><strong>Edit 1:</strong> Adding Expected Input and Output as requested</p>
<p>Input 1 - BRN CLG-CI IQ PAID ROHIT SINGH</p>
<p>Output 1 - ROHIT SINGH</p>
<p>Input 2 - BRN-TO CASH SELF</p>
<p>Output 2 - ''  //null string</p>
",https://stackoverflow.com/questions/67824633/unit-testing-regex-to-check-for-false-positives,"['python', 'regex', 'unit-testing', 'false-positive']",280,True,1,1
Unit testing and high-order functions in Kotlin,"<p>So i have a base class:</p>
<pre class=""lang-kotlin prettyprint-override""><code>abstract class BaseService&lt;M : MyMetric&gt;(private val otherService: OtherService) {

    abstract fun &lt;T&gt; monitor(metric: M, action: () -&gt; T): T

    protected fun &lt;T&gt; monitorDefault(metric: M, action: () -&gt; T): T {
        val begin = System.currentTimeMillis()
        return try {
            notifyEvent(metric.total)
            val result = action()
            notifyEvent(metric.success)
            result
        } catch (e: CommonException) {
            //handling
        }
    }
</code></pre>
<p>and simple implementation:</p>
<pre class=""lang-kotlin prettyprint-override""><code>class PrintMetricService(otherService: OtherService): BaseService&lt;PrintMetric&gt;(otherService) {

    override fun &lt;T&gt; monitor(metric: PrintMetric, action: () -&gt; T) : T {
        return monitorDefault(metric, action)
    }
}
</code></pre>
<p>then i use this method:</p>
<pre class=""lang-kotlin prettyprint-override""><code>@Service
class PrintReportService(private val reportService: ReportService,
                         private val metricService: MetricService&lt;PrintMetric&gt;) {

    fun getReport(): String {
 
        return metricService.monitor(PrintMetric) {
            val response = try {
                    reportService.renderPdf(jsonRequest, TEMPLATE_CODE, channel)
                } catch (e: Exception) {
                    throw CommonException(PRINT_SERVICE_ERROR_EXCEPTION_CODE)
                }
            response.body.data!!
        }
    }
</code></pre>
<p>now I want to write a unit test for <code>getReport()</code> (we use TestNg and mockito in project):</p>
<pre class=""lang-kotlin prettyprint-override""><code>class PrintReportServiceImplTest {

    @InjectMocks
    private lateinit var printReportService: PrintReportServiceImpl

    @Mock
    private lateinit var reportService: ReportService

    @Mock
    private lateinit var metricService: PrintMetricService


    @BeforeMethod
    fun setUp() {
        openMocks(this)

        whenever(reportService.renderPdf().thenReturn(&quot;response (base64)&quot;)
    }

    @Test
    fun getReportTest() {
        val report = printReportService.getReport()
        assertNotNull(report)
    }
}
</code></pre>
<p>the test crashes with an error:  <code>java.lang.AssertionError: expected object to not be null</code>
But if i add <code>inline</code> when override <code>monitor(metric: M, action: () -&gt; T)</code> in <code>PrintMetricService</code> the test will pass. What could be the problem? Is this a feature of the high-order functions in Kotlin?</p>
",https://stackoverflow.com/questions/69974440/unit-testing-and-high-order-functions-in-kotlin,"['unit-testing', 'kotlin', 'mockito']",174,False,1,0
Angular unit testing is there any thing wrong,"<p>I am learning angular testing and write simple testing code and it shows me error in it. In my app folder, I had created a test.spect.ts file that contains the following code.</p>
<pre><code>describe('app',()=&gt;{
    it('should display original title', () =&gt; {
    expect(true).toBe(true);
  });
});
</code></pre>
<p>using ng test I am trying to run the code and here comes the error.</p>
<pre><code>is not digitally about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.
At line:1 char:1
+ ng test
+ ~~
    + CategoryInfo          : SecurityError: (:) [], PSSecurityException
    + FullyQualifiedErrorId : UnauthorizedAccess
</code></pre>
<p>Please help I am just on learning phase.</p>
",https://stackoverflow.com/questions/66357033/angular-unit-testing-is-there-any-thing-wrong,"['angular', 'angular-test']",43,False,1,0
Unit Testing Angular If condition make button disabled,"<p>I try create unit test for this condition</p>
<pre><code>  insertForm(index) {
if (this.getForms().length === 0) {
  this.getForms().insert(0, this.formTemplate());
} else {
  this.getForms().insert(index + 1, this.formTemplate());
}
if (this.getForms().length &gt; 99) {
  this.addBtnDisabled = true;
}
</code></pre>
<p>}</p>
<p>I have 3 condition, and I success make it for 2 first condition, but in the last condition I got out of my expectation, addBtnDisabled should be true. But in karma, it shows false. this is my code in jasmine. what's wrong with my last condition?</p>
<pre><code>  it('insert form function should insert new form in index 0 IF GETFORMS.LENGTH IS 0', () =&gt; { 
(component.formGroup.get('forms') as FormArray).removeAt(0);
const getFormValue = component.getForms().length;
expect(getFormValue).toEqual(0);
component.insertForm(0);
expect(component.getForms().length).toEqual(1);


 });



 it('insert form function should insert new form in index param + 1 IF GETFORMS.length not equal to 0', () =&gt; {
    const getFormLength: number = component.getForms().length;
    const isGetFormLengthtoNotEqual0: boolean = (getFormLength &gt; 0);
    expect(isGetFormLengthtoNotEqual0).toBeTruthy();
    expect(component.getForms().length).toEqual(1);

    spyOn(component.getForms(), 'insert').and.callThrough();

    component.insertForm(1);

    expect(component.getForms().length).toEqual(2);

  });



it('insert form function should addBtnDisabled', () =&gt; { // 
    const getFormValue: number = component.getForms().length + 99;
    expect(getFormValue).toEqual(100);
    component.insertForm(100);
    expect(component.addBtnDisabled).toBeTruthy()
  });
</code></pre>
",https://stackoverflow.com/questions/68279994/unit-testing-angular-if-condition-make-button-disabled,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",260,False,0,1
Unit testing nodejs module using mocha and chai,"<p>I have a nodejs app for which I am writing unit tests and I have the following situation : I have a config.js file in which I read multiple parameters from as environmental variables and some certificates to connect to RabbitMQ. I export this configuration as a module.</p>
<p>What I want to do is to create a unit test file which will take test the module in different scenarios and try to achieve a very high coverage percentage.</p>
<p>I have several environments like LOCAL_DEV, DEV, UAT and PROD with several instances of RabbitMQ. For dev for example I connect to RabbitMQ using a key file, in LOCAL_DEV only with username and password, in UAT with a pfx and so on.</p>
<p>The environment variables like process.env.ENO_ENV get injected during deployment and other configuration params I get them via the .env_dev or .env_uat files for example. I get also certificates injected when I do the deployment and the path to them is given in the '.env_' file.</p>
<p>For example, in DEV, I have process.env.ENO_ENV = dev and the .env_dev looks like :</p>
<pre><code>RABBITMQ_SSL_KEYFILE = 'tls/dev/rmq-XXX.key'
RABBITMQ_SSL_CERTFILE = 'tls/dev/rmq-XXX.crt'
RABBITMQ_SSL_CAFILE = 'tls/dev/rmq-dev-ca.crt'
</code></pre>
<p>The tests are done in Gitlab, where I do not have any certificate file or .env_ file given so I need to mock the process.env.ENO_ENV and the .env_file.</p>
<p>The content of the config.js file :</p>
<pre><code>const fs = require('fs');
const path = require('path');

// Load config for the set env
global.appRoot = path.resolve(__dirname);
const eno_env = process.env.ENO_ENV || &quot;&quot;;

if (process.env.ENO_ENV == 'dev' || 
  process.env.ENO_ENV == 'local_dev' || 
  process.env.ENO_ENV == 'uat' || 
  process.env.ENO_ENV == 'prod') {    
  require('dotenv').config({ path: path.join(global.appRoot, '.env_' + eno_env) });
} else {
  require('dotenv').config({ path: path.join(global.appRoot, '.env') });
}

const {
  PORT,
  RABBITMQ_PROTOCOL,
  RABBITMQ_USER,
  RABBITMQ_PASS,
  RABBITMQ_HOSTS,
  RABBITMQ_PORT,
  RABBITMQ_VHOST,
  RABBITMQ_EXCHANGE,
  RABBITMQ_QUEUE,
  RABBITMQ_SSL_CAFILE,
  RABBITMQ_SSL_KEYFILE,
  RABBITMQ_SSL_CERTFILE,
  RABBITMQ_SSL_PFX,
  RABBITMQ_SSL_PASSWORD,
} = process.env;

let opts = {};

if (RABBITMQ_SSL_PFX) {
  console.log ('RABBITMQ_SSL_PFX : ' + path.join(global.appRoot, RABBITMQ_SSL_PFX));
  opts = {
    pfx: fs.readFileSync(path.join(global.appRoot, RABBITMQ_SSL_PFX)),
    passphrase: RABBITMQ_SSL_PASSWORD,
    ca: [fs.readFileSync(path.join(global.appRoot, RABBITMQ_SSL_CAFILE))],
    rejectUnauthorized: false,
  };
} else if (RABBITMQ_SSL_KEYFILE) {
  opts = {
    key: fs.readFileSync(path.join(global.appRoot, RABBITMQ_SSL_KEYFILE)),
    cert: fs.readFileSync(path.join(global.appRoot, RABBITMQ_SSL_CERTFILE)),
    ca: [fs.readFileSync(path.join(global.appRoot, RABBITMQ_SSL_CAFILE))],
    rejectUnauthorized: false,
  };
}

const config = {
  app: {
    port: parseInt(PORT) || 8126,
    enoenv: eno_env,
  },
  rabbitmq: {
    protocol: RABBITMQ_PROTOCOL || 'amqps',
    user: RABBITMQ_USER || 'test',
    pass: RABBITMQ_PASS || 'test',
    hosts: RABBITMQ_HOSTS || 'localhost',
    port: parseInt(RABBITMQ_PORT) || 5671,
    vhost: RABBITMQ_VHOST || 'test_virtualhost',
    exchange: RABBITMQ_EXCHANGE || 'test_exchange',
    queue: RABBITMQ_QUEUE || 'test_queue',
    opts,
  },
};

module.exports = config;
</code></pre>
<p>My problem is to achieve the unit test coverage with mocha and chai by using a file called configCert1UnitTest.js :</p>
<pre><code>const should = require('chai').should();

process.env['RABBITMQ_SSL_PFX'] = '/test/test.json';
process.env['RABBITMQ_SSL_PASSWORD'] = 'test';
process.env['RABBITMQ_SSL_CAFILE'] = '/test/test.json';

const config = require('./../config');

describe('env 1', function () {
    // running tests
    it('reads env RABBITMQ_SSL_PFX property, config.rabbitmq.opts.pfx and test.json file correctly', function () {
        try {
            //target = fs.readFileSync(path.join(global.appRoot, process.env['RABBITMQ_SSL_PFX']));
            should.equal( 
                config.rabbitmq.opts.pfx.toString('utf8'), 
                '{\r\n    &quot;property&quot; : &quot;test&quot;\r\n}');
          } catch(e) {
            throw new Error(&quot;error reading env RABBITMQ_SSL_PFX property, config.rabbitmq.opts.pfx or test.json: &quot; + e.message);
          }    
    });

    it('reads env RABBITMQ_SSL_CAFILE property, config.rabbitmq.opts.ca and test.json file correctly', function () {
        try {
            should.equal( 
                config.rabbitmq.opts.ca.toString('utf8'), 
                '{\r\n    &quot;property&quot; : &quot;test&quot;\r\n}');
          } catch(e) {
            throw new Error(&quot;error reading env RABBITMQ_SSL_CAFILE property, config.rabbitmq.opts.ca or test.json: &quot; + e.message);
          }
              
    });
  });
  
  delete process.env.RABBITMQ_SSL_PFX;
  delete process.env.RABBITMQ_SSL_PASSWORD;
  delete process.env.RABBITMQ_SSL_CAFILE;
</code></pre>
<p>Now, for having the situation where the other IF in the condif.js is covered i wrote the second test case in file configCert2UnitTest.js :</p>
<pre><code>const should = require('chai').should();

process.env['RABBITMQ_SSL_KEYFILE'] = '/test/test.json';
process.env['RABBITMQ_SSL_CERTFILE'] = '/test/test.json';
process.env['RABBITMQ_SSL_CAFILE'] = '/test/test.json';

const config = require('./../config');
  
describe('env 2', function () {
    
    // running tests
    it('reads env RABBITMQ_SSL_KEYFILE property, config.rabbitmq.opts.key and test.json file correctly', function () {
        try {
            should.equal( 
                config.rabbitmq.opts.key.toString('utf8'), 
                '{\r\n    &quot;property&quot; : &quot;test&quot;\r\n}');
          } catch(e) {
            throw new Error(&quot;error reading env RABBITMQ_SSL_KEYFILE property, config.rabbitmq.opts.key or test.json: &quot; + e.message);
        }    
    });

    it('reads env RABBITMQ_SSL_CERTFILE property, config.rabbitmq.opts.cert and test.json file correctly', function () {
        try {
            should.equal( 
                config.rabbitmq.opts.cert.toString('utf8'), 
                '{\r\n    &quot;property&quot; : &quot;test&quot;\r\n}');
          } catch(e) {
            throw new Error('error reading env RABBITMQ_SSL_CERTFILE property, config.rabbitmq.opts.cert or test.json:' + e.message);
          }    
    });

    it('reads env RABBITMQ_SSL_CAFILE property, config.rabbitmq.opts.ca and test.json file correctly', function () {
        try {
            should.equal( 
                config.rabbitmq.opts.ca.toString('utf8'), 
                '{\r\n    &quot;property&quot; : &quot;test&quot;\r\n}');
          } catch(e) {
            throw new Error('error reading env RABBITMQ_SSL_CAFILE property, config.rabbitmq.opts.ca or test.json: ' + e.message);
          }    
    });

  });

delete  process.env.RABBITMQ_SSL_KEYFILE;
delete process.env.RABBITMQ_SSL_CERTFILE;
delete process.env.RABBITMQ_SSL_CAFILE;
</code></pre>
<p>The problem is the tests do not cover the ELSE of the module config.</p>
<p>Commands for testing in my package.json:</p>
<pre><code>...
&quot;test&quot;: &quot;npx nyc mocha test --exit --timeout 10000 --reporter mocha-junit-reporter&quot;,
...
</code></pre>
<p>Output :</p>
<pre><code>PS D:\zzz-api&gt; npx mocha test
global.appRoot : D:\zzz-liveprice-api
RABBITMQ_SSL_PFX : D:\zzz-api\test\test.json


  env 1
    ✔ reads env RABBITMQ_SSL_PFX property, config.rabbitmq.opts.pfx and test.json file correctly
    ✔ reads env RABBITMQ_SSL_CAFILE property, config.rabbitmq.opts.ca and test.json file correctly

  env 2
    1) reads env RABBITMQ_SSL_KEYFILE property, config.rabbitmq.opts.key and test.json file correctly
    2) reads env RABBITMQ_SSL_CERTFILE property, config.rabbitmq.opts.cert and test.json file correctly
    ✔ reads env RABBITMQ_SSL_CAFILE property, config.rabbitmq.opts.ca and test.json file correctly

  Dummy Test
    ✔ First test that should pass

  Bindings Unit Test
    ✔ Should return true if the correct bindings are found for the EUA
    ✔ Should return true if the correct bindings are found for the POWER
    ✔ Should return true if the correct bindings are found for the GAS


  7 passing (534ms)
  2 failing

  1) env 2
       reads env RABBITMQ_SSL_KEYFILE property, config.rabbitmq.opts.key and test.json file correctly:
     Error: error reading env RABBITMQ_SSL_KEYFILE property, config.rabbitmq.opts.key or test.json: Cannot read property 'toString' of undefined
      at Context.&lt;anonymous&gt; (test\configCert2UnitTest.js:19:19)
      at processImmediate (internal/timers.js:439:21)

  2) env 2
       reads env RABBITMQ_SSL_CERTFILE property, config.rabbitmq.opts.cert and test.json file correctly:
     Error: error reading env RABBITMQ_SSL_CERTFILE property, config.rabbitmq.opts.cert or test.json:Cannot read property 'toString' of undefined
      at Context.&lt;anonymous&gt; (test\configCert2UnitTest.js:30:19)
      at processImmediate (internal/timers.js:439:21)
</code></pre>
<p>I forgot to mention that I set up a test.json file for the tests in my \test directory, which contains '{\r\n    &quot;property&quot; : &quot;test&quot;\r\n}' just to simulate the certificates, which are missing when testing in Gitlab.</p>
<p>Any ideas how to fix this ? Thanks !</p>
",https://stackoverflow.com/questions/68229635/unit-testing-nodejs-module-using-mocha-and-chai,"['node.js', 'unit-testing', 'rabbitmq', 'mocha.js', 'chai']",485,True,0,1
Mockito unit testing: Invalid use of argument matchers,"<p>I see dozens of occurrences of this same Mockito exception but, in my case, I really don't understand what am I suppose to do as I don't mix matchers and values. Here is the case:</p>
<p>I have a REST resource which invokes a service and I want to mock the service and to inject the mocked service into the REST resource. Here is the code:</p>
<pre><code>  @Mock
  private Service service;
  @InjectMocks
  private Resource resource;
  ...
  @Test
  public void test() throws URISyntaxException
  {
    assertThat(resource).isNotNull();
    doNothing().when(service).createItem(anyLong(), any(Item.class));
    when(resource.createItem(any(Item.class))).thenReturn(Response.created(new URI(&quot;/items&quot;)).build());
    Response response = resource.createItem(item);
    Mockito.verify(service).createItem(item);
  }
</code></pre>
<p>And the exception:</p>
<pre><code>-&gt; at fr.simplex_software.micro_services_without_spring.customers.tests.TestCustomers.testCreateCustomer(TestCustomers.java:59)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), &quot;raw String&quot;);
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq(&quot;String by matcher&quot;));

For more info see javadoc for Matchers class.
</code></pre>
<p>I don't think that I'm mixing matchers and values here. Could anyone please help?</p>
",https://stackoverflow.com/questions/65827186/mockito-unit-testing-invalid-use-of-argument-matchers,"['java', 'mockito']",89,True,0,1
Endpoint unit testing with Lacinia-Pedestal in Clojure,"<p>I have been using <code>Pedestal</code> for RESTful API servers and its endpoint unit testing. This approach is to set the server up and test it on endpoint level. The so-called &quot;endpoint unit testing&quot; is well documented in below page.</p>
<p><a href=""http://pedestal.io/reference/unit-testing#_testing_your_service_with_response_for"" rel=""nofollow noreferrer"">http://pedestal.io/reference/unit-testing#_testing_your_service_with_response_for</a></p>
<p>This time, however, I am using <code>Lacinia-Pedestal</code> for GraphQL (not RESTful, in other words) and am wondering if I can apply the same endpoint testing logic. In Lacinia-Pedestal repository (<a href=""https://github.com/walmartlabs/lacinia-pedestal"" rel=""nofollow noreferrer"">https://github.com/walmartlabs/lacinia-pedestal</a>), I could not find a relevant instruction. In fact it doesn't mention about unit testing at all.</p>
<p>If anyone has experience with this approach, can you please share?
Thanks!</p>
<p>-- edit
I am adding my testing code here.</p>
<p><strong>resources/main-schema.edn:</strong></p>
<pre><code>{:queries
 {:hello
  {:type String}}}
</code></pre>
<p><strong>core.clj</strong></p>
<pre><code>(ns lacinia-pedestal-lein-clj.core
  (:require [clojure.edn :as edn]
            [clojure.java.io :as io]
            [com.walmartlabs.lacinia.pedestal2 :as p2]
            [com.walmartlabs.lacinia.schema :as schema]
            [com.walmartlabs.lacinia.util :as util]
            [io.pedestal.http :as http]))

(defn resolve-hello
  [_ _ _]
  &quot;hello, darren&quot;)

(defn hello-schema
  []
  (-&gt; (io/resource &quot;main-schema.edn&quot;)
      slurp
      edn/read-string
      (util/inject-resolvers {:queries/hello resolve-hello})
      schema/compile))

(def service
  (-&gt; (hello-schema)
      (p2/default-service nil)
      http/create-server
      http/start))
</code></pre>
<p>and <code>Pedestal</code> (not <code>Lacinia-Pedestal</code>) says that the server instance can be set up and tested by the following code snippet:</p>
<pre><code>(ns lacinia-pedestal-lein-clj.core-test
  (:require [lacinia-pedestal-lein-clj.core :as core]
            [clojure.test :as t]
            [io.pedestal.http :as http]
            [io.pedestal.test :as ptest]
            [com.walmartlabs.lacinia.pedestal2 :as p2]
            [com.walmartlabs.lacinia.util :as util]))

(def service 
  (:io.pedestal.http/service-fn 
    (io.pedestal.http/create-servlet service-map)))

(is (= &quot;Hello!&quot; (:body (response-for service :get &quot;/hello&quot;))))
</code></pre>
<p>But, I believe this way works for RESTful but not for GraphQL because GraphQL needs to set schema (.edn file) and resolvers for a server.</p>
<p>So, I tried to tweak this.</p>
<pre><code>(ns lacinia-pedestal-lein-clj.core-test
  (:require [lacinia-pedestal-lein-clj.core :as core]
            [clojure.test :as t]
            [io.pedestal.http :as http]
            [io.pedestal.test :as ptest]
            [com.walmartlabs.lacinia.pedestal2 :as p2]
            [com.walmartlabs.lacinia.util :as util]))

(defonce service
  (-&gt; (core/hello-schema)
      (p2/default-service nil)
      http/create-server
      http/start))

(t/is (= &quot;Hello!&quot;
         (:body 
          (util/response-for service
                             :get &quot;/hello&quot;)))) ;; NOT WORKING
</code></pre>
<p>But it does not work this way because <code>response-for</code> expects <code>interceptor-service-fn</code> type.
So, as far as I know, the real question is how to use <code>response-for</code> function with GraphQL server instance.</p>
",https://stackoverflow.com/questions/68575488/endpoint-unit-testing-with-lacinia-pedestal-in-clojure,"['unit-testing', 'clojure', 'graphql', 'pedestal']",126,False,0,1
Spock unit testing a Kotlin private static method,"<p>I'm looking for help to debug/resolve the obscure error:</p>
<blockquote>
<p>java.lang.IllegalArgumentException: wrong number of arguments</p>
</blockquote>
<p>I don't want to get into an argument of whether or not I should be testing a private method. But, I'm open to learning how to restructure this into something more testable that isn't exposed to the plugin user. I just can't seem to make it work. Below is the signature of the method and the relevant code.</p>
<h2>Output from println in test setup</h2>
<pre><code>public static final org.gradle.api.file.DirectoryProperty my.project.MyPlugin.access$getResolvedDir(my.project.MyPlugin,java.lang.Object,org.gradle.api.Project)
</code></pre>
<h2>Class under test</h2>
<pre><code>class MyPlugin : Plugin&lt;Project&gt; {

    override fun apply(project: Project): Unit = project.run {
        // do some gradle plugin stuff
        myTask.configure { dir = getResolvedDir(pluginExtension.dir, project) }
    }

    private fun getResolvedDir(dir: Any?, project: Project): DirectoryProperty {
        // do some stuff to transform the input to a DirectoryProperty
        return resolvedDir
    }
}
</code></pre>
<h2>Spock test case</h2>
<pre><code>class MyPluginTest extends Specification {

    @Rule
    public final TemporaryFolder testProjectDir = new TemporaryFolder()
    private Project p
    private MyPlugin plugin
    private CachedMethod getResolvedDirMethod

    def setup() {
        p = ProjectBuilder.builder().withName(&quot;install-plugin-test&quot;).build()
        plugin = new InstallPlugin()
        plugin.metaClass.methods.each {
            if (it.name.contains(&quot;getResolvedDir&quot;))
                getResolvedDirMethod = it
        }
        getResolvedDirMethod.setAccessible()
        println getResolvedDirMethod
    }

    def &quot;String resolution for dir&quot;() {
        when:
        def x = &quot;xyz&quot;

        then:
        DirectoryProperty dir = getResolvedDirMethod.invoke(plugin, x, p)
    }
}
</code></pre>
",https://stackoverflow.com/questions/67200575/spock-unit-testing-a-kotlin-private-static-method,"['kotlin', 'gradle', 'spock']",179,False,0,0
Missing c/c++ unit testing support in eclipse?,"<p>I am using the <em>Eclipse IDE for C/C++ Developers</em> (2021-03) package and cannot find the entry &quot;C/C++
Unit Testing Support&quot; under &quot;Help &gt; Install New Software&quot;.</p>
<p>I need it for using gtest with a C++ project but the installation entry in the software menu (within Programming Languages) does not exist anymore. Previous versions appeared to have it available. I followed this guide: <a href=""https://www.pbma.de/docpt/content/951f7999aa405c4c016c1cda35f564d08ae7c71bf867722ad896d11c21e3be51"" rel=""nofollow noreferrer"">https://www.pbma.de/docpt/content/951f7999aa405c4c016c1cda35f564d08ae7c71bf867722ad896d11c21e3be51</a></p>
<p>Is it removed from there or how can I install it?</p>
",https://stackoverflow.com/questions/66903457/missing-c-c-unit-testing-support-in-eclipse,"['eclipse', 'unit-testing']",136,True,0,1
Unit testing file download for NestJS using Jest,"<p>I want to know how can I test the file downloaded is the file I want from just backend. Most tutorials/instructions I saw is test from frontend side. I want to know is it possible to test just the backend API using Jest? Thanks in advance!</p>
<p>This is the code for controller:</p>
<pre><code>@Post('downloadDB')
async downloadDB(@Res() res: Response) {
    return this.configPageService.downloadDB(res);
}
</code></pre>
<p>This is the code for service:</p>
<pre><code>async downloadDB(res: Response) {
    try {
        const admzip = require('adm-zip')
        var configService = new ConfigService();
        var dbPath = configService.dbSource;
        var zip = new admzip();
        var outputFilePath = Date.now() + &quot;_lbkpngr.zip&quot;;
        zip.addLocalFile(dbPath);
        fs.writeFileSync(outputFilePath, zip.toBuffer());
        res.download(outputFilePath, (err) =&gt; {
            if (err)
                console.log(err);
            fs.unlink(outputFilePath, (error) =&gt; {
                console.log(error);
            });
        });
    } catch (e) {
        console.error(e);
        res.status(500).end();
    }
}
</code></pre>
",https://stackoverflow.com/questions/68630164/unit-testing-file-download-for-nestjs-using-jest,"['node.js', 'unit-testing', 'jestjs', 'nestjs']",153,False,0,0
Angular-Unit testing: ng test command not working,"<p>I am working on an angular project. I want to add karma &amp; jasmine testing to my project. I did all the necessary setups and created a spec.ts file with testcases.</p>
<p>When I put <code>npm test</code> command I got the below output:</p>
<pre><code>PS C:\Users\Vinay\retailer-webapp&gt; npm test

&gt; retialer-webapp@1.0.0 test C:\Users\Vinay\retailer-webapp
&gt; ng test

PS C:\Users\Vinay\retailer-webapp&gt; 
</code></pre>
<p>The test cases are not executed and karma is also not initialized.</p>
<p>PS: I don't know how to debug the command execution process.</p>
",https://stackoverflow.com/questions/65663974/angular-unit-testing-ng-test-command-not-working,"['angular', 'unit-testing', 'karma-jasmine']",1369,True,0,1
How to fake Alamofire request for unit testing?,"<p>In my app, I'm using Alamofire to make network calls, but now, I want to test the calls.</p>
<p>I do the network call like this :</p>
<pre><code>AF.request(myURL).responseData { response in 
    // Decode the data
    // Translate the data into an object
}
</code></pre>
<p>I tried to fake the AF session and override his request, but I don't know what should go inside.</p>
<pre><code>class FakeAFSession: Session {
    override func request(_ convertible: URLRequestConvertible, interceptor: RequestInterceptor? = nil) -&gt; DataRequest {
        // Fake the network request here
    }
}
</code></pre>
<p>Here is how I want the test to run.</p>
<pre><code>func testGivenCallbackFailed_WhenErrorInNetworkCall_ThenObjectReturnAreNil(){
        // MARK: - Given
        
        // I want to create a fake request
        let fakeRequest = FakeNetworkRequest()
        
        // I want to pass the request to the fake session of Alamofire
        let fakeSession = FakeAFSession(request: fakeRequest)
        
        // Finally, I want to pass the session to the service
        let service = RecipeService(session: fakeSession)
        
        // MARK: - When
        let expectation = XCTestExpectation(description: &quot;Error in network call&quot;)
        
        let fakeIngredients = [&quot;Mozzarella&quot;, &quot;Tomato&quot;]
        service.getRecipe(containing: fakeIngredients) { _recipes, success, _error in
            // MARK: - Then
            // Here is where I should test the network call
            
            XCTAssertNil(_recipes)
            XCTAssertFalse(success)
            XCTAssertNotNil(_error)
            
        }
        wait(for: [expectation], timeout: 0.01)
    }
</code></pre>
<p>What technique should I use if this one is not recommended or the best ?</p>
<p><strong>PS :</strong> I don't want to use only Xcode expectations to wait for the response,I really want to use faking or mocking process.</p>
<p>Thank's in advance for your answers.</p>
",https://stackoverflow.com/questions/68058464/how-to-fake-alamofire-request-for-unit-testing,"['swift', 'unit-testing', 'networking', 'mocking', 'alamofire']",1105,False,1,0
Unit testing Command Line Tool target in Xcode,"<p>I’ve been struggling for hours trying to find a way to unit test my code. There’s no way to select the main target (<code>MazeGeneratorTests</code> is there b/c I already created it).</p>
<p><img src=""https://i.stack.imgur.com/IzYkIm.png"" alt=""Screenshot of test target creation dialog"" /></p>
<p>Here’s what the Project Navigator looks like (don’t mind the random structure):</p>
<p><img src=""https://i.stack.imgur.com/kRUptm.png"" alt=""Project Navigator"" /></p>
<p>After importing with <code>@testable import MazeGenerator</code>, calling anything from the module causes an <code>Undefined symbols for architecture x86_64</code> error, e.g.:</p>
<pre class=""lang-swift prettyprint-override""><code>func testPerformanceExample() throws {
    measure {
        let _ = generateNodes(rows: 20, cols: 20)
    }
}
</code></pre>
",https://stackoverflow.com/questions/66859919/unit-testing-command-line-tool-target-in-xcode,"['swift', 'xcode', 'xctest']",593,True,1,1
Unit Testing asserts before the function is complete,"<p>I have a unit test that should assert a value when it was flagged true at some point</p>
<pre><code>  it('should tick invalidLogin at error on login', () =&gt; {
    var checker;
    var targetObj = new Proxy(component, {
      set: (target, key, value) =&gt; {
        if (key == 'invalidLogin' &amp;&amp; value == true) {checker = true;}
        return true;
      }
    })
    targetObj.onSubmit(); // empty form should cause error
    expect(checker).toBeTruthy();
  });
</code></pre>
<p>but the problem is the assertion happens <strong>BEFORE</strong> the property gets flagged.
How can I make it so that the assertion is after?</p>
<p>here's the function that flags the property</p>
<pre><code>  onSubmit(){
    if (this.loginform.invalid) {
      return;
    }
    this.isSubmitted = true;
    
    const _id = this.f.username.value
    const _pass = this.f.password.value

    this.authService.login(_id, _pass)
      .pipe(first())
      .subscribe(
        data =&gt; {
          this.authService.checkAdmin().subscribe(data =&gt; {
            if(this.authService.IsCurrentUserAdmin) this.router.navigate(['admin'])
          });
        },
        error =&gt; {
          if(error['status']== 400) this.invalidLogin = true;
          console.log(error)
        },
        () =&gt; {
          this.isSubmitted = false;
          
        });
        return
    }
</code></pre>
<p><strong>UPDATE</strong>
I ditched this method, and instead mocked the onSubmit() method using a Spy, so i can just flag the property without going through the service.</p>
<pre><code>  it('should tick invalidLogin at error on login', () =&gt; {
    let button = fixture.debugElement.query(By.css('#form-login')).nativeElement;
    spyOn(component,'onSubmit').and.callFake(() =&gt; {
      component.invalidLogin = true;
    })
    button.click();
    fixture.detectChanges();
    let message = fixture.debugElement.query(By.css('#invalid-text')).nativeElement;
    expect(message).toBeTruthy;
  });
</code></pre>
",https://stackoverflow.com/questions/65605800/unit-testing-asserts-before-the-function-is-complete,"['angular', 'rxjs', 'jasmine', 'angular-test']",89,False,1,0
Issue Getting correct Full Path in Unit Testing,"<p>Having an issue in getting the correct path to a file during unit testing, the file exist in &quot;C:\Users\Name\source\repos\ProjectOne\ProjectOneTests\bin\Debug\netcoreapp3.1\Test\textFile.txt&quot;</p>
<pre><code> string fileName = &quot;textFile.txt&quot;;
 string directoryName = Path.GetFullPath(fileName);
</code></pre>
<p>directoryName =<strong>&quot;C:\Users\Name\source\repos\ProjectOne\ProjectOneTests\bin\Debug\netcoreapp3.1&quot;</strong></p>
<p>directoryName should be <strong>&quot;C:\Users\Name\source\repos\ProjectOne\ProjectOneTests\bin\Debug\netcoreapp3.1\Test&quot;</strong></p>
<p>If I write code</p>
<pre><code> string fileName = &quot;Test\\textFile.txt&quot;;
 string directoryName = Path.GetFullPath(fileName);
</code></pre>
<p>Then directoryName =<strong>&quot;C:\Users\Name\source\repos\ProjectOne\ProjectOneTests\bin\Debug\netcoreapp3.1\Test&quot;</strong></p>
<p>Why is Path.GetFullPath giving me the incorrect path when I only call file name <strong>&quot;textFile.txt&quot;</strong>
I can't seem to find any sources on stack or google to explain why and how I can get the correct path inside netcoreapp3.1 path, any advice, sources or help would be appreciated</p>
",https://stackoverflow.com/questions/68307692/issue-getting-correct-full-path-in-unit-testing,"['c#', 'asp.net', 'visual-studio', 'unit-testing', 'asp.net-core']",131,False,1,0
Unit Testing With/Without hardward in the loop,"<h1>Background</h1>
<p>I am working on a project that interfaces with various cameras and their unique APIs. All cameras are abstracted into one interface, and the camera-specific API calls are contained within their own implementing classes.</p>
<h1>Problem Explanation</h1>
<p>I am trying to test a factory method that parses a form of configuration, and returns a pointer to the newly created camera. Here is a high-level view of what that looks like:</p>
<pre class=""lang-cpp prettyprint-override""><code>// camerafactory.cpp 

Camera* make_camera(Config&amp; config) {
    switch (config.type) {
        case CameraTypes.A : {
            int paramInt = config.paramInt;
            return new CameraA(paramInt);
        }
        case CameraTypes.B : {
            string paramString = config.paramString;
            return new CameraB(paramString);
        }
        case CameraTypes.C : {
            float param1 = config.param1;
            float param2 = config.param2;
            return new CameraC(param1, param2);
        }
        default: {
            throw std::invalid_argument(&quot;Invalid configuration!&quot;);
        }

    }
}
</code></pre>
<p>I want to test that these constructors are getting called correctly, however this would require the cameras to be physically connected to the computer to allow for the camera API's within the camera constructors to work. This does make sense for some testing situations, i.e. demonstrating hardware in the loop, however in my specific case, it is unrealistic to have all types of cameras connected at a single time.</p>
<p>I would like to test that <em>these constructors are at least getting called with the correct parameters</em>, demonstrating that the parsing is working correctly. I have considered abstracting out the parsing and testing that separately, but technically there is still the constructor call that is not being tested. I was also always told that adding functionality for the sake of testing is usually something that should be avoided, so that is another thing I am considering with my solution. It would also be interesting to find a solution that allows easy compile-time switching between mocks/concrete implementations to test hardware in the loop.</p>
<h1>Versions</h1>
<p>Note, I am using C++ 17, CMake, and the latest version of gtest.</p>
<h1>Solutions being considered</h1>
<h2>Using macros to change the constructor calls to Mock constructor calls.</h2>
<p>At the top of <code>camerafactory.cpp</code>, adding something like:</p>
<pre class=""lang-cpp prettyprint-override""><code>// camerafactory.cpp

#ifndef PRODUCTION
#include &quot;MockCamera.hpp&quot;
#define CameraA MockCameraA
#define CameraB MockCameraB
#define CameraC MockCameraC
#endif
</code></pre>
<p>Where <code>MockCameraN</code> are defined in a separate hpp/cpp file with identical constructors, and also implement the same Camera Interface, which I can then use to test correct construction.</p>
<p>This would allow me to test that the constructors are getting called correctly, but does feel like it goes against a cleaner solution that could be done with a language like Java.</p>
<h2>Using GMock</h2>
<p>I have not looked too deeply into it yet, but GMock seems to be promising: <a href=""http://google.github.io/googletest/gmock_cook_book.html"" rel=""nofollow noreferrer"">http://google.github.io/googletest/gmock_cook_book.html</a></p>
",https://stackoverflow.com/questions/70513101/unit-testing-with-without-hardward-in-the-loop,"['c++', 'testing', 'factory', 'googletest', 'hardware-interface']",211,True,0,1
Unit testing: how to stub a wrapper function,"<p>I'm new to unit testing and trying to figure out how to stub a wrapper function. I'm using Sinon/Mocha.</p>
<p>If I have a function like:</p>
<pre><code>const user = await User.findOne({ email: email });
</code></pre>
<p>I've been able to stub it like so:</p>
<pre><code>const userFindOneStub = sandbox.stub(User, 'findOne')
  .returns({
    _id: 'userId1234',
    companies: [
    {
      _id: 'companyId1234'
    }
  ]
});
</code></pre>
<p>But I've had to create a wrapper for my function to reorder the params for a specific function, using Lodash:</p>
<pre><code>const userWrapper = _.rearg(UserFunction, [0, 1, 2, 3, 5, 4]);
const res = await userWrapper(someargs);
</code></pre>
<p>I can stub the <code>UserFunction</code> call, but how would I stub the <code>userWrapper</code> call in a unit test?</p>
",https://stackoverflow.com/questions/67394142/unit-testing-how-to-stub-a-wrapper-function,"['javascript', 'node.js', 'mocha.js', 'sinon']",504,True,0,1
unit testing for aem not covering a condition,"<p>im new to unit testing. I am using junit5 for an aem 6.5 application. Im trying to write unit test so that i can migrate to cloud which has a requirement of atleast 50% unit test, thus what im doing now. My code has an init method for the getTags(). My unit test works fine but the jacoco reports a line that is not being covered. Any help would be appreciated to pint me in the right direction.</p>
<p>I have this class:</p>
<pre><code>@Self
private SlingHttpServletRequest request;

@ValueMapValue
private List&lt;String&gt; tags;

@Override
public String getExportedType() {
    return RESOURCE_TYPE;
}

@PostConstruct
public void init() {
    Resource tagsNode = request.getResource().getChild(&quot;tags&quot;);
    tags = new ArrayList&lt;&gt;();
    if (tagsNode!=null) {
        for (Resource child : tagsNode.getChildren()) {
            TagModel tag = child.adaptTo(TagModel.class);
            tags.add(tag.getTag());
        }
    }
}

public List&lt;String&gt; getTags() {
    return this.tags;
}
</code></pre>
<p>And i have this unit test for aem</p>
<pre><code>@Test
void testGetTags() {
    List&lt;String&gt; expected = new ImmutableList.Builder&lt;String&gt;()
            .add(&quot;4&quot;)
            .add(&quot;22&quot;)
            .build();

    ctx.currentResource(&quot;/content/blog_placeholder&quot;);

    BlogPlaceholderModel blogPlaceholderModel = ctx.request().adaptTo(BlogPlaceholderModel.class);

    List&lt;String&gt; actual = blogPlaceholderModel.getTags();

    assertEquals(expected, actual);
}

@Test
void testGetExportedType() {
    final String expected = &quot;furniture-row/components/content/blog-placeholder&quot;;

    ctx.currentResource(&quot;/content/blog_placeholder&quot;);

    BlogPlaceholderModel blogPlaceholderModel = ctx.request().adaptTo(BlogPlaceholderModel.class);

    String actual = blogPlaceholderModel.getExportedType();

    assertEquals(expected, actual);
}
</code></pre>
<p>For some reason my test is not covering the if condition:</p>
<p><a href=""https://i.stack.imgur.com/Pktmm.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Pktmm.png"" alt=""enter image description here"" /></a></p>
<p>what am i missing ? thanks</p>
",https://stackoverflow.com/questions/68627442/unit-testing-for-aem-not-covering-a-condition,"['unit-testing', 'junit', 'aem', 'junit5']",204,True,0,1
Unit Testing File with Space in the Name,"<p>I have a Python project where the main file has spaces in the name. I understand that this is not encouraged, but in this case, I think it's necessary. The file is being compiled into a stand alone executable using py2app--which uses the file name for the application name when building the executable (app name, menu references, etc.). This works fine because the base file is not imported anywhere within the project and py2app handles the spaces gracefully. Let's call the file <code>Application Name.py</code>.</p>
<p>In order to run unit tests against <code>Application Name.py</code>, however, I have to eliminate the spaces in order to import the file into <code>unittest</code>. I'm unable to use <code>importlib</code> or <code>__import__</code> because the file is not constructed as a package, so both approaches fail. My workflow has been to refactor the file name to <code>application_name.py</code>, run the unit tests, and then refactor the name to <code>Application Name.py</code> before compiling it into <code>Application Name.app</code>.</p>
<p>So the options appear to be:</p>
<ol>
<li>Keep doing what I'm doing (workable, but not ideal),</li>
<li>Create a wrapper called <code>Application Name.py</code> that imports <code>application_name.py</code> where the wrapper doesn't need to be unit tested (seems silly),</li>
<li>Convert <code>Application Name</code> into a package so I can use <code>importlib</code> (seems like overkill), or</li>
<li>Something else entirely.</li>
</ol>
<p>Is there some way to gracefully handle file names with spaces in unit testing that I'm not seeing or should I just suck it up?</p>
",https://stackoverflow.com/questions/66379066/unit-testing-file-with-space-in-the-name,"['python-3.x', 'python-unittest', 'py2app']",216,True,0,1
Unit testing Symfony 5 Mailer: MessageLoggerListener not available,"<p>I want to test email delivery in Behat tests in Symfony 5. Apparently, there is a <code>MailerAssertionsTrait</code> in the PHPUnit package for Symfony which uses the <code>MessageLoggerListener</code> to check the sent emails. Following this tutorial <a href=""https://swag.industries/test-emails-with-symfony/"" rel=""nofollow noreferrer"">https://swag.industries/test-emails-with-symfony/</a>, I adapted that trait for my Behat context.</p>
<p>Unfortunately the service <code>mailer.message_logger_listener</code> does not seem to be available in the Symfony container. No matter if I set the <code>MAILER_DSN</code> to <code>null://null</code> or to an actually working transport.</p>
<p>I saw that this listener is being registered in the file <code>vendor/symfony/framework-bundle/Resources/config/mailer_debug.php</code>, which leads me to believe that I have to enable debug mode for the <code>symfony/mailer</code> package in some way. But I did not yet find out how exactly that is done.</p>
<p>How do I enable the <code>MessageLoggerListener</code> for the <code>symfony/mailer</code> package in my test environment?</p>
",https://stackoverflow.com/questions/69795742/unit-testing-symfony-5-mailer-messageloggerlistener-not-available,"['php', 'symfony', 'symfony-mailer']",413,False,0,0
"Problem with Unit Testing Exercise, module not found","<p>I am stuck on an exercise. These are the files I was given:</p>
<p><strong>A readme file:</strong></p>
<p>Before you begin, make sure to run this command in your terminal to install pytest:</p>
<pre><code>pip install -U pytest
</code></pre>
<p>Then, to run pytest, just enter:</p>
<pre><code>pytest
</code></pre>
<p>Right now, not all of the tests should pass. Fix the function to pass all its tests! Once all your tests pass, try writing some additional unit tests of your own!</p>
<p><strong>A &quot;compute-launch.py&quot; file:</strong></p>
<pre><code>def days_until_launch(current_day, launch_day):
    &quot;&quot;&quot;&quot;Returns the days left before launch.
    
    current_day (int) - current day in integer
    launch_day (int) - launch day in integer
    &quot;&quot;&quot;
    return launch_day - current_day
</code></pre>
<p><strong>A &quot;test-compute-launch.py&quot; file:</strong></p>
<pre><code>from compute_launch import days_until_launch

def test_days_until_launch_4():
    assert(days_until_launch(22, 26) == 4)

def test_days_until_launch_0():
    assert(days_until_launch(253, 253) == 0)

def test_days_until_launch_0_negative():
    assert(days_until_launch(83, 64) == 0)
    
def test_days_until_launch_1():
    assert(days_until_launch(9, 10) == 1)
</code></pre>
<p><strong>This is my problem:</strong>
ModuleNotFoundError: No module named 'compute_launch'</p>
<p>I have tried looking at other Stack Overflow threads which contain the same error &quot;no module named&quot; but I was not able to understand how this problem could be fixed. I have installed pytest. I need to be able to run the tests so I can see which tests are working and which are not. I don't need help with fixing or writing unit tests, I only need help with how to run the file to do the unit tests.</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/69219602/problem-with-unit-testing-exercise-module-not-found,"['python', 'pytest']",145,True,0,2
External link not working in Spring Unit Testing,"<p>In my code for token I used external link . External link open in browser but not working in unit testing code. Any suggestion.</p>
<p>My code</p>
<pre><code>           private String getHRCToken() throws Exception {
            
            String token=&quot;&quot;;
            
            
            MultiValueMap&lt;String, String&gt; variables = new LinkedMultiValueMap&lt;&gt;();
            variables.add(&quot;email&quot;, HRC_LOGIN_EMAIL);
            variables.add(&quot;password&quot;, HRC_LOGIN_PASSWORD);
            
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            HttpEntity&lt;MultiValueMap&lt;String, String&gt;&gt; requestEntity = new HttpEntity&lt;MultiValueMap&lt;String, String&gt;&gt;(variables ,
                    requestHeaders);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity&lt;String&gt; response = restTemplate.exchange(BASE_URL, HttpMethod.POST,
                    requestEntity, String.class);
            System.out.println(response.getStatusCode());
        }

        @Test
            public void updateData() throws Exception {
                String URI = &quot;/reviewData/leads/update&quot;;
                String token = getHRCToken();
                MvcResult result = mockMvc.perform(MockMvcRequestBuilders.put(URI)
                        .accept(MediaType.APPLICATION_JSON_VALUE)
                        .header(&quot;Authorization&quot;, token).param(&quot;status&quot;, &quot;New&quot;)
                        .param(&quot;lead_id&quot;, &quot;1&quot;)
                        ).andReturn();
                //Checking if our service has issues
                assertEquals(200, result.getResponse().getStatus());
                String response = result.getResponse().getContentAsString();
                int i = response.indexOf(&quot;{&quot;);
                response = response.substring(i);
                JSONObject json = new JSONObject(response.trim());
                JSONObject responseObject = json;
                String message = responseObject.getString(&quot;message&quot;);
                //Checking if process as exepected
                assertTrue(message.equalsIgnoreCase(&quot;success&quot;));
            }
</code></pre>
<p>Error</p>
<p>org.springframework.web.client.HttpClientErrorException: 415 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:85)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:708)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:661)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:621)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:539)</p>
",https://stackoverflow.com/questions/68110275/external-link-not-working-in-spring-unit-testing,"['java', 'spring-boot', 'spring-mvc']",49,False,-1,1
GraphQL API unit testing for user sign in,"<p>I need to write a unit test for a user signing in for an app that uses Ruby on Rails and GraphQL API. On Altair, when performing the signIn mutation, I need to set the server URL as an environment variable, then send a POST request for the mutation to work. I'm trying to do the same thing, just in a unit test file. This is my mutation file:</p>
<pre><code>module Mutations
  class SignInUser &lt; BaseMutation
    argument :auth, Types::AuthProviderEmailInput, required: false

    field :token, String, null: true
    field :user, Types::UserType, null: true

    def resolve(auth: nil)
      # basic validation
      return unless auth

      user = User.where('uuid=? OR email=?', auth[:user_id], auth[:user_id]).first()

      # ensures we have the correct user
      return unless user &amp;&amp; user.is_active
      return unless user.authenticate(auth[:password])

      user.update_attributes(invitation_status: true) if !user.invitation_status

      { user: user, token: AuthToken.token(user) }
    end
  end
end
</code></pre>
<p>This is my test file:</p>
<pre><code>require 'test_helper'

class Mutations::SignInUserTest &lt; ActionDispatch::IntegrationTest
    def perform(args = {})
        Mutations::SignInUser.new(object: nil, field: nil, context: {}).resolve(args)
    end

    test 'sign in user' do
        post &quot;serverurl.com&quot;

        user = perform(
            auth: {
                user_id: &quot;example&quot;,
                password: &quot;example&quot;
            }
        )

        assert user.persisted?
    end
end
</code></pre>
<p>The POST request seems to work since it doesn't return any errors, but <code>user</code> returns null. I think it's because my POST request and when I actually sign in the user are separate, so the mutation doesn't work. I tried sending a POST request only and <code>puts response.body</code> like so:</p>
<pre><code>post &quot;serverurl.com&quot;
puts response.body
</code></pre>
<p>which gives me a message saying <code>{&quot;errors&quot;:[{&quot;message&quot;:&quot;No query string was present&quot;}]}</code>. This makes me think I have to send the mutation along with the POST request in its parameters or something so I've tried using:</p>
<pre><code>post &quot;serverurl.com&quot;, params: { signInUser: { input: { auth: user_id: &quot;example&quot;, password: &quot;example&quot; } } }
</code></pre>
<p>but that just gives me a bunch of syntax errors for the <code>} } }</code> at the end, which I don't know why.
I'm not sure what else to try here, so some help would be very appreciated.</p>
",https://stackoverflow.com/questions/67974169/graphql-api-unit-testing-for-user-sign-in,"['ruby-on-rails', 'graphql']",406,False,0,1
Angular unit testing component ngIf element is null,"<p>I've a component with a few *ngIf statements throughout, most of them like the following</p>
<pre><code>&lt;ul *ngFor=&quot;let item of items&quot;&gt;
&lt;li&gt; 
    &lt;ng-container *ngIf=&quot;itemCount &amp;&amp; item.GroupId == 4&quot;&gt;
        &lt;span class=&quot;bridge&quot;&gt;{{itemCount}}&lt;/span&gt;
    &lt;/ng-container&gt;
&lt;/li&gt;
... and so on
</code></pre>
<p>in my spec file I've a test that is trying to check on the scenario whereby the itemCount is not null /empty and the groupId = 4...then checking that the span contains the correct item count.</p>
<p>I've spent hours on variations of this but no matter what I try the attempt to get access to the span results in null and the test fails.</p>
<p>So here's an example of one of the tests</p>
<pre><code>if('should show the correct item count', () =&gt;{
    let component = fixture.componentInstance;
    component.itemCount = 4;
    fixture.detectChanges();

    let bridge = fixture.debugElement.query(By.css('.bridge'));
    expect(bridge).tobeTruthy();
});


</code></pre>
<p>As I say above, through many multiples of attempts this is ALWAYS null, no matter what. I've debugged the test and have confirmed that the correct groupId is being used have also confirmed the itemCount is not null or empty so both conditions of the *ngIf should be fulfilled -but the span doesn't exist so I have to presume there's something amiss.</p>
<p>Please excuse typos, I'm copying the code manually but it does run currently, just doesn't succeed.</p>
<p>Any pointers?</p>
<p><strong>Update</strong>:</p>
<p>Here's more info, the beforeEach where the component is populated with dummy data.</p>
<pre><code>const ItemServiceStub = jasmine.createSpyObj('ItemService', ['getItems']);

beforeEach(() =&gt;{
    TestBed.configureTestingModule({
        declarations: [ItemComponent],
        providers: [{provide: ItemService, useValue: ItemServiceStub}]
    }).compileComponents();
});

beforeEach(() =&gt; {
    itemService = Testbed.inject(ItemService);

    spyOn(itemService, 'getItems').and.callFake(() =&gt; of(fakeItems));

    fixture = TestBed.createComponent(ItemComponent);
    fixture.autoDetectChanges();
});

</code></pre>
<p><strong>Update 2</strong>
Here's the fake data being set</p>
<pre><code>describe('item tests', () =&gt; {

let fakeItems: Item[];

fakeItems = [
   {GroupId: '2', ItemName: 'test', isExternal: false},
   {GroupId: '3', ItemName: 'testing', isExternal: false},
   {GroupId: '4', ItemName: 'test item', isExternal: false}
];

});


</code></pre>
",https://stackoverflow.com/questions/67078582/angular-unit-testing-component-ngif-element-is-null,"['angular', 'unit-testing', 'jasmine']",3067,True,0,1
Some issue with Unit Testing on CI Gitlab,"<p>Goodday,</p>
<p>I have an issue with running my code through CI. When I run my code locally the test is fine.</p>
<p>So I have a Role Model (no pun intended)</p>
<p>and in my test i assign the role to a newly created test user.</p>
<pre class=""lang-php prettyprint-override""><code> // Assigning Role
        $role = Role::where('name','administrator')-&gt;first();
        $user-&gt;assignRole($role);
</code></pre>
<p>The assign Role is added through my User Model</p>
<pre class=""lang-php prettyprint-override""><code>/**
     * Assigns Role to the User
     *
     * @param Role $role
     */
    public function assignRole(Role $role)
    {
        $this-&gt;roles()-&gt;save($role);
    }
</code></pre>
<p>When I run the Test locally it works like it was intended.</p>
<pre>
   PASS  Tests\Feature\UserTest
  ✓ user login
  ✓ users list allowed
  ✓ users list not allowed
  ✓ user creation
  ✓ user delete

  Tests:  6 passed
  Time:   7.05s
</pre>
<p>But when i am running it in my CI env. I get the following error message:</p>
<pre><code> ✓ basic test
   FAIL  Tests\Feature\UserTest
  ✓ user login
  ✓ users list allowed
  ✓ users list not allowed
  ⨯ user creation
  ✓ user delete
  ---
  • Tests\Feature\UserTest &gt; user creation
   TypeError 
  Argument 1 passed to App\Models\User::assignRole() must be an instance of App\Models\Role, null given, called in /builds/marcel43/backendapi/tests/Feature/UserTest.php on line 86
  at app/Models/User.php:73
     69▕      * Assigns Role to the User
     70▕      *
     71▕      * @param Role $role
     72▕      */
  ➜  73▕     public function assignRole(Role $role)
     74▕     {
     75▕         $this-&gt;roles()-&gt;save($role);
     76▕     }
     77▕
  1   tests/Feature/UserTest.php:86
      App\Models\User::assignRole()
  Tests:  1 failed, 5 passed
  Time:   0.97s
</code></pre>
<p>What am i missing here?</p>
",https://stackoverflow.com/questions/67416059/some-issue-with-unit-testing-on-ci-gitlab,"['unit-testing', 'continuous-integration', 'laravel-8']",22,True,0,1
Separate ServiceProviders for Unit Testing and Production Code,"<p>I am using ServiceLoader to dynamically load Plugins.
In purpose of unit testing I want to Mock some behavior of these Plugins.
These Mock-Plugins should be used when unit testing, but not when building the Project.
How would one do this though?</p>
<p>I feel like this question is IDE / build tool specific, for that matter I am using Eclipse.</p>
<p>Project Structure:</p>
<ul>
<li>src
<ul>
<li>app
<ul>
<li>app.java</li>
</ul>
</li>
<li>scraper
<ul>
<li>ScraperController.java</li>
<li>Scraper.java</li>
</ul>
</li>
</ul>
</li>
<li>Scrapers</li>
<li>tests
<ul>
<li>mockups
<ul>
<li>FailingScraperMock.jar</li>
<li>...</li>
</ul>
</li>
<li>unit_tests
<ul>
<li>ServiceLoaderWithProvidedMockScrapersTest.java</li>
<li>...</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>scraper.Scraper.java is the provider interface</p>
<p>Scrapers is where all the Scraper-Providers go</p>
<p>I tried to exclude the Mock-Plugins for the source folder: src/ .
Either I am doing it wrong or that's not intended for what I am trying to do.</p>
<p>Would appreciate any kind of help / information.</p>
",https://stackoverflow.com/questions/66507659/separate-serviceproviders-for-unit-testing-and-production-code,"['java', 'eclipse', 'unit-testing', 'plugins', 'serviceloader']",58,False,0,1
unit testing for component containing dynamically loaded component,"<p>I have a component and I have dynamically loaded other component inside this component.
I am struggling to write unit test cases for angular component.
Unable to find reading material on this topic.</p>
<p>In my component I have :</p>
<pre><code>const factory = this.componentFactoryResolver.resolveComponentFactory(component);
</code></pre>
<p>In the spec file I am getting this error,</p>
<pre><code>{
    &quot;message&quot;: &quot;An error was thrown in afterAll\nUncaught Error: No component factory found for TestComponent. Did you add it to @NgModule.entryComponents? thrown&quot;,
    &quot;str&quot;: &quot;An error was thrown in afterAll\nUncaught Error: No component factory found for TestComponent. Did you add it to @NgModule.entryComponents? thrown&quot;
}
</code></pre>
",https://stackoverflow.com/questions/68040750/unit-testing-for-component-containing-dynamically-loaded-component,"['angular', 'jasmine', 'karma-runner']",152,False,0,0
Wrapper for cloud NDB context when unit testing?,"<p>I'm migrating a Python 2 GAE app to Python 3, and I'm in the process of replacing ndb with cloud-ndb. This involves changing lines like</p>
<pre><code>do_something_with_ndb()
</code></pre>
<p>to</p>
<pre><code>with client.context() as context:
    do_something_with_ndb()
</code></pre>
<p>For Flask apps, you can use WSGI middleware (see <a href=""https://cloud.google.com/appengine/docs/standard/python3/migrating-to-cloud-ndb"" rel=""nofollow noreferrer"">here</a>) to handle this automatically, which is pretty awesome.</p>
<p>Is it possible to do something similar for unit tests?  It is tedious to add the context throughout my test code.</p>
<p>Looking for solutions for both <code>nose</code> and <code>pytest</code> since I have both.</p>
",https://stackoverflow.com/questions/65570850/wrapper-for-cloud-ndb-context-when-unit-testing,"['python', 'unit-testing', 'google-app-engine', 'app-engine-ndb', 'google-app-engine-python']",175,True,0,1
c++ unit testing with dependency and file writing,"<p>I am a student and new for unit testing. I'm confused with testing problems when writing my project.</p>
<p>I have three functions <code>A()</code>, <code>B(string file)</code> and <code>C()</code>. <code>A()</code> is used for initialization and it creates a directory <code>temp</code> to store files. <code>B(string file)</code> writes file in <code>temp</code>. <code>C()</code> transfer the current files in <code>temp</code> to another place and mark these files. They are usually called in the following order:</p>
<pre><code>         | - - - - - - - - - - - - -
        \ /                        |
A - - -&gt; B (multiple times) - - -&gt; C
</code></pre>
<p>(the three functions are kind of like the commands <code>init</code>, <code>add</code> and <code>commit</code> in the version control system <em>git</em>)</p>
<p>Here is the thing:</p>
<ol>
<li>I've written the test and implementation of <code>A()</code>. In <code>testB()</code> I need the initialization, so I call <code>A()</code>. Though it is tested, it seems that it's a bad choice. What should I do? Should I just create the directory <code>temp</code> on my own in <code>testB()</code>?</li>
<li>If a file has been marked by <code>C()</code>, <code>B(string file)</code> should do nothing if  then we forward the file to <code>B(string file)</code>. How can I test this situation?</li>
</ol>
<p>I'll aappreciate it if you can give detailed instructions.</p>
",https://stackoverflow.com/questions/66407215/c-unit-testing-with-dependency-and-file-writing,"['c++', 'unit-testing']",369,True,0,1
Unit testing function ehich return observable of observables,"<p>I've got a problem with unit testing function like this:</p>
<pre><code>loadData({prop1, prop2, prop3}: Props): Observable&lt;unknown&gt; {
    return this.dataService.clearData().pipe(
         concanMap(() =&gt; this.personalDataService.getData(prop1)),
         concanMap(() =&gt; this.extendedDataService.getData(prop2)),
         concanMap(() =&gt; this.weatherDataService.getData(prop3))
    );
}
</code></pre>
<p>I want to do this based on spyOn's. Something like this:</p>
<pre><code>it('should correctly load data', () =&gt; {
    spyOn(dataService, 'clearData');
    spyOn(personalDataService, 'getData');
    spyOn(extendedDataService, 'getData');
    spyOn(weatherDataService, 'getData');

    spectator.service.loadData({
          prop1: '',
          prop2: '',
          prop3: ''
    })

    expect(dataService.clearData).toHaveBeenCalled();
    expect(personalDataService.getData).toHaveBeenCalled();
    expect(extendedDataService.getData).toHaveBeenCalled();
    expect(weatherDataService.getData).toHaveBeenCalled();
});
</code></pre>
<p>I've got an error:</p>
<blockquote>
<p>TypeError: Cannot read properties of undefined (reading 'pipe')</p>
</blockquote>
<p>It's quite obvious because dataService.clearData is a mock, so I need to return some value from this method:</p>
<pre><code>spyOn(dataService, 'clearData').and.returnValue(of());
</code></pre>
<p>This solution is bad because the other services calls can't be triggerred.</p>
<p>Do you have any idea how to test this function?</p>
",https://stackoverflow.com/questions/70470757/unit-testing-function-ehich-return-observable-of-observables,"['angular', 'unit-testing', 'jestjs', 'angular-spectator']",98,False,-1,1
Angular Observable error part unit testing using jasmine,"<p>I have the below function in my angular service &quot;config.service.ts&quot;. I have written some unit test cases for the same and I'm unable to cover the error part of the subscribe method.</p>
<pre><code>getConfiguration(params){
  return new Promise((resolve, reject) =&gt; {
    try {
      this.httpService.post('getConfig', params).subscribe{
        data =&gt; {
         resolve(data);
        },
        error =&gt; {
         reject(error);
        }
      };
    } catch(error) {
     reject(error);
    }
  });
}
</code></pre>
<p>Below is the 'config.service.spec.ts' code. Please let me know how to cover the subscribe error part for the same.</p>
<pre><code>it('coverage for getConfiguration()', () =&gt; {
 const service: ConfigService = Testbed.get(ConfigService);
 const param = {id: 10};
 const response = {success: true};
 const httpService: HttpService = Testbed.get(HttpService);
 spyOn(httpService, 'post').and.returnValue(of(response));
 service.getConfiguration(param).then(function() {});
 expect(service.getConfiguration).toBeTruthy();
});
</code></pre>
<p>Here the observable error part is not covering and unable to reach the coverage. Kindly correct me if anything wrong here.</p>
",https://stackoverflow.com/questions/68577041/angular-observable-error-part-unit-testing-using-jasmine,"['angular', 'observable', 'karma-jasmine', 'subscribe']",4765,True,0,1
Unit testing DB:: call with PhpUnit in Laravel,"<p>I am new to TDD. I am writing a little package that interpolate a string with values from the database. So far, I managed to write most of the test but I am getting stuck now that I need to test calls to the Database.
I want to test a class that retrieves a particular row in the database given a table, column and id. It should then return that instance column value.</p>
<pre class=""lang-php prettyprint-override""><code>class DatabaseResolver
{
    private $referredField;
    private $dependencies;

    public function __construct(ReferredField $referredField, array $dependencies)
    {
        $this-&gt;referredField = $referredField;
        $this-&gt;dependencies = $dependencies;
    }

    public function resolve() : string
    {
        if(!isset($this-&gt;dependencies['id'])) {
            throw new MissingDependencyException('id');
        }

        $instance = $this-&gt;getTargetedInstance();
        if ($instance) {
            return $instance-&gt;{$this-&gt;referredField-&gt;column};
        }
        return '';
    }

    public function getTargetedInstance()
    {
        return DB::table($this-&gt;referredField-&gt;table)
            -&gt;select($this-&gt;referredField-&gt;column)
            -&gt;where('id', $this-&gt;dependencies['id'])
            -&gt;first();
    }
}
</code></pre>
<p>I have managed to test that it throws my exception when there is no id in the dependency array and that it returns the original sentence when a token is not found:</p>
<pre class=""lang-php prettyprint-override""><code>    /** @test */
    public function it_will_throw_if_no_id_is_present_in_dependency()
    {
        $this-&gt;expectException(MissingDependencyException::class);

        $rf = ReferredField::newFactory()-&gt;testAsTable()-&gt;create();
        $rf-&gt;getReferredValue([]);
    }

    /** @test */
    public function it_returns_blanked_tokens_when_referred_field_is_not_found()
    {
        $stringToInterpolate = 'This is a {{adj}} day!';
        $interpolatedString = $this-&gt;interpoler-&gt;interpolate($stringToInterpolate, ['adj' =&gt; ['id' =&gt; -1]]);

        $this-&gt;assertEquals('This is a  day!', $interpolatedString);
    }
</code></pre>
<p><strong>EDIT</strong>:
Here is the code of the Interpoler class:</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php

namespace Armcanada\LaravelReferredField\Concerns;

use Armcanada\LaravelReferredField\Exceptions\MissingDependencyException;

class Interpoler
{
    private $tokenizer;
    private $mapper;

    public function __construct(Tokenizer $tokenizer = null, TokenReferredFieldMapper $mapper = null)
    {
        $this-&gt;tokenizer = $tokenizer ?: new Tokenizer;
        $this-&gt;mapper = $mapper ?: new TokenReferredFieldMapper;
    }

    public function interpolate(string $text, array $dependencies = []) : string
    {
        $map = $this-&gt;getReferredFieldsFromText($text);
        $replacedMap = $map-&gt;mapWithKeys(function($referredField, $token) use($dependencies) {
            if (!isset($dependencies[$token])) {
                throw new MissingDependencyException($token);
            }
            $key = str_replace(' ', $token, config('laravel-referred-field.interpolation_pattern'));
            return [$key =&gt; $referredField?-&gt;getReferredValue($dependencies[$token]) ?? null];
        });
        
        $replacedMap-&gt;map(function($newValue, $token) use(&amp;$text) {
            $text = str_replace($token, $newValue, $text);
        });
        return $text;
    }

    public function getReferredFieldsFromText($text)
    {
        $tokens = $this-&gt;tokenizer-&gt;extract($text);
        return $this-&gt;mapper-&gt;mapTokensToReferredFields($tokens);
    }

}
</code></pre>
<p>And my ReferredField model:</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php

namespace Armcanada\LaravelReferredField\Models;

use Armcanada\LaravelReferredField\Database\Factories\ReferredFieldFactory;
use Armcanada\LaravelReferredField\Resolvers\DatabaseResolver;
use Armcanada\LaravelReferredField\Traits\Referrable;
use Illuminate\Database\Eloquent\Model;

class ReferredField extends Model
{
    use Referrable;

    protected $guarded = [];
    protected $table = 'referred_fields';

    protected static function newFactory()
    {
        return ReferredFieldFactory::new();
    }

    public function getReferredValue(array $dependencies) : string
    {
        $resolver = $this-&gt;getResolver($dependencies);

        return $resolver-&gt;resolve();
    }

    private function getResolver($dependencies)
    {
        if ($this-&gt;table !== null) {
            return new DatabaseResolver($this, $dependencies);
        }
        //return new HandlerResolver($this, $dependencies);
    }

}
</code></pre>
<p>How can I test this path?</p>
<pre class=""lang-php prettyprint-override""><code>$instance = $this-&gt;getTargetedInstance();
if ($instance) {
    return $instance-&gt;{$this-&gt;referredField-&gt;field};
}
</code></pre>
",https://stackoverflow.com/questions/67837644/unit-testing-db-call-with-phpunit-in-laravel,"['php', 'laravel', 'unit-testing', 'phpunit']",263,True,0,1
Unit testing lambda functions together with generic classes,"<p>I have a question regarding the use of lambdas in factories, together with generic/templated classes. It seems like it is possible to get carried away with lambdas and generic classes, to have too much untested logic in lambda functions. Example:</p>
<p>In a Factory:</p>
<pre><code>createGenericClass(ARG1 arg1, ARG2 arg2)
{ 
    auto lambda = [](std::vector&lt;DataSP&gt;&amp; inputVector) {
          DataSP spData(new Data);
          if (inputVector.empty())
          {
             return spData;
          }
    
          spData-&gt;clear();
    
          for (const DataSP&amp; spCurrentData : inputVector)
          {
             if (spCurrentData &amp;&amp; spCurrentData-&gt;getNumberOfSubData() != 0)
             {
                for (auto subDataIdx = 0;
                     subDataIdx &lt; spCurrentData-&gt;getSize();
                     ++subDataIdx)
                {
                   ...// Some manipulation here
                }
             }
          }
          return spData;
       };
       
      using GenericClassT = Nmcp::GenericClass&lt;ARG1, ARG2, SomePolicy&gt;;

   return std::make_unique&lt;GenericClassT&gt;(
      arg1, arg2, lambda);
}
</code></pre>
<p>The code above is used in a factory. This factory, uses the lambda to create a GenericClass, which will be connected to other classes(for data flow).</p>
<p>Since GenericClass is generic/templated, it makes it hard to test the logic in the lambda. There is a google test for GenericClass, but of course it uses different lambdas everytime it is used. What would you recommend to use/change in such a case? Rewrite a lambda to be a class and test it? Or not use a generic/templated class? Or is this just a bad design altogether?</p>
<p>If you feel that this question does not belong at SO, I'll remove it.</p>
",https://stackoverflow.com/questions/70276256/unit-testing-lambda-functions-together-with-generic-classes,"['c++', 'unit-testing', 'lambda']",130,False,0,0
How to create mock object for unit testing,"<p>How to Write Test Cases: I'm write test cases in beginner please help.</p>
<p>Angular class of function.</p>
<pre><code>picklistScroll() {
          const picklistWrapper = document.getElementsByClassName('picklist-values-wrapper')[0];

           jQuery(picklistWrapper).animate({
              scrollTop: picklistWrapper.scrollHeight
          }, 'slow'); 
}
</code></pre>
<p>Below is the spec.ts file −</p>
<pre><code>  describe('picklistScroll', () =&gt; {
    it('makes expected calls', () =&gt; {

    // scroll height problem coming
    var dummyElement = document.createElement('div');
    dummyElement.className = &quot;picklist-values-wrapper&quot;;
    dummyElement.style.height = '200px';
    dummyElement.style.overflowY = 'auto';

    document.getElementsByClassName = jasmine.createSpy('picklist-values-wrapper').and.returnValue(dummyElement);

    });
  });
</code></pre>
<p>fails with following message:</p>
<blockquote>
<p>TypeError: Cannot read properties of undefined (reading
'scrollHeight')</p>
</blockquote>
<p>Looks like I need to create mock object for innerHTML. How I can do this?</p>
",https://stackoverflow.com/questions/70285404/how-to-create-mock-object-for-unit-testing,"['jquery', 'angular', 'unit-testing', 'karma-jasmine']",313,False,0,1
Mocking API Call in Unit Testing Python 3,"<p>I have been given the task to write unit-tests for a function which eventually makes a requests.post API call. I have been asked to use mocking in Python. I am fairly new to it and have been reading lot of articles related to it. I have also written the unit test following the document. But, I do have a few questions which none of the documents I have come across answered-</p>
<ol>
<li><p>In unit test function too, I am making a call to the original function which is making the API call. And for now, I am mocking the response using mock.return_value. <em>So, eventually does this make an API call too from the unit-test function??</em>  If it does, then it fails my use-case where I am not supposed to make API calls regularly to third party server.</p>
</li>
<li><p>If it not making an API call, what exactly is it validating? I myself have fed the response and let's say status code of the API call. <em>So, without making the API call, how can these two be validated?</em></p>
</li>
</ol>
<pre><code>@patch('post.requests.get')
def test_api_function(self, mock_incident):
    mock_incident.return_value.json.return_value = [{'mock':'json'}]
    mock_incident.return_value.status_code = 200
    response = api_fucntion()

    assert response.status_code == 200
</code></pre>
<p>If you see, I am still making that call to the function(api_response). How does this serve my purpose of unit testing with mocking?? And, how does it verify 200 response without making an actual API call if it doesn't make one ??</p>
",https://stackoverflow.com/questions/65669782/mocking-api-call-in-unit-testing-python-3,"['python-3.x', 'api', 'unit-testing']",528,True,0,1
Mocking `peer` while unit testing gRPC with bufconn,"<p>I have unidirectional (both client- and server-) streaming gRPC methods implemented in my golang server. I came across <a href=""https://pkg.go.dev/google.golang.org/grpc@v1.37.0/test/bufconn"" rel=""nofollow noreferrer""><code>bufconn</code></a> which enables me to creates my server via in-memory connections in my tests. However, I have logic in my method where I check the peer's address, it always returns &quot;bufconn&quot;. I do rely on the peer to provide the IP address along with its port, but I can't really achieve that using bufconn.</p>
<ol>
<li>What is a canonical (or preferred) way to test gRPC streaming calls in golang?</li>
<li>Is it considered an anti-pattern to rely on peer information in the context?</li>
</ol>
",https://stackoverflow.com/questions/67955694/mocking-peer-while-unit-testing-grpc-with-bufconn,"['unit-testing', 'go', 'grpc-go', 'go-testing']",651,False,0,0
Unit Testing Azure Functions that user property binding,"<p>I've created some functions and have used this post <a href=""https://www.rickvandenbosch.net/blog/azure-functions-binding-to-a-property/"" rel=""nofollow noreferrer"">https://www.rickvandenbosch.net/blog/azure-functions-binding-to-a-property/</a> to create them using custom properties</p>
<p>I set up the test project and files using the docs here <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></p>
<p>My question is, how can functions that use property binding be unit tested? as all the examples I've looked at online use the test factory class to pass in a type of httpRequest.</p>
<pre><code> public static async Task&lt;IActionResult&gt; Run(
        [HttpTrigger(AuthorizationLevel.Function, &quot;post&quot;, Route = null)] GetStudyDetailsRequest req,
        ILogger log)
    {
        try
        {
            var client = new ArtenaServiceClient(ArtenaServiceClient.EndpointConfiguration.BasicHttpBinding_IArtenaService);
            var result = await client.GetStudyDetailsAsync(req.StudentID, req.Dev);
            return CreateActionResult.Create(result);
        }
        catch (Exception e)
        {
            log.LogError(e, &quot;&quot;, req);
            return new OkObjectResult(new { e.Message, e.StackTrace });
        }
    }
</code></pre>
",https://stackoverflow.com/questions/65620847/unit-testing-azure-functions-that-user-property-binding,"['c#', 'unit-testing', 'azure-functions']",308,False,0,1
Unit Testing functional components with Jest and Enzyme,"
<p>I have written test case for the post.js to find 3 p tag but it's throwing an error. How do I properly test this component?</p>
<p>Post.js</p>
<pre class=""lang-js prettyprint-override""><code>import React from 'react';
import './Post.css';

const Post = (props) =&gt; {

    const displayPosts = (props) =&gt; {

    const { posts } = props;

    if ( posts.length &gt; 0 ){

        return(

            posts.map( (post) =&gt; {

                return(

                    &lt;div className = &quot;Post&quot;&gt;

                        &lt;p className = &quot;name&quot;&gt; &lt;b&gt;Name :&lt;/b&gt; {post.name}&lt;/p&gt;

                        &lt;p className = &quot;email&quot;&gt; &lt;b&gt; Email :&lt;/b&gt; {post.email}&lt;/p&gt;

                        &lt;p className = &quot;body&quot;&gt; &lt;b&gt; Body :&lt;/b&gt; {post.body}&lt;/p&gt;

                    &lt;/div&gt;
                )
            })
        )
    }

    }
    return (
        &lt;div className = &quot;Posts&quot;&gt;
            { displayPosts(props) } 
        &lt;/div&gt;
    )
}

export default Post;
</code></pre>
<p>Post.test.js</p>
<pre class=""lang-js prettyprint-override""><code>import React from &quot;react&quot;;
import Adapter from &quot;enzyme-adapter-react-16&quot;;
import { shallow, configure } from &quot;enzyme&quot;;
import Post from &quot;./Post&quot;;

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

describe(&quot;Post&quot;, () =&gt; {
    it(&quot;includes three paragraphs&quot;, () =&gt; {
        const wrapper = shallow(&lt;Post /&gt;);
        expect(wrapper.find(&quot;p&quot;)).toHaveLength(3);
      });
});
</code></pre>
",https://stackoverflow.com/questions/66838188/unit-testing-functional-components-with-jest-and-enzyme,"['reactjs', 'unit-testing', 'jestjs', 'react-hooks', 'enzyme']",83,False,0,1
Mock a controller error in c# unit testing,"<p>I am trying to create different types of errors in an ASP.NET controller (which communicates with a service). Right now I am focusing on a ServiceNotFound error, but <code>DbContextMock()</code> always returns true. What is the correct way to do this?</p>
<p>(In OrdersController.cs)</p>
<pre><code>    public OrdersController(IOrdersService ordersService)
    {
        _ordersService = ordersService ?? throw new ArgumentNullException(nameof(ordersService));
    }

    [HttpPut]
    [ProducesResponseType((int)HttpStatusCode.NoContent)]
    [ProducesResponseType((int)HttpStatusCode.InternalServerError)]
    public async Task&lt;IActionResult&gt; PutOrdersAsync()
    {
        try
        {
            await _ordersService.PutOrdersAsync();

            return new StatusCodeResult(StatusCodes.Status204NoContent);
        }
        catch (ServiceException ex)
        {
            return StatusCode(
                (int)ex.StatusCode,
                Responses.ErrorResponse with { Message = ex.Message, Content = JsonConvert.SerializeObject(ex), RequestId = Request.HttpContext.Connection.Id }
            );
        }
        catch (Exception ex)
        {
            return StatusCode(
                StatusCodes.Status500InternalServerError,
                Responses.ErrorResponse with { Message = ex.Message, Content = JsonConvert.SerializeObject(ex), RequestId = Request.HttpContext.Connection.Id }
            );
        }
    }
</code></pre>
<p>(In Tests.cs)</p>
<pre><code>        ...
        var context = new DbContextMock();
        ...
        var service = GetOrdersService(context.Object, _pdcClientFactory.Object);
        ...
        await service.PutOrdersAsync();
</code></pre>
",https://stackoverflow.com/questions/69690242/mock-a-controller-error-in-c-unit-testing,"['c#', 'unit-testing']",107,False,0,0
Unit testing using Mockito 3.x fails randomly,"<p>Here is the relevant code in my test:</p>
<pre><code>private MockedStatic&lt;MyDAO&gt; myDAOStaticMock;

@Captor
ArgumentCaptor&lt;SomeInput&gt; someInputCaptor;

@Before
public void before() {
  myDAOStaticMock = Mockito.mockStatic(MyDAO.class);
}

@After
public void after() {
  myDAOStaticMock.close();
}

@Test
public void test() {
  thingImTesting.methodThatCallsDaoStatically();

  myDAOStaticMock.verify(() -&gt; MyDao.staticMethod(someInputCaptor.capture()), times(2));
}
</code></pre>
<p>When I run this test in intellij, it almost always works. When it runs through our build system, it fails every time. The error is that there is 0 interaction with this mock.</p>
<p>What might be the problem with this particular verify, when all of the rest of my static checks work fine?</p>
<p>Edit: I was wrong about the reason for the issue and the static checks were not related. See my answer for more information.</p>
",https://stackoverflow.com/questions/67691112/unit-testing-using-mockito-3-x-fails-randomly,"['java', 'mockito']",208,False,0,1
(unit testing) How to keep Scanner running (Java),"<p><em>Edit:</em> <em>It was a mistake on my part, changed the testing input by mistake. It runs like a charm now :) Thanks for your help guys! You can close the question if you want.</em></p>
<p><strong>Original:</strong> I have an assignment that should read user input (test files) and return some data (output). Everything is running fine and I pass 2 of my tests, but due to some sily mistake on my end the stream gets closed (after passing the tests).</p>
<p>Main handles the user input and has Scanner declared and running, it calls the methods from the class I created (I cannot change Main due to assignment restriction).</p>
<p>This is the code I've written on my class:</p>
<pre><code>public class MyInstance extends Intersection {

private boolean methodHasRun = false;
//  keeps count of getIntersectionState() loop
    private static int loop_count;

public String getIntersectionState(){

        String left = &quot;LVg0&quot;;
        String right = &quot;RVg0&quot;;
        String bottom = &quot;BVr0&quot;;
        String top = &quot;TVr0&quot;;
        String temp = &quot; &quot;;
        String temp1 = &quot; &quot;;
        String temp2 = &quot; &quot;;
        String temp3 = &quot; &quot;;
        String nr [] = {&quot;1&quot;,&quot;2&quot;,&quot;3&quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&quot;7&quot;,&quot;8&quot;,&quot;9&quot;,&quot;10&quot;};

//      if advanceTime() was executed
        if (this.methodHasRun) {
            
            //get last char, write it to temp
            temp = bottom.substring(bottom.length()-1).trim();  
            temp1 = top.substring(top.length()-1).trim();
            while(loop_count &lt; nr.length-1) { 
                temp = &quot;BVr&quot; + nr[loop_count];
                temp1 = &quot;TVr&quot; + nr[loop_count];
                ++loop_count;
//              break after each increment
                break;
            }
            if(loop_count == 9) {
                temp = &quot;BVr&quot; + nr[8];
                temp1 = &quot;TVr&quot; + nr[8]; 
                ++loop_count;
            }else if(loop_count &gt; 9) {
                while(loop_count &lt; 20) {                
                temp = &quot;BVg&quot; + nr[8];
                temp1 = &quot;TVg&quot; + nr[8];
                temp2 = &quot;LVr&quot; + nr[loop_count-10];
                temp3 = &quot;RVr&quot; + nr[loop_count-10];
                ++loop_count; 
//              can't save left and right out of else if
//              because they will be assigned to: &quot; &quot;
                left = temp2;
                right = temp3;
                break;
                }
            }
                
            if(loop_count == 21) {
                temp = &quot;BVg&quot; + nr[9];
                temp1 = &quot;TVg&quot; + nr[9];
                temp2 = &quot;LVr&quot; + nr[9];
                temp3 = &quot;RVr&quot; + nr[9];
                
                left = temp2;
                right = temp3;
            }
            while(loop_count == 20) {
                temp2 = &quot;LVr&quot; + nr[9];
                temp3 = &quot;RVr&quot; + nr[9];
                ++loop_count;
                break;
            }
            if (loop_count &gt; 21) {
                System.out.println(&quot;go on&quot;);
            }
            bottom = temp;
            top = temp1;

//          System.out.println(&quot;State changed!&quot;+
//                  &quot;\nLoop count is: &quot;+loop_count);
            
//          revert to false until state changes again
            this.methodHasRun = false;
        
            } else {
            System.out.println(&quot;State hasn't changed&quot;);
            }
        return left +&quot; &quot;+ right +&quot; &quot;+ bottom +&quot; &quot;+ top;
    }
}
</code></pre>
<p>It produces this when run:
<a href=""https://i.stack.imgur.com/8HvnV.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/8HvnV.png"" alt=""enter image description here"" /></a></p>
<p>The test input file is:</p>
<pre><code>state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
vehicle left
vehicle right
vehicle bottom
vehicle top
step
state
</code></pre>
<p>That should output:</p>
<pre><code>LVg0 RVg0 BVr0 TVr0
LVg0 RVg0 BVr1 TVr1
LVg0 RVg0 BVr2 TVr2
LVg0 RVg0 BVr3 TVr3
LVg0 RVg0 BVr4 TVr4
LVg0 RVg0 BVr5 TVr5
LVg0 RVg0 BVr6 TVr6
LVg0 RVg0 BVr7 TVr7
LVg0 RVg0 BVr8 TVr8
LVg0 RVg0 BVr9 TVr9
LVr1 RVr1 BVg9 TVg9
LVr2 RVr2 BVg9 TVg9
LVr3 RVr3 BVg9 TVg9
LVr4 RVr4 BVg9 TVg9
LVr5 RVr5 BVg9 TVg9
LVr6 RVr6 BVg9 TVg9
LVr7 RVr7 BVg9 TVg9
LVr8 RVr8 BVg9 TVg9
LVr9 RVr9 BVg9 TVg9
LVr10 RVr10 BVg9 TVg9
LVg10 RVg10 BVr10 TVr10
</code></pre>
<p>I hope someone can catch my mistake or suggest something.</p>
",https://stackoverflow.com/questions/65634345/unit-testing-how-to-keep-scanner-running-java,"['java', 'unit-testing', 'testing', 'java.util.scanner']",62,True,-1,1
Unit testing of catcherror pipe function in angular service,"<p>I try to understand how to test this function. From <code>(err)=&gt;{ line,</code> it's showing as an uncovered statement.
<em><strong>service.ts</strong></em></p>
<pre class=""lang-js prettyprint-override""><code>Deletevote(inp) {
   console.log(inp);
     
   return this.http.post(environment.apiUrl + '/api/reset/abc', inp).pipe(
      catchError((err) =&gt; {
         console.log('error caught in service');
         console.error(err);
         return throwError(err);
      })
   );
}
</code></pre>
<p>I have created this test case for positive flow, but err part is still not covered. Please guide me about how to create the error.</p>
<p><strong>service.spec.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>const Mockcolor = 'green';
const MockGen = 'male';

it('submitnominGreen', () =&gt; {
    service.Deletevote(DeleteObj).subscribe((posts) =&gt;{
      expect(posts).toEqual([Mockcolor,MockGen], 'should check mock data');
    });
    const req =  httpTestCtrl.expectOne(environment.apiUrl + '/api/reset/abc');
    expect(req.request.method).toBe('POST');
    expect(req.cancelled).toBeFalsy();
    req.flush([Mockcolor,MockGen])
});
</code></pre>
",https://stackoverflow.com/questions/68379204/unit-testing-of-catcherror-pipe-function-in-angular-service,"['angular', 'unit-testing', 'jestjs', 'karma-jasmine', 'angular-unit-test']",4763,True,5,1
How to do unit testing for guard in nest?,"<p>I'v done unit testing for controllers and services like this:</p>
<pre><code>import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

describe('CatsController', () =&gt; {
 let catsController: CatsController;
 let catsService: CatsService;

 beforeEach(() =&gt; {
   catsService = new CatsService();
   catsController = new CatsController(catsService);
 });

 describe('findAll', () =&gt; {
   it('should return an array of cats', async () =&gt; {
     const result = ['test'];
     jest.spyOn(catsService, 'findAll').mockImplementation(() =&gt; result);

     expect(await catsController.findAll()).toBe(result);
   });
 });
});
</code></pre>
<p>but I hava a global guard, this guard is independent of any controller or service, I do not know how to write the .spec file. PLZ</p>
",https://stackoverflow.com/questions/67496417/how-to-do-unit-testing-for-guard-in-nest,"['typescript', 'unit-testing', 'jestjs', 'nestjs']",3941,True,5,1
Should fixture.destroy() be explicit in Angular 2+ unit testing,"<p>For unit testing with Karma/Jasmine in Angular 2+, should the fixture destruction be explicit?</p>
<pre><code>afterEach(() =&gt; fixture.destroy());
</code></pre>
<p>and what are the consequences if not destroying the fixture (i.e. is it called behind the scenes by the framework or does the fixture persist leading to side-effects)?</p>
<p>Angular <a href=""https://angular.io/api/core/testing/ComponentFixture#destroy"" rel=""nofollow noreferrer"">docs</a> on the topic don't suggest the right answer. What are your thoughts ? Thanks</p>
",https://stackoverflow.com/questions/66257081/should-fixture-destroy-be-explicit-in-angular-2-unit-testing,"['angular', 'karma-jasmine']",1117,False,4,0
Laravel user hierarchy w/ relationship unit testing gone wrong,"<p>Scenario:
So, I've got a users table that contains a ForeignKey named <code>parent_id</code> that references the id of the users table. This allows for one User to belongs to another User, and a User having Many &quot;children&quot; Users (one-to-many).</p>
<p>Now, the question itself is due to the unit testing. When I use records from a database it works as expected but mocking the relationship values doesn't seem it work. Also note that having this test being run against a database doesn't make sense as because the structure has a lot of dependencies.</p>
<p>The Goal: test the rule without hitting the database</p>
<p>The rule:</p>
<pre><code>&lt;?php

namespace App\Rules;

use App\Repositories\UserRepository;
use Illuminate\Contracts\Validation\Rule;

class UserHierarchy implements Rule
{
    /**
     * User related repository
     *
     * @var \App\Repositories\UserRepository $userRepository
     */
    private $userRepository;

    /**
     * User to affected
     *
     * @var null|int $userId 
     */
    private $userId;

    /**
     * Automatic dependency injection
     *
     * @param \App\Repositories\UserRepository $userRepository
     * @param integer|null $userId
     */
    public function __construct(UserRepository $userRepository, ?int $userId)
    {
        $this-&gt;userRepository = $userRepository;
        $this-&gt;userId = $userId;
    }

    /**
     * Determine if the validation rule passes.
     * Uses recursivity in order to validate if there is it causes an infinite loop
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        if (is_null($value)) {
            return true;
        }

        $childrenOfUserToBeUpdated = $this-&gt;userRepository-&gt;show($this-&gt;userId);
    //pluck_key_recursive is a customized function but its not posted because the issue can be traced on the dd below
        $notAllowedUserIds = pluck_key_recursive($childrenOfUserToBeUpdated-&gt;childrenTree-&gt;toArray(), 'children_tree', 'id');
         dd($childrenOfUserToBeUpdated-&gt;childrenTree-&gt;toArray());
        return in_array($value, $notAllowedUserIds) ? false : true;
    }
}
</code></pre>
<p>The User relationships are as it follows:</p>
<pre><code>/**
     * An User can have multiple children User
     *
     * @return EloquentRelationship
     */
    public function children(): HasMany
    {
        return $this-&gt;hasMany(self::class, 'parent_id', 'id');
    }

    /**
     * An User can have a hierarchal of children
     *
     * @return EloquentRelationship
     */
    public function childrenTree(): HasMany
    {
        return $this-&gt;children()-&gt;with('childrenTree');
    }
</code></pre>
<p>This is the test:</p>
<pre><code>&lt;?php

namespace Tests\Unit\Rules;

use App\Repositories\UserRepository;
use App\Rules\UserHierarchy;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Mockery;
use Tests\TestCase;

class UserHierarchyTest extends TestCase
{
    /**
     * Setting up Mockery
     *
     * @return void
     */
    protected function setUp(): void
    {
        parent::setUp();
           $this-&gt;parent = new User(['id' =&gt; 1]);
        $this-&gt;sonOne = new User(['id' =&gt; 2, 'parent_id' =&gt; $this-&gt;parent-&gt;id]);
        $this-&gt;sonTwo = new User(['id' =&gt; 3, 'parent_id' =&gt; $this-&gt;parent-&gt;id]);
        $this-&gt;sonThree = new User(['id' =&gt; 4, 'parent_id' =&gt; $this-&gt;parent-&gt;id]);
        $this-&gt;grandSonOne = new User(['id' =&gt; 5, 'parent_id' =&gt; $this-&gt;sonOne-&gt;id]);
        $this-&gt;grandSonTwo = new User(['id' =&gt; 6, 'parent_id' =&gt; $this-&gt;sonOne-&gt;id]);

 //$this-&gt;sonOne-&gt;children = new Collection([$this-&gt;grandSonOne, $this-&gt;grandSonTwo]);
        //$this-&gt;parent-&gt;children = new Collection([$this-&gt;sonOne, $this-&gt;sonTwo, $this-&gt;sonThree]);
        $this-&gt;sonOne-&gt;childrenTree = new Collection([$this-&gt;grandSonOne, $this-&gt;grandSonTwo]);
        $this-&gt;parent-&gt;childrenTree = new Collection([$this-&gt;sonOne, $this-&gt;sonTwo, $this-&gt;sonThree]);


        $this-&gt;userRepositoryMock = Mockery::mock(UserRepository::class);
        $this-&gt;app-&gt;instance(UserRepository::class, $this-&gt;userRepositoryMock);
    }

    /**
     * The rule should pass if the user to be updated will have not a child as a parent (infinite loop)
     *
     * @return void
     */
    public function test_true_if_the_user_id_isnt_in_the_hierarchy()
    {
        //Arrange
        $this-&gt;userRepositoryMock-&gt;shouldReceive('show')-&gt;once()-&gt;with($this-&gt;parent-&gt;id)-&gt;andReturn($this-&gt;parent);
        //Act
        $validator = validator(['parent_id' =&gt; $this-&gt;randomUserSon-&gt;id], ['parent_id' =&gt; resolve(UserHierarchy::class, ['userId' =&gt; $this-&gt;parent-&gt;id])]);
        //Assert
        $this-&gt;assertTrue($validator-&gt;passes());
    }

    /**
     * The rule shouldnt pass if the user to be updated will have a child as a parent (infinite loop)
     *
     * @return void
     */
    public function test_fail_if_the_user_id_is_his_son_or_below()
    {
        //Arrange
        $this-&gt;userRepositoryMock-&gt;shouldReceive('show')-&gt;once()-&gt;with($this-&gt;parent-&gt;id)-&gt;andReturn($this-&gt;parent);
        //Act
        $validator = validator(['parent_id' =&gt; $this-&gt;grandSonOne-&gt;id], ['parent_id' =&gt; resolve(UserHierarchy::class, ['userId' =&gt; $this-&gt;parent-&gt;id])]);
        //Assert
        $this-&gt;assertFalse($validator-&gt;passes());
    }

    /**
     * Tear down Mockery
     *
     * @return void
     */
    public function tearDown(): void
    {
        parent::tearDown();
        Mockery::close();
    }
}

</code></pre>
<p>I've tried a lot of combinations but I can't seem to get it to work. I've even tried mocking the user model all the way but it results in the same end: the children of a user are converted to an array but the grandchildren remain as item objects of a collection.</p>
<p>This is the sample output on this test:</p>
<pre><code>array:3 [
  0 =&gt; array:6 [
    &quot;name&quot; =&gt; &quot;asd&quot;
    &quot;email&quot; =&gt; &quot;asdasdasd&quot;
    &quot;id&quot; =&gt; 2
    &quot;parent_id&quot; =&gt; 1
    &quot;childrenTree&quot; =&gt; Illuminate\Database\Eloquent\Collection^ {#898
      #items: array:2 [
        0 =&gt; App\Models\User^ {#915
          #fillable: array:8 [...
</code></pre>
<p>Why does -&gt;toArray() convert everything to an array with real database objects but not when you set the expected outcome?</p>
",https://stackoverflow.com/questions/67710450/laravel-user-hierarchy-w-relationship-unit-testing-gone-wrong,"['laravel', 'eloquent', 'phpunit', 'laravel-8', 'eloquent-relationship']",314,True,3,1
Unit testing in Angular: Mocking RxJS observable with Jasmine,"<p>I am unit testing an Angular 12 component.  The component fetches, on initialisation, an observable returned from a service (see <code>thing.service.ts</code> below).  It is assigned to a Subject, which is displayed in the html template (see <code>app.component.html</code> below) via the <code>async</code> pipe.</p>
<p><strong>AppComponent.ts</strong></p>
<pre><code>export class AppComponent  {
  public errorObjectSubject = null;
  public thingsSubject: Subject&lt;Array&lt;IThing&gt;&gt; = new Subject();

  constructor(private readonly _service: ThingService) {
    this._getAllProducts();
  }

  private async _getAllProducts(): Promise&lt;void&gt; {
    this._service.getAllObservableAsync()
      .pipe(take(1),
        catchError(err =&gt; {
          this.errorObjectSubject = err;
          return throwError(err);
        })
      ).subscribe(result =&gt; { this.thingsSubject.next(result) });
  }
}
</code></pre>
<p>The template subscribes to <code>public thingsSubject: Subject&lt;Array&lt;IThing&gt;&gt; = new Subject();</code> with the <code>async</code> pipe:</p>
<p><strong>app.component.html</strong></p>
<pre><code>&lt;div&gt;
  &lt;app-thing *ngFor=&quot;let thing of thingsSubject | async&quot; [thing]=&quot;thing&quot;&gt;&lt;/app-thing&gt;
&lt;/div&gt;
</code></pre>
<p><strong>thing.service.ts</strong></p>
<pre><code>  constructor(private readonly _http: HttpClient) { }

  public getAllObservableAsync(): Observable&lt;Array&lt;IThing&gt;&gt; {
    return this._http.get&lt;Array&lt;IThing&gt;&gt;('https://jsonplaceholder.typicode.com/todos'); }
</code></pre>
<p>Here is the test setup.</p>
<p><strong>app.component.spec.ts</strong></p>
<pre><code>describe('AppComponent', () =&gt; {
  let component: AppComponent,
    fixture: ComponentFixture&lt;AppComponent&gt;,
    dependencies: { thingService: ThingServiceStub };

  function getThings(): Array&lt;DebugElement&gt; {
    return fixture.debugElement.queryAll(By.directive(ThingComponentStub));
  }

  beforeEach(async () =&gt; {
    dependencies = {
      thingService: new ThingServiceStub()
    };
    await TestBed.configureTestingModule({
      declarations: [AppComponent, ThingComponentStub],
      providers: [
        { provide: ThingService, useValue: dependencies.thingService }
      ]
    }).compileComponents();
  });

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

  describe('on initialisation', () =&gt; {
    let getThingsSubject: Subject&lt;Array&lt;IThing&gt;&gt;;

    beforeEach(() =&gt; {
      getThingsSubject = new Subject();
      (dependencies.thingService
        .getAllObservableAsync as jasmine.Spy).and.returnValue(
        getThingsSubject.asObservable()
      );
      fixture.detectChanges();
    });

    it('should fetch all of the things', () =&gt; {
      //fixture.detectChanges();
      expect(
        dependencies.thingService.getAllObservableAsync
      ).toHaveBeenCalledWith();
    });

    describe('when the things have been fetched', () =&gt; {
      beforeEach(fakeAsync(() =&gt; {
        getThingsSubject.next()
        // getThingsSubject.next([
        //   {
        //     userId: 1,
        //     id: 1,
        //     title: 'string',
        //     completed: 'string'
        //   }
        // ]);
        //getThingsSubject.pipe().subscribe()

        tick();

        fixture.detectChanges();
      }));

      it('should display the things', () =&gt; {
        expect(getThings()[0].componentInstance.product).toEqual({
          name: 'product',
          number: '1'
        });
      });
    });
  });
});
</code></pre>
<p><strong>thing.service.stub.ts</strong></p>
<pre><code>export class ProductServiceStub {
    public getAllObservableAsync: jasmine.Spy = jasmine.createSpy('getAllObservableAsync');
  }
</code></pre>
<p>I am trying to test how it works after the template has been populated with things (<code>IThing[]</code>).  I have a <em>passing</em> spec which calls the mock observable:</p>
<pre><code>it('should fetch all of the things', () =&gt; {
  expect(
    dependencies.thingService.getAllObservableAsync
  ).toHaveBeenCalledWith();
});
</code></pre>
<p>However I hit the 'Error: Uncaught (in promise): TypeError: Cannot read property 'pipe' of undefine' when I attempt to test the template: <code>describe('when the things have been fetched'</code>.</p>
<p>I am not quite sure what is the problem.  Is it how I have setup the subscription to the Subject?  Or the change detection?</p>
",https://stackoverflow.com/questions/68224715/unit-testing-in-angular-mocking-rxjs-observable-with-jasmine,"['angular', 'jasmine', 'angular12']",5277,True,2,1
Android unit testing how to test observable and Subscriber,"<p>Hi Following is my part of code which I want to test with various requests but I am unable to test as it is observable subscriber patter any idea how to mock subscriber or how to wait for a result in unit testing</p>
<pre><code>api.loadData(request)
            .observeOn(schedulers.main())
            .doOnNext(this::addDataCheck)
            .subscribe(
                    data -&gt; onDataLodaded(listener, data),
                    e -&gt; onAdFailedToLoad(listener, Api.error(request), e)
            )
            .addTo(disposables);
</code></pre>
",https://stackoverflow.com/questions/69942177/android-unit-testing-how-to-test-observable-and-subscriber,"['android', 'unit-testing', 'mockito', 'android-testing', 'android-junit']",1538,False,2,1
Unit testing timestamp field rule in firestore security rules,"<p>I am writing unit tests for my firestore security rules using the node.js library <code>@firebase/rules-unit-testing</code></p>
<p>Here is my security rule for updating a document:</p>
<pre><code>allow update: if request.auth.uid != null &amp;&amp;
  request.auth.uid == userId &amp;&amp;
  request.resource.data.updatedAt == request.time;
</code></pre>
<p>I want the <code>updatedAt</code> field to be always set to the <code>FieldValue.serverTimestamp()</code>.</p>
<p>In my unit test, I am trying to update the value with <code>FieldValue.serverTimestamp()</code> and verifying  that it should succeed. Here is my code snippet:</p>
<pre><code>let testEnvironment: RulesTestEnvironment = await initializeTestEnvironment({
  projectId: PROJECT_ID,
  firestore: {
    rules: fs.readFileSync(&quot;../firestore.rules&quot;, &quot;utf8&quot;),
    host: &quot;localhost&quot;,
    port: 8080
  }
})

const firestore = testEnvironment.authenticatedContext(&quot;user_123&quot;).firestore()
const testDoc = firestore.doc(&quot;/writers/user_123&quot;)
await assertSucceeds(testDoc.update(
  &quot;some_field&quot;, &quot;some_value&quot;, &quot;updatedAt&quot;, firestore.FieldValue.serverTimestamp()
))
</code></pre>
<p>In this case, <code>firestore.FieldValue</code> is not defined.</p>
<p>I tried using the admin SDK <code>firebase-admin</code>, changing the last statement to:</p>
<pre><code>await assertSucceeds(testDoc.update(
  &quot;some_field&quot;, &quot;some_value&quot;, &quot;updatedAt&quot;, admin.firestore.FieldValue.serverTimestamp()
))
</code></pre>
<p>For this, I get the error-</p>
<blockquote>
<p>FirebaseError: Function DocumentReference.update() called with invalid data. Unsupported field value: a custom object (found in field updatedAt in document writers/user_123)</p>
</blockquote>
<p>Can anyone suggest how to add tests for the timestamp field update?</p>
",https://stackoverflow.com/questions/69045894/unit-testing-timestamp-field-rule-in-firestore-security-rules,"['typescript', 'firebase', 'google-cloud-firestore', 'firebase-security']",426,False,2,1
How to do Unit Testing on bloc using blocTest?,"<p>I have a bloc that works to get cartItem from orderItem by id and i want to test the bloc, I've read some bloc testing from flutter_bloc but I still don't know how to implement it on my bloc. I want to do a test using dummy data that I made. I want it to get the dummy list when CartItemCheck event is emitted and remove the list when CartItemUncheck is emitted. here is my bloc code:</p>
<pre><code>import...

abstract class CartItemEvent {
  const CartItemEvent();
}

class CartItemCheck extends CartItemEvent {
  final CartItem? item;

  CartItemCheck({this.item});

  List&lt;Object&gt; get props =&gt; [item!];

  @override
  String toString() =&gt; 'CartItemChecked { item: $item }';
}

class CartItemUncheck extends CartItemEvent {
  final CartItem? item;
  CartItemUncheck({this.item});

  List&lt;Object&gt; get props =&gt; [item!];

  @override
  String toString() =&gt; 'CartItemUnchecked { item: $item }';
}

class CartItemUpdate extends CartItemEvent {
  final String? itemId;
  final String? type;

  CartItemUpdate({this.itemId, this.type});

  List&lt;Object&gt; get props =&gt; [itemId!, type!];

  @override
  String toString() =&gt; 'CartItemUpdated { item: $itemId }';
}


class CartItemBloc extends Bloc&lt;CartItemEvent, List&lt;CartItem&gt;&gt; {
  final List&lt;CartItem&gt;? initialItems;

  CartItemBloc(this.initialItems) : super(initialItems!);

  @override
  Stream&lt;List&lt;CartItem&gt;&gt; mapEventToState(CartItemEvent event) async* {
    if (event is CartItemCheck) {
      List&lt;CartItem&gt; newItems = state..add(event.item!);
      yield newItems.toList();
    }
    else if (event is CartItemUncheck) {
      List&lt;CartItem&gt; newItems = state.where((item) =&gt; item.itemId != event.item!.itemId).toList();
      yield newItems.toList();
    } else if (event is CartItemUpdate) {
      CartItem oldItem = state.where((item) =&gt; item.itemId == event.itemId).first;
      List&lt;CartItem&gt; cartItems = state;
      if (event.type == 'increment') {
        CartItem updatedItem = oldItem.copyWith(qty: oldItem.qty + 1);
        cartItems[cartItems.indexWhere((item) =&gt; item.itemId == event.itemId)] = updatedItem;
        yield cartItems.toList();
      } else {
        CartItem updatedItem = oldItem.copyWith(qty: oldItem.qty - 1);
        cartItems[cartItems.indexWhere((item) =&gt; item.itemId == event.itemId)] = updatedItem;
        yield cartItems.toList();
      }
    }
  }
}
</code></pre>
<p>and here is my current test code:</p>
<pre><code>import 'package:bloc_test/bloc_test.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pikpo_screen/blocs/cart_item_bloc.dart';
import 'package:pikpo_screen/model/cart_item.dart';
import 'package:pikpo_screen/util/order_helper.dart';

main(){
  CartItemBloc? cartItemBloc;
  List&lt;CartItem&gt; expectedResult = [CartItem(itemId: &quot;1&quot;), CartItem(price: 35), CartItem(qty: 2)];
  List&lt;CartItem&gt; initialItem = [];
  setUp(() {
    cartItemBloc = CartItemBloc(initialItem);
  });

  test('initial state is []', () {
    expect(cartItemBloc!.state, []);
  });
  blocTest('description',
      build: () =&gt; cartItemBloc,
    act: (bloc) =&gt; bloc.add(CartItemCheck()),
    expect: () =&gt; [1]
  );
}
</code></pre>
<p>Thank you in advance for helping me</p>
",https://stackoverflow.com/questions/69525314/how-to-do-unit-testing-on-bloc-using-bloctest,"['flutter', 'dart', 'bloc', 'flutter-bloc', 'bloc-test']",4477,True,2,1
How to use ThrowTheSwitch&#39;s Unity C unit testing library?,"<p>How to use ThrowTheSwitch's Unity C unit testing library?</p>
<p>I'm trying to use <a href=""https://github.com/ThrowTheSwitch/Unity/"" rel=""nofollow noreferrer"">ThrowTheSwitch's Unity library</a> to create my unit test in C, but I got some strange errors, but I'm newbie, so this is maybe something basic.</p>
<p>Here is My code:
this is <code>mytest.c</code></p>
<pre><code>int testValue = 45;

int testThisPass(int idx)
{
    if idx == 42
        return 1;
    
    return 0;
}

int testThisNotPass(int idx)
{
    return 42;
} 
</code></pre>
<p>this is <code>mytest.h</code></p>
<pre><code>int testThisPass(int idx);
int testThisNotPass(int idx);
</code></pre>
<p>this is <code>mytestMain.c</code></p>
<pre><code>#include &quot;unity.h&quot;
#include &quot;unity_internals.h&quot;
#include &quot;mytest.h&quot;
#include &lt;stdio.h&gt;

void setUp(void) {
    //testValue = 40;
}

void tearDown(void) {
    // clean stuff up here
}

void test_function_should_doBlahAndBlah(void) {
    TEST_ASSERT_EQUAL(1,testThisPass(42));
}

void test_function_should_doAlsoDoBlah(void) {
    TEST_ASSERT_EQUAL(42, testThisNotPass(5));
}

// not needed when using generate_test_runner.rb
int main(void) {
    UNITY_BEGIN();
    RUN_TEST(test_function_should_doBlahAndBlah);
    RUN_TEST(test_function_should_doAlsoDoBlah);
    return UNITY_END();
}
</code></pre>
<p>And this is the error what I got when I tried to compile <code>mytestMain.c</code>:</p>
<pre><code>/usr/bin/ld: /tmp/ccOOjz1w.o: in function `test_function_should_doBlahAndBlah':
mytestMain.c:(.text+0x24): undefined reference to `testThisPass'
/usr/bin/ld: mytestMain.c:(.text+0x43): undefined reference to `UnityAssertEqualNumber'
/usr/bin/ld: /tmp/ccOOjz1w.o: in function `test_function_should_doAlsoDoBlah':
mytestMain.c:(.text+0x58): undefined reference to `testThisNotPass'
/usr/bin/ld: mytestMain.c:(.text+0x77): undefined reference to `UnityAssertEqualNumber'
/usr/bin/ld: /tmp/ccOOjz1w.o: in function `main':
mytestMain.c:(.text+0x8e): undefined reference to `UnityBegin'
/usr/bin/ld: mytestMain.c:(.text+0xa6): undefined reference to `UnityDefaultTestRun'
/usr/bin/ld: mytestMain.c:(.text+0xbe): undefined reference to `UnityDefaultTestRun'
/usr/bin/ld: mytestMain.c:(.text+0xc3): undefined reference to `UnityEnd'
collect2: error: ld returned 1 exit status
</code></pre>
<p>What Should I do to work? What did I missed here?</p>
",https://stackoverflow.com/questions/69418872/how-to-use-throwtheswitchs-unity-c-unit-testing-library,"['c', 'unit-testing', 'gcc', 'unity-test-framework']",1086,True,2,2
Unit testing getting error class could not be found,"<p>I have a class for <code>dynamoDB</code> in location</p>
<pre><code>src/Dynamo/shop.php 
</code></pre>
<p>My class looks like below</p>
<pre><code>&lt;?php
    
    namespace App\Dynamo;
    
    
    class Shop
    {
        -----
    }
    
?&gt;
</code></pre>
<p>I am trying to implement unit test for this class, So I have created a folder class dynamo in below location.</p>
<pre><code>app/cake/tests/TestCase/Dynamo
</code></pre>
<p>In Dynamo folder I have created a class with file name <code>ShopTest.php</code></p>
<p>For create a unit testing I have written this class like below</p>
<pre><code>&lt;?php
declare(strict_types=1);

namespace App\Test\TestCase\Dynamo;

use App\Dynamo\Shop;
use Cake\TestSuite\TestCase;

class ShopTest{
    
    public function setUp()
    {
        $this-&gt;shop = new Shop;
    }

    public function testconnectDynamoDB()
    {
        debug($this-&gt;shop-&gt;connectDynamoDB());

        $this-&gt;assertNotEmpty($this-&gt;shop-&gt;connectDynamoDB());

    }
}
</code></pre>
<p>Now after run phpunit command</p>
<pre><code>vendor/bin/phpunit tests/TestCase/Dynamo/ShopTest.php 
</code></pre>
<p>I am getting</p>
<pre><code>Class 'App\Test\TestCase\Dynamo\ShopTest' could not be found in '/var/www/html/tests/TestCase/Dynamo/ShopTest.php'.
</code></pre>
<p>Class is present in this location , Why I am getting Class could not be found ?</p>
<pre><code>root@0ceda1df4444:/var/www/html# cd /var/www/html/tests/TestCase/Dynamo/
    root@0ceda1df4444:/var/www/html/tests/TestCase/Dynamo# ls
    ShopTest.php

root@0ceda1df4444:/var/www/html/tests/TestCase/Dynamo# cat ShopTest.php 
&lt;?php
declare(strict_types=1);

namespace App\Test\TestCase\Dynamo;

use App\Dynamo\Shop;
use Cake\TestSuite\TestCase;

class ShopTest{

</code></pre>
<p>Also I am trying to run all test case by below command , I am getting a warning.</p>
<pre><code>root@0ceda1df4444:/var/www/html# vendor/bin/phpunit                
PHPUnit 9.5.9 by Sebastian Bergmann and contributors.

Warning:       Your XML configuration validates against a deprecated schema.
Suggestion:    Migrate your XML configuration using &quot;--migrate-configuration&quot;!

No tests executed!
</code></pre>
",https://stackoverflow.com/questions/69123049/unit-testing-getting-error-class-could-not-be-found,"['cakephp', 'cakephp-4.x']",406,True,1,1
Jest-Vue-Quasar unit testing issue with ES modules,"<p>I'm have issues testing with Jest, I don't have much experience.  My component is using my own ES <strong>Node Module</strong>, an it works fine in runtime, except when running the test., I'm using Vue3, Quasar and Jest.</p>
<p>I Tried different things such as mapping (moduleNameMapper) in the jest config file without success.</p>
<p>I get this error while running the test.</p>
<p><code> Cannot find module 'my-module' from 'src/Helpers.js'</code></p>
<p>In Helpers.js this is how is declared</p>
<pre><code>import EventEmitter from 'events';
import { v4 as uuid } from 'uuid';
import { testMethod  } from 'my-module';
</code></pre>
<p>This is my jest.config.js</p>
<pre><code>const esModules = ['quasar/lang', 'lodash-es'].join('|');

/* eslint-env node */
module.exports = {
  globals: {
    __DEV__: true,
    // TODO: Remove if resolved natively
    // See https://github.com/vuejs/vue-jest/issues/175
    'vue-jest': {
      pug: { doctype: 'html' },
    },
  },
  // noStackTrace: true,
  // bail: true,
  // cache: false,
  verbose: true,
  // watch: true,
  collectCoverage: true,
  reporters: [
    'default',
    [ 'jest-junit', {
      outputDirectory: '&lt;rootDir&gt;/',
      outputName: 'junit.xml',
    } ]
  ],
  coverageReporters: [
    &quot;json&quot;, &quot;lcov&quot;, &quot;text&quot;, &quot;clover&quot;, &quot;cobertura&quot;
  ],
  coverageDirectory: '&lt;rootDir&gt;/coverage',
  collectCoverageFrom: [
    '&lt;rootDir&gt;/src/**/*.vue',
    //'&lt;rootDir&gt;/src/**/*.js',
    '&lt;rootDir&gt;/src/**/*.ts',
    //'&lt;rootDir&gt;/src/**/*.jsx',
    //'&lt;rootDir&gt;/src/**/*.tsx',
  ],
  coveragePathIgnorePatterns: ['/node_modules/', '.d.ts$'],
  coverageThreshold: {
    global: {
      //  branches: 50,
      //  functions: 40,
      //  lines: 50,
      //  statements: 50
    },
  },
  testMatch: [
    // Matches tests in any subfolder of 'src' or into 'test/jest/__tests__'
    // Matches all files with extension 'js', 'jsx', 'ts' and 'tsx'
    '&lt;rootDir&gt;/test/jest/__tests__/**/*.(spec|test).+(ts|js)?(x)',
    '&lt;rootDir&gt;/src/**/*.jest.(spec|test).+(ts|js)?(x)',
  ],
  // Extension-less imports of components are resolved to .ts files by TS,
  //  grating correct type-checking in test files.
  // Being 'vue' the first moduleFileExtension option, the very same imports
  //  will be resolved to .vue files by Jest, if both .vue and .ts files are
  //  in the same folder.
  // This guarantee a great dev experience both for testing and type-checking.
  // See https://github.com/vuejs/vue-jest/issues/188#issuecomment-620750728
  moduleFileExtensions: ['vue', 'js', 'jsx', 'json', 'ts', 'tsx'],
  moduleNameMapper: {
    '^~/(.*)$': '&lt;rootDir&gt;/$1',
    '^src/(.*)$': '&lt;rootDir&gt;/src/$1',
    '^app/(.*)$': '&lt;rootDir&gt;/$1',
    '^components/(.*)$': '&lt;rootDir&gt;/src/components/$1',
    '^layouts/(.*)$': '&lt;rootDir&gt;/src/layouts/$1',
    '^pages/(.*)$': '&lt;rootDir&gt;/src/pages/$1',
    '^assets/(.*)$': '&lt;rootDir&gt;/src/assets/$1',
    '^boot/(.*)$': '&lt;rootDir&gt;/src/boot/$1',
    '.*css$': '@quasar/quasar-app-extension-testing-unit-jest/stub.css',
  },
  transform: {
    // See https://jestjs.io/docs/en/configuration.html#transformignorepatterns-array-string
    [`^(${esModules}).+\\.js$`]: 'babel-jest',
    '^.+\\.(ts|js|html)$': 'ts-jest',
    // vue-jest uses find-babel-file, which searches by this order:
    //  (async) .babelrc, .babelrc.js, package.json, babel.config.js
    //  (sync) .babelrc, .babelrc.js, babel.config.js, package.json
    // https://github.com/tleunen/find-babel-config/issues/33
    '.*\\.vue$': 'vue-jest',
    '.+\\.(css|styl|less|sass|scss|svg|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub',
  },
  transformIgnorePatterns: [`&lt;rootDir&gt;/node_modules/(?!(${esModules}))`],
  snapshotSerializers: ['&lt;rootDir&gt;/node_modules/jest-serializer-vue'],
};
</code></pre>
<p>.babelrc</p>
<pre><code>{
  &quot;plugins&quot;: [&quot;@babel/plugin-syntax-dynamic-import&quot;],
  &quot;env&quot;: {
    &quot;test&quot;: {
      &quot;plugins&quot;: [&quot;dynamic-import-node&quot;],
      &quot;presets&quot;: [
        [
          &quot;@babel/preset-env&quot;,
          {
            &quot;modules&quot;: &quot;commonjs&quot;,
            &quot;targets&quot;: {
              &quot;node&quot;: &quot;current&quot;
            }
          }
        ]
      ]
    }
  }
}

</code></pre>
",https://stackoverflow.com/questions/69702639/jest-vue-quasar-unit-testing-issue-with-es-modules,"['unit-testing', 'jestjs', 'quasar']",240,False,1,0
Can&#39;t resolve all parameters + error + for service unit testing,"<p>I am receiving the following error:..</p>
<pre><code>Can't resolve all parameters for Service1: (?, ?).

Service1.ts
export class Service1 {
constructor(protected url: string, protected http: HttpClient) { }
}

Service1.spec.ts
describe('Service1', () =&gt; {
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [Service1],
    });
  });

    it('should be created', () =&gt; {
      const service1: Service1 = TestBed.get(Service1);
      expect(service1).toBeTruthy();
  });
});
</code></pre>
<p>Have mocked inly httpclient module here, If it mocke url:stirng part it will work i think so.So how can i mock and makke the test pass?.</p>
",https://stackoverflow.com/questions/65678783/cant-resolve-all-parameters-error-for-service-unit-testing,"['angular', 'unit-testing', 'jestjs']",63,False,1,1
Issue with my unit testing - Junit - mockito - EntityManager - createNativeQuery,"<p>I am trying to test my class that uses a createNativeQuery to query a database</p>
<p>Here is the class that i am using to query the database.</p>
<pre><code>@component
public class QueryAdapter{
...    

     public UtilityResponse getCreditLimit(String id) {
         Query q = entityManager.createNativeQuery(&quot;select name from MY_TABLE where id=:id&quot;);
 
         LOGGER.info(id);
 
         q.setParameter(&quot;id&quot;, id);
         q.setMaxResults(Integer.parseInt(env.getProperty(&quot;maxrows&quot;)));
 
         @SuppressWarnings(&quot;unchecked&quot;)
         List&lt;Object[]&gt; d = q.getResultList();
 
         UtilityResponse duresp = new UtilityResponse();
         duresp.setData(d);
 
         return duresp;
...
}
</code></pre>
<p>I have written a junit test class like below. I have mocked the EntityManager and the Query classes. I am expecting the List&lt;Object[]&gt; from the getResponse() method to be returned when the getResultList method is encountered.</p>
<pre><code> package com.myorg.myapp.datautility.test;
 
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.when;
 import static org.mockito.ArgumentMatchers.any;
 
 import java.util.ArrayList;
 import java.util.List;
 
 import javax.persistence.EntityManager;
 import javax.persistence.Query;
 
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.Mockito;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
 import org.springframework.test.context.junit4.SpringRunner;
 
 import com.myorg.myapp.datautility.adapter.QueryAdapter;
 
 @SpringBootTest
 @RunWith(SpringRunner.class)
 public class UtilityAdapterTest {
     
     @Mock
     EntityManager em;
     
     @Autowired
     public QueryAdapter dqa;
     
     @Mock
     Query mockedQuery;
     
     @Test
     public void getCreditLimitTest() {
         String id = &quot;12345&quot;;
         
         when(em.createNativeQuery(any(String.class))).thenReturn(mockedQuery);
         Mockito.when(em.createNativeQuery(Mockito.anyString())).thenReturn(mockedQuery);
         when(mockedQuery.getResultList()).thenReturn(getResponse());
 
         UtilityResponse dur=dqa.getCreditLimit(id);
         
         assertTrue(dur instanceof UtilityResponse);
 
     }
 
     public List&lt;Object[]&gt; getResponse() {
         List&lt;Object[]&gt; lo = new ArrayList&lt;&gt;();
         
         Object[] os = new Object[6];
 
         for (int i = 0; i &lt; 6; i++) {
             os[i] = &quot;STUB&quot;;
         }
 
         lo.add(os);
 
         return lo;
     }
 
 }
</code></pre>
<p>My application.properties goes like this. I am actually using a h2 database.</p>
<pre><code> server.port=8004
 
 spring.jpa.show-sql=true
 
 spring.jpa.properties.hibernate.generate_statistics=false
 spring.datasource.url=jdbc:h2:mem:temp;DB_CLOSE_DELAY=-1
 spring.datasource.username=sa
 spring.datasource.password=
 spring.datasource.driver-class-name=org.h2.Driver
 spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
 spring.jpa.hibernate.ddl-auto=none
</code></pre>
<p>When I run the test case I am expecting a successful result. But i am getting the below result. This is the table i am trying to access</p>
<pre><code>2021-02-25 23:33:19.084  WARN 36008 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 42102, SQLState: 42S02
2021-02-25 23:33:19.084 ERROR 36008 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper   : Table &quot;MY_TABLE&quot; not found; SQL statement
</code></pre>
",https://stackoverflow.com/questions/66380376/issue-with-my-unit-testing-junit-mockito-entitymanager-createnativequery,"['java', 'spring-boot', 'junit', 'mockito', 'h2']",2426,False,1,1
component unit testing services call resolved in the afterviewinit,"<p>I have a component that implement afterviewinit and in the ngAfterViewInit I have some service calls and a call to check the actives tabs but I am struggling to setup my unit test:</p>
<pre><code>export class SomeComponent implements OnInit, AfterViewInit{
@ViewChild('tabGroup') tabGroup: MatTabGroup;

 ngOnInit(): void {}
 ngAfterViewInit(): void {
 const label = this.tabGroup._tabs.find((x: MatTab) =&gt; x.isActive).textLabel;
 
 //Service Call that use the label
 }
}
</code></pre>
<p>and in my test:</p>
<pre><code> describe('SomeComponent', () =&gt; {
        let component: SomeComponent;
        let fixture: ComponentFixture&lt;SomeComponent&gt;;
        
        
        beforeEach(waitForAsync(()=&gt;{
        
        TestBed.configureTestingModule( declarations: [
                    SomeComponent,]
                    imports:[ MatTabsModule,]).compileComponents();
    });
                    
                                 
beforeEach(() =&gt; {
    fixture = TestBed.createComponent(someComponent);
    component = fixture.componentInstance;
    Object.defineProperty(component, 'tabs', { value: [], isActive: true});
    fixture.detectChanges();
  });

        it('should be created', () =&gt; {
            expect(component).toBeTruthy();
        });});
</code></pre>
<p>the test run ok but I am getting this error : <code>AfterAll TypeError: Cannot read property 'textLabel' of undefined</code></p>
<p>I have tried using the:</p>
<pre><code>afterEach(() =&gt; {
  fixture.destroy();
});
</code></pre>
<p>It seems to have resolved the first test but I am just wondering if there is a better way to do it.
PS: Basically my question is how should I mock objects that are set in the ngAfterViewInit, for instance the tabs are viewchild
Regards</p>
",https://stackoverflow.com/questions/66351875/component-unit-testing-services-call-resolved-in-the-afterviewinit,"['angular', 'unit-testing', 'karma-jasmine']",409,True,1,1
Jest Unit testing module export error in browser console,"<p>I am trying to use Jest to test my JS code, but why do I get <code>Uncaught ReferenceError: module is not defined</code> in the browser console?</p>
<p>Example:
<strong>app.js</strong></p>
<pre><code>const funct = (a,b) =&gt; {
    let sum  = a + b;
    return sum;
}

module.exports = funct;
</code></pre>
<p><strong>app.test.js</strong></p>
<pre><code>const funct = require('./app.js')

test('funct func', () =&gt; {
    expect(funct(1, 2)).toBe(3);
})
</code></pre>
<p>The test passes, but I get the module exports error in the browser console?</p>
<pre><code>Uncaught ReferenceError: module is not defined
</code></pre>
",https://stackoverflow.com/questions/66349868/jest-unit-testing-module-export-error-in-browser-console,"['javascript', 'jestjs']",307,True,1,1
Unit testing two objects which return a matrix (java),"<p>I'm trying to create a JUnit test with two objects that return a 2D array/matrix, here is my constructor:</p>
<pre><code>public Matrix(int[][] array) {
    this.matrix = Arrays.copyOf(array, array.length); } 
</code></pre>
<p>Here is my test code:</p>
<pre><code>@Test
void addValue() {
    int[][] array = {{1, 2, 3}, {1, 2, 3}};
    int[][] newArray = {{1, 2, 3, 4}, {1, 2, 3}};

    Matrix result = new Matrix(array);
    Matrix expected = new Matrix(newArray);

    assertEquals(expected,result.addValue(0,4));

}
</code></pre>
<p>addValueInSpecificLine is a function I created, in this case, it adds the value 4 in line 0.</p>
<p>Here is the error of my test:</p>
<pre><code>org.opentest4j.AssertionFailedError: expected: Matrix@3c0a50da&lt;Array{array=[[1, 2, 3, 4], [1, 2, 3]]}&gt; but was: Matrix@646be2c3&lt;Array{array=[[1, 2, 3, 4], [1, 2, 3]]}&gt;
Expected :Array{array=[[1, 2, 3, 4], [1, 2, 3]]}
Actual   :Array{array=[[1, 2, 3, 4], [1, 2, 3]]}
</code></pre>
<p>The expected is the same as the actual, but for some reason the test is false.</p>
<p>Any advice?</p>
",https://stackoverflow.com/questions/70073180/unit-testing-two-objects-which-return-a-matrix-java,"['java', 'arrays', 'matrix', 'junit']",297,True,1,1
How to configure unit testing for AnyLogic agent code?,"<p>How do you configure unit testing framework to help develop code that is part of AnyLogic agents?</p>
<p>To have a suitable test driven development rhythm, I need to be able to run all tests in a few seconds. I thought of exporting the project as a standalone application (jar) each time, but that's pretty slow.</p>
<p>I thought of trying to write all the code outside AnyLogic in separate classes, but there are many references to built-in AnyLogic classes, as well as various agents. My code would need to refer to these somehow, and I'm not sure how to do that except by writing the code inside AnyLogic.</p>
<p>I wonder if there's a way of adding the test runner as a dependency, and executing that test runner from within AnyLogic.</p>
<p>Does anyone have a setup that works nicely?</p>
",https://stackoverflow.com/questions/69005232/how-to-configure-unit-testing-for-anylogic-agent-code,"['unit-testing', 'junit', 'simulation', 'anylogic']",306,True,1,1
How to mock aws-amplify in react unit testing?,"<p>I am using <a href=""https://aws.amazon.com/ru/cognito/"" rel=""nofollow noreferrer"">AWS co</a>, <a href=""https://aws.amazon.com/ru/amplify/"" rel=""nofollow noreferrer"">Amplify</a> and <a href=""https://en.reactjs.org/"" rel=""nofollow noreferrer"">React</a>
I want to mock API.graphql imported from AWS.
This is my helper function for asynchronous functions
<code>useAsync.ts</code></p>
<pre><code>import { ErrorHandle } from '@app/components/ErrorHandle';
import { useCallback, useState } from 'react';

const getRetryWaitTime = (retryCount: number): number =&gt; {
  const httpRetryMaxWaitTime = 10 * 60 * 1000;
  const suggestedRetryWaitTime = 1000 * 2 ** retryCount;
  const retryWaitTime = Math.min(httpRetryMaxWaitTime, suggestedRetryWaitTime);
  return retryWaitTime;
};

const delay = (ms: number) =&gt; {
  return new Promise((resolve) =&gt; setTimeout(resolve, ms));
};

const retry = (retryFunc: () =&gt; Promise&lt;any&gt;, retryCount = -1): Promise&lt;any&gt; =&gt; {
  return retryFunc().catch((err: any) =&gt; {
    if (err &amp;&amp; retryCount) {
      retryCount -= 1;
      const waitTime = getRetryWaitTime(retryCount);
      return delay(waitTime).then(() =&gt; retry(retryFunc, retryCount));
    }
    throw err;
  });
};

export const useAsync = (
  asyncFunction,
  options: {
    onError?: (error, response) =&gt; any;
    onSuccess?: (data) =&gt; any;
    retryCount?: number;
  } = {},
) =&gt; {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  options.retryCount = options.retryCount || 1;
  options.onError = options.onError || ((error, response) =&gt; ErrorHandle(error, response));

  const execute = useCallback(
    async (payload?: any) =&gt; {
      setLoading(true);
      setData(null);
      setError(null);

      return retry(() =&gt; asyncFunction(payload), options.retryCount)
        .then((response) =&gt; {
          setData(response);
          if (options.onSuccess) {
            options.onSuccess(response);
          }
          setLoading(false);
          return { ok: true, data: response.data, response };
        })
        .catch((error: any) =&gt; {
          setError(error);
          if (options.onError) {
            options.onError(error, error ? error.response : null);
          }
          setLoading(false);
          return { error, ok: false, response: error, data: error };
        });
    },
    [asyncFunction, options],
  );

  return { execute, loading, data, error };
};
</code></pre>
<p>This is an example for my graphql mutations file.
<code>mutations.ts</code></p>
<pre><code>export const createLanguage = /* GraphQL */ `
  mutation CreateLanguage($input: CreateLanguageInput!, $condition: ModelLanguageConditionInput) {
    createLanguage(input: $input, condition: $condition) {
      id
      name
      code
      createdAt
      updatedAt
      createdBy
      updatedBy
      direction
      owner
    }
  }
`;
</code></pre>
<p>This is actual code for mocking and unit testing my useLanguages file
<code>useLanguages.ts</code></p>
<pre><code>import { createLanguage } from '@app/graphql/mutations';
import { API, graphqlOperation } from 'aws-amplify';
const useLanguages = () =&gt; {

  const [state, dispatch] = useStore();
  const languageAdd = useAsync(
   (value) =&gt; {
     const input: any = value;
     input.createdBy = state.user.attributes.email;
     input.updatedBy = state.user.attributes.email;
     return API.graphql(graphqlOperation(createLanguage, { input }));
   },
   {
     onSuccess: (result) =&gt; dispatch({ type: Actions.ADD_LANGUAGE, payload: result.data.createLanguage }),
   },
  );
  return { languageAdd };
}
</code></pre>
<p>I tried multiple variants <a href=""https://stackoverflow.com/questions/59215244/how-to-mock-aws-amplify-library-in-angular"">this</a> <a href=""https://stackoverflow.com/questions/60454057/how-do-i-properly-mock-amplify-for-unit-testing-in-jasmine"">that</a> and read a lot of documentations and articles like
<a href=""https://www.apollographql.com/docs/react/development-testing/testing/"" rel=""nofollow noreferrer"">this</a> <a href=""https://dev.to/rakannimer/testing-your-amplify-application-with-jest-and-cypress-1g0i"" rel=""nofollow noreferrer"">that</a></p>
",https://stackoverflow.com/questions/70150882/how-to-mock-aws-amplify-in-react-unit-testing,"['reactjs', 'unit-testing', 'graphql', 'aws-amplify']",606,True,1,1
unit testing for a nested async call in javascript,"<p>I have two methods:
second one is called by the first and I have to write test for the first one.</p>
<pre><code>function func1(props, num) {
    num.value +=1;
    func2(props, num);
}
    
function func2(props, num) {
    props.actions.getItDone().then((res) =&gt; {
    num.value+=res.payload;
    console.log(num);//i see 6 here but not in the test result.
    });
}
</code></pre>
<p>Unit test file:</p>
<pre><code>const props = {
    actions: {
        getItDone: () =&gt; {
            return Promise.resolve({payload: 5 })
        }
    }
}
it('should verify something', () =&gt; {
    const num = {value: 0};
    func1(props, num);
    expect(num.value).toBe(6); // it fails num.value coming here is 1.
});
</code></pre>
<p>it seems to me it's not waiting for the other method to complete. how can i make this return the correct value?</p>
",https://stackoverflow.com/questions/68717111/unit-testing-for-a-nested-async-call-in-javascript,"['javascript', 'unit-testing', 'asynchronous', 'async-await', 'request-promise']",664,True,1,2
Error DataSource.Factory must be provided when Unit Testing RawQuery,"<p>I'am trying to do testing for rawquery using Room. I am using JUnit 4. Here is my code:</p>
<pre><code>// MovieRepositoryTest.kt        
@Test
fun getWatchlistTv() {
    val query = getSortedTv(DEFAULT)
    val dataSourceFactory = mock(DataSource.Factory::class.java) as DataSource.Factory&lt;Int, TvEntity&gt;
    val dummy = DummyData.generateTvWatchlist(tvResponse)
    `when`(local.getWatchlistTv(query)).thenReturn(dataSourceFactory)
    movieRepository.getWatchlistTv(DEFAULT) // here is the line 90

    val tvEntities = PagedListUtil.mockPagedList(dummy)

    verify(local).getWatchlistTv(query)
    assertNotNull(tvEntities)
    assertEquals(tvWatchlist.size, tvEntities.size)
}

// Dao
@RawQuery(observedEntities = [TvEntity::class])
fun getWatchlistTv(query: SupportSQLiteQuery): DataSource.Factory&lt;Int, TvEntity&gt;
</code></pre>
<p>And this is the code in repository:</p>
<pre><code>override fun getWatchlistTv(sort: String): LiveData&lt;PagedList&lt;TvEntity&gt;&gt; {
    val query = getSortedTv(sort)
    return LivePagedListBuilder(localDataSource.getWatchlistTv(query), config).build() // line 94 error
}
</code></pre>
<p>And the error is:</p>
<pre><code>java.lang.IllegalArgumentException: DataSource.Factory must be provided

    at androidx.paging.LivePagedListBuilder.&lt;init&gt;(LivePagedListBuilder.java:63)
    at com.wiryadev.bajpmovie.data.FakeMovieRepository.getWatchlistTv(FakeMovieRepository.kt:94)
    at com.wiryadev.bajpmovie.data.MovieRepositoryTest.getWatchlistTv(MovieRepositoryTest.kt:90)
</code></pre>
<p><strong>Attempted Solution</strong></p>
<ul>
<li>Using <code>@RunWith(MockitoJUnitRunner::class)</code> for the class</li>
<li>Using <code>@Mock private lateinit var dataSourceMovieWatchList: DataSource.Factory&lt;Int, MovieEntity&gt;</code> instead of mock(class)</li>
</ul>
<p>The datasource mock is not null when i do not use RawQuery. Then, i think it is because RawQuery have different way to do this. So how to solve this? Any help is appreciated.</p>
<p>Additional Info: in case anyone need to know code i use (and works) for non-rawquery function:</p>
<pre><code>// Reposiory Test
@Test
fun discoverTv() {
    val dataSourceFactory = mock(DataSource.Factory::class.java) as DataSource.Factory&lt;Int, TvEntity&gt;
    `when`(local.discoverTv()).thenReturn(dataSourceFactory)
    movieRepository.discoverTv()

    val tvEntities = Resource.success(PagedListUtil.mockPagedList(DummyData.generateSeries()))

    verify(local).discoverTv()
    assertNotNull(tvEntities.data)
    assertEquals(tvResponse.size, tvEntities.data?.size)
}

// Dao
@Query(&quot;SELECT * FROM tv_entities&quot;)
fun discoverTv(): DataSource.Factory&lt;Int, TvEntity&gt;
</code></pre>
",https://stackoverflow.com/questions/65573201/error-datasource-factory-must-be-provided-when-unit-testing-rawquery,"['unit-testing', 'android-room']",281,False,1,0
Ceedling unit testing in a project with FreeRTOS dependency,"<p>I'm trying to implement unit tests in Unity (<a href=""http://www.throwtheswitch.org/unity"" rel=""nofollow noreferrer"">Learn more about Unity</a>) with a little help of CMock (<a href=""http://www.throwtheswitch.org/cmock"" rel=""nofollow noreferrer"">Learn more about CMock</a>). To do that I use the Ceedling tool which combines all Unity components into a one framework (<a href=""http://www.throwtheswitch.org/ceedling"" rel=""nofollow noreferrer"">Learn more about Ceedling</a>).</p>
<p>Everything works as expect until I add FreeRTOS to my project/testing. When added, Ceedling struggles to generate mocks for FreeRTOS components, like queue.c or list.c. It gives following error:</p>
<pre><code>Generating include list for queue.h...
build/temp/_queue.h:32:6: error: #error &quot;include FreeRTOS.h&quot; must appear in source files before &quot;include queue.h&quot;
   32 |     #error &quot;include FreeRTOS.h&quot; must appear in source files before &quot;include queue.h&quot;
      |      ^~~~~
In file included from build/temp/_queue.h:40:
../build/_deps/rtos.freertos-src/include/task.h:32:6: error: #error &quot;include FreeRTOS.h must appear in source files before include task.h&quot;
   32 |     #error &quot;include FreeRTOS.h must appear in source files before include task.h&quot;
      |      ^~~~~
In file included from ../build/_deps/rtos.freertos-src/include/task.h:35,
                 from build/temp/_queue.h:40:
../build/_deps/rtos.freertos-src/include/list.h:60:6: error: #error &quot;FreeRTOS.h must be included before list.h&quot;
   60 |     #error &quot;FreeRTOS.h must be included before list.h&quot;
      |      ^~~~~
</code></pre>
<p>For me, it looks like compiles queue.c file to find out list of functions which then should be mocked. That's ok but I don't know to force it to add FreeRTOS.h include while it cheks queue.c or list.c files.</p>
<p>I modified my <em>project.yml</em> file so paths to FreeRTOS are added and also FreeRTOS.h header is added to includes:</p>
<pre><code>:paths:
  :test:
    - +:test/**
    - -:test/support
    - ../
    - ../build/_deps/rtos.freertos-src/portable/GCC/ARM_CM4F
    - ../build/_deps/rtos.freertos-src/include
    - ../debug/
  :source:
    - src/**
    - ../build/_deps/rtos.freertos-src/portable/GCC/ARM_CM4F/**
    - ../build/_deps/rtos.freertos-src/include/**
    - ../build/_deps/rtos.freertos-src/**
  :support:
    - test/support
  :libraries: []

... skipped lines ...
... skipped lines ...
... skipped lines ...

:cmock:
  :mock_prefix: mock_
  :when_no_prototypes: :warn
  :enforce_strict_ordering: TRUE
  :plugins:
    - :ignore
    - :callback
  :treat_as:
    uint8:    HEX8
    uint16:   HEX16
    uint32:   UINT32
    int8:     INT8
    bool:     UINT8
  :includes_h_pre_orig_header:
    - FreeRTOS.h
  :includes_c_pre_header:
    - FreeRTOS.h
  :includes:
    - ../debug/assert.h
    - FreeRTOS.h
</code></pre>
<p>Even with added <em>includes_h_pre_orig_header</em>, <em>includes_c_pre_header</em> and <em>includes</em> it still fails like <em>FreeRTOS.h</em>. is not added before <em>queue.h</em> nor <em>list.h</em> headers.</p>
<p>I've found <a href=""https://github.com/ThrowTheSwitch/Ceedling/issues/579"" rel=""nofollow noreferrer"">similar problem</a>, the resolution there was to add Init and Verify calls to SetUp and Teardown methods in the test script and also to add Expect for calls related to FreeRTOS. I tried that without luck.</p>
<p>My test script is simple:</p>
<pre><code>#include &quot;unity.h&quot;
#include &quot;cmock.h&quot;

#include &quot;FreeRTOS.h&quot;
#include &quot;FreeRTOSConfig.h&quot;
#include &quot;mock_queue.h&quot;

#include &quot;test.h&quot;

void setUp(void) {
    mock_queue_Init();
    mock_list_Init();
    mock_task_Init();

}

void tearDown(void) {
    mock_queue_Verify();
    mock_list_Verify();
    mock_task_Verify();
}

void test_Rtos(void)
{
    xQueueCreate_Expect(8, 16);

    TestRtos();
}
</code></pre>
<p>The source file is also simple, just created to check if Ceedling will work with FreeRTOS:</p>
<pre><code>#include &quot;test.h&quot;

#include &quot;FreeRTOSConfig.h&quot;
#include &quot;FreeRTOS.h&quot;
#include &quot;queue.h&quot;

void TestRtos(void)
{
    QueueHandle_t someQueue = xQueueCreate(8, 16);
    uxQueueMessagesWaiting(someQueue);
}
</code></pre>
<p>I also looked at <a href=""https://github.com/aws/amazon-freertos/blob/main/libraries/abstractions/secure_sockets/utest/secure_sockets_utest.c"" rel=""nofollow noreferrer"">some examples from Amazon</a> but their <em>project.yml</em> doesn't even mention some paths or header files related to FreeRTOS. What I missed here?</p>
",https://stackoverflow.com/questions/67857711/ceedling-unit-testing-in-a-project-with-freertos-dependency,"['unit-testing', 'freertos', 'unity-test-framework', 'cmock', 'ceedling']",970,True,1,2
Setting up a unit testing environment in laravel 8,"<p>So I'm currently working on a larger web app using the laravel (v8) framework. Obviously I have a development environment and a production environment and soon even a staging environment. Since it's neccessary to test my classes (Models, Controllers, etc.) I have already written some unit tests. While doing that I encountered a problem: I really don't want to run my tests on the actual database (not even on the dev env) for various  reasons, to name the main two:</p>
<ol>
<li>data integrity</li>
<li>when I use a separate in-memory database for my tests they will run way faster.</li>
</ol>
<p>So my question is how can I set up my laravel application such that it uses a in memory database (sqlite) for running the unit tests and a regular mysql database for the regular app operations?</p>
",https://stackoverflow.com/questions/66107210/setting-up-a-unit-testing-environment-in-laravel-8,"['php', 'database', 'laravel', 'tdd', 'laravel-8']",2783,True,1,3
Why is this code not good for unit testing?,"<p>Apparently this code is not good for unit testing, I'm wondering why? What does it mean that a code is &quot;good&quot; for unit testing?</p>
<pre><code> public class B 
  {
        public int Y { get ; }
        public int X { get ; }
        public B() 
        {
          X = 3;
          Y = 7;
        }

        public B(int x) 
        {
          X = x;
          Y = 2 * x;
        }
  }

 public class A 
 {
        public B MyB { get ; set ; }
        public A() {MyB = new B ();}

        bool M1( int a, int b) 
        {
           if (a &gt; MyB.X) return false;
           if (b &lt; MyB.Y) return false;
           return true;
        }

        public B M2(int x) { return new B(x);}
}
</code></pre>
",https://stackoverflow.com/questions/68268578/why-is-this-code-not-good-for-unit-testing,"['c#', 'unit-testing']",70,True,1,1
Unit testing React components that access a global store,"<p>First off, please let me know if this is not the right place to ask this question or move it to the right place.</p>
<p>I am starting to write unit tests for some React components. One of them does not have any props but depends on a <code>store</code>:</p>
<pre><code>const PlayerSelector = () =&gt; {
  const classes = useStyles();
  const divRef = useRef(null);
  const [{ playerList }, dispatch] = useStore();
...
</code></pre>
<p>where <code>userStore()</code> comes from:</p>
<pre><code>export const StateContext = createContext(null);

export const StoreProvider = ({ initialState, reducer, children }) =&gt; (
  &lt;StateContext.Provider
    value={useReducer(reducer, initialState)}
  &gt;
    {children}
  &lt;/StateContext.Provider&gt;
);

export const useStore = () =&gt; useContext(StateContext);
</code></pre>
<p>My problem is that when I try to <code>render</code> <code>PlayerSelector</code> in the test file, I run into an error because the test does not have access to that store:</p>
<pre><code>it('loads component', () =&gt; {
  const { queryByRole } = render(&lt;PlayerSelector /&gt;);
  expect(queryByRole('button')).toHaveAttribute('aria-label');
});
</code></pre>
<p>The result is <code>TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))</code> pointing to this line:</p>
<pre><code>const [{ firmList }, dispatch] = useStore();
</code></pre>
<p>After googling a lot, I found some helpful resources indicating how to mock context - but not how to do the same for a reducer. I do not know if I am overcomplicating things and should probably find another way to test, or if I am missing an obvious answer. In any event, I would appreciate any tips or direction you can share.</p>
",https://stackoverflow.com/questions/65693674/unit-testing-react-components-that-access-a-global-store,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",600,True,1,1
Using Moq with Xunit - Unit testing .net core API,"<p>I'm trying to unit test a controller and I created a fake class that Implements an Interface.</p>
<pre><code>public class UnitTest1   
    {
        GrantProgramsController _controller;
        IBLGrantProgram _grant;
        readonly ILogger&lt;GrantProgramsController&gt; _logger;
        public UnitTest1()
        {
             _grant = new BLGrantProgramFake();
            _logger = new Logger&lt;GrantProgramsController&gt;(new NullLoggerFactory());
            _controller = new GrantProgramsController(_grant, _logger);
          
        }
        //tests for get method
        [Fact]
        public void Get_whencalled_returnsokresult()
        {
            // Act
            var okResult = _controller.GetGrantProgram();
            // Assert
            Assert.IsType&lt;OkObjectResult&gt;(okResult.Result);
        }
----------
</code></pre>
<p>But, I'm trying to use Moq framework and mock the interface instead of creating a fake implementation for the interface.</p>
<pre><code> public UnitTest1()
        {
            // _grant = new BLGrantProgramFake();
            _grant = new Mock&lt;BLGrantProgram&gt;();
            _logger = new Logger&lt;GrantProgramsController&gt;(new NullLoggerFactory());
            _controller = new GrantProgramsController(_grant, _logger);
          
        }
</code></pre>
<p>but error pops up for mocking. can somebody point out whether if this is not the way. I'm new to this. Thanks in advance.</p>
",https://stackoverflow.com/questions/66905065/using-moq-with-xunit-unit-testing-net-core-api,"['c#', 'unit-testing', 'moq', 'xunit']",390,True,1,1
C++/CMake/azure DevOps code coverage and unit testing,"<p>I’m developing few modules for my IoT project in C++, and CMake.
Finally, The module is built into a docker image, and pulled to the device, using azure IoT platform.
Also, i have a azure devops CI/CD pipeline to automate the deployment.</p>
<p>Now, i came across unit testing and codec overage.
I used gtest to do unit testing, and lcov to calculate code coverage,locally</p>
<p>But i want this to integrate with my pipeline.</p>
<p>Can someone suggest a best methode,or any alternative to do this.</p>
",https://stackoverflow.com/questions/66567260/c-cmake-azure-devops-code-coverage-and-unit-testing,"['c++', 'docker', 'azure-pipelines', 'code-coverage', 'googletest']",1151,True,1,1
Calling toast.show function in Unit Testing in Android Studio,"<p>I wish to test out my Alert toast class inside Unit Testing. However, when I call <code>alert_toast.show</code>, I get an error <code>Can't create handler inside thread that has not called Looper.prepare()</code>.</p>
<p>I understand that I cant call UI related elements such as Toast from worker class or other processing class, such as Unit Testings. However, is there a way I can call <code>alert_toast.show</code> inside my Unit Testings?</p>
<p>My alert_toast class code</p>
<pre><code>public class Custom_toasts {
    private Context context;
    private final int TOAST_TEXT_COLOR = R.color.white;
    private final int TOAST_TEXT_GRAVITY = Gravity.CENTER;
    private boolean toast_shown = false;
    private Toast toast;

    public Custom_toasts(Context context){
        this.context = context;

    }
    public Toast getToast(){
        return toast;
    }
    public void show_toast(String message,int toast_color){
        toast_shown = false;

        toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
        View view = toast.getView();

        //Gets the actual oval background of the Toast then sets the colour filter
        int background_color = ContextCompat.getColor(context, toast_color);
        view.getBackground().setColorFilter((background_color), PorterDuff.Mode.SRC_IN);

        //Gets the TextView from the Toast so it can be editted
        TextView text = view.findViewById(android.R.id.message);

        int string_color = ContextCompat.getColor(context, TOAST_TEXT_COLOR);
        text.setTextColor((string_color));
        text.setGravity(TOAST_TEXT_GRAVITY);

        toast.show();
        toast_shown = true;
    }
    public boolean getToast_shown(){
        return toast_shown;
    }

}

</code></pre>
<p>I've done a little research, and most answers show that I can show toast, but only if the toast is shown <strong>after</strong> I've clicked on a button on the UI, say clicking on a button will show a toast. As seen here: (<a href=""https://gist.github.com/brunodles/badaa6de2ad3a84138d517795f15efc7"" rel=""nofollow noreferrer"">https://gist.github.com/brunodles/badaa6de2ad3a84138d517795f15efc7</a>).</p>
<p>I don't want to create another layout.xml just to test this toast will show when alert_toast.show is called.</p>
",https://stackoverflow.com/questions/66613461/calling-toast-show-function-in-unit-testing-in-android-studio,"['android', 'unit-testing', 'toast', 'android-toast']",131,False,1,0
Unit testing a service with many dependencies in NestJS,"<p>When building API's in Nest, I often come across an issue where a particular API might need to make use of several Nest modules to do it's job.  I'd like to know if there's a better way to structure my modules so that unit testing them is easier.</p>
<p>For example, imagine we have an <code>OrderService</code>.  The <code>OrderService</code> makes use of a few different dependencies in order to do it's job:</p>
<ul>
<li>It uses the <code>ProductsService</code> in order to look up product details and prices.</li>
<li>It uses the <code>UsersService</code> in order to look up customer information, such as a Stripe customer ID.</li>
<li>It uses a Typeorm to handle writing the <code>Order</code> into the database</li>
<li>And finally, let's say it uses a <code>CouponsService</code> in order to look up and validate coupon details for the <code>Order</code>.</li>
</ul>
<p>For the sake of this example, let's just imagine each of these 4 dependencies to be it's own Nest module.</p>
<p>When it comes to unit testing the <code>OrdersService</code>, I'd then need to stub out 4 different dependencies.  This seems like a lot more work than it should be, and so I realized there must be a better way.</p>
<p>One thing that I've tried doing is creating separate helper files for setting up each services mocks.  This cuts down on the amount of boilerplate for each service that uses a particular dependency, but you still end up in a situation where 1 service might have 4 different dependencies.</p>
<p>Ideally, I'd like to implement some pattern or structure so that when I test a file, the dependencies are either really simple or automatic to mock, or a particular file only has 1 dependency at a time, without oversimplifying the system.</p>
<p>My question really boils down to:</p>
<p>How do you handle many dependencies like this in a Service, without ending up in a situation where testing a function requires you to mock 4+ methods.  I'd love to hear a Nest specific way to do this, but I'd also appreciate any generic software engineering examples or patterns to look into as well.</p>
",https://stackoverflow.com/questions/68434502/unit-testing-a-service-with-many-dependencies-in-nestjs,"['unit-testing', 'nestjs']",4197,True,1,1
How to configure unit testing for AnyLogic agent code?,"<p>How do you configure unit testing framework to help develop code that is part of AnyLogic agents?</p>
<p>To have a suitable test driven development rhythm, I need to be able to run all tests in a few seconds. I thought of exporting the project as a standalone application (jar) each time, but that's pretty slow.</p>
<p>I thought of trying to write all the code outside AnyLogic in separate classes, but there are many references to built-in AnyLogic classes, as well as various agents. My code would need to refer to these somehow, and I'm not sure how to do that except by writing the code inside AnyLogic.</p>
<p>I wonder if there's a way of adding the test runner as a dependency, and executing that test runner from within AnyLogic.</p>
<p>Does anyone have a setup that works nicely?</p>
",https://stackoverflow.com/questions/69005232/how-to-configure-unit-testing-for-anylogic-agent-code,"['unit-testing', 'junit', 'simulation', 'anylogic']",306,True,1,1
How to mock aws-amplify in react unit testing?,"<p>I am using <a href=""https://aws.amazon.com/ru/cognito/"" rel=""nofollow noreferrer"">AWS co</a>, <a href=""https://aws.amazon.com/ru/amplify/"" rel=""nofollow noreferrer"">Amplify</a> and <a href=""https://en.reactjs.org/"" rel=""nofollow noreferrer"">React</a>
I want to mock API.graphql imported from AWS.
This is my helper function for asynchronous functions
<code>useAsync.ts</code></p>
<pre><code>import { ErrorHandle } from '@app/components/ErrorHandle';
import { useCallback, useState } from 'react';

const getRetryWaitTime = (retryCount: number): number =&gt; {
  const httpRetryMaxWaitTime = 10 * 60 * 1000;
  const suggestedRetryWaitTime = 1000 * 2 ** retryCount;
  const retryWaitTime = Math.min(httpRetryMaxWaitTime, suggestedRetryWaitTime);
  return retryWaitTime;
};

const delay = (ms: number) =&gt; {
  return new Promise((resolve) =&gt; setTimeout(resolve, ms));
};

const retry = (retryFunc: () =&gt; Promise&lt;any&gt;, retryCount = -1): Promise&lt;any&gt; =&gt; {
  return retryFunc().catch((err: any) =&gt; {
    if (err &amp;&amp; retryCount) {
      retryCount -= 1;
      const waitTime = getRetryWaitTime(retryCount);
      return delay(waitTime).then(() =&gt; retry(retryFunc, retryCount));
    }
    throw err;
  });
};

export const useAsync = (
  asyncFunction,
  options: {
    onError?: (error, response) =&gt; any;
    onSuccess?: (data) =&gt; any;
    retryCount?: number;
  } = {},
) =&gt; {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  options.retryCount = options.retryCount || 1;
  options.onError = options.onError || ((error, response) =&gt; ErrorHandle(error, response));

  const execute = useCallback(
    async (payload?: any) =&gt; {
      setLoading(true);
      setData(null);
      setError(null);

      return retry(() =&gt; asyncFunction(payload), options.retryCount)
        .then((response) =&gt; {
          setData(response);
          if (options.onSuccess) {
            options.onSuccess(response);
          }
          setLoading(false);
          return { ok: true, data: response.data, response };
        })
        .catch((error: any) =&gt; {
          setError(error);
          if (options.onError) {
            options.onError(error, error ? error.response : null);
          }
          setLoading(false);
          return { error, ok: false, response: error, data: error };
        });
    },
    [asyncFunction, options],
  );

  return { execute, loading, data, error };
};
</code></pre>
<p>This is an example for my graphql mutations file.
<code>mutations.ts</code></p>
<pre><code>export const createLanguage = /* GraphQL */ `
  mutation CreateLanguage($input: CreateLanguageInput!, $condition: ModelLanguageConditionInput) {
    createLanguage(input: $input, condition: $condition) {
      id
      name
      code
      createdAt
      updatedAt
      createdBy
      updatedBy
      direction
      owner
    }
  }
`;
</code></pre>
<p>This is actual code for mocking and unit testing my useLanguages file
<code>useLanguages.ts</code></p>
<pre><code>import { createLanguage } from '@app/graphql/mutations';
import { API, graphqlOperation } from 'aws-amplify';
const useLanguages = () =&gt; {

  const [state, dispatch] = useStore();
  const languageAdd = useAsync(
   (value) =&gt; {
     const input: any = value;
     input.createdBy = state.user.attributes.email;
     input.updatedBy = state.user.attributes.email;
     return API.graphql(graphqlOperation(createLanguage, { input }));
   },
   {
     onSuccess: (result) =&gt; dispatch({ type: Actions.ADD_LANGUAGE, payload: result.data.createLanguage }),
   },
  );
  return { languageAdd };
}
</code></pre>
<p>I tried multiple variants <a href=""https://stackoverflow.com/questions/59215244/how-to-mock-aws-amplify-library-in-angular"">this</a> <a href=""https://stackoverflow.com/questions/60454057/how-do-i-properly-mock-amplify-for-unit-testing-in-jasmine"">that</a> and read a lot of documentations and articles like
<a href=""https://www.apollographql.com/docs/react/development-testing/testing/"" rel=""nofollow noreferrer"">this</a> <a href=""https://dev.to/rakannimer/testing-your-amplify-application-with-jest-and-cypress-1g0i"" rel=""nofollow noreferrer"">that</a></p>
",https://stackoverflow.com/questions/70150882/how-to-mock-aws-amplify-in-react-unit-testing,"['reactjs', 'unit-testing', 'graphql', 'aws-amplify']",606,True,1,1
"Unit testing - Flurl , How to mock flurl request response?","<p><strong>Main service implementation using flurl</strong></p>
<pre><code>Public async Task&lt;ApplicationItemVm&gt; UpdateOpportunityInfo(string optyNumber, UpdateOpportunityVm model, string token = &quot;&quot;)
    {
     
            var result = await &quot;https://api.com/*&quot;
                 .WithOAuthBearerToken(token)
                .PatchJsonAsync(model)
                .ReceiveJson&lt;ApplicationItemVm&gt;();
            return result;
   
    }
</code></pre>
<p><strong>Test Method using MS Test</strong></p>
<pre><code> [TestMethod]
    public async Task UpdateOppTest()
    {
       var updateOpportunityVm = new UpdateOpportunityVm
        {
            AboutYouIConfirm_c = true
        };

        var applicationItemVm = new ApplicationItemVm { AboutYouIConfirm_c=true};

        // fake &amp; record all http calls in the test subject
        using (var httpTest = new HttpTest())
        {
            // arrange
            httpTest.
                RespondWith(&quot;OK&quot;, 200).RespondWithJson(applicationItemVm);
            // act
            var application = await applicationService.UpdateOpportunityInfo(&quot;optyNumber&quot;, updateOpportunityVm, &quot;CloudToken&quot;);
            // assert
            httpTest.ShouldHaveCalled(&quot;https://api.com/*&quot;)
                .WithVerb(HttpMethod.Patch)
                .WithContentType(&quot;application/json&quot;);
        }

    }

   
</code></pre>
<p>After test method execution got following error</p>
<p>Response could nor deserilize</p>
<p>Let me know if I need to add more details.</p>
<p>Please suggest what's wrong I am doing.</p>
<p><strong>Expected Result</strong>
I want to mock request and response when I calling the main service method but unfortunately I not able to do</p>
",https://stackoverflow.com/questions/67445469/unit-testing-flurl-how-to-mock-flurl-request-response,"['c#', 'api', 'tdd', 'flurl']",3392,True,1,1
"Unit testing with Generic repository, UnitOfWork, NUnit and Moq","<p>There are lots of articles with a topic similar to this on StackOverflow, but I have not found any articles dedicated precisely to my situation.</p>
<p>I am trying to make unit tests with Moq and NUnit for Generic repository with Unit of Work pattern implemented.</p>
<p>Here is a code of the generic repository:</p>
<pre><code>public class GenericRepository&lt;TContext, TEntity&gt; : IGenericRepository&lt;TEntity&gt;
    where TEntity : class 
    where TContext : DbContext
{
    protected readonly TContext Context;

    public GenericRepository(TContext context)
    {
        Context = context;
    }

    public async Task&lt;TEntity&gt; Create(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException();
        }

        await Task.Run(() =&gt; Context.Set&lt;TEntity&gt;().Add(entity)).ConfigureAwait(false);
        await Context.SaveChangesAsync().ConfigureAwait(false);
        return entity;
    }

    public async Task&lt;IEnumerable&lt;TEntity&gt;&gt; CreateRange(IEnumerable&lt;TEntity&gt; entities)
    {
        if (entities == null)
        {
            throw new ArgumentNullException();
        }

        await Task.Run(() =&gt; Context.Set&lt;TEntity&gt;().AddRange(entities)).ConfigureAwait(false);
        await Context.SaveChangesAsync().ConfigureAwait(false);
        return entities;
    }

    public async Task&lt;TEntity&gt; Retrieve(object entityId)
    {
        return await Context.Set&lt;TEntity&gt;().FindAsync(entityId).ConfigureAwait(false);
    }

    public async Task&lt;IEnumerable&lt;TEntity&gt;&gt; Retrieve(Expression&lt;Func&lt;TEntity, bool&gt;&gt; predicate)
    {
        return await Task.Run(() =&gt; Context.Set&lt;TEntity&gt;().Where(predicate)).ConfigureAwait(false);
    }

    public async Task&lt;TEntity&gt; Update(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException();
        }

        await Task.Run(() =&gt;
        {
            Context.Set&lt;TEntity&gt;().AddOrUpdate(entity);
        }).ConfigureAwait(false);
        await Context.SaveChangesAsync().ConfigureAwait(false);
        return entity;
    }

    public async Task&lt;IEnumerable&lt;TEntity&gt;&gt; UpdateRange(IEnumerable&lt;TEntity&gt; entities)
    {
        var updateRange = entities as TEntity[] ?? entities.ToArray();
        if (updateRange.Any(entity =&gt; entity == null))
        {
            throw new ArgumentNullException();
        }

        foreach (var entity in updateRange)
        {
            await Task.Run(() =&gt;
            {
                Context.Set&lt;TEntity&gt;().AddOrUpdate(entity);
            }).ConfigureAwait(false);
        }
        await Context.SaveChangesAsync().ConfigureAwait(false);
        return updateRange;
    }

    public async Task&lt;TEntity&gt; SafeDelete(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException();
        }

        var propertySet = TrySetProperty(entity, &quot;Is_deleted&quot;, true);
        if (!propertySet)
        {
            throw new InvalidOperationException();
        }

        await Task.Run(() =&gt;
        {
            Context.Set&lt;TEntity&gt;().AddOrUpdate(entity);
        }).ConfigureAwait(false);
        await Context.SaveChangesAsync().ConfigureAwait(false);
        return entity;
    }

    public async Task&lt;IEnumerable&lt;TEntity&gt;&gt; SafeDeleteRange(IEnumerable&lt;TEntity&gt; entities)
    {
        var safeDeleteRange = entities as TEntity[] ?? entities.ToArray();
        if (safeDeleteRange.Any(entity =&gt; entity == null))
        {
            throw new ArgumentNullException();
        }

        var propertySet = false;
        foreach (var entity in safeDeleteRange)
        {
            propertySet = TrySetProperty(entity, &quot;Is_deleted&quot;, true);
        }
        if (!propertySet)
        {
            throw new InvalidOperationException();
        }

        foreach (var entity in safeDeleteRange)
        {
            await Task.Run(() =&gt;
            {
                Context.Set&lt;TEntity&gt;().AddOrUpdate(entity);
            }).ConfigureAwait(false);
        }
        await Context.SaveChangesAsync().ConfigureAwait(false);
        return safeDeleteRange;
    }

    public async Task&lt;TEntity&gt; Delete(TEntity entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException();
        }

        await Task.Run(() =&gt; Context.Set&lt;TEntity&gt;().Remove(entity));
        await Context.SaveChangesAsync().ConfigureAwait(false);
        return entity;
    }

    public async Task&lt;IEnumerable&lt;TEntity&gt;&gt; DeleteRange(IEnumerable&lt;TEntity&gt; entities)
    {
        if (entities == null)
        {
            throw new ArgumentNullException();
        }

        await Task.Run(() =&gt; Context.Set&lt;TEntity&gt;().RemoveRange(entities));
        await Context.SaveChangesAsync().ConfigureAwait(false);
        return entities;
    }

    private static bool TrySetProperty(object obj, string property, object value)
    {
        var prop = obj.GetType().GetProperty(property, BindingFlags.Public | BindingFlags.Instance);
        if (prop == null || !prop.CanWrite)
        {
            return false;
        }
        prop.SetValue(obj, value, null);
        return true;
    }
}
</code></pre>
<p>And a unit test class:</p>
<pre><code>[TestFixture]
public class GenericRepositoryUnitTests
{
    private Mock&lt;IDomainRepository&gt; _repo;
    private Mock&lt;IUnitOfWork&gt; _unitOfWork;
    private Mock&lt;IUnitOfWorkFactory&lt;DmsDbContext&gt;&gt; _unitOfWorkFactory;
    private Mock&lt;DmsDbContext&gt; _mockContext;
    private Mock&lt;DbSet&lt;Domain&gt;&gt; _mockSet;
    private List&lt;Domain&gt; _domains;
    private User _user;

    [SetUp]
    public void SetUp()
    {
        var userId = Guid.NewGuid();
        _user = new User
        {
            UsersId = userId,
            Username = &quot;Test&quot;,
            Password = &quot;Test&quot;,
            First_name = &quot;Test&quot;,
            Last_name = &quot;Test&quot;,
            Img = &quot;Test&quot;,
            Permissions = &quot;Test&quot;,
            Is_deleted = false
        };
        _domains = new List&lt;Domain&gt;
        {
            new Domain
            {
                DomainId = Guid.NewGuid(),
                Name = &quot;Test&quot;,
                Url = &quot;Test&quot;,
                Is_deleted = false,
                Users = new List&lt;User&gt;
                {
                    _user,
                    new User
                    {
                        UsersId = userId,
                        Username = &quot;Test&quot;,
                        Password = &quot;Test&quot;,
                        First_name = &quot;Test&quot;,
                        Last_name = &quot;Test&quot;,
                        Img = &quot;Test&quot;,
                        Permissions = &quot;Test&quot;,
                        Is_deleted = false
                    },
                    new User
                    {
                        UsersId = Guid.NewGuid(),
                        Username = &quot;Test&quot;,
                        Password = &quot;Test&quot;,
                        First_name = &quot;Test&quot;,
                        Last_name = &quot;Test&quot;,
                        Img = &quot;Test&quot;,
                        Permissions = &quot;Test&quot;,
                        Is_deleted = false
                    }
                }
            },
            new Domain
            {
                DomainId = Guid.NewGuid(),
                Name = &quot;Test&quot;,
                Url = &quot;Test&quot;,
                Is_deleted = false,
                Users = new List&lt;User&gt;
                {
                    _user,
                    new User
                    {
                        UsersId = userId,
                        Username = &quot;Test&quot;,
                        Password = &quot;Test&quot;,
                        First_name = &quot;Test&quot;,
                        Last_name = &quot;Test&quot;,
                        Img = &quot;Test&quot;,
                        Permissions = &quot;Test&quot;,
                        Is_deleted = false
                    },
                    new User
                    {
                        UsersId = Guid.NewGuid(),
                        Username = &quot;Test&quot;,
                        Password = &quot;Test&quot;,
                        First_name = &quot;Test&quot;,
                        Last_name = &quot;Test&quot;,
                        Img = &quot;Test&quot;,
                        Permissions = &quot;Test&quot;,
                        Is_deleted = false
                    }
                }
            },
            new Domain
            {
                DomainId = Guid.NewGuid(),
                Name = &quot;Test&quot;,
                Url = &quot;Test&quot;,
                Is_deleted = false,
                Users = new List&lt;User&gt;
                {
                    _user,
                    new User
                    {
                        UsersId = userId,
                        Username = &quot;Test&quot;,
                        Password = &quot;Test&quot;,
                        First_name = &quot;Test&quot;,
                        Last_name = &quot;Test&quot;,
                        Img = &quot;Test&quot;,
                        Permissions = &quot;Test&quot;,
                        Is_deleted = false
                    },
                    new User
                    {
                        UsersId = Guid.NewGuid(),
                        Username = &quot;Test&quot;,
                        Password = &quot;Test&quot;,
                        First_name = &quot;Test&quot;,
                        Last_name = &quot;Test&quot;,
                        Img = &quot;Test&quot;,
                        Permissions = &quot;Test&quot;,
                        Is_deleted = false
                    }
                }
            }
        };
        
        _mockSet = new Mock&lt;DbSet&lt;Domain&gt;&gt;();
        _mockSet.Setup(m =&gt; m.Add(It.IsAny&lt;Domain&gt;())).Returns(new Domain());

        _mockContext = new Mock&lt;DmsDbContext&gt;();
        _mockContext.Setup(m =&gt; m.Set&lt;Domain&gt;()).Returns(_mockSet.Object);

        _repo = new Mock&lt;IDomainRepository&gt;{CallBase = true};
        _repo.Setup(r =&gt; r.Context).Returns(_mockContext.Object);
        _repo.Setup(r =&gt; r.Create(It.IsAny&lt;Domain&gt;())).Returns(Task.FromResult(new Domain()));
        _repo.Setup(r =&gt; r.CreateRange(It.IsAny&lt;IEnumerable&lt;Domain&gt;&gt;()))
            .Returns(Task.FromResult(new List&lt;Domain&gt;().AsEnumerable()));
        _repo.Setup(r =&gt; r.Retrieve(It.IsAny&lt;Guid&gt;())).Returns(Task.FromResult(_domains.AsEnumerable().First()));
        _repo.Setup(r =&gt; r.Retrieve(pre =&gt; pre.Is_deleted == false))
            .Returns(Task.FromResult(_domains.AsEnumerable()));
        _repo.Setup(r =&gt; r.Update(It.IsAny&lt;Domain&gt;())).Returns(Task.FromResult(new Domain()));
        _repo.Setup(r =&gt; r.Delete(It.IsAny&lt;Domain&gt;())).Returns(Task.FromResult(new Domain()));
        _repo.Setup(r =&gt; r.DeleteRange(It.IsAny&lt;IEnumerable&lt;Domain&gt;&gt;()))
            .Returns(Task.FromResult(new List&lt;Domain&gt;().AsEnumerable()));

        _unitOfWork = new Mock&lt;IUnitOfWork&gt;();
        _unitOfWork.Setup(u =&gt; u.Domains).Returns(_repo.Object);

        _unitOfWorkFactory = new Mock&lt;IUnitOfWorkFactory&lt;DmsDbContext&gt;&gt;();
        _unitOfWorkFactory.Setup(u =&gt; u.Create(It.IsAny&lt;DmsDbContext&gt;())).Returns(_unitOfWork.Object);
    }

    [Test]
    public async Task Create_NewDomainObject_AddToDatabase()
    {
        // Arrange
        var domain = new Domain
        {
            DomainId = Guid.NewGuid(),
            Name = &quot;Test&quot;,
            Url = &quot;Test&quot;,
            Is_deleted = false,
            Users = new List&lt;User&gt; { _user }
        };

        // Act
        using var unitOfWork = _unitOfWorkFactory.Object.Create(_mockContext.Object);
        await unitOfWork.Domains.Create(domain);

        // Assert
        _repo.Verify(m =&gt; m.Context.Set&lt;Domain&gt;().Add(It.IsAny&lt;Domain&gt;()), Times.Once());
    }

    [Test]
    public void Retrieve_TestDomainObjectById_ReturnsValue()
    {
        //Arrange
        var domainId = Guid.NewGuid();

        using var unitOfWork = _unitOfWorkFactory.Object.Create(_mockContext.Object);
        // Act
        var domain = unitOfWork.Domains.Retrieve(domainId);

        // Assert
        Assert.NotNull(domain);
    }
</code></pre>
<p>I cannot make these tests working and have no idea, what is wrong.</p>
<p>Could someone please explain me, how to properly test the generic repository with a set of tools mentioned above?</p>
<p>Thanks in advance :)</p>
",https://stackoverflow.com/questions/68332103/unit-testing-with-generic-repository-unitofwork-nunit-and-moq,"['c#', 'entity-framework', 'nunit', 'moq', 'unit-of-work']",1786,True,0,1
Use unit-testing framework in matlab to test data,"<p>I would like to test datasets with a variable number of values. Each value should be tested and I would like to have a standardized output that I can read in afterward again. My used framework is Matlab.</p>
<p>Example:<br />
The use case would be a dataset which includes, e.g., 14 values that need to be testet. The comparison is already completely handled by my implementation. So I have 14 values, which I would like to compare against some tolerance or similar and get an output like</p>
<pre><code>1..14
ok value1
ok value2
not ok value3
...
ok value14
</code></pre>
<p>Current solution:<br />
I try to use the <a href=""https://de.mathworks.com/help/matlab/class-based-unit-tests.html?s_tid=CRUX_lftnav"" rel=""nofollow noreferrer"">unit-testing framework</a> and the according <a href=""https://de.mathworks.com/help/matlab/ref/matlab.unittest.plugins.tapplugin-class"" rel=""nofollow noreferrer"">TAPPlugin</a> that would produce exactly such an output (<a href=""https://testanything.org/"" rel=""nofollow noreferrer"">tap</a>), one for every unit-test. My main problem is that the unit-testing framework does not take any input parameters. I already read about parametrization, but I do not know how this helps me. I could put the values as a list into the parameter, but how to I pass them there? Afaik the unit-test class does not allow additional parameters during initialization, so I cannot include this in the program the way I want.</p>
<p>I would like to avoid to need to format the TAP output on my own, because it is already there, but only for unit-test objects. Unfortunately, I cannot see how to implement this wisely.</p>
<p>How can I implement the output of a test anything protocol where I have a variable amount of comparisons (values) in Matlab?</p>
",https://stackoverflow.com/questions/69191537/use-unit-testing-framework-in-matlab-to-test-data,"['matlab', 'testing']",82,False,0,1
Unit Testing Stops In Middle When I use Console.Readline(),"<p>I want to mock <code>Console.ReadLine()</code> using MOQ but I do not know how to do that. I tried to search on the internet but I couldn't find an appropriate answer.
I have tried various things but none had worked so far. This is just a demo file. I am working on a console app where I have to use <code>Console.ReadLine()</code>. But I do not know how to mock the function that is using <code>Console.ReadLine()</code>.</p>
<pre><code>using System;

namespace _Calci
{
    public class Operands
    {
        public int num1;
        public int num2;
    }

    public class ret
    {
        public virtual int _ret()
        { 
            return (Int32.Parse(Console.ReadLine()));
        }
    }

    public class Calci : ret
    {
        ret retObj = new ret();

        public int Multiply()
        {
            int result;
            int num1 = 4;
            result = retObj._ret() * num1;

            return result;
        }
    }
}
</code></pre>
<p>Unit Testing File:</p>
<pre><code>using Xunit;
using _Calci;
using Moq;

namespace Testings
{
    public class Testing
    {
        [Fact]
        public void MultiplyTesting()
        {
            Mock&lt;ret&gt; mockingVar = new Mock&lt;ret&gt;();
            mockingVar.Setup(x=&gt; x._ret()).Returns(()=&gt;5);
            Calci calciObj = new Calci();
            int expected = 20;
            int actual = calciObj.Multiply();
        
            Assert.Equal(expected, actual);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/67157278/unit-testing-stops-in-middle-when-i-use-console-readline,"['c#', 'unit-testing', 'mocking', 'moq']",67,True,0,1
Unit testing a defer statement within an async function,"<p>I am having a <code>defer</code> statement in my function that makes a server side request to get data. It is used to simply set the <code>isLoading</code> variable to <code>false</code>.</p>
<p>The thing is that I can not unit test that my method set the <code>isLoading</code> variable to <code>true</code> as the <code>defer</code> statement is inevitably triggered, which is causing my unit test to fail.</p>
<p>Is there a way to avoid the defer statement in my unit test to make sure that my variable <code>isLoading</code> is set?</p>
<pre><code>var isLoading = false

func triggerServerSideRequest() async -&gt; UserData {
  isLoading = true
  defer { isLoading = false }
  
  let user = await serverSideRequest.getUser()
  
  return user
}


func testServerSideRequest_requestIsTriggered_isLoadingIsTrue() async {
  _ = await sut.triggerServerSideRequest()
  let result = sut.isLoading

  // defer statement set isLoading to false
  // which cause my test to fail.
  XCTAssertTrue(result)
}
</code></pre>
",https://stackoverflow.com/questions/69282874/unit-testing-a-defer-statement-within-an-async-function,"['swift', 'unit-testing', 'async-await']",814,True,-1,1
Dart Aqueduct Rest API Unit Testing: Null Safety Error,"<p>I have created a simple REST Api using aqueduct and dart and I am attempting to run unit tests. However, I get the following error when trying to do so:</p>
<pre><code>Failed to load &quot;test\example_test.dart&quot;:
  Unable to spawn isolate: Error: Cannot run with sound null safety, because the following dependencies
  don't support null safety:

   - package:test_core
   - package:test_api
   - package:aqueduct_test
   - package:test
   - package:aqueduct
   - package:boolean_selector
   - package:logging
   - package:safe_config
   - package:matcher
   - package:crypto
   - package:password_hash
   - package:open_api
   - package:yaml
   - package:postgres
   - package:convert
   - package:codable
   - package:pub_semver
</code></pre>
<p>My Code is as follows:</p>
<p>channel.dart</p>
<pre><code>Controller get entryPoint {
    final router = Router();

    // Prefer to use `link` instead of `linkFunction`.
    // See: https://aqueduct.io/docs/http/request_controller/
    router.route(&quot;/example&quot;).linkFunction((request) async {
      return Response.ok({&quot;key&quot;: &quot;value&quot;});
    });
</code></pre>
<p>example_test.dart</p>
<pre><code>import 'harness/app.dart';

Future main() async {
  final harness = Harness()..install();

  test(&quot;GET /example returns 200 {'key': 'value'}&quot;, () async {
    expectResponse(await harness.agent.get(&quot;/example&quot;), 200, body: {&quot;key&quot;: &quot;value&quot;});
  });
}
</code></pre>
<p>Any help is appreciated</p>
",https://stackoverflow.com/questions/66646458/dart-aqueduct-rest-api-unit-testing-null-safety-error,"['rest', 'dart', 'aqueduct']",333,True,-1,1
Unit Testing: How to mock class variable in Dart?,"<p>can I get some suggestions on how can I mock <code>_appointmentCollection</code> variable in my <code>AppointmentService</code> class from below please ?</p>
<p>Here is my Service</p>
<pre><code>class AppointmentService {
  CollectionReference _appointmentCollection =
      FirebaseFirestore.instance.collection('appointments');

  Future&lt;bool&gt; scheduleAppointment(
    Appointment appointment,
    String useremail,
  ) async {
    Map&lt;String, dynamic&gt; appointmentInfo = appointment.toJson();
    try {
      await _appointmentCollection.doc(useremail).update({
        &quot;appointments&quot;: FieldValue.arrayUnion([appointmentInfo]),
      });
      return true;
    } catch (e) {
      return false;
    }
  }
}
</code></pre>
<p>I generated mocks for my class using flutter command <code>flutter pub run build_runner build</code></p>
<p>Now inside my test class I am trying to mock interaction of <code>_appointmentCollection.doc().....</code> with something like this
<code>when(mockAppointmentCollection.doc(any())).thenDoNothing()....</code>
but I am having hard time finding documentation related to how can I mock class variable in Dart.</p>
<p>Here is my test class I have at the moment</p>
<pre><code>@GenerateMocks([AppointmentService])
void main() {
  group(&quot;Test Appointment Service&quot;, () {
    test(&quot;schedule appointment should return true or false&quot;, () {
      final appointmentService = MockAppointmentService();
      // TODO: create mock of appointmentCollection variable
      expect(2, 2);
      // Above assertion is dummy one just to make sure I can run tests
    });
  });
}
</code></pre>
",https://stackoverflow.com/questions/70526693/unit-testing-how-to-mock-class-variable-in-dart,"['flutter', 'unit-testing', 'dart', 'mockito']",1414,False,0,0
JavaScript unit testing: Mocking other function from same module,"<p>I'm a novice JavaScript developer, and I'm having trouble with unit tests.
I am using Jest. I run the tests with Node.js 13.14.0 (I use the older version because I have Windows 7).
I had the following problem: I needed to mock a function from the same module where the function I'm testing is located. Simply put, the function calls another function from the same module, and I want to make sure it gets called. After searching on Google, I didn't find a complete solution. I liked the option of using the rewire plugin, but that breaks code coverage.
I export functions from the module as follows:</p>
<pre><code>module.exports = {
    functions...
}
</code></pre>
<p>Then I import them into the test file using require.</p>
<p>I saw that people who encountered this problem were advised some methods using ES6 modules, but I haven't been able to figure out how to make them work and I don't have a pressing need to use them in my project. So still, is there any full-fledged solution? Maybe I should use a different testing framework? And I don't really understand why this problem exists at all. Is using one function per module a common practice?</p>
<p>Anyway, I'm looking for some simple way, like using rewire:</p>
<pre><code>const otherFuncMock = module.__set__(otherFunc, jest.fn())

module.func() // calls otherFunc()

expect(otherFuncMock).toHaveBeenCalledTimes(1)
</code></pre>
",https://stackoverflow.com/questions/68515446/javascript-unit-testing-mocking-other-function-from-same-module,"['javascript', 'unit-testing', 'jestjs']",277,True,-1,1
"NgRx Effects Unit Testing: Test catchError Case, Without Marbles","<p>I'm trying to test a simple scenario, with the following Effect defined:</p>
<pre><code>import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { EMPTY } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { TodosService } from '../services/todos.service';
import { getTodos, getTodosSuccess } from './todos.actions';

@Injectable()
export class TodosEffects {
  loadTodos$ = createEffect(() =&gt;
    this.actions$.pipe(
      ofType(getTodos),
      mergeMap(() =&gt; this.todosService.getTodos()
        .pipe(
          map(todos =&gt; getTodosSuccess({ todoItems: todos })),
          catchError(() =&gt; EMPTY)
        )
      )
    )
  );

  constructor(
    private actions$: Actions,
    private todosService: TodosService
  ) { }
}
</code></pre>
<p>In this scenario, I am <strong>deliberately trying to get this working without Marbles</strong>. That is, without <code>hot()</code> <code>cold()</code> and so on. The few examples I've found online covering this topic just use those, but I'm looking for a way to do this without that for now.</p>
<p>Here's what I have in my test class so far. The mocking of <code>TodosService</code>, first test of the happy path, mock actions setup, etc. all work as expected. The second test, the one where I'm basically trying to confirm that the <code>EMPTY</code> observable is generated by <code>catchError</code>, is where I'm struggling:</p>
<pre><code>import { TestBed } from '@angular/core/testing';
import { TodosService } from '@app/services/todos.service';
import { provideMockActions } from '@ngrx/effects/testing';
import { Action } from '@ngrx/store';
import { EMPTY, Observable, of } from 'rxjs';
import { TodoItem } from './todo-model';
import { getTodos, getTodosSuccess } from './todos.actions';
import { TodosEffects } from './todos.effects';

let actions$ = new Observable&lt;Action&gt;();

let effects: TodosEffects;
let todosServiceSpy: jasmine.SpyObj&lt;TodosService&gt;;

describe('Todos Effects', () =&gt; {
  beforeEach(() =&gt; {
    const todosServiceSpyObject = jasmine.createSpyObj('TodosService', ['getTodos']);

    TestBed.configureTestingModule({
      providers: [
        TodosEffects,
        provideMockActions(() =&gt; actions$),
        { provide: TodosService, useValue: todosServiceSpyObject }
      ]
    });

    effects = TestBed.inject(TodosEffects);
    todosServiceSpy = TestBed.inject&lt;TodosService&gt;(TodosService) as jasmine.SpyObj&lt;TodosService&gt;;
  });

  it('should return successful todo get action with service results', () =&gt; {
    actions$ = of(getTodos());
    const expectedTodos: TodoItem[] = [{} as TodoItem];
    todosServiceSpy.getTodos.and.returnValue(of(expectedTodos));
    const expectedAction = getTodosSuccess({ todoItems: expectedTodos });

    effects.loadTodos$.subscribe(result =&gt; {
      expect(result).toEqual(expectedAction);
    });
  });

  it('should return EMPTY observable I think?', () =&gt; {
    actions$ = of(getTodos());
    // todosServiceSpy.getTodos.and.throwError('');
    todosServiceSpy.getTodos.and.returnValue(throwError(''));
    const expected = EMPTY;

    effects.loadTodos$.subscribe();
    // TODO: What to expect / etc. here?
  });
});
</code></pre>
<p>The <a href=""https://ngrx.io/guide/effects/testing"" rel=""nofollow noreferrer"">NgRx Effects testing documentation is unfortunately quite lacking here</a>, as it only posts snippets and edge case testing scenarios for examples.</p>
",https://stackoverflow.com/questions/67139044/ngrx-effects-unit-testing-test-catcherror-case-without-marbles,"['angular', 'unit-testing', 'rxjs', 'ngrx', 'ngrx-effects']",954,True,0,1
"Realm file for unit testing path permission (Xcode, Swift)","<p>Please forgive me if there is answered question similar to this. I tried to find any but couldn't find it</p>
<p>Hi guys, i am having problem with running Realm file for my unit testing</p>
<p>So i have moved the realm files to my project test folder</p>
<pre><code>   SampleAppTest
      + SampleAppTest.swift
      + SampleRealm.realm
</code></pre>
<p>I can successfully located the realm file, however, when I tried to instantiate the Realm connection, it threw me an error saying</p>
<p><code>Please use a path where your app has read-write permissions.</code></p>
<pre><code>    let bundle = Bundle(for: type(of: self))
    if let path = bundle.path(forResource: &quot;SampleRealm&quot;, ofType: &quot;realm&quot;) {
        let realmLocationURL = URL(string: path)
        
        let realmVersion: UInt64 = 1
        let config = Realm.Configuration(fileURL: realmLocationURL, schemaVersion: realmVersion, migrationBlock: { migration, oldSchemaVersion in
                if (oldSchemaVersion &lt; realmVersion) {}
            }
        )
        let realm = try! Realm(configuration: config) // throws error
    }
    else {
        print(&quot;path not found&quot;)
    }
</code></pre>
<p><code>Folder access in Finder -&gt; Get Info -&gt; Read &amp; Write</code></p>
<p>So in general, where can I put a file that my app has a permission to read-write? Is there a possible way to put within the project so that other team member that clone the project can also run the test with same realm file? Thank you</p>
",https://stackoverflow.com/questions/67897554/realm-file-for-unit-testing-path-permission-xcode-swift,"['ios', 'swift', 'realm']",235,False,0,1
Component unit testing with @Input with service observable subscription,"<p>I try to test(Jasmine/Karma) a component with an @Input which has subscription to service Observable and it's own property using combineLatest and have this error:</p>
<pre><code>*TypeError: You provided 'undefined' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.*
</code></pre>
<p>My code looks like this:</p>
<p><strong>Service</strong></p>
<pre><code>import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class Service {

  private _servicePropertySub = new BehaviorSubject&lt;[]&gt;([]);
  public get servicePropertyObs (): Observable&lt;[]&gt; {
    return this._servicePropertySub .asObservable();
  }
}
</code></pre>
<p><strong>Component</strong></p>
<pre><code>//...
@Component({
  //...
})
export class MyComponent implements OnDestroy {
private _componentProp = BehaviorSubject&lt;[]&gt;([]);
public get componentPropObs (): Observable&lt;[]&gt; {
        return this._componentProp.asObservable();
      }

public sum = 0;

@Input()
  public set myInput(value: V) {
    if (v) {
       combineLatest([
            this.service.servicePropertyObs,
            this.componentPropObs 
          ]).subscribe(([one, two]) =&gt; {
            this.sum = one + two;
        });
    }
  }

 constructor(private service: Service) {}


//...
</code></pre>
<p>Numbers in Observables are only for this example.</p>
<p>I want to test this component with @Input but I always have an error about undefined (error above) observable. I guess this is because I create spy for the service. How should this test been created in this case with using service in Input?</p>
",https://stackoverflow.com/questions/69018447/component-unit-testing-with-input-with-service-observable-subscription,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",347,True,0,1
How to mock views for unit testing in android,"<p>I have a helper class that I am using for TextInputEditText field validation in my application. It takes in an array of TextInputEditText with different tags. Firstly it sieve anyone that is empty and then proceed to validate them based on their different tag.
I want to be able to test the class and pass array of TextInputEditText with tags as a parameter but finding it hard to mock an TextInputEditText.</p>
<pre><code>class Validation private constructor(
    var respond:TextInputEditText,
    vararg edits: TextInputEditText
) {

    class Builder(
        var email: TextInputEditText? = null,
        var password: TextInputEditText? = null,
        var phoneNumber: TextInputEditText? = null,
        var respond:TextInputEditText?=null,
        vararg var edits: TextInputEditText

    ) {

        fun getEmptyField(edits: Array&lt;out TextInputEditText&gt;): Builder = apply {
            this.edits = edits
            for (edit in edits) {
                when {
                    edit.text?.isEmpty() == true -&gt; {
                        edit.error = &quot;${edit.tag} is required&quot;
                        this.respond = edit
                        return@apply
                    }
                    edit.tag.toString().contains(&quot;email&quot;, true) -&gt; {
                        this.email = edit
                    }
                    edit.tag.toString().contains(&quot;password&quot;, true) -&gt; {
                        this.password = edit
                    }
                    edit.tag.toString().contains(&quot;phone&quot;, true) -&gt; {
                        this.phoneNumber = edit
                    }
                }

            }
        }
        fun email() = apply {
            val emailPattern = Regex(&quot;&quot;&quot;^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*${'$'}&quot;&quot;&quot;)
            val matchedEmail = emailPattern.matches(this.email?.text.toString())
            if(matchedEmail){
                return@apply
            }
            else{
                this.respond = email
                this.respond?.error = &quot;Invalid&quot;
                return@apply
            }
        }
        fun password() = apply {
            val passwordPattern = Regex(&quot;&quot;&quot;^[a-zA-Z0-9@$!.%*#?&amp;]{6,}$&quot;&quot;&quot;)
            val matchedPassword = passwordPattern.matches(this.password?.text.toString())
            if(matchedPassword){
                return@apply
            }
            else{
                this.respond = password
                this.respond?.error = &quot;Invalid&quot;
                return@apply
            }
        }
        fun phone() = apply {
            val phonePattern = Regex(&quot;&quot;&quot;^(80|70|90|81)([12356709])\d{7}$&quot;&quot;&quot;)
            val matchedPhone = phonePattern.matches(this.phoneNumber.toString())
            if(matchedPhone){
                return@apply
            }
            else{
                this.respond = phoneNumber
                this.respond?.error = &quot;Invalid&quot;
                return@apply
            }

        }
        fun build():Validation? {
            val listOfDefaulters = arrayListOf&lt;TextInputEditText&gt;()
            for (edit in this.edits){
                if (edit.error != null){
                    listOfDefaulters.add(edit)
                    this.respond = listOfDefaulters[0]
                    this.respond!!.error = &quot;Invalid&quot;
                }
            }
           return respond?.let { Validation(it, *edits) }
        }
    }

}
</code></pre>
<p>How can I test this class and pass the stub.</p>
",https://stackoverflow.com/questions/66968713/how-to-mock-views-for-unit-testing-in-android,"['android', 'kotlin']",592,False,0,1
Unit testing async/await javascript with mocha and chai,"<p>Hey guys so I am currently working on this async function and writing unit test for this but it is not working it says <code>AssertionError: expected undefined to equal 'Everytime I think of coding, I am happy'</code> this is my code for the function:</p>
<pre><code>async function funcFour() {// async automatically returns a promise
let result = new Promise((resolve) =&gt; {// returns a new promise named result
    setTimeout(() =&gt; {
        resolve(`Everytime I think of coding, I am happy`);//resolve happens after three seconds
    }, 1500)
});
const response = await result;//closing resolve of new promise
console.log(response);//console.logging response of new promise
</code></pre>
<p><code>} funcFour();</code></p>
<p>And here is my unit test for it:</p>
<pre><code>describe(&quot;flirtFour()&quot;, () =&gt; {
it(&quot;Should return Everytime I think of coding, I am happy&quot;, async function () {
    return flirtFour().then(result =&gt; {
        expect(result).to.equal(&quot;Everytime I think of coding, I am happy&quot;)

    })
    

})
</code></pre>
<p><code>})</code></p>
<p>This is the first time I write unit test and I am trying to do it with async func so I am new to it. I really want to see how this is done so Thanks in advance :)</p>
",https://stackoverflow.com/questions/66719262/unit-testing-async-await-javascript-with-mocha-and-chai,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'chai']",259,True,0,1
&quot;RuntimeError: No application found.&quot; when unit testing with SQLAlchemy,"<p>I want to write unit test for some of the function of my application and for that I need to mock some SQLAlchemy call to my db. The problem is everytime I tried it gives me an error : &quot;RuntimeError: No application found.&quot;</p>
<p>This is the function I want to unit test :</p>
<pre><code>def update_user(user_uid, new_info):
    user = db.session.query(User).filter_by(uid=user_uid).first()

    # check if values are the same before changing
    # ensure unique username and email for all users
    if user.username != new_info[&quot;username&quot;]:
        if db.session.query(User).filter_by(username=new_info[&quot;username&quot;]).first() is not None:
            return {&quot;success&quot;: &quot;False&quot;, &quot;code&quot;: &quot;400&quot;, &quot;result&quot;: &quot;Username already taken&quot;}
        else:
            user.username = new_info[&quot;username&quot;]

    if user.email != new_info[&quot;email&quot;]:
        if db.session.query(User).filter_by(email=new_info[&quot;email&quot;]).first() is not None:
            return {&quot;success&quot;: &quot;False&quot;, &quot;code&quot;: &quot;400&quot;, &quot;result&quot;: &quot;Email already taken&quot;}
        else:
            user.email = new_info[&quot;email&quot;]

    if user.subscription_uid != new_info[&quot;subscription_uid&quot;]:
        user.subscription_uid = new_info[&quot;subscription_uid&quot;]

    # password only has length if being changed
    if len(new_info[&quot;password&quot;]):
        hashed = bcrypt.hashpw(new_info[&quot;password&quot;].encode(&quot;utf-8&quot;), bcrypt.gensalt())
        user.password = hashed.decode(&quot;utf-8&quot;)

    db.session.commit()
    return {&quot;success&quot;: &quot;True&quot;, &quot;code&quot;: &quot;200&quot;, &quot;result&quot;: &quot;User updated successfully&quot;}
</code></pre>
<p>I want to mock all the</p>
<pre><code>db.session
</code></pre>
<p>I tried doing this :</p>
<pre><code>class TestUser(unittest.TestCase):
    def test_update_user(self):
        user_db = {&quot;username&quot;: &quot;user&quot;, &quot;email&quot;: &quot;user@test.com&quot;, &quot;subscription_uid&quot;: &quot;1&quot;, &quot;password&quot;: &quot;&quot;}
        info_user_same_username = {&quot;username&quot;: &quot;user&quot;, &quot;email&quot;: &quot;new_user@test.com&quot;, &quot;subscription_uid&quot;: &quot;1&quot;, &quot;password&quot;: &quot;&quot;}
        info_user_same_email = {&quot;username&quot;: &quot;new_user&quot;, &quot;email&quot;: &quot;user@test.com&quot;, &quot;subscription_uid&quot;: &quot;1&quot;, &quot;password&quot;: &quot;&quot;}
        info_new_user = {&quot;username&quot;: &quot;new_user&quot;, &quot;email&quot;: &quot;new_user@test.com&quot;, &quot;subscription_uid&quot;: &quot;2&quot;, &quot;password&quot;: &quot;new_password&quot;}

        with mock.patch('flask_sqlalchemy._QueryProperty.__get__') as mock_user:
            mock_user.return_value = user_db

            response_correct = {&quot;success&quot;: &quot;True&quot;, &quot;code&quot;: &quot;200&quot;, &quot;result&quot;: &quot;User updated successfully&quot;}
            response_same_username = {&quot;success&quot;: &quot;False&quot;, &quot;code&quot;: &quot;400&quot;, &quot;result&quot;: &quot;Email already taken&quot;}
            response_same_email = {&quot;success&quot;: &quot;False&quot;, &quot;code&quot;: &quot;400&quot;, &quot;result&quot;: &quot;Username already taken&quot;}

            response = update_user(1, info_new_user)
            response_username = update_user(1, info_user_same_username)
            response_email = update_user(1, info_user_same_email)

            self.assertEqual(response, response_correct)
            self.assertEqual(response_username, response_same_username)
            self.assertEqual(response_email, response_same_email)
</code></pre>
<p>But I got this error :</p>
<pre><code>Traceback (most recent call last):
  File &quot;C:\Users\gusta\OneDrive\Documents\Pomelo\backend\pomelo_backend\tests\test_User.py&quot;, line 23, in test_update_user
    response = update_user(1, info_new_user)
  File &quot;C:\Users\gusta\OneDrive\Documents\Pomelo\backend\pomelo_backend\user.py&quot;, line 8, in update_user
    user = db.session.query(User).filter_by(uid=user_uid).first()
  File &quot;&lt;string&gt;&quot;, line 2, in query
  File &quot;C:\Users\gusta\OneDrive\Documents\Python\backend\lib\site-packages\sqlalchemy\orm\scoping.py&quot;, line 105, in _proxied
    return self.registry()
  File &quot;C:\Users\gusta\OneDrive\Documents\Python\backend\lib\site-packages\sqlalchemy\util\_collections.py&quot;, line 1010, in __call__
    return self.registry.setdefault(key, self.createfunc())
  File &quot;C:\Users\gusta\OneDrive\Documents\Python\backend\lib\site-packages\sqlalchemy\orm\session.py&quot;, line 4058, in __call__
    return self.class_(**local_kw)
  File &quot;C:\Users\gusta\OneDrive\Documents\Python\backend\lib\site-packages\flask_sqlalchemy\__init__.py&quot;, line 174, in __init__
    self.app = app = db.get_app()
  File &quot;C:\Users\gusta\OneDrive\Documents\Python\backend\lib\site-packages\flask_sqlalchemy\__init__.py&quot;, line 1043, in get_app
    'No application found. Either work inside a view function or push'
RuntimeError: No application found. Either work inside a view function or push an application context. See http://flask-sqlalchemy.pocoo.org/contexts/.
</code></pre>
<p>I tried some other methods:
- using <a href=""https://pypi.org/project/alchemy-mock/"" rel=""nofollow noreferrer"">alchemy-mock</a>
- @patch('flask_sqlalchemy._QueryProperty.<strong>get</strong>')</p>
<p>But always the same error message.</p>
",https://stackoverflow.com/questions/67313936/runtimeerror-no-application-found-when-unit-testing-with-sqlalchemy,"['python', 'unit-testing', 'flask-sqlalchemy']",256,False,-1,1
unit testing angular directive throws Access to XMLHttpRequest ...error,"<p>This is my directive</p>
<pre class=""lang-js prettyprint-override""><code>@Directive({
  selector: '[appTitleCase]',
})
export class TitleCaseDirective {
  @HostListener('change', ['$event']) onChange($event: Event) {
    const titleCaseValue = TextHelpers.convertToTitleCase(
      ($event.target as HTMLInputElement).value,
    );
    
    if (this.el.nativeElement.children.length &gt; 0) {
      (this.el.nativeElement.children[0] as HTMLInputElement).value =
        titleCaseValue;
    } else {
      (this.el.nativeElement as HTMLInputElement).value = titleCaseValue;
    }
    
    // must create an &quot;input&quot; event, if not, there are no change in your value (though ui is changed)
    const evt = document.createEvent('Event');
    evt.initEvent('input', false, true);
    $event.target.dispatchEvent(evt);
  }
    
  constructor(private el: ElementRef) {}
}
</code></pre>
<p>and this is my test</p>
<pre class=""lang-js prettyprint-override""><code>@Component({
  template: `
    &lt;div&gt;
      &lt;input id=&quot;txt&quot; type=&quot;text&quot; appTitleCase /&gt;
    &lt;/div&gt;
    &lt;div appTitleCase id=&quot;txtInput&quot;&gt;
      &lt;input type=&quot;text&quot; /&gt;
    &lt;/div&gt;
  `,
})
class TestTitleCaseComponent {}
    
describe('TitleCaseDirective', () =&gt; {
  let fixture: ComponentFixture&lt;TestTitleCaseComponent&gt;;
  let el: DebugElement;
    
  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [TestTitleCaseComponent, TitleCaseDirective],
    });
    
    fixture = TestBed.createComponent(TestTitleCaseComponent);
    el = fixture.debugElement;
  });
    
      
  it('should convert the text input value to title case when the input element has the directive', () =&gt; {
    const inputEl = el.query(By.css('#txt')).nativeElement;
    inputEl.value = 'hello';
    inputEl.dispatchEvent(new Event('change'));
    expect(inputEl.value).toEqual('Hello');
  });
    
  it('should convert the text input value to title case when the parent has the directive', () =&gt; {
    const parentEl = el.query(By.css('#txtInput')).nativeElement;
    const inputEl = parentEl.children[0];
    inputEl.value = 'hello';
    parentEl.dispatchEvent(new Event('change'));
    console.log(inputEl.value);
    // expect(inputEl.value).toEqual('Hello');
  });
});
</code></pre>
<p>the first two unit tests are passing, but the 3rd one is throwing this error:</p>
<blockquote>
<p><em>Access to XMLHttpRequest at 'ng:///TitleCaseDirective/%C9%B5dir.js' from origin 'http://localhost:9876' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.</em></p>
</blockquote>
<p>I'm not sure why CORS error is thrown here.</p>
",https://stackoverflow.com/questions/68469709/unit-testing-angular-directive-throws-access-to-xmlhttprequest-error,"['angular', 'angular-directive', 'angular-unit-test']",318,False,0,1
Android: Updating database from viewmodel and unit testing it,"<p>I have a method in my viewmodel that resets rows in the database.</p>
<pre><code> fun resetScores() {
    viewModelScope.launch {
       for(player in players){ 
           
           player.level = 1
           player.score = 0
           playerDao.updatePlayer(player) // updates the DB
       }
    }
}

var players = mutableListOf&lt;Player&gt;() -- &gt; players is a mutable list
</code></pre>
<p>I have this unit test for testing this method</p>
<pre><code>@Test
fun testResetScores() {
    val context = ApplicationProvider.getApplicationContext&lt;Context&gt;()
    val viewModel = PlayerViewModel(Phase10DataBase.getDatabase(context).playerDao)
    viewModel.players = mutableListOf(Player(1,&quot;Player1&quot;,5,100),
        Player(2,&quot;Player2&quot;,5,100),
        Player(3,&quot;Player3&quot;,5,100))
    assertEquals(viewModel.players.get(1).score, 100)
    viewModel.resetScores()
    assertEquals(viewModel.players.get(1).score, 100)
}
</code></pre>
<p>And this test pass whereas I expect it to fail.
Looks like the test is not waiting for the async DB operation to be finished before calling the assert.
What is the right way to test it or should the actual code resetScore need to be updated?</p>
",https://stackoverflow.com/questions/66891722/android-updating-database-from-viewmodel-and-unit-testing-it,"['android', 'junit', 'viewmodel', 'coroutine']",39,False,0,2
Unit testing in Docker image in Azure DevOps Pipeline,"<p>I have my <code>PR</code> pipeline with the following stages, one being dependent on the previous one:</p>
<ol>
<li><code>Changed</code>: basically determines what services have changed so it ignores testing and buildings ones that haven't.</li>
<li><code>UnitTesting</code>: installs services into agent pool and runs the unit tests <em>if</em> the services have changes to them.</li>
<li><code>BuildAndPush</code>: builds and pushes the <code>test-&lt;version&gt;</code> image to ACR if unit tests are passing.</li>
<li><code>IntegrationTesting</code>: honestly haven't figured this out yet, but it should pull all the images and deploy them somehow.</li>
<li><code>SeleniumTesting</code>: same as 4.</li>
</ol>
<p>Anyway, I had <code>UnitTesting</code> before <code>BuildAndPush</code> because I figured it was the quickest way to determine if a build is failing by cutting out the the time of building the image.</p>
<p>It is quicker:</p>
<ul>
<li><code>UnitTesting</code> one service takes about 1.5 minutes. The bulk of that is <code>npm install</code> and <code>npm build</code>. The tests themselves are only about 10-15 seconds.</li>
<li><code>BuildAndPush</code> one service takes about 2.25 minutes, but that doesn't including the testing portion.</li>
</ul>
<p>That being said I feel like the <code>UnitTesting</code> stage adds an additional 1.25 minutes per service that really isn't necessary: just <code>BuildAndPush</code> and unit test the image would actually be faster overall for the pipeline. The developer would know if the build is failing still well under 5 minutes.</p>
<p>So that is what I can't figure out:</p>
<p>How do you run unit tests in a Docker image in an Azure Pipeline?</p>
",https://stackoverflow.com/questions/66808980/unit-testing-in-docker-image-in-azure-devops-pipeline,"['node.js', 'azure', 'docker', 'azure-devops', 'azure-pipelines']",6993,True,1,1
Nunit unit testing of .Net core Web API 5.0,"<p>Is there any proper good resource to learn unit testing of .Net core Web API with EF Core/Dapper as ORM &amp; having N-tier architecture using NUnit ?? I am not finding any proper resource on controller testing, service layer testing, Data access layer testing, middleware testing etc</p>
",https://stackoverflow.com/questions/69584527/nunit-unit-testing-of-net-core-web-api-5-0,"['unit-testing', 'nunit', 'asp.net-core-webapi']",187,False,0,1
Unit testing spring boot | Failed to load application context,"<p>I am trying to run these tests but don't know for what reason i am having failed to load context exception.
Here is the stack trace</p>
<pre><code>Found multiple occurrences of org.json.JSONObject on the class path:

        jar:file:/C:/Users/Administrator/.gradle/caches/modules-2/files-2.1/org.json/json/20171018/36ced462c97f0845b4a7b266a25cebe95d18baa3/json-20171018.jar!/org/json/JSONObject.class
        jar:file:/C:/Users/Administrator/.gradle/caches/modules-2/files-2.1/com.vaadin.external.google/android-json/0.0.20131108.vaadin1/fa26d351fe62a6a17f5cda1287c1c6110dec413f/android-json-0.0.20131108.vaadin1.jar!/org/json/JSONObject.class

    You may wish to exclude one of them to ensure predictable runtime behavior
</code></pre>
<pre><code>java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:123)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:118)
    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.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.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
    at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
    at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:119)
    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:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    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:56)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [uk.co.stratasecurity.Application]; nested exception is java.io.FileNotFoundException:  (The system cannot find the path specified)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:184)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:319)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:236)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:275)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:95)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:706)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:532)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:126)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 50 more
Caused by: java.io.FileNotFoundException:  (The system cannot find the path specified)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.&lt;init&gt;(FileInputStream.java:138)
    at java.io.FileInputStream.&lt;init&gt;(FileInputStream.java:93)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
    at org.springframework.core.io.UrlResource.getInputStream(UrlResource.java:173)
    at org.springframework.core.io.support.EncodedResource.getInputStream(EncodedResource.java:159)
    at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:99)
    at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:73)
    at org.springframework.core.io.support.PropertiesLoaderUtils.loadProperties(PropertiesLoaderUtils.java:59)
    at org.springframework.core.io.support.ResourcePropertySource.&lt;init&gt;(ResourcePropertySource.java:67)
    at org.springframework.core.io.support.DefaultPropertySourceFactory.createPropertySource(DefaultPropertySourceFactory.java:37)
    at org.springframework.context.annotation.ConfigurationClassParser.processPropertySource(ConfigurationClassParser.java:455)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:274)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:245)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:194)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:298)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:245)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:202)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:170)
    ... 63 more
</code></pre>
<p>I have tried to use different test annotations but they didnt worked ... as far as i guess i should have some xml file for the test class??
I have seen this <a href=""https://stackoverflow.com/questions/48247413/spring-boot-controller-unit-test-failed-to-load-applicationcontext"">post</a> in this ApplicationService will do the work but in my case i dont have such service :/</p>
<p>And here is the test class.</p>
<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class LoginTest {
    @LocalServerPort
    private int port;
    
    @Test
    public void canLogin() {
        LoginPageDriver loginPageDriver = new LoginPageDriver(port);
        HomePageDriver homePageDriver = loginPageDriver.login(ADMIN_USERNAME, ADMIN_PASSWORD);

        loginPageDriver = homePageDriver.onMenu().logout();

        loginPageDriver.close();
    }
}
</code></pre>
",https://stackoverflow.com/questions/66955526/unit-testing-spring-boot-failed-to-load-application-context,"['java', 'spring', 'unit-testing', 'testing', 'junit']",617,False,0,0
Unit testing Azure functions v3 with xUnit and FakeItEasy,"<p>I am trying to implement some unit/integration testing to an Azure v3 HTTP trigger and am running into some issues with the process.</p>
<p>I previously wrote some testing for an API controller that was using syntax like so:</p>
<pre><code>TransactionResponse fakeResponse = new TransactionResponse { APIResponse = &quot;Okay&quot; };

var fakeSbus = A.Fake&lt;IServiceBusPlatform&gt;();
var fakeTransaction = A.Fake&lt;ITransaction&gt;();
            
A.CallTo(() =&gt; fakeTransaction.CreateTransaction(tran)).Returns(Task.FromResult(fakeResponse.APIResponse));
var controller = new SubmitController(fakeSbus, fakeTransaction);

var result = await controller._transaction.CreateTransaction(tran);
Assert.Equal(fakeResponse.APIResponse, result.ToString());
</code></pre>
<p>This worked fine because it was just testing a dbcontext and then asserting the return.</p>
<p>What I'm trying to do with the Azure function is evaluate the trigger based on the OkObjectResult but inside the function I have a few method calls and then logic that is dependant on the result of the method call. (returning a list, using a property of ListMember[0] to declare a var). Like so:</p>
<pre><code>var BatchResults = await _dbService.RetrieveBatch(session);
var CompanyID = BatchResults[0].CompanyID;
</code></pre>
<p>Update: For a little more clarity here is the whole testing function:</p>
<pre><code>var fakeBatch = new List&lt;RetrievedBatch&gt;();
fakeBatch.Add(new RetrievedBatch
{
  CompanyID = new Guid(),
});


var testResponse = new OkObjectResult(&quot;OKAY&quot;);
var request = A.Fake&lt;HttpRequest&gt;();
request.Method = &quot;POST&quot;;
            
byte[] byteArray = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(fakeTransaction));
MemoryStream stream = new MemoryStream(byteArray);
request.Body = stream;

var logger = A.Fake&lt;ILogger&gt;();

var fakeService = A.Fake&lt;IDbService&gt;();

A.CallTo(() =&gt; fakeService.RetrieveBatch(fakeTransaction)).Returns(fakeBatch);

var test = fakeService.RetrieveBatch(fakeTransaction);

var SM = new SessionManager(fakeService);
var response = await SM.Run(request, logger);
</code></pre>
<p>Oh and the method/type inside the interface is like this:</p>
<pre><code>Task&lt;List&lt;RetrievedBatch&gt;&gt; RetrieveBatch(Transaction session);
</code></pre>
<p>The error is occurring inside SM.Run(x,y). After a bit of debugging I can see that the A.CallTo is returning the correct results inside of the testing function but when the Azure function is being run the value is not carried over, which is the code breaking issue.</p>
<p>Any help would be appreciated as I've spent far too much time trying to work this out and all the examples out there are basic and unfortunately not very helpful in this scenario.</p>
",https://stackoverflow.com/questions/67674404/unit-testing-azure-functions-v3-with-xunit-and-fakeiteasy,"['c#', 'azure', 'unit-testing', 'fakeiteasy']",508,True,0,1
Unit testing a registration component with enzyme and jest,"<p>I am trying to unit test my registration component</p>
<pre><code>const Register = () =&gt; {
  const dispatch = useDispatch();
  const currentUser = useSelector((state: RootState) =&gt; state.user.currentUser);
  const errors = useSelector((state: RootState) =&gt; state.user.error);
  const loading = useSelector((state: RootState) =&gt; state.user.loading);
  const history = useHistory();
  const [email, setEmail] = useState&lt;UseState&gt;({ text: &quot;&quot;, touched: false });
  const [firstName, setFirstName] = useState&lt;UseState&gt;({
    text: &quot;&quot;,
    touched: false,
  });
  const [lastName, setLastName] = useState&lt;UseState&gt;({
    text: &quot;&quot;,
    touched: false,
  });
  const [password, setPassword] = useState&lt;UseState&gt;({
    text: &quot;&quot;,
    touched: false,
    isValid: null,
  });
  const [confirmPassword, setConfirmPassword] = useState&lt;UseState&gt;({
    text: &quot;&quot;,
    touched: false,
    isValid: null,
  });
  const [error, setError] = useState&lt;string&gt;(&quot;&quot;);

  useEffect(() =&gt; {
    //cleanup
    return () =&gt; {
      dispatch(clearError());
    };

    //eslint-disable-next-line
  }, []);

  useEffect(() =&gt; {
    if (currentUser &amp;&amp; currentUser.jwt) {
      setEmail({ text: &quot;&quot;, touched: false });
      setFirstName({ text: &quot;&quot;, touched: false });
      setLastName({ text: &quot;&quot;, touched: false });
      setPassword({ text: &quot;&quot;, touched: false });
      setConfirmPassword({ text: &quot;&quot;, touched: false });
    }   
    // eslint-disable-next-line
  }, [currentUser]);

  const handleRegister = (e: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {
    e.preventDefault();

    if (
      password.text === confirmPassword.text &amp;&amp;
      password.isValid &amp;&amp;
      confirmPassword.isValid
    ) {
      dispatch(
        signUpStart({
          email: email.text,
          firstName: firstName.text,
          lastName: lastName.text,
          password: password.text,
          confirmPassword: confirmPassword.text,
        })
      );
    } else {
      if (errors) {
        // cleanup
        return () =&gt; {
          dispatch(clearError());
        };
      }
      setError(&quot;Different passwords&quot;);
    }
  };

  return (
    &lt;section className={styles.register__page}&gt;
      {loading &amp;&amp; &lt;Loading /&gt;}
      &lt;article className={styles.register__wrapper}&gt;
        &lt;div className={styles.register__wrapper__header}&gt;
          &lt;h1&gt;Sign-up&lt;/h1&gt;
          &lt;p&gt;
            Text
          &lt;/p&gt;
        &lt;/div&gt;
        &lt;div className={styles.register__wrapper__body}&gt;
          &lt;form
            onSubmit={(e) =&gt; handleRegister(e)}
            className={styles.register__form}
          &gt;
            &lt;div className={styles.input__wrapper}&gt;
              &lt;FontAwesomeIcon icon={faUser} /&gt;
              &lt;div className={styles.input__wrapper__inner}&gt;
                &lt;input
                  required
                  type=&quot;email&quot;
                  name=&quot;email&quot;
                  id=&quot;email&quot;
                  value={email.text}
                  onChange={(e) =&gt;
                    setEmail({ text: e.target.value, touched: true })
                  }
                /&gt;
                &lt;label
                  htmlFor=&quot;email&quot;
                  placeholder=&quot;E-mail&quot;
                  className={email.text !== &quot;&quot; ? styles.filled : undefined}
                &gt;
                  E-mail
                &lt;/label&gt;
              &lt;/div&gt;
            &lt;/div&gt;
            &lt;div className={styles.input__wrapper}&gt;
              &lt;FontAwesomeIcon icon={faUser} /&gt;
              &lt;div className={styles.input__wrapper__inner}&gt;
                &lt;input
                  type=&quot;text&quot;
                  name=&quot;firstname&quot;
                  id=&quot;firstname&quot;
                  value={firstName.text}
                  onChange={(e) =&gt;
                    setFirstName({ text: e.target.value, touched: true })
                  }
                /&gt;
                &lt;label
                  htmlFor=&quot;firstname&quot;
                  className={firstName.text !== &quot;&quot; ? styles.filled : undefined}
                &gt;
                  Name
                &lt;/label&gt;
              &lt;/div&gt;
            &lt;/div&gt;
            &lt;div className={styles.input__wrapper}&gt;
              &lt;FontAwesomeIcon icon={faUser} /&gt;
              &lt;div className={styles.input__wrapper__inner}&gt;
                &lt;input
                  type=&quot;text&quot;
                  name=&quot;lastname&quot;
                  id=&quot;lastname&quot;
                  value={lastName.text}
                  onChange={(e) =&gt;
                    setLastName({ text: e.target.value, touched: true })
                  }
                /&gt;
                &lt;label
                  htmlFor=&quot;lastname&quot;
                  className={lastName.text !== &quot;&quot; ? styles.filled : undefined}
                &gt;
                  Surname
                &lt;/label&gt;
              &lt;/div&gt;
            &lt;/div&gt;
            &lt;div
              className={[
                styles.input__wrapper,
                !password.isValid &amp;&amp; password.touched
                  ? styles.wrong
                  : styles.input__wrapper,
              ].join(&quot; &quot;)}
            &gt;
              &lt;FontAwesomeIcon icon={faKey} /&gt;
              {!password.isValid &amp;&amp; password.touched &amp;&amp; (
                &lt;FontAwesomeIcon
                  icon={faExclamationCircle}
                  className={styles.errorIcon}
                /&gt;
              )}
              &lt;div className={styles.input__wrapper__inner}&gt;
                &lt;input
                  required
                  type=&quot;password&quot;
                  name=&quot;password&quot;
                  id=&quot;password&quot;
                  value={password.text}
                  onChange={(e) =&gt; validateOnChange(e)}
                /&gt;
                &lt;label
                  htmlFor=&quot;password&quot;
                  className={password.text !== &quot;&quot; ? styles.filled : undefined}
                &gt;
                  Hasło
                &lt;/label&gt;
              &lt;/div&gt;
            &lt;/div&gt;
            &lt;div
              className={[
                styles.input__wrapper,
                !confirmPassword.isValid &amp;&amp; confirmPassword.touched
                  ? styles.wrong
                  : styles.input__wrapper,
              ].join(&quot; &quot;)}
            &gt;
              &lt;FontAwesomeIcon icon={faKey} /&gt;
              {!confirmPassword.isValid &amp;&amp; confirmPassword.touched &amp;&amp; (
                &lt;FontAwesomeIcon
                  icon={faExclamationCircle}
                  className={styles.errorIcon}
                /&gt;
              )}
              &lt;div className={styles.input__wrapper__inner}&gt;
                &lt;input
                  required
                  type=&quot;password&quot;
                  name=&quot;confirmPassword&quot;
                  id=&quot;confirmPassword&quot;
                  value={confirmPassword.text}
                  onChange={(e) =&gt; validateOnChange(e)}
                /&gt;
                &lt;label
                  htmlFor=&quot;confirmPassword&quot;
                  className={
                    confirmPassword.text !== &quot;&quot; ? styles.filled : undefined
                  }
                &gt;
                  Confirm password
                &lt;/label&gt;
              &lt;/div&gt;
            &lt;/div&gt;
            &lt;button type=&quot;submit&quot; className={styles.register__btn}&gt;
              Rejestruj
            &lt;/button&gt;
            {errors &amp;&amp; &lt;p className={styles.error}&gt;{errors}&lt;/p&gt;}
            {error !== &quot;&quot; &amp;&amp; &lt;p className={styles.error}&gt;{error}&lt;/p&gt;}
          &lt;/form&gt;
          &lt;p className={styles.login__link}&gt;
            Text
          &lt;/p&gt;
        &lt;/div&gt;
      &lt;/article&gt;
    &lt;/section&gt;
  );
};

export default Register;
</code></pre>
<p>I tried several different approaches, however, none of them have worked for me so far. I ended up with something like that:</p>
<pre><code>describe(&quot;Register /&quot;, () =&gt; {
    it('register with proper credentials', () =&gt; {
        const history = createMemoryHistory();
        const component = mount(&lt;Provider store={store}&gt;&lt;Router history={history}&gt;&lt;Register /&gt;&lt;/Router&gt;&lt;/Provider&gt;);
        component.find('input[name=&quot;firstname&quot;]').simulate('change', {target: {name: 'firstname', value: 'Test'}});
        component.find('input[name=&quot;lastname&quot;]').simulate('change', {target: {name: 'lastname', value: 'Test'}});
        component.find('input[name=&quot;password&quot;]').simulate('change', {target: {name: 'password', value: 'TestSecret'}});
        component.find('input[name=&quot;email&quot;]').simulate('change', {target: {name: 'email', value: 'test@test.com'}});
        })
</code></pre>
<p>After that I wanted to assert if the fields are filled in correctly and if the handleRegister is called but the fields are returning an empty string (&quot;{}&quot;) and that's where I got stuck. What am I doing wrong?</p>
",https://stackoverflow.com/questions/68340275/unit-testing-a-registration-component-with-enzyme-and-jest,"['reactjs', 'unit-testing', 'enzyme']",98,False,0,0
Suppress react error in console log during unit testing,"<p>I'm experiencing an error when I am unit testing:</p>
<pre><code>console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
  Error: Uncaught [Error: Invariant failed: You should not use &lt;Redirect&gt; outside a &lt;Router&gt;]
</code></pre>
<p>I know that this is due to the component I am testing having an un-wrapped <code>&lt;Redirect&gt;</code> element:</p>
<pre><code>return &lt;Redirect to={`${myRedirUrl}`}/&gt;;
</code></pre>
<p>however this is being returned as part of a fully-fledged and wrapped <code>&lt;ConnectedRouter&gt;</code> so there is no issue with the app actually working. This complaint is merely during unit testing.</p>
<p>Is there anyway in which I can suppress this message during testing? The unit test is passing as I have been checking during trial runs, it's just annoying that the result is being buried...</p>
<hr />
<p><strong>Component.jsx</strong></p>
<pre><code>export const MyComp = () =&gt; {
  // /my-url will cause redirect to RedirectComponent
  return &lt;Redirect to=&quot;/my-url&quot; /&gt;
}
</code></pre>
<p><strong>Test</strong></p>
<pre><code>it('should redirect without error', () =&gt; {
  const rendered = render(
      &lt;Provider store={store(state)}&gt;
          &lt;BrowserRouter&gt;
              &lt;MyComponent /&gt;
              &lt;Route path='/my-url'&gt;Redirected&lt;/Route&gt;
           &lt;/BrowserRouter&gt;
       &lt;/Provider&gt;
  );

  expect(rendered.container.textContent).toBe('Redirected');
});
</code></pre>
<p>This test passes as I have told it to expect the mock component, however I am getting the error as above due to the <code>MyComp</code> not having a wrapped <code>&lt;Redirect&gt;</code></p>
",https://stackoverflow.com/questions/66210330/suppress-react-error-in-console-log-during-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'error-handling']",183,False,0,0
Angular unit testing of service using HttpClientTestingModule and HttpTestingController,"<p>I have a problem with testing my application. Mainly my problem is with URL. This is my testBed:</p>
<pre class=""lang-ts prettyprint-override""><code>  let service: AdnimistrationSiteService;
  let httpClient: HttpClient
  let httpClientMock: HttpTestingController;
  let helper : Helper;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule
      ],
      providers: [AdnimistrationSiteService]
    });
    httpClient = getTestBed().inject(HttpClient);
    service = getTestBed().inject(AdnimistrationSiteService);
    httpClientMock = getTestBed().inject(HttpTestingController)
    helper = new Helper();
  });

  afterEach(() =&gt; {
    httpClientMock.verify();
  });

  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });
</code></pre>
<p>The call I am trying to test looks like this:</p>
<pre class=""lang-ts prettyprint-override""><code> getAllFilesWithIcons(id_name: string): Observable&lt;any[]&gt; {
    let parameters = new HttpParams().set(&quot;id_name&quot;, id_name);
    let url = environment.baseUrl + &quot;/api/v1/example/get_example_api&quot;;
    return this.http.get(url, {params: parameters})
    .pipe(
      map(products =&gt; products[&quot;result&quot;]),
      catchError(err =&gt; {
        console.log(err);
        return throwError(err)
      })
    )
  }
</code></pre>
<p>I don't really understand what I have to test here. Whether to make a call real to the server or mocked. If so, I do not know about the parameters. I have tried many times but I have an error every time.</p>
<p>My test looks like this:</p>
<pre class=""lang-ts prettyprint-override""><code>    it(&quot;Should return data&quot;, () =&gt; {
        const testData = [
          {'element_filename': 'something', 'icon_symbol': 'symbol_test', &quot;inventory_id&quot;: &quot;inv &quot; , &quot;sensors&quot;: [&quot;abc &quot; , &quot;eff &quot;]}
        ]
        service.getAllFilesWithIcons(&quot;id_name&quot;).subscribe((id) =&gt; {
          console.log(id)
          console.log(testData)
          expect(testData).toBe(id, &quot;should mocked data&quot;)
        })
        const req = httpClientMock.expectOne(environment.baseUrl + &quot;/api/v1/example/get_example_api&quot; + '?id_name=id_name')

        // expect(req.cancelled).toBeFalsy()
        expect(req.request.method).toBe(&quot;GET&quot;)
        req.flush(testData)
    })
</code></pre>
<p>But still in this case &quot;id&quot; is undefined all the time.</p>
",https://stackoverflow.com/questions/69541520/angular-unit-testing-of-service-using-httpclienttestingmodule-and-httptestingcon,"['angular', 'jasmine', 'karma-jasmine', 'angular-test', 'angular-testing-library']",1001,True,0,1
Gitlab - my unit testing not working because of TLS10,"<p>I got the following error :</p>
<p>Test &gt; test xxxx &gt; Test.test mytests [Id: xxxx, resultOut: xxxx , #7] STANDARD_ERROR
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: &quot;The server selected protocol version TLS10 is not accepted by client preferences [TLS13, TLS12]&quot;. ClientConnectionId:xxxxxxxxxxxxxxxxxxxx
at com.microsoft.sqlserver.jdbc.SQLServerConnection.terminate(SQLServerConnection.java:3422)</p>
<p>I looked at many of the open topics and solutions, but :</p>
<ul>
<li>I can't upgrade the SQL server from TLS10 to TLS12 nor TLS13 ( this is refused because old SQL server )</li>
<li>I can't downgrade to java 7, I need to use java 11</li>
<li>I upgraded to the latest version for jre11
compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '9.4.0.jre11'</li>
</ul>
<p>The gitlab-ci.yml code :</p>
<pre><code>test:
    stage: test
    tags:
      - Linux
    script:
        - echo &quot;Test stage&quot;
        - ./gradlew test -i
</code></pre>
<p>These tests work perfectly on my laptop with my remote connection.
But it doesn't work on (internal ) GitLab with my remote connection</p>
<p>I hope there is a solution...</p>
",https://stackoverflow.com/questions/69257520/gitlab-my-unit-testing-not-working-because-of-tls10,"['java', 'sql-server', 'unit-testing', 'ssl']",193,False,0,1
How to mock a service in Angular unit testing?,"<p>I have the following service subscription which is promise</p>
<pre><code>getTaskData = async() {
line 1   let response = this.getTaskSV.getTaskData().toPromise();
line 2   this.loading = false;
}
</code></pre>
<p>I tried like below,</p>
<pre><code>   it('should load getTaskData', async () =&gt; {
     let getTaskSV= TestBed.inject(getTaskSV);
     spyOn(getTaskSV, 'getTaskData').and.returnValue(of([{name: 'test1'}, {name: 'test2'}]));
     component.getTaskData();
     fixture.detectChanges()
  });
</code></pre>
<p>When I run the above test case I see the line 1 and 2 are not covered. I am actually new to the test cases. Can any one please help me how to mock this service. Thanks in advance.</p>
",https://stackoverflow.com/questions/68299604/how-to-mock-a-service-in-angular-unit-testing,"['javascript', 'angular', 'jasmine', 'karma-jasmine', 'angular-unit-test']",345,False,0,1
Problem during isolated controller unit testing / NestJS / JestJS / Typescript,"<p>I would like to write unit test for my http controller with mocked service.
Main idea is to mock service and provide some mock implementation for it.</p>
<p>Here is my setup to do this (I will skip some imports statements and useless in our context decorators to reduce code lines amount):</p>
<p><strong>create-user.http.controller.ts:</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>export class CreateUserHttpController {
  constructor(
    @Inject(createUserSymbol)
    private readonly createUser: CreateUserService,
  ) {}

  @Post(appRoutes.users.root)
  async create(@Body() body: CreateUserRequest): Promise&lt;IdResponse&gt; {
    const command = new CreateUserCommand({
      email: body.email,
      name: body.name,
      password: body.password,
      role: 'user',
    });

    const id = await this.createUser.createUser(command);

    return new IdResponse(id.value);
  }
}</code></pre>
</div>
</div>
</p>
<p><strong>create-user.http.controller.spec.ts:</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import { Test } from '@nestjs/testing';

import { ID } from 'src/core/value-objects/id.value-object';

import { createUserSymbol } from '../../user.providers';
import { CreateUserHttpController } from './create-user.http.controller';
import { CreateUserService } from './create-user.service';

jest.mock('./create-user.service', () =&gt; {
  return {
    CreateUserService: jest.fn().mockImplementation(() =&gt; {
      return {
        createUser: () =&gt; {
          console.log('ts');
        },
      };
    }),
  };
});

describe('CreateUserHttpController', () =&gt; {
  let createUserHttpController: CreateUserHttpController;
  let createUserService: CreateUserService;

  beforeAll(async () =&gt; {
    const moduleRef = await Test.createTestingModule({
      controllers: [CreateUserHttpController],
      providers: [
        {
          provide: createUserSymbol,
          useValue: CreateUserService,
        },
      ],
    }).compile();

    createUserHttpController = await moduleRef.resolve(
      CreateUserHttpController,
    );
    createUserService = await moduleRef.resolve(createUserSymbol);
  });

  describe('create', () =&gt; {
    it('should call once createUser method in service', async () =&gt; {
      const expectedResult = new ID('test');

      jest
        .spyOn(createUserService, 'createUser')
        .mockResolvedValue(expectedResult);

      const result = await createUserHttpController.create({
        email: 'test@mail.ru',
        name: 'test',
        password: 'test',
      });

      expect(createUserService).toHaveBeenCalledTimes(1);
    });
  });
});</code></pre>
</div>
</div>
</p>
<p>And with this setup I have an issue like this:
(<em>Cannot spy property because it is not a function; undefined given instead</em>)</p>
<p><a href=""https://i.stack.imgur.com/raxiN.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/raxiN.png"" alt=""enter image description here"" /></a></p>
<p>I've tried to console.log mocked service instance to check if there is a 'createUser' property. And it looks like it's not there.</p>
<p><a href=""https://i.stack.imgur.com/4tDxK.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4tDxK.png"" alt=""enter image description here"" /></a></p>
<p>I've checked jest docs deeply, especially here - <a href=""https://jestjs.io/docs/es6-class-mocks#mocking-non-default-class-exports"" rel=""nofollow noreferrer"">jest doc for mocking non-default class exports</a>. I've spend like 6 hours and tried all available options, but result is still the same.</p>
<p>Also I've checked guide here - <a href=""https://medium.com/@jackallcock97/unit-testing-with-nestjs-and-jest-a-comprehensive-tutorial-464910f6c6ba"" rel=""nofollow noreferrer"">medium guide</a>. This lucky guy seems to have identical setup and no any issues.</p>
<p>So, from my perspective it looks like <code>jest.mock</code> function for some reason isn't initialize mocked service with <code>createUser</code> method.</p>
<p>Any help appreciated! Thanks in advance.</p>
",https://stackoverflow.com/questions/68330931/problem-during-isolated-controller-unit-testing-nestjs-jestjs-typescript,"['typescript', 'unit-testing', 'jestjs', 'mocking', 'nestjs']",1152,True,0,1
Twilio API mocking unit testing in Nestjs using Jest,"<p>I have this <code>twilio.service.ts</code> file. I want to write a unit test in <code>twilio.service.spec.ts</code> for two cases in which the verification OTP has been sent successfully or failed with missing parameters.</p>
<p><strong>twilio.services.ts</strong>:</p>
<pre><code>  async startVerification(
   startVerificationDto: StartVerificationDto
   ) {
    try {
      const verificationResponse = await this.twilioClient.verify
        .services(&quot;TWILIO_VERIFY_SERVICE_SID&quot;)
        .verifications.create({
          to: `+91${sendVerificationCodeDto.phoneNumber}`,
          channel: &quot;sms&quot;,
          locale: &quot;en&quot;,
        });
      return verificationResponse;
    } catch (error) {
      throw new BadRequestException(&quot;Failed sending OTP&quot;);
    }
  }
</code></pre>
<p>It tried so far:</p>
<pre><code>it(&quot;Should be able to send verification code on mobile number&quot;, async () =&gt; {
    const actualRes = await controller.startVerification({
      phoneNumber: &quot;xxxxxxxxxxx&quot;,
    });

    expect(twilioService.twilioClient.verify.services).toBeCalledWith(
      &quot;TWILIO_VERIFY_SERVICE_SID&quot;
    );

    expect(actualRes).toEqual({
      sid: &quot;VA_TWILIO_VERIFY_SERVICE_SID&quot;,
    });
  });



  it(&quot;Should return error if required parameters are missing&quot;, async () =&gt; {

    expect(twilioService.twilioClient.verify.services).not.toBeCalledWith(
      &quot;TWILIO_VERIFY_SERVICE_SID&quot;
    );

    try {
      await controller.startVerification({
        phoneNumber: &quot;xxxxxxxxxxx&quot;,
      });
    } catch (e) {
      expect(e.message).toBe(&quot;Failed sending OTP&quot;);
    }
  });
</code></pre>
<p>My main concern is: how to mock nested functions of Twilio (verify&gt;service&gt;verification&gt;create).
Also, after mocking how do I call or use that in spec.ts file.</p>
",https://stackoverflow.com/questions/67897011/twilio-api-mocking-unit-testing-in-nestjs-using-jest,"['typescript', 'unit-testing', 'jestjs', 'twilio', 'twilio-api']",806,True,0,1
Can&#39;t unit testing a method that gets values app.config,"<p>In a .NET Core 3.1 console application I have some methods that use app.config to get some values (System.Configuration.ConfigurationManager.AppSettings[&quot;my-key&quot;]). It gets the values correctly when running the application.</p>
<p>However when I try to unitTest (with Visual Studio TestTools) these methods the values I get are null. I tried creating an app.config file inside the unitTest project and using ConfigurationManager directly in the unitTest method, still null values.</p>
<p>I read there are some workarounds like mocking the configuration or passing these values as parameters to these methods, however I don't think these workarounds are the cleanest thing, also then my unitTests couldn't really check if my configuration file is alright.</p>
<p>So, does anyone know why the ConfigurationManager get null values while unit testing? Is it because its a static class by chance? Also is there a way to use it somehow?</p>
",https://stackoverflow.com/questions/69484592/cant-unit-testing-a-method-that-gets-values-app-config,"['c#', '.net-core-3.1']",264,False,0,0
Unit testing a non-class Groovy function using Gradle,"<p>I was given a Jenkins Library project, and I'd like to write some unit tests for it. I'm currently using the <a href=""https://github.com/mkobit/jenkins-pipeline-shared-libraries-gradle-plugin"" rel=""nofollow noreferrer"">Jenkins Pipeline Shared Libraries Gradle Plugin</a> which <a href=""https://github.com/mkobit/jenkins-pipeline-shared-libraries-gradle-plugin/blob/3cae6e9f3b10cfeec4d989f7a2e72956ed584f1a/src/main/kotlin/com/mkobit/jenkins/pipelines/SharedLibraryPlugin.kt#L135"" rel=""nofollow noreferrer"">sets up source paths for unit and integration tests</a>.</p>
<p>The source file I want to test is located at <code>src/org/example/pipeline/Terraform.groovy</code> and looks like:</p>
<pre><code>package org.example.pipeline

def terraformNewWorkspace(String env, Map config) {
    def tfWSCreate = &quot;&quot;&quot;
        #!/bin/bash
        set -e

        terraform workspace new ${env} || true
        terraform workspace select ${env}
        terraform workspace list
    &quot;&quot;&quot;
    if (config.currentWorkingDirectory != null) {
        dir(&quot;${config.currentWorkingDirectory}&quot;) {
          sh(returnStatus: false, script: tfWSCreate)
        }
    } else {
      sh(returnStatus: false, script: tfWSCreate)
    }
}
</code></pre>
<p>and I've created a <code>test/unit/groovy/example/PipelineTests.groovy</code> which looks like the following:</p>
<pre><code>import static org.example.pipeline.Terraform.terraformNewWorkspace as terraformNewWorkspace

class TerraformUnitTests extends GroovyTestCase {

   void testNewWorkspace() {
    terraformNewWorkspace(&quot;dev&quot;, [currentWorkingDirectory: &quot;/tmp/test&quot;])
   }
}
</code></pre>
<p>However I get a <code>groovy.lang.MissingMethodException at PipelineTests.groovy</code> when I try to execute this using <code>gradle test</code>. I've also tried the following as some documentation seems to indicate functions that are not part of a class get added in Groovy to a class with the name of the file, but I get the same exception about a missing method.</p>
<pre><code>import org.example.pipeline.Terraform
...
t = new Terraform()
t.terraformNewWorkspace(&quot;dev&quot;, [currentWorkingDirectory: &quot;/tmp/test&quot;])
</code></pre>
<p>What is the correct way to import and test this individual function using gradle/groovy?</p>
",https://stackoverflow.com/questions/66496059/unit-testing-a-non-class-groovy-function-using-gradle,"['unit-testing', 'gradle', 'groovy', 'jenkins-pipeline', 'jenkins-plugins']",224,False,0,1
unit testing of controller class which has rest template,"<p>I have tried test on controller class, It is not mock the rest template which is in controller class.</p>
<pre><code>@RestController
public class LoginController {

    @RequestMapping(value = &quot;api/v1/login&quot;, method = RequestMethod.POST)
    public String Loginpostmethod(@RequestBody LoginUser login) {

        String url = &quot;https://jira2.domain.com/rest/auth/1/session&quot;;
        String username = login.getUsername();
        String password = login.getPassword();
        String authStr = username + &quot;:&quot; + password;
        String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());
        HashMap&lt;String, String&gt; map = new HashMap&lt;&gt;();
        map.put(&quot;username&quot;, username);
        map.put(&quot;password&quot;, password);
        HttpHeaders headers = new HttpHeaders();
        headers.add(&quot;Authorization&quot;, &quot;Basic &quot; + base64Creds);
        headers.set(&quot;Content-Type&quot;, &quot;application/json&quot;);
        headers.set(&quot;Accept&quot;, &quot;application/json&quot;);
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity&lt;HashMap&lt;String, String&gt;&gt; entity = new HttpEntity&lt;&gt;(map, headers);
        
        ResponseEntity&lt;String&gt; response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        return response.getBody();
        
    }    
}
</code></pre>
<p>controller test class</p>
<pre><code>public class LoginControllerTest {
    
    @Mock
    RestTemplate mockrestTemplate;
    private String testUrl = &quot;https://jira2.domain.com/rest/auth/1/session&quot;;
    
    @MockBean
    LoginUser mocklogin;
    
    @InjectMocks
    LoginController loginController;
    
    @Test
    public void TestPostMethodSuccess() throws  Exception{
        LoginUser mocklogin=new LoginUser();
        mocklogin.setUsername(&quot;testusername&quot;);
        mocklogin.setPassword(&quot;testpassword&quot;);
        
        
        HashMap&lt;String, String&gt; map = new HashMap&lt;&gt;();  
        map.put(&quot;username&quot;, &quot;username&quot;);
        map.put(&quot;password&quot;, &quot;password&quot;);
        HttpHeaders headers = new HttpHeaders();
        headers.add(&quot;Authorization&quot;, &quot;Basic&quot;);
        headers.set(&quot;Content-Type&quot;, &quot;application/json&quot;);
        headers.set(&quot;Accept&quot;, &quot;application/json&quot;);
        
        HttpEntity&lt;?&gt; request = new HttpEntity&lt;&gt;(map, headers);

        ResponseEntity&lt;String&gt; response = new ResponseEntity&lt;&gt;(&quot;respons&quot;,HttpStatus.OK);
        
        
        Mockito.when(mockrestTemplate.exchange(testUrl, HttpMethod.POST, request, String.class)).thenReturn(response);
   
        assertEquals(200,response.getStatusCodeValue());
        loginController.Loginpostmethod(mocklogin);
    
    }
</code></pre>
<p>This what I have done is this is the proper way to test the controller class, It should call the api inside the controller class have a rest template so I have mocked the rest template which has the null value and assert function also is not working.When I use the verify syntax for when and then,the error as wanted but not invoked.</p>
<hr />
<p>Using mock Mvc,</p>
<pre><code> @RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles(&quot;test&quot;)
public class LoginControllerTest {
    
    @Autowired
    private MockMvc mockMvc;
    
    @Mock
    LoginUser mocklogin;
    
    @InjectMocks
    LoginController loginController;
    
    @Test
    public void TestPostMethodSuccess() throws  Exception{
        LoginUser mocklogin=new LoginUser();
        mocklogin.setUsername(&quot;testusername&quot;);
        mocklogin.setPassword(&quot;testpassword&quot;);
        
        this.mockMvc.perform(MockMvcRequestBuilders
                .post(&quot;/api/v1/login&quot;)
                .contentType(MediaType.APPLICATION_JSON)
                .content(asJsonString(mocklogin))
                .accept(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(MockMvcResultMatchers.status().isOk());
            
        }
    public static String asJsonString(final Object obj) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            final String jsonContent = mapper.writeValueAsString(obj);
            System.out.println(jsonContent);
            return jsonContent;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    
}
</code></pre>
<p>facing the error,</p>
<pre><code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on POST request for &quot;https://jira2.domain.com/rest/auth/1/session&quot;: jira2.domain.com; nested exception is java.net.UnknownHostException: jira2.domain.com
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
    at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
    at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
    at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
</code></pre>
",https://stackoverflow.com/questions/70321133/unit-testing-of-controller-class-which-has-rest-template,"['spring-boot', 'junit', 'mockito', 'resttemplate']",490,False,0,1
Unit testing events emitted from stencilJS components in angular,"<p>I have a angular component, inside the template I have a stencilJS component which is emitting an event which I'm handling in the parent component. I'm trying to write unit-test cases for the &quot;<code>handleEvent</code>&quot; method but I couldn't get the component instance of the component by using <code>By.directive(platformNavbarComponent)</code>, <code>spyOn().and.callFake(...)</code> also did not work or could find any information relating to my problem.</p>
<p>Parent.component.html</p>
<pre><code>&lt;cel-platform-navbar 
 (platformSelected)=&quot;handleEvent($event)&quot;&gt;
&lt;/cel-platform-navbar&gt;
</code></pre>
<p>Parent.component.ts</p>
<pre><code>handleEvent(ev) {
 console.log(ev)
}
</code></pre>
<p>this is the test case I have written and I'm getting the following error</p>
<blockquote>
<p>Expected spy handleEvent to have been called</p>
</blockquote>
<p>this is the test case</p>
<pre><code>fit('should call handler for &quot;platformSelected&quot; event', () =&gt; {
    const event = new CustomEvent('platformSelected', {detail:{navigationUrl: 'abc'}});
    
    fixture.detectChanges();
        
    const spy = spyOn(component, 'handleEvent').and.callThrough();
        
    window.dispatchEvent(event);
    fixture.detectChanges();
        
    expect(spy).toHaveBeenCalled();
       
  });
</code></pre>
",https://stackoverflow.com/questions/67467711/unit-testing-events-emitted-from-stenciljs-components-in-angular,"['angular', 'unit-testing', 'jasmine', 'stenciljs']",843,True,0,1
Unit testing explicitly dispatching WebhookReceived event is not working,"<p>I am building a Laravel application. I am using Laravel Cashier to handle subscription in my application. I am writing unit test for the Stripe Webhook creating a custom event listener for that.</p>
<p>I have an event listener like this:</p>
<pre><code>class StripeEventListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(WebhookReceived $event)
    {
        if ($event-&gt;payload['type'] === 'invoice.payment_succeeded') {
            // Handle the incoming event...
        }
        // TODO: write unit test for this event.
        if ($event-&gt;payload['type'] === 'customer.subscription.updated') {
            // Handle the incoming event...
            // handleCustomerSubscriptionUpdated
            if ($user = $this-&gt;getUserByStripeId($event-&gt;payload['data']['object']['customer'])) {
                $data = $event-&gt;payload['data']['object'];
                if (
                    isset($data['status']) &amp;&amp;
                    ($data['status'] === StripeSubscription::STATUS_INCOMPLETE_EXPIRED ||
                    $data['status'] == StripeSubscription::STATUS_INCOMPLETE)
                ) {
                    if (! $user-&gt;payment_method_needs_updating) {
                        $user-&gt;payment_method_needs_updating = true;
                        $user-&gt;save();
                    }
                }
            }
        }
    }

    protected function getUserByStripeId($stripeId)
    {
        return Cashier::findBillable($stripeId);
    }
}
</code></pre>
<p>Then I bind that to WebhookReceived event in the EventServiceProvider like this:</p>
<pre><code>protected $listen = [
        WebhookReceived::class =&gt; [
            StripeEventListener::class
        ],
        Registered::class =&gt; [
            SendEmailVerificationNotification::class,
        ],
    ];
</code></pre>
<p>I am unit testing the listener dispatching the WebhookReceived event like this:</p>
<pre><code>WebhookReceived::dispatch([
            .... mock data
        ]);
</code></pre>
<p>But I am getting this error:</p>
<pre><code>   Illuminate\Contracts\Container\BindingResolutionException 

  Target class [events] does not exist.

  at vendor/laravel/framework/src/Illuminate/Container/Container.php:879
    875▕ 
    876▕         try {
    877▕             $reflector = new ReflectionClass($concrete);
    878▕         } catch (ReflectionException $e) {
  ➜ 879▕             throw new BindingResolutionException(&quot;Target class [$concrete] does not exist.&quot;, 0, $e);
    880▕         }
</code></pre>
<p>How can I fix it or how can I unit test it?</p>
",https://stackoverflow.com/questions/70509116/unit-testing-explicitly-dispatching-webhookreceived-event-is-not-working,"['laravel', 'laravel-cashier']",293,False,0,0
Request failed with status code 401 - React Unit-Testing,"<p>I have created a table with multiple different fields below. There are more content in the table, but I will just show the part that I have problem with.</p>
<pre><code> &lt;TabPane tabId=&quot;1&quot;&gt;
                &lt;Form&gt;
                  &lt;Row&gt;
                    &lt;Col md=&quot;6&quot;&gt;
                      &lt;Label&gt;Name&lt;/Label&gt;
                    &lt;/Col&gt;
                    &lt;Col md=&quot;3&quot;&gt;
                      &lt;FormGroup&gt;
                        &lt;Input
                          type=&quot;text&quot;
                          name=&quot;firstName&quot;
                          id=&quot;firstName&quot;
                          value={firstName}
                          className={styleProfile.profileText}
                          onChange={this.handleUserProfile}
                          placeholder=&quot;First Name&quot;
                          invalid={!this.state.formValid.firstName}
                        /&gt;
                        &lt;FormFeedback&gt;First Name Can't be null&lt;/FormFeedback&gt;
                      &lt;/FormGroup&gt;
                    &lt;/Col&gt;
</code></pre>
<p>When I try to write unit-test for this code. For some reason, one of them can read and find the first name field area inside the table, the other code give me an <strong>Request failed with status code 401</strong> error.</p>
<p>This is my testFile.test.js file</p>
<pre><code>describe('Sturecture', () =&gt; {
it('should render a first name field', () =&gt; {
  expect(screen.getByPlaceholderText(/first name/i)).toBeInTheDocument();
});
it('should render the correct first name', () =&gt; {
  expect(screen.getByPlaceholderText(/first name/i)).toHaveValue(userProfileMock.firstName);
});
</code></pre>
<p>This is the result of the test run using. yarn test.</p>
<pre><code>     ✕ should render a first name field (92ms)
      ✓ should render the correct first name (73ms)

  ● user profile page › Sturecture › should render a first name field

    Request failed with status code 401

      at createError (node_modules/axios/lib/core/createError.js:16:15)
      at settle (node_modules/axios/lib/core/settle.js:17:12)
      at XMLHttpRequest.handleLoad (node_modules/axios/lib/adapters/xhr.js:61:7)
      at XMLHttpRequest.&lt;anonymous&gt; (node_modules/jsdom/lib/jsdom/living/helpers/create-event-accessor.js:32:32)
      at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:318:25)
      at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
      at XMLHttpRequestImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
      at fireAnEvent (node_modules/jsdom/lib/jsdom/living/helpers/events.js:18:36)
      at readyStateChange (node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js:762:3)
      at Request.&lt;anonymous&gt; (node_modules/jsdom/lib/jsdom/living/xhr/XMLHttpRequest-impl.js:888:5)
      at IncomingMessage.&lt;anonymous&gt; (node_modules/request/request.js:1076:12)

</code></pre>
<p>I wonder what I did wrong here...</p>
",https://stackoverflow.com/questions/65963660/request-failed-with-status-code-401-react-unit-testing,"['reactjs', 'unit-testing', 'jestjs']",924,False,0,1
"Javascript unit testing errors, stubbed function still being called","<p>I am trying to write some unit tests and I am getting errors in the test and I am trying to understand why the errors happen.</p>
<p>The unit test is for the <code>index.ts</code> file that calls the <code>features/index.ts</code> file. I am stubbing the default export from <code>features/index.ts</code> with sinon. But when I run the tests I get the following error <code>TypeError: Cannot read property 'resolve' of undefined</code> pointing at the file <code>features/feature1.ts</code></p>
<p>I have added the relavant extracts from the tests and typescript files below.</p>
<h5>features/feature1.ts</h5>
<pre><code>import path from &quot;path&quot;;
import fs from &quot;fs&quot;;
import {Setup} from &quot;../types&quot;;

const TEMPLATE_ROOT = path.resolve(__dirname,&quot;../../templates&quot;);
const INDEX_TEMPLATE = fs.readFileSync(TEMPLATE_ROOT, &quot;index.js&quot;), &quot;utf8&quot;);

export const setup: Setup = async ({config, options}) =&gt; {
  // Internal code removed
}
</code></pre>
<h5>features/index.ts</h5>
<pre><code>import {setup as feature1} from &quot;./feature1.ts&quot;;
import {setup as feature2} from &quot;./feature2.ts&quot;;

type FeatureTypes = &quot;feature1&quot; | &quot;feature2&quot;

type Features = {
  [key in FeatureTypes]: Setup;
};

const features: Features = {
  feature1: feature1,
  feature2: feature2 
}

export default features
</code></pre>
<h5>index.ts</h5>
<pre><code>import features from &quot;./features&quot;
import { Config, Options  } from &quot;./types&quot;;

export async function init(config: Config, options: Options): Promise&lt;void&gt; {
  const nextFeature = options.features ? options.features.shift() : undefined;
  if (nextFeature) {

    // Other irrelevant code

    await Promise.resolve(features[nextFeature]({ config, options }));
    return init(config, options);
  }
}
</code></pre>
<h5>index.spec.ts</h5>
<pre><code>import { expect } from &quot;chai&quot;;
import * as sinon from &quot;sinon&quot;;
import { init } from '.'
import * as features from &quot;./features&quot;;
import { Config, Options  } from &quot;./types&quot;

describe(&quot;init&quot;, () =&gt; {
  const sandbox: sinon.SinonSandbox = sinon.createSandbox();
  let featuresStub: sinon.SinonStub;
  
  beforeEach(() =&gt; {
    featuresStub = sandbox.stub(features, &quot;default&quot;).returns({
      feature1: sandbox.stub().resolves(),
      feature2: sandbox.stub().resolves(),
    });
  });

  afterEach(() =&gt; {
    sandbox.restore();
  });

  it(&quot;should call setup features&quot;, async () =&gt; {
    const setup: Setup = {
      features: [
        &quot;feature1&quot;,
        &quot;feature2&quot;,
      ],
    };

    await init({}, options);
    expect(featuresStub).to.have.been.calledOnce;
  });

  // rest of tests
});
</code></pre>
<p>I have also tried the changing the stub setup to be:</p>
<pre><code>import * as feature1 from &quot;.features/feature1&quot;;
import * as feature2 from &quot;.features/feature2&quot;;

// Other code

describe(&quot;init&quot;, () =&gt; {
  const sandbox: sinon.SinonSandbox = sinon.createSandbox();
  let feature1Stub: sinon.SinonStub;
  let feature2Stub: sinon.SinonStub;
  
  beforeEach(() =&gt; {
    feature1Stub = sandbox.stub(feature1, &quot;setup&quot;);
    feature2Stub = sandbox.stub(feature2, &quot;setup&quot;);

    feature1Stub.resolves() 
    feature2Stub.resolves()
  });

  // Rest of code and tests
});
</code></pre>
<p>I don't know why it would be trying to run code <code>const TEMPLATE_ROOT = path.resolve(__dirname,&quot;../../templates&quot;);</code> if I have stubbed the function that calls it.</p>
",https://stackoverflow.com/questions/68773289/javascript-unit-testing-errors-stubbed-function-still-being-called,"['javascript', 'typescript', 'unit-testing', 'sinon']",93,False,0,1
Code Quality and Unit Testing for a Landing Page,"<p>I'm creating a personal portfolio landing page using react. This is just a simple landing page with static content so far.</p>
<p>Lately, I have been writing unit tests to my code on other projects, so I wonder, is there any way to make unit tests to this kind of website? Or is there no reason at all to do this?</p>
<p>Is there any other kind of test that I can make to check the stability and quality of my code?</p>
",https://stackoverflow.com/questions/69527583/code-quality-and-unit-testing-for-a-landing-page,"['unit-testing', 'web']",80,False,0,0
Unit testing asp.net core. build all projects in solution,"<p>So I have 4 projects in my solution and all of them needs to be built in order for the test to work.</p>
<p>I have one common class that holds a lot of values that needs to be mocked or accessed in the test.
How ever, these values are all null in the test method and if I try to give them a value I get   System.TypeInitializationException.</p>
<p>I believe that the class is not built when I run the test but there might be some other issue.</p>
<p>Any idea of how to do this?</p>
<p>btw im using Microsoft.VisualStudio.TestTools.UnitTesting;</p>
<p>//Mak</p>
",https://stackoverflow.com/questions/69769452/unit-testing-asp-net-core-build-all-projects-in-solution,"['c#', 'asp.net', 'unit-testing']",48,False,0,0
"FormArray, Form Control for unit testing in angular (jasmine)","<p>I am still new in Angular and Jasmine for unit testing. If code in component.ts like this</p>
<pre><code>formGroup: FormGroup;

regexObj = {
    numberRegex: '^\d+$',
    nameRegex: '^[a-zA-Z0-9-_. ]*$',
    vendorRegex: '^[a-zA-Z0-9-_. ]*$',
    longLatRegex: '^[0-9.-]*$',
    priceRegex: '^[0-9]*$'
};



 
setBillboardIdValidator(index: number) {
     this.getForms().controls[index].get('billboardId').setValidators([Validators.pattern(this.regexObj.nameRegex), Validators.required]);
}


getForms(): FormArray {
    return this.formGroup.get('forms') as FormArray;
}
</code></pre>
<p>in component.spec.ts I write like this:</p>
<pre><code>In component.spec.ts, I create like this
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(UploadFormComponent);
    component = fixture.componentInstance;
    component.form = new FormGroup({
      billboardName: new FormControl('', Validators.required)
    });
    fixture.detectChanges();
  });

  it('setBillboardNameValidator', () =&gt; {
    const control = component.form.controls['billboardName'];
    component.setBillboardNameValidator(9)
    expect(control).toBeTruthy();
  });
</code></pre>
<p>When I running the the unit test, I got message can not read property <strong>TypeError: Cannot read property 'get' of undefined</strong>. Can you help me what's wrong with my code?</p>
",https://stackoverflow.com/questions/68203777/formarray-form-control-for-unit-testing-in-angular-jasmine,"['angular', 'unit-testing', 'jasmine', 'angular-reactive-forms']",743,False,0,0
How can I compare INStartCallContactResolutionResult objects for unit testing?,"<p>I'm trying to unit test my Intent Handler class for INStartCallIntent, but I'm having trouble comparing the result objects for contact resolution.</p>
<p>For example, given a basic handler for INStartCallIntent:</p>
<pre class=""lang-swift prettyprint-override""><code>import Intents

class StartCallHandler: NSObject, INStartCallIntentHandling {
        func resolveContacts(for intent: INStartCallIntent, with completion: @escaping ([INStartCallContactResolutionResult]) -&gt; Void) {
        guard let contacts = intent.contacts, !contacts.isEmpty, let person = contacts.first else {
            completion([.needsValue()])
            return
        }
        
        guard contacts.count == 1 else {
            completion([.unsupported(forReason: .multipleContactsUnsupported)])
            return
        }

        let matchingContacts = [person] // matching logic here
        switch matchingContacts.count {
        case 2  ... Int.max:
            // We need Siri's help to ask user to pick one from the matches.
            completion([.disambiguation(with: matchingContacts)])
        case 1:
            // We have exactly one matching contact
            completion([.success(with: person)])
        default:
            completion([.unsupported(forReason: .noContactFound)])
        }
    }
}
</code></pre>
<p>If I create a simple unit test, I'm unable to to compare the INStartCallContactResolutionResult objects:</p>
<pre class=""lang-swift prettyprint-override""><code>func testResolveContacts() {
    let person = INPerson(personHandle: INPersonHandle(value: nil, type: .unknown), nameComponents: nil, displayName: &quot;Steve Jobs&quot;, image: nil, contactIdentifier: nil, customIdentifier: nil)
    let intent = INStartCallIntent(audioRoute: .unknown, destinationType: .unknown, contacts: [person], recordTypeForRedialing: .unknown, callCapability: .audioCall)
    let handler = StartCallHandler()
        
    handler.resolveContacts(for: intent) { result in
        XCTAssertEqual(result.count, 1)
        guard let firstResult = result.first else { return XCTFail() }
        
        let expectedPerson = INPerson(personHandle: INPersonHandle(value: nil, type: .unknown), nameComponents: nil, displayName: &quot;Steve Jobs&quot;, image: nil, contactIdentifier: nil, customIdentifier: nil)
        let expectedResult = INStartCallContactResolutionResult(.success(with: expectedPerson))
        XCTAssertEqual(firstResult, expectedResult)
    }
}
</code></pre>
<p>The XCTAssertEqual fails with this message:</p>
<blockquote>
<p>XCTAssertEqual failed: (&quot;&lt;INStartCallContactResolutionResult:
0x600002109310&gt; {
resolutionResultCode = Success;
resolvedValue = &lt;INPerson: 0x600002c7b780&gt; {
displayName = Steve Jobs;
contactIdentifier = ;
nameComponents = ;
image = ;
customIdentifier = ;
relationship = ;
siriMatches = ;
personHandle = &lt;INPersonHandle: 0x600000d78960&gt; {
value = ;
type = Unknown;
label = ;
};
};
disambiguationItems = ;
itemToConfirm = ;
unsupportedReason = 0; }&quot;) is not equal to (&quot;&lt;INStartCallContactResolutionResult: 0x6000021092c0&gt; {
resolutionResultCode = Success;
resolvedValue = &lt;INPerson: 0x600002c7b900&gt; {
displayName = Steve Jobs;
contactIdentifier = ;
nameComponents = ;
image = ;
customIdentifier = ;
relationship = ;
siriMatches = ;
personHandle = &lt;INPersonHandle: 0x600000d78d80&gt; {
value = ;
type = Unknown;
label = ;
};
};
disambiguationItems = ;
itemToConfirm = ;
unsupportedReason = 0; }&quot;)</p>
</blockquote>
<p>So even though the two objects have identical properties, the XCTAssertEqual fails presumably because there is no equality function implemented on Apple's end.</p>
<p>This makes it pretty much impossible to test this function as a result. Has anyone been able to accomplish this some other way?</p>
",https://stackoverflow.com/questions/69651515/how-can-i-compare-instartcallcontactresolutionresult-objects-for-unit-testing,"['ios', 'swift', 'xctest', 'sirikit']",122,True,0,1
React Unit Testing Jest using Typescript problem with mount(),"<p>I have this simple app / components</p>
<pre><code>import GraphicCanvas from './Graphing/GraphCanvas';
import { drawCircle } from './Graphing/DrawCircle';
function App() {
  return (
    &lt;div className=&quot;App&quot;&gt;
     &lt; GraphicCanvas  draw={drawCircle} /&gt;
    &lt;/div&gt;
  );
}

export default App;
</code></pre>
<hr />
<pre><code>    import React, { FC, useRef, useEffect } from &quot;react&quot;;
    
    export interface IGraphicCanvas{
        draw : Function;
    }
    
    const GraphicCanvas : FC&lt;IGraphicCanvas&gt; = (props) : JSX.Element =&gt; {
        const canvasRef = useRef&lt;HTMLCanvasElement&gt;(null)
    
        useEffect(() =&gt; {
            if (canvasRef.current) {
                const canvas = canvasRef.current
                const context = canvas?.getContext('2d')
                props.draw(context)
            }
        }, [props.draw])
    return &lt;canvas ref={canvasRef} /&gt;

}

export default GraphicCanvas ;
</code></pre>
<hr />
<pre><code>export const drawCircle = (ctx : CanvasRenderingContext2D | null ) : void =&gt; {
    ctx!.fillStyle = '#000000'
    ctx?.beginPath()
    ctx?.arc(50, 100, 20, 0, 2 * Math.PI)
    ctx?.fill()
}
</code></pre>
<p>It works and renders a small black dot .</p>
<p>My problem is trying to write a unit test with Enzyme and Jest, mount() errors.</p>
<p>Below is my test, which is pretty self explanatory in what it's trying to test.</p>
<pre><code>import React from 'react'
import { configure, shallow, mount } from &quot;enzyme&quot;;
import Adapter from &quot;enzyme-adapter-react-16&quot;;

import GraphicCanvas, { IGraphicCanvas } from &quot;./GraphCanvas&quot;;
import  { drawCircle }  from &quot;./DrawCircle&quot;

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

describe(&quot;GraphCanvas &quot;, () =&gt; {
  
  let props: IGraphicCanvas;
  let useEffect: { getMockImplementation: (arg0: (ctx: CanvasRenderingContext2D | null) =&gt; void) =&gt; void; }
  
  const mockUseEffect = () =&gt; {
    useEffect.getMockImplementation( drawCircle );
  };

  beforeEach(() =&gt; {
    props = { draw: jest.fn().getMockImplementation }; 
  });

  //shallow method renders only a single component, without child components.
  it(&quot;renders without crashing&quot;, () =&gt; {
    shallow(&lt;GraphicCanvas draw={drawCircle} /&gt;);
  });

  it(&quot;calls function drawCircle passed in props as draw&quot;, () =&gt; {
    //mockUseEffect();
    //mount(&lt;GraphicCanvas draw={drawCircle} /&gt;);
    mount(&lt;GraphicCanvas {...props} /&gt;);
    expect(props.draw).toHaveBeenCalled();
  });

});
</code></pre>
<p>When I run my test I get the following error</p>
<pre><code>  ● GraphCanvas  › calls function drawCircle passed in props as draw

    TypeError: Cannot read properties of undefined (reading 'child')

      29 |     //mockUseEffect();
      30 |     //mount(&lt;GraphicCanvas draw={drawCircle} /&gt;);
    &gt; 31 |     mount(&lt;GraphicCanvas {...props} /&gt;);
         |     ^
      32 |     expect(props.draw).toHaveBeenCalled();
      33 |   });
      34 |
</code></pre>
<p>If I uncomment line 30 I get the same error</p>
<p>If I uncomment line 29 I get</p>
<pre><code> ● GraphCanvas  › calls function drawCircle passed in props as draw

    TypeError: Cannot read properties of undefined (reading 'getMockImplementation')

      14 |   
      15 |   const mockUseEffect = () =&gt; {
    &gt; 16 |     useEffect.getMockImplementation( drawCircle );
         |               ^
      17 |   };
</code></pre>
<p>Obviously I'm doing something very wrong with line 29</p>
<p>But I can't understand with both line 30 and 31 fail</p>
<p>All I'm trying to do is test that the function drawCircle which is passed in as a prop &quot;draw&quot; to GraphicCanvas is called</p>
<pre><code> expect(props.draw).toHaveBeenCalled()
</code></pre>
",https://stackoverflow.com/questions/69780222/react-unit-testing-jest-using-typescript-problem-with-mount,"['reactjs', 'typescript', 'react-hooks', 'jestjs', 'enzyme']",1184,False,0,2
"Node.js axios unit testing using Mocha, sinon and chai","<p>I have node.js component name controller.js which have a function that calls api service using axios with options and it also have catch function for error handling. I am not able to stub axios function so as to cover it by unit testing.</p>
<p>Below is controller.js component.</p>
<pre><code>const axios = require('axios');
export.getData = function(req, res, next) {
  try {
     const options = {
            method: 'GET',
            headers: headers,
            url,
            params: queryParams
     };  
     axios(options).then(function (response) {
            res.json(response.data);
        })
            .catch(function (error) {
                if (error &amp;&amp; error.response) {
                    if (error.response.status === 401) {
                        res.status(500).send({ error: true, message: 'There seems to be an issue, please try after sometime' });                   
                    }
                 }
             });
  }
}
</code></pre>
<p>below is my controller.test.js</p>
<pre><code>const chai = require('chai');
const assert = chai.assert;
const axios = require('axios');
const sinon = require('sinon');
const controller = require('../controllersr');

describe(&quot;controller API testing&quot;, () =&gt; {

it(&quot;should call getMarketId function and return status 200 on success&quot;, function (done) {
        const req = { };
        const res =  { json: {greet: &quot;hello&quot;}, status: 200};
        var mockStub = sinon.stub(axios, 'get').resolves(res);
        controller.getData(req, res);
        assert.equal(res.status, 200);
        mockStub.restore();
        done();
    });

});
</code></pre>
<p>Here, I am not able to stub axios funtion and catch function for error handling.
And thus unable to cover the code for axios success and catch function in NYC.
Please help..</p>
",https://stackoverflow.com/questions/68451221/node-js-axios-unit-testing-using-mocha-sinon-and-chai,"['node.js', 'unit-testing', 'axios', 'mocha.js', 'sinon']",3164,True,0,1
How to unit test window.location.reload in angular 12 unit testing?,"<p>In my angular project, I have a function</p>
<pre><code>reloadPage(): void {
  window.location.reload();
}
</code></pre>
<p>So when ever I need to reload the page, I used to call this function.</p>
<p>Now I am trying to add the unit testing for this function but it is not working.</p>
<pre><code>it(&quot;reloadPage: should be validated&quot;, () =&gt; {
    spyOn(window.location, 'reload').and.callFake(() =&gt; {
      //test
    });
    component.reloadPage();
});
</code></pre>
<p>It still reloads the page on unit testing</p>
<p>How can I achieve a unit test for this function? Any help could be appreciated. Thanks in advance</p>
",https://stackoverflow.com/questions/68607971/how-to-unit-test-window-location-reload-in-angular-12-unit-testing,"['angular', 'unit-testing', 'angular-unit-test', 'angular12']",7365,True,6,4
Unit testing Reactive code in constructors using AutoMock from AutoFixture?,"<p>I'm hitting a bit of a chicken and egg problem setting up my mocks for Reactive Extensions code in a constructor. Here's the class under test (along with the service interface it depends on):</p>
<pre class=""lang-cs prettyprint-override""><code>class MyViewModel
{
    public int Thing { get; set; }
    public MyViewModel(IMyService service)
    {
        service.StreamOfThings.Subscribe(x =&gt; Thing = x));
    }

    public void SomeClickEvent()
    {
        // Do something with `Thing`
    }
}
public interface IMyService
{
    IObservable&lt;int&gt; StreamOfThings { get; }
}
</code></pre>
<p>To make testing easier, I have also defined a custom attribute named <code>AutoMockData</code> I can use to use Moq to inject mock instances into my classes through AutoFixture:</p>
<pre class=""lang-cs prettyprint-override""><code>public class AutoMockDataAttribute : AutoDataAttribute
{
    private static IFixture Create() =&gt;
        new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true });
        
    public AutoMockDataAttribute() : base(Create) {}
}
</code></pre>
<p>With this, I am ready to write my test (using NUnit3):</p>
<pre class=""lang-cs prettyprint-override""><code>[Test, AutoMockData]
public void Verify_some_behavior(
    [Frozen] Mock&lt;IMyService&gt; mockService,
    MyViewModel vm)
{
    mockService.Setup(x =&gt; x.StreamOfThings).Returns(Observable.Return(100));
    vm.SomeClickEvent();
    vm.Thing.Should().Be(100);
}
</code></pre>
<p>This test fails. I believe this fails because the constructor of <code>MyViewModel</code> sets up an observable pipeline on a different instance of <code>IObservable</code> than the one I set up in the unit test method.</p>
<p>The ideal solution here would be to use the <code>IObservable&lt;&gt;</code> instance that was set up using AutoFixture, but I'm not sure how to best do that. It would somehow need to already set up a pre-constructed pipeline for me.</p>
<p>The workaround I have found is to not use the <code>AutoMock</code> functionality of <code>AutoFixture</code> and instead construct a <code>Fixture</code> directly and directly use the <code>.Freeze()</code> and <code>.Create()</code> methods in the proper order. However, this leads to an arguably more difficult to read and less clean unit test body.</p>
<p>How can I continue to implement my test as shown here but also be able to set up any observables before they are used in the SUT's constructor?</p>
",https://stackoverflow.com/questions/68848578/unit-testing-reactive-code-in-constructors-using-automock-from-autofixture,"['c#', 'unit-testing', 'nunit', 'system.reactive', 'autofixture']",232,True,2,1
How to mock InputFile (csv) in Blazor while unit testing?,"<p>I am using <code>InputFile</code> in Blazor to accept csv files from user.
While doing testing I want to either give a physical file to <code>InputFile</code> or I want to mock a CSV file and do the testing.</p>
<p>I created a mock as below but I don't know how to give <code>Name</code>,mock data(in file) to this mock:</p>
<p><code>var mockIbrowser = new Mock&lt;IReadOnlyList&lt;IBrowserFile&gt;&gt;();</code></p>
<p>Actual Test Case:</p>
<pre><code>[Fact]
        public void FileUploadTest()
        {
            using var ctx = new TestContext();
            var mockIbrowser = new Mock&lt;IReadOnlyList&lt;IBrowserFile&gt;&gt;();
            
            var optionsMock = Substitute.For&lt;IOptions&lt;RemoteBrowserFileStreamOptions&gt;&gt;();
            ctx.Services.AddSingleton&lt;IOptions&lt;RemoteBrowserFileStreamOptions&gt;&gt;(optionsMock);
            ctx.JSInterop.SetupVoid(&quot;Blazor._internal.InputFile.init&quot;, x =&gt; true);
            //Arrange
            var comp = ctx.RenderComponent&lt;FileProcess&gt;();
            //expected
            string expectedMarkupButton = @&quot;&lt;button type=&quot;&quot;submit&quot;&quot; class=&quot;&quot;btn btn-outline-primary&quot;&quot; @btnstatus&gt;Upload Selected File(s)&lt;/button&gt;&quot;;
            string expectedMarkupMsg = @&quot;&lt;h3 style=&quot;&quot;color:Black;&quot;&quot;&gt;All Tasks performed successfully&lt;/h3&gt;&quot;;
            //Action
            comp.Find(&quot;InputFile&quot;).Click();
            comp.Find(&quot;form&quot;).Submit();
            //Matched ?
            comp.Find(&quot;button&quot;).MarkupMatches(expectedMarkupButton);
            comp.Find(&quot;h3&quot;).MarkupMatches(expectedMarkupMsg);
        }
</code></pre>
",https://stackoverflow.com/questions/67770176/how-to-mock-inputfile-csv-in-blazor-while-unit-testing,"['c#', 'unit-testing', 'mocking', 'blazor']",686,False,2,0
Unit Testing asynchronous functions called by various didSets in Swift,"<p>I'm trying to unit test a property in a ViewModel (in Swift) that is dependent on a series of other properties being set, and having trouble doing so.</p>
<p>I have a viewModel which includes a <code>timeLength</code>, a <code>timePeriod</code>, and a <code>listOfObjects</code> that fits my time period.</p>
<p>These values depend on the previous one,</p>
<p><code>timeLength</code> and <code>timePeriod</code> are both stored in the user's profile, and my code follows this flow:</p>
<ol>
<li>Search for a <code>timeLength</code> in the profile.</li>
<li>If none is found, allow the user to select a <code>timeLength</code></li>
<li>Once the <code>timeLength</code> is set, a <code>didSet</code> triggers a flow that searches for a matching <code>timePeriod</code>, (in a mock repository for time periods) or creates one if one doesn't exist.</li>
<li>Once the <code>timePeriod</code> exists, a <code>didSet</code> triggers a flow that searches a database to compile a <code>listOfObjects</code> that match that <code>timePeriod</code> (using a separate mockRepository for objects).</li>
</ol>
<p>I'm trying to create a unit test that checks the list of objects once that code flow is completed, but every time I do so, the <code>XCTAssertEqual</code> method completes before the code flow is finished. I tried using XCTestExpectation, as described in <a href=""https://www.hackingwithswift.com/example-code/testing/how-to-test-asynchronous-functions-using-expectation"" rel=""nofollow noreferrer"">Hacking with Swift</a>, but I don't have a specific asynchronous method to call, since this is all triggered by a series of <code>didSet</code> calls.</p>
<p>I could create a <code>timePeriod</code> in the repository, which would trigger the <code>listOfObjects</code> to be set in the ViewModel, but then I'd be missing out on the full flow of this. Is there a way to just have the test complete after a few seconds?
(Or is this a bad test since I'm relying on the system to do multiple things at once in order to pass the test?)</p>
<p>Here's the specific test (right now it won't do anything since there's nothing to fulfill the asynchronous wait)</p>
<pre><code>    func testSeasonObjectsVM_loadData() {
        // given
        let exp = expectation(description: &quot;loading Data&quot;)
        sut.timeLength = .quarter
        waitForExpectations(timeout: 20)
        
        // when
        let count = sut.listOfObjects.count
        
        // assert
        XCTAssertEqual(count, 2)
        
    }
</code></pre>
",https://stackoverflow.com/questions/68116477/unit-testing-asynchronous-functions-called-by-various-didsets-in-swift,"['swift', 'unit-testing', 'asynchronous']",255,False,2,1
How to detect empty IEnumerator function calls during unit testing?,"<p>I'm working with Unity's play mode test unit that run on Enumerator function (aka. Coroutine).</p>
<p>Inside the test, they will call more sub routines, some of them are ordinary function, some of them are IEnumerator function, thus allowing the test to run and span over several frames.</p>
<pre><code>[UnityTest]
public IEnumerator Test1( )
{
    SubAction1( );
    yield return SubAction2( );
}

void SubAction1( ) // A sub function that does not need to run over several frames
{ 
}

IEnumerator SubAction2( ) // A sub function that need to span over several frames
{
    ... // More code
    yield return WaitForSeconds( 1 );

    ... // More code
    while( condition == false )
        yield return null; // Wait until condition becomes true to continue

    ... // More code
}
</code></pre>
<p>If I misuse the <code>SubAction2</code> and call it just like ordinary function:</p>
<pre><code>SubAction2( ); // without yield return, this is misuse
</code></pre>
<p>it would still compile and run silently! This will make SubAction2 does not execute all of its code. It is just a small typo, but this one could cause the entire test to fail silently! SubAction2 is an IEnumerator function, and meant to be called with yield return.</p>
<p>Do I have some way to sanity check, or enforce that this function should be called with 'yield return'?</p>
<p>I'm looking for any possible solution of:</p>
<ul>
<li>Some C# language pattern to prevent such misuse, either on runtime or compile time.</li>
<li>OR some magic attribute that will help checking this misuse?</li>
<li>OR an editor warning that help detecting such misuse (Such as option in VisualStudio intellisense?)</li>
</ul>
<p>My solution for now is to name all IEnumerator function with some prefix like &quot;DoSubAction2&quot; and then do a regular expression search to find the occurrence of &quot;Do&quot; function calls without &quot;yield return&quot; to manually check for misuse.</p>
",https://stackoverflow.com/questions/67820221/how-to-detect-empty-ienumerator-function-calls-during-unit-testing,"['c#', 'unity-game-engine', 'enumerator']",212,True,2,2
Cypress: unit testing the pure React component is throwing error,"<p>I am writing unit tests using Cypress for my React JS web application. I can write functional tests using Cypress. But I also need to write the unit tests for my presentation components in my app. So I am using this Cypress wrapper for React, <a href=""https://github.com/cypress-io/cypress/tree/master/npm/react"" rel=""nofollow noreferrer"">https://github.com/cypress-io/cypress/tree/master/npm/react</a>. But, when I write the unit test for my component, it is throwing an error. Following is how I installed and wrote the unit test for my pure component.</p>
<p>First I installed the required libraries running the following command.</p>
<pre><code>npm install --save-dev cypress @cypress/react @cypress/webpack-dev-server
</code></pre>
<p>Then I added the following line into the cypress/plugins/index.js</p>
<pre><code>module.exports = (on, config) =&gt; {
    require('@cypress/react/plugins/react-scripts')(on, config)
  // `on` is used to hook into various events Cypress emits
  // `config` is the resolved Cypress config
}
</code></pre>
<p>Then I created a test file called, no_result.spec.js with the following code.</p>
<pre><code>import React from 'react';
import { mount } from '@cypress/react';
import NoResult from &quot;../../../src/components/NoResult&quot;;

describe(&quot;NoResult Component&quot;, () =&gt; {

    it ('should display message', () =&gt; {
        mount(&lt;NoResult message={&quot;No data available.&quot;} /&gt;);

        cy.contains('No data available').should('be.visible');
    })
})
</code></pre>
<p>Then I opened the cypress and run that no_result.js test and I got the following error.</p>
<pre><code>AssertionError
Timed out retrying after 4000ms: Expected to find element: #__cy_root, but never found it.

Because this error occurred during a before each hook we are skipping all of the remaining tests.
node_modules/@cypress/react/dist/cypress-react.esm-bundler.js:317:1
  315 |     return cy.then(function () {
  316 |         var selector = &quot;#&quot; + ROOT_ID;
&gt; 317 |         return cy.get(selector, { log: false }).then(function ($el) {
      | ^
  318 |             var wasUnmounted = unmountComponentAtNode($el[0]);
  319 |             if (wasUnmounted &amp;&amp; options.log) {
  320 |                 cy.log('Unmounted component at', $el);
</code></pre>
<p>What is missing in my configuration and how can I fix it?</p>
",https://stackoverflow.com/questions/67110214/cypress-unit-testing-the-pure-react-component-is-throwing-error,"['reactjs', 'unit-testing', 'cypress']",1178,False,1,0
Jasmine/Karma unit testing AngularJS service: how to mock &quot;import&quot;,"<p>We have a Karma/Jasmine unit tests set up for a legacy AngularJS (v1) app (nowadays compiled with Webpack). We're trying to build unit tests for a service that uses regular Angular injections BUT also an <code>import</code> statement. Something like this:</p>
<pre><code>import myMember from 'my-module';

(function () {
  angular
    .module('app.core')
    .service('myService', myService);

  myService.$inject = ['$window', 'anotherService'];

  function myService($window, anotherService) {
    ...
  }
})();
</code></pre>
<p>The <code>import</code> part poses a challenge because I need to mock <code>myMember</code> from the imported module.</p>
<p><s>First I tried testing like before, but, naturally, when I try to access <code>myMember</code> in any way, I get an error: <strong>&quot;myMember is not defined&quot;</strong></p>
<p>Then I tried inserting a similar <code>import</code> statement at the beginning of the unit test file. However: <strong>&quot;SyntaxError: Cannot use import statement outside a module&quot;</strong></s></p>
<p>Can't seem to wrap my head around this issue. Anyone got a hint how to move forward?</p>
<p><strong>EDIT:</strong> The project has a complicated structure and <code>import</code> <strong>started working</strong> when the test file was located deeper in the directory structure. Maybe something related to file running order. Dunno. Anyways, <strong>mocking</strong> still remains a challenge.</p>
",https://stackoverflow.com/questions/68981190/jasmine-karma-unit-testing-angularjs-service-how-to-mock-import,"['angularjs', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-runner']",201,False,1,0
How solve the undefined value in jest angular unit testing?,"<p>I have passed the api response value from one function to another function, But in JEST unit test case showing undefined, How to solve this error</p>
<p>angular  code</p>
<pre><code>  this.content = this.commonSiteContent();
 this.passingvalue(this.content.name);


 jest.spyOn(srvice, 'commonSiteContent').mockReturnValue(mockContent);
component.ngOnInit();
expect(mockContent.getContentDetails).toHaveBeenCalledWith(&quot;sss&quot;);
expect(component.passvalue).toHaveBeenCalled()
</code></pre>
<p>I got the below error</p>
<p>TypeError: Cannot read property 'name' of undefined</p>
<pre><code>  27 |   
  28 |
  29 |     this.passvalue(this.content.name);
     |                                     ^
  30 |   }
  31 |   passvalue(name=&quot;&quot; ){
</code></pre>
",https://stackoverflow.com/questions/68619713/how-solve-the-undefined-value-in-jest-angular-unit-testing,"['angular', 'jestjs', 'jasmine', 'karma-jasmine', 'jest-fetch-mock']",804,False,1,0
Firebase offline unit testing: Could not load the default credentials,"<p>I am trying to write some unit-tests using the firebase-emulator. No matter what I do, it always gives me this error:</p>
<pre><code>Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
</code></pre>
<h2>Test</h2>
<pre><code>describe('Cloud Functions', function() {
    let myFunctions: any, adminInitStub: sinon.SinonStub&lt;[options?: admin.AppOptions, name?: string], admin.app.App&gt;;
    const tester = funcTest();

    before(async () =&gt; {
        admin.initializeApp();
        adminInitStub = sinon.stub(admin, &quot;initializeApp&quot;);
        myFunctions = await import(&quot;../src/index&quot;)
    });
  
    after(() =&gt; {
        adminInitStub.restore();
        tester.cleanup();
    });

    describe(&quot;dbOrderServiceOnCreated&quot;, () =&gt; {

        it(&quot;should add snapshot successfully&quot;, async function() {
            const wrapped = tester.wrap(myFunctions.dbOrderServiceOnCreated)
            
            wrapped(serviceOrderSnap)
            this.timeout(0);

            // THIS IS THE PROBLEM
            const value = await admin.firestore().collection(constants.collectionOrdersService).get(); 
            return chai.assert.equal(value.size, 1);
        })
    })
})
</code></pre>
",https://stackoverflow.com/questions/70249373/firebase-offline-unit-testing-could-not-load-the-default-credentials,"['javascript', 'typescript', 'google-cloud-firestore', 'google-cloud-functions', 'firebase-tools']",196,False,1,0
How to mock an interface in Unit Testing in Java?,"<p>I am trying to create a Unit Test for the following method:</p>
<pre><code>public List&lt;CompanyUserDTO&gt; findAllByUserUuidIn(final Set&lt;UUID&gt; userUuidList) {
        return companyUserRepository.findAllByUserUuidIn(userUuidList);
    }
</code></pre>
<p>This method returns a list of <code>CompanyUserDTO</code> that is interface. Here is the interface definition:</p>
<pre><code>public interface CompanyUserDTO {
    UUID getUserUuid();

    UUID getCompanyUuid();

    String getCompanyName();

    default CompanyDTO getCompany() {
        return new CompanyDTO(getCompanyUuid(), getCompanyName());
    }
}
</code></pre>
<p>Here is <em><strong>CompanyDTO</strong></em>:</p>
<pre><code>@Data
@AllArgsConstructor
@NoArgsConstructor
public class CompanyDTO {
    private UUID uuid;
    private String name;

    public CompanyDTO(final Company company) {
        this.uuid = company.getUuid();
        this.name = company.getName();
    }
}
</code></pre>
<p>My Unit Test is as shown below:</p>
<pre><code>@Test
public void test_findAllByUserUuidIn() {
    Set&lt;UUID&gt; userUuidList = new HashSet&lt;&gt;();
    userUuidList.add(UUID.fromString(&quot;00000000-0000-0000-0000-000000000001&quot;));
    userUuidList.add(UUID.fromString(&quot;00000000-0000-0000-0000-000000000002&quot;));
    userUuidList.add(UUID.fromString(&quot;00000000-0000-0000-0000-000000000003&quot;));

    // --&gt; here I need a mock list of `CompanyUserDTO`
    List&lt;CompanyUserDTO&gt; companyUserDTOList = new ArrayList&lt;&gt;();

    when(companyUserRepository.findAllByUserUuidIn(userUuidList))
        .thenReturn(companyUserDTOList);

    List&lt;CompanyUserDTO&gt; result = companyUserService
        .findAllByUserUuidIn(userUuidList);

    assertEquals(companyUserDTOList, result);
}
</code></pre>
<p><strong>1.</strong> So, how should I create a mock list of <code>CompanyUserDTO</code> in the test?</p>
<p><strong>2.</strong> Is my unit test ok with this approach?</p>
",https://stackoverflow.com/questions/70020551/how-to-mock-an-interface-in-unit-testing-in-java,"['java', 'unit-testing', 'junit', 'mocking', 'mockito']",936,True,1,1
Django unit-testing for ProfileEditForm with disabled (read-only) fields,"<p>I want to write unit tests for my <code>ProfileEditForm</code> form that has some fields with <code>disabled=True</code>. So, these fields are read-only and cannot be changed. I want to test this logic. As far as I know, I don't have to give <a href=""https://docs.djangoproject.com/en/3.2/ref/forms/fields/#disabled"" rel=""nofollow noreferrer"">disabled</a> fields to the form. The form itself validates these fields.</p>
<p><strong>models.py</strong></p>
<pre><code>class Profile(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=63, blank=False)
    last_name = models.CharField(max_length=63, blank=False)
    about_me = models.CharField(max_length=511, blank=True)
</code></pre>
<p><strong>forms.py</strong></p>
<pre><code>class ProfileEditForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = [
            &quot;username&quot;,
            &quot;email&quot;,
            &quot;first_name&quot;,
            &quot;last_name&quot;,
            &quot;about_me&quot;,
        ]

    username = forms.CharField(label=&quot;Username&quot;, disabled=True)
    email = forms.EmailField(label=&quot;Email&quot;, disabled=True)
    first_name = forms.CharField(label=&quot;First Name&quot;, max_length=63, required=False)
    last_name = forms.CharField(label=&quot;Last Name&quot;, max_length=63, required=False)
    about_me = forms.CharField(label=&quot;About Me&quot;, max_length=511, required=False)
</code></pre>
<p><strong>tests.py</strong></p>
<pre><code>class ProfileEditFormTests(TestCase):

    def setUp(self) -&gt; None:
        self.user = get_user_model().objects.create_user(username=&quot;testuser&quot;,
                                                         email=&quot;test@test.com&quot;,
                                                         password=&quot;password123&quot;)
        self.profile = Profile.objects.create(user=self.user)

    def test_email_field_is_not_editable(self):

        form_data = {
            &quot;username&quot;: self.profile.user.username,
            &quot;email&quot;: self.profile.user.email,
            &quot;first_name&quot;: &quot;first&quot;,
            &quot;last_name&quot;: &quot;last&quot;,
            &quot;about_me&quot;: &quot;&quot;,
        }
        form = ProfileEditForm(data=form_data)
        self.assertTrue(form.is_valid())
</code></pre>
<p>I get:</p>
<pre><code>AssertionError: False is not true
</code></pre>
<p>When I print out the form errors with <code>print(form.errors)</code>:</p>
<pre><code>&lt;ul class=&quot;errorlist&quot;&gt;&lt;li&gt;username&lt;ul class=&quot;errorlist&quot;&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;li&gt;email&lt;ul class=&quot;errorlist&quot;&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;
</code></pre>
<p>Even if I provide all fields, the form is still invalid.</p>
<pre><code>    form_data = {
        &quot;username&quot;: self.profile.user.username,
        &quot;email&quot;: self.profile.user.email,
        &quot;first_name&quot;: &quot;first&quot;,
        &quot;last_name&quot;: &quot;last&quot;,
        &quot;about_me&quot;: &quot;&quot;,
    }
</code></pre>
<p>I get the same error Nothing changes.</p>
<p>During the test, I check whether <code>Profile</code> instance is successfully created with <code>Profile.objects.count()</code>. The answer is yes.</p>
<p>To give you an idea: I'm using generic UpdateView for editing users' profiles with the help of <code>ProfileEditForm</code>. The view and form are working well.</p>
<p>How should I write unit tests for read-only fields?</p>
",https://stackoverflow.com/questions/69240960/django-unit-testing-for-profileeditform-with-disabled-read-only-fields,"['python', 'django', 'django-models', 'django-forms', 'django-testing']",196,False,1,0
Python 3.9: Unit testing of retrieving data from Cloud Datastore,"<p>I'm new to unit tests with python and I have trouble trying to write one for my code where I fetch a few properties (<code>string</code>, <code>timestamp</code>) of two Datastore <strong>entities</strong> and based on a condition set the timestamp.</p>
<p>My <code>main.py</code> looks like this:</p>
<pre><code>from google.cloud import datastore

datastore_client = datastore.Client()

def get_timestamp():
    # fetch property1 (string), property2 (timestamp), property3 (timestamp) from entity1
    query = datastore_client.query(kind=&quot;kind1&quot;)
    key_entity1 = datastore_client.key(&quot;kind1&quot;, &quot;entity1_key_id&quot;)
    query.key_filter(key_entity1, &quot;=&quot;)
    list_entity1 = list(query.fetch())
    entity1 = dict(list_entity1[0])
    property1 = entity1['property1']
    # based on the value of property1 set timestamp1
    if property1 == &quot;value1&quot; or property1 == &quot;value2&quot;:
        timestamp1 = entity1['property2']
    elif property1 == &quot;value3&quot;:
        timestamp1 = entity1['property3']
    # fetch property1 (timestamp) from entity2
    query = datastore_client.query(kind=&quot;kind1&quot;)
    key_entity2 = datastore_client.key(&quot;job_results&quot;, &quot;entity2_key_id&quot;)
    query.key_filter(key_entity2, &quot;=&quot;)
    list_entity2 = list(query.fetch())
    entity2 = dict(list_entity2[0])
    timestamp2 = entity2['property1']
    if timestamp2 &gt; timestamp1:
        timestamp = timestamp2.isoformat().replace('+00:00', 'Z')
    elif timestamp1 &gt; timestamp2:
        timestamp = timestamp1.isoformat().replace('+00:00', 'Z')
    return timestamp
</code></pre>
<p>So I'm fetching two entities and their properties from Datastore, I choose the timestamp property based on a condition and then I compare two timestamps.</p>
<p>From searching I just know I can use <code>patch</code> to mock the Datastore API and <code>test_main.py</code> can look like this:</p>
<pre><code>import pytest
from unittest.mock import Mock, patch
import main

@patch(&quot;main.datastore_client&quot;)
def test_get_timestamp():
    # test code
</code></pre>
<p>Can someone help and tell me how the unit test looks like for my code?
If it helps I'm using Python 3.9.</p>
<p>I appreciate any help and thanks in advance.</p>
",https://stackoverflow.com/questions/68809145/python-3-9-unit-testing-of-retrieving-data-from-cloud-datastore,"['python', 'unit-testing', 'google-api', 'google-cloud-datastore']",326,True,1,1
unit testing: mock ThreadContext map impl using Spock or Mockito,"<p>my method is in a Java class like this...</p>
<pre><code>   //some business logic
   String userId = org.apache.logging.log4j.ThreadContext.get(&quot;userId&quot;); //I need mocking for this using Spock or Mockito
   //more business logic
   return map;
}
</code></pre>
<p>I am trying to write a test for the above method using Spock framework and ThreadContext is getting in the way - I couldn't mock it to return a string of my wish. I tried to put a custom value into the ThreadContext during setup of the spock test...(didn't work)</p>
<pre><code>    def setupSpec() {
        ThreadContext.put(&quot;userId&quot;, &quot;sriram&quot;)
    }
</code></pre>
<p>Any ideas are appreciated, thank you.</p>
",https://stackoverflow.com/questions/65702384/unit-testing-mock-threadcontext-map-impl-using-spock-or-mockito,"['java', 'mockito', 'log4j', 'spock']",1278,True,1,1
store is undefined in vue 3 class component unit testing,"<p>I am new to unit testing in vue 3 class component. I getting error says store is undefined. Here is my code in Home.vue file.</p>
<pre><code>&lt;script lang=&quot;ts&quot;&gt;
import { Options, Vue } from &quot;vue-class-component&quot;;
import HelloWorld from &quot;@/components/HelloWorld.vue&quot;;
import { useStore } from &quot;vuex&quot;;
import { key } from &quot;@/store&quot;;
import { ProductType } from &quot;@/types/commonTypeDefinitions&quot;;

@Options({
  components: {
    HelloWorld,
  },
})
export default class Home extends Vue {
  store = useStore(key);
  get getAllProducts() {
    return this.store.state.products ? this.store.state.products.groups : null;
  }
  mounted() {
    if (!this.store.state.products) {
      this.store.dispatch(&quot;getJsonData&quot;);
    }

  }
  goToDetail(item: ProductType) {
    localStorage.setItem(&quot;productDetail&quot;, JSON.stringify(item));
    this.store.commit(&quot;setProductDetail&quot;, item);
    const name = item.name.replaceAll(&quot; &quot;, &quot;-&quot;);
    console.log(name);
    this.$router.push(&quot;/detail/&quot; + name);
  }
}
&lt;/script&gt;
</code></pre>
<p>I am using jest for testing. Please help me with this.Thanks.</p>
",https://stackoverflow.com/questions/68402827/store-is-undefined-in-vue-3-class-component-unit-testing,"['vuejs3', 'vuex4']",183,False,1,0
Avoid or bypass multiple decorators in unit testing with pytest,"<p>Similar questions were asked before:</p>
<ul>
<li><a href=""https://stackoverflow.com/questions/9702219/how-to-skip-or-ignore-python-decorators"">How to skip or ignore python decorators</a></li>
<li><a href=""https://stackoverflow.com/questions/41206565/bypassing-a-decorator-for-unit-testing"">Bypassing a decorator for unit testing</a></li>
</ul>
<p><a href=""https://docs.python.org/3/library/functools.html#functools.wraps"" rel=""nofollow noreferrer""><code>functools.wraps</code></a> creates a magic method called <code>__wrapped__</code> in the decorator, which allows to access the wrapped function. When you have multiple decorators, though, this would return an inner decorator, not the original function.</p>
<p>How to avoid or bypass multiple decorators?</p>
",https://stackoverflow.com/questions/65961706/avoid-or-bypass-multiple-decorators-in-unit-testing-with-pytest,"['python', 'python-3.x', 'unit-testing', 'pytest']",639,True,1,1
Spark Dataframe comparison in Unit testing to check the Functionality,"<p>I have created few methods that will transform dataframes into required format and to filter multiple error checks and to update the dataframe based on error rules.</p>
<p>I am new to write unit testing in scala on intelliJ.
I have to write unit testing to compare the actual dataframes with expected result.</p>
<p>Below is the unit test case i wrote for pivot functionality of the dataframe. Similar way i have to compare the obtained datasets with expected dataframe.</p>
<pre><code> @Test
  def testPivotingDataFramePositive(): Unit = {

    val inputDf = spark.read.option(&quot;header&quot;,true).csv(&quot;src/test/resources/input-test-files/pivotInput.csv&quot;)
    val expectedResult = spark.read.option(&quot;header&quot;,true).csv(&quot;src/test/resources/output-test-files/pivotOutput.csv&quot;)
    val actualResult = parserObj.pivotingDataFrame(inputDf)
    assertEquals(expectedResult, actualResult)
}
</code></pre>
<p>Even the above test case is failing by throwing differences, even though both dataframes are same (might be because of the dataframe records ordering at each time).</p>
<p>Even tried the below comparison and it failed by giving output as 0 even though the dataframes are same.</p>
<pre><code>assert (actualResult.except(expectedResult).count() != 0 &amp;&amp; expectedResult.except(actualResult).count != 0)
</code></pre>
<p>How could i test the dataframe transform functionality effectively in unit testing?</p>
",https://stackoverflow.com/questions/69161373/spark-dataframe-comparison-in-unit-testing-to-check-the-functionality,"['scala', 'dataframe', 'unit-testing', 'apache-spark', 'apache-spark-sql']",763,True,1,1
Unit Testing - Passing enum as method parameters in Test Class,"<p>I have a class called Game. I am wondering what is best practice in this situation to pass the enums in the Game class to the Test class as parameters in a method</p>
<p>Game class has the following:</p>
<pre><code>public enum Result
{
  Zero,
  One,
  etc...
}

public int ResultCount(Result result)
{
  switch(result)
  {
    case Result.Zero
         return 0;
    case Result.One
         retun 1;
    etc...
  }
}

public void CurrentResult(Result hometeam, Result awayteam)
{
  setHomeTeamGoals(hometeam);
  setAwayTeamGoals(awayteam);
}
</code></pre>
<p>I then have a unit test class where I want to set the result in the setup</p>
<pre><code> [TestFixture]
    public class Result_is_1_1
    {
        private Game _game;

        [SetUp]
        public void SetUp()
        {
            _game = new Game();
            _game.CurrentResult(Result.One, Result.One);
        }
</code></pre>
<p>It works when I use the following</p>
<pre><code>using static unitTest.Game;
</code></pre>
<p>But I am unsure if this is bad practice/ quick fix etc.</p>
<p>What is the recommended way to do this?</p>
",https://stackoverflow.com/questions/67028826/unit-testing-passing-enum-as-method-parameters-in-test-class,"['c#', '.net', 'unit-testing', 'nunit']",1749,True,1,2
Unit testing an C# Azure Durable Function with external events,"<p>I've got an Azure Durable Function orchestrator that waits for two external events. Once they've both been received, the orchestrator calls an activity function.</p>
<p>Is there a way to unit test this orchestrator, to verify that the activity function is called only after both events have been received?</p>
<p>Here's the orchestrator function code:</p>
<pre><code>[FunctionName(&quot;MyOrchestrator&quot;)]

public static async Task MyOrchestrator(

    [OrchestrationTrigger] IDurableOrchestrationContext context)

{
    var event1 = context.WaitForExternalEvent&lt;string&gt;(&quot;Event1&quot;);
    var event2 = context.WaitForExternalEvent&lt;string&gt;(&quot;Event2&quot;);
    await Task.WhenAll(event1, event2);

    await context.CallActivityAsync&lt;object&gt;(&quot;Activity1&quot;, null);
    context.SetOutput(new { Status = &quot;Complete&quot; });
}
</code></pre>
",https://stackoverflow.com/questions/66773484/unit-testing-an-c-azure-durable-function-with-external-events,"['c#', 'unit-testing', 'azure-functions', 'xunit', 'azure-durable-functions']",1053,True,1,1
How to handle API call rate limit when unit testing?,"<p>I am building an application using YouTube's API. This is my first time using a proper API, so I don't <em>fully</em> understand how it works (hence I am here).</p>
<p>Every time I come to code for the application, I am finding that my unit tests run into the limit pretty quickly. How do people normally handle situations like this? Is it a case of <em>not</em> unit testing? Or there something I can do instead to prevent this issue?</p>
<p>For anyone familiar with YouTube's API, based on <a href=""https://stackoverflow.com/a/15580411/12488201"">this</a>, I am only making requests to retrieve 1-2 videos per test, and I currently have around 10 tests. If I am correct, assuming that I am requesting 2 videos per call, I should be able to run the tests <em>10,000/20 = <strong>500</strong></em> <strong>times</strong>, no?</p>
",https://stackoverflow.com/questions/66516916/how-to-handle-api-call-rate-limit-when-unit-testing,"['api', 'youtube', 'youtube-api']",888,True,1,1
User function not defined within a class and Unit Testing,"<p>I am trying to create a class which can standardize a pandas dataframe. I have created a fit method within the class to get the mean and standard deviation. My aim is to call the fit method in the transform method (defined within the class). However it shows as not defined</p>
<pre><code>import pandas as pd
import numpy as np
import statistics as st

class standardize:

    def fit(self):
        mean = sum(self)/len(self)
        std_dev = round(st.stdev(self),2)
        return mean,std_dev

    def transform(self):
        data_fitted = self.fit()
        data_transformed = []
        for i in self:
            self[i] = (self[i] - data_fitted.mean)/(data_fitted.std_dev)
            data_transformed = data_transformed.append()
        return data_transformed

    def inverse_transform(self):
        data_transformed = self.transform()
        inverse_transformed = []
        for i in data_transformed:
            self.data_transformed[i] = 
            (self.data_transformed[i]*data_fitted.stddev)+(data_fitted.mean)
            inverse_transformed = inverse_transformed.append()
        return inverse_transformed  


stock_data = {'Day': ['Day_1','Day_2','Day_3','Day_4','Day_5','Day_6','Day_7'],
              'Daily_Closing_Price': [7,8,9,10,11,12,13]}
series_1 = pd.DataFrame(stock_data, columns = ['Day','Daily_Closing_Price'])
x = standardize.fit(series_1['Daily_Closing_Price'])
print(x)
y = standardize.transform(series_1['Daily_Closing_Price'])
print(y)
z = standardize.inverse_transform(series_1['Daily_Closing_Price'])
print(z)
</code></pre>
<p>I get the initial output of print(x) with mean and standard deviation value. However after that I get the following error.</p>
<pre class=""lang-none prettyprint-override""><code>(10.0, 2.16)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
&lt;ipython-input-89-0ee877b48308&gt; in &lt;module&gt;
        4 x = standardize.fit(series_1['Daily_Closing_Price'])
        5 print(x)
  ----&gt; 6 y = standardize.transform(series_1['Daily_Closing_Price'])
        7 z = standardize.inverse_transform(series_1['Daily_Closing_Price'])
        8 print(y)

&lt;ipython-input-87-71f5759b9dac&gt; in transform(self)
        7 
        8     def transform(self):
        ----&gt; 9         data_fitted = self.fit()
        10         data_transformed = []
        11         for i in self:

        ~\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
        5177             if self._info_axis._can_hold_identifiers_and_holds_name(name):
        5178                 return self[name]
        -&gt; 5179             return object.__getattribute__(self, name)
        5180 
        5181     def __setattr__(self, name, value):

        AttributeError: 'Series' object has no attribute 'fit'
</code></pre>
<p>I have 3 main questions here.</p>
<ol>
<li>Is it compulsory or prudent to write an <code>__init__</code> method for this use case. If yes, then how would that fit in?</li>
<li>How to use the fit method for transform method (and subsequently transform for <code>inverse_transform</code>)?</li>
<li>How do I write a unit test class to make sure the class correctly standardizes a column of data, and then another unit test to make sure it correctly inverse transforms a column of standardized data.</li>
</ol>
",https://stackoverflow.com/questions/65659872/user-function-not-defined-within-a-class-and-unit-testing,"['python', 'function', 'unit-testing', 'oop', 'initialization']",99,False,1,0
Gitlab-CI Laravel unit testing fails online but works locally,"<p>I have a similar issue as in this <a href=""https://stackoverflow.com/questions/53695165/test-fails-only-in-gitlab-ci-locally-successful"">post</a>: My unit/feature test work locally, but fail online. I have already figured out that the test which fail are probably related to the <em>Laravel Storage API</em> which is used with the local driver.</p>
<p>This is the code is suspect is causing issues.</p>
<pre class=""lang-php prettyprint-override""><code>            // DELETE IF EXISTS
            if (Storage::exists($path))
                Storage::delete($path);

            // COPY BOILERPLATE
            Storage::copy('bp-template.py', $path);

            // APPEND
            Storage::append($path, $validator['complexFormula']);

</code></pre>
<p>In my <code>.env.testing</code> file, I have set</p>
<pre class=""lang-sh prettyprint-override""><code>FILESYSTEM_DRIVER=local
</code></pre>
<p>I created the docker image for testing by following <a href=""https://docs.gitlab.com/ee/ci/examples/laravel_with_gitlab_and_envoy/#create-a-container-image"" rel=""nofollow noreferrer"">these</a> instructions.</p>
",https://stackoverflow.com/questions/70497374/gitlab-ci-laravel-unit-testing-fails-online-but-works-locally,"['php', 'laravel', 'testing', 'gitlab', 'gitlab-ci']",118,True,0,1
How to mock DynamodbContext BatchWrite for unit testing in net,"<p>I have a method that adds Items in the DynamoDb table using DynamoDbContext.</p>
<pre><code>var batchWriteObj = context.CreateBatchWrite&lt;myDynamoDBModel&gt;
                                            (new DynamoDBOperationConfig { TableNamePrefix = &quot;abc&quot; });
                    batchWriteObj.AddPutItem(myDynamoDBModel);
</code></pre>
<p>I want to test this piece in my Unit test.
Since BatchWrite does not have any constructor, and also its properties are not virtual. I am unable to create a mock for it.</p>
<p>Is there any way I can test this piece of code? maybe by mocking the BatchWrite?</p>
",https://stackoverflow.com/questions/66710616/how-to-mock-dynamodbcontext-batchwrite-for-unit-testing-in-net,"['c#', 'unit-testing', 'amazon-dynamodb', 'nunit']",1268,True,0,1
Django Unit Testing : MultipleChoiceField dependent on objects created during setUp,"<p>I'm trying to test a form which has a <code>MultipleChoiceField</code> which is populated with content from the database. Currently the test is failing, because the choices passed are invalid. The reason being that the field doesn't seem to have any data on it.</p>
<p>TEST RESULTS &amp; DEBUG PRINT STATEMENTS</p>
<pre><code>&lt;QuerySet []&gt;
System check identified no issues (0 silenced).
&lt;QuerySet [&lt;Subject: Subject object (1)&gt;, &lt;Subject: Subject object (2)&gt;]&gt;
&lt;ul class=&quot;errorlist&quot;&gt;&lt;li&gt;subjects&lt;ul class=&quot;errorlist&quot;&gt;&lt;li&gt;
Select a valid choice. Subject object (1) is not one of the available choices.&lt;/li&gt;&lt;/ul&gt;&lt;/li&gt;&lt;/ul&gt;
</code></pre>
<p>CODE</p>
<pre class=""lang-py prettyprint-override""><code># TEST
def test_lecturer(self):
        print(Subject.objects.all())
        subjects = [self.subject, self.subject2]
        response = self.client.post(reverse('manager:register'),
                {'email' : self.lecturer_email, 
                'is_lecturer' : True,
                'subjects' : subjects })
        lecturer = UserProfile.objects.get(email=self.lecturer_email)
        self.assertEqual(lecturer.can_edit, subjects)

# FORM
class UserCsvForm(forms.Form):
    try:
        subjects = [(x,x.title) for x in Subject.objects.all()]
    except:
        subjects = []

    print(Subject.objects.all())
    ... OTHER FIELDS ...

    subjects = forms.MultipleChoiceField(choices=subjects, required=False)
</code></pre>
<p>It seems like the form is being called before the test is setup, but shouldn't the form only be generated once the post request is sent?</p>
",https://stackoverflow.com/questions/66291708/django-unit-testing-multiplechoicefield-dependent-on-objects-created-during-se,"['python', 'django', 'unit-testing']",89,False,0,1
Angular 12 Unit Testing: Directive with Can&#39;t bind to &#39;scrollIntoForm&#39;,"<p>I have a scroll-into-new-form.directive.ts file</p>
<pre><code>import {
  Directive,
  ElementRef,
  HostListener,
  Input,
  OnChanges,
} from '@angular/core';

/***
 * @example
 *  &lt;div [scrollIntoForm] [index]=&quot;1&quot;&gt;
 *  &lt;/div&gt;
 */
@Directive({
  selector:
    // eslint-disable-next-line
    '[scrollIntoForm]',
})
export class ScrollIntoNewFormDirective implements OnChanges {
  constructor(private el: ElementRef) {}
  @Input() public index: number;

  ngOnChanges(changes) {
    if (changes.index.currentValue != 0 &amp;&amp; changes.index.firstChange) {
      this.el.nativeElement.scrollIntoView({
        block: 'center',
        inline: 'nearest',
        behavior: 'smooth',
      });
    }
  }

  @HostListener('click')
  onChangeOrder() {
    this.el.nativeElement.scrollIntoView({
      block: 'center',
      inline: 'nearest',
      behavior: 'smooth',
    });
  }
}

</code></pre>
<p>In component use:
<code>&lt;div [formGroupName]=&quot;i&quot; [scrollIntoForm] [index]=&quot;i&quot;&gt;&lt;/div&gt;</code>
In file component specs file: I declared ScrollIntoNewFormDirective. But when I run test, it show error:</p>
<p><code>Template parse errors: Can't bind to 'scrollIntoForm' since it isn't a known property of 'div'. (&quot;&quot;&gt; &lt;div [formGroupName]=&quot;i&quot; [ERROR -&gt;][scrollIntoForm] [index]=&quot;i&quot;&gt; &lt;span class=&quot;label&quot;&gt;連絡先: 優先度 {{ i + 1 }}&lt;/span&gt; &quot;): ng:///DynamicTestModule/CreatedAclFormComponent.html@249:35</code></p>
<p>Please help me to fix it!!!</p>
",https://stackoverflow.com/questions/69356139/angular-12-unit-testing-directive-with-cant-bind-to-scrollintoform,"['angular-directive', 'directive', 'angular12']",161,False,0,0
Angular unit testing &quot;SPEC HAS NO EXPECTATIONS&quot; and &quot;error: Timeout&quot;,"<p>I'm trying to write a test for my post function. This is an Angular app and I'm using Karma/Jasmine to test.</p>
<p>This was my test:</p>
<pre><code> it(`should post data`, ()=&gt;{
    const service: ApiService = TestBed.get(ApiService);
    service.sendMessage(data).subscribe(values =&gt;{
      expect(values).toBe('observable value');
    });
  });
</code></pre>
<p>Both methods &quot;pass&quot; the test, but have the &quot;SPEC HAS NO EXPECTATIONS&quot; message. The fix I have found for this is to try to get a promise from it. I tried two ways:</p>
<p>Adding &quot;done()&quot;</p>
<pre><code> it(`should post data`, (done:any)=&gt;{
    const service: ApiService = TestBed.get(ApiService);
    service.sendMessage(data).subscribe(values =&gt;{
      expect(values).toBe('observable value');
      done();
    });
  });
</code></pre>
<p>or rewriting the whole thing to this:</p>
<pre><code>it('should post data', inject([ApiService], async (service: ApiService) =&gt; {
    const tada = await service.sendMessage(data).toPromise();
    expect(tada).toBe('observable data');
  }));
</code></pre>
<p>These call the test to fail due to timing out.(<strong>Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)</strong>) So, to fix that I tried increasing the timeout. I used</p>
<pre><code>jasmine.DEFAULT_TIMEOUT_INTERVAL = 150000;
</code></pre>
<p>but even after longer periods, it would still timeout. This makes me think that's not the right solution, but I couldn't find answers beyond what I've tried. I have also tried moving parts around, like putting the expect() outside of the subscribe, etc.</p>
<p>EDIT: HERE IS THE WHOLE UNIT TEST FILE</p>
<pre><code>import { TestBed } from '@angular/core/testing';
import { ApiService } from './api.service';
import { HttpClientTestingModule } from '@angular/common/http/testing';

describe('ApiService', () =&gt; {
  let service: ApiService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [ApiService]
    });
    // service = TestBed.inject(ApiService);
  });

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

  let data = {
    name: &quot;fdsgs&quot;,
    sex: &quot;gfjhghj&quot;,
    address:&quot;ghmfgj&quot;,
    county: &quot;ghjdgfhj&quot;,
    contactMethod: [&quot;dfghjsfdghd&quot;, &quot;helloworld&quot;],
    daysAvailable: [&quot;dfghfdgh&quot;, &quot;heloo world&quot;],
    timesAvailable: [&quot;sdfghfgh&quot;, &quot;hello world&quot;],
    aboutPerson: [&quot;stfghfdghd&quot;, &quot;sadf&quot;],
    aboutChildren: [&quot;jdfhjtd&quot;, &quot;awert&quot;],
    questions: &quot;gfhdfgh&quot;,
    howTheyHeardOfUs: [&quot;dfghasg&quot;, &quot;fasfg&quot;]
  }

  it(`should post data`, (done: DoneFn)=&gt;{
    const service: ApiService = TestBed.get(ApiService);
    service.sendMessage(data).subscribe(values =&gt;{
      expect(values).toBe('observable value');
      done();
    });
  });
</code></pre>
<p>AND HERE IS THE API SERVICE FILE:</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  sendMessage(data:any){
    return this.http.post&lt;any&gt;(&quot;URL&quot;, data)
    .pipe(map((res:any)=&gt;{
      return res;
    }));
  }
}
</code></pre>
",https://stackoverflow.com/questions/70252864/angular-unit-testing-spec-has-no-expectations-and-error-timeout,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1116,True,0,1
"Python unit testing with PyTest, stuck on more advanced testing","<p>I have been using PyTest for some time now to write some simple tests (like the ones you find in tutorials and youtube video's) and I thought now it was time to start writing actual test for our python scripts. The scripts are way more advanced than any shown in tutorials so I am getting a bit stuck. I do not want the entire correct answer, but rather a nudge in the right direction if possible. Here is my issue:</p>
<p>We have a script that reads a .md text file and converts it to a pdf file based on an external template. Part of the script is here below (I removed most of it because I first just want to have 1 running test)</p>
<pre><code>class DocumentationEngine:

    def __init__(self, title, subtitle, series, style='TIIStyle_Digital_Aug_2020', templateFile='template.docet', tableOfContents=True, listOfFigures=False, listOfTables=False):
        self.title = title
        self.subtitle = subtitle
        self.series = series
        self.style = style
        self.template = {}
        self.hasTOC = tableOfContents
        self.hasLOF = listOfFigures
        self.hasLOT = listOfTables
        self.loadTemplate(templateFile)

    def loadTemplate(self, file='template.docet'):
        with open(file, &quot;r&quot;) as templatefile:
            lines = templatefile.readlines()
            key = &quot;dummy&quot;
            value = &quot;&quot;
            for line in lines:
                line = line.strip()
                if line.startswith('[') and line.endswith(']'):
                    self.template[key] = value
                    key = line[1:-1]
                    value = &quot;&quot;
                else:
                    value += line + '\n'

    def build(self, versions=[], content='', filename='Documenter\\_Autogenerated'):
        document = self.template[&quot;doc&quot;]
        document = document.replace(&quot;%%style%%&quot;, self.style)
        document = document.replace(&quot;%%body%%&quot;,
                                    self.buildFirstPage() +
                                    self.buildTableOfContents() +
                                    self.buildListOfFigures() +
                                    self.buildListOfTables() +
                                    self.buildVersionTable(versions, filename) +
                                    self.buildContentPages(content=content) +
                                    self.buildLastPage()
                                    )
        return document


    def buildLastPage(self):
        return self.template[&quot;last_page&quot;]
</code></pre>
<p>I am trying to write a simple unit test for the buildLastPage method and have been stuck for several days now.</p>
<p>I am not sure whether or not I need to mock the template file, use a fixture and/or if I can actually test only that method with all dependencies.</p>
<p>I started with the following:</p>
<pre><code>from doceng import DocumentationEngine
import pytest


class Test:
    def test_buildLastPage(self):
        build_last_page = DocumentationEngine()

        assert build_last_page.template(1) == 1
</code></pre>
<p>which gives me an error regarding 3 required arguments. When adding the arguments like this:</p>
<pre><code>from doceng import DocumentationEngine
import pytest


class Test:
    def test_buildLastPage(self, title, subtitle, series):
        build_last_page = DocumentationEngine()

        assert build_last_page.template(1) == 1
</code></pre>
<p>which gives me an error that the fixture is not found.</p>
<p>I added a fixture in conftest.py file like this:</p>
<pre><code>import pytest
from doceng import DocumentationEngine


@pytest.fixture
def title(title):
    return title(&quot;test&quot;)
</code></pre>
<p>which will get me another error, recursive dependency involving fixture 'title' detected</p>
<p>I'm quite stuck so any nudge in the right direction for a newbie would be highly appreciated</p>
",https://stackoverflow.com/questions/69152546/python-unit-testing-with-pytest-stuck-on-more-advanced-testing,"['python', 'unit-testing', 'pytest']",363,False,0,1
How to cover arrow functions in unit testing in angular?,"<p><code>this.service = () =&gt; { -- statements -- }</code></p>
<p>The above statement is to be tested using jasmine unit testing in angular.
Can i get some suggestions for that ?</p>
<p><code>it(&quot;should service call&quot;,()=&gt;{ // i want to call the arrow function here like component.service.? what to use in place of '?'. })</code></p>
",https://stackoverflow.com/questions/66257552/how-to-cover-arrow-functions-in-unit-testing-in-angular,"['node.js', 'angular', 'typescript', 'unit-testing', 'jasmine']",1427,True,-1,1
Swift UI: Unit testing @Published var in an ObservableObject ViewModel,"<p>So I'm trying to write a unit test to test a view model function however it is an Async function and in the test I'm trying to write it will run synchronously. I've seen a few examples online e.g</p>
<pre><code>listViewModel.$list.sink { _ in
    XCTAssertEqual(listViewModel.list?.items.count , 1)
    actionExpectation.fulfill()
}
wait(for: [actionExpectation], timeout: 1)
</code></pre>
<p>and also trying the solution given here <a href=""https://stackoverflow.com/questions/62154604/unit-testing-an-observableobject-in-swift-test-driven-development"">Unit testing an @ObservableObject in Swift Test Driven Development</a></p>
<p>I've not had any luck trying to test it, any ideas?</p>
<p>ViewModel</p>
<pre><code>class ListViewModel: ObservableObject {
    @Published var list: List?
    
    let services: Services

    init(services: Services) {
        self.services = services
        getList()
    }

    func getList() {
        if let listService = self.services.resolve(ListService.self) {
            ListService().getList() { [weak self] result in
                switch result {
                    case .success(let dataRecieved):
                        DispatchQueue.main.async {
                            self?.list = dataRecieved
                        }
                    case .failure(let error):
                        print(error)
                }
            }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/67443559/swift-ui-unit-testing-published-var-in-an-observableobject-viewmodel,"['ios', 'swift', 'swiftui', 'xctest']",1055,False,0,1
How to raise an error with decorator for unit testing?,"<p>I would like to do something in my unit testing before it fails and using decorator to do so</p>
<p>Here is my code :</p>
<pre><code>import requests
import unittest
import test


class ExceptionHandler(object):
    def __init__(self, f):
        self.f = f

    def __call__(self, *args, **kwargs):
        try:
            self.f(*args, **kwargs)
        except Exception as err:
            print('do smth')
            raise err


class Testing(unittest.TestCase):
    @ExceptionHandler
    def test_connection_200(self):
        r = requests.get(&quot;http://www.google.com&quot;)
        self.assertEqual(r.status_code, 400)


if __name__ == '__main__':
    unittest.main(verbosity=2)
</code></pre>
<p>But it throws me an :</p>
<pre><code>TypeError: test_connection_200() missing 1 required positional argument: 'self'
</code></pre>
<p>How can I do something when my test fail, then having the normal failing behavior of unitest?</p>
<p>Edit :
I would like to do something before my test fail like write a  log and then continue the normal process of failing.</p>
<p>If possible with a decorator.</p>
<p>Edit bis the solution thanks to @Thymen :</p>
<pre><code>import requests
import unittest
import test


class ExceptionHandler(object):
    def __init__(self, f):
        self.f = f

    def __call__(self, *args, **kwargs):
        try:
            self.f(*args, **kwargs)
        except Exception as err:
            print('do smth')
            raise err


class Testing(unittest.TestCase):
    def test_connection_200(self):
        @ExceptionHandler
        def test_connection_bis(self):
            r = requests.get(&quot;https://www.google.com&quot;)
            print(r.status_code)
            self.assertEqual(r.status_code, 400)
        test_connection_bis(self)


if __name__ == '__main__':
    unittest.main(verbosity=2)
</code></pre>
",https://stackoverflow.com/questions/67032032/how-to-raise-an-error-with-decorator-for-unit-testing,"['python-3.x', 'unit-testing']",427,True,0,1
It.IsAny&lt;T&gt; for unit testing for type:- params Action&lt;IResultsReader&gt;[],"<p>I am writing unit test and i have this function:-</p>
<pre><code>void QueryMultipleFromStoredProcedure(string sproc, object parameters, params Action&lt;IResultsReader&gt;[] readerFuncs);
</code></pre>
<p>I am not sure what is the type for params Action&lt; IResultsReader &gt;[]. I wrote this in my unit test:-</p>
<pre><code>mockDataInfrastructure.Setup(x =&gt; x.QueryMultipleFromStoredProcedure(It.IsAny&lt;string&gt;(), It.IsAny&lt;object&gt;(), It.IsAny&lt;T&gt;));
</code></pre>
<p>what would be the last one return type?</p>
",https://stackoverflow.com/questions/66420263/it-isanyt-for-unit-testing-for-type-params-actioniresultsreader,"['c#', 'unit-testing', 'mocking']",402,True,0,1
ASP.NET: Unit testing controller fails because default response is null,"<p>I'm trying to unit test a controller. <code>SomeController</code> inherits from <code>BaseController</code>. <code>BaseController</code> inherits from <code>Microsoft.AspNetCore.Mvc.Controller</code>.</p>
<p>My NUnit tests fail because a property <code>Response</code> in <code>Controller</code> is always null when running my tests. My test currently looks like this:</p>
<pre><code>[Test]
public void GetByFilter_ShouldReturnABadRequest_WhenModelStateIsInvalid()
{
    _sut.ModelState.AddModelError(&quot;SessionName&quot;, &quot;Required&quot;);
    var result = _sut.GetByFilter(_mockedFilter);
    Assert.IsAssignableFrom&lt;BadRequestObjectResult&gt;(result);
}
</code></pre>
<p><code>_sut</code> is set by <code>[SetUp]</code> with this method:</p>
<pre><code>protected override void InitSut() =&gt; _sut =
        new SomeController(_mockedLogger, _mockedService, _mockedRepository, _mockedHtmlSanitizer);
</code></pre>
<p>The code that fails on tests but works fine when running looks like this:</p>
<pre><code>Response.Headers.Add(&quot;RowCount&quot;, result.Count().ToString());
return Ok(result);
</code></pre>
<p>Seems I need to do something to have the BaseController set the Response. In production the Response is filled with an instance of <code>HttpDefaultResponse</code>, but Response is <code>readonly</code>, so no way to set this myself.</p>
<p>I have tried following testing guides like this, but without luck:<br>
<a href=""https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api</a></p>
<p>What do I need to do to start my controllers correctly and thus pass my tests?</p>
",https://stackoverflow.com/questions/69466131/asp-net-unit-testing-controller-fails-because-default-response-is-null,"['c#', 'asp.net', 'asp.net-mvc', 'unit-testing']",561,False,0,1
Unit testing Room android - This job has not completed yet,"<p>I am currently unit testing my local data source which uses Room.
I created a test class:</p>
<pre><code>/**
 * Integration test for the [WatchListLocalDataSource].
 */
@RunWith(AndroidJUnit4::class)
@MediumTest
class WatchListLocalDataSourceTest {

    private lateinit var sut: WatchListLocalDataSourceImpl
    private lateinit var database: ShowsDatabase
    private lateinit var entityMapper: ShowEntityMapper

    private lateinit var testDispatcher: TestCoroutineDispatcher
    private lateinit var testScope: TestCoroutineScope

    @Before
    fun setup() {
        entityMapper = ShowEntityMapper()
        testDispatcher = TestCoroutineDispatcher()
        testScope = TestCoroutineScope(testDispatcher)
        val context = InstrumentationRegistry.getInstrumentation().context
        // using an in-memory database for testing, since it doesn't survive killing the process
        database = Room.inMemoryDatabaseBuilder(
            context,
            ShowsDatabase::class.java
        )
            .setTransactionExecutor(testDispatcher.asExecutor())
            .setQueryExecutor(testDispatcher.asExecutor())
            .build()

        sut = WatchListLocalDataSourceImpl(database.watchListDao(), entityMapper)
    }

    @After
    @Throws(IOException::class)
    fun cleanUp() {
        database.close()
    }

    @Test
    @Throws(Exception::class)
    fun observeWatchedShows_returnFlowOfDomainModel()  = testScope.runBlockingTest {

        val showId = 1
        sut.addToWatchList(mockShow(showId))

        val watchedShows: List&lt;Show&gt; = sut.observeWatchedShows().first()

        assertThat(&quot;Watched shows should contain one element&quot;, watchedShows.size == 1)
        assertThat(&quot;Watched shows element should be ${mockShow(showId).name}&quot;, watchedShows.first() == mockShow(showId))
    }
}
</code></pre>
<p>However, the test does not complete, noting:</p>
<pre><code>java.lang.IllegalStateException: This job has not completed yet
</code></pre>
<p>The actual method in the <code>sut</code> is:</p>
<pre><code>override suspend fun addToWatchList(show: Show) = withContext(Dispachers.IO) {
    watchListDao.insertShow(WatchedShow(entityMapper.mapFromDomainModel(show)))
}
</code></pre>
",https://stackoverflow.com/questions/65550564/unit-testing-room-android-this-job-has-not-completed-yet,"['android', 'android-room', 'kotlin-coroutines', 'android-unit-testing']",834,True,0,1
Using Firestore emulator for unit testing in a packaged project,"<p>I am trying to mock a firestore local client to run my unit integration tests in my Go project, but I have packaged the project so that, firestore is initialized in a separate package and used throughout the other packages.</p>
<p>So I am kind of confused about where should I define the local firestore client and the <code>TestMain(m *testing.M)</code> function. Below is the basic idea of my file structure.</p>
<pre><code>main.go
main_test.go (This could also need firestore local connection)
pkg
|____datastore (where firestore clients are defined)
     |___datastore.go
     |___testing.go (I intended to have my TestMain(m *testing.M) function to run the emulator)
     |___ .....
|____pkg2
     |___myfile.go (go file that I use the firestore client to deal with firestore db)
     |___myfile_test.go ( tests I am going to write that I need to use the local emulator)
     |___ .....
</code></pre>
<p>So I am wondering how this kind of a testing can be achieved. Waitng for help. Also I got the idea of firestore emulator using this <a href=""https://www.captaincodeman.com/2020/03/04/unit-testing-with-firestore-emulator-and-go"" rel=""nofollow noreferrer"">link</a></p>
",https://stackoverflow.com/questions/66066212/using-firestore-emulator-for-unit-testing-in-a-packaged-project,"['unit-testing', 'go', 'google-cloud-firestore', 'integration-testing']",498,True,1,1
Unit testing methods in Service Layer of Spring Boot Application,"<p>I'm facing issues with Service Layer Test of a Spring Boot Application. Please consider that relevant imports and done and there are NO problems with gradle/pom dependencies.</p>
<p>Let's say I want to test <strong>scheduleFreeze</strong> method of class Sample</p>
<pre><code>public class Sample{

    @Autowired
    private RDAO rDAO;

    @Autowired
    private RHelper rHelper;

    public void scheduleFreeze(){

    
    HashMap&lt;String, HashSet&lt;String&gt;&gt; myMap = rDAO.myMap(rHelper.getSortKey());
    //Some code to format map by making its values comma separated

    }

}
</code></pre>
<p>I'm writing a Service Layer test SampleTest. Here's the sample</p>
<pre><code>
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
@Slf4j
public class SampleTest {

    @InjectMocks
    public Sample sample;

    @Mock
    private RDAO rDAO;

    @Mock
    private RHelper rHelper;

    private HashMap&lt;String, HashSet&lt;String&gt;&gt; testMap; // to be used for assertions

    private void uploadToDB(){
        //This fn creates table, creates dummy data and populates data to db tables
        //Also updates testMap
    }

    @Before
    public void setUp(){

     MockitoAnnotations.initMocks(this);
     uploadToDB();

    }

    @Test
    public void scheduleFreezeTest() {
    
       sample.scheduleFreeze();

    }
}
</code></pre>
<p>I want the to cross verify/assert the contents of the <strong>testMap</strong> that I'm updating while populating to DB with the contents of <strong>myMap</strong> formed in scheduleFreeze function. How can I achieve this?</p>
<p>Edit - Ideally, I feel real methods of class Sample must be called to see the content in myMap</p>
",https://stackoverflow.com/questions/66092035/unit-testing-methods-in-service-layer-of-spring-boot-application,"['java', 'spring-boot', 'junit', 'mockito', 'microservices']",285,False,0,0
How to mock a @Header request for NestJS unit testing,"<p>I am attempting to implement unit testing in NestJS. However, I am new to both NestJS and unit testing in general.
So, what I need to do is to pass a test that gets all projects from a gitlab profile.</p>
<pre><code>@Get()
getProjects(@Headers() headers: any): Observable&lt;Project[]&gt; {
if (!headers.token) {
  throw new HttpException('Missing User Token', HttpStatus.BAD_REQUEST);
 }
 return this.projectsService.listProjects(headers.token);
}
</code></pre>
<p>This is the code in the project.controller.ts file. It works well, and returns an observable with the list of projects. However, it requires a header to be sent through the HTTP request(Which is received using the @Headers decorator), as the gitlab is locked behind an authentication that requires a token to be passed through the header of the request.</p>
<p>I have attempted to mock the header to no success, and I was wondering if anyone has any idea how to proceed with the unit testing for that get request.</p>
",https://stackoverflow.com/questions/70497975/how-to-mock-a-header-request-for-nestjs-unit-testing,"['unit-testing', 'jestjs', 'mocking', 'nestjs']",2136,True,0,1
Unit testing app using node.js and azure functions with SQL,"<p>How can I start unit testing my application?
First of I wanna test that I can access my SQL database.
Second i wanna test how i can test the creation of a new User</p>
<p>I can't seem to find any documentation on this subject</p>
<p>Which kind of test framework can i use, mocha &amp; chai?</p>
<p>This is my azure function for register</p>
<pre><code>    module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.')
    try {
        await db.startDb(); //start db connection
    } catch (error) {
        console.log(&quot;Error connecting to the database&quot;, error.message)
    }
    
    switch (req.method) {
        case 'GET':
            await get(context, req);
            break;
        case 'POST':
            await post(context, req);
            break
        default:
            context.res = {
                body: &quot;Please get or post&quot;
            };
            break
    }
}

async function get(context, req){
    try{
        let name = req.query.name;
        let user = await db.select(name)
        context.res = {
            body: user
        };
    } catch(error){
        context.res = {
            status: 400,
            body: `No user - ${error.message}`
        }
    }
}

async function post(context, req){
    try{
        let payload = req.body;
        await db.insert(payload)
        console.log(payload)
        
        context.res = {
            body: [&quot;succes&quot;]
        }
    } catch(error){
        context.res = {
            status: 400,
            body: error.message
        }
    }
}
</code></pre>
<p><strong>This is my DB file</strong></p>
<pre><code>const { Connection, Request, TYPES } = require('tedious');
const config = require('./config.json');
const jwt = require(&quot;jsonwebtoken&quot;);
const safeJWT = require(&quot;../middleware/Jwt&quot;)
const bcrypt = require(&quot;bcryptjs&quot;);

var connection = new Connection(config);

function startDb() {
    return new Promise((resolve, reject) =&gt; {
        connection.on('connect', (err) =&gt; {
            if (err) {
                console.log('Connection failed')
                reject(err)
                throw (err);
            } else {
                console.log('Connected')
                resolve();
            }
        })
        connection.connect();
    })
}
module.exports.sqlConnection = connection
module.exports.startDb = startDb
</code></pre>
<p><strong>This is some of my register.js file</strong></p>
<pre><code>    fetch(&quot;http://localhost:7071/api/register&quot;, {
        method: 'POST',
        body: JSON.stringify({
            username: username,
            email: email,
            password: password
        }),
        headers: {
            &quot;Content-Type&quot;: &quot;application/json; charset-UTF-8&quot;
        }
    }).then((response) =&gt;
        response.json()).then((data) =&gt; {
            if(data[0] = &quot;succes&quot;){
            location.href = &quot;login.html&quot;
            } else {
                alert(&quot;failed&quot;)
            }
        }).catch((err) =&gt; {
            console.log(err)
        })
})
</code></pre>
",https://stackoverflow.com/questions/67473484/unit-testing-app-using-node-js-and-azure-functions-with-sql,"['javascript', 'sql', 'node.js', 'azure', 'unit-testing']",229,True,0,1
How to bypass (custom) MessageBoxes when unit testing with Moq?,"<p><strong>Update:</strong></p>
<p>Added requested table drawing code, where the MessageBoxService.Show() called.</p>
<pre><code>/// &lt;summary&gt;
    /// Draws the classic sudoku table with the given size.
    /// &lt;/summary&gt;
    protected override void Draw(object o)
    {
        if (GetCurrentTableViewModel() != null &amp;&amp; GetCurrentTableViewModel().AreAnyCellsFilled())
        {
            var messageBoxResult = MessageBoxService.Show(
               Resources.MessageBox_DrawIfNumbersArePresented,
               Resources.MessageBox_Question_Title, MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (messageBoxResult == MessageBoxResult.No || messageBoxResult == MessageBoxResult.Cancel)
            {
                return;
            }
        }

        SudokuBoardSize sudokuBoardSize = (SudokuBoardSize)o;

        bool oldDiagonalRulesStatus = AreDiagonalRulesApplied;
        if (sudokuBoardSize.Height == 9 &amp;&amp; sudokuBoardSize.Width == 9)
        {
            SudokuBoardControl = new UcClassicSudoku9x9Table();
            _actualSudokuBoard = CreateBoard(sudokuBoardSize, (BaseSudokuTableViewModel)SudokuBoardControl.DataContext, false);
        }
        else if (sudokuBoardSize.Height == 6 &amp;&amp; sudokuBoardSize.Width == 6)
        {
            SudokuBoardControl = new UcClassicSudoku6x6Table();
            _actualSudokuBoard = CreateBoard(sudokuBoardSize, (BaseSudokuTableViewModel)SudokuBoardControl.DataContext, false);
        }
        else
        {
            SudokuBoardControl = new UcClassicSudoku4x4Table();
            _actualSudokuBoard = CreateBoard(sudokuBoardSize, (BaseSudokuTableViewModel)SudokuBoardControl.DataContext, false);
        }

        ((BaseClassicSudokuTableViewModel)SudokuBoardControl.DataContext).AreDiagonalRulesApplied = oldDiagonalRulesStatus;
        SolutionCounter = string.Empty;
        IsSolutionCounterVisible = false;
        _solutions.Clear();
    }
</code></pre>
<p>I am new on Stackoverflow, so sorry for any mistakes.</p>
<p>I am developed a Sudoku solver hobby project and I would like to add Unit tests to it. It is fully MVVM. (<a href=""https://github.com/denesdavid/Solvedoku"" rel=""nofollow noreferrer"">https://github.com/denesdavid/Solvedoku</a>)</p>
<p>I wanted to test 'the drawing of a new empty table' feature when there is at least one filled cell in the current Sudoku. The software asks you in this case if you really want to draw a new one. I would like to bypass this question, I mean...simulating to press on the Yes button. I read that Moq is perfect for this, but it is not working for me currently. The question pops up during unit testing, but I have to click on Yes manually.</p>
<p>Here is my test:</p>
<pre><code>[TestMethod]
    public void Draw9x9TableWithAlreadyFilledCellsTest()
    {
        Mock&lt;IMessageBoxService&gt; messageBoxMock = new Mock&lt;IMessageBoxService&gt;(MockBehavior.Strict);
        messageBoxMock.Setup(m =&gt;
            m.Show(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;MessageBoxButton&gt;(),
            It.IsAny&lt;MessageBoxImage&gt;()));
        messageBoxMock.SetReturnsDefault(MessageBoxResult.OK);
        
        ClassicSudokuViewModel classicSudokuViewModel = new ClassicSudokuViewModel(messageBoxMock.Object);
        SudokuBoardSize sudokuBoardSize = new SudokuBoardSize();
        sudokuBoardSize.Height = 9;
        sudokuBoardSize.Width = 9;
        sudokuBoardSize.BoxCountX = 3;
        sudokuBoardSize.BoxCountY = 3;

        
        BaseSudokuTableViewModel tableViewModel = classicSudokuViewModel.GetCurrentTableViewModel();
        tableViewModel.Cells[0][0] = &quot;1&quot;;
        classicSudokuViewModel.DrawSudokuCommand.Execute(sudokuBoardSize);
        object actualBoard = classicSudokuViewModel.SudokuBoardControl;
        tableViewModel = classicSudokuViewModel.GetCurrentTableViewModel();

        Assert.AreEqual(typeof(UcClassicSudoku9x9Table), actualBoard.GetType());
        Assert.AreEqual(string.Empty, tableViewModel.Cells[0][0]);
        Assert.AreEqual(false, classicSudokuViewModel.AreDiagonalRulesApplied);
        Assert.AreEqual(string.Empty, classicSudokuViewModel.SolutionCounter);
        Assert.AreEqual(false, classicSudokuViewModel.IsSolutionCounterVisible);
        Assert.AreEqual(0, classicSudokuViewModel.Solutions.Count);
    }
</code></pre>
<p>IMessageBoxService:</p>
<pre><code>public interface IMessageBoxService
{
    /// &lt;summary&gt;
    /// Shows a MessageBox with the given text, title, button(s) and image.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;messageText&quot;&gt;Text of the MessageBox.&lt;/param&gt;
    /// &lt;param name=&quot;title&quot;&gt;Title of the MessageBox&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxButton&quot;&gt;Button(s) of the MessageBox&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxImage&quot;&gt;Image of the MessageBox&lt;/param&gt;
    /// &lt;returns&gt;MessageBoxResult&lt;/returns&gt;
    MessageBoxResult Show(string messageText, string title, MessageBoxButton messageBoxButton,
        MessageBoxImage messageBoxImage);

    /// &lt;summary&gt;
    /// Shows a MessageBox with the given text, title, button(s), image and style.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;messageText&quot;&gt;Text of the MessageBox.&lt;/param&gt;
    /// &lt;param name=&quot;title&quot;&gt;Title of the MessageBox&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxButton&quot;&gt;Button(s) of the MessageBox&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxImage&quot;&gt;Image of the MessageBox&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxStyle&quot;&gt;Style of the MessageBox&lt;/param&gt;
    /// &lt;returns&gt;MessageBoxResult&lt;/returns&gt;
    MessageBoxResult Show(string messageText, string title, MessageBoxButton messageBoxButton,
        MessageBoxImage messageBoxImage, Style messageBoxStyle);
}
</code></pre>
<p>}</p>
<p>MessageBoxService:</p>
<pre><code>class MessageBoxService : DependencyObject, IMessageBoxService
{
    private Style _messageBoxStyle = (Style)Application.Current?.Resources[&quot;MessageBoxStyle&quot;];

    /// &lt;summary&gt;
    /// Displays a messagebox with the given parameters.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;messageText&quot;&gt;Text of the messagebox.&lt;/param&gt;
    /// &lt;param name=&quot;title&quot;&gt;Title of the messagebox.&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxButton&quot;&gt;Displayed button(s) in the messagebox. (Choose from the MessageBoxButton enum.).&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxImage&quot;&gt;Displayed icon in the messagebox. (Choose from the MessageBoxImage enum.).&lt;/param&gt;
    /// &lt;returns&gt;MessageBoxResult&lt;/returns&gt;
    public MessageBoxResult Show(string messageText, string title, MessageBoxButton messageBoxButton, MessageBoxImage messageBoxImage)
    {
        return Xceed.Wpf.Toolkit.MessageBox.Show(Application.Current?.MainWindow, messageText, title, messageBoxButton, messageBoxImage, _messageBoxStyle);
    }

    /// &lt;summary&gt;
    /// Displays a messagebox with the given parameters.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;messageText&quot;&gt;Text of the messagebox.&lt;/param&gt;
    /// &lt;param name=&quot;title&quot;&gt;Title of the messagebox.&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxButton&quot;&gt;Displayed button(s) in the messagebox. (Choose from the MessageBoxButton enum.).&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxImage&quot;&gt;Displayed icon in the messagebox. (Choose from the MessageBoxImage enum.).&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxStyle&quot;&gt;Style what is applied on the MessageBox.&lt;/param&gt;
    /// &lt;returns&gt;MessageBoxResult&lt;/returns&gt;
    public MessageBoxResult Show(string messageText, string title, MessageBoxButton messageBoxButton, MessageBoxImage messageBoxImage, Style messageBoxStyle)
    {
        return Xceed.Wpf.Toolkit.MessageBox.Show(Application.Current?.MainWindow, messageText, title, messageBoxButton, messageBoxImage, messageBoxStyle);
    }
}
</code></pre>
<p>}</p>
<p>Thank you for your help!</p>
",https://stackoverflow.com/questions/68909377/how-to-bypass-custom-messageboxes-when-unit-testing-with-moq,"['c#', 'unit-testing', 'mocking', 'moq', 'messagebox']",80,True,0,1
Verify method called in unit testing using coroutine with delay,"<p>I've been reading <a href=""https://craigrussell.io/2019/11/unit-testing-coroutine-suspend-functions-using-testcoroutinedispatcher/"" rel=""nofollow noreferrer"">this article</a> to understand how to unit test a coroutine that contains a delay and applied it, but I still don't understand why <code>verify</code> is being called before having called myDelayedMethod() in the coroutine and therefore the verification fails. Isn't there a way to execute the code synchronously in the test?</p>
<p>Pseudocode:</p>
<pre><code>class ClasUnderTest{

  fun method1(){
      GlobalScope.launch {
      myDelayedMethod()
    }
  }

  suspend fun myDelayedMethod(): String{
    withContext(dispatchers.default()){
      delay(X)
      ...
      someClass.someMethod()
   }
  }
}

@Test
fun myTest()= coroutinesTestRule.testDispatcher.runBlockingTest {
  val someClassMock = mock(SomeClass::class.java)
  val myObject = ClasUnderTest(someClassMock) 
  method1()
  verify(someClassMock).someMethod()
}
</code></pre>
",https://stackoverflow.com/questions/67939693/verify-method-called-in-unit-testing-using-coroutine-with-delay,"['android', 'unit-testing', 'delay', 'kotlin-coroutines']",978,True,0,1
Unit testing with Cosmos Db fails within Azure Devops pipeline,"<p>I have written unit test cases where I have my test cases written against Cosmos Db emulator. (Those who don't know what emulator is , it is a local development cosmos Db provided by Microsoft which are generally used to test your queries)</p>
<p>In my unit test case I am instantiating the Emulator db and then running the test cases. problem occurs when I push this changes to my Azure devops pipeline. there the test cases fails with error as</p>
<blockquote>
<p>Target machine actively refused the connection.</p>
</blockquote>
<p>It does mean it is not able to instansiate db. How can i fix this. Any idea??</p>
<p>here is the initial code for testing</p>
<pre><code>public class CosmosDataFixture : IDisposable
{
        public static readonly string CosmosEndpoint = &quot;https://localhost:8081&quot;;
        public static readonly string EmulatorKey = &quot;C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==&quot;;
        public static readonly string DatabaseId = &quot;testdb&quot;;
        public static readonly string RecordingCollection = &quot;testcolec&quot;;
        public static string Root = Directory.GetParent( Directory.GetCurrentDirectory() ).Parent.Parent.FullName;
        public static DocumentClient client { get; set; }
public async Task ReadConfigAsync()
        {

          //  StartEmulatorDatabaseFromPowerShell();
            client = new DocumentClient( new Uri( CosmosEndpoint ), EmulatorKey,
                 new ConnectionPolicy
                 {
                     ConnectionMode = ConnectionMode.Direct,
                     ConnectionProtocol = Protocol.Tcp

                 } );
            await client.CreateDatabaseIfNotExistsAsync( new Database { Id = DatabaseId } );
            await client.CreateDocumentCollectionIfNotExistsAsync( UriFactory.CreateDatabaseUri( DatabaseId ),
                new DocumentCollection { Id = RecordingCollection } );
            await ReadAllData( client );
        }
     public CosmosDataFixture()
        {
                      
            ReadConfigAsync();     
        }


        public void Dispose()
        {
          DeleteDatabaseFromPowerShell();// this is also defined in above class
        }
    }   
    public class CosmosDataTests : IClassFixture&lt;CosmosDataFixture&gt;
    { // mu unit test case goes here
</code></pre>
",https://stackoverflow.com/questions/68189836/unit-testing-with-cosmos-db-fails-within-azure-devops-pipeline,"['c#', 'azure-devops', 'xunit', 'azure-cosmosdb-emulator']",1167,False,0,1
Mock class in vue action with sinon for unit testing,"<p>I want to be able to assert whether my 'SIGN_IN' action works as intended.</p>
<p>My action looks like this (not the cleanest implementation but it's what I have to work with for now):</p>
<pre class=""lang-js prettyprint-override""><code>// actions.js

import {
  SIGN_IN, SIGN_OUT, SET_AUTH_TOKEN, CLEAR_AUTH_TOKEN, USER_AUTHORISED,
} from '@/store/types';
import AuthService from '../../../authService';

export default {
  async [SIGN_IN]({ commit, rootState }) {
    const authService = new AuthService(rootState.clientSettings);
    let response;
    try {
      response = await authService.getToken();
    } catch (e) {
      console.log('User not authorised to use application.');
    }
    if (response) {
      commit(SET_AUTH_TOKEN, response);
    } else {
      commit(USER_AUTHORISED, false);
    }
  },
  ...
};

</code></pre>
<p><code>authService.getToken();</code> is what I want to mock the response of.
I want this to be able to resolve to a mock response in my test.</p>
<p>The class for AuthService looks like this:</p>
<pre class=""lang-js prettyprint-override""><code>// authService.js

import { PublicClientApplication } from '@azure/msal-browser';

class AuthService {
  constructor(clientSettings) {
    this.config = {
      auth: {
        clientId: clientSettings.clientId,
        authority: `https://login.microsoftonline.com/${clientSettings.tenantId}`,
      },
      cache: {
        cacheLocation: 'sessionStorage',
        storeAuthStateInCookie: false,
      },
    };

    this.scopes = [
      clientSettings.appScope,
    ];

    this.msal = new PublicClientApplication(this.config);
    this.clientSettings = clientSettings;
  }
    ...

    async getToken() {
      const { scopes } = this;
      try {
        const response = await this.msal.acquireTokenSilent({ scopes });
        return response;
      } catch (err) {
        const response = await this.msal.acquireTokenPopup({ scopes });
        return response;
      }
    }

    ...
}

export default AuthService;
</code></pre>
<p>This is what I tried in my test:</p>
<pre class=""lang-js prettyprint-override""><code>// actions.spec.js
import sinon, { mock } from 'sinon';
import actions from '@/store/modules/auth/actions';
import { SIGN_IN, SIGN_OUT } from '@/store/types';
import { PublicClientApplication } from '@azure/msal-browser';
import AuthService from '../../../../../src/authService';
import templateRootState from '../../../../helpers/rootState.json';

describe('Auth', () =&gt; {
  describe('Actions', () =&gt; {
    let state;

    beforeEach(() =&gt; {
      state = JSON.parse(JSON.stringify(templateRootState));
    });

    afterEach(() =&gt; {
      sinon.reset();
    });

    describe('SIGN_IN', () =&gt; {
      it.only('returns a token from the AuthService &amp; sets it in the store', async () =&gt; {
        const commit = sinon.spy();
        const mockResponse = {
          token: 'bobbins'
        };

        sinon.stub(AuthService, 'getToken').resolves(mockResponse);

        const requestParams = { commit, rootState: state };

        await actions[SIGN_IN](requestParams);

        expect(commit.calledOnce).toEqual(true);
        expect(commit.args.length).toEqual(1);
        expect(commit.args[0][0]).toEqual('SET_AUTH_TOKEN');
        expect(commit.args[0][1]).toEqual(mockResponse);
      });
    });
  });
});

</code></pre>
<p>While debugging, I am unable to get <code>getToken</code> to be a stubbed response. It still calls the actual <code>userService</code> class instance created in my action: <code>new AuthService(rootState.clientSettings);</code>.</p>
<p>Hopefully you can see what I'm trying to achieve with my test. I just want to assert that <code>SET_AUTH_TOKEN</code> is triggered and nothing else. How can I stub out this <code>AuthService</code> class entirely so that my action uses that one instead? I don't really want to be passing an instance of <code>AuthService</code> into the action itself, there must be a neater way of doing it?</p>
",https://stackoverflow.com/questions/69110657/mock-class-in-vue-action-with-sinon-for-unit-testing,"['javascript', 'vue.js', 'unit-testing', 'vuex', 'sinon']",182,True,0,1
How to mock a logger for unit testing in c#?,"<p>The method that i need to unit test logs the output in the following way and doesnt return anything. How do i write a unit test method for the following case? Please help i'm new to this concept and havent written any test methods before</p>
<pre><code>private void revoke (params) {
    if (userexist (revokedb, userid))``
{
        deleteusers (revokedb, userid);
        if (userexist (revokedb, userid))
       {
           logger.info (&quot;Not able to delete user&quot;);
       }
       else
       {
          logger.info (&quot;User was succesfully deleted&quot;);
       }
    else
  {
       logger.info (&quot;unable of find the user&quot;);
  }
}
</code></pre>
",https://stackoverflow.com/questions/67799061/how-to-mock-a-logger-for-unit-testing-in-c,"['c#', '.net', 'unit-testing']",2820,True,0,2
cakephp unit testing failed asserting that response has header &#39;Location&#39;,"<p>I am trying to test a cakephp add method which in UsersController, I have written below action in UsersController</p>
<pre><code>public function testAdd(): void
{
        $this-&gt;enableCsrfToken();
        $this-&gt;enableSecurityToken();
        
        $user = ['username'=&gt;'jone','email'=&gt;'pitocms@yahoo.com', 'password'=&gt;'123'];
        $this-&gt;post('users/add',$user);
        $this-&gt;assertRedirect('/users');
        $count = $this-&gt;Users-&gt;find('all')-&gt;where($user)-&gt;count();
        $this-&gt;assertEquals(1,$count);
 }
</code></pre>
<p>After run this test case I am getting below error</p>
<pre><code>Time: 00:00.133, Memory: 14.00 MB

There was 1 failure:

1) App\Test\TestCase\Controller\UsersControllerTest::testAdd
Failed asserting that response has header 'Location'.

/Applications/XAMPP/xamppfiles/htdocs/cake4/vendor/cakephp/cakephp/src/TestSuite/IntegrationTestTrait.php:833
/Applications/XAMPP/xamppfiles/htdocs/cake4/tests/TestCase/Controller/UsersControllerTest.php:89
</code></pre>
<p>How I will solve this problem ?</p>
<p>After remove <code>$this-&gt;assertRedirect('/users');</code> this script is working fine. Here How I will test action redirection is okay ?</p>
<p>Note : Here I am running cakephp application using cake server , by below command</p>
<pre><code>bin/cake server 
</code></pre>
<p>Location of <code>/users</code> is <code>http://localhost:8765/users</code></p>
",https://stackoverflow.com/questions/68979428/cakephp-unit-testing-failed-asserting-that-response-has-header-location,"['cakephp', 'cakephp-4.x']",226,False,0,0
Unit testing Spring Boot service layer bean which uses validation,"<p>I really like the Java validation annotations to check basic validity of method arguments. My problem is how to test such a method of a service bean without starting a Spring application context which is very slow.</p>
<p>I understand that validation requires some validator to be executed. Normally, this is set up by the Spring Boot infrastructure when the service bean has @Validated. Is there a way to set up a unit test that sets up validation without using @SpringBootTest which creates a full context?</p>
<p>For example, I have an entity Thing and a service ThingService.</p>
<pre><code>@Entity
@Getter @Setter @AllArgsConstructor @NoArgsConstructor @Accessors(chain=true)
public class Thing {
    @Id
    private Long id;
    
    @NotNull
    @Min(value=5)
    private Long one;
    
    @NotNull @NotEmpty @NotBlank
    @Size(max = 3)
    private String two;
    
    public Thing(
            Long one,
            String two) {
        this.one = one;
        this.two = two;
    }
}
</code></pre>
<p>and</p>
<pre><code>@Service
@Validated
public class ThingService {
    @Setter
    private ThingRepository repo;
    
    @Autowired
    public ThingService(ThingRepository repo) {
        this.repo = repo;
    };
    
    
    public Thing create(@NotNull Long arg, @NotNull @Valid Thing thing) {
        // Use arg to check that thing meets higher level constraints
        
        Thing savedThing = repo.save(thing);
        return savedThing;
    }
}
</code></pre>
<p>I can correctly test this using @SpringBootTest, but it is very slow</p>
<pre><code>@SpringBootTest
@ExtendWith(MockitoExtension.class)
public class ThingServiceTestOverkill {
    @MockBean
    private ThingRepository repo;
        
    @Autowired
    private ThingService service;
    
    @Test
    public void createSuccess() {
        when(repo.save(any(Thing.class))).thenAnswer(returnsFirstArg());
        
        Thing thing = service.create(2L, new Thing(5L, &quot;foo&quot;));
        
        verify(repo, times(1)).save(thing);
        assertThat(thing.getOne(), is(5L));
        assertThat(thing.getTwo(), is (&quot;foo&quot;));
    }
    
    @Test
    public void createNullUser() {
        ConstraintViolationException ex = assertThrows(ConstraintViolationException.class, () -&gt; {
            service.create(null, new Thing(5L, &quot;foo&quot;));
        });
        
        assertThat(ex.getConstraintViolations(), hasSize(1));
        ConstraintViolation&lt;?&gt; cv = ex.getConstraintViolations().stream().findFirst().get();
        assertThat(cv.getPropertyPath().toString(), is(&quot;create.arg&quot;));
        assertThat(cv.getInvalidValue(), is(nullValue()));
        assertThat(cv.getMessage(), is(&quot;must not be null&quot;));
    }
 }
</code></pre>
<p>If I try to test with a more traditional direct Mockito approach, no validation is done.</p>
<pre><code>@ExtendWith(MockitoExtension.class)
public class ThingServiceTestUnderkill {
    @Mock
    private ThingRepository repo;
    
    // Decided not to use @InjectMocks as it fails silently and can hide errors and bad smells
    private ThingService service;
    
    @BeforeEach
    public void initializeTest() {
        service = new ThingService(repo);  // No validation wrapper used.
    }
    
    @Test
    public void createSuccess() {
        when(repo.save(any(Thing.class))).thenAnswer(returnsFirstArg());
        
        Thing thing = service.create(2L, new Thing(5L, &quot;foo&quot;));
        
        verify(repo, times(1)).save(thing);
        assertThat(thing.getOne(), is(5L));
        assertThat(thing.getTwo(), is (&quot;foo&quot;));
    }
    
    @Test
    public void createNullUser() {
        ConstraintViolationException ex = assertThrows(ConstraintViolationException.class, () -&gt; {
            service.create(null, new Thing(5L, &quot;foo&quot;));
        });
        
        // NEVER THROWS EXCEPTION
        
        assertThat(ex.getConstraintViolations(), hasSize(1));
        ConstraintViolation&lt;?&gt; cv = ex.getConstraintViolations().stream().findFirst().get();
        assertThat(cv.getPropertyPath().toString(), is(&quot;create.arg&quot;));
        assertThat(cv.getInvalidValue(), is(nullValue()));
        assertThat(cv.getMessage(), is(&quot;must not be null&quot;));
    }
 }
</code></pre>
<p>Is there a way to access the validation wrapping functionality of Spring Boot? Is there some other solution?</p>
<p>Spring boot 2.5.2, Java 11.</p>
",https://stackoverflow.com/questions/68387646/unit-testing-spring-boot-service-layer-bean-which-uses-validation,"['spring-boot', 'unit-testing', 'validation', 'mockito']",1355,False,0,2
Mocking dependencies of a module singleton in unit testing (Python),"<p>In a simple unit testing scenario, suppose I have the following module:</p>
<pre><code>class DatabaseMediator:
    def __init__(self, mock_connection):
        self.db_connection = mock_connection if mock_connection is not None else connect()


databaseMediator = DatabaseMediator()
</code></pre>
<p>assuming <code>connect</code> is a method that might be imported from another module and establishes a db connection.</p>
<p>Now because we're unit testing, it is desirable to be able to test the class isolated way and therefore instantiate it without an actual database connection, so one could to this:</p>
<pre><code>from database_mediator import DatabaseMediator

mock_mediator = DatabaseMediator(mock())
</code></pre>
<p>in order to get a testable instance of <code>DatabaseMediator</code> that doesn't actually have a database connection. However, as we know, when you import anything from a module in Python, the whole module is executed and therefore, the <code>databaseMediator</code> instance will also be created. This can become a problem however, e. g. when we're in a CI pipeline and there is no database instance to connect to and therefore this method throws an error.</p>
<p>Is there any way to have the dependencies of the singleton mocked? Or an overall better approach to the problem?</p>
",https://stackoverflow.com/questions/68458614/mocking-dependencies-of-a-module-singleton-in-unit-testing-python,"['python', 'unit-testing', 'mocking', 'singleton', 'python-module']",63,False,0,0
SpringMVC Unit testing - Service method is not called in controller,"<p>I'm working on a REST API, and I want to do some testing on the controllers. But when I run a test on the controller, it looks like the service method is not called. This is one controller and test of many other that has same problem.</p>
<p>This is the controller I want to test:</p>
<p><strong>Controller</strong></p>
<pre><code>@RestController
@RequestMapping(&quot;/api/&quot;)
@CrossOrigin(origins = &quot;*&quot;)
@Api(tags = &quot;Auth&quot;)
public class AuthController {

    @Autowired
    TrainerService trainerService;
    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    ClientService clientService;


    @ApiOperation(value = &quot;Trainer register&quot;, response = Trainer.class)
    @PostMapping(&quot;pregister&quot;)
    public Trainer registerTrainer(@RequestBody Trainer trainer) throws GlobalReqException {
        try {
            return trainerService.register(trainer); // trainerService.register() is not called
        } catch (GlobalReqException e) {
            throw new GlobalReqException(&quot;Something went wrong registering trainer&quot;, e);
        }
    }

...

</code></pre>
<p>And this is the Test</p>
<p><strong>Test</strong></p>
<pre><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = AuthController.class)
@WebAppConfiguration
@EnableWebMvc
public class AuthControllerTest {

    @MockBean
    JwtUtil jwtUtil;
    @MockBean
    AuthenticationManager authenticationManager;
    @MockBean
    TrainerService trainerService;
    @MockBean
    ClientService clientService;

    @Autowired
    WebApplicationContext webApplicationContext;

    protected MockMvc mvc;

    @Test
    @DisplayName(&quot;Register Trainer&quot;)
    public void registerTrainer() throws Exception {

        mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

        String json = &quot;{\n&quot; +
                &quot;  \&quot;userName\&quot;: \&quot;trainer@test.com\&quot;,\n&quot; +
                &quot;  \&quot;name\&quot;: \&quot;trainer\&quot;,\n&quot; +
                &quot;  \&quot;password\&quot;: \&quot;pass12345\&quot;,\n&quot; +
                &quot;  \&quot;phone\&quot;: \&quot;12345678\&quot;\n&quot; +
                &quot;}&quot;;

        String uri = &quot;/api/pregister/&quot;;
        MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .content(json))
                .andReturn();

        int status = mvcResult.getResponse().getStatus();
        System.out.println(mvcResult.getResponse());
        assertEquals(200, status);
    }
}
</code></pre>
",https://stackoverflow.com/questions/67486276/springmvc-unit-testing-service-method-is-not-called-in-controller,"['java', 'spring-boot', 'spring-test', 'spring-test-mvc']",494,False,0,0
Spring MVC Unit Testing - Mocked Service method is not called,"<p>I was working on a spring boot project where I have controller which calls a service method and process the output.</p>
<p>I'am using spring MockMvc for testing the web layer. In my test class I have mocked the service method with Mockito.when(). But when I call the corresponding handler method it is not calling the mocked service method instead returns a null response.</p>
<p><strong>Controller</strong></p>
<pre><code>@Controller
public class SocialLoginEndpoints {

  @Autowired
  @Qualifier(&quot;facebookAuth&quot;)
  SocialLogin faceBookAuth;

  @Autowired
  @Qualifier(&quot;googleAuth&quot;)
  SocialLogin googleAuth;

  @Autowired SignupService signupService;

  @GetMapping(&quot;/auth/google&quot;)
  public String googleAuth(@RequestParam String signupType, HttpServletRequest request) {
    return &quot;redirect:&quot; + googleAuth.getAuthURL(request, signupType);
  }
}
</code></pre>
<p><strong>Test Class</strong></p>
<pre><code>@WebMvcTest(SocialLoginEndpoints.class)
class SocialLoginEndpointsTest {

  @Autowired MockMvc mockMvc;
  MockHttpServletRequest mockHttpServletRequest;

  @MockBean GoogleAuth googleAuth;

  @MockBean FacebookAuth facebokAuth;

  @MockBean SignupService signupService;

  @BeforeEach
  void setUp() {
    mockHttpServletRequest = new MockHttpServletRequest();
  }

  @Test
  void googleAuth() throws Exception {
    Mockito.when(googleAuth.getAuthURL(mockHttpServletRequest, &quot;free&quot;))
        .thenReturn(&quot;www.google.com&quot;);
    mockMvc
        .perform(MockMvcRequestBuilders.get(&quot;/auth/google&quot;).param(&quot;signupType&quot;, &quot;free&quot;))
        .andExpect(MockMvcResultMatchers.redirectedUrl(&quot;www.google.com&quot;))
        .andExpect(MockMvcResultMatchers.status().isFound())
        .andDo(MockMvcResultHandlers.print());

    Mockito.verify(googleAuth, Mockito.times(1)).getAuthURL(mockHttpServletRequest, &quot;free&quot;);
  }
</code></pre>
<p>The reponse which is returned is</p>
<pre><code>MockHttpServletResponse:
           Status = 302
    Error message = null
          Headers = [Content-Language:&quot;en&quot;, Location:&quot;null&quot;]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
</code></pre>
<p>please help me to resolve this issue.
Thanks in Advance !</p>
",https://stackoverflow.com/questions/66852523/spring-mvc-unit-testing-mocked-service-method-is-not-called,"['spring-boot', 'mockito', 'spring-boot-test', 'mockmvc', 'spring-mvc-test']",792,True,0,1
Simple Unit Testing of firebase rules in emulator always fails,"<p>I am trying to setup unit testing for my firestore rules and I followed the <a href=""https://firebase.google.com/docs/rules/unit-tests"" rel=""nofollow noreferrer"">video tutorial</a> but for some reason <code>firebase.assertSucceeds.(testDoc.get())</code> always passes even though I am not allowing it by the security rule.</p>
<p>Security rule:</p>
<pre><code>rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}
</code></pre>
<p>Unit test:</p>
<pre><code>process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8090';
const assert = require('assert');
const firebase = require('@firebase/testing');

const PROJECT_ID = 'my-proj-id';

describe(&quot;Security Rules&quot;,()=&gt;{

    it(&quot;monkeytest&quot;, async()=&gt;{
        const db = firebase.initializeTestApp({projectId:PROJECT_ID}).firestore();
        const testDoc = db.collection(&quot;foo&quot;).doc('bar');
        await firebase.assertSucceeds(testDoc.get());
    })
});
</code></pre>
<p>No matter what I change in the security rule this unit test always passes. When I use <code>firebase.assertFails(testDoc.get())</code> instead the test always fails no matter what I change.</p>
",https://stackoverflow.com/questions/66696292/simple-unit-testing-of-firebase-rules-in-emulator-always-fails,"['unit-testing', 'google-cloud-firestore', 'firebase-security']",373,True,0,1
Unit Testing Apache Spark Application with Intellij Results in Error,"<p>I have a Spark application that is supposed to do data preparation step. I have some unit tests written for checking data quality using deequ and as usual I wanted to run one of my unit tests, but I'm running into errors as below:</p>
<pre><code>Error while instantiating 'org.apache.spark.sql.internal.SessionStateBuilder':
java.lang.IllegalArgumentException: Error while instantiating 'org.apache.spark.sql.internal.SessionStateBuilder':
    at org.apache.spark.sql.SparkSession$.org$apache$spark$sql$SparkSession$$instantiateSessionState(SparkSession.scala:1148)
    at org.apache.spark.sql.SparkSession.$anonfun$sessionState$2(SparkSession.scala:159)
    at scala.Option.getOrElse(Option.scala:189)
    at org.apache.spark.sql.SparkSession.sessionState$lzycompute(SparkSession.scala:155)
    at org.apache.spark.sql.SparkSession.sessionState(SparkSession.scala:152)
    at org.apache.spark.sql.DataFrameReader.&lt;init&gt;(DataFrameReader.scala:997)
    at org.apache.spark.sql.SparkSession.read(SparkSession.scala:658)
    at com.bigelectrons.housingml.dataprep.HousingDataTest.$anonfun$new$1(HousingDataTest.scala:32)
    at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
    at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
    at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
    at org.scalatest.Transformer.apply(Transformer.scala:22)
    at org.scalatest.Transformer.apply(Transformer.scala:20)
    at org.scalatest.FlatSpecLike$$anon$1.apply(FlatSpecLike.scala:1682)
    at org.scalatest.TestSuite.withFixture(TestSuite.scala:196)
    at org.scalatest.TestSuite.withFixture$(TestSuite.scala:195)
    at org.scalatest.FlatSpec.withFixture(FlatSpec.scala:1685)
    at org.scalatest.FlatSpecLike.invokeWithFixture$1(FlatSpecLike.scala:1680)
    at org.scalatest.FlatSpecLike.$anonfun$runTest$1(FlatSpecLike.scala:1692)
    at org.scalatest.SuperEngine.runTestImpl(Engine.scala:289)
    at org.scalatest.FlatSpecLike.runTest(FlatSpecLike.scala:1692)
    at org.scalatest.FlatSpecLike.runTest$(FlatSpecLike.scala:1674)
    at org.scalatest.FlatSpec.runTest(FlatSpec.scala:1685)
    at org.scalatest.FlatSpecLike.$anonfun$runTests$1(FlatSpecLike.scala:1750)
    at org.scalatest.SuperEngine.$anonfun$runTestsInBranch$1(Engine.scala:396)
    at scala.collection.immutable.List.foreach(List.scala:431)
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:384)
    at org.scalatest.SuperEngine.runTestsInBranch(Engine.scala:373)
    at org.scalatest.SuperEngine.$anonfun$runTestsInBranch$1(Engine.scala:410)
    at scala.collection.immutable.List.foreach(List.scala:431)
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:384)
    at org.scalatest.SuperEngine.runTestsInBranch(Engine.scala:379)
    at org.scalatest.SuperEngine.runTestsImpl(Engine.scala:461)
    at org.scalatest.FlatSpecLike.runTests(FlatSpecLike.scala:1750)
    at org.scalatest.FlatSpecLike.runTests$(FlatSpecLike.scala:1749)
    at org.scalatest.FlatSpec.runTests(FlatSpec.scala:1685)
    at org.scalatest.Suite.run(Suite.scala:1147)
    at org.scalatest.Suite.run$(Suite.scala:1129)
    at org.scalatest.FlatSpec.org$scalatest$FlatSpecLike$$super$run(FlatSpec.scala:1685)
    at org.scalatest.FlatSpecLike.$anonfun$run$1(FlatSpecLike.scala:1795)
    at org.scalatest.SuperEngine.runImpl(Engine.scala:521)
    at org.scalatest.FlatSpecLike.run(FlatSpecLike.scala:1795)
    at org.scalatest.FlatSpecLike.run$(FlatSpecLike.scala:1793)
    at com.bigelectrons.housingml.dataprep.HousingDataTest.org$scalatest$BeforeAndAfterAll$$super$run(HousingDataTest.scala:20)
    at org.scalatest.BeforeAndAfterAll.liftedTree1$1(BeforeAndAfterAll.scala:213)
    at org.scalatest.BeforeAndAfterAll.run(BeforeAndAfterAll.scala:210)
    at org.scalatest.BeforeAndAfterAll.run$(BeforeAndAfterAll.scala:208)
    at com.bigelectrons.housingml.dataprep.HousingDataTest.run(HousingDataTest.scala:20)
    at org.scalatest.tools.SuiteRunner.run(SuiteRunner.scala:45)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13(Runner.scala:1346)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13$adapted(Runner.scala:1340)
    at scala.collection.immutable.List.foreach(List.scala:431)
    at org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:1340)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24(Runner.scala:1031)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24$adapted(Runner.scala:1010)
    at org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:1506)
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:1010)
    at org.scalatest.tools.Runner$.run(Runner.scala:850)
    at org.scalatest.tools.Runner.run(Runner.scala)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2or3(ScalaTestRunner.java:38)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:25)
Caused by: java.lang.IllegalStateException: LiveListenerBus is stopped.
    at org.apache.spark.scheduler.LiveListenerBus.addToQueue(LiveListenerBus.scala:97)
    at org.apache.spark.scheduler.LiveListenerBus.addToStatusQueue(LiveListenerBus.scala:80)
    at org.apache.spark.sql.internal.SharedState.&lt;init&gt;(SharedState.scala:99)
    at org.apache.spark.sql.SparkSession.$anonfun$sharedState$1(SparkSession.scala:138)
    at scala.Option.getOrElse(Option.scala:189)
    at org.apache.spark.sql.SparkSession.sharedState$lzycompute(SparkSession.scala:138)
    at org.apache.spark.sql.SparkSession.sharedState(SparkSession.scala:137)
    at org.apache.spark.sql.internal.BaseSessionStateBuilder.build(BaseSessionStateBuilder.scala:335)
    at org.apache.spark.sql.SparkSession$.org$apache$spark$sql$SparkSession$$instantiateSessionState(SparkSession.scala:1145)
    ... 60 more
</code></pre>
<p>Here is how I get access to a Spark session:</p>
<pre><code>  val spark: SparkSession = SparkSession.builder().config(&quot;spark.master&quot;, &quot;local&quot;).appName(&quot;housing-data-test&quot;).getOrCreate()
</code></pre>
<p>Here is my actual code:</p>
<pre><code>&quot;simple unit test&quot; should &quot;check for data correctness&quot; in {
    appCfgT match {
      case Success(appCfg) =&gt;
        preStart()
        val rawDF: DataFrame = spark
          .read
          .format(&quot;csv&quot;)
          .option(&quot;delimiter&quot;, &quot;,&quot;)
          .option(&quot;timestampFormat&quot;, &quot;yyyy/MM/dd HH:mm:ss ZZ&quot;)
          .option(&quot;inferSchema&quot;, value = true)
          .option(&quot;mode&quot;, &quot;DROPMALFORMED&quot;)
          .option(&quot;header&quot;, value = true)
          .option(&quot;multiLine&quot;, value = true)
          .schema(encodedHousingSchema)
          .load(appCfg.sourceFileUrl)

        DataTestUtils.withSpark { session =&gt;
          val rows = session.sparkContext.parallelize(Seq(new HousingModel()))
          val data = session.createDataFrame(rows)
          println(&quot;******************************************************************************&quot;)
          val verificationResult = VerificationSuite()
            .onData(data)
            .addCheck(
              Check(CheckLevel.Error, &quot;unit testing my data&quot;)
                .hasSize(_ == 4092) // we expect 4092 rows
                .isComplete(&quot;id&quot;) // should never be NULL
                .isUnique(&quot;id&quot;) // should not contain duplicates
                .isComplete(&quot;productName&quot;) // should never be NULL
                // should only contain the values &quot;high&quot; and &quot;low&quot;
                .isContainedIn(&quot;priority&quot;, Array(&quot;high&quot;, &quot;low&quot;))
                .isNonNegative(&quot;numViews&quot;) // should not contain negative values
                // at least half of the descriptions should contain a url
                .containsURL(&quot;description&quot;, _ &gt;= 0.5)
                // half of the items should have less than 10 views
                .hasApproxQuantile(&quot;numViews&quot;, 0.5, _ &lt;= 10)
            )
            .run()
        }

      case Failure(fail) =&gt;
        // TODO: Fail the unit test!
    }
  }
</code></pre>
",https://stackoverflow.com/questions/69446766/unit-testing-apache-spark-application-with-intellij-results-in-error,"['scala', 'unit-testing', 'apache-spark', 'amazon-deequ']",495,False,0,0
Making mockito to use the real Log4j during unit testing,"<p>During the unit testing of method <em>Utility#sum</em>, I want that the <em>log</em> should print the <em>sum</em> on the console.</p>
<pre class=""lang-java prettyprint-override""><code>public class Utility {

    private static Logger log = Logger.getLogger(Utility.class);
   
    private Utility() {
    }

    public static Integer getSum(Integer a, Integer b) {
        Integer sum = a + b
        log.info(sum);
        return sum;
    }
}
</code></pre>
<p>For that in my test <em>testGetSumRealLogger</em> I am passing a real <em>Logger log = Logger.getLogger(getClass())</em>, but in method <em>Utility#sum</em> its is initialized to null.</p>
<p>In my second test <em>testGetSumMockedLogger</em> I am passing a mocked  <em>Logger log = Mockito.mock(Logger.class)</em>, this time the log inside method Utility#sum is not null, but does not print anything.</p>
<pre class=""lang-java prettyprint-override""><code>class UtilityTest {

    @Test
    void testGetSumRealLogger() throws Exception {
        try (MockedStatic&lt;Logger&gt; mockedStaticLoggerBean = Mockito.mockStatic(Logger.class)) {

            Logger log = Logger.getLogger(getClass());
            mockedStaticLoggerBean.when(() -&gt; Logger.getLogger(Utility.class)).thenReturn(log);

            assertEquals(4, Utility.getSum(2, 2));
        }
    }

    @Test
    void testGetSumMockedLogger() throws Exception {
        try (MockedStatic&lt;Logger&gt; mockedStaticLoggerBean = Mockito.mockStatic(Logger.class)) {

            Logger log = Mockito.mock(Logger.class);
            mockedStaticLoggerBean.when(() -&gt; Logger.getLogger(Utility.class)).thenReturn(log);

            assertEquals(4, Utility.getSum(2, 2));
        }
    }

}

</code></pre>
<p>How can I get the Logger to print something in the Utility#sum method without refactoring the code.
I am using Junit 5 with mockito-inline, 3.11.2.
I also have a proper log4j.xml in the test resources.
Please avoid suggesting logging is bad during the unit test.</p>
",https://stackoverflow.com/questions/68834741/making-mockito-to-use-the-real-log4j-during-unit-testing,"['mockito', 'log4j', 'junit5']",847,True,0,1
Unit testing a RestAPI client that doesn&#39;t implement a protocol,"<p>I'm new to developing code and writing unit tests.</p>
<p>I need to write a unit test for a <code>getData(url)</code> method that would return <code>nil</code> if the data coming from another call within the function is <code>nil</code></p>
<p>Sample code</p>
<pre><code>func getData(url: URL) -&gt; string? {
  guard let jsonData = self.get(url) else {
    return nil
  }
  .....
}
</code></pre>
<p>Here how would I make the test go to return nil part</p>
<ul>
<li>Check if the class is implementing any protocols, but its not. So I think I cannot use mocking/stubbing where I could say return <code>nil</code> for <code>get(url)</code> call</li>
</ul>
",https://stackoverflow.com/questions/66064438/unit-testing-a-restapi-client-that-doesnt-implement-a-protocol,"['swift', 'unit-testing']",10,False,0,0
Setting local variables inside a function for unit testing kotlin,"<p>I'm trying to testing a function in android.For the function to be tested ,have to set local variable inside the function. Heres the code:</p>
<pre><code> fun needToBeTested(serviceContext: Context):Int
    {
        val manager = serviceContext.getSystemService(Context.USB_SERVICE) as UsbManager
        val deviceList = manager.deviceList
        

            if(deviceList.size != 0){
                val deviceIterator = deviceList.values.iterator()
                while (deviceIterator.hasNext()) {
                    val device = deviceIterator.next()
                    
                    if ((device != null)&amp;&amp;(device.deviceClass == 255)) {   // USB_CLASS_VENDOR_SPEC - HUB
                        val permitToRead:Boolean = manager.hasPermission(device)
                        if(permitToRead){
                            setUpConnection(device,serviceContext)
                        } else{
                            manager.requestPermission(device, permissionIntent)
                        }
                        deviceConnectionStatus = 1
                    } else if((device != null) &amp;&amp;(device.deviceClass == 0)){ // USB_CLASS_PER_INTERFACE - USB STICK
                       
                    }
                }
            } else (deviceList.size == 0){
                connectionStatus = 0
                }
            }
</code></pre>
<p><strong>Test class</strong></p>
<p>class Test {</p>
<pre><code>val mockContext = ApplicationProvider.getApplicationContext&lt;Context&gt;()



    @Test
    fun needTobeTested_returnOne(){

    asserThat(sample.needToBeTested(mockContext)==1) //successcase
</code></pre>
<p>}
}</p>
<p>For testing this class,need to set the value of <strong>deviceList</strong>.Is there any way to set the value of 'x' from the test class for testing this function. Im new to android and testing.Any help would be really helpful.</p>
",https://stackoverflow.com/questions/67703677/setting-local-variables-inside-a-function-for-unit-testing-kotlin,"['kotlin', 'android-testing']",640,False,0,0
Are there any tools for unit testing VodaPay Mini-Programs?,"<p>What are, if any, the testing tools used for test automation when you develop mini-programs on the VodaPay Mini-Program platform? I'm looking specifically to do Unit and E2E testing.</p>
",https://stackoverflow.com/questions/68152326/are-there-any-tools-for-unit-testing-vodapay-mini-programs,['vodapay-miniprogram'],262,True,0,3
How to do unit testing for session timeout in VB?,"<p>I am working on a VB project where I had to increase the session timeout of the page to 9 hours. I achieved it by adding <code>&lt;sessionState mode=&quot;InProc&quot; timeout=&quot;540&quot;&gt;&lt;/sessionState&gt;</code> in the <code>web.config</code> file</p>
<p>Now I have to write the unit testing for the same in VB. I have not written any unit test ever before. I know unit testing can be done on individual unit or group of interrelated units of the software. Is there a way to unit test session timeout? There is no login involved here.</p>
<p>Please give some reference. Some blog or existing question(s).
I am new to both VB and unit testing.</p>
",https://stackoverflow.com/questions/68621482/how-to-do-unit-testing-for-session-timeout-in-vb,"['vb.net', 'unit-testing', 'web-config', 'session-state', 'session-timeout']",146,False,0,0
How to add unit testing in strapi version 4 using jest?,"<p>I'm trying to add unit testing on a brand new strapi application. The official documentation is still in progress. So, until the documentation is being ready is there a way to add jest unit testing to strapi application ? i followed the approach in the v3 documentation with no luck.</p>
",https://stackoverflow.com/questions/70283992/how-to-add-unit-testing-in-strapi-version-4-using-jest,"['node.js', 'unit-testing', 'jestjs', 'strapi']",573,True,5,1
Difference between Testbed.inject(serviceName) and fixture.debugElement.injector.get(serviceName) in Angular Unit Testing,"<p>I was going through the test cases written by my team members. What I observed was at some places they've used <strong>TestBed.inject(serviceName)</strong> for injecting the service and at some places they've used <strong>fixture.debugElement.injector.get(serviceName)</strong>. Can somebody tell me the difference between these two? Also what is the correct way of injecting services?</p>
<p>For eg:</p>
<p>let abc: ABCService</p>
<p>Technique 1: abc = TestBed.inject(ABCService)
Technique 2: abc = fixture.debugElement.injector.get(ABCSerice)</p>
<p>Thanks in Advance</p>
",https://stackoverflow.com/questions/67718077/difference-between-testbed-injectservicename-and-fixture-debugelement-injector,"['angular', 'unit-testing', 'karma-jasmine']",1671,True,5,1
How to set up Camunda for unit testing in Spring Boot,"<p>I am able to run a Spring Boot application with Camunda for workflow management. My pom.xml with Camunda related dependencies are shown below.</p>
<pre><code>&lt;dependencyManagement&gt;
        ...
        &lt;dependency&gt;
            &lt;groupId&gt;org.camunda.bpm&lt;/groupId&gt;
            &lt;artifactId&gt;camunda-bom&lt;/artifactId&gt;
            &lt;version&gt;7.15.0&lt;/version&gt;
            &lt;scope&gt;import&lt;/scope&gt;
            &lt;type&gt;pom&lt;/type&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
&lt;/dependencyManagement&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm.springboot&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-bpm-spring-boot-starter&lt;/artifactId&gt;
        &lt;version&gt;7.15.0&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!-- REST API --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm.springboot&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-bpm-spring-boot-starter-rest&lt;/artifactId&gt;
        &lt;version&gt;7.15.0&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!-- dashboard --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm.springboot&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-bpm-spring-boot-starter-webapp&lt;/artifactId&gt;
        &lt;version&gt;7.15.0&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-engine-plugin-spin&lt;/artifactId&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.spin&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-spin-dataformat-all&lt;/artifactId&gt;
    &lt;/dependency&gt;
</code></pre>
<p>I have just one .BPMN file. My application.yml file looks like this:</p>
<pre><code>spring.main.banner-mode: console
server.port: 9090

springdoc:
  model-and-view-allowed: true
  swagger-ui:
    operationsSorter: alpha

spring.jpa:
  hibernate:
    ddl-auto: none
  show-sql: true
  properties:
    hibernate:
      format_sql: true
spring.datasource:
  initialization-mode: always
  platform: postgres
  url: jdbc:postgresql://xxxx
  username: xxxx
  password: xxxx

spring.flyway.enabled: false

camunda.bpm:
  admin-user:
    id: demo
    password: demo
  generic-properties:
    properties:
      generalResourceWhitelistPattern: &quot;[a-zA-Z0-9,'_\\$\\-\\.\\+\\!\\*\\(\\)]+|camunda-admin&quot;
</code></pre>
<p>In the codes, all I have to do are just to declare the Camunda objects and I can used them without further setups:</p>
<pre><code>@AutoWired
protected final RuntimeService runtimeService;

@AutoWired
protected final TaskService taskService;

@AutoWired
protected final IdentityService identityService;
</code></pre>
<p>Now I am trying to write unit tests. It seems that there are more than one way to set up Camunda for unit testing, but I am not able to get any of the examples I found working. By some trial and error, I managed to get the following codes to set up Camunda for unit test.</p>
<pre><code>@ActiveProfiles(&quot;test&quot;)
public class EntitlementServiceTest {

    private RuntimeService runtimeService;
    private TaskService taskService;
    private IdentityService identityService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        ProcessEngine processEngine = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration()
            .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE)
            .setJdbcUrl(&quot;jdbc:h2:mem:database_user;DB_CLOSE_ON_EXIT=FALSE&quot;)
            .setJobExecutorActivate(true)
            .buildProcessEngine();
        runtimeService = processEngine.getRuntimeService();
        taskService = processEngine.getTaskService();
        identityService = processEngine.getIdentityService();
    }

    ...
}
</code></pre>
<p>But I am not sure if this is the correct way to do so, so it would be better if someone points this out. The codes don't seem to have loaded anything from the application file for unit testing, application-test.yml. Replacing the hardcoded JDBC URL with ${spring.datasource.url} does not work at all. And even though I have set the camunda.bpm.generic-properties.properties.generalResourceWhitelistPattern, application-test.yml, it is obvious that it is not being read.</p>
",https://stackoverflow.com/questions/69345064/how-to-set-up-camunda-for-unit-testing-in-spring-boot,"['java', 'spring-boot', 'unit-testing', 'camunda']",3357,True,4,1
Spec has no expectations when unit testing a Service in Angular,"<p>So my tests are passing but it's this one unit test named <code>should get the notes</code> for the <code>NoteService</code> which, when <code>ng test</code> is ran, its name in Karma is written like</p>
<blockquote>
<p>SPEC HAS NO EXPECTATIONS should get the notes</p>
</blockquote>
<p>The method that I am trying to test is the following:</p>
<pre><code>@Injectable()
export class NoteService {

  readonly baseUrl = &quot;https://localhost:4200&quot;;
  readonly httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
    })
  };

  constructor(private httpClient: HttpClient) { }
 
  getNotes(): Observable&lt;Note[]&gt; {
    return this.httpClient.get&lt;Note[]&gt;(this.baseUrl + `/notes`, this.httpOptions);
  }
</code></pre>
<p>And the unit test is this:</p>
<pre><code>describe('NoteService', () =&gt; {
  let service: NoteService;
  
  const mockList = [
    {
      &quot;id&quot;: &quot;id1&quot;,
      &quot;title&quot;: &quot;First note&quot;,
      &quot;description&quot;: &quot;This is the description for the first note&quot;,
      &quot;categoryId&quot;: &quot;1&quot;
    },
    {
      &quot;id&quot;: &quot;id2&quot;,
      &quot;title&quot;: &quot;Second note&quot;,
      &quot;description&quot;: &quot;This is the description for the first note&quot;,
      &quot;categoryId&quot;: &quot;2&quot;
    }]

beforeEach(() =&gt; {
    TestBed.configureTestingModule({imports: [HttpClientTestingModule], 
      providers: [NoteService]});
    service = TestBed.inject(NoteService);
  });

  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });

  it('should get the notes', fakeAsync(() =&gt; {
    service.getNotes().subscribe((val) =&gt; {
      expect(val).toBe(mockList);
    });
  }));
});
</code></pre>
<p>Therefore, why is it saying that &quot;SPEC HAS NO EXPECTATIONS&quot;? Is it something wrong with my unit test? And how should I tweak it in order to make it work well?</p>
",https://stackoverflow.com/questions/66059460/spec-has-no-expectations-when-unit-testing-a-service-in-angular,"['angular', 'unit-testing', 'service', 'karma-jasmine']",3355,True,4,1
Connection &quot;default&quot; was not found with NestJS Unit Testing of Service,"<p>I am currently unit testing my NestJS service. My entity is called 'User' and I established a basic Service that allows me to interact with a MS SQL server, with GET and POST endpoints established in my Controller.</p>
<p>While I was able to mock the <code>Repository</code> that is used in the Service, I was unable to establish a mock <code>getConnection</code> in a method that had to call <code>getConection()</code>.</p>
<p>When I tried unit testing with <code>npm run test:watch</code>, I get the error that <code>ConnectionNotFoundError: Connection &quot;default&quot; was not found.</code> I have looked into (and in fact, taken much from) <a href=""https://stackoverflow.com/questions/61637468/how-to-stub-entitymanager-and-connection-in-typeorm-with-jest"">How to stub EntityManager and Connection in TypeORM with Jest</a>, but this post does not seem to elaborate on a connection that was not established, which is my problem.</p>
<p>In any case, here's my service with the relevant parts:</p>
<pre><code>import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, Repository } from &quot;typeorm&quot;;
import {User} from '../entities/user.entity';


@Injectable()
export class ServiceName {
  constructor(@InjectRepository(User) private usersRepository: Repository&lt;User&gt;) {}

  // Creating and inserting a new user into the database table using Repository
  // unit testing for this one works fine
  async createUserRepository(user: User): Promise&lt;User&gt; {
    const newUser = this.usersRepository.create(user); 
    return await this.usersRepository.save(newUser);
  }

  // Creating and inserting a new user into the database table using QueryBuilder and getConnection
  // unit testing for this one does not work so well 
  async createUserQueryBuilder(user: User): Promise&lt;User&gt; {
    await getConnection()
    .createQueryBuilder()
    .insert()
    .into(User)
    .values([
        user, 
     ])
    .execute();
    return user;  
  }
</code></pre>
<p>And here's my spec.ts file for unit testing:</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { ServiceName } from './app_codes_rms_area.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { User } from '../entities/user.entity';
import { Connection, Repository } from 'typeorm';

describe('service tests', () =&gt; {

    const repositoryMockFactory: () =&gt; MockType&lt;Repository&lt;any&gt;&gt; = jest.fn(() =&gt; ({ 
        create: jest.fn(),
        save: jest.fn(),
        // other functions
    }));

    const mockConnectionFactory = jest.fn(() =&gt; ({
        getConnection: jest.fn().mockReturnValue({
            createQueryBuilder: jest.fn().mockReturnThis(),
            getMany: jest.fn().mockReturnValue(allUsers),
            insert: jest.fn().mockReturnThis(),
            into: jest.fn().mockReturnThis(),
            values: jest.fn().mockReturnThis(),
            execute: jest.fn().mockReturnValue(user),
        })
    }));
 
    let service: ServiceName;
    let mockRepository: MockType&lt;Repository&lt;User&gt;&gt;;
    let mockConnection: Connection;

    beforeEach(async () =&gt; {
        const module: TestingModule = await Test.createTestingModule({
            providers: [
                ServiceName,
                {
                    provide: getRepositoryToken(User), // a User Repository is injected to the service 
                    useFactory: repositoryMockFactory, // using factory ensures that a new mock is used for every test
                },
                {
                    provide: Connection,
                    useFactory: mockConnectionFactory,
                }
            ],
        }).compile();

        service = module.get&lt;ServiceName&gt;(ServiceName);
        mockRepository = module.get(getRepositoryToken(User));
        mockConnection = module.get&lt;Connection&gt;(Connection);
    });
        it('should create a new user and return it using Repository', async () =&gt; {
            // some test that passes using mockRepository
        });

        it('should create a new user and return it using QueryBuilder (with mocked Connection)', async () =&gt; {
            expect(await service.createUserQueryBuilder(user)).toEqual(user);
            expect(mockConnection.createQueryBuilder).toBeCalled();
            expect(mockConnection.createQueryBuilder()['insert']).toBeCalled();
            expect(mockConnection.createQueryBuilder()['into']).toBeCalled();
            expect(mockConnection.createQueryBuilder()['values']).toBeCalled();
            expect(mockConnection.createQueryBuilder()['execute']).toBeCalled();
        })
</code></pre>
<p>It is the second test, <code>it('should create a new user and return it using QueryBuilder (with mocked Connection)'</code>, that triggers the following error:</p>
<pre><code>  ● service tests › Service Functions › should create a new user and return it using QueryBuilder (with mocked Connection)

    ConnectionNotFoundError: Connection &quot;default&quot; was not found.

      at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)
      at ConnectionManager.Object.&lt;anonymous&gt;.ConnectionManager.get (connection/ConnectionManager.ts:40:19)
      at Object.getConnection (index.ts:252:35)
      at ServiceName.createUserQueryBuilder (somefile:19:11)
      at Object.it (somefile:134:34)
</code></pre>
",https://stackoverflow.com/questions/67521900/connection-default-was-not-found-with-nestjs-unit-testing-of-service,"['typescript', 'unit-testing', 'mocking', 'nestjs', 'typeorm']",1759,True,3,1
Connection &quot;default&quot; was not found with NestJS Unit Testing of Service,"<p>I am currently unit testing my NestJS service. My entity is called 'User' and I established a basic Service that allows me to interact with a MS SQL server, with GET and POST endpoints established in my Controller.</p>
<p>While I was able to mock the <code>Repository</code> that is used in the Service, I was unable to establish a mock <code>getConnection</code> in a method that had to call <code>getConection()</code>.</p>
<p>When I tried unit testing with <code>npm run test:watch</code>, I get the error that <code>ConnectionNotFoundError: Connection &quot;default&quot; was not found.</code> I have looked into (and in fact, taken much from) <a href=""https://stackoverflow.com/questions/61637468/how-to-stub-entitymanager-and-connection-in-typeorm-with-jest"">How to stub EntityManager and Connection in TypeORM with Jest</a>, but this post does not seem to elaborate on a connection that was not established, which is my problem.</p>
<p>In any case, here's my service with the relevant parts:</p>
<pre><code>import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, Repository } from &quot;typeorm&quot;;
import {User} from '../entities/user.entity';


@Injectable()
export class ServiceName {
  constructor(@InjectRepository(User) private usersRepository: Repository&lt;User&gt;) {}

  // Creating and inserting a new user into the database table using Repository
  // unit testing for this one works fine
  async createUserRepository(user: User): Promise&lt;User&gt; {
    const newUser = this.usersRepository.create(user); 
    return await this.usersRepository.save(newUser);
  }

  // Creating and inserting a new user into the database table using QueryBuilder and getConnection
  // unit testing for this one does not work so well 
  async createUserQueryBuilder(user: User): Promise&lt;User&gt; {
    await getConnection()
    .createQueryBuilder()
    .insert()
    .into(User)
    .values([
        user, 
     ])
    .execute();
    return user;  
  }
</code></pre>
<p>And here's my spec.ts file for unit testing:</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { ServiceName } from './app_codes_rms_area.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { User } from '../entities/user.entity';
import { Connection, Repository } from 'typeorm';

describe('service tests', () =&gt; {

    const repositoryMockFactory: () =&gt; MockType&lt;Repository&lt;any&gt;&gt; = jest.fn(() =&gt; ({ 
        create: jest.fn(),
        save: jest.fn(),
        // other functions
    }));

    const mockConnectionFactory = jest.fn(() =&gt; ({
        getConnection: jest.fn().mockReturnValue({
            createQueryBuilder: jest.fn().mockReturnThis(),
            getMany: jest.fn().mockReturnValue(allUsers),
            insert: jest.fn().mockReturnThis(),
            into: jest.fn().mockReturnThis(),
            values: jest.fn().mockReturnThis(),
            execute: jest.fn().mockReturnValue(user),
        })
    }));
 
    let service: ServiceName;
    let mockRepository: MockType&lt;Repository&lt;User&gt;&gt;;
    let mockConnection: Connection;

    beforeEach(async () =&gt; {
        const module: TestingModule = await Test.createTestingModule({
            providers: [
                ServiceName,
                {
                    provide: getRepositoryToken(User), // a User Repository is injected to the service 
                    useFactory: repositoryMockFactory, // using factory ensures that a new mock is used for every test
                },
                {
                    provide: Connection,
                    useFactory: mockConnectionFactory,
                }
            ],
        }).compile();

        service = module.get&lt;ServiceName&gt;(ServiceName);
        mockRepository = module.get(getRepositoryToken(User));
        mockConnection = module.get&lt;Connection&gt;(Connection);
    });
        it('should create a new user and return it using Repository', async () =&gt; {
            // some test that passes using mockRepository
        });

        it('should create a new user and return it using QueryBuilder (with mocked Connection)', async () =&gt; {
            expect(await service.createUserQueryBuilder(user)).toEqual(user);
            expect(mockConnection.createQueryBuilder).toBeCalled();
            expect(mockConnection.createQueryBuilder()['insert']).toBeCalled();
            expect(mockConnection.createQueryBuilder()['into']).toBeCalled();
            expect(mockConnection.createQueryBuilder()['values']).toBeCalled();
            expect(mockConnection.createQueryBuilder()['execute']).toBeCalled();
        })
</code></pre>
<p>It is the second test, <code>it('should create a new user and return it using QueryBuilder (with mocked Connection)'</code>, that triggers the following error:</p>
<pre><code>  ● service tests › Service Functions › should create a new user and return it using QueryBuilder (with mocked Connection)

    ConnectionNotFoundError: Connection &quot;default&quot; was not found.

      at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)
      at ConnectionManager.Object.&lt;anonymous&gt;.ConnectionManager.get (connection/ConnectionManager.ts:40:19)
      at Object.getConnection (index.ts:252:35)
      at ServiceName.createUserQueryBuilder (somefile:19:11)
      at Object.it (somefile:134:34)
</code></pre>
",https://stackoverflow.com/questions/67521900/connection-default-was-not-found-with-nestjs-unit-testing-of-service,"['typescript', 'unit-testing', 'mocking', 'nestjs', 'typeorm']",1759,True,3,1
ParseError: Colon is expected (svelte with scss style) svelte unit testing,"<p>I am trying to write a test for the component which is using SCSS as default styling. But the test is throwing error that it's not able to understand SCSS</p>
<p>myComponent.svelte</p>
<pre class=""lang-html prettyprint-override""><code>&lt;div&gt;Hello &lt;span&gt;world&lt;/span&gt;&lt;/div&gt;
&lt;style&gt;
div {
 padding: 20px;
 span {
  font-weight: bold;
 }
}
&lt;/style&gt;
</code></pre>
<p>Test File</p>
<pre class=""lang-js prettyprint-override""><code>// mycomponent.test.js
import { render } from '@testing-library/svelte';
import MyComponent from './MyComponent.svelte';
...
const { component } = render(MyComponent, {});
...
</code></pre>
<p>Jest Config</p>
<pre class=""lang-js prettyprint-override""><code>module.exports = {
  transform: {
    '^.+\\.js$': 'babel-jest',
    '^.+\\.svelte$': ['svelte-jester', { preprocess: true, debug: true }],
  },
  moduleFileExtensions: ['js', 'svelte'],
  roots: ['&lt;rootDir&gt;/app/modules'],
  modulePaths: ['&lt;rootDir&gt;/app/modules'],
  moduleDirectories: ['node_modules', 'app/modules'],
  setupFilesAfterEnv: [
    '&lt;rootDir&gt;/app/modules/tests/setupTest.js',
    '@testing-library/jest-dom/extend-expect',
  ],
  clearMocks: true, // Automatically clear mock calls and instances before every test.
};
</code></pre>
<p>I am setting the default style to <code>SCSS</code> in the svelte config</p>
<p>svelte.config.js</p>
<pre class=""lang-js prettyprint-override""><code>const preprocess = require('svelte-preprocess');

module.exports = {
  preprocess: preprocess({ defaults: { style: 'scss' } }),
};
</code></pre>
<p>Error Stack</p>
<pre><code>Colon is expected
4:     padding: 20px;
5: 
6:     span {
              ^
7:       font-weight: bold;
8:     }
ParseError: Colon is expected

      at error (node_modules/svelte/src/compiler/utils/error.ts:25:16)
      at Parser$1.error (node_modules/svelte/src/compiler/parse/index.ts:101:3)
      at Object.read_style [as read] (node_modules/svelte/src/compiler/parse/read/style.ts:31:11)
      at tag (node_modules/svelte/src/compiler/parse/state/tag.ts:189:27)
      at new Parser$1 (node_modules/svelte/src/compiler/parse/index.ts:53:12)
      at parse (node_modules/svelte/src/compiler/parse/index.ts:218:17)
      at Object.compile (node_modules/svelte/src/compiler/compile/index.ts:93:14)
      at compiler (node_modules/svelte-jester/dist/transformer.cjs:135:32)
      at Object.processSync [as process] (node_modules/svelte-jester/dist/transformer.cjs:111:12)
      at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:464:35)
</code></pre>
<p>To reproduce clone and run this repo
<a href=""https://github.com/rparsh/svelte-testing-scss"" rel=""nofollow noreferrer"">https://github.com/rparsh/svelte-testing-scss</a></p>
",https://stackoverflow.com/questions/70091105/parseerror-colon-is-expected-svelte-with-scss-style-svelte-unit-testing,['svelte'],1082,True,2,1
How to fetch a record from db asynchronously while unit testing?,"<p>In this unit test I would like to check if the device has been created and that the expiry date is 7 days in future.</p>
<pre><code>database.py

import databases
database = databases.Database(settings.sqlalchemy_database_uri)
</code></pre>
<p>Unit Test:</p>
<pre><code>from database.database import database

def test_successful_register_expiry_set_to_seven_days():
    response = client.post(
        &quot;/register/&quot;,
        headers={},
        json={&quot;device_id&quot;: &quot;u1&quot;},
    )
    assert response.status_code == 201
    query = device.select(whereclause=device.c.id == &quot;u1&quot;)
    d = database.fetch_one(query)
    assert d.expires_at == datetime.utcnow().replace(microsecond=0) + timedelta(days=7)
</code></pre>
<p>Because <code>d</code> is a coroutine object it fails with the message:</p>
<pre><code>AttributeError: 'coroutine' object has no attribute 'expires_at'
</code></pre>
<p>And I can't use <code>await</code> inside a unit test.</p>
<pre><code>d = await database.fetch_one(query)
</code></pre>
<p>What am I missing, please?</p>
",https://stackoverflow.com/questions/66018042/how-to-fetch-a-record-from-db-asynchronously-while-unit-testing,"['python', 'sqlalchemy', 'fastapi']",561,True,2,1
TypeError: AWS.SecretsManager is not a constructor in unit testing with proxyquire,"<p>I have written a test code to test code that gives credentials from AWS Secret Manager. I used proxyquire and sinon for stubbing and getting this error.</p>
<p>Function I want to test</p>
<pre><code>    exports.getCredsFromAWSSecretsManager = (keyName) =&gt; {
    const SM = new AWS.SecretsManager({
        apiVersion: process.env.AWS_SM_API_VERSION,
        region: process.env.AWS_SM_REGION
    });

    return SM.getSecretValue(params).promise().then((data) =&gt; {
        logger.info(logMsgs.awsHlpr_smGetSecretValueSuccess(JSON.stringify(data)));
        return JSON.parse(data.SecretString);
        
    }).catch((err) =&gt; {
        logger.error(logMsgs.awsHlpr_smGetSecretValueErr(JSON.stringify(err)));
        throw err;
    });
};
</code></pre>
<p>Test case that I have written</p>
<pre><code>const sinon = require(&quot;sinon&quot;);
const proxyquire = require(&quot;proxyquire&quot;).noCallThru().noPreserveCache();
const { mockLogger } = require(&quot;../../mockdata/mockLogger&quot;);

let awsHelper;
let secretsManagerStub;

describe.only(&quot;AWS Helper &quot;, () =&gt; {

    // function1

    describe(&quot;AWS Helper: getCredsFromAWSSecretsManagera method&quot;, () =&gt; {

        before((done) =&gt; {
            const data = {
                SecretString: JSON.stringify({ publicKey: 'secretUsername', privateKey: 'secretPassword' }),
              };
            
            secretsManagerStub = {
                getSecretValue: sinon.stub().callsFake((params, callback) =&gt; {
                  callback(null, data);
                }),
               
              };

            const awsStub = {
                
                  SecretsManager: sinon.stub().returns(secretsManagerStub)
               
                
            } 
            awsHelper = proxyquire('../../../utils/aws_helper.js', {
                'aws-sdk':{
                    AWS:awsStub
                } ,
                 &quot;../../utils/logger&quot;: mockLogger,
            }); 
            
              

            done();
        });

        afterEach(() =&gt; {
            
            sinon.restore();
        });

        it('should write random data!', async () =&gt; {

            const expectedData = &quot;abcdef&quot;;

            secretsManagerStub.getSecretValue.yields(null, expectedData);

            const data = await awsHelper.getCredsFromAWSSecretsManager();

            sinon.assert.callCount(secretsManagerStub.getSecretValue, 1);
            assert.strictEqual(data, expectedData);
            
        });

    });
});
</code></pre>
<p>This code gives me the error saying
<strong>TypeError: AWS.SecretsManager is not a constructor</strong></p>
<p>any help would be greatly appreciated.</p>
",https://stackoverflow.com/questions/69763319/typeerror-aws-secretsmanager-is-not-a-constructor-in-unit-testing-with-proxyqui,"['node.js', 'unit-testing', 'aws-sdk', 'sinon', 'proxyquire']",2379,True,2,1
Unit testing threads: how to confirm that a thread was blocked,"<p>I'm writing a set of unit tests for a multi-threaded system. I want to write a test the confirms that thread B was blocked by thread A. My current solution, which I know isn't correct, is for thread A to sleep for a while, and then for the main thread to determine that thread B took at least that long to complete. I realize that this test isn't really valid because thread B could have simply been scheduled out by the system and took a long time to run that had nothing to do with being blocked.</p>
<hr />
<p>More information, based on the comments:</p>
<p>I can't go into the details, but $dayjob has implemented its own task threading system not too different from e.g. Android's AsyncTask and I've been tasked (get it?) with writing the unit tests for it. I've written a dozen or so unit tests which I'm happy with, and satisfied are completely deterministic. But just a few unit tests elude me. There are a few cases where a thread needs to wait for a specific condition, and I need to confirm that it was actually blocked on the condition and didn't just happen to sleep at the wrong time.</p>
<p>The test I came up with won't generate any false failures, but could still generate false successes if the scheduler happens to put a thread to sleep at the wrong time.</p>
<hr />
<p>Still more information: I'm not testing code that uses the threading library, I'm testing the library itself.</p>
",https://stackoverflow.com/questions/66791033/unit-testing-threads-how-to-confirm-that-a-thread-was-blocked,"['c++', 'multithreading', 'unit-testing', 'synchronous']",821,True,2,2
Unit Testing of functions with method decorator with mocha and sinon,"<p>I have a class method like this:</p>
<pre><code>export class MyClass {

        @myDecorator()
        public async createItem(itemId: string, itemOptions: ItemOption[]): Promise&lt;boolean&gt; {

                // ...
                // return await create Item
        }
}
</code></pre>
<p>I defined the decorator in another file like this:</p>
<pre><code>export function myDecorator() {
        return function check(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
                const newDescriptor = Object.assign({}, descriptor);
                // do something ...
                return newDescriptor;
        }
}

</code></pre>
<p>Now I want to unit test the <code>createItem</code> method not the decorator, only the method. But as the decorator is kind of heavy in what it does (there is even a database access in it) I need to mock it so that it doesn't get executed in the unit test.</p>
<p>I'm using mocha and sinon in my unit tests and already tried the following to mock the decorator:</p>
<pre><code>const decorator = require('./decorator/MyDecorator');
describe('test createItem method', function () {

        it('should return valid result', async function () {
                // 1. try
                decorator.myDecorator = () =&gt; sinon.fake();
                // 2. try
                const decoratorStub = sinon.stub(decorator, 'myDecorator');
                decoratorStub.return(true);

                // rest of test 
                const myClass = new MyClass();
                let result = await myClass.createItem(itemId, options);
                expect(result).to.be.equal(true);
        }
}
</code></pre>
<p>Both of the tries were not successfull. the decorator was executed anyways but I actually just want to skip it.</p>
<p>How can I achieve this?</p>
",https://stackoverflow.com/questions/67413500/unit-testing-of-functions-with-method-decorator-with-mocha-and-sinon,"['typescript', 'unit-testing', 'mocha.js', 'decorator', 'sinon']",1528,True,2,2
Unit Testing for Filtered set of results using Laravel and PhpUnit,"<p>Lets say I have a system, build with Laravel and used for displaying different restaurants and It has a standard filter , that checks for all restaurants that have the given filter criteria.
Every restaurant holds properties:</p>
<ul>
<li>has_wifi;  can_pay_with_card;  has_parking;  is_pet_friendly</li>
</ul>
<div class=""s-table-container"">
<table class=""s-table"">
<thead>
<tr>
<th style=""text-align: center;"">Restaurant</th>
<th style=""text-align: center;"">Wifi</th>
<th style=""text-align: center;"">Card Pay</th>
<th style=""text-align: center;"">Parking</th>
<th style=""text-align: center;"">Pet Friendly</th>
</tr>
</thead>
<tbody>
<tr>
<td style=""text-align: center;"">R 1</td>
<td style=""text-align: center;"">1</td>
<td style=""text-align: center;"">1</td>
<td style=""text-align: center;"">0</td>
<td style=""text-align: center;"">0</td>
</tr>
<tr>
<td style=""text-align: center;"">R 2</td>
<td style=""text-align: center;"">0</td>
<td style=""text-align: center;"">0</td>
<td style=""text-align: center;"">1</td>
<td style=""text-align: center;"">1</td>
</tr>
<tr>
<td style=""text-align: center;"">R 3</td>
<td style=""text-align: center;"">1</td>
<td style=""text-align: center;"">1</td>
<td style=""text-align: center;"">1</td>
<td style=""text-align: center;"">0</td>
</tr>
</tbody>
</table>
</div>
<p>and there is filter, that uses those same properties.</p>
<p>(<strong>Wifi</strong>) (Card Pay) (Parking) (Pet Friendly) -&gt; R1, R3</p>
<p>(<strong>Wifi</strong>) (Card Pay) (<strong>Parking</strong>) (Pet Friendly) -&gt; R3</p>
<p>Currently I am writing tests using PHPUnit and for what I understand, I should check all input possibilities for the given filter and compare the returned subset of data.</p>
<p>(<strong>Wifi</strong>) (Card Pay) (Parking) (Pet Friendly)</p>
<p>(<strong>Wifi</strong>) (<strong>Card Pay</strong>) (Parking) (Pet Friendly)</p>
<p>(<strong>Wifi</strong>) (<strong>Card Pay</strong>) (<strong>Parking</strong>) (Pet Friendly)</p>
<p>…..</p>
<p>(Wifi) (<strong>Card Pay</strong>) (<strong>Parking</strong>) (Pet Friendly)</p>
<p>….</p>
<p>(Wifi) (Card Pay) (Parking) (<strong>Pet Friendly</strong>)</p>
<p>For the base case, where I should check only for places with wifi for example, I can do the following:</p>
<pre><code>public function testFilterByWifiWithPlaces()
{
    $body = $this-&gt;requestParameters([
        'wifi' =&gt; 1,
    ]);

    $this-&gt;json(
        'POST',
        $this-&gt;baseUrl . self::SEARCH_PLACES_ENDPOINT,
        $body,
        $this-&gt;requestHeaders()
    )-&gt;seeJsonStructure([
        'id',
        'code',
        'data' =&gt; [
            'places' =&gt; [
                '*' =&gt; $this-&gt;dataObject-&gt;getStructure()
            ],
        ]
    ])-&gt;seeJson([
    'id' =&gt; $this-&gt;placeWithWifi-&gt;place_key,
    'name' =&gt; $this-&gt;placeWithWifi-&gt;default_name]);
}
</code></pre>
<p>BUT given the data that I have and the dual possibility of the values, using separate methods like
<code>testFilterByWifiWithPlaces()</code>, <code>testFilterByWifiAndParkingWithPlaces()</code>,… (all possibilities),… is not an valid option for sure!</p>
<p>My approach to the problem is the following:</p>
<ul>
<li>Creating a array holding instances of all possible objects with
different property combinations</li>
<li>Accessing them via keys: ex: <code>$testRestaurants[‘with_wifi][’no_card_pay’][‘with_parking][’no_pet_friendly’]</code>
-&gt; Restaurant object</li>
<li>Looping through all $testRestaurants and executing above mentioned logic, knowing the state of the filter from keys given</li>
</ul>
<p>I am not sure if i am on the right track. This seems as a problem that many people should’ve faced, taking in consideration the large amount of filter engines existing on the internet :D Still , I wonder is there easiest way to test this kind of large set with data with many possibilities?</p>
",https://stackoverflow.com/questions/65795235/unit-testing-for-filtered-set-of-results-using-laravel-and-phpunit,"['php', 'laravel', 'unit-testing', 'testing', 'phpunit']",370,False,1,0
"Unit testing actix actors, sending messages to different types of actor","<p>I'm trying to use the Rust Actix actor framework where I have a thread polling some hardware, forming simple event messages and sending them to an Actor via its <code>Addr</code>. There's an enum <code>KeyingEvent</code> that forms the <code>Message</code>.</p>
<p>In my tests, I have an Actor that captures incoming <code>KeyingEvents</code>, and records them for the test to verify:</p>
<pre><code>    struct CapturingKeyingEventReceiver {
        received_keying_events: Vec&lt;KeyingEvent&gt;,
    }
    impl CapturingKeyingEventReceiver {
        fn new() -&gt; Self {
            Self {
                received_keying_events: vec![],
            }
        }
    }
    impl Actor for CapturingKeyingEventReceiver {
        type Context = Context&lt;Self&gt;;
    }
    impl Handler&lt;KeyingEvent&gt; for CapturingKeyingEventReceiver {
        type Result = ();
        fn handle(&amp;mut self, keying_event: KeyingEvent, _ctx: &amp;mut Self::Context) {
            info!(&quot;Keying Event {}&quot;, keying_event);
            self.received_keying_events.push(keying_event);
        }
    }
</code></pre>
<p>I start this and get its Addr with:</p>
<pre><code>let capturing_keying_event_receiver = CapturingKeyingEventReceiver::new().start();
</code></pre>
<p>This is an Addr, and I could pass this to my threaded code's constructor....</p>
<p>However in my application code, I have a different Actor, <code>KeyingEventRouter</code> that also handles these messages and routes them to various other subsystems:</p>
<pre><code>struct KeyingEventRouter {
...
}
impl Actor for KeyingEventRouter {
...
}
impl Handler&lt;KeyingEvent&gt; for KeyingEventRouter {
...
}
</code></pre>
<p>The problem I have is in my threaded code constructor, how can I pass a generic <code>Addr&lt;???&gt;</code> as the destination actor to which the thread should send messages? - I've tried specifying the parameter in the constructor as:</p>
<pre><code>pub fn new(keying_event_receiver: Addr&lt;dyn Actor&gt;) -&gt; Self {
...
</code></pre>
<p>But Rust disallows this:</p>
<pre class=""lang-none prettyprint-override""><code>help: specify the associated type: `Actor&lt;Context = Type&gt;`
</code></pre>
<p>I'd like it to be able to send these messages to any actor that is a <code>Handler&lt;KeyingEvent&gt;</code>. How do I allow the constructor to take an <code>Addr&lt;CapturingKeyingEventReceiver&gt;</code> in my test, and an <code>Addr&lt;KeyingEventRouter&gt;</code> in my application code?</p>
<p>In Java (handwaving a bit) I'd create an interface <code>KeyingEventReceiver</code>, have <code>CapturingKeyingEventReceiver</code> and <code>KeyingEventRouter</code> inherit from it, and pass an <code>Addr&lt;KeyingEventReceiver&gt;</code>..... but how do you say 'impl Actor from KeyingEventReceiver' since <code>KeyingEventReceiver</code> has to be a concrete struct?</p>
",https://stackoverflow.com/questions/69403308/unit-testing-actix-actors-sending-messages-to-different-types-of-actor,"['rust', 'rust-actix']",633,True,1,1
Angular Unit Testing - Is there an advantage to calling ngOnDestroy() or fixture.destroy()?,"<p>I have seen the practice of manually destroying the component in <code>afterEach()</code> with something like the following:</p>
<pre><code>afterEach() {
  component.ngOnDestroy();
  // or fixture.destroy();
}
</code></pre>
<p>Is there a performance enhancement in doing this? I couldn't see in the documentation any concern for destroying a component after each unit test. Does it speed up a large batch of unit tests running? Are there memory leaks otherwise while other tests continue to run? Is there a difference for <code>jest</code> vs <code>jasmine+karma</code>?</p>
",https://stackoverflow.com/questions/67127170/angular-unit-testing-is-there-an-advantage-to-calling-ngondestroy-or-fixture,"['angular', 'jestjs', 'jasmine', 'karma-runner']",615,False,7,0
Why users credentials are not working in my login unit testing?,"<p>I'm using PHPUnit for testing my Laravel project.</p>
<pre><code>?php

namespace Tests\Feature;

use App\Models\User;
use Tests\TestCase;

class LoginTest extends TestCase
{
    public function test_user_can_login():
    {
        $user = User::factory()-&gt;create();

        $response = $this-&gt;postJson('/api/auth/login', [
            'email'    =&gt; $user-&gt;email,
            'password' =&gt; $user-&gt;password,
        ]);

        $response
            -&gt;assertStatus(200)
            -&gt;assertHeader('Authorization')
            -&gt;assertJson([
                'success' =&gt; 'Usuário logado com sucesso!',
            ]);
    }
}
</code></pre>
<p>I want to create a new user for login test flow, but it returns a 400 status response.</p>
<blockquote>
<p>Tests\Feature\LoginTest &gt; user can login
Expected status code 200 but received 400.
Failed asserting that 200 is identical to 400.</p>
</blockquote>
<p>I have no idea what is going wrong. Any suggestions?</p>
",https://stackoverflow.com/questions/68758497/why-users-credentials-are-not-working-in-my-login-unit-testing,"['laravel', 'authentication', 'testing', 'jwt', 'phpunit']",303,False,1,0
Angular 11: Unit testing an HttpInterceptor - async timer or AfterAll errors,"<p>I'm working on getting my HttpInterceptor to pass my unit tests and I have run into issues with getting the tests to pass. I have 6 tests and If I run the tests as &quot;normal&quot; tests, I often get &quot;An error was thrown in afterAll&quot; as the tests finish locally, but my Azure pipelines fail with the same error every time.</p>
<p>If I run the tests in an async zone using <code>fakeAsync()</code>, I get a &quot;1 timer(s) still in the queue&quot; error for each.</p>
<p>Here's the code for the Interceptor:</p>
<pre class=""lang-js prettyprint-override""><code>import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { retry, tap, catchError } from 'rxjs/operators';
import { HttpServiceError } from '../models/httpServiceError.model';
import { LoggingService, LogLevel } from '../services/logging.service';

@Injectable({
    providedIn: 'root'
})

export class HttpResponseInterceptorService implements HttpInterceptor{
  public logLevel!: LogLevel;

  constructor(private readonly loggingService: LoggingService) {
// Intentionally left blank
  }

  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    return next.handle(request)
      .pipe(
        retry(1),
        tap(() =&gt; console.log('ResponseInterceptor called')),
        catchError((error: HttpErrorResponse) =&gt; {
          this.handleHttpError(error);
          return throwError(error);
        }));
  }

  private handleHttpError(error: HttpErrorResponse): Observable&lt;HttpServiceError&gt; {
    const requestError = new HttpServiceError();    
    
    requestError.errorNumber = error.status;
    requestError.statusMessage = error.statusText;

    switch (error.status) {
      case 401: {
        requestError.friendlyMessage = 'You are not logged in';
        break;
      }
      case 403: {
        requestError.friendlyMessage = 'You are not logged in';
        break;
      }
      case 404: {
        requestError.friendlyMessage = 'The service failed to respond';
        break;
      }
      case 429: {
        requestError.friendlyMessage = 'The service is busy';
        break;
      }
      case 500: {
        requestError.friendlyMessage = 'The service is not responding correctly';
        break;
      }
      default: {
        requestError.friendlyMessage = 'An error occured retrieving the data';
        break;
      }
    }

    // TODO replace with some kind of notification
    // window.alert(errorMessage);

    this.loggingService.logWithLevel(JSON.stringify(requestError), LogLevel.Information);

    return throwError(requestError);
  }
}
</code></pre>
<p>Here's my spec file:</p>
<pre class=""lang-js prettyprint-override""><code>import { HttpClient, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { fakeAsync, flush, inject, TestBed } from '@angular/core/testing';
import { LoggingService } from '../services/logging.service';

import { HttpResponseInterceptorService } from './httpresponseinterceptor.service';

describe('HttpResponseInterceptorService', () =&gt; {
  let interceptor: HttpResponseInterceptorService;
  let httpMock: HttpTestingController;
  let loggingService: LoggingService;
  let httpClient: HttpClient;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [
        {
          provide: HTTP_INTERCEPTORS,
          useClass: HttpResponseInterceptorService,
          multi: true,
        },
      ]
    });
    loggingService = TestBed.inject(LoggingService);
    interceptor = TestBed.inject(HttpResponseInterceptorService);
    httpMock = TestBed.inject(HttpTestingController);
    httpClient = TestBed.inject(HttpClient);
  });

  afterEach(() =&gt; {
    httpMock.verify();
  });

  afterAll(() =&gt; {
    TestBed.resetTestingModule();
  });

  it('should be created', () =&gt; {
    expect(interceptor).toBeTruthy();
  });

  it('should call loggingService with a friendlyMessage of An error occured retrieving the data (everything else)', fakeAsync(() =&gt; {
    spyOn(loggingService,'logWithLevel');

    const errorResponse = new HttpErrorResponse({
      error: '599 error',
      status: 599, statusText: 'Unknown Error'
    });

    httpClient.get('/api').subscribe();

    let request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('599 First Unknown Error'), errorResponse);

    request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('599 Second Unknown Error'), errorResponse);

    expect(loggingService.logWithLevel).toHaveBeenCalled();
  }));

  it('should call loggingService with a friendlyMessage of You are not logged in (401)', fakeAsync(() =&gt; {
    spyOn(loggingService,'logWithLevel');

    const errorResponse = new HttpErrorResponse({
      error: '401 error',
      status: 401, statusText: 'Unauthorized'
    });

    httpClient.get('/api').subscribe();

    let request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('401 First Unauthorized'), errorResponse);

    request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('401 Second Unauthorized'), errorResponse);

    expect(loggingService.logWithLevel).toHaveBeenCalled();
  }));

  it('should call loggingService with a friendlyMessage of You are not logged in (403)', fakeAsync(() =&gt; {
    spyOn(loggingService,'logWithLevel');

    const errorResponse = new HttpErrorResponse({
      error: '403 error',
      status: 403, statusText: 'Forbidden'
    });

    httpClient.get('/api').subscribe();

    let request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('403 First Forbidden'), errorResponse);

    request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('403 Second Forbidden'), errorResponse);

    expect(loggingService.logWithLevel).toHaveBeenCalled();
  }));

  it('should call loggingService with a friendlyMessage of The service failed to respond (404)', fakeAsync(() =&gt; {
    spyOn(loggingService,'logWithLevel');

    const errorResponse = new HttpErrorResponse({
      error: '404 error',
      status: 404, statusText: 'Not Found'
    });

    httpClient.get('/api').subscribe();

    let request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('404 First Error'), errorResponse);

    request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('404 Second Error'), errorResponse);

    expect(loggingService.logWithLevel).toHaveBeenCalled();
  }));

  it('should call loggingService with a friendlyMessage of The service is busy (429)', fakeAsync(() =&gt; {
    spyOn(loggingService,'logWithLevel');

    const errorResponse = new HttpErrorResponse({
      error: '429 error',
      status: 429, statusText: 'Too Many Requests'
    });

    httpClient.get('/api').subscribe();

    let request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('429 First Too Many Requests'), errorResponse);

    request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('429 Second Too Many Requests'), errorResponse);

    expect(loggingService.logWithLevel).toHaveBeenCalled();

  }));

  it('should call loggingService with a friendlyMessage of The service is not responding correctly (500)', fakeAsync(() =&gt; {
    spyOn(loggingService,'logWithLevel');

    const errorResponse = new HttpErrorResponse({
      error: '500 error',
      status: 500, statusText: 'Internal Server Error'
    });

    httpClient.get('/api').subscribe();

    let request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('500 First Internal Server Error'), errorResponse);

    request = httpMock.expectOne('/api');
    request.error(new ErrorEvent('500 Second Internal Server Error'), errorResponse);

    expect(loggingService.logWithLevel).toHaveBeenCalled();
  }));

});
</code></pre>
<p>It seems that there'a an async call that doesn't get completed. I have tried with <code>flush()</code> after the <code>httpClient.get()</code> call, I have tried to put it after both <code>request = httpMock.expectOne('/api')</code>, after each call and nothing seems to actually fix the error.</p>
<p>It may also be down to my clumsy one-test-per-condition approach.</p>
<p>Good ideas and feedback are very welcomed!</p>
<p>Thanks, Bjarne</p>
",https://stackoverflow.com/questions/66566994/angular-11-unit-testing-an-httpinterceptor-async-timer-or-afterall-errors,"['angular', 'unit-testing', 'karma-jasmine']",728,True,1,1
How to do Unit testing in Object Box for flutter project?,"<p>How can we do unit testing for object box in flutter project for all crud operations?</p>
<pre><code>class ShapeRepo {

final _box = store.box&lt;ShapeModel&gt;();

void saveShape(ShapeModel model) {
    _box.put(model);
}

</code></pre>
<p>This is one example. There are many box operations. I was wondering if a separate object box store is available for testing?</p>
",https://stackoverflow.com/questions/68711698/how-to-do-unit-testing-in-object-box-for-flutter-project,"['flutter', 'unit-testing', 'dart', 'flutter-objectbox']",745,True,1,1
Laravel 6 PHP unit testing - Session store not set on request,"<p>I got a run time error (RuntimeException: Session store not set on request.) while running the unit testing</p>
<pre><code>public function testUserCanLoginCorrectCredentials()
{
    $this-&gt;withoutExceptionHandling();
    $user = factory(Users::class)-&gt;create();
    $response = $this-&gt;post('/admin/login', [
        'email' =&gt; $user-&gt;email,
        'password' =&gt; '123456789',
    ]);
    $response-&gt;withSession(['user_id' =&gt; $user-&gt;id]);
    $response-&gt;assertRedirect('/admin/dashboard');
    $this-&gt;assertAuthenticatedAs($user);
}
</code></pre>
<p>In Controller :</p>
<pre><code>$checkUserExist =$this-&gt;users-&gt;where('email',$request-&gt;email)-&gt;where('password',$request-&gt;password)-&gt;first();
if(isset($checkUserExist)){

    $user = Auth::guard('users');
    $users = Auth::login($checkUserExist);
    //Authentication passed...
    $request-&gt;session()-&gt;put('admin_user_id', $checkUserExist-&gt;id);
    return redirect('admin/dashboard')-&gt;with('success', 'You are Logged in !');
} else {
    return redirect('/admin')-&gt;with('error','Invalid Password, Please Entered Correct Credentials!');
}
</code></pre>
<p>While running the command I'm getting this error</p>
<pre><code>Time: 1.76 seconds, Memory: 52.00 MB

There was 1 error:

1) Tests\Unit\HostLoginTest::testUserCanLoginCorrectCredentials
RuntimeException: Session store not set on request.

C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Http\Request.php:482
C:\xampp\htdocs\parkk-web\app\Http\Controllers\Auth\LoginController.php:107
C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php:45
C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Routing\Route.php:219
C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Routing\Route.php:176
C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Routing\Router.php:680
</code></pre>
",https://stackoverflow.com/questions/70096316/laravel-6-php-unit-testing-session-store-not-set-on-request,"['php', 'laravel']",1273,False,1,1
Android Studio unit testing with LibGDX test folder missing Arctic Fox,"<p>I've not used Android Studio in a while and have forgotten more things about it than I ever knew.</p>
<p>I am working with LibGDX and have some complicated class/methods I'd like to do unit testing on them outside of the graphic environment. On a normal android project, I'd have a structure that looks something like:
app
manifests
java
com.example.myApplication
MainActivity
ClassToTest
com.example.myApplication (test)
ClassToTestUnitTest</p>
<p>But when I generate a LibGDX my structure looks like:
Android
manifests
java
com.example.myApplication
MainActivity
ClassToTest</p>
<p>When I go to 'Generate...' 'Tests' by right clicking on the ClassToTest entry in the java file, I receive the message 'Create test in the same root?'</p>
<p><strong>No</strong>, I don't want that - I want to have a special folder for tests to be contained away from my main code.</p>
<p>How do I create that folder and have the test generator know where it is?? All the answers I could find looked like they were created for a much older version of Android Studio, since the folder hierarchy was different.</p>
<p>In further looking, it appeared I needed to make some changes to my code build.gradle. I tried the changes suggested, but there was no effect that I could see.</p>
<p>The gradle now looks like:</p>
<pre><code>sourceCompatibility = 1.7
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

sourceSets.main.java.srcDirs = [ &quot;src/&quot; ]
sourceSets.test.java.srcDirs = [&quot;test/&quot;]

eclipse.project.name = appName + &quot;-core&quot;
</code></pre>
<p>Thanks for any insight you can provide. I am sure I am missing something fairly basic.</p>
",https://stackoverflow.com/questions/68667909/android-studio-unit-testing-with-libgdx-test-folder-missing-arctic-fox,"['java', 'android-studio', 'unit-testing']",126,False,1,0
C# - Unit testing - initializing private fields - ASP.NET Core 5 - NUnit test,"<p>I am new to unit testing, and is currently trying to test a method that gets rows of data using Entity Framework from a SQL Server database.</p>
<p>The problem is that I have 3 fields that are private readonly, and I need to pass those three fields to a method. But since I cant make a constructor, all 3 values are null as default.</p>
<p>How do I make initialize private readonly fields, that talk with a database when unit testing?</p>
",https://stackoverflow.com/questions/70317504/c-unit-testing-initializing-private-fields-asp-net-core-5-nunit-test,"['c#', 'entity-framework', 'unit-testing', 'initialization', 'nunit']",287,False,1,1
Unit testing and coverage-ing a function using multiprocessing.Process() in python,"<p>I am trying to test a function that might crash, using multiprocessing.Process(). The code written below restarts the call if the function doesn't respond ideally within 10 minutes which is working completely fine, even the <code>self.assert...</code> tests are working fine. The problem comes out to be with the coverage, for some reason, running coverage over my files shows that <code>my_func</code> is being called but nothing inside it is getting covered while testing whereas the tests (which require the whole function to be executed without crashing) are passing.</p>
<pre><code>        while True:
           p = multiprocessing.Process(
               target=my_func, args=(return_dict) # return_dict to get the return values
           )
           p.start()
           p.join(600)

           if p.is_alive():
               print(
                   &quot;Taking too long, &quot;
                   + &quot;KILLING IT and starting AGAIN.&quot;
               )
               p.kill()
               p.join()
           else:
               break
</code></pre>
<p>Is there something that I am doing wrong? Please let me know if the information seems incomplete, I'll add my tests and the function then.</p>
",https://stackoverflow.com/questions/67891203/unit-testing-and-coverage-ing-a-function-using-multiprocessing-process-in-pyth,"['python', 'code-coverage', 'python-multiprocessing', 'python-unittest', 'coverage.py']",777,True,1,1
How to skip calling function in unit testing controller moq context?,"<p>This is my controller</p>
<pre><code>BusinessLayer.Lookup.Lookup_Rooms RoomsBL = new BusinessLayer.Lookup.Lookup_Rooms();

[HttpPost]
public ActionResult CreateRoom(UMIS_Portal_BackEnd.Areas.StudentAcadimic.Models.RoomLocationModel room) {
        
    if (ModelState.IsValid)
    {
        try
        {
            // TODO: Add insert logic here

           

           
            int? Serial = RoomsBL.Lookup_RoomInsert(room.BuildingFloorID, room.RoomName, room.Min_Capacity, room.Max_Capacity);
           
        }
        catch (Exception error)
        {
            
            ViewBag.Messages = error.InnerException.Message;
         
        }

    }
    return View();
}
</code></pre>
<p>I only want to test that there is view exist for this action result so i write this code</p>
<pre><code>[TestMethod()]
public void CreateRoomTestPost()
{
    LookupRoomsController controller = new LookupRoomsController();
  
    UMIS_Portal_BackEnd.Areas.StudentAcadimic.Models.RoomLocationModel room = new UMIS_Portal_BackEnd.Areas.StudentAcadimic.Models.RoomLocationModel();

    ViewResult viewResult = controller.CreateRoom(room) as ViewResult;
    Assert.IsNotNull(viewResult);
 
}
</code></pre>
<p>I want the test to skip calling</p>
<pre><code>int? Serial = RoomsBL.Lookup_RoomInsert(room.BuildingFloorID, room.RoomName, room.Min_Capacity, room.Max_Capacity); 
</code></pre>
<p>on the main controller action.</p>
",https://stackoverflow.com/questions/66333869/how-to-skip-calling-function-in-unit-testing-controller-moq-context,"['c#', 'asp.net-mvc', 'unit-testing', 'moq']",308,True,1,1
Getting error while unit testing my own Node modules with Cypress.io,"<p><a href=""https://stackoverflow.com/questions/66055150/how-to-run-unit-tests-with-cypress-io"">Following this previous question &amp; answer</a>. I was able to start using <a href=""https://www.cypress.io/"" rel=""nofollow noreferrer"">Cypress</a> to unit test my Node's module by using the <a href=""https://docs.cypress.io/api/commands/task.html#Syntax"" rel=""nofollow noreferrer"">task()</a> method. However, I'm getting an error which I have been trying to debug or find a reference online but I haven't been able to.</p>
<pre><code>cy:command ✘  assert    expected **{ Object (userInvocationStack, specWindow, ...) }** to equal **[]**
</code></pre>
<p>What's this <code>{ Object (userInvocationStack, specWindow, ...) }</code>? How can I get the actual <code>array</code> of <code>objects</code> instead?</p>
<p><strong>EDIT:</strong> Included <code>assertions</code> &amp; <code>task</code> code.</p>
<p><strong>File:</strong><code>utils.spec.js</code></p>
<pre><code>describe('Unit Tests for utils.js methods', () =&gt; {
  /**
   * Array of objects mocking Tickets Object response
   */
  const mockedTickets = {
    data: {
      issues: [
        {
          id: 1,
          key: 'ticket-key-1',
          fields: {
            summary: 'This is ticket number 1',
          },
        },
        {
          id: 2,
          key: 'ticket-key-2',
          fields: {
            summary: 'This is ticket number 2',
          },
        },
      ],
    },
  };

  const mockedEmptyTicketsArray = [];

  it('returns an array containing a found ticket summary', () =&gt; {
    expect(
      cy.task('getTicketBySummary', {
        issues: mockedTickets,
        summaryTitle: 'This is ticket number 1',
      })
    ).eq(mockedTickets.data.issues[0]);
  });
  it('returns an empty array, when no ticket summary was found', () =&gt; {
    expect(
      cy.task('getTicketBySummary', {
        issues: mockedTickets,
        summaryTitle: 'This is ticket number 3',
      })
    ).eq(mockedEmptyTicketsArray);
  });
});
</code></pre>
<p><strong>File:</strong>`plugins/index.js</p>
<pre><code>on('task', {
    getTicketBySummary({ issues, summaryTitle }) {
      issues.data.issues.filter(issueData =&gt; {
        return issueData.fields.summary === summaryTitle ? issueData : null;
      });
    },
  });
</code></pre>
",https://stackoverflow.com/questions/66106349/getting-error-while-unit-testing-my-own-node-modules-with-cypress-io,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'cypress']",1713,True,1,2
How to create dummy ExecutionContext for CanActivate function for unit testing?,"<p>I have authGuard service with canActivate function ```<pre>canActivate(context: ExecutionContext): boolean | Promise | Observable</p>
<p>const ctx = GqlExecutionContext.create(context);
const { req } = ctx.getContext();   </pre> ```
For testing this function with some header value and all, I need to pass ExecutionContext.
So How to create dummy ExecutionContext for test this function?
This is the interface of ExecutionContext.</p>
<pre><code>export interface ExecutionContext extends ArgumentsHost {
    /**
     * Returns the *type* of the controller class which the current handler belongs to.
     */
    getClass&lt;T = any&gt;(): Type&lt;T&gt;;
    /**
     * Returns a reference to the handler (method) that will be invoked next in the
     * request pipeline.
     */
    getHandler(): Function;
}


export interface ArgumentsHost {
    /**
     * Returns the array of arguments being passed to the handler.
     */
    getArgs&lt;T extends Array&lt;any&gt; = any[]&gt;(): T;
    /**
     * Returns a particular argument by index.
     * @param index index of argument to retrieve
     */
    getArgByIndex&lt;T = any&gt;(index: number): T;
    /**
     * Switch context to RPC.
     * @returns interface with methods to retrieve RPC arguments
     */
    switchToRpc(): RpcArgumentsHost;
    /**
     * Switch context to HTTP.
     * @returns interface with methods to retrieve HTTP arguments
     */
    switchToHttp(): HttpArgumentsHost;
    /**
     * Switch context to WebSockets.
     * @returns interface with methods to retrieve WebSockets arguments
     */
    switchToWs(): WsArgumentsHost;
    /**
     * Returns the current execution context type (string)
     */
    getType&lt;TContext extends string = ContextType&gt;(): TContext;

}```
</code></pre>
",https://stackoverflow.com/questions/65786534/how-to-create-dummy-executioncontext-for-canactivate-function-for-unit-testing,"['typescript', 'nestjs']",1874,True,0,1
"Angular Unit Testing using Jasmine and Karma, for a switch case","<p>I am new to angular unit testing</p>
<p>I have implemented a method to convert the data type of the column values(which is of type text) of a particular array, into integer or float. And I used a switch case for this in my product component.</p>
<p>Here is my switch method</p>
<pre class=""lang-js prettyprint-override""><code>
     export() {
       
        this.getProducts().then(() =&gt; {
          let products: Array&lt;Array&lt;any&gt;&gt; = [];
        
        this.productContent = this.productContent.map(product =&gt; {
            ProductConfig.forEach(item =&gt; {
              let columnValue = product[item.column];
              let valueIsString = isNaN(parseFloat(columnValue));
              if (!valueIsString) {
                switch (item.dataType) {
                  case item.dataType = &quot;Integer&quot;: {
                    product[item.column] = parseInt(columnValue);
                    break;
                  }
                  case item.dataType = &quot;Float&quot;: {
                    product[item.column] = parseFloat(columnValue);
                    break;
                  }
                  default: {
                    product[item.column] = columnValue;
                    break;
                  }
                }
              }
            });
            return product;
          });
        
    }

</code></pre>
<p>The productConfig is implemented as below.</p>
<pre class=""lang-js prettyprint-override""><code>export const ProductConfig
  = [
    { column:&quot;Product Code&quot;, dataType: &quot;Integer&quot; },
    { column:&quot;Total Price&quot;, dataType: &quot;Float&quot; },
    { column:&quot;Discounted Price&quot;, dataType: &quot;Float&quot; },
    { column:&quot;Tax&quot;, dataType: &quot;Float&quot; },
  ]
</code></pre>
<p>How can I write a unit test case for the above method using jasmine and karma?</p>
",https://stackoverflow.com/questions/68411211/angular-unit-testing-using-jasmine-and-karma-for-a-switch-case,"['angular', 'unit-testing', 'switch-statement', 'karma-jasmine']",353,False,0,0
Getting unexpected error while executing queries for unit testing with sqlmock,"<p>I have the following function that takes a slice of type <code>SchoolDbEntry</code> and bulk inserts it into a DB.</p>
<pre><code>type SchoolRegistry struct {
    Conn         *sqlx.DB
}

insertStudentEntry = `insert into StudentEntries (registerId, studentId, fee, admissionDate) values (:registerId, :studentId, :fee, :admissionDate)`

func (s *SchoolRegistry) AddStudentEntries(ctx context.Context, entry []StudentDbEntry) error {
    requestHeaders := helper.FetchHeaders(ctx)

    query, args, err := sqlx.Named(insertStudentEntry, entry)
    if err != nil {
        return exception.DBInternalError
    }

    _, err = s.Conn.Exec(query, args...)
    if err != nil {
        return cutomModels.NewError(err.Error()
    }

    return nil
}
</code></pre>
<p>I am trying to test this using sqlmock using the following functions</p>
<pre><code>var repo *SchoolRegistry


func TestAddStudentEntriesSuccess(t *testing.T) {

     db, mock, err := sqlmock.New()
     if err != nil {
            t.Fatalf(&quot;an error '%s' was not expected when opening a stub database connection&quot;, err)
     }

     sqlxDb := sqlx.NewDb(db, &quot;sqlmock&quot;)

     defer sqlxDb.Close()

     repo = &amp;SchoolRegistry{sqlxDb}
     if err := logger.Init(logLevel, logTimeFormat); err != nil {
         fmt.Printf(&quot;failed to initialize logger: %v&quot;, err)
     }

    query := `insert into StudentEntries (registerId, studentId, fee, admissionDate) values (:registerId, :studentId, :fee, :admissionDate)`

    args := []models.StudentDbEntry{
        {
            RegisterID:     1,
            StudentID:      1,
            Fee:            &quot;100&quot;,
            AdmissionDate:  &quot;10-20-2015&quot;,
        },
    }

    prep := mock.ExpectPrepare(query)
    prep.ExpectExec().WithArgs(1,1,&quot;100&quot;,&quot;10-20-2015&quot;).WillReturnResult(sqlmock.NewResult(0, 0))

    err := repo.AddStudentEntries(helper.FetchTestContext(), args)
    assert.NoError(t, err)

}
</code></pre>
<p>However, the tests are failing. I am getting</p>
<pre><code>call to ExecQuery 'insert into StudentEntries (registerId, studentId, fee, admissionDate) values (?, ?, ?, ?)' with args [{Name: Ordinal:1 Value:1} {Name: Ordinal:2 Value:1} {Name: Ordinal:3 Value:&quot;100&quot;} {Name: Ordinal:4 Value:&quot;10-20-2015&quot;}], was not expected, next expectation is: ExpectedPrepare =&gt; expecting Prepare statement which:
                              - matches sql: 'insert into StudentEntries (registerId, studentId, fee, admissionDate) values (:registerId, :studentId, :fee, :admissionDate)' 
</code></pre>
<p>error when no errors are expected ( that is, after this line : <code>_, err = s.Conn.Exec(query, args...)</code> ). The function works fine when I tested it as a part of the actual code. The issue is just with the unit testing.</p>
",https://stackoverflow.com/questions/69456040/getting-unexpected-error-while-executing-queries-for-unit-testing-with-sqlmock,"['unit-testing', 'go', 'sqlx', 'go-sqlmock']",348,False,0,0
How to pass specific UserContext in unit testing of controller action,"<p>I have the following controller action</p>
<pre><code>        [Route(ActionName.Create)]
        public async Task&lt;ActionResult&gt; Create()
        {
            .... 
            if (!UserContext.Roles.HasFlag(GroupsEnum.Admin))
            {
                throw new UnauthorizedAccessException(&quot;Permission Denied&quot;);
            }
            ... 
        }
</code></pre>
<p>I have following in xxxxControllerTests.cs</p>
<pre><code>        [TestMethod]
        public async Task Can_Request_Create()
        {

            ViewResult result = (ViewResult)await MockController.Object.Create();
            ...
            ...
        }
</code></pre>
<p>when I run the unit test I get unauthorized access exception raised. How can pass UserContext while mockController, so controller action will be executed with specific user context?</p>
",https://stackoverflow.com/questions/66232754/how-to-pass-specific-usercontext-in-unit-testing-of-controller-action,"['c#', 'unit-testing']",688,True,-1,2
Database unit testing - How to mock the time within a procedure,"<p>I have a TSQL procedure in an Azure Database Instance. The procedure has logic that determines the state of an ETL process and <strong>is sensitive to the current time</strong> to determine whether an event is within bound or not within bound. This procedure has complex behaviour and <strong>is a core requirement</strong>.</p>
<p>I must validate the behaviour of the procedure. I am writing unit tests in Python, I am using <code>unittest</code> to manage tests and <code>pyodbc</code> to make the calls to the database. These unit tests must validate the behaviour of the procedure irrespective of the time that the procedure is called. <strong>I need the database to behave as if it is a certain time like '05:30:00' for example</strong>.</p>
<p>I am familiar with the concept of mocking objects to run tests at any time and to remove external dependencies. I do not think this applies to Microsoft databases, more like a REST API for example. Another consideration is that <strong>I would not want to target a copy of the object</strong> that I want to test as the copy might not be the same as the original.</p>
<p><strong>The only solutions that come to mind (<em>bad solutions</em>) are:</strong></p>
<ul>
<li>Implement a variable in the procedure to hold <code>DATETIME</code> and override this using a parameter with a <code>DEFAULT</code> specification instead of <code>GETDATE()</code>.</li>
<li>Use some conditional logic that is only executed if the session was authenticated by the application account that runs the tests, using a default value for the time.</li>
</ul>
<p><strong>Outcomes of 1 would be;</strong></p>
<ul>
<li>All calls to the procedure would need to be updated</li>
<li>A parameter that <em>shouldn't be there</em> would now be included</li>
<li>Risk of calling the procedure with the wrong arguments would be increased and could cause havoc <em>silently</em></li>
</ul>
<p><strong>Outcomes of 2 would be;</strong></p>
<ul>
<li>Testing is dependent on the user account not changing and if we segregate responsibility for security implementation and that person is not available we would be temporarily stuck</li>
<li>Slower procedure</li>
<li>Reduced readability</li>
</ul>
<p>Both of these options are awful. Has anybody been able to solve this kind of problem?</p>
",https://stackoverflow.com/questions/69741261/database-unit-testing-how-to-mock-the-time-within-a-procedure,"['unit-testing', 'stored-procedures', 'azure-sql-database', 'python-unittest']",179,True,0,1
Laravel 8 Unit Testing - assertJson() how to capture it in controller,"<p>I have a laravel 8 Unit Test which looks like this:</p>
<pre><code>public function testAddingTwoCars()
{
    $response = $this-&gt;postJson('api/basket', ['cars' =&gt; [['name' =&gt; 'car one'], ['name' =&gt; 'car two']]]);
    $response
        -&gt;assertStatus(200)
        -&gt;assertJson(['total' =&gt; 40]);
}
</code></pre>
<p>In my route I have:</p>
<pre><code>Route::post('/api/basket',[basketController::class, 'store']);
</code></pre>
<p>In my controller I have:</p>
<pre><code>public function store(Request $request)
{
    $data = $request-&gt;all();
    return response()-&gt;json($data);
}
</code></pre>
<p>when I run the test with <code>php artisan test</code> it shows this:</p>
<pre><code> • Tests\Unit\BasketTest &gt; adding two cars
 Unable to find JSON:                                        
                                                                                                                                                    
 [{                                                          
     &quot;total&quot;: 40                                             
 }]                                                          
                                                                                                                                                                      
 within response JSON:                                       
                                                        
 [{                                                          
   &quot;cars&quot;: [                                           
     {                                                   
         &quot;name&quot;: &quot;car one&quot;                                 
     },                                                  
     {                                                   
         &quot;name&quot;: &quot;car two&quot;                                 
     }                                                   
   ]                                                       
 }].      
</code></pre>
<p>How do I:grab the total as its not in <code>$request</code> so that I could do something like this in my controller:</p>
<pre><code>$public function store(Request $request)
{
    $data = $request-&gt;all();
    $data['total'] = 40;
    return response()-&gt;json($data);
}  
</code></pre>
<p>The above works, but it is hard coded so is not the best way to do it</p>
",https://stackoverflow.com/questions/66665575/laravel-8-unit-testing-assertjson-how-to-capture-it-in-controller,"['php', 'laravel', 'unit-testing']",2853,True,0,2
laravel unit testing error &#39;call to member function call() on null&#39;,"<p>I want to write a unit test for a form post request.</p>
<pre><code>public function addForm(SaveFormRequest $request)
{
    $this-&gt;servicelayer-&gt;addFormDetails($request-&gt;validated());

    return redirect-&gt;route('register');
}
</code></pre>
<p>How can I mock <code>$request-&gt;validated();</code> for a <code>FormRequest</code> class.</p>
<p>I trying below like</p>
<pre><code>$saveRequest = $this-&gt;createMock(SaveFormRequest::class);
</code></pre>
<p>But I got an error:</p>
<blockquote>
<p>Error: call to a member function <code>call()</code> on null.</p>
</blockquote>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/69112792/laravel-unit-testing-error-call-to-member-function-call-on-null,"['php', 'laravel', 'unit-testing', 'phpunit', 'laravel-unit-test']",1110,True,-1,1
"Unit testing, assert equals if difference is not bigger than 1","<p>Im new to Unit testing. I use Junit4, I have to compare two double numbers. But if difference is not longer than 1, it should pass.
For example:</p>
<pre><code>Assert.assertEquals(240, 241); //should pass
Assert.assertEquals(240, 239); //should pass

Assert.assertEquals(240, 242); //should fail
Assert.assertEquals(240, 238); //should fail
</code></pre>
<p>Is there way to implement it?</p>
",https://stackoverflow.com/questions/66007085/unit-testing-assert-equals-if-difference-is-not-bigger-than-1,"['java', 'unit-testing', 'testing', 'junit4']",193,True,0,2
Error when unit testing cloud function: no document found to update,"<p>I am following the firebase <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">documentation</a> for unit testing. I created a simple cloud function that is triggered when a firestore document is created. It turns the value in that document to uppercase. I tried the function by creating a document and it worked as expected.</p>
<p>I use jest for the test. When I run the test I get the following error:</p>
<pre><code>NOT_FOUND: No document to update: projects/myproject/databases/(default)/documents/test/testId

  10 |   return admin.firestore().doc(`test/` + snap.id)
&gt; 11 |               .update({ input: input });
     |                ^
  12 | });
</code></pre>
<p>I added a console.log to my function to see what data was passed by the unit-test. It passes the right data (meaning the right document id and the right value for &quot;input&quot;.</p>
<p>I'm not sure what I'm missing here. It's a simple function and a simple test. I don't understand how the function could receive the right data but not found the document, or how the document is not created in firestore when the test is run.</p>
<p>The function:</p>
<pre><code>import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

export const makeUpperCase = functions.firestore
.document('test/{id}')
.onCreate((snap, context) =&gt; {
  const data = snap.data();
  const input = data.input.toUpperCase();
  console.log('new data: ' + input + ', id: ' + snap.id);
  return admin.firestore().doc('test/' + snap.id)
              .update({ input: input });
});
</code></pre>
<p>index.ts:</p>
<pre><code>import * as admin from 'firebase-admin';
admin.initializeApp();

export { makeUpperCase } from './makeUpperCase';
</code></pre>
<p>the test (basicTest.test.ts):</p>
<pre><code>import * as functions from 'firebase-functions-test';
import * as admin from 'firebase-admin';
import 'jest';

const testEnv = functions({
  databaseURL: &quot;https://mydb.firebaseio.com&quot;,
  projectId: &quot;myproject&quot;,
}, './service-account.json');

testEnv.mockConfig({});

import { makeUpperCase } from '../src/index';

describe('basicTest', () =&gt; {
  let wrapped: any;

  beforeAll(() =&gt; {
    wrapped = testEnv.wrap(makeUpperCase);
  });

  test('converts input to upper case', async () =&gt; {
    const path = 'test/testId';
    const data = { input: 'a simple test' };
    const snap = await testEnv.firestore.makeDocumentSnapshot(data, path);
    await wrapped(snap);
    const after = await admin.firestore().doc(path).get();
    expect(after.data()!.input).toBe('A SIMPLE TEST');
  });
});
</code></pre>
",https://stackoverflow.com/questions/66604714/error-when-unit-testing-cloud-function-no-document-found-to-update,"['firebase', 'unit-testing']",340,False,0,1
AfterAll TypeError: Cannot read property &#39;isCompleted&#39; of undefined - Angular unit testing,"<p>I tried to recreate part of the code that we use in a real project and in which after run ng test I get this error - &quot;AfterAll TypeError: Cannot read property 'isCompleted' of undefined.</p>
<p><a href=""https://i.stack.imgur.com/vzWCT.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
<p>Unit Test Spec file.</p>
<pre><code>import { HttpClientTestingModule } from '@angular/common/http/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { EventService } from 'src/app/event.service';

import { UnitTestComponent } from './unit-test.component';

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

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

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(UnitTestComponent);
    component = fixture.componentInstance;
    eventService = TestBed.inject(EventService);
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
<p>Unit Test Component</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { EventService } from 'src/app/event.service';

@Component({
  selector: 'app-unit-test',
  templateUrl: './unit-test.component.html',
  styleUrls: ['./unit-test.component.scss']
})
export class UnitTestComponent implements OnInit {

  formStatus: string = &quot;formId2&quot;;
  isApproval: boolean = false;

  constructor(private eventService: EventService) { }

  ngOnInit(): void {
    this.getForms();
  }

  getForms(): void {
    this.eventService.forms.subscribe(res =&gt; {
      if (res) {
        this.isApproval = res.find(f =&gt; f.formId == this.formStatus).isCompleted;
      }
    })
  }
}
</code></pre>
<p>UnitTestService</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class UnitTestService {
    private URL = 'http://localhost:4200/assets/db.json';
    constructor(private http: HttpClient) { }
    // Make the HTTP request:

    getData() {
        return this.http.get(this.URL);
    }

}
</code></pre>
<p>Event Service</p>
<pre><code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
    providedIn: 'root'
})
export class EventService {
    private _formEventSub = new BehaviorSubject&lt;any[]&gt;([]);
    public forms = this._formEventSub.asObservable();

    updateValue(data: any[]) {
        this._formEventSub.next(data);
    }
}
</code></pre>
<p>Can anyone tell me why it happens so thank you.</p>
",https://stackoverflow.com/questions/67560061/afterall-typeerror-cannot-read-property-iscompleted-of-undefined-angular-un,"['angular', 'unit-testing']",833,True,0,1
Unit testing with Jest and Sequelize - Test passing when it shouldn&#39;t,"<p>I'm trying to write some unit tests, and at first they appeared to be working, but then I realized some of them were passing when they definitely shouldn't be, and I've included one such example from my code of a test passing when it shouldn't:</p>
<p><strong>controller.js</strong></p>
<pre><code>const userModel = require('../models').users;

module.exports = {
    async getUserByID(req, res) {
        try {
            var user = await userModel.findOne({
                where: { id: req.params.id }
            });
            res.status(201).send(user);
        catch (error) {
            res.status(500).send(error)
        }
    }
}
</code></pre>
<p><strong>controller.test.js</strong></p>
<pre><code>const controller = require('../controllers/controller');
const httpMocks = require('node-mocks-http');

//mock for main model that my controller function uses
jest.mock('../models/users', () =&gt; {
    const SequelizeMock = require('sequelize-mock');
    const dbMock = new SequelizeMock();
    return dbMock.define('users', {
        id: 1,
        name: 'Tony',
        email: 'test1@gmail.com',
        uid: '12345'
    })
});

//mock for model that's associated to my users model
jest.mock('../models/user_prefs', () =&gt; {
    const SequelizeMock = require('sequelize-mock');
    const dbMock = new SequelizeMock();
    return dbMock.define('user_prefs', {
        id: 1,
        uid: '12345',
        notification_settings: {}
    })
});

//the actual test
describe('getUserByID', () =&gt; {
    it('should get user from mock', () =&gt; {
        var req = httpMocks.createRequest({
            params: {
                id: 1
            }
        });

        var res = httpMocks.createResponse();

        controller.getUserByID(req, res).then(function(user) {
            expect(user.name).toEqual('Steve');
        })
    });
});
</code></pre>
<p><strong>package.json</strong></p>
<pre><code>&quot;scripts&quot;: {
    &quot;test&quot;: &quot;jest --config ./jest.config.js --forceExit --coverage&quot;
}
</code></pre>
<p><strong>jest.config.js</strong></p>
<pre><code>module.exports = {
    testEnvironment: &quot;node&quot;
}
</code></pre>
<p>When I run <code>npm test</code> everything runs just fine, but it tells me that the test passes, even though it obviously shouldn't if it was correctly retrieving the data from the mock, and I can't really figure out why.</p>
",https://stackoverflow.com/questions/68443158/unit-testing-with-jest-and-sequelize-test-passing-when-it-shouldnt,"['node.js', 'unit-testing', 'jestjs', 'sequelize.js']",1435,False,0,0
Mocking a return value for a Subject - Unit Testing with Jasmine,"<p>I'm unit testing and part of the testing has a Subject. I'm new to Subjects and get the general gist of how they work but am struggling to mock a return value on one. I've tried various ways in the hopes of stumbling on the correct way like using a spy and returnvalue to return the number 3.</p>
<p>In the component:</p>
<pre><code>.... 
private searchEvent: Subject&lt;string&gt; = new Subject&lt;string&gt;();

....
      this.searchEvent.pipe(debounceTime(500)).subscribe(value =&gt; {
        if (value.length &gt;= 3) {
          this.retrieveAssets(value);
        }
      })
....
</code></pre>
<p>In my spec file I basically have:</p>
<pre><code>        component['searchStockEvent'].subscribe(x=&gt; of(3));

        fixture.whenStable().then(() =&gt; {
          expect(component['retrieveAssets']).toHaveBeenCalled();
        });
</code></pre>
",https://stackoverflow.com/questions/68682463/mocking-a-return-value-for-a-subject-unit-testing-with-jasmine,"['testing', 'mocking', 'jasmine', 'subject']",765,True,0,1
"Lit Element, unit testing - Nested Elements - Child element does not render","<p>I am very new to lit-element and unit testing and am not sure if the question is even framed correctly. Please correct me if I am wrong anywhere.</p>
<p>So, I have 1 lit component created such that it fetches the json from the uri
<code>&lt;abc infoJsonLink=&quot;../data/data.json&quot;&gt;&lt;/abc&gt;</code></p>
<p>data.json</p>
<pre><code>[
 {&quot;id&quot;:1, &quot;name&quot;:&quot;one&quot;, &quot;img&quot;:&quot;one.jpg&quot;},
{&quot;id&quot;:1, &quot;name&quot;:&quot;two&quot;, &quot;img&quot;:&quot;two.jpg&quot;}, 
...]
</code></pre>
<p>Within abc's render() method, we loop through the json data and create a array with html markup corresponding to each item, <code>itemsMarkupList</code></p>
<pre><code> *0* &lt;div &quot;item-data&quot;&gt;&lt;span&gt;one&lt;/span&gt;&lt;img src=&quot;one.jpg&quot;/&gt;&lt;/div&gt; 
 *1* &lt;div &quot;item-data&quot;&gt;&lt;span&gt;two&lt;/span&gt;&lt;img src=&quot;two.jpg&quot;/&gt;&lt;/div&gt;  
 *2* ...
</code></pre>
<p>Each one of these markups, has to be rendered in a bootstrap carousel. <a href=""https://mdbootstrap.com/snippets/jquery/ascensus/135508"" rel=""nofollow noreferrer"">https://mdbootstrap.com/snippets/jquery/ascensus/135508</a></p>
<p>For this we have created another component, <code>&lt;carousel-helper&gt;</code>, which has the code to accept an array of markups and render it as a carousel using bootstrap libraries.</p>
<p>Below is the <code>render()</code> method of <code>&lt;abc&gt;</code> component</p>
<pre><code>render(){... 
let ch = document.createElement(&quot;carousel-helper&quot;); 
ch.itemsMarkupList = this.itemsMarkupList;
return html`... &lt;div class=&quot;parent_wrapper&quot;&gt; ${ch} &lt;/div&gt;`;
}
</code></pre>
<p>This whole renders perfectly when I <code>npm run</code> it.</p>
<p>But when I am writing the test cases for this,  the shadowroot of child elements seems to be not rendering.</p>
<pre><code>  it(&quot;test1&quot;, async () =&gt; {
   const el = /** @type {Abc} */ (await fixture(
    html`&lt;abc infoJsonLink=&quot;/data/data.json&quot;&gt;&lt;/abc&gt;
    `));

  await el.loadJsonData();

  /*statement 1*/
  console.log(el.shadowRoot.querySelector(&quot;carousel-helper&quot;)); 

  /*statement 2*/
  console.log(el.shadowRoot.querySelector(&quot;carousel-helper&quot;).
    shadowRoot.querySelectorAll(&quot;.item-data&quot;));

  }); 
</code></pre>
<p><em>statement-1</em> works and returns <code>&lt;carousel-helper&gt;&lt;/carousel-helper&gt; </code><br />
<em>statement-2</em> return and empty array, <code>NodeList {}</code></p>
<p>Can anyone tell me what I need to do to get a filled array from <em>statement-2</em>?</p>
",https://stackoverflow.com/questions/67979324/lit-element-unit-testing-nested-elements-child-element-does-not-render,"['unit-testing', 'web-component', 'web-testing', 'lit-element', 'react-testing']",913,False,0,0
React / Unit testing: TypeError: Cannot read properties of undefined (reading &#39;buttonGroup&#39;),"<p>Need help to undrstand why my test stop working.</p>
<p>Using React + Jest + React testing lib</p>
<p>this is test:</p>
<pre><code>  it('renders all buttons correctly', () =&gt; {
    render(&lt;ButtonGroup {...buttonGroupDefaultProps} /&gt;);

    expect(screen.getByText(/first/i)).toBeInTheDocument();
    expect(screen.getByText(/second/i)).toBeInTheDocument();
    expect(screen.getByText(/third/i)).toBeInTheDocument();
  });
</code></pre>
<p>This is the error:</p>
<pre><code>TypeError: Cannot read properties of undefined (reading 'buttonGroup')

  38 | describe('ButtonGroup tests', () =&gt; {
  39 |   it('renders all buttons correctly', () =&gt; {
&gt; 40 |     render(&lt;ButtonGroup {...buttonGroupDefaultProps} /&gt;);
     |     ^
  41 |
  42 |     expect(screen.getByText(/first/i)).toBeInTheDocument();
  43 |     expect(screen.getByText(/second/i)).toBeInTheDocument();

  at useCompo
</code></pre>
<p>Any comment is welcome</p>
",https://stackoverflow.com/questions/70495593/react-unit-testing-typeerror-cannot-read-properties-of-undefined-reading-b,"['reactjs', 'jestjs', 'react-testing-library']",751,False,0,0
How to handle methods that cannot be mocked during unit testing,"<p>I would like to know how we can handle methods that cannot be mocked while writing unit tests.</p>
<p>We have class called Students and it has a set of methods that are used to operate on the student data. And we also have some extensions methods(in C#) that are used for further processing. Now our business logic includes the use of methods of student class and extension methods.</p>
<p><strong>Example:</strong></p>
<pre class=""lang-cs prettyprint-override""><code>class Student
{
    // fields
    filter()
    check()
    ...
}
</code></pre>
<pre class=""lang-cs prettyprint-override""><code>BusinessLogic()
{
   // get list of students
   return students.Where(filter()).someExtensionMethod().FirstOrDefault().check();
}
</code></pre>
<p>Now if we want to test BusinessLogic method we cannot mock the methods filter(), check() and someExtensionMethod(). And if we go by regular approach we will setup test data such that we can test the output of each every methods and ensure that these methods are being called. It will be okay to do that if we have such 2 or 3 method calls. But I would like to know what to do in case when there many such method calls and the method involves complex logic which makes our test data setup more complex?</p>
<p><strong>Edit:</strong>
Here I am interested about functions that are defined in Student class. For example I have functions to check student has marks above 33. Like IsPass(). And I will call it like student.IsPass(). But the problem is in real project the number of such methods can be huge. And our business logic can be a combination of these methods</p>
",https://stackoverflow.com/questions/70447560/how-to-handle-methods-that-cannot-be-mocked-during-unit-testing,"['c#', 'unit-testing', 'mocking']",227,False,0,1
Unit Testing with Karma (Jasmine): dynamically called functions defined in Object,"<p>Trying to test dynamically caled functions, figurig out how to do this with a Spy. Suggestions are welcome.</p>
<p>I really want to emphasize that i am not looking for a Mock approach of the Object under test.</p>
<p>Currently implemented expectation doesnt work:</p>
<p><code>Expected spy dispatch to have been called with: [ &lt;jasmine.objectContaining(Object({ type: 'userEdit' }))&gt; ] but it was never called.</code></p>
<p>jumpTable</p>
<pre><code>public jumpTable: {} = {
  [ComponentState.USER_EDIT]: (componentState: ComponentState, userModel: IUserModel) =&gt; {
    this.store.dispatch({ type: USER_EDIT, payload: { userModel } });
  }
}
</code></pre>
<p>test</p>
<pre><code>  it(`should have jumpTable object with accoring keys`, () =&gt; {
    component.userModel = userIndy;
    fixture.detectChanges();

    // evaluates to true
    expect(component.jumpTable[ComponentState.USER_EDIT]).toBeDefined();

    // error &gt; USER_EDIT does not resolve
    // const jumpDispatchStoreSpy = spyOn(component.jumpTable, USER_EDIT).and.callThrough();

    component.jumpTable[ComponentState.USER_EDIT](ComponentState.USER_EDIT, component.userModel);

    const storeSpy = spyOn(component.store, 'dispatch').and.callThrough();
    const dispatchObject = { type: USER_EDIT };
    expect(storeSpy).toHaveBeenCalledWith(jasmine.objectContaining(dispatchObject));
  });
</code></pre>
",https://stackoverflow.com/questions/67062655/unit-testing-with-karma-jasmine-dynamically-called-functions-defined-in-objec,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'karma-runner']",338,True,0,1
Unit-testing: Mocking a subprocess running &quot;aws s3 sync&quot; with Python,"<p>My project needs to download quite a few files regularly before doing treatment on them.
I tried coding it directly in Python but it's horribly slow considering the amount of data in the buckets.</p>
<p>I decided to use a subprocess running <code>aws-cli</code> because <code>boto3</code> still doesn't have a sync functionality. I know using a subprocess with <code>aws-cli</code> is not ideal, but it really is useful and works extremely well out of the box.</p>
<p>One of the perks of <code>aws-cli</code> is the fact that I can see the progress in <code>stdout</code>, which I am getting with the following code:</p>
<pre><code>def download_bucket(bucket_url, dir_name, dest):
&quot;&quot;&quot;Download all the files from a bucket into a directory.&quot;&quot;&quot;
path = Path(dest) / dir_name
bucket_dest = str(os.path.join(bucket_url, dir_name))
with subprocess.Popen([&quot;aws&quot;, &quot;s3&quot;, &quot;sync&quot;, bucket_dest, path], stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) as p:
    for b in p.stdout:
        print(b, end='')

if p.returncode != 0:
    raise subprocess.CalledProcessError(p.returncode, p.args)
</code></pre>
<p>Now, I want to make sure that I test this function but I am blocked here because:</p>
<ol>
<li>I don't know the best way to test this kind of freakish behavior:
<ul>
<li>Am I supposed to actually create a fake local s3 bucket so that <code>aws s3 sync</code> can hit it?</li>
<li>Am I supposed to mock the subprocess call and not actually call my <code>download_bucket</code> function?</li>
</ul>
</li>
</ol>
<p>Until now, my attempt was to create a fake bucket and to pass it to my download_bucket function.
This way, I thought that <code>aws s3 sync</code> would still be working, albeit locally:</p>
<pre><code>def test_download_s3(tmpdir):
tmpdir.join(f'frankendir').ensure()
with mock_s3():
    conn = boto3.resource('s3', region_name='us-east-1')
    conn.create_bucket(Bucket='cool-bucket.us-east-1.dev.000000000000')

    s3 = boto3.client('s3', region_name=&quot;us-east-1&quot;)
    s3.put_object(Bucket='cool-bucket.us-east-1.dev.000000000000', Key='frankendir', Body='has no files')

    body = conn.Object('cool-bucket.us-east-1.dev.000000000000', 'frankendir').get()[
        'Body'].read().decode(&quot;utf-8&quot;)

    download_bucket('s3://cool-bucket.us-east-1.dev.000000000000', 'frankendir', tmpdir)

    #assert tmpdir.join('frankendir').join('has not files').exists()
    assert body == 'has no files'
</code></pre>
<p>But I get the following error <code>fatal error: An error occurred (InvalidAccessKeyId) when calling the ListObjects operation: The AWS Access Key Id you  provided does not exist in our records.</code></p>
<p>My questions are the following:</p>
<ol>
<li>Should I continue to pursue this creation of a fake local s3 bucket?
<ul>
<li>If so, how am I supposed to get the credentials to work?</li>
</ul>
</li>
<li>Should I just mock the subprocess call and how?
<ul>
<li>I am having a hard time understanding how mocking works and how it's supposed to be done. From my understanding, I would just fake a call to <code>aws s3 sync</code> and return some files?</li>
</ul>
</li>
<li>Is there another kind of unit test that would be enough that I didn't think of?
<ul>
<li>After all, I just want to know if when I transmit a well-formed <code>s3://bucketurl</code>, a <code>dir</code> in that bucket and a <code>local dir</code>, the files contained within the <code>s3://bucketurl/dir</code> are downloaded to my <code>local dir</code>.</li>
</ul>
</li>
</ol>
<p>Thank you for your help, I hope that I am not all over the place.</p>
",https://stackoverflow.com/questions/69651356/unit-testing-mocking-a-subprocess-running-aws-s3-sync-with-python,"['python', 'unit-testing', 'amazon-s3', 'mocking', 'subprocess']",513,False,0,1
File imports from different relative paths when unit testing in python,"<p>When I include <code>__init__.py</code> throughout my project, my unit tests can find everything that my main program can, so long as I do all imports relative to the project root.  But this doesn't work for files that get loaded.  I'm trying to write tests for code that includes imports of yaml files throughout the code.</p>
<p>This question is a follow-on, but distinct from <a href=""https://stackoverflow.com/questions/69914758/chained-imports-for-unit-tests-in-python"">this question</a> that I recently asked, which was answered in the comments.</p>
<p>Here's my project structure:</p>
<p><a href=""https://i.stack.imgur.com/V6w3O.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/V6w3O.png"" alt=""enter image description here"" /></a></p>
<p>Here's util1:</p>
<pre><code>def add(x, y):
    return x + y


if __name__ == &quot;__main__&quot;:
    pass
</code></pre>
<p>Here's util2:</p>
<pre><code>from Scripts.Project.util1 import add
import yaml


def add_then_string(x, y):
    z = add(x, y)
    with open(&quot;file.yml&quot;) as f:
        word = yaml.safe_load(f)['A']
    return str(z) + word


if __name__ == &quot;__main__&quot;:
    print(add_then_string(2, 3))
</code></pre>
<p>And here's the test file:</p>
<pre><code>import unittest


class TestProject(unittest.TestCase):
    def test_dummy(self):
        self.assertTrue(True)

    def test_add(self):
        from Scripts.Project.util1 import add
        self.assertEqual(add(1,1), 2)

def test_add_then_string(self):
    from Scripts.Project.util2 import add_then_string
    self.assertEqual(add_then_string(1,1), &quot;2hello&quot;)


if __name__ == &quot;__main__&quot;:
    unittest.main()
</code></pre>
<p>The problem is that <code>util2</code> looks for <code>file.yml</code> in a different place than the tests look for it.</p>
<p>Here's the error when I run the tests:</p>
<pre><code>Error
Traceback (most recent call last):
  File &quot;C:\Users\Andrew_Cranedroesch\projects\dummy_test_project\UnitTests\test_project.py&quot;, line 14, in test_add_then_string
    self.assertEqual(add_then_string(1,1), &quot;2hello&quot;)
  File &quot;C:\Users\Andrew_Cranedroesch\projects\dummy_test_project\Scripts\Project\util2.py&quot;, line 7, in add_then_string
    with open(&quot;file.yml&quot;) as f:
FileNotFoundError: [Errno 2] No such file or directory: 'file.yml'
</code></pre>
<p>How do I make this work so that I can test a function that imports a file from a path?</p>
",https://stackoverflow.com/questions/69915364/file-imports-from-different-relative-paths-when-unit-testing-in-python,"['python', 'unit-testing', 'python-import']",327,False,0,0
Flutter ObjectBox Unit Testing - Failed to load dynamic library &#39;lib/objectbox.dll&#39;,"<p>I'm building my new Flutter app with objectBox as DB.</p>
<p>When I write a unittest that includes objectBox, at running the test I get following error message:</p>
<blockquote>
<p>Failed to load &quot;C:\Dev\flutter_rebuild\test\db_model_test.dart&quot;: Invalid argument(s): Failed to load dynamic library 'lib/objectbox.dll': 126</p>
</blockquote>
",https://stackoverflow.com/questions/69631115/flutter-objectbox-unit-testing-failed-to-load-dynamic-library-lib-objectbox-d,"['flutter', 'unit-testing', 'objectbox', 'flutter-objectbox']",961,True,0,1
Unit testing object instantiation static call to a third party library,"<p>Is there a way to control the static call to getInstance method of a third party library using mockito.
For ex :</p>
<pre><code>public static ThirdPartyLibraryFactory createInstance() {
     
        return ThirdPartyLibrary.getInstance(
                param1, param2
        );
}
</code></pre>
<p>Considering i cannot use powermockito or anything that helps testing static calls
Also, consider those param1 to be some credentials and thirdpartylibrary will return a successful object if credentials are authentic. otherwise it will throw an error. And there is no way i can get the real credentials while testing due to complexity of the code. I would like to somehow intercept that call and return my dummy object.</p>
",https://stackoverflow.com/questions/69473440/unit-testing-object-instantiation-static-call-to-a-third-party-library,"['java', 'unit-testing', 'mockito']",17,False,0,0
Could not load file or assembly after working on Unit Testing,"<p>I've been working on a project for a month now. I have even run the project this morning. I added a new Unit Test class to the test for the application. I was working on getting my test running along with a [TestInitialize] method and a [TestCleanup] method.</p>
<p>Now for some reason I am getting the following error on my project (not the test project):</p>
<blockquote>
<p>Could not load file or assembly 'SolidWorks.Interop.swconst,
Version=28.1.0.74, Culture=neutral, PublicKeyToken=19f43e188e4269d8'
or one of its dependencies. The system cannot find the file
specified.    DispensingAddIn C:\Users\erics\source\repos\TestingEFClassLibrary\TestingEFClassLibrary\RegAsm</p>
</blockquote>
<p>My Unit Test looks like this:</p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using SolidWorks.Interop.sldworks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Dispensing.Classes.Utilities;
using SolidWorks.Interop.swconst;

namespace TestEntityDB
{
    /// &lt;summary&gt;
    ///     Summary description for SolidworksFeatureTreeTests
    /// &lt;/summary&gt;
    [TestClass]
    public class SolidworksFeatureTreeTests
    {
        public ISldWorks _swApp;

        [TestInitialize]
        public void StartTestEnvironment()
        {
            _swApp = new SldWorks();
            var errors = 0;
            var warnings = 0;
            _swApp.OpenDoc6(@&quot;C:\Users\erics\Desktop\Part1.SLDPRT&quot;, 1, 1, &quot;Default&quot;, ref errors, ref warnings);
        }

        [TestCleanup]
        public void CleanUpTestEnvironment()
        {
            _swApp.CloseAllDocuments(true);
            _swApp.ExitApp();
        }


        [TestMethod]
        public void TestMethod1()
        {
            var tree = new SwFeatureTree();
            tree.FeatureTreeConfiguration.ExclusionByNamesList.Add(&quot;(-) Sketch1&quot;);
            Assert.AreEqual(1, tree.FeatureTreeConfiguration.ExclusionByNamesList.Count);
            //tree.BuildTree(_swApp.ActiveDoc as IModelDoc2);
            //Assert.AreEqual(25, tree.TreeItems.Count);
        }
    }
}
</code></pre>
<p>By the way, Solidworks loads and runs just fine when run manually.</p>
<p>I have tried removing and readding the reference to SolidWorks.Interop.swconst in both the project and the testing project.</p>
<p>What could have happened here? How would I resolve this?</p>
",https://stackoverflow.com/questions/69711280/could-not-load-file-or-assembly-after-working-on-unit-testing,"['c#', 'reference']",149,False,0,1
How to access custom headers in controller constructor when unit testing,"<p>My problem is that I have a web api controller base class that I need to write tests for. I am having trouble doing this because my controller base class constructor needs to use the &quot;accessToken&quot; request header value, which is still NULL when the constructor goes off when the class is instantiated from the unit test as follows:</p>
<pre><code>HttpRequestMessage request = new HttpRequestMessage();
request.Headers.Add(&quot;accessToken&quot;, &quot;some token value&quot;);
BaseController controller = new BaseController()
 {
   Request = request,
   Configuration = new HttpConfiguration()
 };
</code></pre>
<p>Here is the code for BaseController:</p>
<pre><code>   public class BaseController : ApiController
    {
        public UserInformation CurrentUser { get; set; }
        readonly private IDatabase dataBase;

        public BaseController(IDatabase db = null) : base()
        {
            if (db == null)
                dataBase = new Database();
            else
                dataBase = db;
            ReadUserFromToken();
        }

        private void ReadUserFromToken()
        {
            // verify that the request contains an access token header
            if (Request.Headers.Contains(&quot;accessToken&quot;) == false)
                throw new AuthorizationException(&quot;Authorization token is missing&quot;);

            // get the request header containing the user information
            string loginToken = Request.Headers.GetValues(&quot;accessToken&quot;).FirstOrDefault();
            if (loginToken != null)
            {
                CurrentUser = new UserInformation();
                if (CurrentUser.LoadFromDatabaseByAccessToken(loginToken, dataBase) == false)
                {
                   throw new AuthorizationException(&quot;Authorization token is not valid&quot;);
                }
            }
        }
    }
</code></pre>
<p>Is there a different way to instantiate my class so that the request is populated before the constructor goes off? I really do not want to modify my class just so that I can test it because that breaks one of the golden rules of testing. My expectation is that when a controller that inherits from this base controller is instantiated, the &quot;CurrentUser&quot; property is automatically populated without the controller having to call a method to make it happen.</p>
<p>I understand that this could be implemented by lazy loading the property, but that would cause the authorization test to only happen if the property is used. I want the authorization test to happen every time the controller is instantiated regardless of whether or not the &quot;CurrentUser&quot; property is ever referenced.</p>
<p>Any suggestions or insights would be appreciated.</p>
",https://stackoverflow.com/questions/66251458/how-to-access-custom-headers-in-controller-constructor-when-unit-testing,"['c#', 'class', 'constructor', 'initialization']",343,False,0,0
Unit-Testing Angular service with RendererFactory2 and private Renderer2 without TestBed,"<p>I created a service to</p>
<ol>
<li>open modals</li>
<li>blur the background (as long as there is at least one open modal)</li>
</ol>
<p>The Servie looks like this:</p>
<pre class=""lang-js prettyprint-override""><code>@Injectable({
  providedIn: 'root',
})
export class ModalService {
  private readonly _renderer: Renderer2;
  // Overlaying hierarchy
  private _modalCount = 0;

  // Functional references
  private _viewContainerRef: ViewContainerRef;

  constructor(
    @Inject(DOCUMENT) private readonly _document: Document,
    private readonly _injector: Injector,
    private readonly _rendererFactory: RendererFactory2,
  ) {
    this._renderer = this._rendererFactory.createRenderer(null, null);
  }

  /**
   * Set the point where to insert the Modal in the DOM. This will generally be the
   * AppComponent.
   * @param viewContainerRef
   */
  public setViewContainerRef(viewContainerRef: ViewContainerRef): void {
    this._viewContainerRef = viewContainerRef;
  }

  /**
   * Adds a modal to the DOM (opens it) and returns a promise. the promise is resolved when the modal
   * is removed from the DOM (is closed)
   * @param componentFactory the modal component factory
   * @param data the data that should be passed to the modal
   */
  public open&lt;S, T&gt;(componentFactory: ComponentFactory&lt;AbstractModalComponent&lt;S, T&gt;&gt;, data?: S): Promise&lt;T&gt; {
    return new Promise(resolve =&gt; {
      const component = this._viewContainerRef.createComponent(componentFactory, null, this._injector);
      if (data) {
        component.instance.data = data;
      }
      const body = this._document.body as HTMLBodyElement;
      // we are adding a modal so we uppen the count by 1
      this._modalCount++;
      this._lockPage(body);
      component.instance.depth = this._modalCount;
      component.instance.close = (result: T) =&gt; {
        component.destroy();
        // we are removing a modal so we lessen the count by 1
        this._modalCount--;
        this._unlockPage(body);
        resolve(result);
      };
      component.changeDetectorRef.detectChanges();
    });
  }

  /**
   * Prevents the page behind modals from scrolling and blurs it.
   */
  private _lockPage(body: HTMLBodyElement): void {
    this._renderer.addClass(body, 'page-lock');
  }

  /**
   * Removes the `page-lock` class from the `body`
   * to enable the page behind modals to scroll again and be clearly visible.
   */
  private _unlockPage(body: HTMLBodyElement): void {
    // If at least one modal is still open the page needs to remain locked
    if (this._modalCount &gt; 0) {
      return;
    }
    this._renderer.removeClass(body, 'page-lock');
  }
}
</code></pre>
<p>Since Angular forbids to directly inject the Renderer2 as a dependency into services, I have to inject the RendererFactory2 and call <code>createRenderer</code> in the constructor.</p>
<p>Now I want to unit test the service and check whether the <code>_modalCount</code> is correctly incremented and then passed to every opened modal as <code>depth</code> input to manage their CSS <code>z-index</code>.</p>
<p>My unit test looks like this (I commented out some <code>expect</code>s to pin-point the problem:</p>
<pre class=""lang-js prettyprint-override""><code>describe('ModalService', () =&gt; {
  let modalService: ModalService;
  let injectorSpy;
  let rendererSpyFactory;
  let documentSpy;
  let viewContainerRefSpy;

  @Component({ selector: 'ww-modal', template: '' })
  class ModalStubComponent {
    instance = {
      data: {},
      depth: 1,
      close: _ =&gt; {
        return;
      },
    };
    changeDetectorRef = {
      detectChanges: () =&gt; {},
    };
    destroy = () =&gt; {};
  }

  const rendererStub = ({
    addClass: jasmine.createSpy('addClass'),
    removeClass: jasmine.createSpy('removeClass'),
  } as unknown) as Renderer2;

  beforeEach(() =&gt; {
    rendererSpyFactory = jasmine.createSpyObj('RendererFactory2', ['createRenderer']);
    viewContainerRefSpy = jasmine.createSpyObj('ViewContainerRef', ['createComponent']);
    documentSpy = {
      body: ({} as unknown) as HTMLBodyElement,
      querySelectorAll: () =&gt; [],
    };
    modalService = new ModalService(documentSpy, injectorSpy, rendererSpyFactory);
    rendererSpyFactory.createRenderer.and.returnValue(rendererStub);
    modalService.setViewContainerRef(viewContainerRefSpy);
  });

  it('#open should create a modal component each time and keep track of locking the page in the background', done =&gt; {
    function openModal(depth: number) {
      const stub = new ModalStubComponent();
      viewContainerRefSpy.createComponent.and.returnValue(stub);
      const currentModal = modalService.open(null, null);

      expect(viewContainerRefSpy.createComponent).toHaveBeenCalledWith(null, null, injectorSpy);
      expect(rendererSpyFactory.createRenderer).toHaveBeenCalledWith(null, null);
      // expect(stub.instance.depth).toBe(depth);
      // expect(rendererStub.addClass).toHaveBeenCalledWith(documentSpy.body, pageLockClass);

      return { currentModal, stub };
    }
    openModal(1); // Open first modal; `modalCount` has `0` as default, so first modal always gets counted as `1`
    const { currentModal, stub } = openModal(2); // Open second modal; `modalCount` should count up to `2`

    currentModal.then(_ =&gt; {
      // expect(rendererStub.removeClass).toHaveBeenCalledWith(documentSpy.body, pageLockClass);
      openModal(2); // If we close a modal, `modalCount` decreases by `1` and opening a new modal after that should return `2` again
      done();
    });
    stub.instance.close(null);
  });
});
</code></pre>
<p>As you see, I am not using Angulars <code>TestBed</code> as it adds more hidden functionalities.
Running the test throws</p>
<blockquote>
<p><code>Unhandled promise rejection: TypeError: Cannot read property 'addClass' of undefined</code></p>
</blockquote>
<p>So apparently, <code>_renderer</code> is not defined even though <code>createRenderer</code> has been called.
How can I solve this?</p>
",https://stackoverflow.com/questions/66225897/unit-testing-angular-service-with-rendererfactory2-and-private-renderer2-without,"['angular', 'unit-testing', 'jasmine']",823,True,0,1
Stencil unit testing: How to mock initial state and load newSpecPage?,"<p>I am new to unit testing and planning to write unit test cases but not E-2-E for the below mentioned scenario and playgrounnd link for scenario is at the bottom.</p>
<p><code>Scenario:-</code></p>
<p>I have a <code>@State</code> variable called <code>&quot;ifSuccessResponse&quot;</code> with initial value set as <code>false</code>.</p>
<p>When <code>@State</code> variable <code>&quot;ifSuccessResponse&quot;</code> is <code>true</code>, <code>green-div</code> loads.</p>
<p>When <code>@State</code> variable <code>&quot;ifSuccessResponse&quot;</code> is <code>false</code>, <code>red-div</code> loads.</p>
<ol>
<li>How to mock initial state to have <code>@State</code> variable <code>ifSuccessResponse</code> to have value set as <code>true</code> and then load the newSpecPage so that I can test <code>green-div</code> is loaded.</li>
</ol>
<ol start=""2"">
<li>Is it possible to update the <code>@State</code> variable <code>ifSuccessResponse</code> after loading the page in Moc Doc using <code>newSpecPage</code> . Curious to know whether we can do this like how we can do in <code>enzyme</code> library using <code>setState method</code>.</li>
</ol>
<p><code>Playground-link</code>:
<a href=""https://webcomponents.dev/edit/Cbr1NS2QTrvC5scsmFZQ/src/index.stories.tsx"" rel=""nofollow noreferrer"">https://webcomponents.dev/edit/Cbr1NS2QTrvC5scsmFZQ/src/index.stories.tsx</a></p>
",https://stackoverflow.com/questions/69979647/stencil-unit-testing-how-to-mock-initial-state-and-load-newspecpage,"['jestjs', 'stenciljs', 'stencil-component']",1277,True,0,2
Object Reference not set to instance of Object in Unit Testing,"<p>I want to Assert each property of my returned object which has been returned in my controller. Can someone help me with this?</p>
<p>My Controller:</p>
<pre><code>    [HttpGet(&quot;{id?}&quot;)] 
    public IActionResult GetById(string id)
    {
        var customerFromDb = this._custBizManager.GetByID(id);

        if (customerFromDb == null)
        {
            return base.NotFound(); // Status Code 404 - Not Found 
        }
        else
        {
            return Ok(customerFromDb); // Status Code 200 - OK 
        }
    } 
</code></pre>
<p>My Test Method:</p>
<pre><code>    [Test] 
    public void GetById_WithExistingCustomer_GetsCustomerById()
    {
        var expectedCustomer = CreatRandomCustomer();

        _customerRepoMock.Setup(x =&gt;x.GetByID(expectedCustomer.Id)).Returns(expectedCustomer);

        var result = _controller.GetById(expectedCustomer.Id);

        var response = (result as Customer);

        Assert.IsInstanceOf&lt;OkObjectResult&gt;(result);
        Assert.AreEqual(expectedCustomer.Id, response.Id); ----&gt; ?????? is this right?
    }
</code></pre>
",https://stackoverflow.com/questions/69352214/object-reference-not-set-to-instance-of-object-in-unit-testing,"['asp.net', 'unit-testing']",521,False,-1,1
How to call the subscribe error block in unit testing Angular?,"<p>i have tried unit testing in Angular subscribe, i write below testcase but its not 100% reach not accessin error block section</p>
<p>componant</p>
<pre><code>   this.Servive.methof(value).subscribe(res =&gt; {
   
    this.router.navigate('url');
  },
  error =&gt; {
    this.error= true;
  });
</code></pre>
<p>spec file</p>
<pre><code>   const spy = jest.spyOn(servive, 'method').mockReturnValue(of(appDataCreateResponse));
   component.dunction();
    expect(spy).Error(); 
    expect(component.apiError).toBeTruthy;
</code></pre>
",https://stackoverflow.com/questions/68282436/how-to-call-the-subscribe-error-block-in-unit-testing-angular,"['angular', 'jestjs', 'jasmine', 'karma-jasmine']",183,True,0,1
Is there a way to mock MassTransit IMediator for unit testing?,"<p>I'm using <a href=""https://masstransit-project.com/usage/mediator.html"" rel=""nofollow noreferrer"">MassTransit</a> Mediator in my project and I ran into a problem. Well, I would like to write unit tests for controller methods, but I don't know how to mock the IMediator object in the correct way to get me back the data from the GetResponse  method that I want to return.</p>
<p>I am using nunit and nsubstitute in the test project.</p>
<p>I tried to do it this way, but it doesn't give the desired results. In this case, the List is null.
IMediator object and controller initialization:</p>
<pre class=""lang-c# prettyprint-override""><code>private PotionsController _potionsController;
private IMediator _mediator;
</code></pre>
<pre class=""lang-c# prettyprint-override""><code>[SetUp]
public void SetUp() {
   _mediator = Substitute.For&lt;IMediator&gt;();
   _potionsController = new PotionsController(_potionsRepository, _mediator);
}
</code></pre>
<pre class=""lang-c# prettyprint-override""><code>[Test]
public async Task GetAllPotions_WhenCalled_ReturnsListOfPotions() {
   var requestClient = Substitute.For&lt;IRequestClient&lt;IGetPotionsQuery&gt;&gt;();
   var response = Substitute.For&lt;Response&lt;IGetPotionsResponse&gt;&gt;();
   response.Message.Potions.Returns(new List&lt;Potion&gt;() {
      new Potion(Guid.NewGuid(), &quot;Greater Arcane Protection Potion&quot;,
          &quot;Absorbs 1950 to 3250 arcane damage. Lasts 1 hour. (2 Min Cooldown)&quot;,
          &quot;Protection&quot;, 7.50m, 4),
      new Potion(Guid.NewGuid(), &quot;Greater Frost Protection Potion&quot;,
          &quot;Absorbs 1950 to 3250 frost damage. Lasts 1 hour.(2 Min Cooldown)&quot;,
          &quot;Protection&quot;, 7.50m, 4)
      });
   requestClient.GetResponse&lt;IGetPotionsResponse&gt;(Arg.Any&lt;IGetPotionsQuery&gt;. 
      ()).Returns(response);
   _mediator.CreateRequestClient&lt;IGetPotionsQuery&gt;().Returns(requestClient);

   var actionResult = await _potionsController.GetAllPotions();
   var okObjectResult = actionResult.Result as OkObjectResult;
   var potions = okObjectResult?.Value as List&lt;Potion&gt;;

   Assert.That(potions, Is.Not.Null);
   Assert.That(potions.Count, Is.EqualTo(2));
}
</code></pre>
<p>Is there any way to properly mock <code>GetResponse&lt;T&gt;</code>? If I use the IMediator object's <code>Send&lt;TRequest&gt;</code> method in the controller method, it is enough to check in the test whether this method was called with the appropriate parameters? An example of how to solve this would be great. Thank you in advance for any hints and help.</p>
",https://stackoverflow.com/questions/68182303/is-there-a-way-to-mock-masstransit-imediator-for-unit-testing,"['c#', 'unit-testing', '.net-5', 'masstransit', 'webapi']",446,False,0,0
How can I mock this code for unit testing using Moq?,"<p>I am trying to write unit test for below method but I am getting error as <code>this</code> object set to null reference in case of arguments <code>this.Request.Body</code> and <code>this.Request.Headers</code>. What will be the solution to mock <code>_azureDevopsTask.PublishToHandler(this.Request.Body, this.Request.Headers)</code>?</p>
<p>I am currently using Moq framework to write unit tests. Where <code>_azureDevopsTask</code> is the object of different class which is used here using dependency injection.</p>
<pre><code>[HttpPost]
public IActionResult Execute()
{
    try
    {
        _azureDevopsTask.PublishToHandler(this.Request.Body, this.Request.Headers);
        return CreateSuccessResponse(true);
    }
    catch (Exception ex)
    {
        return CreateErrorResponse(ex.Message);
    }
}
</code></pre>
",https://stackoverflow.com/questions/69025202/how-can-i-mock-this-code-for-unit-testing-using-moq,"['c#', 'unit-testing']",173,False,0,1
Unit testing with Angular: how to test changes on parent to child,"<p>I am unit testing a component in Angular, using Jasmine.
My test</p>
<pre class=""lang-js prettyprint-override""><code>it('contacts should be passed to child component', fakeAsync(() =&gt; {
    const newContact: Contact = {
        id: 1,
        name: 'Jason Pipemaker'
    };
    const contactsList: Array&lt;Contact&gt; = [newContact];
    contactsComponent.contacts = contactsList;//change on parent component
    tick()
    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; {
        expect(childComponents()[0].contacts).toEqual(contactsComponent.contacts);//want to check if changed on child also
    })
}));
</code></pre>
<p><strong>I want to test if a change in the parent will reflect on the child</strong>, like happens in a real scenario.</p>
<p>I have tested that the values are equal when everything starts, but I want to test the scenario when one changes the parent value, and that should automatically reflect on the child.</p>
<pre class=""lang-js prettyprint-override""><code>it('contacts should be the same', () =&gt; {
   expect(childComponents([0].contacts)
      .toEqual(contactsComponent.contacts);
});
</code></pre>
<p>Error:</p>
<blockquote>
<p>Expected $.length = 0 to equal 1.
Expected $[0] = undefined to equal Object({ id: 1, name: 'Jason Pipemaker' }).</p>
</blockquote>
<p><strong>My interpretation</strong>: it is not waiting for the update to test.</p>
<p>Maybe it is not even a unit test? Since I want to test the binding, maybe it is an integration test.</p>
<p><strong>Suggestions so far</strong></p>
<p><em>Suggestion 1</em>: I would try with <code>contactsComponent.contacts = JSON.parse(JSON.stringify(contactsList))</code></p>
<p>comments: Thanks, it does not work. See that I have already tested at the beginning: everything passes. The question would be. Why did it work at the beginning/launching but not after started? I guess this is a problem of somehow making sure everything finishes before testing: an async issue, not JSON.stringify. I have no idea how to make that in code terms! In simple terms: I am changing something on the parent, and want to make sure the child receives the change, like it happens on real scenarios. Thanks for your participation! 🤝👊💪
My HTML:</p>
<pre class=""lang-html prettyprint-override""><code>&lt;app-contact-list [contacts]=contacts&gt;&lt;/app-contact-list&gt;
</code></pre>
<p>PS. app-contact-list is the child:</p>
<pre class=""lang-js prettyprint-override""><code>export class ContactListComponent implements OnInit {
  .......
  @Input('contacts') contacts: Contact[];//the input for the component
</code></pre>
<p><em>Suggestion 2</em>: I think you should test the component individually.</p>
<p>Comments:
Regarding mocking the child, I am already mocking using ng-mock</p>
<pre class=""lang-js prettyprint-override""><code>beforeEach(async(() =&gt; {
   TestBed.configureTestingModule({
      declarations: [ContactsComponent, 
         MockComponent(ContactListComponent)],
   }).compileComponents();
}));
</code></pre>
<p>Drawback: it came to me as private lessons that some organizations do not allow installing those packages, thus, one should mock manually, as suggested.</p>
<p><em>Suggestion 3</em>: You can avoid it by leveraging the async/await syntax.</p>
<p><em>Comments</em>: tried, but did not work, same problem as before. it seems the code is executing before test. I face the same problem with Jest, learnt a trick, that that never happened before. I guess I am missing something like that, something that makes sure the test waits for the final modifications before testing.</p>
<p><strong>Codes</strong>: some suggested making the codes available.
Here it goes: <a href=""https://github.com/JorgeGuerraPires/testing-angular-applications/tree/master/website/src/app/contacts"" rel=""nofollow noreferrer"">https://github.com/JorgeGuerraPires/testing-angular-applications/tree/master/website/src/app/contacts</a></p>
<p>Maybe someone could make a StackBlitz as suggested!💪🤝👊</p>
<p><strong>Final solution</strong></p>
<p>In order to close this issue, I have decided to test in a simple case, as so the core idea under test would be the only concern. See the full simple application <a href=""https://github.com/JorgeGuerraPires/angulartypescript/tree/master/code-samples/Angular9/chapter8/inter-component/src/app/input"" rel=""nofollow noreferrer"">here</a> before testing. And see the final testing file <a href=""https://github.com/JorgeGuerraPires/angular-unit-testing/blob/main/order.componenent.spec.ts"" rel=""nofollow noreferrer"">here</a>.</p>
<p>I draw insights from both answers, and accepted the one that helped me the most, even the comments helped.</p>
<p>Thanks to everyone!</p>
",https://stackoverflow.com/questions/68330614/unit-testing-with-angular-how-to-test-changes-on-parent-to-child,"['angular', 'unit-testing', 'tdd', 'karma-jasmine']",3420,True,4,2
Unit testing for Drools rule when used with Kogito and spring boot,"<p>I am using <strong>Kogito</strong> service for bpmn flow (<strong>spring boot kogito starter</strong> is the maven dependency I have used) and as part of the flow have written several business rules using <strong>Drools</strong>. I have not been able to figure our unit test configuration to use if want to test just the rules independently.</p>
<p>e.g. If I try to create the KieServices in my test config, get the exception which I am not sure how to get past.</p>
<pre><code>KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem);
kieBuilder.buildAll();
</code></pre>
<p><em><strong>kieFIleSystem</strong></em> has the drl file reference.</p>
<p>Exception when executing above block from within Junit Test class:</p>
<pre><code>java.lang.RuntimeException: You're trying to compile a Drools asset without mvel. Please add the module org.drools:drools-mvel to your classpath.
                at org.drools.core.base.CoreComponentsBuilder.throwExceptionForMissingMvel(CoreComponentsBuilder.java:34)
                at org.drools.compiler.compiler.Dialect$DummyDialect.getBuilder(Dialect.java:216)
                at org.drools.compiler.rule.builder.PatternBuilder.processSource(PatternBuilder.java:348)
                at org.drools.compiler.rule.builder.PatternBuilder.build(PatternBuilder.java:166)
                at org.drools.compiler.rule.builder.PatternBuilder.build(PatternBuilder.java:134)
                at org.drools.compiler.rule.builder.PatternBuilder.build(PatternBuilder.java:116)
                at org.drools.compiler.rule.builder.GroupElementBuilder.build(GroupElementBuilder.java:66)
                at org.drools.compiler.rule.builder.RuleBuilder.build(RuleBuilder.java:106)
                at org.drools.compiler.builder.impl.KnowledgeBuilderImpl.internalAddRule(KnowledgeBuilderImpl.java:1186)
                at org.drools.compiler.builder.impl.KnowledgeBuilderImpl.addRule(KnowledgeBuilderImpl.java:1181)
                at org.drools.compiler.builder.impl.KnowledgeBuilderImpl.compileRulesLevel(KnowledgeBuilderImpl.java:1159)
                at org.drools.compiler.builder.impl.KnowledgeBuilderImpl.compileRules(KnowledgeBuilderImpl.java:1107)
                at org.drools.compiler.builder.impl.KnowledgeBuilderImpl.compileKnowledgePackages(KnowledgeBuilderImpl.java:925)
                at org.drools.compiler.builder.impl.KnowledgeBuilderImpl.buildRules(KnowledgeBuilderImpl.java:2477)
                at org.drools.compiler.builder.impl.KnowledgeBuilderImpl.buildPackages(KnowledgeBuilderImpl.java:2405)
                at org.drools.compiler.builder.impl.CompositeKnowledgeBuilderImpl.build(CompositeKnowledgeBuilderImpl.java:105)
                at org.drools.compiler.builder.impl.CompositeKnowledgeBuilderImpl.build(CompositeKnowledgeBuilderImpl.java:97)
                at org.drools.compiler.kie.builder.impl.AbstractKieProject.buildKnowledgePackages(AbstractKieProject.java:268)
                at org.drools.compiler.kie.builder.impl.AbstractKieProject.buildKnowledgePackages(AbstractKieProject.java:216)
                at org.drools.compiler.kie.builder.impl.AbstractKieProject.verify(AbstractKieProject.java:80)
                at org.drools.compiler.kie.builder.impl.KieBuilderImpl.buildKieProject(KieBuilderImpl.java:277)
                at org.drools.compiler.kie.builder.impl.KieBuilderImpl.buildAll(KieBuilderImpl.java:245)
                at org.drools.compiler.kie.builder.impl.KieBuilderImpl.buildAll(KieBuilderImpl.java:192)
                at com.anthem.systemy.codeset.RulesUtil.compile(RulesUtil.java:90)
                at com.anthem.systemy.codeset.RuleTest.test_drl(RuleTest.java:62)
                at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
                at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
                at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
                at java.lang.reflect.Method.invoke(Method.java:498)
                at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
                at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
                at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
                at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
                at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
                at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
                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:366)
                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$4.run(ParentRunner.java:331)
                at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
                at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
                at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
                at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
                at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
                at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
                at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
                at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
                at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
                at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
                at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
                at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
                at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:184)
                at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
                at java.util.Iterator.forEachRemaining(Iterator.java:116)
                at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
                at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
                at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
                at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:151)
                at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:174)
                at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
                at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:418)
                at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
                at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
                at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
                at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
                at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
                at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
                at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
                at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
                at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
                at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
                at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
                at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
                at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
 
</code></pre>
",https://stackoverflow.com/questions/66404781/unit-testing-for-drools-rule-when-used-with-kogito-and-spring-boot,"['spring-boot', 'kogito']",2118,True,2,2
How can I set a caller in ink! contract unit testing function?,"<pre><code>fn do_check(&amp;mut self) -&gt; Result&lt;()&gt; {
    let caller = self.env().caller();
    ...
}
</code></pre>
<p>I am writing a test function for <code>do_check</code> function. Here, I want to set a caller but not sure how to do that.</p>
<pre><code>#[cfg(test)]
mod tests {
    use super::*;
    use ink_lang as ink;

    #[ink::test]
    fn do_check_works() {
        let mut test = Test::new();
        // here I want to set a caller for calling do_check
        test.do_check();
        ...
</code></pre>
",https://stackoverflow.com/questions/69829061/how-can-i-set-a-caller-in-ink-contract-unit-testing-function,"['unit-testing', 'rust', 'substrate', 'rust-ink']",195,True,2,1
How to mock constructor injected @Value property in Spring Boot Unit Testing,"<p>I have a service as below with constructor dependency injection of a service and a configuration property.</p>
<pre><code>@Service
public class MyService {

    private OtherService service;

    private final SomeClass c;

    @Autowired
    public MyService(
        OtherService service,
        @Value(&quot;${app.some-property}&quot;) String someProperty) {

        this.service = service;
        final String key = service.getKey();
        SomeClient client = new SomeClient(key, someProperty);
        c = new SomeClass(client);
    }
}
</code></pre>
<p>How should we inject/mock value for property ${app.some-property} in unit test case using Mockito?</p>
",https://stackoverflow.com/questions/68403917/how-to-mock-constructor-injected-value-property-in-spring-boot-unit-testing,"['spring-boot', 'unit-testing', 'mockito']",1788,False,2,2
Test if a function is called in Unit Testing for Objective C,"<p>In the implementation file (.mm) I have a function that calls different APIs depending on the value of a boolean <code>isTrue</code> which is set in other APIs</p>
<pre><code>@implementation Controller

-(void) setProperty:(Id)Id value:(NSObject*)value
{
   if(value) {
      if(self.isTrue) {
         [self function1]
      } else {
         [self function2]
      }
   }
}
</code></pre>
<p>Now I need to write a test where for different values of isTrue, I need to test if the correct function is being called.</p>
<p>I wrote something like:</p>
<pre><code>-(void) testCaseforProperty
{
   _controller.isTrue = true;
   _controller setProperty:0 value:@YES];
  // I need to check if function1 is called here
}
</code></pre>
<p>Can anyone please tell me how to write a test here in place of the comment in order to test that function1 is called here either with OCMock or XCTest or any other way?</p>
",https://stackoverflow.com/questions/67282074/test-if-a-function-is-called-in-unit-testing-for-objective-c,"['objective-c', 'unit-testing', 'ocmock', 'xctestcase']",399,False,2,1
Uncaught TypeError: Cannot read property &#39;filter&#39; of undefined thrown Unit Testing Jasmine,"<p>I have this error in unit testing with jasmine:</p>
<p><strong>Uncaught TypeError: Cannot read property 'filter' of undefined thrown</strong></p>
<p>My function:</p>
<pre><code>info() {
  this.requestService.postRequest('Reports', 'getInfo', {})
   .subscribe(
    data =&gt; {
      this.places = data.places;
      this.types = data.types.filter(obj =&gt; obj.id != 20);
      this.loading = false;
    },
    error =&gt; {
      console.log(error);
      this.loading = false;
    });
  };
</code></pre>
<p>The test:</p>
<pre><code>it('When call requestService.postRequest', () =&gt; {
  
  spyOn(component.requestService, 'postRequest').and.returnValue(of({}));
  
  component.info();
  
  expect(component.requestService.postRequest).toHaveBeenCalled();
  expect(component.requestService.postRequest).toHaveBeenCalledTimes(1);
});
</code></pre>
",https://stackoverflow.com/questions/68036457/uncaught-typeerror-cannot-read-property-filter-of-undefined-thrown-unit-testi,"['javascript', 'typescript', 'karma-jasmine']",1516,True,2,1
"Angular unit testing. TypeError: Cannot read property &#39;id&#39; of null. [Jasmine, Karma]","<p>I am writing a component unit tests for my Angular application. I have a <code>currentUser</code> variable i am using in my component as well as html template. It is been mocked (hardcoded via <strong>component.currentUser = {...}</strong>) on every test. Anyway, Karma fails. Would appreciate any help.</p>
<pre><code>UserProfileComponent &gt; should create
TypeError: Cannot read property 'id' of null
    at UserProfileComponent.ngOnInit (http://localhost:9877/_karma_webpack_/webpack:/src/app/modules/user-profile/page/user-profile/user-profile.component.ts:4:21)
    at callHook (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2573:1)
    at callHooks (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2542:1)
    at executeInitAndCheckHooks (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:2493:1)
    at refreshView (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9481:1)
    at renderComponentOrTemplate (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9580:1)
    at tickRootContext (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10811:1)
    at detectChangesInRootView (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10836:1)
    at RootViewRef.detectChanges (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:22815:1)
    at ComponentFixture._tick (http://localhost:9877/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:141:1)
</code></pre>
<p>Code example below.<br></p>
<p><strong>user-profile.component.ts</strong></p>
<pre><code>ngOnInit(): void {
    this.currentUser = this.userService.getUser();
    console.log(this.currentUser.id);
    this.userAnnouncements();
  }
</code></pre>
<p><strong>user-profile.component.spec.ts</strong></p>
<pre><code>describe('UserProfileComponent', () =&gt; {
  let component: UserProfileComponent;
  let fixture: ComponentFixture&lt;UserProfileComponent&gt;;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule],
      declarations: [UserProfileComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    }).compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(UserProfileComponent);
    component = fixture.componentInstance;
    component.currentUser = {
      id: 1,
      email: 'admin@admin.com',
      firstname: 'admin',
      img_name: 'photo',
      lastname: 'admin',
      location: 1,
      password: 'hashed_pass',
      role: 'admin',
      username: 'admin',
    };
    fixture.detectChanges();
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
",https://stackoverflow.com/questions/67555930/angular-unit-testing-typeerror-cannot-read-property-id-of-null-jasmine-ka,"['javascript', 'angular', 'typescript', 'unit-testing', 'karma-jasmine']",12160,True,1,2
Unit Testing and Mocking SubscriberClient (Google Pub/Sub) in a C# Project,"<p>I'm using Google Cloud Pub/Sub (Google.Cloud.PubSub.V1 (2.2.0)) in a .NET Core 3.1 project.
I'm trying to write a unit test for the code that retrieves messages from a Google Pub/Sub subscription.
My code is similar to what you find in the Google documentation.</p>
<pre><code>var subscriber = await SubscriberClient.CreateAsync(subscriptionName);

try
{
    var startTask = subscriber.StartAsync(async (PubsubMessage message, CancellationToken cancel) =&gt;
    {
            //code
    });
    
    await Task.Delay(5000);
    await subscriber.StopAsync(CancellationToken.None);
    await startTask;
}
catch (Exception ex)
{
        //code
}
</code></pre>
<p>Is there a way to mock SubscriberClient in a unit test? SubscriberClient doesn't appear to have an interface.
My unit tests are using NUnit (3.12.0) and Moq (4.14.5).</p>
<p>Any ideas would be appreciated.</p>
",https://stackoverflow.com/questions/65582817/unit-testing-and-mocking-subscriberclient-google-pub-sub-in-a-c-project,"['c#', 'unit-testing', 'mocking', 'google-cloud-pubsub']",1487,False,1,1
How to use Chai and Mocha for Google Cloud functions unit testing,"<p>Having issue in writing simple unit test for Google Cloud Function using Chai, Mocha and Sinon although I am referring <a href=""https://cloud.google.com/functions/docs/testing/test-http"" rel=""nofollow noreferrer"">Google unit testing reference doc</a> but unable to understand it.</p>
<p><strong>Problems</strong></p>
<ul>
<li>I'm getting below error message while running unit test.</li>
</ul>
<pre><code>TypeError: response.status is not a function
</code></pre>
<ul>
<li>Why do I need to typecast Request and Response object while call function? In Google docs example (<a href=""https://github.com/GoogleCloudPlatform/nodejs-docs-samples/blob/e0ae58139eca50a578785624cc46dbc2e91e95c6/functions/helloworld/test/sample.unit.http.test.js#L35"" rel=""nofollow noreferrer"">Github</a>), they are not doing typecasting.</li>
</ul>
<pre><code>onCalculate(req as Request, res as unknown as Response);
</code></pre>
<p><strong>Objective:</strong>
Test should pass</p>
<p><strong>onCalculate.ts</strong></p>
<pre><code>import * as functions from &quot;firebase-functions&quot;;

export const onCalculate = functions.https.onRequest((request, response) =&gt; {
  const param1 = request.body.param1;
  const param2 = request.body.param2;
  response.status(200).send(calculate(param1 as number, param2 as number));
});

/**
 * Function to calculate two numbers
 * @param {number} param1
 * @param {number} param2
 * @return {number}
 */
function calculate(param1: number, param2: number): number {
  return param1 + param2;
}

</code></pre>
<p><strong>onCalculate.spec.ts</strong></p>
<pre><code>import firebase from &quot;firebase-functions-test&quot;;
import { Request, Response } from &quot;firebase-functions&quot;;
import { stub } from &quot;sinon&quot;;
import { assert } from &quot;chai&quot;;
import { onCalculate } from &quot;./onCalculate&quot;;

const test = firebase();

describe(&quot;Calculate&quot;, () =&gt; {
  after(() =&gt; {
    test.cleanup();
  });

  it(&quot;should return 3&quot;, () =&gt; {
    const req = {
      query: {},
      body: {
        param1: 1,
        param2: 2,
      },
    };

    const res = { send: stub() };

    onCalculate(req as Request, res as unknown as Response);

    assert.ok(res.send.calledOnce);
  });
});

</code></pre>
",https://stackoverflow.com/questions/70521083/how-to-use-chai-and-mocha-for-google-cloud-functions-unit-testing,"['node.js', 'unit-testing', 'google-cloud-functions', 'mocha.js', 'chai']",634,True,1,1
Unit Testing Nested Components UI elements in Angular using Jasmine and Karma,"<p><strong>pseudo-code of my parentComponent html:</strong></p>
<pre><code>&lt;mat-tab-group class=&quot;mat-elevation-z4&quot;&gt;
&lt;mat-tab label=&quot;OneBox&quot;&gt;
&lt;host-configuration [hostTemplate]=&quot;shareNodes&quot;&gt; 
&lt;/host-configuration&gt;
&lt;/mat-tab&gt;
&lt;/mat-tab-group&gt;
</code></pre>
<p>I am creating an instance of child component using it's selector(host-configuration) to create form fields where user can give the values.</p>
<p>Code in childComponent(host-configuration) which will create UI form fields</p>
<pre><code> @Input()
  set hostTemplate(value: HostTemplate) {
    this.loadedTemplate = value ?? new HostTemplate();

    this.templateNameConfigItem.formControl.setValue(value.TemplateName);
    this.vmStubNameConfigItem.formControl.setValue(value.VMStubName);
    this.virtualApplianceConfigItem.formControl.setValue(value.VirtualAppliance);

    this.cpuCountConfigItem.formControl.setValue(value.Sizing.cpu_count);
    this.numOfCoresPerSocketConfigItem.formControl.setValue(value.Sizing.num_cores_per_socket);
    this.ramInMBConfigItem.formControl.setValue(value.Sizing.ram_mb);

    if (value.VMs.length &gt; 0) {
      this.hostNameConfigItem.formControl.setValue(value.VMs[0]?.ComputerName);
      this.ipAddressConfigItem.formControl.setValue(value.VMs[0]?.Ip);
      this.macAddressConfigItem.formControl.setValue(value.VMs[0]?.Mac);
    }
    this.diskConfigurationItems.length = 0;
    for (const d of value.Disks) {
      this.diskConfigurationItems.push(new DiskConfigurationItems(d));
    }
  }
</code></pre>
<p>Now I want to test this particular UI form elements of child component (host-configuration) in parent component spec file?</p>
<p>Is there a way to do this , if yes could you please help me on how to do it ?</p>
",https://stackoverflow.com/questions/67815910/unit-testing-nested-components-ui-elements-in-angular-using-jasmine-and-karma,"['jasmine', 'karma-runner', 'angular-unit-test']",442,False,1,0
Spring Boot MockMVC returning empty body with statuscode 200 when unit testing,"<p>I'm trying to test my microservice endpoint Get Payees using MockMvc to perform the get request.
I've already set the behavior with mockito.when(), so whatever ID used in the request, it should return my response.</p>
<p><strong>I have this test:</strong></p>
<pre><code>@ControllerTest
@AutoConfigureMockMvc
public class PayeesApiControllerGetPayeesTest {

    private static final String ACCOUNTS_URI = &quot;/payees&quot;;
    
    @Autowired
    private MockMvc mvc;
    @Autowired
    private GetPayeesModule module;
    
    @Test
    public void testGetPayees() throws Exception {
        when(module.execute(
                anyString(),
                anyInt(),
                anyInt(),
                anyString(),
                anyString(),
                anyString(),
                anyString(),
                anyString(),
                anyString()))
                .thenReturn(
                        ResponseEntity.ok()
                                .header(X_V_HEADER, X_V_VERSION)
                                .header(X_FAPI_INTERACTION_ID_HEADER, UUID.randomUUID().toString())
                                .body(
                                        new ResponsePayee()
                                                .data(
                                                        new PayeeData()
                                                                .addPayeesItem(
                                                                        new PayeeDetails()
                                                                                .id(35L)
                                                                                .type(PayeeType.DOMESTIC)
                                                                                .fullName(&quot;Robert Doe&quot;)
                                                                                .description(&quot;My brother&quot;)
                                                                                .bsb(&quot;010-147&quot;)
                                                                                .accountNumber(&quot;123456789&quot;)))));
        
        mvc.perform(
                get(ACCOUNTS_URI)
                        .param(&quot;userId&quot;, &quot;1&quot;)
                        .accept(MediaType.APPLICATION_JSON)
                        .header(X_V_HEADER, X_V_VERSION)
                        .with(jwtWithAccountsBasicReadPermissionAndBankClientRole()))
                .andExpect(status().isOk())
                .andExpect(content().string(&quot;DOMESTIC&quot;));
    }
</code></pre>
<p><strong>And this is my Controller:</strong></p>
<pre><code>@Controller
@Validated
@RequiredArgsConstructor
public class PayeesApiController implements PayeesApiInterface {

  private final GetPayeesModule getPayeesModule;
  private final CreatePayeesModule createPayeesModule;

  @Override
  public ResponseEntity&lt;ResponsePayee&gt; getPayees(
      String userId,
      Integer page,
      Integer pageSize,
      String xRequestId,
      String xCorrelationContext,
      String xCorrelationId,
      String xFapiAuthDate,
      String xFapiCustomerIpAddress,
      String xCdsClientHeaders) {
    return getPayeesModule.execute(
        userId,
        page,
        pageSize,
        xRequestId,
        xCorrelationContext,
        xCorrelationId,
        xFapiAuthDate,
        xFapiCustomerIpAddress,
        xCdsClientHeaders);
  }
</code></pre>
<p><strong>@Controller annotation:</strong></p>
<pre><code>/**
 * Meta-annotation (annotation of annotations) to group Spring's annotations for testing web slice.
 */
@WebMvcTest()
@ActiveProfiles(&quot;test&quot;)
@Import(ControllerTestConfiguration.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface ControllerTest {}
</code></pre>
<p><strong>This is what my console shows:</strong></p>
<pre><code>2021-01-26 18:56:58.010  INFO 17428 --- [           main] c.m.s.o.HttpServletLogService            : REQUEST m:[GET], p:[/payees], q:[null], h:[{empty}], b:[{empty}]

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /payees
       Parameters = {userId=[1]}
          Headers = [Accept:&quot;application/json&quot;, x-v:&quot;1&quot;]
             Body = &lt;no character encoding set&gt;
    Session Attrs = {}

Handler:
             Type = com.marlo.payees.api.PayeesApiController
           Method = com.marlo.payees.api.PayeesApiController#getPayees(String, Integer, Integer, String, String, String, String, String, String)

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-Correlation-Id:&quot;f7d29ced-1ddc-4788-93fb-ba6655da412d&quot;, X-Content-Type-Options:&quot;nosniff&quot;, X-XSS-Protection:&quot;1; mode=block&quot;, Cache-Control:&quot;no-cache, no-store, max-age=0, must-revalidate&quot;, Pragma:&quot;no-cache&quot;, Expires:&quot;0&quot;, X-Frame-Options:&quot;DENY&quot;]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
</code></pre>
<p>------EDIT--------</p>
<p>Adding the ApiInterface example on how I use RequestMapping</p>
<pre><code>@RequestMapping(
      value = &quot;/payees&quot;,
      produces = {&quot;application/json&quot;},
      method = RequestMethod.GET)
  default ResponseEntity&lt;ResponsePayee&gt; getPayees
</code></pre>
<p>For some reason, I always get empty body even with 200 status code.
If you guys could help me... i would appreciate it.
Thanks in advance.</p>
",https://stackoverflow.com/questions/65909403/spring-boot-mockmvc-returning-empty-body-with-statuscode-200-when-unit-testing,"['java', 'spring-boot', 'unit-testing', 'controller', 'mockmvc']",1679,False,1,1
C# login failed when connecting to SQL Server database for unit testing,"<p>I'm working on a project and when attempting to run a unit test to check progress, I get an error:</p>
<blockquote>
<p>Initialization method UnitTestProject.UnitTest1.Init threw exception. System.Data.SqlClient.SqlException: Cannot open database &quot;database&quot; requested by the login. The login failed.<br />
Login failed for user 'User\User1'</p>
</blockquote>
<p>I've checked that <code>User1</code> is owner in SQL Server and think I have the connection string right but I must be missing something obvious, please let me know :)</p>
<p>My repository class:</p>
<pre><code>public class Repository
{
    private string _connectionString; 

    public Repository()
    {
        _connectionString = configurationManager.ConnectionStrings[&quot;database&quot;].ConnectionString;
    }

    public IEnumerable&lt;Person&gt; GetPeople()
    {
        var people = new List&lt;Person&gt;();

        using (SqlConnection connection = new SqlConnection(_connectionString))
        {
            string commandText = &quot;SELECT dbo.People.Id&quot;
                + &quot;, dbo.People.FirstName&quot;
                + &quot;, dbo.People.LastName&quot;
                + &quot;, dbo.People.Height&quot;
                + &quot;, dbo.People.Weight&quot;
                + &quot;FROM dbo.People&quot;;

            SqlCommand command = new SqlCommand(commandText, connection);

            try
            {
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    people.Add(new Person()
                    {
                        Id = reader.GetInt32(0),
                        FirstName = reader.GetString(1),
                        LastName = reader.GetString(2),
                        Height = reader.GetDouble(3),
                        Weight = reader.GetDouble(4)
                    });
                }
            }
            catch (Exception ex) 
            {
                Console.WriteLine(ex.Message);                
            }
        }
        return people; 
    }
}
</code></pre>
<p>My connection string in <code>App.config</code>:</p>
<pre><code>add name=&quot;database&quot; 
    connectionString=&quot;Data Source=localhost;Initial Catalog=database;Integrated Security=true&quot;
</code></pre>
<p>My unit test:</p>
<pre><code>public class UnitTest1
{
    private Repository _repo; 

    [TestInitialize]
    public void Init()
    {
        _repo = new Repository();
        _repo.ResetDatabase();
    }

    [TestMethod]
    public void GetPeople()
    {
        int count = _repo.GetPeople().Count();
        Assert.IsTrue(count &gt; 0);
    }
}
</code></pre>
",https://stackoverflow.com/questions/68125111/c-login-failed-when-connecting-to-sql-server-database-for-unit-testing,"['c#', 'sql-server', 'database-connection']",639,True,1,2
How do I create a mock context for grpc unit testing (python),"<p>In normal grpc communications, grpc automatically creates a context to go with the request.  How do I create a mock context to pass with my unit test call, so my servicing function has an object to manipulate?</p>
<p>Currently I have the code skip the context calls if it receives a NoneType as context, but that is not a good solution.</p>
",https://stackoverflow.com/questions/68365158/how-do-i-create-a-mock-context-for-grpc-unit-testing-python,"['python-3.x', 'pytest', 'grpc-python', 'pytest-mock']",1786,True,1,1
Vis-js Timeline error when unit testing click events with test-library,"<p>I'm having some issues with unit testing a react component that uses the vis-js timeline control. The error I'm getting is &quot;Cannot read property 'scale' of undefined&quot;, debugging the code the error happens because the timeaxis object is supposed to have a step property but that property only gets set when the timeaxis's redraw method is ran. I suspect that the issue is that the testing library generates the DOM with no height or width. I would have expected setting the timeaxis option to resolve this issue but that does not seem to be the case. Here is my test method.</p>
<pre><code>const defaultProps: GanttProps = {
    rowData: [],
    data: [],
    expanded: false,
    availabilityItems: [],
    dragLocked: false,
    isVisualizerForPrint: false,
    showNestedOverride: false,
    textItemsForDisplay: [&quot;Name&quot;],
    options: {
        start: moment(0).toDate(),
        end: moment(0).add(1, &quot;year&quot;).toDate(),
        timeAxis: {scale: 'day', step: 30}
    }
};

it(&quot;Should call handleClick&quot;, async () =&gt; {
        const handleClick = jest.fn();
        const props = {
            ...defaultProps,
            click: handleClick,
            data: mockData,
            rowData: mockRowData
        };
        
        render(&lt;Gantt { ...props } /&gt;);

        userEvent.click(screen.getByText(/Test Item/i));

        expect(handleClick).toHaveBeenCalledTimes(1);
    });
</code></pre>
<pre><code>import * as React from &quot;react&quot;;
import ReactDOM from &quot;react-dom&quot;;
import * as visTimeline from &quot;vis-timeline&quot;;
import * as typeDefs from &quot;./../common/typeDefs&quot;;
import moment from &quot;moment&quot;;
import &quot;vis-timeline/styles/vis-timeline-graph2d.min.css&quot;;

export type SchedTemplateFunc = (item: typeDefs.TaskItem, element: any) =&gt; any;

export type SubgroupStackingLookupBuilder = (items: typeDefs.GanttSubgroupData[]) 
    =&gt; { [subgroupId: string]: boolean };

const DefaultTimeZone = &quot;America/Edmonton&quot;;
const _timelineItemTypes = [&quot;background&quot;, &quot;box&quot;, &quot;point&quot;, &quot;range&quot;];
const MonthDragScale: visTimeline.TimelineOptions = 
    { timeAxis: { scale: &quot;month&quot; } };
const YearDragScale: visTimeline.TimelineOptions = 
    { timeAxis: { scale: &quot;year&quot; } };
const defaultOptions: visTimeline.TimelineOptions = {
    stack: false,
    stackSubgroups: true,
    minHeight: 200,
    editable: false,
    verticalScroll: true,
    zoomable: true,
    zoomMax: 253206145314,
    zoomMin: 80927257,
    zoomKey: &quot;ctrlKey&quot;,
    moveable: true,
    orientation: &quot;top&quot;,
    margin: {
        item: { horizontal: 0, vertical: 0 }
    },
    timeAxis: { scale: &quot;day&quot; }
};

type GanttProps = {
    data?: typeDefs.TaskItem[] | null;
    rowData?: typeDefs.GanttRowData[] | null;
    subGroups?: typeDefs.GanttSubgroupData[] | null;
    availabilityItems?: typeDefs.AvailabilityItem[] | null;
    parentSelector?: string;
    dragDirection?: string;
    dragLocked?: boolean;
    expanded?: boolean;
    isVisualizerForPrint?: boolean;
    showNestedOverride?: boolean;
    timescaleSelector?: string | null;
    textItemsForDisplay?: string[];
    timezone?: string | undefined;
    options?: visTimeline.TimelineOptions | undefined;
    timelineRange?: typeDefs.Range | undefined;
    click?: (event: string, properties: any) =&gt; void;
    doubleClick?: (event: React.MouseEvent&lt;HTMLElement&gt;) =&gt; void;
    changed?: () =&gt; void;
    select?: (items: visTimeline.IdType[], event?: any) =&gt; void;
    rangeChange?: (properties?: typeDefs.RangeProperties) =&gt; void;
    rangeChanged?: (properties?: typeDefs.RangeProperties) =&gt; void;
    subgroupStackingLookup?: SubgroupStackingLookupBuilder;
    focusedItem? : string;
};

const Gantt = (props: GanttProps) =&gt; {
    const [loaded, setLoaded] = React.useState(false);
    const [items, setItems] = React.useState&lt;visTimeline.DataItemCollectionType&gt;([]);
    const [groups, setGroups] = React.useState&lt;visTimeline.DataGroupCollectionType&gt;([]);
    const [range, setRange] = React.useState&lt;typeDefs.Range&gt;()

    let timeline: visTimeline.Timeline | undefined = undefined;
    let timelineNode: HTMLDivElement | null = null;
    let invisibleInput: HTMLInputElement | null = null;
    let hideColumnsTimer: number = 0;

    const timelineRef = React.useRef&lt;visTimeline.Timeline | undefined&gt;(timeline);

    const deferredLoad = _.debounce(() =&gt; setLoaded(true), 200);

    const createTimeline = (): void =&gt; {
        if (timelineNode &amp;&amp; !timelineRef.current) {
            let tlOptions = {
                ...defaultOptions,
                ...props.options,
                autoResize: true,
                moveable: !props.dragLocked
            };

            if (tlOptions.height === undefined) {
                delete tlOptions.height;
            }

            if (tlOptions.maxHeight === undefined) {
                delete tlOptions.maxHeight;
            }

            timeline = new visTimeline.Timeline(
                timelineNode,
                items ?? [],
                groups,
                tlOptions
            );

            timelineRef.current = timeline;

            timelineRef.current.on(&quot;doubleClick&quot;, doubleClickHandler);
            timelineRef.current.on(&quot;changed&quot;, changedHandler);
            timelineRef.current.on(&quot;select&quot;, selectHandler);
            timelineRef.current.on(&quot;rangechanged&quot;, rangeChangedHandler);
            timelineRef.current.on(&quot;rangechange&quot;, rangeChangeHandler);

            timelineRef.current.on(&quot;mouseDown&quot;, mouseDownHandler);
            timelineRef.current.on(&quot;mouseUp&quot;, mouseUpHandler);
            timelineRef.current.on(&quot;click&quot;, (properties) =&gt; {
                clickHandler(&quot;click&quot;, properties);
            });
        } else if (!loaded) {
            deferredLoad();
        }
    }

    /* Start Event Handlers */
    const doubleClickHandler = (event: React.MouseEvent&lt;HTMLElement&gt;): void =&gt; {
        ...
    }

    const clickHandler = (event: string, properties: any): void =&gt; {
        ...
    }

    const changedHandler = (): void =&gt; {
        ...
    };

    const rangeChangedHandler = (properties?: typeDefs.RangeProperties): void =&gt; {
        ...
    };

    const rangeChangeHandler = (properties?: typeDefs.RangeProperties): void =&gt; {
        ...
    }

    // vanishes the columns on drag so that they don't make dragging choppy
    const mouseDownHandler = (event: visTimeline.TimelineEventPropertiesResult )
        : boolean =&gt; 
    {
        ...
    }

    const mouseUpHandler = () : boolean =&gt; {
        ...
    }

    const selectHandler = (params: typeDefs.SelectionEventInfo): void =&gt; {
        ...
    }

    /* End Event Handlers */

    /**
     * Update the timeline scale options based on current scale.
     * Timeline scale is being switched to auto when the zoom reaches a level where days labels can fit and will revert back to day when zoomed out above that scale level.
     * @returns Void
     */
    const updateOptions = (prevOptions?: visTimeline.TimelineOptions): void =&gt; {
        if (!timelineRef.current) {
            return;
        }

        let options: visTimeline.TimelineOptions | null = null;

        if (calcScale &gt; 0) {
            options = {
                showMinorLabels: true
                
            };
        }

        if (prevOptions &amp;&amp; prevOptions!.multiselect !== props.options!.multiselect) {
            options = { ...options, multiselect: props.options!.multiselect };
        }

        if (options) {
            timelineRef.current.setOptions(options);
        }
    }

    // ---------- start effect hooks
    React.useEffect(() =&gt; {
        createTimeline();

        if(props.timescaleSelector) {
            createTimescale();
        }

        // find the nearest focusable grid target in the parent element
        if (timelineNode) {
            const parent = timelineNode.parentElement;
            if (parent !== null) {
                const grandparent = parent.parentElement;
                if (grandparent !== null) {
                    invisibleInput = grandparent.querySelector(
                        `.form-control[type=&quot;text&quot;]`
                    );
                }
            }
        }

        return () =&gt; {
            if (timelineRef.current) {
                timelineRef.current.destroy();
            }
        }
    }, []);

    React.useEffect(() =&gt; {
        setItems(() =&gt; [...]);
   }, [props.data]);

    React.useEffect(() =&gt; {
        setGroups([...]);
    }, [props.rowData]);

    React.useEffect(() =&gt; {
        removeResizeLeftDiv();

        if(timelineRef.current)
            timelineRef.current.setItems(items);
    }, [items]);

    React.useEffect(() =&gt; {
        removeResizeLeftDiv();
        
        if(timelineRef.current)
            timelineRef.current.setData({
                groups: groups,
                items: items
            });
    }, [groups]);

    React.useEffect(() =&gt; {
        if(!range) {
            return;
        }

        if (
            timelineRef.current &amp;&amp; props.options &amp;&amp;
            props.options.maxHeight
        ) {
            timelineRef.current.setOptions({
                maxHeight: props.options!.maxHeight
            });
        }
        updateOptions();

        if(range?.start &amp;&amp; range?.end)
        {
            if(timelineRef.current)
                timelineRef.current.setWindow(
                    range.start, 
                    range.end,
                    {
                        animation: true
                    });
        }

    }, [range]);

    React.useEffect(() =&gt; {
        if(props?.timelineRange)
        {
            setRange(props.timelineRange);
        }
    },[props.timelineRange])

    React.useEffect(() =&gt; {

        if(props.focusedItem &amp;&amp; timelineRef.current)
        {
            timelineRef.current.focus(props.focusedItem,{animation: false, zoom: false});
        }
    }, [props.focusedItem])

    // ---------- end effect hooks

    return (
        &lt;div ref={el =&gt; (timelineNode = el)} /&gt;
    );
}

export default Gantt; export type { GanttProps };
</code></pre>
",https://stackoverflow.com/questions/67112988/vis-js-timeline-error-when-unit-testing-click-events-with-test-library,"['javascript', 'react-testing-library', 'vis.js']",422,False,1,0
facing issue in method channel internet connectivity in unit testing in flutter,"<p>I have checked internet connectivity in flutter while calling api in store class like this using 'connectivity' library.</p>
<pre><code>    Future&lt;bool&gt; callApi() async {

    final isInternet = await Util.checkInternetAndShowDialog(context);

    if (isInternet) {

      final future = _repository.callApi();

      var res = await future;

      return true;

    }

return false;

    }
</code></pre>
<p>In Util class network connectivity is been checked like this::</p>
<pre><code>class Util {

  static Future&lt;bool&gt; checkInternetAndShowDialog(BuildContext context) async{
    var internet = await NetworkConnectivity.rechability();
    if (internet == false) {
      AlertMessage().showAlertDialog(context, 'error message');
    }
    return internet;
  }

}
</code></pre>
<p>In NetworkConnectivity class network connectivity is been checked using Connectivity library.</p>
<pre><code>class NetworkConnectivity {

static Future&lt;bool&gt; rechability() async {

    var connectivityResult = await (Connectivity().checkConnectivity());

    if (connectivityResult == ConnectivityResult.mobile) {

      return true;

    } else if (connectivityResult == ConnectivityResult.wifi) {

      return true;

    }

    return false;

  }

}
</code></pre>
<p>my test cases code is like below:</p>
<pre><code>test('call api successfully', () async {

      when(mockStore.callApi()).thenAnswer((realInvocation) =&gt; Future.value());
      expect(await store.callApi(), true);
    });
</code></pre>
<p>so while writing unit testing I am facing error of connectivity and method channel.
<a href=""https://i.stack.imgur.com/1wEjN.png"" rel=""nofollow noreferrer"">connectivity error image</a></p>
<p>Can any one help please me how I can mock for internet connectivity in unit testing and pass the test in flutter. I shall be thankful for this.</p>
",https://stackoverflow.com/questions/68659780/facing-issue-in-method-channel-internet-connectivity-in-unit-testing-in-flutter,"['flutter', 'dart', 'flutter-test', 'connectivity']",303,False,1,0
Check created queries with Entity Manager when unit testing in Spring Boot,"<p>I'm currently building an API using springboot. In my service layer, I used entity manager to create queries. As an example,</p>
<pre><code>public Object editFeedback(Long user_id, Long reservation_id, String feedback){
    String s = &quot;select r from  Reservation  r left join fetch r.driverAssignment where r.id=:id and r.reservation_done_by.id=:user_id &quot;;
    List&lt;Reservation&gt; reservations = em.createQuery(s).setParameter(&quot;id&quot;, reservation_id).setParameter(&quot;user_id&quot;, user_id).getResultList();
    if (reservations.size() == 0)
        return new DefaultResponseDTO(201, ResponseStatus.INVALID_INPUTS, &quot;Wrong reservation id&quot;);
    Reservation reservation = reservations.get(0);
    reservation.setFeedback(feedback);
    reservationRepository.save(reservation);
    return new DefaultResponseDTO(200, ResponseStatus.OK, &quot;Successfully done&quot;);

}
</code></pre>
<p>My question is when writing unit tests for methods in the service layer, how can I check those queries are working correctly without affecting or fetching data from the original database?</p>
<p>For additional details, If I get data from the original database to check the query, then the output changes from time to time. So, I have to mock the Entity manager. Then the queries don't get checked.</p>
<pre><code>  Query query = Mockito.mock(Query.class);
  Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query);
  Mockito.when(query.getResultList()).thenReturn(sampleReservations.getReservationsForUserReservations());
</code></pre>
<p>Is there any proper way to check that queries are working fine using a mocked entity manager? or If I have understood unit testing wrongly or any other suggestions?</p>
",https://stackoverflow.com/questions/69395276/check-created-queries-with-entity-manager-when-unit-testing-in-spring-boot,"['java', 'spring-boot', 'unit-testing', 'mocking', 'entitymanager']",615,True,1,1
Error in unit testing Svelte app within Nx Workspace project using Jest,"<p>I created an empty NxWorkspace, and then added a svelte project following the steps <a href=""https://github.com/nxext/nx-extensions/tree/main/packages/svelte#project-schematics"" rel=""nofollow noreferrer"">here</a>. I added the component and its spec file using the command <code>nx g @nxext/svelte:c my-comp</code>. Until this point the tests run without any trouble, but after adding some TypeScript code to the MyComp.svelte file as below, the test stop working.</p>
<pre class=""lang-js prettyprint-override""><code>&lt;script lang=&quot;ts&quot;&gt;
  let temp: string;
&lt;/script&gt;

&lt;h1&gt;Hello component!&lt;/h1&gt;

&lt;h1&gt;
&lt;/h1&gt;
</code></pre>
<p>The test file my-comp.spec.ts</p>
<pre class=""lang-js prettyprint-override""><code>import MyComp from './MyComp.svelte';
import { render } from '@testing-library/svelte';

it('it works', async () =&gt; {
  const { getByText } = render(MyComp);

  expect(getByText('Hello component!'));
});

</code></pre>
<p>The error I receive is:</p>
<pre class=""lang-sh prettyprint-override""><code> FAIL   my-app  apps/my-app/src/components/my-comp/my-comp.spec.ts
  ● Test suite failed to run

    ParseError: Unexpected token

      at error (../../node_modules/svelte/src/compiler/utils/error.ts:25:16)
      at Parser$1.error (../../node_modules/svelte/src/compiler/parse/index.ts:100:3)
      at Parser$1.acorn_error (../../node_modules/svelte/src/compiler/parse/index.ts:93:8)
      at Object.read_script [as read] (../../node_modules/svelte/src/compiler/parse/read/script.ts:51:10)
      at tag (../../node_modules/svelte/src/compiler/parse/state/tag.ts:205:27)
      at new Parser$1 (../../node_modules/svelte/src/compiler/parse/index.ts:52:12)
      at parse (../../node_modules/svelte/src/compiler/parse/index.ts:216:17)
      at Object.compile (../../node_modules/svelte/src/compiler/compile/index.ts:91:14)
      at Object.process (../../node_modules/svelte-jester/src/transformer.js:21:25)
      at ScriptTransformer.transformSource (../../node_modules/@jest/transform/build/ScriptTransformer.js:464:35)
</code></pre>
<p>the generated <code>jest.config.js</code>:</p>
<pre class=""lang-js prettyprint-override""><code>module.exports = {
  displayName: 'my-app',
  preset: '../../jest.preset.js',
  globals: {
    'ts-jest': {
      tsconfig: '&lt;rootDir&gt;/tsconfig.spec.json',
    },
  },
  transform: {
    '^.+\\.svelte$': 'svelte-jester',
    '^.+\\.[tj]s$': 'ts-jest',
  },
  moduleFileExtensions: ['ts', 'js', 'html', 'svelte'],
  coverageDirectory: '../../coverage/apps/my-app',
};

</code></pre>
<p>the <code>tsconfig.json</code> file:</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;extends&quot;: &quot;../../tsconfig.base.json&quot;,

  &quot;compilerOptions&quot;: {
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;target&quot;: &quot;es2017&quot;,
    /**
      Svelte Preprocess cannot figure out whether you have a value or a type, so tell TypeScript
      to enforce using `import type` instead of `import` for Types.
     */
    &quot;importsNotUsedAsValues&quot;: &quot;error&quot;,
    &quot;isolatedModules&quot;: true,
    /**
      To have warnings/errors of the Svelte compiler at the correct position,
      enable source maps by default.
     */
    &quot;sourceMap&quot;: true,
    /** Requests the runtime types from the svelte modules by default. Needed for TS files or else you get errors. */
    &quot;types&quot;: [&quot;svelte&quot;],

    &quot;strict&quot;: false,
    &quot;esModuleInterop&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;forceConsistentCasingInFileNames&quot;: true
  },
  &quot;files&quot;: [],
  &quot;include&quot;: [],
  &quot;references&quot;: [
    {
      &quot;path&quot;: &quot;./tsconfig.app.json&quot;
    },
    {
      &quot;path&quot;: &quot;./tsconfig.spec.json&quot;
    }
  ]
}
</code></pre>
<p>the <code>tsconfig.spec.json</code>:</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;extends&quot;: &quot;./tsconfig.json&quot;,
  &quot;compilerOptions&quot;: {
    &quot;outDir&quot;: &quot;../../dist/out-tsc&quot;,
    &quot;module&quot;: &quot;commonjs&quot;,
    &quot;types&quot;: [&quot;jest&quot;, &quot;node&quot;, &quot;@types/jest&quot;]
  },
  &quot;include&quot;: [
    &quot;**/*.spec.ts&quot;,
    &quot;**/*.spec.tsx&quot;,
    &quot;**/*.spec.js&quot;,
    &quot;**/*.spec.jsx&quot;,
    &quot;**/*.d.ts&quot;
  ]
}
</code></pre>
<p><code>tsconfig.base.json</code> on the root of the NX workspace</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;compileOnSave&quot;: false,
  &quot;compilerOptions&quot;: {
    &quot;rootDir&quot;: &quot;.&quot;,
    &quot;sourceMap&quot;: true,
    &quot;declaration&quot;: false,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;emitDecoratorMetadata&quot;: true,
    &quot;experimentalDecorators&quot;: true,
    &quot;importHelpers&quot;: true,
    &quot;target&quot;: &quot;es2015&quot;,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;lib&quot;: [&quot;es2017&quot;, &quot;dom&quot;],
    &quot;skipLibCheck&quot;: true,
    &quot;skipDefaultLibCheck&quot;: true,
    &quot;baseUrl&quot;: &quot;.&quot;,
    &quot;paths&quot;: {}
  },
  &quot;exclude&quot;: [&quot;node_modules&quot;, &quot;tmp&quot;]
}
</code></pre>
<p>I am hopping, there's some easy fix in some of this files that I am not seeing.</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/66463653/error-in-unit-testing-svelte-app-within-nx-workspace-project-using-jest,"['typescript', 'svelte-3', 'ts-jest']",639,False,1,1
How to properly stub an element when unit testing a LitElement component?,"<p>I'm trying to unit test LitElement components. When trying to isolate components, I got perplexed how to actually stub elements. That is, I cannot find a solution how to replace a proper element with a hollowed one.<br />
The polymer project on the topic of unit testing mentions <a href=""https://polymer-library.polymer-project.org/3.0/docs/tools/tests"" rel=""nofollow noreferrer"">this</a> I failed to find the definition of the replace() function to see the implementation details. Actually, what is described by the polymer project in the &quot;Create Stub Elements&quot; heading is what I'm looking for.</p>
<p>Element definition file</p>
<pre><code>export class AppElement extends LitElement {
    render() {
        return html`
            &lt;header-element class=&quot;header&quot;&gt;&lt;/header-element&gt;
            &lt;div class=&quot;body&quot;&gt;
                &lt;menu-element&gt;&lt;/menu-element&gt;
                &lt;social-media-element&gt;&lt;/social-media-element&gt;
                &lt;contacts-element&gt;&lt;/contacts-element&gt;
                &lt;tap-list-element name=&quot;Fridge List&quot; display=&quot;fridge&quot;&gt;&lt;/tap-list-element&gt;
                &lt;tap-list-element route=&quot;tap&quot; name=&quot;Tap List&quot; display=&quot;tap&quot; &gt;&lt;/tap-list-element&gt;
                &lt;home-element&gt;&lt;/home-element&gt;
                &lt;about-us-element&gt;&lt;/about-us-element&gt;
                &lt;not-found-element&gt;&lt;/not-found-element&gt;
            &lt;/div&gt;
       `;
   }
}
</code></pre>
<p>Element testing file</p>
<pre><code>describe(&quot;Test Case for the AppElement Component&quot;, function() {
beforeEach(() =&gt; {
    app = new AppElement();
    document.body.appendChild(app);
    shadow = app.shadowRoot;
    app.updateComplete.then(() =&gt; {
        const tapListStub = new TapListElementStub();
        const tapListNodes = shadow.querySelectorAll('tap-list-element');
        console.log(app);
        const tapListLength = tapListNodes.length;
        const tapListNode = tapListLength === 1 ? tapListNodes[0] : null;
        tapListNode.replaceWith(tapListStub);
    });
});

it(&quot;should have the node for tap-list replaced with a stub&quot;, function(done) {
    app.updateComplete.then(() =&gt; {
        const newTap: TapListElement = shadow.querySelector('tap-list-element');
        console.log(shadow);
        assert.strictEqual('Tap List Stub', newTap.name);
        done();
    })
});
</code></pre>
<p>Here is the code for the original TapListElement</p>
<pre><code>@customElement('tap-list-element')
export class TapListElement extends LitElement {
    private _menu: Menu;
    private _tapList: Section;
    private _bottleList: Section;

    @property()
    name: string = 'Tap List';

    @property({type: String, attribute: true})
    display: string;

    constructor() {
        super();
        super.connectedCallback();
    }
}
</code></pre>
<p>And here is the stub</p>
<pre><code>@customElement('tap-list-element')
export class TapListElementStub extends LitElement {

    @property()
    name: string = 'Tap List Stub';

    @property({type: String, attribute: true})
    display: string;

    constructor() {
        super();
        super.connectedCallback();
    }
}
</code></pre>
<p>Apologies for any indentation typos.</p>
<p>When I tried the code above, I get the error that the web component with that name &quot;tap-list-element&quot; had already been registered. I tried removing the @customElement decorator in the TapListElementStub but then I get the error that an Illegal Constructor had been called.
Has anyone tried stubbing litElement components?
I'm coming from an Angular background. There the TestBed helper library sets up the module and you can substitute any component as long as the attributes remain the same and the name of the component in the decorator is the same.</p>
",https://stackoverflow.com/questions/66231428/how-to-properly-stub-an-element-when-unit-testing-a-litelement-component,"['typescript', 'unit-testing', 'mocking', 'mocha.js', 'lit-element']",836,True,1,1
Unit testing client-go function that auths and returns a k8s clientset,"<p>I am writing the simplest fxn possible using <code>client-go</code> that justs performs in-cluster authentication and returns a pointer to the <code>kubernetes.Clientset</code> object</p>
<pre class=""lang-golang prettyprint-override""><code>// getInClusterAuth performs in cluster authentication and returns the clientset
func getInClusterAuth() (*kubernetes.Clientset, error) {
    // creates the in-cluster config
    config, err := rest.InClusterConfig()
    if err != nil {
        return nil, err
    }
    // create the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        return nil, err
    }

    return clientset, nil
}
</code></pre>
<p>Since this is sth that not only does it run against an external system (a <code>k8s</code> api server) but it is also supposed to be running from within a <code>Pod</code> once deployed, what is the appropriate way of unit-testing it?</p>
<p>Could it be that it is an acceptable practice to cover the case in e2e or integration tests?</p>
",https://stackoverflow.com/questions/68705402/unit-testing-client-go-function-that-auths-and-returns-a-k8s-clientset,"['unit-testing', 'go', 'testing', 'kubernetes', 'client-go']",1108,True,1,1
Symfony 5.1 to 5.2 unit testing do not authenticate via guard authenticator,"<p>I 'm working with Symfony 5.1 using the firewall and a guard authenticator;</p>
<pre><code>        secured_area:
        pattern:  ^/
        stateless: true
        provider: chain_provider
        guard:
            authenticators:
                - App\&lt;pathToAuthenticator&gt;
            entry_point: App\&lt;pathToAuthenticator&gt;
</code></pre>
<p>All was working fine with 5.1.
I've recently upgrade to Symfony 5.2 and almost all working fine except Unit tests.
When i do a step by step debugging, it's not stepping into the <code>Authenticator</code> anymore like it was the case previously (in 5.1).</p>
<p>Any parameter missing in my configuration ? Default parameter have change ?</p>
",https://stackoverflow.com/questions/67093692/symfony-5-1-to-5-2-unit-testing-do-not-authenticate-via-guard-authenticator,"['php', 'unit-testing', 'symfony', 'authenticator']",251,True,0,1
Unit testing text to html throwing assertion error because of extra characters,"<p>I have this function:</p>
<pre><code>def text_to_html(text):
    &quot;&quot;&quot;
    Convert text into HTML
    Args:
        text (): text to convert

    Returns:
        HTML string
    &quot;&quot;&quot;
    html = &quot;&lt;p&gt;&quot; + text.replace(&quot;\n&quot;, &quot;&lt;br&gt;&quot;) + &quot;&lt;/p&gt;&quot;
    return html
</code></pre>
<p>I'm trying to create a unit test for this function like this.</p>
<pre><code>class TestDebtModules(unittest.TestCase):
    def test_html(self):
        string = &quot;&quot;&quot;
        THIS
        IS A TEST
        STRING
        &quot;&quot;&quot;
        string_input = text_to_html(string)
        string_output = r'&lt;p&gt;&lt;br&gt;THIS &lt;br&gt;IS A TEST &lt;br&gt;STRING&lt;br&gt;&lt;/p&gt;'
        self.assertEqual(string_input, string_output)
</code></pre>
<p>However. it's throwing an assertion error because it's adding extra characters in my string. Is this a known bug or is it me doing something wrong? (Hopefully the latter). If it happens to be the former, is there any workaround for this?</p>
<pre><code>Expected :&lt;p&gt;&lt;br&gt;        THIS&lt;br&gt;        IS A TEST&lt;br&gt;        STRING&lt;br&gt;        &lt;/p&gt;
Actual   :&lt;p&gt;&lt;br&gt;THIS &lt;br&gt;IS A TEST &lt;br&gt;STRING&lt;br&gt;&lt;/p&gt;
</code></pre>
",https://stackoverflow.com/questions/70162722/unit-testing-text-to-html-throwing-assertion-error-because-of-extra-characters,"['python', 'python-3.x', 'unit-testing']",234,True,0,1
Spring Boot unit testing assertion error JSON object got a JSON array,"<p>I am unit testing in a spring boot application. But as the getProductById() method returns Optional of the object, I am not sure how to test it.</p>
<p><strong>ProductController.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>@GetMapping(&quot;/products/{id}&quot;)
@Transactional(readOnly=true)
@Cacheable(&quot;product-cache&quot;)
public Product getProduct(@PathVariable(&quot;id&quot;) int id) {
        LOGGER.info(&quot;Finding product by id : &quot;+id);
        return productRepository.findById(id).get();
}
</code></pre>
<p><strong>MockTest.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>private static final String PRODUCTS_URL = &quot;/productsapi/products&quot;;
private static final int PRODUCT_ID = 1;
private static final String CONTEXT_URL = &quot;/productsapi&quot;;
private static final int PRODUCT_PRICE = 1000;
private static final String PRODUCT_DESCRIPTION = &quot;Its awesome&quot;;
private static final String PRODUCT_NAME = &quot;Macbook&quot;;

@Test
public void testGetProductById() throws JsonProcessingException, Exception {
        Product product = buildProduct();
        when(productRepository.findById(PRODUCT_ID)).thenReturn(Optional.of(product));
        
        ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
        mockMvc.perform(get(PRODUCTS_URL).contextPath(CONTEXT_URL))
           .andExpect(status().isOk())
           .andExpect(content().json(objectWriter.writeValueAsString(Optional.of(product))));
}

private Product buildProduct() {
        Product product = new Product();
        product.setId(PRODUCT_ID);
        product.setName(PRODUCT_NAME);
        product.setDescription(PRODUCT_DESCRIPTION);
        product.setPrice(PRODUCT_PRICE);
        return product;
}
</code></pre>
<p>When I run the test, it fails with below error.</p>
<p><strong>Error:</strong>
java.lang.AssertionError:
Expected: a JSON object
got: a JSON array</p>
<p>It doesn't show any compilation error. But test case fails. I think it's the problem with conversion of product object into json.</p>
<p>So, little help in resolving this will be helpful!!</p>
",https://stackoverflow.com/questions/67405278/spring-boot-unit-testing-assertion-error-json-object-got-a-json-array,"['java', 'spring-boot', 'unit-testing', 'junit', 'option-type']",1220,True,0,1
Getting error while unit testing my machine learning model on Audio files,"<p>I am getting errors when training my machine learning model which is for checking what a person is feeling while saying somthing. I am working with librosa, soundfile &amp; MLPClassifier from sklearn. This is my code:</p>
<pre><code>;imported required libraries
import librosa
import soundfile
import os, glob, pickle
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score

; created a function that basically gathers features from audio files
def extract_feature(file_name, mfcc, chroma, mel):
    with soundfile.SoundFile(file_name) as sound_file:
        X = sound_file.read(dtype=&quot;float32&quot;)
        sample_rate=sound_file.samplerate
        if chroma:
            stft=np.abs(librosa.stft(X))
            result=np.array([])
        if mfcc:
            mfccs=np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T, axis=0)
            result=np.hstack((result, mfccs))
        if chroma:
            chroma=np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T,axis=0)
            result=np.hstack((result, chroma))
        if mel:
            mel=np.mean(librosa.feature.melspectrogram(X, sr=sample_rate).T,axis=0)
            result=np.hstack((result, mel))
    return result
; defined emotions
emotions={
  '01':'neutral',
  '02':'calm',
  '03':'happy',
  '04':'sad',
  '05':'angry',
  '06':'fearful',
  '07':'disgust',
  '08':'surprised'
}
observed_emotions=['calm', 'happy', 'fearful', 'disgust']
;to load data
def load_data(test_size=0.2):
    x,y=[],[]
    for file in glob.glob(&quot;data\\Actor_*\\*.wav&quot;):
        file_name=os.path.basename(file)
        emotion=emotions[file_name.split(&quot;-&quot;)[2]]
        if emotion not in observed_emotions:
            continue
        feature=extract_feature(file, mfcc=True, chroma=True, mel=True)
        x.append(feature)
        y.append(emotion)
    return train_test_split(np.array(x), y, test_size=test_size, random_state=9)

x_train,x_test,y_train,y_test=load_data(test_size=0.23)

print((x_train.shape[0], x_test.shape[0]))

; used the mlpclassifier
model=MLPClassifier(alpha=0.01, batch_size=256, epsilon=1e-08, hidden_layer_sizes=(300,), learning_rate='adaptive', max_iter=500)

;trained my model
model.fit(x_train,y_train)

; This is the part used for unit testing and I am getting a lot of errors
a,b = [],[]
file_name=os.path.basename(&quot;data/what.wav&quot;)
emotion=emotions[file_name.split(&quot;-&quot;)[2]]
if emotion not in observed_emotions:
    continue
feature=extract_feature(file, mfcc=True, chroma=True, mel=True)
a.append(feature)
b.append(emotion)
</code></pre>
<p>This is the error that I am getting, which when i try to remove via other methods like using pydub , I get different types of errors. I am a begineer to this and still have to learn a lot. So i hope can find a way to resolve this .</p>
<pre><code>IndexError                                Traceback (most recent call last)
&lt;ipython-input-41-8b30084e3248&gt; in &lt;module&gt;
      1 a,b = [],[]
      2 file_name=os.path.basename(&quot;data/what.wav&quot;)
----&gt; 3 emotion=emotions[file_name.split(&quot;-&quot;)[2]]
      4 if emotion not in observed_emotions:
      5     continue

IndexError: list index out of range

</code></pre>
",https://stackoverflow.com/questions/69980821/getting-error-while-unit-testing-my-machine-learning-model-on-audio-files,"['python', 'machine-learning', 'scikit-learn', 'librosa', 'soundfile']",96,True,0,1
Angular Unit Testing - How to trigger another emit from an injected service?,"<p>I have a component that does the following:</p>
<ol>
<li><p>In the constructor, it takes the query parameters and parses them into the given quarter and year</p>
</li>
<li><p>In ngOnInit, it subscribes to a service that returns a list of quarters and years. In the subscription's callback, it uses the values of the quarter and year to assign a value to either the chosen quarter and year from the query params, or the first in the list if they are not valid.</p>
</li>
</ol>
<p>In my unit test, I am able to set the params (or at least the snapshot) but I want to re-trigger the callback inside the subscribe method and assert some expectations. I am not sure how to re-trigger the callback in the subscribe method.</p>
<p>Here is the relevant code of my component:</p>
<pre><code>@Component({
    ...
})
export class MyComponent implements OnInit {
quarter: number;
year: number;
paramQuarter: string;
selectedQuarter: IQuarter;
quartersList: IQuarter[];

constructor(
            private quarterService: QuarterService,
            private activatedRoute: ActivatedRoute,
            private router : Router) {

    // if no query param is set, set as the current quarter and year from moment.js
    this.paramQuarter = this.activatedRoute.snapshot.queryParams['quarter'] 
        || moment().quarter() + '-' + moment().year();

}

ngOnInit(): void {

    this.quarterService.getQuarters().subscribe(response =&gt; {
        this.quartersList = response;
        /// ----------------------------------
        /// The code I want to test is in here
        /// ----------------------------------
        const [quarter, year] = this.paramQuarter.split(&quot;-&quot;).map(string =&gt; parseInt(string));
        // get the correct quarter based on URL params, or the current one if the url param is malformed
        this.selectedQuarter: IQuarter = this.quartersList
            .filter(q =&gt; q.quarter === quarter &amp;&amp; q.year === year)[0]
            || this.quartersList[0];
    });
}

}
</code></pre>
<p>And of the test:</p>
<pre><code>const MOCK_QUARTERS = [
{
    quarter: 2,
    year: 2020,
    startDate: '2020-04-01',
    endDate: '2020-06-30',
},
{
    quarter: 1,
    year: 2020,
    startDate: '2020-01-01',
    endDate: '2020-03-31',
}
]

describe('MyComponent', () =&gt; {
let component: MyComponent;
let fixture: ComponentFixture&lt;MyComponent&gt;;
let quarterService: QuarterService;
let router : Router;
let activatedRoute : ActivatedRoute;

const MockQuarterService = {
    getQuarters: jasmine.createSpy('getQuarters').and.returnValue(
    of(MOCK_QUARTERS)
    )
}

beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
    declarations: [
        MyComponent,
    ],
    imports: [
        SharedModule,
        RouterTestingModule,
        ...HttpClientTestingImports,
    ],
    providers: [
        ...HttpClientTestingProviders,
        { provide: QuarterService, useValue: MockQuarterService },
        {
        provide: ActivatedRoute,
        useValue: {
            queryParams: of({ quarter: '2-2020' }),
            snapshot: {
            queryParams: { quarter: '2-2020' }
            }
        }
        },
    ]
    })
    .compileComponents();
}));

beforeEach(() =&gt; {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    quarterService = TestBed.inject(QuarterService);
    router = TestBed.inject(Router);
    activatedRoute = TestBed.inject(ActivatedRoute);
    fixture.detectChanges();
});

fit('should set the current quarter from correctly formed URL params', async(() =&gt; {
    // set from the params in the beforeEach callback
    expect(component.selectedQuarter).toEqual(MOCK_QUARTERS[0]);
    spyOn(component, 'updateQuarterSelection').and.callThrough();

    let actRoute : ActivatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
    actRoute.queryParams = of( {quarter: `${MOCK_QUARTERS[1].quarter}-${MOCK_QUARTERS[1].year}` } );
    actRoute.snapshot.queryParams.quarter = `${MOCK_QUARTERS[1].quarter}-${MOCK_QUARTERS[1].year}`;
    /// ----------------------------------
    // Somehow need the callback of the quarterService.getQuarters().subscribe() 
    // method to retrigger here
    /// ----------------------------------
    fixture.detectChanges();
    console.log(component);
    
    expect(quarterService.getQuarters).toHaveBeenCalledTimes(2);
    expect(component.updateQuarterSelection).toHaveBeenCalledTimes(2);
    expect(component.selectedQuarter).toEqual(MOCK_QUARTERS[1]);
}));

});
</code></pre>
",https://stackoverflow.com/questions/67639177/angular-unit-testing-how-to-trigger-another-emit-from-an-injected-service,"['angular', 'unit-testing', 'jasmine', 'angular-test']",236,True,0,1
How to Start Unit Testing in React Native using jest for constant,"<p>I m new to Unit Test and currently writing Unit Test for my TypeScript app using Jest. I m using a custom package named <code>common-packages</code> where i store all of my constant, something simple like this</p>
<pre><code>const CLIENT_ID = 1231123123;
const TEXT = {
  Discover:&quot;Discover&quot;,
  loading: 'loading',
  Type: &quot;Testing&quot;,
}
const Constants = {
  TEXT,
  CLIENT_ID,
} as const;

export default Constants;
</code></pre>
<p>on my package, index.tsx. i export the <code>Constant</code></p>
<pre><code>export { default as Constants } from &quot;./constants&quot;;
</code></pre>
<p>And the function that i want to test is this</p>
<pre><code>import {Constants} from 'common-packages';

export const lockNextCardIfUncompleted = (data: any[]) =&gt; {
  if (data.length !== 0) {
    const locked = data.filter((e: any) =&gt; e.Type === Constants.TEXT.Type );
    if (locked.length === 0) return false;
    return true;
  }
  return false;
};
</code></pre>
<p>i have tried writing a unit test for lodash like this and it is working</p>
<pre><code>const lodash = require('lodash')
test(&quot;repeat&quot;, () =&gt; {
expect(lodash.repeat(&quot;A&quot;,3)).toBe(&quot;AAA&quot;);
})
</code></pre>
<p>But for the unit test that have common-packages, it failed</p>
<pre><code>import {
  lockNextCardIfUncompleted,
} from './fileName';

test('should return locked', () =&gt; {
  expect(
    lockNextCardIfUncompleted([
      {
        Type: 'A',
      },
    ]),
  ).toBe(false);
  expect(
    lockNextCardIfUncompleted([
      {
        Type: 'Testing,
      },
    ]),
  ).toBe(true);
});
</code></pre>
<p>It return <code>TypeError: Cannot read property 'TEXT' of undefined</code>. So the test didnt recognize the Constant from <code>common-package</code>. can anybody please help me solve this issue?
thank you</p>
",https://stackoverflow.com/questions/66316736/how-to-start-unit-testing-in-react-native-using-jest-for-constant,"['javascript', 'typescript', 'unit-testing', 'jestjs']",374,False,0,1
Unit testing code that persist a new object and generate its id,"<p>I have some code that persist an object with doctrine, then use its newly generated id to link it to another object.</p>
<p>But when I want to test the code, the id is not generated</p>
<pre><code>class Foo extends DefaultDocument
{

    /**
     * @var int
     * @MongoDB\Field(type=&quot;int&quot;)
     * @MongoDB\Id(strategy=&quot;INCREMENT&quot;)
     */
     protected $id
}


class Link
{
    /**
     * @var int
     * @MongoDB\Field(type=&quot;int&quot;)
     */
    private $fooId;
}


class Service
{

    public function doesSomething()
    {
        $foo = new Foo();
        $this-&gt;documentManager-&gt;persist($foo);

        $link = new Link();
        $link-&gt;setFooId($foo-&gt;getId());
    }
}


class TestService
{
    private function createService()
    {
        return new Service();
    }

    public function testDoesSomething()
    {
        $service = $this-&gt;createService();
        $service-&gt;doesSomething(); 
    }
}
</code></pre>
<p>When launching the test I get the following error :</p>
<blockquote>
<p>TypeError: Argument 1 passed to ...\Link::setFooId() must be of the
type int, null given</p>
</blockquote>
<p>Is this a default logic of my code, or the normal behavior of doctrine ?</p>
<p><strong>EDIT :</strong></p>
<p>Finally found the right topic for my question :
<a href=""https://stackoverflow.com/questions/42133082/symfony2-doctrine-phpunit-set-entity-id-during-flushing-with-mocked-entity"">Symfony2 : Doctrine : PHPUnit : Set entity Id during flushing with mocked entity manager in unit tests</a></p>
<p>I used his first solution</p>
",https://stackoverflow.com/questions/68128924/unit-testing-code-that-persist-a-new-object-and-generate-its-id,"['unit-testing', 'symfony', 'testing', 'doctrine', 'doctrine-odm']",768,False,-1,1
Django unit testing if a POST request properly updates a model instance,"<p>I'm having trouble understanding why my test keeps failing.</p>
<p>I have two models (only showing relevant code):</p>
<pre><code>class Listings(models.Model):
    listing_instagram = models.URLField(null=True, blank=True)
    listing_facebook = models.URLField(null=True, blank=True)
    ...

class ListingsDescription(models.Model):
    listing = models.OneToOneField(Listings, on_delete=models.CASCADE)
    space_description = models.TextField(max_length=1000, blank=True)
    accessibility_description = models.TextField(max_length=1000, blank=True)
    ...
</code></pre>
<p>I have a properly functioning view that processes two forms (one form per model):</p>
<pre><code>def some_view(request, listing_id):
    listing = get_object_or_404(Listings, id=listing_id)
    listing_description = listing.listingsdescription

    if request.method == &quot;POST&quot;:
        form_a = ListingForm(request.POST or None, instance=listing)
        form_b = ListingDescriptionForm(request.POST or None, instance=listing_description)
        if form_a.is_valid() and form_b.is_valid():
            form_a.save()
            form_b.save()
            messages.success(request, &quot;Changes Made&quot;)
            return HttpResponseRedirect(reverse('destination')
</code></pre>
<p>Manual testing on my browser works fine, and all fields are properly saved in the database.</p>
<p>However, running below test:</p>
<pre><code>class ListingJourney(TestCase):
@classmethod
def setUpTestData(cls):
    cls.client = Client()
    # Create Listing
    cls.listing = ...

def listing_post(self):
    self.assertTrue(Listings.objects.filter(id=self.listing.id).exists())
    response = self.client.get(reverse('new_listing', kwargs={'listing_id': self.listing.id}),
                               follow=True)
    self.assertEqual(response.status_code, 200)
    self.assertTemplateUsed(response, template_name='foo/listing.html')

    response = self.client.post(reverse('new_listing', kwargs={'listing_id': self.listing.id}),
                                follow=True,
                                data={
                                    'space_description': &quot;Lorem ipsum dolor&quot;,
                                    'neighborhood_description': &quot;Lorem ipsum dolor&quot;,
                                    'listing_instagram': &quot;https://www.instagram.com/listing/&quot;,
                                    'listing_facebook': &quot;https://www.facebook.com/listing/&quot;,
                                    # some more data
                                })
    self.assertRedirects(response, reverse('redirect', kwargs={'listing_id': self.listing.id}),
                         status_code=302,
                         target_status_code=200,
                         fetch_redirect_response=True)
    self.assertEqual(self.listing.listingsdescription.space_description, &quot;Lorem ipsum dolor&quot;)
    self.assertEqual(self.listing.listing_facebook, &quot;https://www.facebook.com/listing/&quot;)
    self.assertEqual(self.listing.listing_instagram, &quot;https://www.instagram.com/listing/&quot;)
</code></pre>
<p>The test fails at:</p>
<pre><code>self.assertEqual(self.listing.listing_facebook, &quot;https://www.facebook.com/listing/&quot;)

Traceback (most recent call last):
  File &quot;...\tests.py&quot;, line 153, in listing_post
    self.assertEqual(self.listing.listing_facebook, &quot;https://www.facebook.com/listing/&quot;)
AssertionError: None != 'https://www.facebook.com/listing/'
</code></pre>
<p>Meaning the Description fields were properly saved with the right text, but the social media fields are still empty. Again, manually testing, everything works fine.</p>
<p>printing request.POST in the view, and manually testing, also shows the name of the keys are correct:</p>
<pre><code>&lt;QueryDict: {'csrfmiddlewaretoken': ['blabla'], 
'listing_instagram': ['https://www.instagram.com/listing/'],
'listing_facebook': ['https://www.facebook.com/listing/'],
'space_description': ['Lorem ipsum dolor'], 
'neighborhood_description': ['Lorem ipsum dolor']}&gt;
</code></pre>
<p>Could it be that somehow the database has not finished saving the model field, before it asserts that the data is saved properly?</p>
<p>Help is appreciated.</p>
",https://stackoverflow.com/questions/69690283/django-unit-testing-if-a-post-request-properly-updates-a-model-instance,"['django', 'unit-testing', 'django-testing']",212,False,0,1
Unit Testing : Retrofit 2 Exception - API interfaces must not extend other interfaces,"<p>I am not extending any interface and all my interfaces are independent. While performing unit testing I am getting the following exception. During normal API calls, everything works fine.</p>
<pre><code> val retrofit: Retrofit = Retrofit.Builder()
            .baseUrl(url)
            .client(httpBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
        return retrofit.create(MyApi::class.java)
</code></pre>
<p>The exception is thrown at <code>retrofit.create(..)</code> only while performing the unit test. Is there a way to avoid this error?</p>
",https://stackoverflow.com/questions/65829761/unit-testing-retrofit-2-exception-api-interfaces-must-not-extend-other-inter,"['android', 'mockito', 'powermockito', 'android-unit-testing']",181,False,0,1
Unit testing a custom hook to ensure that it calls another hook,"<p>How can we ensure that a custom hook actually calls a method exposed by another hook?</p>
<p>Let's say, I have a custom hook <code>useName</code> that internally leverages <code>useState</code>.</p>
<pre class=""lang-js prettyprint-override""><code>import { useState } from 'react'

export const useName = () =&gt; {

    const [name, setState] = useState()

    const setName = (firstName: string, lastName: string) =&gt; setState([firstName, lastName].join(' '))

    return {name, setName}
}
</code></pre>
<p>I need to assert that calling <code>setName</code> actually calls `setState'. My test case is written as following:</p>
<pre class=""lang-js prettyprint-override""><code>/**
* @jest-environment jsdom
*/

import * as React from 'react'
import { renderHook, act } from '@testing-library/react-hooks'
import { useName } from './useName'

jest.mock('react')

const setState = jest.fn()

React.useState.mockReturnValue(['ignore', setState]) //overwriting useState

test('ensures that setState is called', () =&gt; {
    
    const {result} = renderHook(() =&gt; useName())

    act(() =&gt; {
        result.current.setName(&quot;Kashif&quot;, &quot;Nazar&quot;) //I am expecting this to hit jest.fn() declared above.
    })

    expect(setState).toBeCalled()

})
</code></pre>
<p>and I get the following result.</p>
<pre><code> FAIL  src/useName.test.ts
  ✕ ensures that setState is called (3 ms)

  ● ensures that setState is called

    TypeError: Cannot read property 'setName' of undefined

      18 |
      19 |     act(() =&gt; {
    &gt; 20 |         result.current.setName(&quot;Kashif&quot;, &quot;Nazar&quot;)
         |                        ^
      21 |     })
      22 |
      23 |     expect(setState).toBeCalled()

      at src/useName.test.ts:20:24
      at batchedUpdates$1 (node_modules/react-dom/cjs/react-dom.development.js:22380:12)
      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:1042:14)
      at Object.&lt;anonymous&gt; (src/useName.test.ts:19:5)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.32 s, estimated 1 s
Ran all test suites.
</code></pre>
<p>Is this possible, and am I doing it the right way?</p>
",https://stackoverflow.com/questions/70381825/unit-testing-a-custom-hook-to-ensure-that-it-calls-another-hook,"['reactjs', 'unit-testing', 'react-hooks', 'jestjs', 'react-hooks-testing-library']",2069,True,0,1
angular unit testing a method having a cont and a for loop,"<p>I am doing unit test in Angular using jasmine. I have a method containing a <code>const</code> and a <code>for</code> loop. Below is the code:</p>
<pre><code>private initializeFilterArrays() {
    const today = new Date().getFullYear();
    for (let i = 0; i &lt; 5; i++) {
      this.yearsFilter.push(today - i);
    }
  }
</code></pre>
<p>The html for this:</p>
<pre><code>&lt;button (click)=&quot;initializeFilterArrays()&quot; id=&quot;init&quot;&gt;Filter&lt;/button&gt;
</code></pre>
<p>The spec.ts:</p>
<pre><code>it('clicking on &quot;Filter&quot; should filter', () =&gt; {
   const filterBtn = debugElement.query(By.css('#init'));
   filterBtn.triggerEventHandler('click', {});
   ...
}
</code></pre>
<p>So, in the testcase, what do I write after I triggered the click so that all the lines of the method are executed? I want to test whether all the lines are executed or not. And how to make all lines execute? What to do if I want total code coverage?</p>
",https://stackoverflow.com/questions/66745008/angular-unit-testing-a-method-having-a-cont-and-a-for-loop,"['angular', 'unit-testing', 'jasmine', 'karma-runner']",1231,True,0,1
How do i apply unit testing to check leap year with golang?,"<p>I want to do unit testing and check if dates are leap year or not, how do i apply unit testing in this case, i don’t t know how to go about it in this situation?</p>
<p>I have already created my function and it works fine, i also have a JSON file that contains list of people and their Birthday dates !</p>
<p>Would appreciate some feedback or advice on how to tackle this problem ! Thanks</p>
<p>BD.go:</p>
<pre><code> package main

import (
    &quot;encoding/json&quot;
    &quot;fmt&quot;
    &quot;io/ioutil&quot;
    &quot;log&quot;
    &quot;os&quot;
    &quot;time&quot;
)

// Users struct which contains
// an array of users
type Users struct {
    Users []User `json:&quot;users&quot;`
}

// User struct which contains a name
// a type and a list of social links
type User struct {
    Firstname  string `json:&quot;fname&quot;`
    Secondname string `json:&quot;lname&quot;`
    Date       string `json:&quot;date&quot;`
}

var users Users
var user User

func Birthday() {
    // Open our jsonFile
    jsonFile, err := os.Open(&quot;users.json&quot;)
    // if we os.Open returns an error then handle it
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(&quot;Successfully Opened users.json&quot;)
    // defer the closing of our jsonFile so that we can parse it later on
    defer jsonFile.Close()

    // read our opened xmlFile as a byte array.
    byteValue, _ := ioutil.ReadAll(jsonFile)

    // we initialize our Users array
    // we unmarshal our byteArray which contains our
    // jsonFile's content into 'users' which we defined above
    json.Unmarshal(byteValue, &amp;users)
    IsLeapYear(&quot;users.json&quot;)
}

func IsLeapYear(user string) bool {
    // we iterate through every user within our users array and
    // print out the user Type, their name
    for i := 0; i &lt; len(users.Users); i++ {
        date, err := time.Parse(&quot;2006/01/02&quot;, users.Users[i].Date)
        if err != nil {
            date, err = time.Parse(&quot;2006-01-02&quot;, users.Users[i].Date)
            // date, err = time.Parse(&quot;2006 01 02&quot;, users.Users[i].Date)
            if err != nil {
                log.Fatal(&quot;unsupported date format:&quot;, err)
            }
        }

        // check if the date is a leap year, ex: 29 is not a leap year but 28th is !

        if date.Day()%400 == 0 || (date.Day()%4 == 0 &amp;&amp; date.Day()%100 != 0) {
            fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
            fmt.Println(&quot;User Second Name: &quot; + users.Users[i].Secondname)
            fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
            fmt.Println(users.Users[i].Date, &quot;is a Leap Year ✨ ✨ ✨&quot;)

            // checking if the date.day matches today's date
            if date.Day() == time.Now().Day() {
                fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
                fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
                fmt.Println(&quot;TODAY IS YOUR BIRTHDAY, Happy birthday !!!🎉 🎉 🍾 🍾 &quot;)

                // not ur birthday today because the date in the json doesn't match todays date
            } else {

                fmt.Println(&quot;TODAY IS NOT YOUR BIRTHDAY..!!!&quot;)

            }

        } else {
            fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
            fmt.Println(&quot;User Second Name: &quot; + users.Users[i].Secondname)
            fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
            fmt.Println(users.Users[i].Date, &quot; is Not a Leap Year 💥 💥 💥 &quot;)
        }

    }

    return false
}

func main() {
    Birthday()

}
</code></pre>
<p>bd_test.go:</p>
<p>package main</p>
<pre><code>import (
    &quot;testing&quot;
    &quot;time&quot;

    &quot;github.com/stretchr/testify/assert&quot;
)

//main_test.go
type dateTest struct {
    date   time.Time
    expect bool
}

var dateTests = []dateTest{
    {&quot;2021-07-28&quot;, true},
    {time.Date(2021,9,10), false},
}

func TestIsLeapYear(t *testing.T) {
    for _, tc := range dateTests {
        result := IsLeapYear(tc.date)
        assert.Equal(t, tc.expect, result)
    }
}
</code></pre>
<p>users.JSON:</p>
<pre><code>{
    &quot;users&quot;: [
      {
        &quot;Fname&quot;: &quot;Johnny&quot;,
        &quot;Lname&quot;:&quot;mane&quot;,
        &quot;date&quot;:&quot;1982/01/08&quot;
      },
      {
        &quot;Fname&quot;: &quot;Wayne&quot;,
        &quot;Lname&quot;:&quot;Bruce&quot;,
        &quot;date&quot;:&quot;1965/01/30&quot;
      },
      {
        &quot;Fname&quot;: &quot;Gaga&quot;,
        &quot;Lname&quot;:&quot;Lady&quot;,
        &quot;date&quot;:&quot;1986/03/08&quot;
      },
      {
        &quot;Fname&quot;: &quot;radio&quot;,
        &quot;Lname&quot;:&quot;head&quot;,
        &quot;date&quot;:&quot;1988/02/29&quot;
      },
      {
        &quot;Fname&quot;: &quot;Mario&quot;,
        &quot;Lname&quot;:&quot;torres&quot;,
        &quot;date&quot;:&quot;1996/09/04&quot;
      },
      
      {
        &quot;Fname&quot;: &quot;robert&quot;,
        &quot;Lname&quot;:&quot;Alex&quot;,
        &quot;date&quot;:&quot;1991/12/05&quot;
      },
      {
        &quot;Fname&quot;: &quot;Julia&quot;,
        &quot;Lname&quot;:&quot;sevak&quot;,
        &quot;date&quot;:&quot;1991-03-28&quot;

      },
      {
        &quot;Fname&quot;: &quot;feb&quot;,
        &quot;Lname&quot;:&quot;robert&quot;,
        &quot;date&quot;:&quot;1995-05-24&quot;

      },
      {
        &quot;Fname&quot;: &quot;Liam&quot;,
        &quot;Lname&quot;:&quot;Noah&quot;,
        &quot;date&quot;:&quot;2002-10-04&quot;

      },
      {
        &quot;Fname&quot;: &quot;alex&quot;,
        &quot;Lname&quot;:&quot;sam&quot;,
        &quot;date&quot;:&quot;2021/10/21&quot;

      }
      
      }

    ]
  }
</code></pre>
",https://stackoverflow.com/questions/69673616/how-do-i-apply-unit-testing-to-check-leap-year-with-golang,"['unit-testing', 'go', 'testing']",480,True,-2,2
How to deal with Page while unit testing with mockito and Junit,"<p>I want to mock database call with fake data but I got stuck in the following scenario:</p>
<p>MyService</p>
<pre class=""lang-java prettyprint-override""><code>public class MyService {
    // some stuff

    Page&lt;SampleDto&gt; sample = repo.findAllSample();

    // other stuff
}
</code></pre>
<p>I want to stub this with <code>when()</code> but I am not able to do this. My test is:
MyServiceTest</p>
<pre class=""lang-java prettyprint-override""><code>public class MySampleTest {

    @Test
    void myTest() {
        // initialisation and all stuff

        when(myRepo.findAll()).thenReturn(......)
        // I want to pass 2 fake SampleDto from 
        // here but don't know how to do that
    }
}
</code></pre>
",https://stackoverflow.com/questions/70322398/how-to-deal-with-page-while-unit-testing-with-mockito-and-junit,"['java', 'unit-testing', 'junit', 'mocking', 'mockito']",1061,True,1,4
Not getting a filled array in unit testing (sepc.ts) from (.ts) file,"<p>I want to get this all appointments array in apec.ts file with its filled objects, but when I am directly calling it by component.allAppoitments its getting allAppoitments with zero elements filled, how can i get this array with all element filled in spec.ts file</p>
<p>spec.ts file ======&gt;</p>
<pre><code>beforeEach(() =&gt; {
    fixture = TestBed.createComponent(DashboardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    component.getAppointments();
  });

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

  it(&quot;all appoitments added&quot;,()=&gt;{
    expect(component.allAppointment.length).toEqual(0);
  });
</code></pre>
<p>.ts file ======&gt;</p>
<pre><code> allAppointment: AppointmentModel []=[];
 appointmentSummary:any[]=[];



  ngOnInit(): void {
   
    this.getAppointments()

  
    this.getAppointmentsSummary();
  }

  
  getAppointments(){
    this.dashboardService.getAllPatients().subscribe((res: any) =&gt; {
      for(let r of res){
        this.allAppointment.push(r)
      }
    })
  }
</code></pre>
",https://stackoverflow.com/questions/69708867/not-getting-a-filled-array-in-unit-testing-sepc-ts-from-ts-file,"['angular', 'typescript', 'unit-testing', 'testing', 'angular-test']",78,False,0,0
Getting &quot;System.logW: No Compatibility callbacks set! Querying change 119147584&quot; Warning when Unit-Testing Kotlin App,"<p>I wrote a Unit-test with RobolectricsTestRunner included.</p>
<p>The unit test passed, but with the following warning:</p>
<pre><code>System.logW: No Compatibility callbacks set! Querying change 119147584
</code></pre>
<p>All I did in the unit-test, I saved a variable in Shared Preferences.
This warning doesn't destroy anything. I was just wondering what it means.
Unit-Test:</p>
<pre><code>@RunWith(RobolectricTestRunner::class)
@Config(sdk = [30])
class SharedPreferencesProviderTest {

    private lateinit var sharedPreferencesProvider: SharedPreferencesProviderInterface

    @Before
    fun setup() {
        // setup Shared preferences
        ...

        // Shared Preferences Access
        ...

        // clearing Shared Preferences
       ...
    }

    @Test
    fun firstStart_shouldBeTrueDefaultAndCheckChange() {
        // Default check
        var firstStart =
            sharedPreferencesProvider.getIsFirstStart()
        var expected = true
        assertTrue(firstStart == expected)

        // Check whether it handles changes
        sharedPreferencesProvider.setIsFirstStart(false)
        firstStart =
            sharedPreferencesProvider.getIsFirstStart()
        expected = false
        assertTrue(firstStart == expected)
    }}
</code></pre>
<p>I seems like it doesn't trigger OnSharedPreferenceChangeListener anymore, but I'm not sure. <a href=""https://developer.android.com/about/versions/11/reference/compat-framework-changes?hl=pl"" rel=""noreferrer"">source</a></p>
",https://stackoverflow.com/questions/70350809/getting-system-logw-no-compatibility-callbacks-set-querying-change-119147584,"['android', 'unit-testing', 'kotlin', 'sharedpreferences', 'robolectric']",1095,False,17,0
"C# unit testing MoQ, Mock DB context, issue when transactions are used","<p>I need to write unit testing for legacy code. I'm using MoQ for wring DB Context based unit testing.  One repository method contains saving 2 entities in a transaction.</p>
<p>And when the test execution hit the dbContext.Database.BeginTransaction() it gives the error &quot;No connection string named 'LimaV3DbContext' could be found in the application config file&quot;.</p>
<p>It seems the test trying the execute the actual db context rather than using the mock db context. Is there a way to force the test execution to use the mock db context used in the test initialization.</p>
<p>I've setup the tests based on the following article.</p>
<p><a href=""https://learn.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking</a></p>
",https://stackoverflow.com/questions/68405222/c-unit-testing-moq-mock-db-context-issue-when-transactions-are-used,"['c#', 'unit-testing', 'moq']",457,False,0,0
Unit testing of a function that starts a go routine inside it,"<p>I have a codebase that is roughly as follows</p>
<pre><code>type Service struct {
    Repo                 repo // An interface that contains both FunctionOne and FunctionTwo
    GoRoutineWaitgroup   *sync.WaitGroup
}

func (impl *Service) MyFunction(s string) bool {
    a := impl.Repo.FunctionOne()
    b := impl.Repo.FunctionTwo()
    fmt.Println(&quot;Executed Function One and Function two&quot;)
    go impl.validateMyFunction(a,b)
    return true

}

func (impl *Service) validateMyFunction(a string,b string) {
    defer helpers.PanicHandler()
    impl.GoRoutineWaitgroup.Add(1)
    defer impl.GoRoutineWaitgroup.Done()

    fmt.Println(&quot;a and b are validated&quot;)
}
</code></pre>
<hr />
<p>And I wrote unit tests as something similar to this.</p>
<pre><code>func TestMyFunction(t *testing.T) {

     ms := &amp;Service{}

     test := []struct{
                 input string
                 output bool
                 case string
             }{
                 {&quot;a&quot;, true, sample}
              }
     }

    for _, test := range tests {
        t.Run(test.case, func(t *testing.T) {

            mockRepo := new(mockrepo.Repo) // mockRepo contains mocks of original repo layer methods generated using mockery for testing purposes

            mockRepo.On(&quot;FunctionOne&quot;)
            mockRepo.On(&quot;FunctionTwo&quot;)

            ms.Repo = mockRepo

            op := ms.MyFunction(test.input)
            assert.Equal(t, test.Output, op)
        })
    }

} // Please keep in mind that this is not my actual code, but just a basic structure.
</code></pre>
<p>All tests are successful. But when executing the command <code>go test -v</code>, I saw multiple places in the code where the program panicked and gave <code>invalid memory address or nil pointer dereference</code>. I checked the code in debug mode and realized that the issue is with <code>impl.GoRoutineWaitgroup.Add(1)</code> in method <code>validateMyFunction</code> and when I commented out <code>go validateMyFunction(a,b)</code> and ran tests again, there were no panics in the logs. So How do I solve this issue? How to handle unit tests of functions where we start a goroutine from inside ( as in this case )?</p>
",https://stackoverflow.com/questions/70010794/unit-testing-of-a-function-that-starts-a-go-routine-inside-it,"['unit-testing', 'go', 'concurrency', 'goroutine', 'waitgroup']",2081,True,0,1
How do unit testing on whether data is available oninit from activatedRoute,"<p>Am new to unit testing in angular . We are using jest and don't really know how to make to test whether the route is returning data or not . Am wondering can we do unit testing to check if data is return from the route in angular. Any help much appreciated</p>
<p>In my class component.ts</p>
<pre><code>public data$: Observable&lt;Data&gt;;
  public salariesPerHours: salariesPerHoursViewModel[];

  private destroy$ = new Subject&lt;boolean&gt;();

  constructor(private activatedRoute: ActivatedRoute) {}

  public ngOnInit(): void {

    this.data$ = this.activatedRoute.data;
    this.data$?.pipe(takeUntil(this.destroy$)).subscribe((data: Data) =&gt; {
      this.salariesPerHours= data?.Salary?.salaryPerHour;
    });
  }
</code></pre>
<p>In test class compontent</p>
<pre><code>import { ActivatedRoute, Data } from '@angular/router';
import { salariesPerHoursViewModel,SalaryType } from 'lib/store/store.barrel';
import { Subject } from 'rxjs';

import { SalaryComponent } from './salary.component';

const dataMock: salariesPerHoursViewModel[] = [
  {
      year:2018,
      salaryModifications:[
         {
            date:'2018-02-01T00:00:00',
            type: 'Salary',
            action:[
               {
                  logical :'0212834',
                  label:''
               }
            ]
         },
        ]
  }
]


describe('SalaryComponent', () =&gt; {
  let component: SalaryComponent;
  let activatedRoute: ActivatedRoute;

  beforeEach(() =&gt; {
    activatedRoute = new ActivatedRoute();
    component = new SalaryComponent(activatedRoute);
  });

  describe('ngOnInit', () =&gt; {
    beforeEach(() =&gt; {
      jest.spyOn(component, 'ngOnInit');
    });
   //how to  test if data is coming up
   
  });

  describe('ngOnDestroy', () =&gt; {
    test('should complete the destroy observable', () =&gt; {
      component['destroy$'].next = jest.fn();
      component['destroy$'].complete = jest.fn();

      component.ngOnDestroy();

      expect(component['destroy$'].next).toHaveBeenCalledWith(true);
      expect(component['destroy$'].complete).toHaveBeenCalled();
    });
  });
});

</code></pre>
",https://stackoverflow.com/questions/66763748/how-do-unit-testing-on-whether-data-is-available-oninit-from-activatedroute,"['angular', 'typescript', 'unit-testing', 'rxjs', 'jestjs']",541,False,0,1
Azure Functions (AF) 3.0/.NET 5.0/XUnit Unit Testing - Compilation Errors (C#),"<p>I am trying to adapt the Microsoft example for AF 3.0/.NET Core 3.1/xUnit (see <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-test-a-function"" rel=""nofollow noreferrer"">Strategies for testing your code in Azure Functions</a>) to work with AF 3.0/.NET 5.0/xUnit.  However, I am running into compilation issues.</p>
<p>The Azure Function is a simple HTTP Trigger (GET only), ExportFuncApp.csproj file is as follows:</p>
<pre><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;
  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net5.0&lt;/TargetFramework&gt;
    &lt;AzureFunctionsVersion&gt;v3&lt;/AzureFunctionsVersion&gt;
    &lt;OutputType&gt;Exe&lt;/OutputType&gt;
  &lt;/PropertyGroup&gt;
  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.Functions.Worker.Extensions.Http&quot; Version=&quot;3.0.12&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.Functions.Worker.Sdk&quot; Version=&quot;1.2.0&quot; OutputItemType=&quot;Analyzer&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.Functions.Worker&quot; Version=&quot;1.5.2&quot; /&gt;
  &lt;/ItemGroup&gt;
  &lt;ItemGroup&gt;
    &lt;None Update=&quot;host.json&quot;&gt;
      &lt;CopyToOutputDirectory&gt;PreserveNewest&lt;/CopyToOutputDirectory&gt;
    &lt;/None&gt;
    &lt;None Update=&quot;local.settings.json&quot;&gt;
      &lt;CopyToOutputDirectory&gt;PreserveNewest&lt;/CopyToOutputDirectory&gt;
      &lt;CopyToPublishDirectory&gt;Never&lt;/CopyToPublishDirectory&gt;
    &lt;/None&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;
</code></pre>
<p>The ExportFunc.cs file is as follows:</p>
<pre><code>using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;

namespace ExportFuncApp
{
    public class ExportFunc
    {
        [Function(nameof(ExportFunc))]
        public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;)] HttpRequestData req,
            FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger(&quot;ExportFunc&quot;);
            logger.LogInformation(&quot;C# HTTP trigger function processed a request.&quot;);

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add(&quot;Content-Type&quot;, &quot;text/plain; charset=utf-8&quot;);

            response.WriteString(&quot;Welcome to Azure Functions!&quot;);

            return response;
        }
    }
}
</code></pre>
<p>Nothing special there.  However, XUnit tests provided by Microsoft (.NET Core 3.1) are not really applicable to .NET 5.0.  There was a StackOverflow article on the subject: <a href=""https://stackoverflow.com/questions/67937686/testing-an-azure-function-in-net-5"">Testing an Azure Function in .NET 5</a>.  4 solutions were given in the article and all of them have compile issues.  The first solution given was (ExportFuncUnitTests2.cs):</p>
<pre><code>using Xunit;
using ExportFuncApp;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using Moq;
using Microsoft.Azure.Functions.Worker;
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.Functions.Worker.Http;

namespace ExportFuncAppUnitTestsXunit
{
    public class ExportFuncUnitTests2
    {
        [Fact]
        public async Task Http_trigger_should_return_known_string()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddScoped&lt;ILoggerFactory, LoggerFactory&gt;();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var context = new Mock&lt;FunctionContext&gt;();
            context.SetupProperty(c =&gt; c.InstanceServices, serviceProvider);

            var byteArray = Encoding.ASCII.GetBytes(&quot;test&quot;);
            var bodyStream = new MemoryStream(byteArray);

            var request = new Mock&lt;HttpRequestData&gt;(context.Object);
            request.Setup(r =&gt; r.Body).Returns(bodyStream);
            request.Setup(r =&gt; r.CreateResponse()).Returns(() =&gt;
            {
                var response = new Mock&lt;HttpResponseData&gt;(context.Object);
                response.SetupProperty(r =&gt; r.Headers, new HttpHeadersCollection());
                response.SetupProperty(r =&gt; r.StatusCode);
                response.SetupProperty(r =&gt; r.Body, new MemoryStream());
                return response.Object;
            });

            var result = await ExportFunc.Run(request.Object, context.Object);
            result.HttpResponse.Body.Seek(0, SeekOrigin.Begin);

            // Assert
            var reader = new StreamReader(result.HttpResponse.Body);
            var responseBody = await reader.ReadToEndAsync();
            Assert.NotNull(result);
            Assert.Equal(HttpStatusCode.OK, result.HttpResponse.StatusCode);
            Assert.Equal(&quot;Hello test&quot;, responseBody);
        }
    }
}
</code></pre>
<p>This results in a compilation error in ExportFuncUnitTests2.cs:</p>
<pre><code>CS1061  'HttpResponseData' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'HttpResponseData' could be found (are you missing a using directive or an assembly reference?)
for:
var result = await ExportFunc.Run(request.Object, context.Object);
</code></pre>
<p>The second solution given in the article involves FakeHttpRequestData.cs:</p>
<pre><code>using System;
using System.Collections.Generic;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.Functions.Worker;
using System.IO;
using System.Security.Claims;

namespace ExportFuncAppUnitTestsXunit
{
    class FakeHttpRequestData : HttpRequestData
    {
        public FakeHttpRequestData(FunctionContext functionContext, Uri url, Stream body = null) : base(functionContext)
        {
            Url = url;
            Body = body ?? new MemoryStream();
        }

        public override Stream Body { get; } = new MemoryStream();

        public override HttpHeadersCollection Headers { get; } = new HttpHeadersCollection();

        public override IReadOnlyCollection&lt;IHttpCookie&gt; Cookies { get; }

        public override Uri Url { get; }

        public override IEnumerable&lt;ClaimsIdentity&gt; Identities { get; }

        public override string Method { get; }

        public override HttpResponseData CreateResponse()
        {
            return new FakeHttpResponseData(FunctionContext);
        }
    }
}
</code></pre>
<p>and, FakeHttpResponseData.cs:</p>
<pre><code>using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.Functions.Worker;
using System.Net;
using System.IO;

namespace ExportFuncAppUnitTestsXunit
{
    class FakeHttpResponseData : HttpResponseData
    {
        public FakeHttpResponseData(FunctionContext functionContext) : base(functionContext)
        {
        }

        public override HttpStatusCode StatusCode { get; set; }
        public override HttpHeadersCollection Headers { get; set; } = new HttpHeadersCollection();
        public override Stream Body { get; set; } = new MemoryStream();
        public override HttpCookies Cookies { get; }
    }
}
</code></pre>
<p>And the test is (ExportFuncUnitTests2.cs):</p>
<pre><code>using Xunit;
using ExportFuncApp;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using Moq;
using Microsoft.Azure.Functions.Worker;
using System;
using System.Net;
using Microsoft.Extensions.Logging.Abstractions;

namespace ExportFuncAppUnitTestsXunit
{
    public class ExportFuncUnitTests2
    {
        [Fact]
        public async Task Http_trigger_should_return_known_string()
        {
            // Arrange
            var body = new MemoryStream(Encoding.ASCII.GetBytes(&quot;{ \&quot;test\&quot;: true }&quot;));
            var context = new Mock&lt;FunctionContext&gt;();
            var request = new FakeHttpRequestData(
                           context.Object,
                           new Uri(&quot;https://stackoverflow.com&quot;),
                          body);

            // Act
            var function = new ExportFunc(new NullLogger&lt;ExportFunc&gt;());
            var result = await function.Run(request, context);
            result.HttpResponse.Body.Position = 0;

            // Assert
            var reader = new StreamReader(result.HttpResponse.Body);
            var responseBody = await reader.ReadToEndAsync();
            Assert.NotNull(result);
            Assert.Equal(HttpStatusCode.OK, result.HttpResponse.StatusCode);
            Assert.Equal(&quot;Hello test&quot;, responseBody);
        }
    }
}
</code></pre>
<p>The ExportFuncUnitTests2.cs has the following compilation errors:</p>
<pre><code>CS1729  'ExportFunc' does not contain a constructor that takes 1 arguments
for:
var function = new ExportFunc(new NullLogger&lt;ExportFunc&gt;());
</code></pre>
<p>and</p>
<pre><code>CS1503  Argument 2: cannot convert from 'Moq.Mock&lt;Microsoft.Azure.Functions.Worker.FunctionContext&gt;' to 'Microsoft.Azure.Functions.Worker.FunctionContext'
for:
var result = await function.Run(request, context);
</code></pre>
<p>I the article <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide"" rel=""nofollow noreferrer"">Guide for running C# Azure Functions in an isolated process</a> was somewhat useful but no help in terms of unit testing.  Maybe I am missing the point.  Since there is no examples/documentation on how to do unit testing for AF 3.0 with .NET 5.0 from Microsoft then I should not be trying to do that?</p>
<p>Any pointers will be greatly appreciated.  Thanks!</p>
",https://stackoverflow.com/questions/70119693/azure-functions-af-3-0-net-5-0-xunit-unit-testing-compilation-errors-c,"['unit-testing', 'azure-functions', 'visual-studio-2019', '.net-5', 'xunit']",191,False,0,1
Query regarding unit testing of camel multiple routes within the same class,"<p>I'm having issues unit testing multiple camel routes within the same class.I have a class which contains several route definitions. e.g. as below:</p>
<pre><code>public class A extends RouteBuilder{
    @Override
    public void configure() throws Exception {
        method1();
        method2();
        method3();
        ...
    }
    private void method1() {
        // contains route definitions
        final RouteDefinition route = from(&quot;direcct:&quot;);
        route.id(&quot;ID1&quot;);
        route.setHeader(&quot;&quot;,simple(&quot;&quot;));
        route.to(&quot;direct:B&quot;);
        route.end();
    }
// similarly other methods
}
</code></pre>
<p>i want to unit test each method. so have extended CamelTestSupport. can't override the methods in configure when creating routebuilder since the method are private.
this is what i am doing currently</p>
<pre><code>public class A extends CamelTestSupport {
    private A route;
    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        route = new A();
//can't use below configure since methods are private
    //@Override public void configure() throws Exception {
    //  method1();
    //}

        //logic for mocking and setting endpoints using mockito
        
        return route;
    }
@Test
public void method1_test() throws Exception {
}
}
</code></pre>
<p>I can test one method while commenting others(camelcontext loads and starts all the routes in a class).If i don't comment the test fails.
Also for testing other methods within the same test class i cant use the same createRoutebuilder.So below are the questions:</p>
<ol>
<li>How will i test other methods within the same test class</li>
<li>Is there a way to start and stop routeid so i can test only those routes(tries startroute method but since all the routes are already started it doesn't do anything)</li>
<li>Is there any workaround so that individual methods can be tested
Using camel 3.6, spring boot2 and junit 5</li>
</ol>
",https://stackoverflow.com/questions/67918282/query-regarding-unit-testing-of-camel-multiple-routes-within-the-same-class,"['java', 'unit-testing', 'apache-camel']",295,False,0,0
How to create Unit Testing for filterPredicate function of Angular Material Table,"<p>I am new on AUT and working on this for a week but it seems like my test can't cover the whole function.</p>
<p><strong>Component</strong></p>
<pre><code>import {MatTableDataSource} from '@angular/material/table';
export class AppComponent {
 dataSource = new MatTableDataSource&lt;UserData&gt;([]);
 ...
}
</code></pre>
<p><strong>Function</strong></p>
<pre><code>setupfilter(column: string) :void {
 this.dataSource.filterPredicate = (data: any, filter: string): boolean =&gt; {
  return (
   data[column].toString().toLowerCase().includes(filter)
  );
 }
}
</code></pre>
<p><strong>Test</strong></p>
<pre><code>    let app : AppComponent;
    ...
    it('should call setupfilter() on search',()=&gt;{
    
      let spy1 = spyOn(app, 'setupfilter');
      let spy2 = spyOn(app.dataSource, 'filterPredicate');
    
      app.setupfilter('firstname');
    
      expect(spy1).toHaveBeenCalled();
      expect(spy2).toHaveBeenCalled();
      expect(app.dataSource.filterPredicate.length).toBeGreaterThan(1);
    });
</code></pre>
",https://stackoverflow.com/questions/69878190/how-to-create-unit-testing-for-filterpredicate-function-of-angular-material-tabl,"['angular', 'typescript', 'unit-testing', 'angular-material', 'jasmine']",641,False,0,0
Why it is better to have independent test cases in unit testing?,"<p>In a lot of unit testing frameworks, test cases are independent. For example, GoogleTest says:</p>
<blockquote>
<p>Tests should be <em>independent</em> and <em>repeatable</em>. It’s a pain to debug a test that succeeds or fails as a result of other tests. googletest isolates the tests by running each of them on a different object.</p>
</blockquote>
<p>I don't understand why it is good that test cases are independent. For example, assume an composite object <code>A</code> which uses objects <code>B</code> and <code>C</code>. It is obvious that if <code>B</code> and <code>C</code> are buggy, what <code>A</code> does will be incorrect too, whether it is implemented correctly or not. So I somehow like to see an output like this:</p>
<pre><code>Testing B [SUCCEED]
Testing C [FAILED]
Testing A [FAILED] because dependent test C failed. 
</code></pre>
<p>Do these framework assume that rather than depending these to each other, it is better to test <code>A</code> by mocking <code>B</code> and <code>C</code>? Because sometimes writing correct mocker for your classes can be complex (and buggy itself), so I still think depending tests is better.</p>
",https://stackoverflow.com/questions/70409849/why-it-is-better-to-have-independent-test-cases-in-unit-testing,"['unit-testing', 'testing']",144,True,0,1
NestJS Unit Testing for Controller: Mocking the Delete from Service Not Working,"<p>I am currently unit testing my NestJS Service. My entity is called 'User' and I established a basic Service that allows me to interact with a MS SQL server, with GET and POST endpoints established in my Controller.</p>
<p>I have a <code>delete</code> method in my Controller file that basically just calls the <code>delete</code> method from my Service:</p>
<pre><code>@Injectable()
export class ServiceName {
  constructor(@InjectEntityManager() private manager: EntityManager) {}


  async delete(id: number): Promise&lt;any&gt; {
    return await this.manager.delete(User, id);
  }
// some other functions 

</code></pre>
<p>To test the <code>delete</code> method of my Controller, I mock the same method from the Service. However, when I defined a clear mock return value for the delete method from the service, this mocked return value does not match the return value from the delete method from the Controller, although they should be the same.</p>
<p>Here are my configurations in my spec.ts file:</p>
<pre><code>    const mockService = {
        delete: jest.fn(),
    };

    beforeEach(async () =&gt; { 
        const module: TestingModule = await Test.createTestingModule({
            controllers: [ControllerName],
            providers: [ServiceName],
        })
            .overrideProvider(ServiceName)
            .useValue(mockService) 
            .compile();

        service = module.get&lt;ServiceName&gt;(ServiceName);
        controller = module.get&lt;ControllerName&gt;(ControllerName);
    });
</code></pre>
<p>Here's the test case in my spec.ts file:</p>
<pre><code>        it('testing delete', async () =&gt; {
            mockService.delete.mockReturnValue(5);
            expect(controller.delete(5)).toEqual(5);
        }) 
</code></pre>
<p>The above test case fails, and below is shown the error message:</p>
<pre><code>    expect(received).toEqual(expected) // deep equality

    Expected: 5
    Received: {}

      122 |         it('testing delete', async () =&gt; {
      123 |             mockService.delete.mockReturnValue(5);
    &gt; 124 |             expect(controller.delete(5)).toEqual(5);
          |                                          ^
      125 |         })
      126 |     });
      127 | });
</code></pre>
<p>Any help is greatly appreciated!</p>
",https://stackoverflow.com/questions/67524766/nestjs-unit-testing-for-controller-mocking-the-delete-from-service-not-working,"['typescript', 'unit-testing', 'nestjs']",3161,True,0,1
Unit Testing React Component using ReactBootstrap Modal with a Form Input element,"<p>I've react-bootstrap's Modal component which has an input and when i do the unit test for the Focus, it says it received whole document instead of just the Input element.</p>
<p>Does any one know why the focus went to whole doc(Does Modal make the whole document to have focused). Really appreciate the help. Below is my code</p>
<p>Signup.js</p>
<pre><code>import { Container, Form, Modal } from 'react-bootstrap';

const Signup = () =&gt; {
const handleClick = (e) =&gt; {
  e.preventDefault();
  const element = e.currentTarget;
  const id = element.getAttribute('id');
  if (id === 'userEmail') {
    const emailLabel = document.getElementById('emailLabel');
    emailLabel.style.fontSize = '30px';
  }
};
return (
  &lt;Container&gt;
    &lt;Modal show={true} autoFocus&gt;
      &lt;Modal.Header&gt;Header&lt;/Modal.Header&gt;
      &lt;Modal.Body&gt;
        &lt;Form&gt;
          &lt;Form.Group&gt;
            &lt;Form.Label&gt;
              &lt;span id=&quot;emailLabel&quot;&gt;Email&lt;/span&gt;
              &lt;Form.Control
                name=&quot;userEmail&quot;
                id=&quot;userEmail&quot;
                data-testid=&quot;userEmail&quot;
                type=&quot;email&quot;
                onClick={(e) =&gt; handleClick(e)}
              /&gt;
            &lt;/Form.Label&gt;
          &lt;/Form.Group&gt;
        &lt;/Form&gt;
      &lt;/Modal.Body&gt;
    &lt;/Modal&gt;
  &lt;/Container&gt;
);
};
export default Signup;
</code></pre>
<p>Signup.test.js</p>
<pre><code>import Signup from '.';

describe('helo', () =&gt; {
it('signup', async () =&gt; {
 render(&lt;Signup /&gt;);
 const emailInput = screen.getByTestId('userEmail');
 fireEvent.click(emailInput);
 expect(emailInput).toHaveFocus();
});
});
</code></pre>
<p>Result</p>
<pre><code>
    Expected element with focus:
      &lt;input class=&quot;form-control&quot; data-testid=&quot;userEmail&quot; id=&quot;userEmail&quot; name=&quot;userEmail&quot; type=&quot;email&quot; /&gt;
    Received element with focus:
      &lt;div aria-modal=&quot;true&quot; class=&quot;fade modal show&quot; role=&quot;dialog&quot; style=&quot;display: block;&quot; tabindex=&quot;-1&quot;&gt;&lt;div class=&quot;modal-dialog&quot;&gt;&lt;div class=&quot;modal-content&quot;&gt;&lt;div class=&quot;modal-header&quot;&gt;Header&lt;/div&gt;&lt;div class=&quot;modal-body&quot;&gt;&lt;form class=&quot;&quot;&gt;&lt;div class=&quot;form-group&quot;&gt;&lt;label class=&quot;form-label&quot;&gt;&lt;span id=&quot;emailLabel&quot; style=&quot;font-size: 30px;&quot;&gt;Email&lt;/span&gt;&lt;input class=&quot;form-control&quot; data-testid=&quot;userEmail&quot; id=&quot;userEmail&quot; name=&quot;userEmail&quot; type=&quot;email&quot; /&gt;&lt;/label&gt;&lt;/div&gt;&lt;/form&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;

      123 |     const emailInput = screen.getByTestId('userEmail');
      124 |     fireEvent.click(emailInput);
    &gt; 125 |     expect(emailInput).toHaveFocus();
          |                        ^
      126 |   });
      127 | });
      128 |
</code></pre>
",https://stackoverflow.com/questions/67976072/unit-testing-react-component-using-reactbootstrap-modal-with-a-form-input-elemen,"['unit-testing', 'focus', 'react-bootstrap', 'react-modal', 'react-testing']",969,True,0,2
Why does Panel from System.Web.UI.WebControls.Panel returns null in unit testing using C#?,"<p>I have a designer class with name <code>ExpenseReceipts.aspx.designer.cs</code> in which a partial class ExpenseReciepts contains</p>
<pre><code>public partial class ExpenseReceipts {
    protected global::System.Web.UI.WebControls.Panel ResultPanel;
}
</code></pre>
<p>I have another class ExpenseReceipts.aspx.cs within the module which makes use of this <code>ResultPanel</code>.</p>
<pre><code>public partial class ExpenseReceipts : LayoutsPageBase
{
public void HandleRecordsNotFound()
        {
            ResultPanel.Visible = false;
            NoItemsMessage.Text = &quot;No Items Found!!!&quot;;
            NoItemsMessage.ForeColor = System.Drawing.Color.Red;
            NoItemsPanel.Visible = true;
        }
}
</code></pre>
<p>This works fine as far as the production code goes but the problem arises when I try to write the unit test for the same.
I have the following method trying to shim everything here.</p>
<pre><code>        [TestMethod]
        public void HandleRecordsNotFound_ShouldMakeNoResultPanelVisible()
        {
            using (ShimsContext.Create())
            {
                bool flag = false;

                ShimControl.AllInstances.VisibleSetBoolean = (PANEL, BOOLEAN) =&gt; { };
                ShimLabel.AllInstances.TextSetString = (LABEL, TEXT) =&gt; { };
                ShimWebControl.AllInstances.ForeColorSetColor = (WEBCONTROL, FORECOLOR) =&gt; { };
                ShimControl.AllInstances.VisibleSetBoolean = (CONTROL, BOOLEAN) =&gt; { flag = true; };
                ExpenseReceipts expenseReceipts = new ExpenseReceipts();
                expenseReceipts.HandleRecordsNotFound();
                Assert.IsTrue(flag);
            }
        }
</code></pre>
<p>It FAILS because of the exception thrown in HandleRecordsNotFound saying <code>NUll pointer exception</code> indicating -  <code>ResultPanel</code> is null.</p>
<p>Kindly help me fix this.
Thanks in advance.
PS: I am using Sharepoint 2019.</p>
",https://stackoverflow.com/questions/69989403/why-does-panel-from-system-web-ui-webcontrols-panel-returns-null-in-unit-testing,"['c#', 'sharepoint', 'sharepoint-online', 'sharepoint-designer', 'sharepoint-2019']",63,True,0,1
Unit Testing Angular component with service : Cannot read property &#39;diagonisticData&#39; of undefi,"<p>I am new to angular testing. I have a component, nested json and a service. The app works fine but during testing values are not being populated into the component. Please help.I have attached the service, json object,component and spec file.
I am not sure if I am following the right approach in spec file.
<strong>App component -Hub-Details-component.ts</strong></p>
<pre><code>export class HubDetailsComponent implements OnInit {
ngOnInit(): void {}
public jsonData:any = []
public diagnosticsData:any = [];
public dummy:any = [];
public hubData:any;
constructor(private dataService: DataService) {}
handleData() 
{
  this.dataService.getData()
    .subscribe(response =&gt;{
          if(response!=null)
          {
        this.jsonData=response;
        console.log(this.jsonData);
          this.dummy=this.jsonData.result;
        
        console.log(this.dummy);
          this.diagnosticsData=this.dummy.diagnosticData;
        const DataArray = [];
        for(const element in this.diagnosticsData)
        {

            DataArray.push({
                id:element,
                name:this.diagnosticsData[element]
            });
        }
        console.log(DataArray);
        this.hubData=DataArray;

      }
      });
   }
}
</code></pre>
<p>DataService</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'})
export class DataService {
  public url = '/assets/Data/Data.json'
  constructor(private http: HttpClient ) { }
  getData = () =&gt; {
     const url = 'assets/Data/Data.json';
     return this.http.get(url);
 }}
</code></pre>
<p>json file</p>
<pre><code>{
  &quot;result&quot;
   {
     &quot;abc&quot;
      {
        &quot;name&quot; :&quot;abc&quot;,
        &quot;tag&quot; : &quot;xyz&quot;,
        &quot;status&quot;: &quot;qwe&quot;
      }
   }
 }
</code></pre>
<p>spec.ts</p>
<pre><code>it('should get data from dataservice',fakeAsync(()=&gt;{
const fixture = 
TestBed.createComponent(HubDetailsComponent);
const component = 
fixture.debugElement.componentInstance;
const service = 
fixture.debugElement.injector.get(DataService);
let spy_getPosts = 
spyOn(service,'getData').and.callFake(() =&gt; {
        return of([{&quot;result&quot;{
                          &quot;abc&quot;
                           {
                           &quot;name&quot; :&quot;abc&quot;,
                           &quot;tag&quot; : &quot;xyz&quot;,
                           &quot;status&quot;: &quot;qwe&quot;
                            }
                          }
                       }]).pipe(delay(2000));});
    fixture.detectChanges();
    component.handleData();
    tick(2000);
  
    expect(component.jsonData).toEqual([{
                         {&quot;result&quot;{
                          &quot;abc&quot;
                           {
                           &quot;name&quot; :&quot;abc&quot;,
                           &quot;tag&quot; : &quot;xyz&quot;,
                           &quot;status&quot;: &quot;qwe&quot;
                            }
                          }
                       }
        
    }]);
}));
</code></pre>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/67518188/unit-testing-angular-component-with-service-cannot-read-property-diagonisticd,"['json', 'angular', 'unit-testing', 'karma-jasmine', 'angular-components']",103,False,0,1
Unit testing delete method that is called after mat dialog is closed,"<p>I have a method</p>
<pre><code>  delete(document: IDocument): void {
    const headerMessage = ''
    const message = ''
    const confirm = ''
    const reject = ''

    this.dialogService.openDialog(headerMessage, message, confirm, reject);
    this.dialogService.isClosed().subscribe(confirmed =&gt; {
      if (confirmed &amp;&amp; document.id) {
        this.documentService.delete(document.id).subscribe(() =&gt; {
          this.loadPage();
        });
      } 
    });
  }
</code></pre>
<p>I simply cant test it right.</p>
<p>Unit test is this:</p>
<pre><code> it('should call delete service using confirmDialog',() =&gt; {
      // GIVEN

      const dialogService = TestBed.inject(DialogService);
      jest.spyOn(dialogService.dialogRef, 'afterClosed').mockReturnValue(of({}));
      const result = dialogService.isClosed();
      expect(result instanceof Observable).toBe(true);
      expect(dialogService.dialogRef.afterClosed).toHaveBeenCalled();

      jest.spyOn(service, 'delete').mockReturnValue(of(new HttpResponse({})));

      // WHEN
      comp.delete({ id: 123 });

      // THEN
      expect(service.delete).toHaveBeenCalledWith(123);
    });
</code></pre>
<p>I get error:</p>
<pre><code>Cannot spyOn on a primitive value; undefined given

  139 |
  140 |       const dialogService = TestBed.inject(DialogService);
&gt; 141 |       jest.spyOn(dialogService.dialogRef, 'afterClosed').mockReturnValue(of({}));
</code></pre>
<p>Since I can't just test delete method, I need to mock dialog and delete if its accepted but dont understand the error. Below is the confirm dialog service:</p>
<pre><code>export class DialogService {
  dialogRef!: MatDialogRef&lt;ConfirmationDialogComponent&gt;;
  constructor(private dialog: MatDialog) {}

  openDialog(headerMsg: string, msg: string, confirm: string, reject: string): void {
    this.dialogRef = this.dialog.open(ConfirmationDialogComponent, {
      data: {
        header: headerMsg,
        message: msg,
        buttonText: {
          ok: confirm,
          cancel: reject,
        },
      },
    });
  }

  isClosed(): Observable&lt;any&gt; {
    return this.dialogRef.afterClosed();
  }
}
</code></pre>
<p>So basically, I just need mock that accept is clicked and then check the delete method</p>
",https://stackoverflow.com/questions/69756795/unit-testing-delete-method-that-is-called-after-mat-dialog-is-closed,"['javascript', 'angular', 'unit-testing', 'jestjs']",115,False,0,0
Conditional change of Makefile variable (Application to unit testing of static function),"<p>Originally I wanted to automatically include helpers to unit-test static functions by using <em>--include</em> gcc keyword like described in the link below:</p>
<p><a href=""https://stackoverflow.com/q/593414/3972710"">How to test a static function</a></p>
<p>The idea is to automatically include a foo.cu ( <strong>c</strong>/c++ for <strong>u</strong>nit ) making calls to static functions defined in foo.cc</p>
<p>I read several answers like</p>
<p><a href=""https://stackoverflow.com/q/1077676/3972710"">How to conditional set up a Makefile variable by testing if a file exists</a></p>
<p><a href=""https://stackoverflow.com/q/1909188/3972710"">Define make variable at rule execution time</a></p>
<p><a href=""https://stackoverflow.com/q/5553352/3972710"">How do I check if file exists in Makefile so I can delete it?</a></p>
<p>but syntax like the one below was not successful (even with characters alignment to the target...)</p>
<pre class=""lang-makefile prettyprint-override""><code>#did not work
ifneq ($(wildcard $(UT_FILE_LOC)),)
    $(eval LOC_CPPFLAGS := $(CPPFLAGS) --include $(UT_FILE_LOC))
else
    $(eval LOC_CPPFLAGS := $(CPPFLAGS) )
endif
</code></pre>
<p>and I ended-up with syntax</p>
<pre class=""lang-makefile prettyprint-override""><code>$(eval LOC_CPPFLAGS := $(shell [[ -e $(UT_FILE_LOC) ]] &amp;&amp; echo $(CPPFLAGS) --include $(UT_FILE_LOC) || echo $(CPPFLAGS) ))
</code></pre>
<p><strong>Question:</strong>
Is this a correct way to modify/orientate the value of a makefile variable ?</p>
<p>=========================================================</p>
<p>MCVE for the makefile itself</p>
<pre class=""lang-makefile prettyprint-override""><code>SRCDIR   = src
SRCFILES = $(wildcard src/*.cc)
OBJDIR   = obj
DEPDIR   = dep
OBJFILES = $(patsubst %.cc,$(OBJDIR)/%.o, $(SRCFILES))
DEPFILES = $(patsubst %.cc,$(DEPDIR)/%.d, $(SRCFILES))

#just some flags for this MCVE
CPPFLAGS = -std=c++11 -Wall -Weffc++

main: $(OBJFILES)
    g++ -o $@ $^ 

# Include dependencies ( change in foo.cu are seen )
-include $(DEPFILES)

$(OBJDIR)/%.o: %.cc
    @echo '&gt; Compiling source file: $&lt;'
    @install -d $(OBJDIR)/$(dir $&lt;)
    @install -d $(DEPDIR)/$(dir $&lt;)
    $(eval UT_FILE_LOC  :=  $(patsubst %.cc,%.cu,$&lt;))
    $(eval LOC_CPPFLAGS := $(shell [[ -e $(UT_FILE_LOC) ]] &amp;&amp; echo $(CPPFLAGS) --include $(UT_FILE_LOC) || echo $(CPPFLAGS) ))

    g++ -c $(LOC_CPPFLAGS) -MMD -MP -MF&quot;$(DEPDIR)/$*.d&quot; -o $@ $&lt;

clean:
    $(RM) -r $(OBJDIR)/*
    $(RM) -r $(DEPDIR)/*
</code></pre>
<p>and with basic C++ files (foo.cc, foo.cu and main)</p>
<pre class=""lang-c prettyprint-override""><code>#include &lt;iostream&gt;
static void foo() {
   std::cout &lt;&lt; &quot;foo&quot; &lt;&lt; &quot;\n&quot; &lt;&lt; std::flush;
}

void bar() {  foo(); } //avoid unused foo() warning for this MCVE
</code></pre>
<pre class=""lang-c prettyprint-override""><code>static void foo();

void ut_foo() {
    return foo();
}
</code></pre>
<pre class=""lang-c prettyprint-override""><code>void ut_foo();

int main(int argc, char* argv[]) {
    ut_foo();
    return 0;
}
</code></pre>
<hr />
<p><em>--include src/foo.cu</em> is visible for foo.cc compilation and not for the other files (well, here just the main...).</p>
<pre class=""lang-default prettyprint-override""><code>&gt; Compiling source file: src/foo.cc
g++ -c -std=c++11 -Wall -Weffc++ --include src/foo.cu -MMD -MP -MF&quot;dep/src/foo.d&quot; -o obj/src/foo.o src/foo.cc
&gt; Compiling source file: src/main_unit.cc
g++ -c -std=c++11 -Wall -Weffc++ -MMD -MP -MF&quot;dep/src/main_unit.d&quot; -o obj/src/main_unit.o src/main_unit.cc
g++ -o main obj/src/foo.o obj/src/main_unit.o 

./main 
foo
</code></pre>
<p>Interestingly foo.cu appears in foo.o dependency and a change to foo.cu restart the compilation of foo.c (so no extra work to be done for this point)</p>
<blockquote>
<p>obj/src/foo.o: src/foo.cc src/foo.cu</p>
<p>src/foo.cu:</p>
</blockquote>
<p>=========================================================</p>
",https://stackoverflow.com/questions/68041977/conditional-change-of-makefile-variable-application-to-unit-testing-of-static-f,"['unit-testing', 'makefile']",84,True,0,1
Unit testing with MOQ &amp; EFCore using .Find with composite primary key,"<p>I am trying to figure out a way to be able to moq the EF Core 'Find' functionality using a composite primary key. A work colleague has pointed in one direction which does appear to work but I am wondering if there is a better solution?</p>
<p>This is what I have so far.</p>
<p>I have a factory class for creating a mock DB set. I am creating the DB set from a list objects that have this structure;</p>
<pre><code>public int FK { get; set; }
public string SourceId { get; }
public string EntityName { get; set; }
public int? EntityKey { get; set; }
public string IdLong { get; set; }
</code></pre>
<p>The primary key consists FK, EntityName &amp; SourceId.</p>
<p>This is how I am currently creating my DBSet</p>
<pre><code>  var assocMock = EFCoreFactory.CreateMockDBSet(new List&lt;AData&gt; { obj1, obj2});


  // Map the associated data for the EF .Find to work
  assocMock.Setup(m =&gt; m.Find(It.Is&lt;object[]&gt;(mm =&gt;
     mm[0] as int? == obj1.FK &amp;&amp;
     mm[1].ToString() == obj1.EntityName &amp;&amp;
     mm[2].ToString() == obj1.SourceId
    ))).Returns(obj1);

  assocMock.Setup(m =&gt; m.Find(It.Is&lt;object[]&gt;(mm =&gt;
     mm[0] as int? == obj2.FK &amp;&amp;
     mm[1].ToString() == obj2.EntityName &amp;&amp;
     mm[2].ToString() == obj2.SourceId
    ))).Returns(obj2);

  EFCoreFactory.CreateMockSet&lt;AData&gt;(context, assocMock.Object);
</code></pre>
<p>Can anybody suggest any better or more generic way to do this?</p>
<p><strong>UPDATE</strong> based on the link provided by Shafiq below this is my latest attempt which I think is a bit more generic and wont require me to map each individual object. Can anybody see any flaw in this approach?</p>
<pre><code>  assocMock.Setup(m =&gt; m.Find(It.IsAny&lt;object[]&gt;()))
           .Returns&lt;object[]&gt;(ad =&gt; assocDataList.FirstOrDefault(d =&gt; d.FK == (int)ad[0] &amp;&amp;
                                                                      d.EntityName == ad[1].ToString() &amp;&amp;
                                                                      d.SourceId == ad[2].ToString()))
</code></pre>
",https://stackoverflow.com/questions/66078683/unit-testing-with-moq-efcore-using-find-with-composite-primary-key,"['entity-framework', 'unit-testing', 'entity-framework-core', 'moq']",198,False,0,1
Mocking only two methods in class for unit testing Moq and XUnit,"<p>Hope you are doing great.</p>
<p>WE have service which calls method  <code>GetUserAccountNo()</code>   in  turn call other two (<code>GetUser</code>, <code>CreateUser</code>) in that service .
we are using Moq and XUnit for testing
Can anybody let me know how can I mock only the <code>GetUser</code> and <code>CreateUser</code> and write unit test for the <code>GetUserAccountNo</code>?</p>
<p>I can see some people saying about making the methods as <code>virtual</code>.
Here in  this case all the methods are in same class and from same interface and <code>public</code> as well</p>
<p>Please find the code snippet</p>
<pre><code>public int GetUserAccountNo (string id)
{
    if (GetUser(id)!=null )
    {
        return GetUser(id).AccountNo;
    }
    else
    {
        return CreateUser(id).AccountNo;
    }
}


public User GetUser(string id)
{
    //Get from  userAPi
    return new User();
}

public User CreateUser(string id)
{
    //Create from userAPi using  http request
    return new User();
}
</code></pre>
",https://stackoverflow.com/questions/69591516/mocking-only-two-methods-in-class-for-unit-testing-moq-and-xunit,"['c#', 'unit-testing', 'moq', 'xunit']",1739,False,0,1
Unit Testing LifeCycle Throws NPE after adding AndroidX Fragment and Activity dependencies,"<p>(Self answered below)</p>
<p>I have numerous unit tests that involve using the lifecycle arch components, where the life cycle was registered in the init block of the object</p>
<pre><code>class someClass(lifeCycle: Lifecycle) {
    
    init {
        lifecycle.addObserver(this)
    }
 ...
}
</code></pre>
<p>And in the test they are setup like this</p>
<pre><code>@Before
override fun setup() {
    super.setup()

    lifecycleOwner = mock()
    lifecycle = LifecycleRegistry(lifecycleOwner)
...
}
</code></pre>
<p>Everything was working until I added these two dependencies and now every unit test in these files are throwing exceptions</p>
<pre><code>implementation &quot;androidx.activity:activity-ktx:1.2.2&quot;
implementation 'androidx.fragment:fragment-ktx:1.3.3'

java.lang.NullPointerException
at androidx.arch.core.executor.DefaultTaskExecutor.isMainThread(DefaultTaskExecutor.java:77)
at androidx.arch.core.executor.ArchTaskExecutor.isMainThread(ArchTaskExecutor.java:116)
at androidx.lifecycle.LifecycleRegistry.enforceMainThreadIfNeeded(LifecycleRegistry.java:316)
at androidx.lifecycle.LifecycleRegistry.addObserver(LifecycleRegistry.java:172)
</code></pre>
",https://stackoverflow.com/questions/67323540/unit-testing-lifecycle-throws-npe-after-adding-androidx-fragment-and-activity-de,['android'],404,True,0,1
Returning a Promise from &quot;describe&quot; is not supported In Nestjs Unit testing,"<p>I want to do unit testing of service in nestjs using mongoose.
This error comes up at the end</p>
<blockquote>
<p>Returning a Promise from &quot;describe&quot; is not supported. Tests must be defined synchronously.</p>
</blockquote>
<blockquote>
<p>Returning a value from &quot;describe&quot; will fail the test in a future version of Jest.</p>
</blockquote>
<p><img src=""https://i.stack.imgur.com/PGSai.png"" alt=""enter image description here"" /></p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { MongooseModule } from '@nestjs/mongoose';

import { closeInMongodConnection, rootMongooseTestModule } from '../test-utils/mongo/MongooseTestModule';
import { UserSchema } from './user.model';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

describe('UserController', async () =&gt; {
  let controller: UsersController;
  let service: UsersService;

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      imports: [rootMongooseTestModule(), MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],
      controllers: [UsersController],
      providers: [UsersService],
    }).compile();

    controller = module.get&lt;UsersController&gt;(UsersController);
    service = module.get&lt;UsersService&gt;(UsersService);
  });

  it('should be defined', () =&gt; {
    expect(controller).toBeDefined();
  });

  it('should return all the events', async () =&gt; {
    const result = {
      totalDocs: 0,
      resource: [],
    };

    const data = await service.findAll();
    expect(data).toEqual(result);
  });
  

  afterAll(async () =&gt; {
    await closeInMongodConnection();
  });
});
</code></pre>
<p><img src=""https://i.stack.imgur.com/bs1oz.png"" alt="""" /></p>
",https://stackoverflow.com/questions/66744886/returning-a-promise-from-describe-is-not-supported-in-nestjs-unit-testing,"['javascript', 'node.js', 'unit-testing', 'testing', 'nestjs']",2243,True,0,1
Angular Unit Testing - How to test a service which creates a Websocket,"<p>I need to write a unit test for the following code:</p>
<pre class=""lang-js prettyprint-override""><code>getSomething(id: string): Observable&lt;State | null&gt; {
  return new WebSocketSubject(webSocket(`ws://&lt;websocket&gt;`)
    .pipe(
      catchError(err =&gt; {
        console.error('Error in WebSocket connection: ', err);
        return concat(
          of(null),
          throwError(err)
        );
      }),
      retryWhen(errors =&gt;
        errors.pipe(
          delay(1000)
        )
      )
    )
  );
}
</code></pre>
<p>I would like to write two tests to:</p>
<ul>
<li>check if the websocket is created;</li>
<li>generate the error in websocket connection to achieve a good coverage.</li>
</ul>
<p>I wrote first test as below but I don't know what to expect here:</p>
<pre class=""lang-js prettyprint-override""><code>it('should get Something create websocket', () =&gt; {
  service.getSomething('test').subscribe(
    data =&gt; expect(data).toBeInstanceOf(webSocket),
      fail
  ); 
});  
</code></pre>
<p>Your inputs are welcome. Thanks.</p>
",https://stackoverflow.com/questions/69948522/angular-unit-testing-how-to-test-a-service-which-creates-a-websocket,"['angular', 'unit-testing', 'karma-jasmine']",175,False,0,1
"Unit testing using Karma, Jasmine facing issue in Interface based Dependency Injection","<p>I am new to Jasmine, Karma testing. I was facing issue in writing the one of the test cases for service named AuthRealService which injected using an interface name AuthService into component LoginComponent.</p>
<p>here is AuthService interface</p>
<pre><code>import { Observable } from 'rxjs';

export const AUTH_SERVICE = 'AUTH_SERVICE';
export interface AuthService {
  doAuthenticate(loginUser: any): Observable&lt;any&gt;;
}
</code></pre>
<p>here is my Real Service</p>
<pre><code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { SERVICE_URL } from 'src/app/shared/constants/service.constants';
import { ApiService } from 'src/app/shared/services/api.service';

import { AuthService } from './auth.service';

@Injectable()
export class AuthRealService implements AuthService {
  constructor(private apiService: ApiService) {}

  doAuthenticate(loginUser: any): Observable&lt;any&gt; {
    return this.apiService.post(SERVICE_URL.GET_DIRECT_LOGIN_URL, loginUser);
  }
}
</code></pre>
<p>Here is Mock Service</p>
<pre><code>import { Injectable } from '@angular/core';
import { of } from 'rxjs';
import { Observable } from 'rxjs';
import { delay } from 'rxjs/operators';

import { AuthService } from './auth.service';

@Injectable()
export class AuthMockService implements AuthService {
  doAuthenticate(): Observable&lt;any&gt; {
    const MockSuccessResponse = {
      status: 'SUCCESS',
      data: [
        {
          status: 'Good'
        }
      ]
    };
    return of(MockSuccessResponse).pipe(delay(100));
  }
}
</code></pre>
<p>The LoginComponent is here</p>
<pre><code>import { Component, Inject, OnInit, ViewContainerRef } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NgxSpinnerService } from 'ngx-spinner';
import { APP_CONST } from 'src/app/shared/constants/app.constants';
import {
  COMMON_API_SERVICE,
  CommonApiService
} from 'src/app/shared/services/common-api.service';
import { CommonService } from 'src/app/shared/services/common.service';

import { VoyaPayCloudGlobalState } from 'src/app/shared/store/our-global.store';

import { ToastrService } from '../../../shared/services/toastr.service';
import { AUTH_SERVICE, AuthService } from '../../login/services/auth.service';

const noop = () =&gt; {};

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  isLabelHidden: boolean;
  errorCount = 0;
   _onTouchedCallback: (_: any) =&gt; void = noop;
   _onChangeCallback: (_: any) =&gt; void = noop;
  public loginFail;
  constructor(
    @Inject(AUTH_SERVICE) private authService: AuthService,
    @Inject(COMMON_API_SERVICE) private commonApiService: CommonApiService,
    private commonService: CommonService,
    private router: Router,
    private toastrService: ToastrService,
    private spinner: NgxSpinnerService,
    vcr: ViewContainerRef
  ) {
    this.toastrService.toastr.setRootViewContainerRef(vcr);
  }

  ngOnInit() {
    //Form intialization is done here
  }

  onSubmit() {
    //implmented after submit functionality here
  }

  login(): void {
  //implemented login functionality here
}
</code></pre>
<p>here is testing spec file</p>
<pre><code>  HttpClient,
  HttpClientModule,
  HttpHeaders,
  HttpParams
} from '@angular/common/http';
import { DebugElement, ViewContainerRef } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserModule, By } from '@angular/platform-browser';
import { Router, RouterModule } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { NgxSpinnerService } from 'ngx-spinner';
import { AppComponent } from 'src/app/app.component';
import { TextboxComponent } from 'src/app/shared/components/form/voya-textbox/voya-textbox.component';
import { SpinnerComponent } from 'src/app/shared/components/layout/spinner/spinner.component';
import { OurRoutingModule } from 'src/app/shared/modules/our-routing.module';
import { ApiService } from 'src/app/shared/services/api.service';
import { CommonApiRealService } from 'src/app/shared/services/common-api-real.service';
import { COMMON_API_SERVICE } from 'src/app/shared/services/common-api.service';
import { CommonService } from 'src/app/shared/services/common.service';
import { ToastrService } from 'src/app/shared/services/toastr.service';
import { AuthRealService } from '../services/auth-real.service';
import { AUTH_SERVICE } from '../services/auth.service';
import { LoginComponent } from './login.component';

fdescribe('LoginComponent', () =&gt; {
  let component: LoginComponent;
  let fixture: ComponentFixture&lt;LoginComponent&gt;;
  let submitElement: DebugElement;
  let userNameElement: DebugElement;
  let passwordElement: DebugElement;
  let authRealServiceSpy: jasmine.SpyObj&lt;AuthRealService&gt;;
  beforeEach(() =&gt; {
    const authRealServiceSpyObj = jasmine.createSpyObj('AuthRealService', [
      'doAuthenticate'
    ]);
    TestBed.configureTestingModule({
    
      declarations: [LoginComponent, SpinnerComponent, TextboxComponent],
      imports: [
        BrowserModule,
        HttpClientModule,
        RouterTestingModule,
        OurRoutingModule
      ],
      providers: [
        { provide: AuthRealService, useValue: authRealServiceSpyObj },
        ApiService,
        HttpClient,
        { provide: COMMON_API_SERVICE, useClass: CommonApiRealService },
        CommonService,
        Router,
        ToastrService,
        NgxSpinnerService,
        ViewContainerRef
      ]
    });

    //create component test fixture
    fixture = TestBed.createComponent(LoginComponent);

    authRealServiceSpy = TestBed.inject(AuthRealService);

    //get the test component from the fixture
    component = fixture.componentInstance;
  });


});

</code></pre>
<p>In the Above spec file i was trying to <code>authRealServiceSpy = TestBed.inject(AuthRealService);</code>
its saying &quot;Type 'AuthRealService' is not assignable to type 'SpyObj'.&quot;</p>
<p>I was referring to this solution <a href=""https://stackoverflow.com/questions/61960557/how-to-handle-dependency-injection-into-angular-unit-test-using-jasmine"">How to handle dependency injection into Angular unit test using Jasmine?</a></p>
<p>Can anyone please help me out to resolve this issue, early replies appreciated.
Thanks in advance.</p>
",https://stackoverflow.com/questions/68361473/unit-testing-using-karma-jasmine-facing-issue-in-interface-based-dependency-inj,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-runner']",332,False,0,1
Managing migration of large number of fixtures in Django for unit testing,"<p>I currently have one fixture for all my tests for my Django application. It is fine however updating units tests each time I add a new object to my fixture is tedious.</p>
<ul>
<li>Objects count and equality of query set have to be updated.</li>
<li>Many &quot;get&quot; methods fail when duplicate appears for various reasons.</li>
<li>Having a dataset filled with every possible use case for each unit test seems like a bad practice.</li>
</ul>
<p>So I would like to have a fixture for each component of the app to test, e.g. if I have a model class &quot;MyModel&quot;, it has a dedicated TestCase all its functionalities have unit tests and I would like them to have a dedicated fixture. The main interest would be that I automatically solve all three points mentioned above.</p>
<p>However, it has some drawbacks</p>
<ul>
<li>File management, I copy a directory into Django's data directory for my fixture, I would need to manage multiple data directories.</li>
<li>Redundance of some fixtures elements. Many elements rely on the existence of other elements up to the user object, each fixture would need a prefilled database with some common objects (e.g. configured user)</li>
<li>Django migrations.</li>
</ul>
<p>The two first points are not the real problem but the task of migrating fixtures alongside my codebase looks like hell, It is already hard to manage for one fixture <a href=""https://stackoverflow.com/questions/4002322/migrating-django-fixtures"">this post</a> explains how to manage code, migrations, database state, and a fixture. But this seems like too much if I have to do it for every fixture of every test.</p>
<p>Is there some clean way out there to migrate fixtures as you migrate the database?</p>
<p>PS: If it matters, I am using Django 3.2 with Django-rest-framework</p>
",https://stackoverflow.com/questions/68768567/managing-migration-of-large-number-of-fixtures-in-django-for-unit-testing,"['python', 'django', 'fixtures', 'django-unittest']",181,False,0,0
"PHP Unit testing is not compatible with PHP8, does it support backward compatibility?","<p>I have several test units in PHPUnit and the PHPUnit is not compatible with php8. I`m looking for a way to run old tests on PHP8.
Is there any wrapper for PHPUnit to work with PHP8?</p>
<p>By the way, this is the error from the composer install:</p>
<pre><code>    - phpunit/phpunit 9.1.1 requires php ^7.3 -&gt; your PHP version (8.0.1) does not satisfy that requirement.
</code></pre>
<p>It may work by removing the requirement from the PHPUnit composer file.</p>
",https://stackoverflow.com/questions/65923491/php-unit-testing-is-not-compatible-with-php8-does-it-support-backward-compatibi,"['php', 'phpunit', 'php-8']",7510,True,4,1
"Unit-Testing, DbContext mocking Async throw InvalidOperationException: The source IQueryable doesn&#39;t implement IDbAsyncEnumerable","<p>Follow instructions from <a href=""https://learn.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking"" rel=""nofollow noreferrer"">Testing with a mocking framework</a>, <strong>I can mock Async function for DBSet like CountAsync...</strong>, but exception <em>&quot;InvalidOperationException: The source <code>IQueryable</code> doesn't implement <code>IDbAsyncEnumerable&lt;OrderSummary&gt;</code>&quot;</em> is throwed when I write to return with anonymous or custom type. Any solution to perform it?</p>
<p>My mocking</p>
<pre><code>public class DbContextBuilderFixture : IDisposable
{
    protected readonly Mock&lt;DbSet&lt;Item&gt;&gt; MockDbSetItem  = new Mock&lt;DbSet&lt;Item&gt;&gt;();
    public DbContextBuilderFixture()
    {

    }

    public ShopingContext Build()
    {
        var mockContext = new Mock&lt;ShopingContext&gt;();

        mockContext.Setup(t=&gt;t.Items).Returns(() =&gt; MockDbSetItem.Object);

        return mockContext.Object;
    }


    public Mock&lt;DbSet&lt;Item&gt;&gt; WithItems(List&lt;Item&gt; items)
    {
        var data = stockTakes.AsQueryable();

        MockDbSetItem.As&lt;IDbAsyncEnumerable&lt;Item&gt;&gt;()
            .Setup(m =&gt; m.GetAsyncEnumerator())
            .Returns(new DbAsyncEnumeratorHelper&lt;Item&gt;(data.GetEnumerator()));

        MockDbSetItem.As&lt;IQueryable&lt;Item&gt;&gt;()
            .Setup(m =&gt; m.Provider)
            .Returns(new DbAsyncQueryProviderHelper&lt;Item&gt;(data.Provider));
        
        MockDbSetItem.As&lt;IQueryable&lt;Item&gt;&gt;().Setup(m =&gt; m.Expression).Returns(data.Expression);
        MockDbSetItem.As&lt;IQueryable&lt;Item&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(data.ElementType);
        MockDbSetItem.As&lt;IQueryable&lt;Item&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(data.GetEnumerator());

        return MockDbSetItem;
    }

    public void Dispose()
    {
        MockDbSetItem?.Invocations.Clear();
        MockDbSetItem?.Reset();
    }
}

</code></pre>
<p>My code (Entity Framework 6.0):</p>
<pre><code>Public Taks&lt;Dictionary&lt;int, OrderSummary&gt; GetOrderSummaryAsync()
{
    return await Db.Items
    .GroupBy(
        i =&gt; i.OrderId,
        i =&gt; new 
        {
            i.SubTotal,
            i.Quantity
        },
        (key, g) =&gt; new OrderSummary
        {
            Id = key,
            Total = g.Sum(i =&gt; i.SubTotal),
            TotalCount = g.Sum(i =&gt; i.Quantity)
        })
    .ToDictionaryAsync(i =&gt; i.Id);
}
</code></pre>
<p>My Unitest</p>
<pre><code>[Fact]
public void GetOrderSumamry_ShouldCorrectTotalCount()
{
    //arrange
    var listItem = new List&lt;Item&gt;
    {
        BuilderItem.Default()
            .WithId(1)
            .WithOrderId(1)
            .WithCreatedDate(new DateTime(2021, 10, 20))
            .WithSubTotal(1000)
            .WithQuantity(200)
            .Build(),

        BuilderItem.Default()
            .WithId(2)
            .WithOrderId(1)
            .WithCreatedDate(new DateTime(2021, 10, 21))
            .WithSubTotal(1000)
            .WithQuantity(200)
            .Build()
    };
    
    DbContext.WithItems(listItem);
   
    var itemService = new ItemService(DbContext.Build());

    //action
    /*
    exception &quot;InvalidOperationException: The source IQueryable doesn't 
    implement IDbAsyncEnumerable&lt;OrderSummary&gt;&quot;
    */
    var orderSummaryDict = itemService.GetOrderSummaryAsync().Result;

    //actual
    orderSummaryDict[1].TotalCount.Should().Be(400);
}

</code></pre>
",https://stackoverflow.com/questions/69743456/unit-testing-dbcontext-mocking-async-throw-invalidoperationexception-the-sourc,"['c#', 'entity-framework', 'unit-testing', 'mocking', 'moq']",218,False,2,0
XCTMemoryMetric not recording memory in iOS Unit Testing bundle in Xcode 12.5 (XCTest),"<h3>Background</h3>
<p>I have implemented a <code>Swift</code> algorithm in which I want to consume low memory at runtime (Space Complexity). So, I wanted to write performance tests using <code>XCTMemoryMetric</code> as part of a &quot;Unit Testing Bundle&quot; for large input sizes. I need to track regressions and optimisations for this algorithm, so I wanted initially to track the baseline metrics and expected this to work out of the box for my iOS app. Unfortunately, even after reading the Apple documentation for <a href=""https://developer.apple.com/documentation/xctest/performance_tests?language=swift"" rel=""nofollow noreferrer"">Performance Tests</a>, I haven't found any potential fixes or information to help me resolve my particular issue.</p>
<p>I am using an iOS Base SDK for my main target (<code>UIKit</code> and <code>Storyboard</code>) and the same Base SDK for my &quot;Unit Testing Bundle&quot; in Xcode. In Xcode, I have left the default &quot;Build active architecture only&quot; setting to &quot;Yes&quot;, and the main target compiles as well, and the tests compile fine. However, when I finish running the <code>measure</code> block with an <code>XCTMemoryMetric()</code> and <code>XCTClockMetric()</code> added as the only parameters, the Memory metrics don't show up in the test report. The Clock metrics are also completely unreliable, and my test fails (almost) every time due to high standard deviations even with the same function! Anyway, this question is focused on the memory metric.</p>
<p><strong>Example of successful compilation:</strong>
<a href=""https://i.stack.imgur.com/XVUwI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/XVUwI.png"" alt=""example of successful compilation"" /></a></p>
<p><strong>Note:</strong> I have also tried other metrics like <code>XCTCPUMetric</code> for performance testing, which doesn't show results either.</p>
<p><strong>Example of missing memory metrics:</strong>
<a href=""https://i.stack.imgur.com/VFMUW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VFMUW.png"" alt=""example of missing memory metrics"" /></a></p>
<p>I don't get warning messages in the console or exceptions.</p>
<h3>What I've tried:</h3>
<ol>
<li>Moving the algorithm to a <code>Swift Package Target</code> and moving performance tests to a <code>Package Unit Testing Bundle</code> - the memory metric shows up in the test logs. Still, it is highly unreliable (sometimes showing even <strong>negative</strong> memory allocation 😂!). This solution is not ideal since I don't want to create a package just for a single algorithm.</li>
<li>Moving the algorithm to a <code>Mac-only Target</code> with correlated <code>Unit Testing Bundle</code> - works but again not appropriate for an iOS-only app.</li>
<li>Debugging using <code>metric.reportMeasurements()</code> shows a missing <code>_data</code> parameter in the metric and crashes at runtime:</li>
</ol>
<p><a href=""https://i.stack.imgur.com/Hkk3N.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Hkk3N.png"" alt=""example of runtime crash when reporting"" /></a></p>
<ol start=""4"">
<li>Running individual test cases instead of the whole suite didn't make a difference.</li>
<li>Testing even larger input array sizes didn't make a difference.</li>
</ol>
<p>Is there any clean way I can resolve my issue without changing my Base SDK? I am considering abandoning <code>XCTest</code> for performance testing since it doesn't seem to work very well, but ideally, I'd like to stick with Apple's recommended APIs.  You can also see the code seems to run completely on Stack Memory (no <code>static let</code>s or <code>var</code>s), so I don't think the confusion between Stack and Heap Memory is the root cause.</p>
<h3>Code:</h3>
<p>I've posted a <a href=""https://gist.github.com/LemonSpike/0e869a6df291190a34322a0bfbf19726"" rel=""nofollow noreferrer"">gist</a> of the algorithm I'm performance testing since the code is too many lines to include here. Even with other (less memory-intensive) code inside the <code>measure</code> block, the issue is reproducible for me.</p>
<p>The test code:</p>
<pre><code>func testPerformanceExample() {
    let metric = XCTMemoryMetric()
    measure(metrics: [metric],
            block: {
      var sums: [[[Int]]] = []
      (1...100).forEach { _ in
        sums.append(QOneSolutionOne().fourSum([1, 0, -1, 0, -2, 2, 3, -3, 0, 4,
                                               -2, 5, -4, 6, -6, 7, -8, 8, -7],
                                              target: 0))
      }
    })
  }
</code></pre>
<p>I think this may be an <code>XCTest</code> bug, but I wanted to see if I am missing something. Open to any advice, thanks.</p>
",https://stackoverflow.com/questions/67359955/xctmemorymetric-not-recording-memory-in-ios-unit-testing-bundle-in-xcode-12-5-x,"['ios', 'swift', 'xcode', 'unit-testing', 'xctest']",750,False,2,0
How to mock array data with object for unit testing in Angular 8,"<p>I would like to write a unit test to test if the <code>expectedData</code> is showing as expected. The HTML code is working and it displays everything correctly.</p>
<p>HTML code:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;div class=""col-6 p-0 LHS"" *ngIf=""data &amp;&amp; data.type === 'App'""&gt;
  &lt;div *ngFor=""let d of data""&gt;
    &lt;div class=""row""&gt;
      &lt;div class=""col-auto""&gt;Item1:&lt;/div&gt;
      &lt;div class=""appItem1""&gt;{{d.item1}}&lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;</code></pre>
</div>
</div>
</p>
<p>TS file:</p>
<pre><code>  data = [{item1: &quot;Item 1&quot;, item2: &quot;Item 2&quot;}, type: &quot;App&quot;, display: true]; // sample input data
  expectedData;

  getExpectedData() {
    if (this.data &amp;&amp; this.data.item) {
      switch (this.data.type) {
        case (&quot;File&quot;):
           this.expectedData = $('.fileItem1')[0].innerHTML;  
          break;
        case (&quot;App&quot;):
          this.expectedData = $('.appItem1')[0].innerHTML;              
          break;
      }
    }
  }
</code></pre>
<p>My test case:</p>
<pre><code>it('should verify expected data', () =&gt; {
    const mockdata= [{item1: &quot;Item 1&quot;}];
    mockdata.type= 'App'; // getting error because this can't be pushed to array
    mockdata.display= true; // getting error because this can't be pushed to array
    component.data = mockdata;
    fixture.detectChanges();
    component.getExpectedData();
    expect(component.expectedData).toBe(&quot;Item 1&quot;);
  });
</code></pre>
<p>However, in my test case, it doesn't seem to be working to mock the data to that type of data, are there any possible way to test the <code>getExpectedData()</code>?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/65600266/how-to-mock-array-data-with-object-for-unit-testing-in-angular-8,"['arrays', 'angular', 'unit-testing']",5823,True,1,1
How to exclude helper projects with &quot;Test&quot; in their name from unit testing?,"<p>We have a utility project named <code>Foo.Testing.Common</code> with helper classes for our real test projects, named things like <code>Foo.Tests.Unit</code> and <code>Foo.Tests.Integration</code>. The Common project doesn't have tests, just base classes, utility methods and the like. It references XUnit so I can use <code>Xunit.Abstractions</code>.</p>
<p>How can we avoid seeing errors like the one below when we run all tests, either via .net command line or VS Test Explorer? The below error appears in VS Test Output during test discovery, for example.</p>
<pre><code>No test is available in C:\Foo.Testing.Common\bin\Debug\netcoreapp3.1\Foo.Testing.Common.dll. Make sure that test discoverer &amp; executors are registered and platform &amp; framework version settings are appropriate and try again.
Microsoft.VisualStudio.TestPlatform.ObjectModel.TestPlatformException...
</code></pre>
<p>I assume the test process is matching on <em>test</em> to find test projects and then throws an error if one of those projects has no tests. Or maybe it's looking for projects that reference any xunit packages?</p>
<p>We could just rename the project, but is there a different way? Would like to avoid passing a list of specific test projects to the command line just to avoid the &quot;no tests found&quot; warnings. That is, <code>dotnet test</code> should just work.</p>
<p>Update: I've also tried referencing just <code>xunit.abstractions</code> and <code>xunit.extensibility.core</code> rather than the main <code>xunit</code> package, but the Common project still gets recognized as a test project.</p>
<p>Also tried setting <code>IsTestProject</code> to false in the project properties.</p>
",https://stackoverflow.com/questions/68502125/how-to-exclude-helper-projects-with-test-in-their-name-from-unit-testing,"['c#', 'visual-studio', '.net-core', 'xunit', 'xunit.net']",1533,True,1,1
Acess two different lists with the same type of objects in unit testing,"<p>If I can explain my problem, these are two methods, a test method and its target:</p>
<h3>Test method</h3>
<pre><code>[Fact]
public async Task Create_Post_Valid_Id_Valid_Name()
{
#region Arrange
    var model = new FixedShippingScheduleEditViewModel{Id = 10, Name = &quot;Schedule&quot;};
    var schedules = new List&lt;Hyper360FixedShippingScheduleSummaryModel&gt;()
    {new Hyper360FixedShippingScheduleSummaryModel{Id = 11, Name = &quot;AnotherSchedule&quot;}};
    var refreshedSchedules = new List&lt;Hyper360FixedShippingScheduleSummaryModel&gt;()
    {new Hyper360FixedShippingScheduleSummaryModel{Id = 10, Name = &quot;Schedule&quot;}};
    _shippingApiClient.Setup(x =&gt; x.GetAllFixedSchedules(CancellationToken.None)).Returns(Task.FromResult((IList&lt;Hyper360FixedShippingScheduleSummaryModel&gt;)schedules));
    _shippingApiClient.Setup(x =&gt; x.CreateFixedSchedule(It.Is&lt;FixedShippingScheduleEditModel&gt;(s =&gt; s.Name == &quot;Schedule&quot;), CancellationToken.None)).Returns(Task.CompletedTask);
    _shippingApiClient.Setup(x =&gt; x.GetAllFixedSchedules(CancellationToken.None)).Returns(Task.FromResult((IList&lt;Hyper360FixedShippingScheduleSummaryModel&gt;)refreshedSchedules));
    _localizationService.Setup(x =&gt; x.GetResource(&quot;Bizay.Logistic.Admin.Schedules.Notification.Create.Error&quot;)).Returns(&quot;Success&quot;);
    _notificationService.Setup(x =&gt; x.SuccessNotification(&quot;Success&quot;, true));
#endregion
#region Act
    var result = await _scheduleController.Create(model, true, CancellationToken.None);
#endregion
#region Assert
    result.Should().BeOfType&lt;ViewResult&gt;();
    ((ViewResult)result).Model.Should().BeOfType&lt;FixedShippingScheduleEditViewModel&gt;();
    ((FixedShippingScheduleEditViewModel)((ViewResult)result).Model).Name.Should().Be(&quot;AnotherSchedule&quot;);
    ((FixedShippingScheduleEditViewModel)((ViewResult)result).Model).Id.Should().Be(11);
#endregion
}
</code></pre>
<h3>Tested method</h3>
<pre><code>[HttpPost]
[ValidateAntiForgeryToken]
[HttpPost, ParameterBasedOnFormName(&quot;save-continue&quot;, &quot;continueEditing&quot;)]
public async Task&lt;ActionResult&gt; Create(FixedShippingScheduleEditViewModel model, bool continueEditing, CancellationToken cancellationToken)
{
    var schedules = await _shippingApiClient.GetAllFixedSchedules(cancellationToken);
    if (schedules.Any(s =&gt; s.Name.Equals(model.Name, StringComparison.InvariantCultureIgnoreCase)))
    {
        ModelState.AddModelError(nameof(model.Name), _localizationService.GetResource(&quot;Bizay.Logistic.Admin.Schedules.Error.Name.Repeated&quot;));
    }
    if (ModelState.IsValid)
    {
        await _shippingApiClient.CreateFixedSchedule(new FixedShippingScheduleEditModel { Name = model.Name }, cancellationToken);

        var refreshedSchedules = await _shippingApiClient.GetAllFixedSchedules(cancellationToken);
        var schedule = refreshedSchedules?.FirstOrDefault(s =&gt; s.Name == model.Name);

        if (schedule == null)
        {
            _notificationService.ErrorNotification(_localizationService.GetResource(&quot;Bizay.Logistic.Admin.Schedules.Notification.Create.Error&quot;));
            return View(model);
        }
        _notificationService.SuccessNotification(_localizationService.GetResource(&quot;Bizay.Logistic.Admin.Schedules.Notification.Create.Success&quot;));
        if (continueEditing)
        {
            return RedirectToAction(&quot;Edit&quot;, new { id = schedule.Id });
        }
        else
        {
            return RedirectToAction(&quot;List&quot;);
        }
    }
    return View(model);
}
</code></pre>
<p>What happens here is that <code>schedules.Any(s =&gt; s.Name.Equals(model.Name, StringComparison.InvariantCultureIgnoreCase))</code> should be working on the <code>schedules</code> list whereas the <code>refreshedSchedules?.FirstOrDefault(s =&gt; s.Name == model.Name)</code> should be working on the <code>refreshedSchedules</code> list, the problem is that is that both lambdas are acting on the <code>schedules</code> list, any idea how I could make this work?</p>
",https://stackoverflow.com/questions/69409640/acess-two-different-lists-with-the-same-type-of-objects-in-unit-testing,"['c#', 'unit-testing', 'asp.net-core', '.net-core']",131,True,1,1
Angular Unit Testing error with export &#39;default&#39; (imported as &#39;__NG_CLI_RESOURCE__1&#39;) was not found,"<p>I am getting error when running ng test/npm test, here is the error. I am not sure why this is happening.</p>
<p><a href=""https://i.stack.imgur.com/gMaTH.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gMaTH.png"" alt=""enter image description here"" /></a></p>
<p>Can I get some help please?
I checked the tsConfig.json and it looks correct to me-</p>
<pre><code>&quot;target&quot;: &quot;es2017&quot;,
    &quot;module&quot;: &quot;es2020&quot;,
</code></pre>
",https://stackoverflow.com/questions/70252381/angular-unit-testing-error-with-export-default-imported-as-ng-cli-resource,"['angular', 'unit-testing', 'error-handling', 'jasmine']",210,False,1,0
How to mock a user for unit testing a Spring Security based application?,"<p>My application uses the Spring security configuration shown below, which requires a user to be authenticated. How can I mock a user for unit testing? It looks like I am being authenticated based on the content of <code>MockHttpServletRequest</code>; however, my test fails because I am denied access to the <code>/portfolio</code> endpoint and am instead redirected to the <code>/login</code> endpoint. I have followed the tutorial here: <a href=""https://rieckpil.de/guide-to-testing-spring-boot-applications-with-mockmvc/"" rel=""nofollow noreferrer"">https://rieckpil.de/guide-to-testing-spring-boot-applications-with-mockmvc/</a></p>
<pre><code>MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /portfolio
       Parameters = {}
          Headers = [Content-Type:&quot;multipart/form-data;charset=UTF-8&quot;]
             Body = null
    Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@3ce7394f, SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_USER]]]}

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 = 302
    Error message = null
          Headers = [X-Content-Type-Options:&quot;nosniff&quot;, X-XSS-Protection:&quot;1; mode=block&quot;, Cache-Control:&quot;no-cache, no-store, max-age=0, must-revalidate&quot;, Pragma:&quot;no-cache&quot;, Expires:&quot;0&quot;, X-Frame-Options:&quot;DENY&quot;, Location:&quot;/login&quot;]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = /login
          Cookies = []

java.lang.AssertionError: Response header 'Location'
Expected: a string containing &quot;/portfolio&quot;
     but: was &quot;/login&quot;
Expected :a string containing &quot;/portfolio&quot;
Actual   :&quot;/login&quot;
&lt;Click to see difference&gt;


    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
    at org.springframework.test.web.servlet.result.HeaderResultMatchers.lambda$string$0(HeaderResultMatchers.java:60)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
    at edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest.uploadPortfolioWithValidFile(PortfolioControllerTest.java:80)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:84)
    at org.junit.platform.runner.JUnitPlatform.run(JUnitPlatform.java:139)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

16:35:57.243 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
16:35:57.277 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
16:35:57.400 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest] from class [org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper]
16:35:57.433 [main] INFO org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest], using SpringBootContextLoader
16:35:57.446 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]: class path resource [edu/bu/cs673/stockportfolio/unittests/api/PortfolioControllerTest-context.xml] does not exist
16:35:57.448 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]: class path resource [edu/bu/cs673/stockportfolio/unittests/api/PortfolioControllerTestContext.groovy] does not exist
16:35:57.449 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
16:35:57.450 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]: PortfolioControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
16:35:57.714 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]
16:35:57.818 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [/Users/mlewis/IntelliJProjects/CS673/StockPortfolio/target/classes/edu/bu/cs673/stockportfolio/StockportfolioApplication.class]
16:35:57.820 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration edu.bu.cs673.stockportfolio.StockportfolioApplication for test class edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest
16:35:57.831 [main] DEBUG org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper - @TestExecutionListeners is not present for class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]: using defaults.
16:35:57.834 [main] INFO org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener, org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener, org.springframework.security.test.context.support.ReactorContextTestExecutionListener]
16:35:57.883 [main] INFO org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@135606db, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@518caac3, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@68034211, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@4f74980d, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@6c372fe6, org.springframework.test.context.support.DirtiesContextTestExecutionListener@58594a11, org.springframework.test.context.transaction.TransactionalTestExecutionListener@2a3888c1, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@4167d97b, org.springframework.test.context.event.EventPublishingTestExecutionListener@14fa86ae, org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener@6e15fe2, org.springframework.security.test.context.support.ReactorContextTestExecutionListener@68f1b17f, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@1722011b, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@57ad2aa7, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@5b3f61ff, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@3e2059ae, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@398dada8, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@7cb502c]
16:35:57.892 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@31920ade testClass = PortfolioControllerTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@1d483de4 testClass = PortfolioControllerTest, locations = '{}', classes = '{class edu.bu.cs673.stockportfolio.StockportfolioApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@4032d386 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration, org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration, org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration, org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration, org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration, org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration, org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration, org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration, org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration, org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration, org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration, org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@793f29ff, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@543295b0, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@fffa4b8f, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@7a35b0f5, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@645aa696, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@f44380e2, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@ef800a42, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@480d3575, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null].
16:35:58.033 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper=true}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.0)

2021-07-31 16:35:59.499  INFO 12834 --- [           main] e.b.c.s.u.api.PortfolioControllerTest    : Starting PortfolioControllerTest using Java 13.0.1 on Michaels-MacBook-Air.local with PID 12834 (started by mlewis in /Users/mlewis/IntelliJProjects/CS673/StockPortfolio)
2021-07-31 16:35:59.504  INFO 12834 --- [           main] e.b.c.s.u.api.PortfolioControllerTest    : No active profile set, falling back to default profiles: default
2021-07-31 16:35:59.582 DEBUG 12834 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@21ec5d87
2021-07-31 16:35:59.904  WARN 12834 --- [kground-preinit] o.s.h.c.j.Jackson2ObjectMapperBuilder    : For Jackson Kotlin classes support please add &quot;com.fasterxml.jackson.module:jackson-module-kotlin&quot; to the classpath
2021-07-31 16:36:02.405  INFO 12834 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@fb5aeed, org.springframework.security.web.context.SecurityContextPersistenceFilter@626e0c86, org.springframework.security.web.header.HeaderWriterFilter@51cab489, org.springframework.security.web.csrf.CsrfFilter@528c8c1, org.springframework.security.web.authentication.logout.LogoutFilter@491cafec, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@e91af20, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@6b8d54da, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@7cf63b9a, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@73893ec1, org.springframework.security.web.session.SessionManagementFilter@15e1f8fe, org.springframework.security.web.access.ExceptionTranslationFilter@7418d76e, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@14c99bf6]
2021-07-31 16:36:02.830 DEBUG 12834 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : ControllerAdvice beans: 0 @ModelAttribute, 0 @InitBinder, 1 RequestBodyAdvice, 1 ResponseBodyAdvice
2021-07-31 16:36:02.963 DEBUG 12834 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : 4 mappings in 'requestMappingHandlerMapping'
2021-07-31 16:36:03.082 DEBUG 12834 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Patterns [/webjars/**, /**] in 'resourceHandlerMapping'
2021-07-31 16:36:03.109 DEBUG 12834 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : ControllerAdvice beans: 0 @ExceptionHandler, 1 ResponseBodyAdvice
2021-07-31 16:36:03.502  INFO 12834 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2021-07-31 16:36:03.503  INFO 12834 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2021-07-31 16:36:03.505  INFO 12834 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 2 ms
2021-07-31 16:36:03.580  INFO 12834 --- [           main] e.b.c.s.u.api.PortfolioControllerTest    : Started PortfolioControllerTest in 5.499 seconds (JVM running for 8.233)

</code></pre>
<pre><code>@Service
public class AuthenticationService implements AuthenticationProvider {
    private final UserRepository userRepository;
    private final HashService hashService;

    public AuthenticationService(UserRepository userRepository, HashService hashService) {
        this.userRepository = userRepository;
        this.hashService = hashService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = userRepository.findAllByUsername(username);
        if (user != null) {
            String encodedSalt = user.getSalt();
            String hashedPassword = hashService.getHashedValue(password, encodedSalt);
            if (user.getPassword().equals(hashedPassword)) {
                return new UsernamePasswordAuthenticationToken(username, password, new ArrayList&lt;&gt;());
            }
        }

        return null;
    }

    @Override
    public boolean supports(Class&lt;?&gt; authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

</code></pre>
<pre><code>
@Component
public class HashService {
    private final FluentLogger log = FluentLoggerFactory.getLogger(HashService.class);

    public String getHashedValue(String data, String salt) {
        byte[] hashedValue = null;

        KeySpec keySpec = new PBEKeySpec(data.toCharArray(), salt.getBytes(), 5000, 128);

        try {
            SecretKeyFactory factory = SecretKeyFactory.getInstance(&quot;PBKDF2WithHmacSHA1&quot;);
            hashedValue = factory.generateSecret(keySpec).getEncoded();
        } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
            log.error().log(e.getMessage());
        }

        return Base64.getEncoder().encodeToString((hashedValue));
    }
}

</code></pre>
<pre><code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final AuthenticationService authenticationService;

    public SecurityConfig(AuthenticationService authenticationService) {
        this.authenticationService = authenticationService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(this.authenticationService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(&quot;/signup&quot;, &quot;/css/*&quot;, &quot;/js/*&quot;, &quot;/images/*&quot;).permitAll()
                .anyRequest().authenticated() // -
                .and()
                .formLogin().loginPage(&quot;/login&quot;).permitAll()
                .and()
                .formLogin().defaultSuccessUrl(&quot;/home&quot;, true)
                .and()
                .logout().permitAll()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).invalidSessionUrl(&quot;/login&quot;);
    }
}

</code></pre>
<pre><code>@Controller
@RequestMapping(&quot;/portfolio&quot;)
public class PortfolioController {
    private final UserService userService;
    private final PortfolioService portfolioService;
    private final ValidationService validationService;
    private final ResponseService responseService;
    private final FluentLogger log = FluentLoggerFactory.getLogger(PortfolioController.class);

    public PortfolioController(UserService userService, PortfolioService portfolioService,
                               ValidationService validationService, ResponseService responseService) {
        this.userService = userService;
        this.portfolioService = portfolioService;
        this.validationService = validationService;
        this.responseService = responseService;
    }

    @PostMapping
    public String uploadPortfolio(Authentication authentication,
                                  @RequestParam(&quot;csvUpload&quot;)MultipartFile multipartFile, Model model) {
        // Removing implementation details for brevity 
}

</code></pre>
<pre><code>@AutoConfigureMockMvc
@AutoConfigureJsonTesters
@WebMvcTest(PortfolioController.class)
public class PortfolioControllerTest {

    @Autowired
    private MockMvc mvc;

    private MockMultipartFile mockFile;

    @Before
    public void setup() {
        mockFile =
                new MockMultipartFile(
                        &quot;portfolio&quot;,
                        &quot;/Users/name/Downloads/TestPortfolio.csv&quot;,
                        &quot;text/csv&quot;,
                        &quot;portfolio&quot;.getBytes());
    }

    @Test
    @WithMockUser()
    public void uploadPortfolioWithValidFile() throws Exception {
        mvc.perform(
                multipart(&quot;/portfolio&quot;)
                        .file(mockFile))
                .andExpect(header().exists(&quot;Location&quot;))
                .andExpect(header().string(&quot;Location&quot;, Matchers.containsString(&quot;/portfolio&quot;)))
                .andExpect(status().is3xxRedirection());

    }
}

</code></pre>
",https://stackoverflow.com/questions/68598201/how-to-mock-a-user-for-unit-testing-a-spring-security-based-application,"['java', 'spring', 'unit-testing', 'mocking', 'mockito']",617,False,1,0
Unit testing individual pieces of Laravel artisan commands without running the entire command,"<p>I have some pretty complicated commands with a lot of moving parts. I want to write tests for individual parts of those commands. This is proving to be a real pain the way I am currently doing it because the input and output interfaces are not instantiated until the <code>run()</code> method is hit during a typical programmatic call.</p>
<p>e.g.</p>
<pre><code>Artisan::call('do:something', ['foo' =&gt; 'whatever', '--bar' =&gt; true]);
</code></pre>
<p>As such, I've written most of my tests like so:</p>
<pre><code>protected function setUp()
{
    parent::setUp();

    $this-&gt;command = new DoSomething;
    $this-&gt;thing = Something::first();
}

/** @test */
public function it_succeeds_and_fails_at_doing_something()
{
    // Test happy path.
    $success = $this-&gt;command-&gt;verySuccess($this-&gt;thing-&gt;id);

    $this-&gt;assertInstanceOf(SomethingSuccessful::class, $success);

    // Test unhappy path.
    $failed = $this-&gt;command-&gt;verySuccess('nope');

    $this-&gt;assertNull($failed);
}
</code></pre>
<p>The problem with the above is that within the command's code is scattered calls such as <code>if ($this-&gt;option('bar')) { ... }</code> which always fails with <code>Call to a member function getOption() on null</code></p>
<p>Aside from the exception, it also makes it problematic to test these specific methods with the right options and arguments set.</p>
<p>How do I get around this input issue? Feels like I am going about testing this the wrong way.</p>
",https://stackoverflow.com/questions/68823728/unit-testing-individual-pieces-of-laravel-artisan-commands-without-running-the-e,"['laravel', 'laravel-5']",46,False,1,0
Angular 11: Unit testing an HttpInterceptor - can&#39;t get catchError to work in test,"<p>I struggeling to finish a unit test for my HttpInterceptor. The interceptor works as a global error handler and simply triggers on catchError(httpResponseError). The interceptor is working just fine on my site, but I can't get the unit test to actually test the code.</p>
<p>Here's the code for the Interceptor:</p>
<pre><code>import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { retry, tap, catchError } from 'rxjs/operators';
import { HttpServiceError } from '../models/httpServiceError.model';
import { LoggingService, LogLevel } from '../services/logging.service';

@Injectable({
    providedIn: 'root'
})

export class HttpResponseInterceptorService implements HttpInterceptor{
  public logLevel!: LogLevel;

  constructor(private readonly loggingService: LoggingService) { 
// Intentionally left blank    
  }

  intercept(request: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    return next.handle(request)
      .pipe(
        retry(1),
        tap(() =&gt; console.log('ResponseInterceptor called')),
        catchError((error:HttpErrorResponse) =&gt; {          
          console.log('HttpErrorResponse caught')
          this.handleHttpError(error);
          return throwError(error);
        }))
  }

  private handleHttpError(error: HttpErrorResponse): Observable&lt;HttpServiceError&gt; {
    const requestError = new HttpServiceError();    
    
    console.log('Error:', error);
    console.log('handleHttpError function called');

    requestError.errorNumber = error.status;
    requestError.statusMessage = error.statusText;

    switch (error.status) {
      case 401: {
        requestError.friendlyMessage = 'You are not logged in';
        break;
      }
      case 403: {
        requestError.friendlyMessage = 'You are not logged in';
        break;
      }
      case 404: {
        requestError.friendlyMessage = 'The service failed to respond';
        break;
      }
      case 429: {
        requestError.friendlyMessage = 'The service is busy';
        break;
      }
      case 500: {
        requestError.friendlyMessage = 'The service is not responding correctly';
        break;
      }      
      default: {
        requestError.friendlyMessage = 'An error occured retrieving the data';
        break;
      }
    }


    this.loggingService.logWithLevel(JSON.stringify(requestError), LogLevel.Information);
    return throwError(requestError);
  }
}
</code></pre>
<p>As you can see, I have a couple of console,logs's in there and only the first is trigger in test.</p>
<p>Here's my spec file:</p>
<pre><code>import { HttpClient, HttpErrorResponse, HttpEvent, HttpHandler, HttpRequest, HttpResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { fakeAsync, inject, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { take } from 'rxjs/operators';
import { LoggingService } from '../services/logging.service';

import { HttpResponseInterceptorService } from './httpresponseinterceptor.service';

describe('HttpResponseInterceptorService', () =&gt; {
  let interceptor: HttpResponseInterceptorService;  
  let httpMock: HttpTestingController;
  let loggingService: LoggingService;
  let httpClient: HttpClient;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [        
        {
          provide: HTTP_INTERCEPTORS,
          useClass: HttpResponseInterceptorService,
          multi: true,
        },
      ]
    });
    loggingService = TestBed.inject(LoggingService);     
    interceptor = TestBed.inject(HttpResponseInterceptorService);
    httpMock = TestBed.inject(HttpTestingController);    
    httpClient = TestBed.inject(HttpClient);
  });

  afterEach(() =&gt; {
    httpMock.verify();
  });

  it('should be created', () =&gt; {
    expect(interceptor).toBeTruthy();
  });

  it('should call loggingService with a friendlyMessage of The service failed to respond (404)', fakeAsync(() =&gt; {
    spyOn(loggingService,'logWithLevel');

    const errorResponse = new HttpErrorResponse({
      error: '404 error',
      status: 404, statusText: 'Not Found'
    });

    httpClient.get('/api').subscribe();
   
    let request = httpMock.expectOne(&quot;/api&quot;);
    request.error(new ErrorEvent('404 Error'), errorResponse);
    // request.flush('Request failed', {status:404, statusText:'Not Found'});
    
    // request.flush(errorResponse);
   
    expect(loggingService.logWithLevel).toHaveBeenCalled();  
  }));

});

</code></pre>
<p>I've tried with both <code>request.error(new ErrorEvent('404 Error'), errorResponse);</code> and <code>// request.flush(errorResponse);</code>: None of the actually triggers the <code>catchError((error:HttpErrorResponse)</code> code branch.</p>
<p>Good ideas and feedback are very welcomed!</p>
<p>Thanks,
Bjarne</p>
",https://stackoverflow.com/questions/66532572/angular-11-unit-testing-an-httpinterceptor-cant-get-catcherror-to-work-in-te,"['angular', 'typescript', 'unit-testing', 'karma-jasmine']",2606,True,1,1
Angular Reactive Form Unit Testing: HTML value and control value out of sync,"<p>I am following the Angular reactive form unit testing guide <a href=""https://medium.com/javascript-frameworks/unit-testing-using-reactive-forms-in-angular-66b9fc4ee429"" rel=""nofollow noreferrer"">here</a> but am perpetually unable to get the control value and the HTML value to synchronize.  Below is my implementation; note that I am trying to call <code>setValue</code> in addition to specifying default values:</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'user',
    templateUrl: './user.component.html',
    styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

    loginForm!: FormGroup;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit(): void {
        this.initLoginForm();

        const usernameControl = this.loginForm.get('username');
        usernameControl?.valueChanges.subscribe(username =&gt; {
            debugger; // This doesn't fire
            this.loginForm.patchValue({username: username});
        });
    }

    initLoginForm() {
        this.loginForm = this.formBuilder.group({
            username: ['jack', Validators.compose([Validators.required])],
            password: ['JacksPassword']
        });

        this.loginForm.setValue({
            username: 'jack',
            password: 'JacksPassword'
        })

        this.loginForm.updateValueAndValidity();
    }
}
</code></pre>
<pre class=""lang-html prettyprint-override""><code>&lt;form [formGroup]=&quot;loginForm&quot; id=&quot;loginForm&quot;&gt;
    &lt;div&gt;
        &lt;input formControlName=&quot;username&quot; placeholder=&quot;Username&quot; required id=&quot;usernameInput&quot;/&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;input formControlName=&quot;password&quot; placeholder=&quot;Password&quot; type=&quot;password&quot;/&gt;
    &lt;/div&gt;
&lt;/form&gt;
</code></pre>
<p>And here are my tests:</p>
<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormBuilder } from '@angular/forms';
import { UserComponent } from './user.component';

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

    beforeEach(async () =&gt; {
        await TestBed.configureTestingModule({
            declarations: [UserComponent],
            providers: [FormBuilder]
        })
            .compileComponents();
    });

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

    it('should have same values between control and UI', () =&gt; {
        const loginFormUserElement: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#loginForm').querySelector('#usernameInput');
        const userNameValueFromGroup = component.loginForm.get('username');
        expect(loginFormUserElement.value).toEqual(userNameValueFromGroup?.value);
    });

    it('should accept username', () =&gt; {
        const loginFormUserElement: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#loginForm').querySelector('#usernameInput');
        loginFormUserElement.value = 'joe';
        loginFormUserElement.dispatchEvent(new Event('input'));
        fixture.detectChanges();
        fixture.whenStable().then(() =&gt; {
            const userNameValueFromGroup = component.loginForm.get('username');
            expect(loginFormUserElement.value).toEqual('joe');
            expect(loginFormUserElement.value).toEqual(userNameValueFromGroup?.value);
        });
    });
});
</code></pre>
<p>And here are the results.  Setting defaults doesn't update the UI.  Calling <code>setValue</code> doesn't update the UI.  And setting a value on the UI element doesn't update the control.</p>
<p><a href=""https://i.stack.imgur.com/2V3rb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2V3rb.png"" alt=""enter image description here"" /></a></p>
<p>It must be something basic.  Whatever am I missing?</p>
<p><strong>EDIT</strong>: I attempted to set up a StackBlitz implementation based on an isolated unit testing example, but the <code>formGroup</code> directive doesn't seem to be recognized under Jasmine; I am importing <code>ReactiveFormsModule</code> into app.module.  The link is <a href=""https://stackblitz.com/edit/angular-unit-testing-examples-jvzhzg"" rel=""nofollow noreferrer"">here</a> in case anyone can provide insight about what I'm missing on this front.</p>
<p><strong>EDIT</strong>: The problem here seems actually seems related to my unit testing effort.  When I use the component directly, default values are displayed on the HTML input element correctly; however, when inspecting messages via the console on Chrome running Karma, I see the same error message indicating that the <code>formGroup</code> directive isn't recognized.  I've updated the title accordingly.</p>
",https://stackoverflow.com/questions/69412403/angular-reactive-form-unit-testing-html-value-and-control-value-out-of-sync,"['javascript', 'html', 'angular', 'typescript']",623,True,1,1
"Jest + React Native, how to configure iOS and Android unit testing from scratch?","<p>I have a Lerna monorepository with a Web application and a module:</p>
<pre class=""lang-sh prettyprint-override""><code>.
├── apps
│   └── id-check-app            &lt;# Web application (create-react-app)
├── lerna.json
├── package.json
├── packages
│   └── id-check                &lt;# Module made with react-native-web
├── tsconfig.json                # and compatible with react-native
└── yarn.lock
</code></pre>
<p>The <code>id-check</code> module within <code>packages</code> is made with <code>react-native-web</code>, aliased on <code>react-native</code> imports.</p>
<p>So far, we are able to test for the Web but if we use custom version of our components for <strong>iOS or Android, then we are not able to test their <code>react-native</code> versions</strong>.</p>
<p>I may try to bootstrap a fresh react native application in the <code>apps</code> directory for being able to test them. (Note: we do not use expo)</p>
<p>How can I configure React Native and Jest to be able to test components for iOS and Android our components using the real <code>react-native</code> package?</p>
",https://stackoverflow.com/questions/67192488/jest-react-native-how-to-configure-ios-and-android-unit-testing-from-scratch,"['javascript', 'reactjs', 'react-native', 'jestjs', 'metro-bundler']",190,False,0,0
How to test If Else block in Angular Unit Testing using Jasmine /Karma,"<p>I am testing a component's ngOnit() which has if and else block. The code in the .ts file looks like this</p>
<pre><code>ngOnInit(): void {

this.profileSvc.loggedIn = true;

if (this.profileSvc.loggedIn) {
  this.setVars();
} else {
  this.stopSpinner();
  this.generalMessage = 'Please Log In!';
  this.displayGeneral = true;
}
this.appInsightsService.logPageView('CustomerProfile');
</code></pre>
<p>}</p>
<p>My tests on .spec.ts are here.
for if block:</p>
<pre><code>  it('test ngOnInit()', () =&gt;{
      component.ngOnInit();
      expect(component.profileSvc.loggedIn).toBe(true);
  });
  it('test ngOnInit() when not loggedIn', () =&gt;{
     //(mockprofileService as any).loggedIn = false;
     //spyOn&lt;any&gt;(mockprofileService, 'loggedIn').and.returnValue(false);
     component.profileSvc.loggedIn = false;
     component.ngOnInit();
     expect(component.displayGeneral).toBe(true);
 });
</code></pre>
<p>The first test which is for the if block got succeeded, but my second test failed which is for else block. I got this error:</p>
<pre><code>Expected false to be true.
</code></pre>
<p>My question is how to set the value of <code>.profileSvc.loggedIn</code> to false to test the else block. Please help! I would really appreciate. Also if you can direct me to best place to learn about Jamsin, I would really appreciate it.</p>
<p>Edit: <code>profileSvc</code> is a service. and I have mock for it is <code>mockprofileService</code></p>
",https://stackoverflow.com/questions/68512990/how-to-test-if-else-block-in-angular-unit-testing-using-jasmine-karma,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",2888,True,0,1
Why I am getting %E2%80%8B in my URL during unit testing,"<p>I am writing the unit testing for my controller and am getting 404 instead of 200 success.<br/>
When I search on the console it is showing we WARN log like</p>
<pre><code>WARN  [2021-02-12T11:53:27.711+0530] servlet.PageNotFound ||${fallback:user}|No mapping for GET /person%E2%80%8B/contacts%E2%80%8B/details
</code></pre>
<p>Why mapping changed to <code>/person%E2%80%8B/contacts%E2%80%8B/details</code> instead of <code>/person/contacts/details</code></p>
<p><strong>Test Class</strong></p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
@ActiveProfiles(&quot;test&quot;)
@SpringBootTest
public class PersonControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @InjectMocks
    private PersonController personController;

    @Mock
    private PersonService personService;

    @Before
    public void setupMethod() {

        mockMvc = MockMvcBuilders.standaloneSetup(personController).build();
    }

    @Test
    public void getPersonContactDetailTest() throws Exception {
    
        Person person = new Person();
        person.setName(&quot;Test&quot;);

        Mockito.when(personService.getPersonContactDetail()).thenReturn(person);

        RequestBuilder rqBuilder = MockMvcRequestBuilders.get(&quot;/person/contacts/details&quot;)
                .accept(MediaType.APPLICATION_JSON);

        mockMvc.perform(rqBuilder).andExpect(MockMvcResultMatchers.status().isOk());

        Mockito.verify(personService, times(1)).getPersonContactDetail());
    }
}
</code></pre>
",https://stackoverflow.com/questions/66167816/why-i-am-getting-e2808b-in-my-url-during-unit-testing,"['java', 'unit-testing', 'mockito', 'urlencode']",603,True,0,1
How would I setup bamboo unit testing that runs both karma and jest,"<p>I have been trying to set up server-side testing for my application but have run into an issue with bamboo recognizing more than one test type. In the past, it worked just fine using only karma as the unit test, but I need to add server-side testing which works much better with jest.</p>
<p>The main problem I am running into is that when both are run as shown below the coverage report is only created for the karma(unit) tests.</p>
<pre><code>test-unit=npm run test:unit &amp;&amp; npm run test:server
</code></pre>
<p>I have also tried running jest under bamboos test-e2e and test-contract-test but when I do this nothing is reported. So is there a way to set up server-side testing separately in the .bamboorc file</p>
",https://stackoverflow.com/questions/65582367/how-would-i-setup-bamboo-unit-testing-that-runs-both-karma-and-jest,"['jestjs', 'karma-runner', 'bamboo']",408,False,1,1
Angular Unit Testing: How to unit test subscription which get value from function?,"<p>I have one subscription inside my ngoninit in ts file.
I want to unit test this subscription how should i can do this?</p>
<p><strong>code.ts</strong></p>
<pre><code>this.generalConfigSubscription = this.generalConfigService.getGeneralConfigState().subscribe((response) =&gt; {
      if (response &amp;&amp; response.status == 'success') {
        if (response.data &amp;&amp; response.data) {
          this.configData = response.data;
          this.calculateNewValues = response.data.calculation_trigger ? response.data.calculation_trigger : [];
          this.valueValidity=response.data.value_validity ? response.data.value_validity : []
        }
      }
    })
</code></pre>
<p><strong>generalConfigService.ts</strong></p>
<pre><code>    private initialGeneralConfigState: GeneralConfigState = undefined;
    private generalConfigStateTracker = new BehaviorSubject&lt;GeneralConfigState&gt;(this.initialGeneralConfigState);
                                 .
                                 .
                                 .
    /** Allows subscription to the behavior subject as an observable */
    getGeneralConfigState(): Observable&lt;GeneralConfigState&gt; {
        return this.generalConfigStateTracker.asObservable();
    }
</code></pre>
",https://stackoverflow.com/questions/70523398/angular-unit-testing-how-to-unit-test-subscription-which-get-value-from-functio,"['angular', 'ionic-framework', 'angular-unit-test']",146,False,0,1
Angular unit testing click event which executes only navigateByUrl using Jasmin &amp; Karma,"<p>How to write unit test case for below click event in angular using Jasmin &amp; Karma</p>
<pre><code>     onClickCancel(): any {
        this.router.navigateByUrl('login');
      }
</code></pre>
<p>How to write unit test case for below click event which open material dialog in angular using Jasmin &amp; Karma. I am new to Angular.</p>
<pre><code>  addNewRole(): any {
    const dialogRef = this.dialog.open(AddNewRoleComponent, {
      width: '450px', disableClose: true
    });
    dialogRef.afterClosed().subscribe(() =&gt; {
      this.getRoles();
    });
  }

  editRole(roleData): any {
    const dialogRef = this.dialog.open(AddNewRoleComponent, {
      width: '450px', disableClose: true, data: roleData
    });
    dialogRef.afterClosed().subscribe(() =&gt; {
      this.getRoles();
    });
  }
</code></pre>
<p>This is my approach for unit testing of opening dialog</p>
<pre><code>  it('should open the add role component on click of addNewRole', () =&gt; {
    component.addNewRole();
    expect(dialog.open.calls.count()).toBe(1);
  });
</code></pre>
<p>My approach of opening dialog works properly for other test cases. But here - <strong>TypeError: Cannot read property 'count' of undefined</strong> error is thrown.</p>
<p>It would be a great pleasure if someone suggested me. Thank you !!!</p>
",https://stackoverflow.com/questions/68919030/angular-unit-testing-click-event-which-executes-only-navigatebyurl-using-jasmin,"['angular', 'typescript', 'jasmine', 'karma-jasmine']",393,False,0,1
Cypress unit testing show empty coverage object or not find any coverage information,"<p>⚠️ Could not find any coverage information in your application by looking at the window coverage object. Did you forget to instrument your application?</p>
<p>See code-coverage#instrument-your-application</p>
<p><strong>@cypress/code-coverage</strong></p>
<p><img src=""https://i.stack.imgur.com/Ffwu5.png"" alt=""enter image description here"" /></p>
<p><img src=""https://i.stack.imgur.com/9ajS2.png"" alt=""enter image description here"" /></p>
",https://stackoverflow.com/questions/69378889/cypress-unit-testing-show-empty-coverage-object-or-not-find-any-coverage-informa,"['javascript', 'reactjs', 'typescript', 'unit-testing', 'cypress']",171,False,0,0
Jest Unit Testing function that calls a second one that returns a promise,"<p><strong>Edited Question with vazsonyidl suggestions applied</strong></p>
<p>I have to write unit tests for a function similar to this one:</p>
<pre><code>import {External} from 'ExternalModule';

async functionA(){
    this.functionB().then((data) =&gt; {
        External.functionC(options);
        console.log(&quot;Reached1&quot;);

    }).catch((data) =&gt; {
        const { OnError = &quot;&quot; } = data || {}
        if(OnError) {
            External.functionC(anotherOptions);
            console.log(&quot;Reached2&quot;);
        }
    })
}

functionB() {
    return new Promise(() =&gt; {
    });
  }

</code></pre>
<p>As functionC belongs to another module, I placed a mock of it in the <code>_mocks_</code>folder:</p>
<pre><code>//_mocks_/ExternalModule.ts

export var External: ExternalClass = {
  functionC(){}
}

class ExternalClass{
  constructor(){};
  functionC(){};
}

</code></pre>
<p>I have mocked functionB in two diferent ways for testing the <code>then</code> and the <code>catch</code> :</p>
<pre><code>it(&quot;should test then block&quot;, () =&gt; {
        functionB = jest.fn(() =&gt; {return Promise.resolve()});

        const functionSpy = jest.spyOn(ExternalModule.External, 'functionC');
        void functionA().then(() =&gt; {
          expect(functionSpy).not.toHaveBeenCalled();
        });
    })

it(&quot;should test catch block&quot;, () =&gt; {
        const err = { OnError: &quot;Error&quot; };
        functionB = jest.fn(() =&gt; {return Promise.reject(err)});

        const functionSpy = jest.spyOn(ExternalModule.External, 'functionC');
        void functionA().then(() =&gt; {
          expect(functionSpy).not.toHaveBeenCalled();
        });
    })
</code></pre>
<p>What I am trying to do is expect that functionC was called and called with the correct params, but the test is always passing even if I test if functionC was not called.</p>
<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/67332331/jest-unit-testing-function-that-calls-a-second-one-that-returns-a-promise,"['javascript', 'typescript', 'unit-testing', 'testing', 'jestjs']",906,True,0,3
How to run/execute a unit testing framework like &quot;catch2&quot; in Unix Bash?,"<p>I am trying to learn testing with makefiles . I  searched online for a framework. Many people talked about &quot;catch2&quot; so I downloaded it. I read the tutorial in git and I've searched about it in many other webpages. I wrote this : <code>mytests</code> (without any suffix in the name)  to check <code>myprogram.cpp</code>.</p>
<pre><code>#define CATCH_CONFIG_RUNNER
#define CATCH_CONFIG_MAIN 
#include &quot;catch.hpp&quot;

TEST_CASE(&quot;maximum space is&quot;,&quot;[myprogram]&quot;){
    REQUIRE( myprogram(test.in1)==50)
    REQUIRE( myprogram(test.in2)==20)
    REQUIRE( myprogram(test.in3) ==1100)
    REQUIRE( myprogram(test.in4)==23)
    REQUIRE( myprogram(test.in5)==10);
}
</code></pre>
<p>The are many articles about how to write this and how to add features and specialisations or how to run it while choosing which tests to run and other stuff...<br />
<strong>But I could not find somewhere explicitly explaining how to run this</strong> . I am a beginner . I know that I can run a single test in my program which takes as input a file, like that : <code> ./myprogram test.in1</code> . So, what I need to type to use this testing framework??</p>
",https://stackoverflow.com/questions/67297434/how-to-run-execute-a-unit-testing-framework-like-catch2-in-unix-bash,"['c++', 'unit-testing', 'unix', 'automated-tests', 'catch2']",615,False,0,0
Python unit testing for a Cloud Function that loads GCS files to BigQuery,"<p>It is the first time I am using a Cloud Function and this cloud function is just doing one single job: everytime a file is uploaded to a GCS bucket, the cloud function is running and copying that file (<code>.csv</code>) to a BigQuery table without any transformations. What would be the most efficient wat to test (unit not integration) the <code>gcs_to_bq</code> method?</p>
<pre><code>def get_bq_table_name(file_name):
    if re.search('car', file_name):
        return 'car'
    return 'bike'

def gcs_to_bq(event, context):

    # Construct a BigQuery client object.
    client = bigquery.Client()

    bq_table = get_bq_table_name(event['name'] )

    table_id = f'xxx.yyy.{bq_table}'
    
    job_config = bigquery.LoadJobConfig(
        schema=[
            bigquery.SchemaField(&quot;datetime&quot;, &quot;STRING&quot;),
            bigquery.SchemaField(&quot;name&quot;, &quot;STRING&quot;),
            bigquery.SchemaField(&quot;id&quot;, &quot;STRING&quot;),

        ],
        skip_leading_rows=1,
        # The source format defaults to CSV, so the line below is optional.
        source_format=bigquery.SourceFormat.CSV,
    )
    
    uri = &quot;gs://&quot; + event['bucket'] + '/' + event['name'] 

    load_job = client.load_table_from_uri(
        uri, table_id, job_config=job_config
    )  # Make an API request.

    load_job.result()  # Waits for the job to complete.

    destination_table = client.get_table(table_id)  # Make an API request.
    print(&quot;Loaded {} rows.&quot;.format(destination_table.num_rows))
</code></pre>
",https://stackoverflow.com/questions/66460044/python-unit-testing-for-a-cloud-function-that-loads-gcs-files-to-bigquery,"['python', 'google-bigquery', 'google-cloud-functions']",341,True,0,1
type error this.service.newPerson is not a fucntion angular unit testing jasmine and jest,"<p><strong>data-detail.spec.ts</strong></p>
<pre><code>let component: PersonDetailComponent;
    let fixture: ComponentFixture&lt;PersonDetailComponent&gt;;

    const personServiceMock: PersonService = {getStringForRelation: jest.fn()} as any;
    const dateAdapterMock: DateAdapter&lt;Date&gt; = {setLocale: jest.fn()} as any;
    const NotificationServiceMock: DatevNotificationService = {} as any;
    const apiServiceMock: ApiService = {} as any;
    const clientServiceMock: ClientService = {} as any;
    it('btnadddata für Kind', () =&gt; {
                component.isNewPerson = true;
        const nodeDataArray: Array&lt;go.ObjectData&gt; = [
            {
                idPerson: 1,
                s: 'M',
                key: 1,
                personDetail: {
                    firstname: 'Vorname',
                    name: 'Nachname',
                    gender: PersonDetail.GenderEnum.IsMale,
                    isAlive: true,
                },
                quotasRelation: {
                    relationToOwner: QuotasRelation.RelationToOwnerEnum.Kind,
                },
                asset: {}
            }
        ];
        const relation: RelationToOwnerEnum = 'Kind';
        const mid = 1;
        const newPerson: Person = {
            idPerson: 1,
            // @ts-ignore
            key: 1,
            personDetail: {
                firstname: 'test',
                name: 'test1',
                gender: 'IsMale',
                idMother: 1,
                idFather: null,
                idSpouse: null,
                birthdate: null,
                isAlive: true,
            },
            quotasRelation: {
                relationToOwner: relation,
            },
            asset: {}
        };
        // const id = component.person.
        // const mid = component.person.personDetail.idMother;
        // const firstname = component.person.personDetail.firstname;
        // const gender = component.person.personDetail.gender;
        component.person.quotasRelation.relationToOwner = relation;
        component.person.idPerson = mid;
        component.nodeDataArray = nodeDataArray;
        component.btnAddPerson_Click(relation);
        console.log();
        component.personService.newPerson(1, 'test', 'test1', 'IsMale', mid, undefined, 
        undefined, relation).personDetail.idMother = mid;
        expect(newPerson).toEqual(component.addChildToPerson(component.selectedNode.data));
    });
</code></pre>
<p><strong>person-detail.component.ts</strong></p>
<pre><code>btnAddPerson_Click(relation: RelationToOwnerEnum): void {
        let newPerson: Person = null;
        if (relation === RelationToOwnerEnum.Kind) {
            newPerson = this.addChildToPerson(this.selectedNode.data);
        } else if (relation === RelationToOwnerEnum.Gatte) {
            newPerson = this.addSpouseToPerson(this.selectedNode.data);
        } else if (relation === RelationToOwnerEnum.BruderSchwester) {
            newPerson = this.addSiblingToPerson(this.selectedNode.data);
        } else if (relation === RelationToOwnerEnum.Vater) {
            newPerson = this.addParentToPerson(this.selectedNode.data);
        }
        if (newPerson) {
            this.isNewPerson = true;
            this.person = newPerson;
        }
    }

    addChildToPerson(parent: Person): Person {
        let fid: number;
        let mid: number;
        console.log('person', parent);
        if (parent.personDetail.idSpouse === undefined) {
            if (parent.personDetail.gender === PersonDetail.GenderEnum.IsMale) {
                fid = parent.idPerson;
                mid = undefined;
            } else {
                fid = undefined;
                mid = parent.idPerson;
            }
        } else if (parent.personDetail.gender === PersonDetail.GenderEnum.IsMale) {
            fid = parent.idPerson;
            mid = parent.personDetail.idSpouse;
        } else {
            fid = parent.personDetail.idSpouse;
            mid = parent.idPerson;
        }
        console.log('addChildToPerson Vater-Key Mutter-Key', fid, mid);
        // tslint:disable-next-line:max-line-length
        return this.personService.newPerson(this.getNextId(this.nodeDataArray), '', 
        parent.personDetail.name, null, mid, fid, -1, 
        QuotasRelation.RelationToOwnerEnum.Kind);
    }
</code></pre>
<p><strong>person.service.ts</strong></p>
<pre><code> export class PersonService {
    
        constructor() {
        }
    
        private readonly DUMMYSPOUSE = 'DummySpouse';
    
        private static getRelationWithGender(gender: GenderEnum, male: string, female: string, 
            diverse: string): string {
            return gender &amp;&amp; gender === GenderEnum.IsMale ? male : gender &amp;&amp; gender === 
            GenderEnum.IsFemale ? female : diverse;
    
        }
    
        public newPerson(
            id: number,
            firstname: string,
            name: string,
            gender: PersonDetail.GenderEnum,
            idMother: number,
            idFather: number,
            idSpouse: number,
            relation: QuotasRelation.RelationToOwnerEnum
        ): Person {
            return {
                idPerson: id,
                // @ts-ignore
                key: id,
                personDetail: {
                    firstname,
                    name,
                    gender,
                    idMother,
                    idFather,
                    idSpouse,
                    birthdate: null,
                    isAlive: true,
                },
                quotasRelation: {
                    relationToOwner: relation,
                },
                asset: {}
            };
           }
</code></pre>
<blockquote>
<p>i have tried several ways but i am not able to identify the error and
i know that newPerson is not a function but how to oversome this
error? I am new to testing , please help me.</p>
</blockquote>
<blockquote>
<p>how can i overcome this problem do i have to mock the method as new
person is not a method i cannot do that either</p>
</blockquote>
",https://stackoverflow.com/questions/68833968/type-error-this-service-newperson-is-not-a-fucntion-angular-unit-testing-jasmine,"['angular', 'unit-testing', 'jasmine', 'components', 'ts-jest']",28,True,0,1
Are there any ways to call database data to provide in Unit Testing,"<p>This is the Test that i have:</p>
<pre><code>[Test]
public async Task Late_Test()
{
  var options = new DBContextOptionsBuilder&lt;MyContext&gt;()
  .Options;
  
  using(var context = MyContext(options))
  {
    //Act?
  }
    // Assert?
}
</code></pre>
<p>This is the service that I am trying to create a test for:</p>
<pre><code>public async Task&lt;int&gt; LatesInMin(Model1 model1, bool isbool) 
{
 //code here
}
</code></pre>
<p>The code int the service also needs the data in the foreign keys attached to Model1.
Can i call a data from the database and use it as the parameter when i call the service? Or do i have to manually provide that data as well? I tried and using linq causes an error and I searched that you cant use extension methods such as 'Where()' and 'FirstOrDefault()'</p>
",https://stackoverflow.com/questions/65611193/are-there-any-ways-to-call-database-data-to-provide-in-unit-testing,"['c#', 'unit-testing', 'testing', 'mocking', 'moq']",38,False,0,2
Unit testing : how could I keep value of an attribute defined in __init__,"<p>I'm testing my code but I have an attribute error that I'm unable to resolve myself.</p>
<pre><code>import os

class MyClass:

    def __init__(self):
        self.folder = os.environ.get('folder')

    def a(self):
        myFolder = self.folder
        return myFolder

    @staticmethod
    def b():
        myData = MyClass.a(MyClass)
        return myData
</code></pre>
<pre><code>import unittest
from unittest.mock import patch
from myclass import MyClass

@patch.dict('os.environ', {'folder': 'blabla'})
class TestMyClass(unittest.TestCase):
    
    def testB(self):
        myclass = MyClass()
        content = myclass.b()
</code></pre>
<p>I have an Attribute Error inside 'a' myFolder = self.folder : 'type object MyClass has no attribute folder'</p>
<p>How could I do (without mocking result of a() ) ?</p>
",https://stackoverflow.com/questions/70069506/unit-testing-how-could-i-keep-value-of-an-attribute-defined-in-init,"['python-3.x', 'python-unittest']",50,False,0,0
Moq a service or service interface with a db context for unit testing,"<p>So I've trying to test my webapp coded in .net core 5.0, and I have a classic MVC model with service classes. Now I am trying to unit test the solution with moq to mock my database, and my tests run, but I have just noticed that they are all wrong when I debug. It seems as if it doesn't actually connect to the mock service or database itself... I have gone for mocking the service interface but that doesn't seem to work still. Help would be greatly appreciated.</p>
<p><strong>Service class:</strong></p>
<pre><code>public class InventoryService : IInventoryService
{
    private readonly DBContext _db;

    public InventoryService(DBContext db)
    {
        _db = db;
    }

    public List&lt;Inventory&gt; GetInventories(string id)
    {
        var inventories = (from i in _db.Inventories where i.userId.Equals(id) select i).ToList();
        return inventories;
    }

    public void CreateInventory(Inventory newInventory)
    {
        _db.Inventories.Add(newInventory);
        _db.SaveChanges();
    }

    public bool DeleteInventory(Guid Id, string UserId)
    {
        var inventory = _db.Inventories.Find(Id);

        if (inventory == null)
            return false;

        if (inventory.userId != UserId)
            return false;

        //Delete items using item service
        var items = from i in _db.Items where i.inventoryId.Equals(Id) select i;
        foreach(var i in items)
        {
            _db.Items.Remove(i);
        }

        _db.Inventories.Remove(inventory);
        _db.SaveChanges();
        return true;
    }

}
</code></pre>
<p>}</p>
<p><strong>Service interface it uses:</strong></p>
<pre><code>public interface IInventoryService
{
    public List&lt;Inventory&gt; GetInventories(string id);
    public void CreateInventory(Inventory newInventory);
    public bool DeleteInventory(Guid Id, string UserId);
}
</code></pre>
<p>}</p>
<p><strong>Model:</strong></p>
<pre><code>public class Inventory
{
    // The Id field is a unique identifier for a specific inventory
    [Key]
    public Guid Id { get; set; }

    // The name of the Inventory. Required to have a value
    [Required]
    [DisplayName(&quot;Inventory Name&quot;)]
    public string name { get; set; }

    public string userId { get; set; }
}
</code></pre>
<p>}</p>
<p><strong>Unit test:</strong></p>
<pre><code>public class InventoryTests
{

    // Unit test defined for the get user inventories, a valid ID will always be passed in so no need for negative testing
    [Fact]
    public void Get_user_inventories_with_valid_id()
    {
        //ARRANGE
        Guid theId1 = new(&quot;00000000-0000-0000-0000-000000000001&quot;);
        Guid theId2 = new(&quot;00000000-0000-0000-0000-000000000002&quot;);

        string u1 = &quot;xxx&quot;;
        string u2 = &quot;yyy&quot;;

        var mockIn = new Mock&lt;IInventoryService&gt;();

        var data = new List&lt;Inventory&gt;
        {
            new Inventory { Id = theId1, name = &quot;Mums 1&quot;, userId = u1},
            new Inventory { Id = theId1, name = &quot;Mums 1.2&quot;, userId = u1},

        }.AsQueryable();

        var mockSet = new Mock&lt;DbSet&lt;Inventory&gt;&gt;();
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.Provider).Returns(data.Provider);
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.Expression).Returns(data.Expression);
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(data.ElementType);
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(data.GetEnumerator());

        Mock&lt;IInventoryService&gt; myser = new Mock&lt;IInventoryService&gt;();

        //ACT

        myser.Setup(x =&gt; x.GetInventories(u1)).Returns(mockSet.Object.ToList());

        var tinvs = myser.Object.GetInventories(u1);


        //ASSERT
        Assert.Equal(2 , tinvs.Count);

    }


    //Unit test for creating an inventory, a valid new inventory object will always be passed in so need for negative testing
    [Fact]
    public void Creating_An_Inventory()
    {
        //ARRANGE
        Guid theId2 = new(&quot;00000000-0000-0000-0000-000000000001&quot;);

        string u1 = &quot;xxx&quot;;
        string u2 = &quot;yyy&quot;;

        var mockIn = new Mock&lt;IInventoryService&gt;();

        var data = new List&lt;Inventory&gt;
        {

        }.AsQueryable();

        var mockSet = new Mock&lt;DbSet&lt;Inventory&gt;&gt;();
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.Provider).Returns(data.Provider);
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.Expression).Returns(data.Expression);
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(data.ElementType);
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(data.GetEnumerator());

        //ACT

        Mock&lt;IInventoryService&gt; myser = new Mock&lt;IInventoryService&gt;();
        myser.Setup(x =&gt; x.GetInventories(u1)).Returns(mockSet.Object.ToList());

        Inventory thenew = new Inventory { Id = theId2, name = &quot;Mums 2&quot;, userId = u2 };
        myser.Object.CreateInventory(thenew);


        //ASSERT
        Assert.NotNull(data);
    }


    //Unit test for deleting an inventory. It will always be valid because a guid and user id will be passed in automatically 
    [Fact]
    public void Deleting_An_Inventory()
    {
        //ARRANGE
        Guid theId1 = new(&quot;00000000-0000-0000-0000-000000000001&quot;);
        Guid theId2 = new(&quot;00000000-0000-0000-0000-000000000002&quot;);


        string u1 = &quot;123&quot;;


        //var mockIn = new Mock&lt;IInventoryService&gt;();

        var data = new List&lt;Inventory&gt;
        {
            new Inventory { Id = theId1, name = &quot;testinv 1&quot;, userId = u1},

        }.AsQueryable();

        var mockSet = new Mock&lt;DbSet&lt;Inventory&gt;&gt;();
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.Provider).Returns(data.Provider);
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.Expression).Returns(data.Expression);
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(data.ElementType);
        mockSet.As&lt;IQueryable&lt;Inventory&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(data.GetEnumerator());

        //ACT

        Mock&lt;IInventoryService&gt; myser = new Mock&lt;IInventoryService&gt;();

        myser.Setup(x =&gt; x.GetInventories(u1)).Returns(mockSet.Object.ToList());


        myser.Object.DeleteInventory(theId1, u1);

        var updInvs = myser.Object.GetInventories(u1);
        int x = updInvs.Count;

        //ASSERT
        Assert.Equal(0, x);
    }

}
</code></pre>
<p>}</p>
<p>I am fairly sure it is a minor error in my setup of the unit test's mocking. any help would be great.</p>
",https://stackoverflow.com/questions/68690972/moq-a-service-or-service-interface-with-a-db-context-for-unit-testing,"['c#', 'unit-testing', 'moq']",1103,True,0,1
How to meet the test coverage in the following Unit testing in Nodejs?,"<p>I am doing Unit testing in NodeJS. I have managed to see the coverage of my unit testing using NYC. I would like to know how can i widen my unit testing scope to increase the coverage of Statement branch and condition branch. I have the following code for testing.</p>
<pre><code>const value = () =&gt; {
  const def = &quot;defvalue&quot;;
  const abc = &quot;abcvalue&quot;;

  if(abc &amp;&amp; abc !== &quot;undefined&quot;){
    return abc
  }else if (def &amp;&amp; def !== &quot;undefined&quot;){
    return def
  }else{
    return false
  }
}

//Function to do unit testing.
describe(&quot;the result function&quot;, () =&gt; {    
  it(&quot;should return false&quot;, () =&gt; {
    const result = value();
    console.log(&quot;The result is:&quot;, result);
    expect(result).to.be.false;
  });
  
  it(&quot;should return abc&quot;, () =&gt; {
    const result = value();
    console.log(&quot;The result is:&quot;, result);
    expect(result).to.be.eq(&quot;abc&quot;);
  });
  
  it(&quot;should return def&quot;, () =&gt; {
    const result = value();
    console.log(&quot;The result is:&quot;, result);
    expect(result).to.be.eq(&quot;def&quot;);
  });
});
</code></pre>
",https://stackoverflow.com/questions/68812371/how-to-meet-the-test-coverage-in-the-following-unit-testing-in-nodejs,"['node.js', 'unit-testing', 'npm', 'test-coverage', 'nyc']",492,True,0,1
initializeAdminApp and clearFirestoreData method no longer available after update to @firebase/rules-unit-testing 2.0,"<p>I just update my dependency to <code>&quot;@firebase/rules-unit-testing&quot;: &quot;^2.0.0&quot;</code></p>
<p>and it breaks my code. my code was</p>
<pre><code>import * as firebase from &quot;@firebase/rules-unit-testing&quot;;

function getAdminFirestore() {
    return firebase.initializeAdminApp({ projectId: projectID }).firestore();
}

function getFirestore(auth?: TokenOptions) {
    return firebase.initializeTestApp({ projectId: projectID, auth: auth }).firestore();
}

beforeEach(async () =&gt; {
    await firebase.clearFirestoreData({ projectId: projectID });
});

after(async () =&gt; {
    await firebase.clearFirestoreData({ projectId: projectID });
});
</code></pre>
<p>but I have a lot of errors because some methods no longer available like this</p>
<p><a href=""https://i.stack.imgur.com/Le0A3.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/Le0A3.png"" alt=""enter image description here"" /></a></p>
<p>so what is the equivalent method in firebase/rules-unit-testing 2.0.0 ?</p>
",https://stackoverflow.com/questions/69060666/initializeadminapp-and-clearfirestoredata-method-no-longer-available-after-updat,"['node.js', 'firebase', 'firebase-security', 'firebase-tools']",530,True,8,1
Unit testing Microsoft Graph API using Mockito - How to code cover 3rd party API,"<p>I am writing unit test using Mockito but I am still unable to understand how to cover the third party APIs - I have a public API called <strong>deleteApplication(String clientId)</strong> and a private API called <strong>getApplicationObjectId(String clientId)</strong></p>
<p>So inside my private method - I have a code which belongs to library Microsoft Graph SDK - Java and I need to mock it so I have a code coverage for below these two lines -</p>
<pre><code>ApplicationCollectionRequest request = this.graphServiceClient.applications().buildRequest(options);

ApplicationCollectionPage appCollectionPage = request.get();
</code></pre>
<p>And...like wise I have this line in my public method - I need to mock this so that I have code coverage for this...</p>
<pre><code>Application application = this.graphServiceClient.applications(appClientObjId)
            .buildRequest()
            .delete();
</code></pre>
<p>Is it possible to mock in these scenarios, if yes what is the best approach? I am using Jacoco for code coverage. Below is my public and private methods.</p>
<pre><code>public boolean deleteApplication(String clientId) {
        
        String appClientObjId = getApplicationObjectId(clientId);

        Application application = this.graphServiceClient.applications(appClientObjId)
            .buildRequest()
            .delete();
        
        return application.appId == null;
}

private String getApplicationObjectId(String clientId) {
    
    String queryTerm = String.format(&quot;appId eq '%s'&quot;, clientId);
    
    LinkedList&lt;Option&gt; options = new LinkedList&lt;&gt;();
    options.add(new QueryOption(&quot;$filter&quot;, queryTerm));
    
    ApplicationCollectionRequest request = this.graphServiceClient.applications().buildRequest(options);
    
    ApplicationCollectionPage appCollectionPage = request.get(); 

    if (!appCollectionPage.getCurrentPage().isEmpty()) {
        
        return appCollectionPage.getCurrentPage().get(0).id;
    }
    
    throw new Exception(&quot;Could not find application resource.&quot;);
}
</code></pre>
",https://stackoverflow.com/questions/70354548/unit-testing-microsoft-graph-api-using-mockito-how-to-code-cover-3rd-party-api,"['java', 'unit-testing', 'junit', 'mockito', 'powermock']",535,False,2,0
Not able to mock/fetch dynamic HTML elements in unit testing for dispatch event,"<p>I'm using devextreme elements for lookup operations (<code>autocomplete</code>). In <code>search.componets.ts</code> am accessing the input elements by using <code>document.getElementByClassName</code> for selecting the elements and applying <code>keyup</code> event</p>
<p>I have created mock elements in the spec file and tried to fetch and dispatch the keyboard event. But it's not working as excepted.</p>
<p>I have added the component code and component spec code below.</p>
<p>Can anyone help me? or suggest any alternative for this.</p>
<p><strong>search.component.ts</strong></p>
<pre><code>search() {
const elements = document.getElementByClassName('dx-texteditor-input)
const totalElements = elements?.length
elements[totalElements - 1].addEventListener(&quot;keyup&quot;, () =&gt; {
  this.input = elements[totalElements - 1].value;
});
}
</code></pre>
<p><strong>search.component.spec.ts</strong></p>
<pre><code>beforeEach(() =&gt; {
fixture = TestBed.createComponent(SearchComponent)
const inputMock = `&lt;div id=&quot;fixture&quot;&gt;
      &lt;input autocomplete=&quot;off&quot; aria-label=&quot;Search in data grid&quot; class=&quot;dx-texteditor-input&quot; type=&quot;text&quot; spellcheck=&quot;false&quot; tabindex=&quot;0&quot; role=&quot;textbox&quot;&gt;
      &lt;input autocomplete=&quot;off&quot; aria-label=&quot;Search in data grid&quot; class=&quot;dx-texteditor-input&quot; type=&quot;text&quot; spellcheck=&quot;false&quot; tabindex=&quot;0&quot; role=&quot;textbox&quot;&gt;
      &lt;input autocomplete=&quot;off&quot; aria-label=&quot;Search in data grid&quot; class=&quot;dx-texteditor-input&quot; type=&quot;text&quot; spellcheck=&quot;false&quot; tabindex=&quot;0&quot; role=&quot;textbox&quot;&gt;
    &lt;/div&gt;`;

document.body.insertAdjacentHTML('afterbegin', inputMock);
}

it('should check search', () =&gt; {
  const keyupEvent = new KeyboardEvent('keyup', { key: 'Enter' });
  const elements = document.querySelector('.dx-texteditor-input') as any;
  elements[0].dispatchEvent(keyupEvent)
  componet.search() 
});
</code></pre>
",https://stackoverflow.com/questions/68422437/not-able-to-mock-fetch-dynamic-html-elements-in-unit-testing-for-dispatch-event,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'addeventlistener']",337,False,1,1
Solidity unit testing isn&#39;t using the correct sender to call the function under test,"<pre><code>pragma solidity 0.6.12;

// This import is automatically injected by Remix
import &quot;remix_tests.sol&quot;; 

import &quot;remix_accounts.sol&quot;;
import &quot;./LottoMock.sol&quot;;

... other test cases

contract lottoMultipleEntranceTest {

LottoMock lotto;

/// #sender: account-0
/// #value: 500000000000000
function beforeEach() public payable {
    lotto = new LottoMock();
    
    Assert.equal(lotto.getQuantityOfEntrants(), uint256(0), &quot;expecting 0 entrants before entering&quot;);
    Assert.equal(lotto.getLotteryBalance(), uint256(0), &quot;expecting 0 lottery balance before entering&quot;);
    Assert.equal(msg.sender, TestsAccounts.getAccount(0), &quot;Invalid sender&quot;);

    
    lotto.enter{value:500000000000000}();
    
    Assert.equal(lotto.getLotteryBalance(), uint256(500000000000000), &quot;expecting lottery balance equal to entrance fee after entering&quot;);
    Assert.equal(lotto.getQuantityOfEntrants(), uint256(1), &quot;user should have successfully entered the lottery&quot;);
}

//TODO: needs debugging
///case 7: multiple entrants
/// #sender: account-1
/// #value: 500000000000000
function enterSuccessfullyMultipleEntrants() public payable {
    Assert.equal(lotto.getLotteryBalance(), uint256(500000000000000), &quot;One user has already entered.&quot;);
    Assert.equal(lotto.getQuantityOfEntrants(), uint256(1), &quot;Expecting an existing entry.&quot;);
    Assert.equal(msg.sender, TestsAccounts.getAccount(1), &quot;Invalid sender&quot;);

    //TODO - this is using account-0
    try lotto.enterDebug1{value:500000000000000}() {
        Assert.ok(false, 'succeed unexpected');
    } catch Error(string memory reason) {
        Assert.equal(reason, &quot;debug&quot;, &quot;debug.&quot;);
    } catch (bytes memory /*lowLevelData*/) {
        Assert.ok(false, 'failed unexpected');
    }
    
    Assert.equal(lotto.getLotteryBalance(), uint256(1000000000000000), &quot;expecting lottery balance equal to entrance fee for two users after entering&quot;);
    Assert.equal(lotto.getQuantityOfEntrants(), uint256(2), &quot;second user should have successfully entered the lottery&quot;);
}
}
</code></pre>
<p>The issue that I am having is in the <code>enterSuccessfullyMultipleEntrants</code> test, even though <code>    Assert.equal(msg.sender, TestsAccounts.getAccount(1), &quot;Invalid sender&quot;);</code> is working correctly, the <code>lotto.enterDebug1{value:500000000000000}()</code> line is still being called with test account 0, not account-1. Can someone please advise on what I'm doing wrong here?</p>
<p>Reference: <a href=""https://remix-ide.readthedocs.io/en/latest/unittesting.html#customization"" rel=""nofollow noreferrer"">https://remix-ide.readthedocs.io/en/latest/unittesting.html#customization</a></p>
",https://stackoverflow.com/questions/69200464/solidity-unit-testing-isnt-using-the-correct-sender-to-call-the-function-under,"['unit-testing', 'testing', 'ethereum', 'solidity', 'remix']",303,False,1,1
How can I print logs on Run tab during unit testing on Android Studio?,"<p>I am trying to print logs when I get the result of Unit Test/Instrumented Test with Run tab on Android Studio.</p>
<p>I tried with <code>Log.d()</code>, <code>Log.wtf()</code>, etc., <code>println()</code> and also Timber Library.</p>
<p>But three of them didn't print any text on Run tab.</p>
<p>I'd like to see the logs with the result altogether, not in separated tab(Logcat)</p>
",https://stackoverflow.com/questions/68407000/how-can-i-print-logs-on-run-tab-during-unit-testing-on-android-studio,"['android-studio', 'intellij-idea', 'junit']",104,False,1,0
The template specified for component AppComponent is not a string with Jest unit testing,"<p>I know this was asked before. I have tried just about everything in each suggestion.  I am trying to run this test app from wijmo with the jest incorporated.  The site runs fine, except the css doesn't quite come through, but not worried about that.  I just need a test app that has wijmo working and jest as a unit test framework.  After I added jest.. I received the error, when I use npm test.</p>
<p><strong>package.json</strong></p>
<pre><code> {
  &quot;name&quot;: &quot;test-app&quot;,
  &quot;version&quot;: &quot;0.0.0&quot;,
  &quot;scripts&quot;: {
    &quot;ng&quot;: &quot;ng&quot;,
    &quot;start&quot;: &quot;ng serve&quot;,
    &quot;build&quot;: &quot;ng build&quot;,
    &quot;test&quot;: &quot;jest --transformIgnorePatterns \&quot;node_modules/(?!@test-app)/\&quot; --env=jsdom&quot;,
    &quot;test:coverage&quot;: &quot;jest --coverage&quot;,
    &quot;lint&quot;: &quot;ng lint&quot;,
    &quot;e2e&quot;: &quot;ng e2e&quot;
  },
  &quot;private&quot;: true,
  &quot;dependencies&quot;: {
    &quot;@angular/animations&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/common&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/compiler&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/core&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/forms&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/platform-browser&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/platform-browser-dynamic&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/router&quot;: &quot;~11.0.0&quot;,
    &quot;@grapecity/wijmo&quot;: &quot;^5.20211.781&quot;,
    &quot;@grapecity/wijmo.angular2.core&quot;: &quot;^5.20211.781&quot;,
    &quot;@grapecity/wijmo.angular2.grid&quot;: &quot;^5.20211.781&quot;,
    &quot;@grapecity/wijmo.angular2.grid.detail&quot;: &quot;^5.20211.781&quot;,
    &quot;@grapecity/wijmo.angular2.grid.filter&quot;: &quot;^5.20211.781&quot;,
    &quot;@grapecity/wijmo.angular2.input&quot;: &quot;^5.20211.781&quot;,
    &quot;@grapecity/wijmo.grid&quot;: &quot;^5.20211.781&quot;,
    &quot;bootstrap&quot;: &quot;^5.0.1&quot;,
    &quot;raw-loader&quot;: &quot;^4.0.2&quot;,
    &quot;rxjs&quot;: &quot;~6.6.0&quot;,
    &quot;tslib&quot;: &quot;^2.0.0&quot;,
    &quot;zone.js&quot;: &quot;~0.10.2&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@angular-devkit/build-angular&quot;: &quot;~0.1100.0&quot;,
    &quot;@angular/cli&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/compiler-cli&quot;: &quot;~11.0.0&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.14.2&quot;,
    &quot;@types/jest&quot;: &quot;^26.0.23&quot;,
    &quot;@types/node&quot;: &quot;^12.20.13&quot;,
    &quot;codelyzer&quot;: &quot;^6.0.0&quot;,
    &quot;jest&quot;: &quot;^26.6.3&quot;,
    &quot;jest-canvas-mock&quot;: &quot;^2.3.1&quot;,
    &quot;jest-preset-angular&quot;: &quot;^8.4.0&quot;,
    &quot;karma-coverage&quot;: &quot;~2.0.3&quot;,
    &quot;protractor&quot;: &quot;~7.0.0&quot;,
    &quot;ts-node&quot;: &quot;~8.3.0&quot;,
    &quot;tslint&quot;: &quot;~6.1.0&quot;,
    &quot;typescript&quot;: &quot;~4.0.2&quot;
  },
  &quot;jest&quot;: {
    &quot;preset&quot;: &quot;jest-preset-angular&quot;,
    &quot;setupFilesAfterEnv&quot;: [
      &quot;&lt;rootDir&gt;/setup-jest.ts&quot;
    ],
    &quot;testPathIgnorePatterns&quot;: [
      &quot;&lt;rootDir&gt;/node_modules/&quot;,
      &quot;&lt;rootDir&gt;/dist/&quot;
    ]
  }
}

</code></pre>
<p><strong>app.module.ts</strong></p>
<pre><code>    
import { BrowserModule } from '@angular/platform-browser';
import { enableProdMode, NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { WjInputModule } from '@grapecity/wijmo.angular2.input';
import { WjGridModule } from '@grapecity/wijmo.angular2.grid';
import { FormsModule } from '@angular/forms';
import { DataService } from './app.data';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

@NgModule({
  declarations: [
    AppComponent
  ],
  providers: [DataService],
  imports: [WjInputModule, WjGridModule, BrowserModule, FormsModule],
  bootstrap: [AppComponent]
})
export class AppModule { }

</code></pre>
<p><strong>app.component.html</strong></p>
<pre><code>&lt;div class=&quot;container-fluid&quot;&gt;
    &lt;p&gt;
        Use an &lt;b&gt;ng-template&lt;/b&gt; element with the &lt;b&gt;wjFlexGridCellTemplate&lt;/b&gt; directive
        to define a cell template.
        The content of the &lt;b&gt;ng-template&lt;/b&gt; element defines the cell content.
        The &lt;b&gt;cellType&lt;/b&gt; property specifies the type of the cells represented by the template.
        The &lt;b&gt;cell&lt;/b&gt; local template variable contains an object with cell specific data,
        including the data item (&lt;b&gt;item&lt;/b&gt;), row (&lt;b&gt;row&lt;/b&gt;) and column (&lt;b&gt;col&lt;/b&gt;) that
        the cell represents.
    &lt;/p&gt;
    &lt;p&gt;
        Note that column-specific templates should be defined as children of
        the corresponding &lt;b&gt;wj-flex-grid-column&lt;/b&gt; component, while the others
        are defined under the &lt;b&gt;wj-flex-grid&lt;/b&gt; element.
    &lt;/p&gt;
    &lt;wj-flex-grid #grid [itemsSource]=&quot;data&quot; [allowSorting]=&quot;false&quot; [autoSizeMode]=&quot;'Both'&quot; [allowResizing]=&quot;'Both'&quot;
        [deferResizing]=&quot;true&quot;&gt;

        &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'TopLeft'&quot; *ngIf=&quot;customTopLeft&quot;&gt;
            №
        &lt;/ng-template&gt;
        &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'BottomLeft'&quot; *ngIf=&quot;customBottomLeft&quot;&gt;
            &amp;#931;
        &lt;/ng-template&gt;
        &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'RowHeader'&quot; *ngIf=&quot;customRowHeader&quot; let-cell=&quot;cell&quot;&gt;
            {{cell.row.index + 1}}
        &lt;/ng-template&gt;
        &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'RowHeaderEdit'&quot; *ngIf=&quot;customRowHeaderEdit&quot;&gt;
            ...
        &lt;/ng-template&gt;

        &lt;wj-flex-grid-column header=&quot;Country&quot; binding=&quot;country&quot; width=&quot;*&quot;&gt;
            &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'Cell'&quot; *ngIf=&quot;customCell&quot; let-cell=&quot;cell&quot;&gt;
                &lt;img src=&quot;/dist/TestApp/assets/{{cell.item.country}}.png&quot; /&gt;
                {{cell.item.country}}
            &lt;/ng-template&gt;
            &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'CellEdit'&quot; *ngIf=&quot;customCellEdit&quot; let-cell=&quot;cell&quot;&gt;
                &lt;wj-combo-box [itemsSource]=&quot;countries&quot; class=&quot;cell-editor&quot; [(selectedValue)]=&quot;cell.value&quot;
                    [isEditable]=&quot;false&quot; [isRequired]=&quot;false&quot; [placeholder]=&quot;'Select a Country'&quot;&gt;
                &lt;/wj-combo-box&gt;
            &lt;/ng-template&gt;
            &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'GroupHeader'&quot; *ngIf=&quot;customGroupHeader&quot; let-cell=&quot;cell&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;cell.row.isCollapsed&quot; /&gt;
                {{cell.item.name}} ({{cell.item.items.length}} items)
            &lt;/ng-template&gt;
        &lt;/wj-flex-grid-column&gt;

        &lt;wj-flex-grid-column header=&quot;Downloads&quot; binding=&quot;downloads&quot; [width]=&quot;170&quot; [aggregate]=&quot;'Sum'&quot;&gt;
            &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'ColumnHeader'&quot; *ngIf=&quot;customColumnHeader&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;highlightDownloads&quot; /&gt;
                Downloads
            &lt;/ng-template&gt;
            &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'Cell'&quot; *ngIf=&quot;customCell&quot; let-cell=&quot;cell&quot;&gt;
                &lt;span [ngStyle]=&quot;{color: highlightDownloads? (cell.item.downloads&gt;10000 ?'green':'red'):''}&quot;
                    style=&quot;font-weight:700&quot;&gt;
                    {{cell.item.downloads}}
                &lt;/span&gt;
            &lt;/ng-template&gt;
            &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'CellEdit'&quot; *ngIf=&quot;customCellEdit&quot; let-cell=&quot;cell&quot;&gt;
                &lt;wj-input-number class=&quot;cell-editor&quot; [(value)]=&quot;cell.value&quot; [step]=&quot;1&quot;&gt;&lt;/wj-input-number&gt;
            &lt;/ng-template&gt;
            &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'Group'&quot; *ngIf=&quot;customGroup&quot; let-cell=&quot;cell&quot;&gt;
                Sum = {{cell.value | number:'1.0-0'}}
            &lt;/ng-template&gt;
            &lt;ng-template wjFlexGridCellTemplate [cellType]=&quot;'ColumnFooter'&quot; *ngIf=&quot;customColumnFooter&quot; let-cell=&quot;cell&quot;&gt;
                Sum: {{cell.value | number:'1.0-0'}}
            &lt;/ng-template&gt;
        &lt;/wj-flex-grid-column&gt;
    &lt;/wj-flex-grid&gt;

    &lt;div class=&quot;checkbox-list&quot;&gt;
        &lt;div class=&quot;checkbox-list-title&quot;&gt;Column level templates:&lt;/div&gt;
        &lt;div class=&quot;checkbox-cell&quot;&gt;
            &lt;label class=&quot;checkbox&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;customCell&quot; /&gt; Cell
            &lt;/label&gt;
            &lt;label class=&quot;checkbox&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;customCellEdit&quot; /&gt; CellEdit
            &lt;/label&gt;
        &lt;/div&gt;
        &lt;div class=&quot;checkbox-cell&quot;&gt;
            &lt;label class=&quot;checkbox&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;customColumnHeader&quot; /&gt; ColumnHeader
            &lt;/label&gt;
            &lt;label class=&quot;checkbox&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;customColumnFooter&quot; /&gt; ColumnFooter
            &lt;/label&gt;
        &lt;/div&gt;
        &lt;div class=&quot;checkbox-cell&quot;&gt;
            &lt;label class=&quot;checkbox&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;customGroupHeader&quot; /&gt; GroupHeader
            &lt;/label&gt;
            &lt;label class=&quot;checkbox&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;customGroup&quot; /&gt; Group
            &lt;/label&gt;
        &lt;/div&gt;

        &lt;div class=&quot;checkbox-list-title&quot;&gt;Grid level templates:&lt;/div&gt;
        &lt;div class=&quot;checkbox-cell&quot;&gt;
            &lt;label class=&quot;checkbox&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;customTopLeft&quot; /&gt; TopLeft
            &lt;/label&gt;
            &lt;label class=&quot;checkbox&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;customBottomLeft&quot; /&gt; BottomLeft
            &lt;/label&gt;
        &lt;/div&gt;
        &lt;div class=&quot;checkbox-cell&quot;&gt;
            &lt;label class=&quot;checkbox&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;customRowHeader&quot; /&gt; RowHeader
            &lt;/label&gt;
            &lt;label class=&quot;checkbox&quot;&gt;
                &lt;input type=&quot;checkbox&quot; [(ngModel)]=&quot;customRowHeaderEdit&quot; /&gt; RowHeaderEdit
            &lt;/label&gt;
        &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;router-outlet&gt;&lt;/router-outlet&gt;
 
</code></pre>
<p><strong>jest.config.js</strong></p>
<pre><code>const { pathsToModuleNameMapper } = require('ts-jest/utils');
const { compilerOptions } = require('./tsconfig');

module.exports = {
  preset: 'jest-preset-angular',
  roots: ['&lt;rootDir&gt;/src/'],
  testMatch: ['**/+(*.)+(spec).+(ts)'],
  setupFilesAfterEnv: ['&lt;rootDir&gt;/setup-jest.ts'],
  setupFiles:[&quot;jest-canvas-mock&quot;],
  collectCoverage: true,
  collectCoverageFrom: [
    '&lt;rootDir&gt;/src/**/*.ts',
    '!&lt;rootDir&gt;/src/**/*.interface.ts',
    '!&lt;rootDir&gt;/src/**/*.mock.ts',
    '!&lt;rootDir&gt;/src/**/*.module.ts',
    '!&lt;rootDir&gt;/src/**/*.spec.ts',
    '!&lt;rootDir&gt;/src/**/*.test.ts',
    '!&lt;rootDir&gt;/src/**/*.d.ts',
    '!&lt;rootDir&gt;/src/**/*.html',
    '!&lt;rootDir&gt;/src/**/*.css',    
    '!&lt;rootDir&gt;/src/polyfills.ts',
    '!&lt;rootDir&gt;/src/main.ts'
],
  coverageReporters: [&quot;text&quot;,&quot;lcov&quot;,&quot;json&quot;,&quot;text&quot;,&quot;clover&quot;,&quot;cobertura&quot;],
  coverageDirectory: 'coverage/test-app',
  moduleNameMapper: {'\\.(css|less)$': '&lt;rootDir&gt;/styleMock.js'}    
};

</code></pre>
<p><strong>app.component.ts</strong></p>
<pre><code>
import 'bootstrap/dist/css/bootstrap.css';
import '@grapecity/wijmo.styles/wijmo.css';
//
import { Component, Inject, ViewChild } from '@angular/core';
//
import * as wjcCore from '@grapecity/wijmo';
import * as wjcGrid from '@grapecity/wijmo.grid';
import { WjInputModule } from '@grapecity/wijmo.angular2.input';
import { WjGridModule } from '@grapecity/wijmo.angular2.grid';
import { DataService } from './app.data';
//
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['../styles.scss']
})
export class AppComponent {
    countries: string[];
    data: wjcCore.CollectionView;
    customTopLeft = true;
    customRowHeader = true;
    customRowHeaderEdit = true;
    customCell = true;
    customCellEdit = true;
    customColumnHeader = true;
    customGroupHeader = true;
    customGroup = true;
    customColumnFooter = true;//
    customBottomLeft = true;
    highlightDownloads = true;
    //
    @ViewChild('grid', { static: true }) grid: wjcGrid.FlexGrid;
    title: any;
    //
    constructor(@Inject(DataService) dataSvc: DataService) {
        this.countries = dataSvc.getCountries();
        this.data = dataSvc.getCv(dataSvc.getData());

    }
    //
    ngAfterViewInit() {
        if (this.grid) {
            this.grid.columnFooters.rows.push(new wjcGrid.GroupRow());
        }
    }
}

</code></pre>
<p><a href=""https://i.stack.imgur.com/NZyUa.png"" rel=""nofollow noreferrer"">AppComponent is not a string</a></p>
",https://stackoverflow.com/questions/67586914/the-template-specified-for-component-appcomponent-is-not-a-string-with-jest-unit,"['angular', 'unit-testing', 'jestjs']",280,False,1,1
Ngrx effect is not being selected when action i being dispatched in unit testing,"<p>I am trying to test my effects. I have notice that, when I dispatch the action using <strong>replaySubject</strong>, SearchEffects class is being called. However, this.actions$ is undefined. Therefore, the right effect, <strong>search$</strong> in this case, is not being selected.</p>
<pre><code> let actions$ = new ReplaySubject(1);
 let effects: SearchEffects;

 beforeEach(async() =&gt; {
  TestBed.configureTestingModule({
    providers: [
      provideMockActions(() =&gt; actions$)
    ]
  });

  effects = TestBed.inject&lt;SearchEffects&gt;(SearchEffects);
});

it('should call register method when &quot;Search&quot; is dispatched', () =&gt; {
  actions$.next(search({
    context: { location: 'test' }
  }));

 effects.search$.subscribe();
});

readonly search$ = createEffect(
() =&gt;
  this.actions$.pipe(     //actions$ IS NULL
    ofType(search),       //THIS EFFECT IS NOT BEING SELECTED. 
    tap((action) =&gt; {
      //...               //I PUT MY BREAKPOINT HERE ... BUT NOTHING IS HAPPENING
    })
  ),
  { dispatch: false }
);
</code></pre>
",https://stackoverflow.com/questions/67324252/ngrx-effect-is-not-being-selected-when-action-i-being-dispatched-in-unit-testing,"['jestjs', 'ngrx']",28,False,1,0
Check if the header has been assigned to the request in Go unit-testing,"<p>I am trying to test the following line of code:</p>
<pre><code>httpReq.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)
</code></pre>
<p>I am mocking the request to an external api in this way:</p>
<pre><code>httpmock.RegisterResponder(http.MethodPost, &quot;do-not-exist.com&quot;,
        httpmock.NewStringResponder(http.StatusOK, `{
            &quot;data&quot;:{&quot;Random&quot;: &quot;Stuff&quot;}}`),
    )
</code></pre>
<p>And want to test if the request to the api has the header that I assigned. Is there a way I could achieve this?</p>
",https://stackoverflow.com/questions/69459575/check-if-the-header-has-been-assigned-to-the-request-in-go-unit-testing,"['go', 'go-http', 'go-testing']",1543,True,1,2
Is it a good practice to Mock entity manager in spring boot unit testing,"<p>I currently design an API using spring boot. In my service layer, I use Entity Manager for accessing the database. I have provided a method in my service layer below as an example.</p>
<pre><code>public Object getFirstReturnDate(Long vehicle_id, LocalDateTime reservation_date){
    String string = &quot;SELECT r.reservation_time from Reservation r left join fetch r.driverAssignment  where r.reservation_time &gt; :reservation_time &quot; +
            &quot;and r.reserved_status.slug in ('pending','approved') and r.reserved_vehicle.id=:vehicle_id &quot; +
            &quot; order by r.reservation_time asc &quot;;
    Query  query = em.createQuery(string);
    query.setParameter(&quot;reservation_time&quot;,reservation_date);
    query.setParameter(&quot;vehicle_id&quot;,vehicle_id);

    List&lt;LocalDateTime&gt; localDateTimes=query.getResultList();
    if(localDateTimes.size()==0)
        return new DefaultResponseDTO(200, ResponseStatus.OK,&quot;Any Date&quot;,null);;
    return new DefaultResponseDTO(200, ResponseStatus.OK,&quot;Possible Time&quot;,localDateTimes.get(0));

}
</code></pre>
<p>in the testing unit, I mocked the entity manager as below,</p>
<pre><code>@Mock
EntityManager em;
</code></pre>
<p>And in the test method,</p>
<pre><code>Query query = Mockito.mock(Query.class);
Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query);
Mockito.when(query.getResultList()).thenReturn(new LinkedList());
</code></pre>
<p>My question is, if I mock entity Manger as I mentioned above then the query in the method didn't get checked. Is it a bad coding practice?</p>
<p>Is there any other way to check queries without calling the database?</p>
",https://stackoverflow.com/questions/69382655/is-it-a-good-practice-to-mock-entity-manager-in-spring-boot-unit-testing,"['spring-boot', 'unit-testing', 'mocking', 'entitymanager']",994,True,1,1
React Unit-Testing - Could not find &quot;store&quot; in the context of &quot;Connect(Connect(AddUserProfile))&quot;,"<p>I tried to build a simple component that will popup to allow a user to create a new acocunt like below.</p>
<p>NewAccount.jsx</p>
<pre><code>import React from 'react';
import {
  Button, Modal, ModalHeader, ModalBody, ModalFooter,
} from 'reactstrap';
import UserProfile from '../UserProfile/AddNewUserProfile';
import { useHistory } from 'react-router-dom';

const NewAccount = React.memo((props) =&gt; {
  const closePopup = (e) =&gt; { props.onUserPopupClose(); };
  const history = useHistory()
  const userCreated = () =&gt; {
    props.userCreated();
  }

  return (
    &lt;Modal isOpen={props.open} toggle={closePopup} className={&quot;modal-dialog modal-lg&quot;}&gt;
      &lt;ModalHeader toggle={closePopup}&gt;New User&lt;/ModalHeader&gt;
      &lt;ModalBody&gt;
        &lt;UserProfile isAddNewUser={true} history={history} userCreated={userCreated} /&gt;
      &lt;/ModalBody&gt;
      &lt;ModalFooter&gt;
        &lt;Button color=&quot;secondary&quot; onClick={closePopup}&gt;Close&lt;/Button&gt;
      &lt;/ModalFooter&gt;
    &lt;/Modal&gt;
  );
});
export default NewAccount;
</code></pre>
<p>This is my NewAccount.test.js just to test out if it render the modal or not.</p>
<pre><code>import React from 'react';
import { screen, render, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import NewAccount from '../../components/UserManagement/NewAccount';

jest.mock('../../components/UserProfile', () =&gt; {
  const userprofile = () =&gt; &lt;div&gt;&lt;h4&gt;User Profile&lt;/h4&gt;&lt;/div&gt;;
  return userprofile;
});
describe('new user popup', () =&gt; {
  const userCreated = jest.fn();
  const onUserPopupClose = jest.fn();
  beforeEach(() =&gt; {
    render(&lt;NewAccount 
      open 
      onUserPopupClose={onUserPopupClose} 
      userCreated={userCreated}/&gt;);
  });
  describe('Structure', () =&gt; {
    it('should render the modal', () =&gt; {
      expect(screen.getByRole('dialog')).toBeInTheDocument();
    });
  });
});
</code></pre>
<p>This is the error that I got</p>
<pre><code>FAIL src/__tests__/UserManagement/NewAccount.test.js
  Stop Error
    ✓ should not error out due to no tests (popper.js.js) (2ms)
  new user popup
    Structure
      ✕ should render the modal (111ms)

  ● new user popup › Structure › should render the modal

    Could not find &quot;store&quot; in the context of &quot;Connect(Connect(AddUserProfile))&quot;. Either wrap the root component in a &lt;Provider&gt;, or pass a custom React context provider to &lt;Provider&gt; and the corresponding React context consumer to Connect(Connect(AddUserProfile)) in connect options.

      12 |   const onUserPopupClose = jest.fn();
      13 |   beforeEach(() =&gt; {
    &gt; 14 |     render(&lt;NewAccount 
         |     ^
      15 |       open 
      16 |       onUserPopupClose={onUserPopupClose} 
      17 |       userCreated={userCreated}/&gt;);

      at ConnectFunction (node_modules/react-redux/lib/components/connectAdvanced.js:259:15)
      at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14803:18)
      at updateFunctionComponent (node_modules/react-dom/cjs/react-dom.development.js:17034:20)
      at updateSimpleMemoComponent (node_modules/react-dom/cjs/react-dom.development.js:16972:10)
      at updateMemoComponent (node_modules/react-dom/cjs/react-dom.development.js:16861:14)
      at beginWork (node_modules/react-dom/cjs/react-dom.development.js:18682:16)
      at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:188:14)
      at HTMLUnknownElement.callTheUserObjectsOperation (node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
      at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:318:25)
      at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
      at HTMLUnknownElementImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
      at HTMLUnknownElementImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
      at HTMLUnknownElement.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
      at Object.invokeGuardedCallbackDev (node_modules/react-dom/cjs/react-dom.development.js:237:16)
      at invokeGuardedCallback (node_modules/react-dom/cjs/react-dom.development.js:292:31)
      at beginWork$1 (node_modules/react-dom/cjs/react-dom.development.js:23203:7)
      at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:22157:12)
      at workLoopSync (node_modules/react-dom/cjs/react-dom.development.js:22130:22)
      at performSyncWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:21756:9)
      at node_modules/react-dom/cjs/react-dom.development.js:11089:24
      at unstable_runWithPriority (node_modules/scheduler/cjs/scheduler.development.js:653:12)
      at runWithPriority$1 (node_modules/react-dom/cjs/react-dom.development.js:11039:10)
      at flushSyncCallbackQueueImpl (node_modules/react-dom/cjs/react-dom.development.js:11084:7)
      at flushSyncCallbackQueue (node_modules/react-dom/cjs/react-dom.development.js:11072:3)
      at batchedUpdates$1 (node_modules/react-dom/cjs/react-dom.development.js:21862:7)
      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:929:14)
      at render (node_modules/@testing-library/react/dist/pure.js:96:26)
      at Object.&lt;anonymous&gt; (src/__tests__/UserManagement/NewAccount.test.js:14:5)

  ● new user popup › Structure › should render the modal

    TestingLibraryElementError: Unable to find an accessible element with the role &quot;dialog&quot;

    There are no accessible roles. But there might be some inaccessible roles. If you wish to access them, then set the `hidden` option to `true`. Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole

    &lt;body
      class=&quot;&quot;
    &gt;
      &lt;div /&gt;
    &lt;/body&gt;

      19 |   describe('Structure', () =&gt; {
      20 |     it('should render the modal', () =&gt; {
    &gt; 21 |       expect(screen.getByRole('dialog')).toBeInTheDocument();
         |                     ^
      22 |     });
      23 |   });
      24 | });

      at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:37:19)
      at node_modules/@testing-library/dom/dist/query-helpers.js:92:38
      at node_modules/@testing-library/dom/dist/query-helpers.js:64:17
      at getByRole (node_modules/@testing-library/dom/dist/query-helpers.js:108:19)
      at Object.&lt;anonymous&gt; (src/__tests__/UserManagement/NewAccount.test.js:21:21)

  console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Uncaught [Error: Could not find &quot;store&quot; in the context of &quot;Connect(Connect(AddUserProfile))&quot;. Either wrap the root component in a &lt;Provider&gt;, or pass a custom React context provider to &lt;Provider&gt; and the corresponding React context consumer to Connect(Connect(AddUserProfile)) in connect options.]
        at reportException (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:62:24)
        at innerInvokeEventListeners (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:333:9)
        at invokeEventListeners (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
        at HTMLUnknownElementImpl._dispatch (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
        at HTMLUnknownElementImpl.dispatchEvent (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
        at HTMLUnknownElement.dispatchEvent (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
        at Object.invokeGuardedCallbackDev (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:237:16)
        at invokeGuardedCallback (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:292:31)
        at beginWork$1 (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:23203:7)
        at performUnitOfWork (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:22157:12) Error: Could not find &quot;store&quot; in the context of &quot;Connect(Connect(AddUserProfile))&quot;. Either wrap the root component in a &lt;Provider&gt;, or pass a custom React context provider to &lt;Provider&gt; and the corresponding React context consumer to Connect(Connect(AddUserProfile)) in connect options.
        at ConnectFunction (/home/user1/WebApplication/webapp1/node_modules/react-redux/lib/components/connectAdvanced.js:259:15)
        at renderWithHooks (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:14803:18)
        at updateFunctionComponent (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:17034:20)
        at updateSimpleMemoComponent (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:16972:10)
        at updateMemoComponent (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:16861:14)
        at beginWork (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:18682:16)
        at HTMLUnknownElement.callCallback (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:188:14)
        at HTMLUnknownElement.callTheUserObjectsOperation (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
        at innerInvokeEventListeners (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:318:25)
        at invokeEventListeners (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
        at HTMLUnknownElementImpl._dispatch (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
        at HTMLUnknownElementImpl.dispatchEvent (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
        at HTMLUnknownElement.dispatchEvent (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
        at Object.invokeGuardedCallbackDev (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:237:16)
        at invokeGuardedCallback (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:292:31)
        at beginWork$1 (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:23203:7)
        at performUnitOfWork (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:22157:12)
        at workLoopSync (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:22130:22)
        at performSyncWorkOnRoot (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:21756:9)
        at /home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:11089:24
        at unstable_runWithPriority (/home/user1/WebApplication/webapp1/node_modules/scheduler/cjs/scheduler.development.js:653:12)
        at runWithPriority$1 (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:11039:10)
        at flushSyncCallbackQueueImpl (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:11084:7)
        at flushSyncCallbackQueue (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:11072:3)
        at batchedUpdates$1 (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:21862:7)
        at act (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom-test-utils.development.js:929:14)
        at render (/home/user1/WebApplication/webapp1/node_modules/@testing-library/react/dist/pure.js:96:26)
        at Object.&lt;anonymous&gt; (/home/user1/WebApplication/webapp1/src/__tests__/UserManagement/NewAccount.test.js:14:5)
        at Object.asyncJestLifecycle (/home/user1/WebApplication/webapp1/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:53:37)
        at /home/user1/WebApplication/webapp1/node_modules/jest-jasmine2/build/queueRunner.js:43:12
        at new Promise (&lt;anonymous&gt;)
        at mapper (/home/user1/WebApplication/webapp1/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
        at /home/user1/WebApplication/webapp1/node_modules/jest-jasmine2/build/queueRunner.js:73:41

  console.error node_modules/react-dom/cjs/react-dom.development.js:19527
    The above error occurred in the &lt;ConnectFunction&gt; component:
        in ConnectFunction (at NewAccount.jsx:26)
        in div (created by ModalBody)
        in ModalBody (at NewAccount.jsx:25)
        in div (created by Modal)
        in div (created by Modal)
        in div (created by Transition)
        in Transition (created by Fade)
        in Fade (created by Modal)
        in div (created by Modal)
        in Portal (created by Modal)
        in Modal (at NewAccount.jsx:23)
        in Unknown (at NewAccount.test.js:14)
    
    Consider adding an error boundary to your tree to customize error handling behavior.


Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        3.745s, estimated 4s
</code></pre>
<p>I'm new to unit-testing .... so I don't know what I did wrong here :(. I have tried to google for few hours and I still can't figure out what wrong with this.</p>
<p>Also if you guys have some video/articles/documentation about how to do unit-testing for React.js noob like me, feel free to share them with me :(</p>
",https://stackoverflow.com/questions/65822304/react-unit-testing-could-not-find-store-in-the-context-of-connectconnecta,"['javascript', 'reactjs', 'unit-testing']",312,False,0,0
Xcode Unit Testing - Can&#39;t get print commands to display consistently while unit tests running,"<p>I recently started running unit tests on my SwiftUI based app in Xcode version 12.4.</p>
<p>When I run my tests, I can't understand what print commands actually show up in the output vs. which ones don't.</p>
<p>For example, I have this MockRepository class that gets used in testing instead of my normal repository calling Firebase, and I have two print commands in the loadData method. For a while, neither of them were showing up in the output. Now I can get the first command to show output (pretty consistently), but the second one is not showing anything.</p>
<p>I have tried adding breakpoints at that line, but I am still not seeing the output. I also get print commands printing out from a couple of my methods in the actual class being tested, but not from other helper methods.</p>
<p>Is there a good way to consistently tell which print commands will show up in the output and which ones won't (for aiding in debugging)?</p>
<p>Here is my mock repository with the loadData function:</p>
<pre><code>//
//  MockActionRepository.swift
//  GoalTogetherTests
//
//  Created by Charlie Page on 3/11/21.
//

import Foundation
@testable import GoalTogether

class MockActionRepository: ObservableObject, ActionStoreType {

    var db = TestDatabase()
    @Published var actions: [Action] = [Action]()
    var actionsPublished: Published&lt;[Action]&gt; { _actions }
    var actionsPublisher: Published&lt;[Action]&gt;.Publisher { $actions }
    
    init() {
        loadData()
    }
    
    func loadData() {
        let actionsList = db.actionsCollection
        self.actions = actionsList
        
        print(&quot;Here's a new printout I'm going to print&quot;)
        print(&quot;The actions list third action of: \(self.actions[2].title) has a startDate of \(self.actions[2].startDate)&quot;)
    }
    
    func addAction(_ action: Action) {
        self.actions.append(action)
    }
    
    func updateAction(_ action: Action) {
        var actionList = self.actions
        let index = actionList.firstIndex(where: {$0.id == action.id})
        
        guard index != nil else {
            print(&quot;Could not find action to update&quot;)
            return
        }
        actionList[index!] = action
        
        self.actions = actionList
    }
    
    func deleteAction(_ action: Action) {
        var actionList = self.actions
        
        if let index = actionList.firstIndex(where: {$0.id == action.id}) {
            actionList.remove(at: index)
        }
        self.actions = actionList
    }
}
</code></pre>
<p>And here are the test methods that call it:</p>
<pre><code>//
//  ActionListViewModelTests.swift
//  GoalTogetherTests
//
//  Created by Charlie Page on 3/11/21.
//

import XCTest
@testable import GoalTogether

class ActionListViewModelTests: XCTestCase {

    var sut: ActionListViewModel!
    
    override func setUp() {
        super.setUp()
        sut = ActionListViewModel(actionRepository: MockActionRepository())
    }
    
    override func tearDown() {
        sut = nil
        super.tearDown()
    }
    
    func testActionListVM_loadData() {
        // given
        let count = sut.actionRepository.actions.count
        
        // when
        
        // assert
        XCTAssertEqual(count, 3)
    }
    
    func testActionListVM_addAction_canAdd() {
        // given
        let testAction = Action(title: &quot;Test Action specific to the canAdd test.&quot;)
        
        // when
        sut.addAction(testAction)
        
        // assert
        XCTAssertTrue(sut.actionRepository.actions.contains(where: { $0.title == testAction.title}))
    }
    
    func testActionListVM_updateAction_canUpdate() {
        // given
        var updatedAction = sut.actionRepository.actions[0]
        
        // when
        updatedAction.title = &quot;New updated action title&quot;
        sut.updateAction(updatedAction)
        
        // assert
        XCTAssertTrue(sut.actionRepository.actions[0].title == &quot;New updated action title&quot;)
    }

    func testActionListVM_removeAction_canRemove() {
        // given
        let removalAction = sut.actionRepository.actions[1]
        
        // when
        sut.deleteAction(removalAction)
        let count = sut.actionRepository.actions.count
        
        XCTAssertEqual(count, 2)
    }
    
    func testActionListVM_loadPastActions_hasPastAction() {
        // given
        let pastCount = sut.previousActionCellViewModels.count
        
        // when
        
        // assert
        XCTAssertEqual(pastCount, 1)
    }
    
    func testActionListVM_loadBaseDateActions_hasBaseDateAction() {
        // given
        let currentCount = sut.baseDateActionCellViewModels.count
        
        // when
        
        // assert
        XCTAssertEqual(currentCount, 2)
    }
    
}
</code></pre>
<p>Here is the first part of my output (I have &quot;All Output&quot; selected), which picks up some of the output, but not all of it:</p>
<pre><code>User ID is: Optional(&quot;EHOohLd6jMPuLp7CpxtajvYjj2t2&quot;)
The current date of 2021-03-30 22:52:12 +0000 is not the end of the week (2021-04-03 22:52:12 +0000)
Start date is 2021-03-31 05:00:00 +0000 and the end of that week is 2021-04-03 05:00:00 +0000
Test Suite 'All tests' started at 2021-03-30 17:52:12.662
Test Suite 'GoalTogetherTests.xctest' started at 2021-03-30 17:52:12.663
Test Suite 'ActionListViewModelTests' started at 2021-03-30 17:52:12.663
Test Case '-[GoalTogetherTests.ActionListViewModelTests testActionListVM_addAction_canAdd]' started.
Here's a new printout I'm going to print
The current date of 2021-03-30 22:52:25 +0000 is not the end of the week (2021-04-03 22:52:25 +0000)
Start date is 2021-03-31 05:00:00 +0000 and the end of that week is 2021-04-03 05:00:00 +0000
Test Case '-[GoalTogetherTests.ActionListViewModelTests testActionListVM_addAction_canAdd]' passed (12.570 seconds).
Test Case '-[GoalTogetherTests.ActionListViewModelTests testActionListVM_loadBaseDateActions_hasBaseDateAction]' started.
Here's a new printout I'm going to print
The current date of 2021-03-30 22:52:25 +0000 is not the end of the week (2021-04-03 22:52:25 +0000)
Start date is 2021-03-31 05:00:00 +0000 and the end of that week is 2021-04-03 05:00:00 +0000
Test Case '-[GoalTogetherTests.ActionListViewModelTests testActionListVM_loadBaseDateActions_hasBaseDateAction]' passed (0.172 seconds).
</code></pre>
",https://stackoverflow.com/questions/66879547/xcode-unit-testing-cant-get-print-commands-to-display-consistently-while-unit,"['swift', 'xcode', 'unit-testing', 'xcode12']",531,False,0,0
Angular Unit Testing: How to write unit testcases for the app.service.ts using Jasmine-Karma,"<p>I want to write test cases for <code>downloadFile()</code> and <code>ConvertToCSV()</code> methods in <strong>app.service.ts</strong> in the <a href=""https://stackblitz.com/edit/angular8-json-to-csv"" rel=""nofollow noreferrer"">given stackblitz</a> code. Please find the reference <a href=""https://www.geeksforgeeks.org/export-json-to-csv-file-in-angular/"" rel=""nofollow noreferrer"">here</a></p>
<pre><code>import { Injectable } from '@angular/core';


@Injectable()
export class AppService {

    downloadFile(data, filename='data') {
        let csvData = this.ConvertToCSV(data, ['name','age', 'average', 'approved', 'description']);
        console.log(csvData)
        let blob = new Blob(['\ufeff' + csvData], { type: 'text/csv;charset=utf-8;' });
        let dwldLink = document.createElement(&quot;a&quot;);
        let url = URL.createObjectURL(blob);
        let isSafariBrowser = navigator.userAgent.indexOf('Safari') != -1 &amp;&amp; navigator.userAgent.indexOf('Chrome') == -1;
        if (isSafariBrowser) {  //if Safari open in new window to save file with random filename.
            dwldLink.setAttribute(&quot;target&quot;, &quot;_blank&quot;);
        }
        dwldLink.setAttribute(&quot;href&quot;, url);
        dwldLink.setAttribute(&quot;download&quot;, filename + &quot;.csv&quot;);
        dwldLink.style.visibility = &quot;hidden&quot;;
        document.body.appendChild(dwldLink);
        dwldLink.click();
        document.body.removeChild(dwldLink);
    }

    ConvertToCSV(objArray, headerList) {
         let array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
         let str = '';
         let row = 'S.No,';

         for (let index in headerList) {
             row += headerList[index] + ',';
         }
         row = row.slice(0, -1);
         str += row + '\r\n';
         for (let i = 0; i &lt; array.length; i++) {
             let line = (i+1)+'';
             for (let index in headerList) {
                let head = headerList[index];

                 line += ',' + array[i][head];
             }
             str += line + '\r\n';
         }
         return str;
     }
}
</code></pre>
<p>I will be having an <strong>Export to CSV</strong> button in the <strong>app.component.html</strong>, which on clicking should execute the <code>download()</code> method of <strong>app.component.ts</strong> which uses <code>downloadFile()</code> of <strong>AppService</strong></p>
<p><strong>app.component.ts</strong></p>
<pre><code>import { Component } from '@angular/core';
import { AppService } from './app.service';

@Component({
 ...
})
export class AppComponent  {

  constructor(private appService:AppService) {  }

    jsonData =  [
      ...
    ];

  download(){
    this.appService.downloadFile(this.jsonData, 'jsontocsv');
  }
}
</code></pre>
",https://stackoverflow.com/questions/67298648/angular-unit-testing-how-to-write-unit-testcases-for-the-app-service-ts-using-j,"['angular', 'unit-testing', 'karma-jasmine']",388,False,-1,1
Angular Unit Testing facing problem in initialization form and subscribing value changes of form,"<p>i'm new in unit testing in angular actually i facing a issue while initialization of form group</p>
<pre><code>  it('should be able to init forms', () =&gt; {

        service.organizationForm = formBuilder.group({})
        service.initOrganizationForm()
})
</code></pre>
<p>while initOrganizationForm function is called in this function there is catch</p>
<pre><code>this.organizationForm.valueChanges.
            subscribe(form =&gt; {
                this.organizationButtonsData[1]['disabled'] = this.organizationForm.valid ? false : true;
                this.getRequiredCount();
            });
</code></pre>
<p>so becuase of this code i am getting this error</p>
<pre><code> should be able to init forms
     Setting Management Service
     TypeError: Cannot read property 'valueChanges' of undefined
    at &lt;Jasmine&gt;
    at SettingManagementService.valueChanges [as initOrganizationForm] (http://localhost:9876/_karma_webpack_/src/app/core/services/settings.management.service.ts:465:31)
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/src/app/core/services/settings.management.service.spec.ts:74:17)
</code></pre>
",https://stackoverflow.com/questions/65577331/angular-unit-testing-facing-problem-in-initialization-form-and-subscribing-value,"['angular', 'unit-testing', 'angular-unit-test']",101,False,0,0
linking with wrap directive for unit testing can be used to redefine a subroutine?,"<p>I'm using Cmocka to write a unit testing suite for a shared object written in C, but I'm having some issue. Since I cannot share the source code, I have written a minimum &quot;not-working&quot; example to show what is the issue:</p>
<p>my program is composed 5 files: foo.c, foo.h bar.c bar.h main.c.</p>
<ul>
<li>bar.* files define a bar() function, which simply returns the argument multiplied by 2</li>
<li>foo.* files declare a foo() function that uses the bar() function defined by bar.h</li>
<li>main.c contains a simple cmocka test and a <em><strong>__wrap_bar()</strong></em></li>
</ul>
<p>function, returning the argument multiplied by 3.</p>
<p>I compile the program by producing a libfootest.so object (foo+bar) and then I link this object with main.o passing the -Wl,--wrap=bar flag to the compiler.  In this configuration <strong>libfootest</strong> is the module under test and main is the tester program. I expect the __wrap__bar to be called (failing the test), but the standard bar() is called(test is passed). How can I solve this problem? Below you find all the code I'm using.</p>
<p>bar.c:</p>
<pre><code>#include &quot;bar.h&quot;
int bar(int val) {
    return val*2;
}
</code></pre>
<p>bar.h:</p>
<pre><code>int bar(int val);
</code></pre>
<p>foo.h:</p>
<pre><code>#include &lt;stdio.h&gt;

int foo(int val);
</code></pre>
<p>foo.c:</p>
<pre><code>#include &quot;foo.h&quot;
#include &quot;bar.h&quot;
int foo(int val) {
    int ret;
    ret = bar(val);
    printf(&quot;RET: %d&quot;, ret);
    return ret;
}
</code></pre>
<p>main.c:</p>
<pre><code>#include &lt;stdio.h&gt;
//required include for CMOCKA
#include &lt;stdarg.h&gt;
#include &lt;stddef.h&gt;
#include &lt;stdint.h&gt;
#include &lt;setjmp.h&gt;
#include &lt;cmocka.h&gt;


//library under test
#include &quot;foo.h&quot;
int __wrap_bar(int val) {
        return 3*val;
}


static void test_foo(void **state) {
    int ret = foo(5);
    assert_int_equal(ret, 10);
    

}

int main (int argc, char** argv) {
    const struct CMUnitTest tests[] = {
        cmocka_unit_test(test_foo),
    };

    return cmocka_run_group_tests(tests, NULL, NULL);
}
</code></pre>
<p>Makefile:</p>
<pre><code>CMOCKA_LIB_DIR=../../cmocka-1.1.5/build/src
CXXFLAGS+=-g -Og  -fPIC
CFLAGS+=-g  -Og  -std=c99 -fPIC
CC=gcc
CXX=g++

all: main.o ./libfootest.so
    gcc -o linux-test -g -L. -L$(CMOCKA_LIB_DIR) $(filter %.o, $^) -lcmocka -lfootest -Wl,-rpath=. -Wall -Wl,--wrap=bar -Wl,-rpath=$(CMOCKA_LIB_DIR)

./libfootest.so: foo.o bar.o
    $(CC) -shared -o $@ -g $^  -pedantic -Wall

clean: 
    rm -f *.o
    rm -f *.so
</code></pre>
",https://stackoverflow.com/questions/68257570/linking-with-wrap-directive-for-unit-testing-can-be-used-to-redefine-a-subroutin,"['c', 'unit-testing', 'gcc', 'ld', 'cmocka']",170,True,0,1
Angular unit testing for public void method which clears input filed on mat selectionChange,"<p>I am new to this job and programming and my task is to unit test and get 80 percent code coverage. I am not able to get code coverage for this method. It says statement not covered. What am I doing wrong?</p>
<p><strong>support.component.ts</strong></p>
<pre><code>searchId: string = '';

orchestration: string = '';


public clearText(){

this.searchId = '';
this.orchestration = '';

}
</code></pre>
<p><strong>support.component.html</strong></p>
<pre><code>&lt;mat-select id=&quot;searchselected&quot; (selectionChange)=&quot;clearText()&quot;&gt;

&lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;searchId&quot; [(ngModel)]=&quot;&quot;searchId size=&quot;40&quot; placeholder=&quot;enter value&quot;&gt;
&lt;input type=&quot;text&quot; class=&quot;form-control&quot; id=&quot;orchestration&quot; [(ngModel)]=&quot;&quot;searchId size=&quot;40&quot; placeholder=&quot;enter orchestration&quot;&gt;
</code></pre>
<p><strong>support.component.spec.ts</strong></p>
<pre><code>const spy = spy = spyon(component, 'clearText').and.callThrough();

component.searchId;
component.orchestration;


component.clearText();

expect(spy).toHaveBeenCalled();
expect(component.searchId).toEqual('');
expect(component.orechestion).toEqual('');
</code></pre>
",https://stackoverflow.com/questions/65896157/angular-unit-testing-for-public-void-method-which-clears-input-filed-on-mat-sele,"['angular', 'angular-test']",323,False,0,1
&quot;RuntimeError: No application found.&quot; when doing unit testing in Python with Flask and SQLAlchemy,"<p>I just started to work on python application that use Flask and SQL Alchemy. I have to do the unit tests of all the routes (no unit test had been done yet) but I have a problem when I try to run the test :</p>
<p>the route :</p>
<pre><code>class AuthResetPassword(Resource):
@cross_origin()
def post(self):
    try:
        body = request.get_json()
        email = body.get('email')
        token = body.get('token')
        password = body.get('password')

        user = User.query.filter_by(email=email).first()

        if token != user.token:
            return flask.make_response(flask.jsonify(success=False, error={&quot;code&quot;: 115, &quot;message&quot;: &quot;Token incorrect&quot;}), 403)

        hashed = bcrypt.hashpw(password.encode(&quot;utf-8&quot;), bcrypt.gensalt())
        user.password = hashed.decode(&quot;utf-8&quot;)
        db.session.commit()
        send_email('Password Reset',
                   sender='derush.app@gmail.com',
                   recipients=[user.email],
                   text_body='Your password was succesfully reset.',
                   html_body='&lt;p&gt;Your password was succesfully reset.&lt;/p&gt;')
        return flask.make_response(flask.jsonify(success=True), 200)
    except Exception as e:
        raise InternalServerError
</code></pre>
<p>the test :</p>
<pre><code>class TestAuthResource(unittest.TestCase):
    @mock.patch(&quot;pomelo_backend.user.User.query.filter_by&quot;)
    @mock.patch(&quot;pomelo_backend.api_base.db.session.commit&quot;)
    @mock.patch(&quot;pomelo_backend.resources.AuthResource.send_email&quot;)
    def test_post(self, mock_select_user, mock_db_commit, mock_send_email):
        user_correct_token = json.dumps({&quot;email&quot;: &quot;user@user.com&quot;, &quot;token&quot;: &quot;correctToken&quot;, &quot;password&quot;: &quot;password&quot;})
        user_wrong_token = json.dumps({&quot;email&quot;: &quot;user@user.com&quot;, &quot;token&quot;: &quot;wrongToken&quot;, &quot;password&quot;: &quot;password&quot;})

        correct_token_response = json.dumps({&quot;success&quot;: True})
        wrong_token_user = json.dumps({&quot;success&quot;: False, &quot;error&quot;: {&quot;code&quot;: 115, &quot;message&quot;: &quot;Token incorrect&quot;}})

        mock_select_user.return_value(user_correct_token)
        mock_db_commit.return_value(True)
        mock_send_email.return_value(True)

        response_user_correct_token = AuthResetPassword.post(user_correct_token)
        response_user_wrong_token = AuthResetPassword.post(user_wrong_token)

        self.assertEqual(response_user_correct_token, correct_token_response)
        self.assertEqual(response_user_wrong_token, wrong_token_user)
</code></pre>
<p>But it returns : &quot;RuntimeError: No application found. Either work inside a view function or push an application context.&quot;
I tried to instantiate the app with this but it doesn't work :</p>
<pre><code>db = SQLAlchemy()

def create_app():
    app = Flask(__name__)
    db.init_app(app)
    return app
</code></pre>
<p>I don't find template or tutorial online that helps, most of the time it's too simplistic.
Thanks!</p>
",https://stackoverflow.com/questions/67198114/runtimeerror-no-application-found-when-doing-unit-testing-in-python-with-fla,"['python', 'unit-testing', 'flask', 'sqlalchemy', 'flask-sqlalchemy']",40,False,0,0
Jest testing Vue lifecycle or async method doesn&#39;t await for result in unit-testing,"<p>I'm trying to implement unit testing with Jest for a Vue component which on created() lifecycle calls a function which has axios who runs async.
The thing is, the created is being triggered, but the value of the object that sits in the component data section won't show it's new value. (remains undefined, tested also when initialized with some other value then undefined)</p>
<p>I've used many solutions that was offered around here but nothing was 100% accurate to the situation I'm dealing with.</p>
<p>Products component:</p>
<pre><code>   data() {
      return {
        products: undefined,
        countries: undefined,
        fields: undefined,
        selectedItem: undefined,
        alert: undefined,
     };
  },
  methods: {
    async getProducts() {
      try {
        let res = await axios.get(&quot;http://localhost:5000&quot;);
        this.products = res.data.products;
        this.countries = res.data.countries;
        this.fields = Object.keys(this.products[0]).splice(1);
        this.fields.push({ key: &quot;Edit&quot;, label: &quot;Click &amp; Edit&quot; });
        } 
        catch (error) {
        this.toggleAlert(true, &quot;Failed to retrieve data from server&quot;);
        console.log(error);
        }
    },
  }
  created() {
    this.getProducts();
  }
</code></pre>
<p>testfile:</p>
<pre><code>// create an extended `Vue` constructor
   const localVue = createLocalVue();
// install plugins as normal 
   localVue.use(BootstrapVue);
   describe(&quot;Testing Products component:&quot;, () =&gt; {
       test(&quot;checks the incoming data from api&quot;, async () =&gt; {
          const wrapper = shallowMount(Products, { localVue });
          await flushPromises();
          console.log(wrapper.vm.$data.products, &quot;products&quot;); //prints undefined instead of an array
          expect(wrapper.vm.$data.products).not.toBe(undefined);
  });
});

</code></pre>
",https://stackoverflow.com/questions/68517663/jest-testing-vue-lifecycle-or-async-method-doesnt-await-for-result-in-unit-test,"['vue.js', 'unit-testing', 'jestjs']",307,False,0,0
How to mock eventHubclient (azure/event-hub) producer connectivity for unit testing using mocha?,"<p>Below is the node js code
I want to mock the eventHub connection in order to invoke the API call.</p>
<pre><code>
const { EventHubProducerClient } = require(&quot;@azure/event-hubs&quot;);

const connectionString = &quot;EVENT HUBS NAMESPACE CONNECTION STRING&quot;;
const eventHubName = &quot;EVENT HUB NAME&quot;;

async function main() {

  // Create a producer client to send messages to the event hub.
  const producer = new EventHubProducerClient(connectionString, eventHubName);

  // Prepare a batch of three events.
  const batch = await producer.createBatch();
  batch.tryAdd({ body: &quot;First event&quot; });
  batch.tryAdd({ body: &quot;Second event&quot; });
  batch.tryAdd({ body: &quot;Third event&quot; });    

  // Send the batch to the event hub.
  await producer.sendBatch(batch);

  // Close the producer client.
  await producer.close();

  console.log(&quot;A batch of three events have been sent to the event hub&quot;);
}

main().catch((err) =&gt; {
  console.log(&quot;Error occurred: &quot;, err);
});
</code></pre>
<p>please help thanks in advance.</p>
",https://stackoverflow.com/questions/68808576/how-to-mock-eventhubclient-azure-event-hub-producer-connectivity-for-unit-test,"['node.js', 'unit-testing', 'mocha.js', 'chai']",1432,True,0,1
How do I correctly mock a debounce event when unit testing UI in jest?,"<p>I currently have a unit test that will mock the click of a button. I've recently added a debounce function around it:</p>
<pre class=""lang-js prettyprint-override""><code>import * as lodash from 'lodash';

//...bunch of code in between

const buttonChangerTrue= lodash.debounce(() =&gt; buttonChanger(true, row), 500);
</code></pre>
<p>This click of the button will cause a change in the UI which will basically change the icon color (assuming the end user doesn't rapidly click it).</p>
<p>For the sake of brevity, I've removed the excess code for the test</p>
<pre class=""lang-js prettyprint-override""><code>this.when.push({

            beforeEachRender: () =&gt; {

                count++;
                jest.useFakeTimers();
                if (count === 1) {
                    this.mockHttpRequests();
                } else {
                    this.mockHttpRequestsReversed('buttonPressed');
                }

            },

            describe: 'When an unsaved search is ran and an agent is pinned',

            then: async () =&gt; {
                test('Then a note should be created', async () =&gt; {


                    const button = tableBody.children[1].children[1].children[0].children[0];
                    const stickyNoteBeforePinning =
                        this.getById(document.body, 'notes-69fc105ad2c94edf16efb1f4de125c38093aefe9') as HTMLElement;

                    if (!button ) {
                        throw 'button  not found';
                    }

                    await wait(() =&gt; {
                        fireEvent.click(button);
                    });

                    jest.runTimersToTime(1000);

                    const stickyNoteAfterPinning =
                        this.getById(document.body, 'notes-ec9c2a3041a18a4a7d8d8b4943292cb8aa92a2f5') as HTMLElement;

                    expect(stickyNoteBeforePinning).toHaveAttribute('class', 'lead material-icons text-light');
                    expect(stickyNoteBeforePinning).not.toBe(stickyNoteAfterPinning);
                    expect(stickyNoteAfterPinning).toHaveAttribute('class', 'lead material-icons text-pink'); // Fails here
                });

            },
        });
</code></pre>
<p>Please let me know if you need more information but this click of a button does make an API call, I've mocked the call in the test as well. When I remove the debounce function and run it as normal -- it passes the test just fine. I've tried a number of things like <code>jest.useFakeTimers();</code> in the <code>beforeEachRender</code> portion and calling <code>jest.runTimersToTime(1000);</code> right after it. I've also tried using <code>jest.advanceTimersByTime(500);</code> right after the click too. Nothing seems to be working.</p>
<p>Edit: I ended up removing the tests for now. I read that Jest does have a version that can take into account something like <code>jest.useFakeTimers('modern');</code> and that will simulate the debouncing. Will report back if I can get results on that.</p>
",https://stackoverflow.com/questions/68865464/how-do-i-correctly-mock-a-debounce-event-when-unit-testing-ui-in-jest,"['javascript', 'unit-testing', 'jestjs', 'debouncing']",644,False,0,1
Assigning html tag a value using interpolation throws error during unit testing in angular,"<p>I am trying to run a unit test in angular. But I am getting the below error message. It is not throwing during compilation process and my application works fine as expected  but this error is thrown only when the unit testing is carried out.</p>
<blockquote>
<p><strong>Error message</strong>: Template parse error,Cant bind to ngxrow since it is not a known property of div.  &lt;div [ERROR -&gt;]ngxcol=&quot;{{newwidth}}&quot;&gt;</p>
</blockquote>
<p>I am not sure if the error is due to assigning value using interpolation {{}}.Is there anyway I can fix this. Trying to find a solution for past  2 days
Below is my partial code:</p>
<h2>component.html</h2>
<pre><code>&lt;div ngxlayout=&quot;grid&gt;
 &lt;div ngxrow&gt;
  &lt;div ngxcol={{newwidth}}&gt;
   html core logic implemented
  &lt;/div&gt;
 &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<h2>component.ts</h2>
<pre><code>export class AppComponent {
newwidth:any=&quot;30&quot;
constructor(){}
}
</code></pre>
<p>I am not getting error if i directly assign the width as 30 in the ngxcol property directly but issue happens only if the value 30 is assigned using interpolation.</p>
",https://stackoverflow.com/questions/69663684/assigning-html-tag-a-value-using-interpolation-throws-error-during-unit-testing,"['html', 'angular', 'jestjs', 'karma-jasmine']",125,True,0,1
"unit testing ava + sinon for api call, one of the stub is not working","<p>I have a test case need to test a function which has 2 upper layer promise functions.
I stub all of these 3 functions, the first 2 works fine, but the last one seems like no working..</p>
<pre><code>classD:

const obj1 = require('./classA');
const obj2 = require('./classB');
const obj3 = require('./classC');

const getTeam = () =&gt;{
    return new Promise((resolve, reject) =&gt; {
        obj1.promiseFunc1().then(res1 =&gt; {
            if(res1.error){
              reject(res1); 
            }else{
              resolve({Teamid: 1, TeamName: 'goodName'});
            }
    })
}

const getMember = () =&gt; {
    return new Promise((resolve, reject) =&gt; {
      obj2.promiseFunc2().then(res2 =&gt; {
        if(res2.id.length === 0){
          obj3.promiseFunc3().then(res3 =&gt; {
            if(res3.error){
              reject(res3); 
            }else{
              getTeam().then(res =&gt; {
                 if(res.error){
                    reject(res);
                  }else{
                   resolve(res);
                  }
              });
            }
        })
      }
   })    
 })
}
</code></pre>
<p>Below is the test case:</p>
<pre><code>Test.js

const obj1 = require('./classA');
const obj2 = require('./classB');
const obj3 = require('./classC');
const obj4 = require('./classD');
const sandbox = require('sinon').createSandbox();

test.serial('test getMember', async (t) =&gt; {
  sandbox.restore();
  sandbox.stub(obj2, 'promiseFunc2').resolves({id: [], error: false});
  sandbox.stub(obj3, 'promiseFunc3').resolves({status: 200, error: false});

  sandbox.stub(obj4, 'getTeam').resolves({data: [], error: false});

  const result = await obj4.getMember();
  console.log('result :' + JSON.stringify(result));
})
</code></pre>
<p>So I need to runa test case for the function obj4.getMember() which will call obj2.promiseFunc2, obj3.promiseFunc3, and obj4.getTeam(), they all return promises. I stub the promiseFunc2 and promiseFunc3 with no problem. But for some reason the obj4.getTeam() seems like not working well. I returned {Teamid: 1, TeamName: 'goodName'} which is the response from last test cases in the same file for getTeam()...</p>
<p>I expected to return {data: [], error: false} which is the outcome I stub for..</p>
<p>Anyone know why the stub is not working? How to make it work?</p>
<p>Thank you very much!</p>
",https://stackoverflow.com/questions/66571497/unit-testing-ava-sinon-for-api-call-one-of-the-stub-is-not-working,"['javascript', 'node.js', 'unit-testing', 'sinon', 'ava']",390,True,0,1
How to approach instantiating a class within a class in unit testing using JS,"<p>Having issues on how to approach this test suite. I am asked to instantiate the Beer class within a method in the Bartender class. I want my takeOrder method to take in multiple inputs so therefore I need to call the Beer class constructor inside takeOrder.</p>
<p>This is my Beer class:</p>
<pre><code>  constructor(newBeer) {
    this.brewer = newBeer.brewer;
    this.name = newBeer.name;
    this.type = newBeer.type;
    this.price = newBeer.price;
    this.volume = newBeer.volume;
    this.isFlat = false;
  }
}
</code></pre>
<p>I have to push an instance of Beer into the orders array in the Bartender class and I am not sure how to approach. Here's my code for the Bartender class:</p>
<pre><code>class Bartender {
  constructor(name, hourlyWage){
    this.name = name;
    this.hourlyWage = hourlyWage;
    this.orders = [];
  }
  takeOrder(newOrder) {
    var newOrder = new Beer();
    this.orders.push(newOrder);
  }
}
</code></pre>
<p>I keep getting this error message on my npm test:</p>
<pre><code> 1) Bartender
       should be able to take orders:
     AssertionError: expected 'Grand Teton Brewing' to be an instance of Beer
      at Context.&lt;anonymous&gt; (test/bartender-test.js:33:12)
      at processImmediate (node:internal/timers:464:21)

</code></pre>
<p>This is the bartender unit test I keep failing:</p>
<pre><code>it('should be able to take orders', function() {
    var bartender = new Bartender(&quot;Chaz&quot;, 8.50);

    bartender.takeOrder(&quot;Grand Teton Brewing&quot;, &quot;Bitch Creek&quot;, &quot;Brown Ale&quot;, 7, 16);

    assert.instanceOf(bartender.orders[0], Beer);
    assert.equal(bartender.orders.length, 1);
    assert.equal(bartender.orders[0].brewer, 'Grand Teton Brewing');
    assert.equal(bartender.orders[0].name, 'Bitch Creek');
    assert.equal(bartender.orders[0].type, 'Brown Ale');
    assert.equal(bartender.orders[0].price, 7);
    assert.equal(bartender.orders[0].volume, 16);
  });
</code></pre>
<p>Lmk if anyone has any advice. Thanks.</p>
",https://stackoverflow.com/questions/69303704/how-to-approach-instantiating-a-class-within-a-class-in-unit-testing-using-js,"['javascript', 'arrays', 'class']",21,False,0,1
How do I do an Angular unit testing karma jasmine of this string function?,"<p>Angular unit testing karma jasmine of this string function, layouts come from the backend (layout.ts) - it should return a string like (1-&quot;ABC&quot;-(active))</p>
<pre><code>getSelectedLayout(): string {
const p = new ActivePipe();
if(this.layoutId === ''){
this.layoutId = this.layouts.find((x)=&gt;x.status ===true)?.gridId.toString() as string;
}
const selectedLayout = this.layouts.find((x)=&gt;x.gridId.toString() === this.layoutId);
return(
selectedLayout?.gridId + '-' + selectedLayout?.name + '(' + p.transform(selectedLayout?.status) + ')' ); }
</code></pre>
",https://stackoverflow.com/questions/68588132/how-do-i-do-an-angular-unit-testing-karma-jasmine-of-this-string-function,"['angular', 'unit-testing', 'testing', 'jasmine', 'karma-runner']",167,False,0,0
Unit Testing Custom React Hooks in TypeScript using Jest and @testing-library/react-hooks,"<p>I have a custom hook that takes a product id and toggles with <code>value (boolean)</code> and <code>toggle</code> as the returns. I'm trying to write a unit test for it, following the example <a href=""https://betterprogramming.pub/test-custom-hooks-using-react-hooks-testing-library-a3a37031a9be"" rel=""nofollow noreferrer"">here</a>, but I'm getting TypeScript type-mismatch errors (the example I'm following isn't typescripted).</p>
<p><strong>Custom Hook:</strong></p>
<pre><code>export default function useToggle(id: number): [boolean, () =&gt; void] {
  const [value, setValue] = React.useState(false);

  useEffect(() =&gt; {
    try {
      const data = localStorage.getItem(ITEMS);
      const all = data ? JSON.parse(data) : {};
      setValue(!!all[id]);
    } catch (error) {
      console.error('items localStorage get error', error);
      setValue(false);
      localStorage.removeItem(ITEMS);
    }
  }, [id]);

  function toggle() {
    try {
      const data = localStorage.getItem(ITEMS);
      const all = data ? JSON?.parse(data) : {};
      all[id] = !all[id];
      localStorage.setItem(ITEMS, JSON.stringify(all));

      setValue(v =&gt; !v);
    } catch (error) {
      console.error('items localStorage set error', error);
    }
  }

  return [value, toggle];
}
</code></pre>
<p><strong>Test in progress:</strong></p>
<pre><code>
describe('useToggle', () =&gt; {
  it('returns value and toggle', () =&gt; {
    const { result } = renderHook(() =&gt; useToggle(1));
    const { value, toggle }: [boolean, () =&gt; void] = result.current;

    expect(value).toBe(false);
    expect(setValue).toBeDefined();

  });
});
</code></pre>
<p><strong>Error:</strong>
Where I'm defining <code>value</code> and <code>toggle</code>, I'm getting <code>Property 'value' does not exist on type '[boolean, () =&gt; void]'.</code> and <code>Property 'toggle' does not exist on type '[boolean, () =&gt; void]'.</code></p>
<p>Am I setting up the type definition incorrectly or is something else going wrong? Any guidance would be appreciated. Thanks!</p>
",https://stackoverflow.com/questions/69995218/unit-testing-custom-react-hooks-in-typescript-using-jest-and-testing-library-re,"['javascript', 'reactjs', 'typescript', 'react-hooks', 'jestjs']",1027,True,0,1
Unit testing a Web API controller actualResult using moq does not behave as expected,"<p>Unit testing a controller returning <code>IHttpActionResult</code> causes</p>
<blockquote>
<p>System.NullReferenceException: 'Object reference not set to an instance of an object.</p>
</blockquote>
<pre><code>[HttpGet]
public async Task&lt;IHttpActionResult&gt; Get(Guid myId)
{    
    var myaccount = await _myaccountService.GetMyAccount(myId);
    return Ok(myaccount);
}
</code></pre>
<p>In Test Method the code</p>
<pre><code>var actualResult = (await controller.Get(It.IsAny&lt;Guid&gt;()) as OkNegotiatedContentResult&lt;IEnumerable&lt;MyAccount&gt;&gt;).Content;
</code></pre>
<p>Returns</p>
<blockquote>
<p>System.NullReferenceException: 'Object reference not set to an instance of an object.**</p>
</blockquote>
<pre><code>[TestMethod]
public async Task GeMyAccount_Returns_CorrectData()
{
      // Arrange         
      var expectedResult = new List&lt;MyAccount&gt;
     {
         new  MyAccount
          {
           Id = &quot;1&quot;,
           Name = &quot;Name1&quot;
          },
         new  MyAccount
          {
           Id = &quot;2&quot;,
           Name = &quot;Name2&quot;
          },
     };

    //Act 
    var mockMyAccountService = new Mock&lt;IMyAccountService&gt;();
    mockMyAccountService.Setup(mock =&gt; 
    mock.GetMyAccount(It.IsAny&lt;Guid&gt;())).Returns(Task.FromResult(expectedResult));
    var controller = new MyAccountController(mockMyAccountService.Object);

     var actualResult = (await controller.Get(It.IsAny&lt;Guid&gt;()) as 
    OkNegotiatedContentResult&lt;IEnumerable&lt;MyAccount&gt;&gt;).Content;
    mockOnrAccountService.Verify(m =&gt; m.GetMyAccount(It.IsAny&lt;Guid&gt;()));
    Assert.AreEqual(expectedResult, actualResult);
</code></pre>
<p>Not sure what I am doing wrong.</p>
",https://stackoverflow.com/questions/68764689/unit-testing-a-web-api-controller-actualresult-using-moq-does-not-behave-as-expe,"['c#', 'unit-testing', 'asp.net-web-api', 'nunit', 'moq']",100,True,0,1
Unit testing a repository with paging 3 using a a remote mediator and paging source,"<p>I am trying to unit test a repository class in android which is using paging with a remote mediator and paging source.</p>
<p>But when I run the test the returned result is empty, although actual should contain the test item.</p>
<p>Like below :</p>
<p><strong>Here is my repository</strong></p>
<pre><code>class PostsRepository @Inject constructor(
    private val postsApi: AutomatticPostsApi,
    private val postsDao: PostDao
) : IPostsRepository {

    @ExperimentalPagingApi
    override fun loadPosts(): Flow&lt;PagingData&lt;Post&gt;&gt; {
        println(&quot;loadPosts&quot;)
        return Pager(
            config = PagingConfig(20),
            initialKey = 1,
            remoteMediator = PostsPageRemoteMediator(
                postsApi,
                postsDao
            ),
            pagingSourceFactory = { postsDao.getPostsPagingSource() }
        ).flow.map { pagingData -&gt;
            pagingData.map { it.toPost() }
        }
    }

}
</code></pre>
<p><strong>Here is my UT</strong></p>
<pre><code>@ExperimentalCoroutinesApi
@ExperimentalPagingApi
class PostsRepositoryTest {
    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    private val coroutineDispatcher = TestCoroutineDispatcher()
    private lateinit var postDao: FakePostDao
    private lateinit var postsApi: CommonAutomatticPostsApi
    private val remotePosts = listOf(createDummyPostResponse())
    private val domainPosts = remotePosts.map { it.toPost() }

    //GIVEN: subject under test
    private lateinit var postsRepository: PostsRepository

    @Before
    fun createRepository() =  coroutineDispatcher.runBlockingTest {
        postsApi = CommonAutomatticPostsApi(remotePosts.toMutableList())
        postDao = FakePostDao()
        postsRepository = PostsRepository(postsApi, postDao)
    }

    @Test
    fun loadPosts_returnsCorrectPosts() = runBlockingTest {
        //WHEN: posts are retrieved from paging source

        launch {

            postsRepository.loadPosts().collect { pagingData -&gt;

                val posts = mutableListOf&lt;Post&gt;()
                pagingData.map {

                    posts.add(it)
                    println(it)
                }

                //THEN: retrieved posts should be the remotePosts
                assertThat(posts, IsEqual(domainPosts))
            }

        }

    }
}
</code></pre>
<p><strong>Here is the FakeApi, FakePagingSource and FakeDao</strong></p>
<pre><code>class CommonAutomatticPostsApi(val posts: MutableList&lt;PostResponse&gt; = mutableListOf()) : AutomatticPostsApi {
    companion object {
        const val SUBSCRIBER_COUNT = 2L
        const val AUTHOR_NAME = &quot;RR&quot;
    }

    override suspend fun loadPosts(page: Int, itemCount: Int): PostsResponse {
        println(&quot;Loaded&quot;)
        return PostsResponse(posts.size.toLong(), posts)
    }
}

class FakePostsPagingSource() : PagingSource&lt;Int, PostEntity&gt;() {
    var triggerError = false
    var posts: List&lt;PostEntity&gt; = emptyList()
        set(value) {
            println(&quot;set&quot;)
            field = value
            invalidate()
        }

    override suspend fun load(params: LoadParams&lt;Int&gt;): LoadResult&lt;Int, PostEntity&gt; {
        println(&quot;load&quot;)
        if (triggerError) {
            return LoadResult.Error(Exception(&quot;A test error triggered&quot;))
        }
        println(&quot;not error&quot;)

        return LoadResult.Page(
            data = posts,
            prevKey = null,
            nextKey = null
        )
    }

    override fun getRefreshKey(state: PagingState&lt;Int, PostEntity&gt;): Int? {
        println(&quot;refresh&quot;)

        return state.anchorPosition ?: 1
    }
}

class FakePostDao(val posts: MutableList&lt;PostEntity&gt; = mutableListOf()) : PostDao {
    val pagingSource = FakePostsPagingSource()

    override suspend fun insertPosts(posts: List&lt;PostEntity&gt;) {
        this.posts.addAll(posts)
        println(&quot;insertPosts&quot;)
        updatePagingSource()
    }

    override suspend fun updatePost(post: PostEntity) {
        onValidPost(post.id) {
            posts[it] = post
            updatePagingSource()
        }
    }

    private fun onValidPost(postId: Long, block: (index: Int) -&gt; Unit): Boolean {
        println(&quot;onValidPost&quot;)

        val index = posts.indexOfFirst { it.id == postId }
        if (index != -1) {
            block(index)
            return true
        }

        return false
    }

    override suspend fun updatePost(postId: Long, subscriberCount: Long) {
        onValidPost(postId) {
            posts[it] = posts[it].copy(subscriberCount = subscriberCount)
            updatePagingSource()
        }
    }

    override suspend fun getPostById(postId: Long): PostEntity? {
        val index = posts.indexOfFirst { it.id == postId }
        return if (index != -1) {
            posts[index]
        } else {
            null
        }
    }

    override suspend fun getPosts(): List&lt;PostEntity&gt; {
        println(&quot;getPosts&quot;)

        return posts
    }

    override fun getPostsPagingSource(): PagingSource&lt;Int, PostEntity&gt; {
        println(&quot;getPostsPagingSource&quot;)

        return pagingSource
    }

    override suspend fun clearAll() {
        posts.clear()
        updatePagingSource()
    }

    private fun updatePagingSource() {
        println(&quot;updatePagingSource&quot;)

        pagingSource.posts = posts
    }

    @Transaction
    override suspend fun refreshPosts(newPosts: List&lt;PostEntity&gt;) {
        println(&quot;refreshPosts&quot;)
        clearAll()
        insertPosts(newPosts)
    }
}
</code></pre>
",https://stackoverflow.com/questions/66503911/unit-testing-a-repository-with-paging-3-using-a-a-remote-mediator-and-paging-sou,"['android', 'unit-testing', 'paging', 'android-paging-3']",2805,True,4,2
How do I mock a realine of a GLOB ref when unit testing in perl?,"<p>For example in the following code how do I mock readline to unit test the do_stuff routine?</p>
<p>I think I require</p>
<ol>
<li>$sock must be a GLOB reference.</li>
<li>readline() must be mocked.</li>
</ol>
<p>I tried using FileHandle-&gt;new but got error - &quot;readline() on unopened filehandle GEN1&quot;
which I took as readline() wasn't being mocked.</p>
<p>I tried an Test::MockObject (not extends), with readline() mocked, but that had the error
&quot;Not a GLOB reference&quot; which reminded me that readline() isn't being called as a method.</p>
<pre><code>package MyIO;

sub get_sock{ return IO::Socket::INET-&gt;new(@tcp_arg); }

sub do_stuff {
    my $sock = get_sock();
    my $line1 = &lt;$sock&gt;;
    my $line2 = readline($sock);
    return;
}

package TestMyIO;

sub test_do_stuff{
    # my $mock_sock = Test::MockObject::Extends-&gt;new(IO::Socket::INET-&gt;new);

    my $mock_sock = die(&quot;TODO&quot;);
    my @fake_lines = ('line 1', 'line 2', 'line 3');

    no warnings 'redefine';    ## no critic (ProhibitNoWarnings)
    local *MyIO::get_sock = sub { return $mock_sock; };
    local *MyIO::readline = sub { return shift @fake_lines; };
    use warnings 'redefine';

}
</code></pre>
",https://stackoverflow.com/questions/68523411/how-do-i-mock-a-realine-of-a-glob-ref-when-unit-testing-in-perl,"['unit-testing', 'perl']",91,True,2,2
IllegalStateException when a getString() is called inside a Fragment Class when Unit Testing with Robolectric,"<p>I am getting IllegalStateException when a getString() is called inside a Fragment Class</p>
<pre><code>Caused by: java.lang.IllegalStateException: Fragment SomeFragment{1df37025} (29efd1d0-77c1-4293-a0f6-b808c7559cf4)} not attached to a context.
at androidx.fragment.app.Fragment.requireContext(Fragment.java:805)
at androidx.fragment.app.Fragment.getResources(Fragment.java:869)
at androidx.fragment.app.Fragment.getString(Fragment.java:891)
</code></pre>
<p><strong>SomeFragment</strong> Code</p>
<pre><code>public void someMethod() {
    getString(R.string.some_res)
}
</code></pre>
<p>Test Code</p>
<pre><code>@Before
fun setUp() {
    val activity = Robolectric.buildActivity(SomeActivity::class.java).create().get()
    fragment = SomeFragment()
    fragmentManager = activity.supportFragmentManager
    val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
    fragmentTransaction.add(fragment, null)
    fragmentTransaction.commit()
}

@Test
@Throws(Exception::class)
fun someTest() {
    fragment.someMethod()
}
</code></pre>
",https://stackoverflow.com/questions/69183141/illegalstateexception-when-a-getstring-is-called-inside-a-fragment-class-when,"['java', 'android', 'unit-testing', 'kotlin', 'robolectric']",226,True,2,1
"sinon stub a firebase collection with chained methods for unit testing...(sinon, node/express, Jasmine)","<p>In my nodejs code, I have a snippet:</p>
<pre><code>   await cfDB.collection('users').doc(userAccount.uid).set({
      email: 'email@domain.com',
      firstName: 'firstname',
      lastName: 'Lastname,
    });
</code></pre>
<p>How would I create a sinon mock of this for unit test with jasmine?</p>
<p>more complete context....</p>
<pre><code> const { Firestore } = require('@google-cloud/firestore');

  const cfDB = new Firestore();

  // Create Firestore user document
  try {
    await cfDB.collection('users').doc('E7skP0IncSW7wkBxnrYFx6udzGH2').set({
      email: 'email@domain.com',
      firstName: 'Firstname',
      lastName: 'Lastname',
    });


  } catch (error) {
    res.json({ success: false, payload: { message: 'Firebase User write error. ' + error } });
    return;
  }

  // Success
  res.json({ success: true, payload: { message: 'User created.', userAccount: userAccount } });
}
</code></pre>
",https://stackoverflow.com/questions/66880802/sinon-stub-a-firebase-collection-with-chained-methods-for-unit-testing-sinon,"['node.js', 'firebase', 'express', 'unit-testing', 'sinon']",569,True,2,5
"In Laravel 8, how do I get the url of a request when unit testing?","<p>I want to write a unit test in Laravel 8 to test a <code>POST</code> request that creates a new entity. In that request, a <code>job_id</code> is created and the url has that <code>job_id</code> appended. I wish to retrieve that <code>job_id</code>. How do I do that?</p>
<p>For example,</p>
<pre class=""lang-php prettyprint-override""><code>$route = route( 'job.store', $payload );
$response = $this-&gt;followingRedirects()-&gt;post( $route );
</code></pre>
<p>The <code>$response</code> should redirect to something like <code>http://localhost:9080/sales/job/J00561</code>. I want to get the url so I can get <code>job_id</code>, being <code>J00561</code>.</p>
<p>How do I do that?</p>
",https://stackoverflow.com/questions/68540395/in-laravel-8-how-do-i-get-the-url-of-a-request-when-unit-testing,"['php', 'laravel', 'phpunit']",1508,False,1,1
How to create a random json dictionary with a fixed outer structure for unit testing?,"<p>Using python and hypothesis I want to feed my unit tests with a json dictionary that has a fixed outer structure but a random dictionary as nested payload.</p>
<p>The outer structure needs to be:</p>
<pre><code>{
'id': &lt;some positive integer&gt;,
'kind', &lt;some uppercase string&gt;,
'payload': &lt;nested random valid json dictionary&gt;,
'timestamp': &lt;some datetime stamp&gt;
}
</code></pre>
<p>While the payload should be a very simple or very complex dictionary of more or less keys and values that represent typical data: emails, integers, lists, booleans,....</p>
<p>How do I create random deeper dictionaries that are still json-fiable?</p>
",https://stackoverflow.com/questions/67569802/how-to-create-a-random-json-dictionary-with-a-fixed-outer-structure-for-unit-tes,"['python', 'json', 'unit-testing']",234,True,1,1
"Unit testing the RestController endpoint using MockMVC, the expected exception is not caught as expected","<p>My RestController endpoint accepts a query parameter, I marked this as @RequestParam(value = &quot;brandId&quot;, required = true). I want to test this endpoint for a BAD-REQUEST. When I run the the test it thorows the exception as mentioned below,</p>
<ol>
<li><p>When I pass <strong>String brandId_bad_req = null;</strong> in test, it receives as <strong>&quot;null&quot;  (string value)</strong> in endpoint. Why this happens?</p>
</li>
<li><p>When I pass  an empty string as **String brandId_bad_req = &quot;&quot;; **in test, it enter the exception check in controller as expected. But after this exception the code breaks and throw the below exception stack. Unable to get the test result any time</p>
</li>
</ol>
<pre><code>@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping(&quot;/brands&quot;)
public class BrandController {

  private BrandService brandService;

  @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity&lt;Brand&gt; getBrandById(@RequestParam(value = &quot;brandId&quot;, required = true) String brandId) {

    if (StringUtils.isBlank(brandId)) {
      throw new ApiException.Builder()
          .errorMessage(BRAND_ID_BAD_REQUEST)
          .errorStatus(ErrorStatus.BAD_REQUEST)
          .build();
    }
    return new ResponseEntity&lt;Brand&gt;(brandService.getBrandById(brandId), HttpStatus.OK);
  }
}
</code></pre>
<p>** Test Case **</p>
<ol start=""3"">
<li>The below test passes always though the exception check in Controller end point is not available</li>
</ol>
<pre><code>//    if (StringUtils.isBlank(brandId)) {
//      throw new ApiException.Builder()
//          .errorMessage(BRAND_ID_BAD_REQUEST)
//          .errorStatus(ErrorStatus.BAD_REQUEST)
//          .build();
//    }
</code></pre>
<pre><code>    mockMvc.perform(get(&quot;/brands&quot;).requestAttr(&quot;brandId&quot;,&quot;&quot;))
        .andExpect(status().isBadRequest());
</code></pre>
<pre><code>@Test
  void testGetBrandById_bad_request() throws Exception {
    String brandId_bad_req = &quot;&quot;;

    mockMvc.perform(get(&quot;/brands&quot;).requestAttr(&quot;brandId&quot;,&quot;&quot;))
        .andExpect(status().isBadRequest()); //Pass

    mockMvc.perform(get(&quot;/brands?brandId=&quot;+brandId_bad_req))
        .andExpect(status().isBadRequest()); // ApiException thrown
 }
</code></pre>
<p><strong>Exception Stack</strong>
*
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is ApiException(errorMessage=Brand id is either null or invalid, errorCode=BAD_REQUEST, timestamp=Sat Oct 16 13:52:33 EDT 2021, status=BAD_REQUEST)</p>
<pre><code>at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:655)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:183)
at ca.loblaw.rmp.ad.demand.brand.controller.BrandControllerTest.testGetBrandById_bad_request(BrandControllerTest.java:91)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
</code></pre>
<p>Caused by: ApiException(errorMessage=Brand id is either null or invalid, errorCode=BAD_REQUEST, timestamp=Sat Oct 16 13:52:33 EDT 2021, status=BAD_REQUEST)
at ca.loblaw.rmp.common.exceptions.ApiException$Builder.build(ApiException.java:131)
at ca.loblaw.rmp.ad.demand.brand.controller.BrandController.getBrandById(BrandController.java:44)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
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:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1064)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
... 83 more</p>
<p>*</p>
",https://stackoverflow.com/questions/69598276/unit-testing-the-restcontroller-endpoint-using-mockmvc-the-expected-exception-i,"['java', 'spring-boot', 'unit-testing', 'spring-restcontroller', 'mockmvc']",275,False,1,1
In Ruby on Rails unit testing update model against MySQL database gives error: ActiveRecord::ValueTooLong,"<p>I have an ENUM type for a column I recently added to a previous table in the a MySQL database.</p>
<p>I'm unit testing creating a db entry with a valid ENUM value for that column.</p>
<p>The migration for adding the column is:</p>
<pre><code>class AddStatusToMymodel &lt; ActiveRecord::Migration[5.2]
  def change
    add_column :my_model, :status,
               &quot;ENUM('have_issues','no_issues', 'checking', 'error')&quot;
  end
end
</code></pre>
<p>And the model:</p>
<pre><code>class MyModel &lt; ApplicationRecord
  # ...
  enum status: %w[have_issues no_issues checking error].map { |i| [i.to_sym, i] }.to_h
end
</code></pre>
<p>Now, running a unit test that calls the controller method to create a record with <code>status: 'have_issues'</code> gives MySQL error:</p>
<pre><code>ActiveRecord::ValueTooLong:
       Mysql2::Error: Data too long for column 'status' at row 1
</code></pre>
<p>But creating the model in rails console actually creates the entry in the database for that <code>'have_issues'</code> status.</p>
<p>On the other hand, when running the same test with <code>'checking'</code> status the entry is created in the test database.</p>
<p>What is the problem when using the test database with a valid ENUM type, and getting <code>ValueTooLong</code> error?</p>
<p><strong>UPDATE</strong>:</p>
<p>As asked in comments I generate the <code>SHOW CREATE TABLE</code> for dev and test databases and, in fact, they differ for the column <code>status</code>. For dev db it's ENUM, and for test db it's VARCHAR(8).</p>
<p>So, looks like the problem is when running the tests, and the statements to create the new column with type ENUM, the column is created with type VARCHAR. Is that a configuration to correctly create the column <code>status</code> with the type ENUM?</p>
",https://stackoverflow.com/questions/67977213/in-ruby-on-rails-unit-testing-update-model-against-mysql-database-gives-error-a,"['mysql', 'ruby-on-rails', 'ruby', 'testing', 'rspec']",104,False,1,0
Angular unit testing doesn&#39;t recognise an extension method when used in a very specific place,"<p>While using an already existing project as a POC for unit testing, I encountered a problem at compilation time only when running tests.</p>
<p>I have a couple of <code>string</code> extension functions with custom title case and whatnot, but one of these which is meant for removing characters from a string is used in a <code>string</code> utilities class, in a method for cleaning up separator characters from document IDs (such as dots and dashes).</p>
<p>This works perfectly when running Angular application, but the Testing API seems to not be able to find it at that point. If the extension method is used directly in the component, it works as expected, so I know it's not a coding issue.</p>
<p>What could I be doing wrong?</p>
<p>The error (which doesn't happen when running the project. Only when running tests):</p>
<p><a href=""https://i.stack.imgur.com/LeaJn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/LeaJn.png"" alt=""Error message"" /></a></p>
<p><code>string-extensions.ts</code> (only relevant code):</p>
<pre class=""lang-js prettyprint-override""><code>export {};

declare global {
  interface String {
    /**
     * Remove a/s string/s passada/s por parâmetro desta string
     * @param text string/s a ser/em removida/s
     */
    emRemove(...text: string[]): string;
  }
}

String.prototype.emRemove = function(...text: string[]) {
  let retorno = this;
  if (text &amp;&amp; text.length &gt; 0) {
    text.forEach(t =&gt; {
      retorno = retorno.split(t).join('');
    });
  }
  return retorno;
};
</code></pre>
<p><code>string-utils.ts</code> (only relevant code):</p>
<pre class=""lang-js prettyprint-override""><code>export default class StringUtils {
  /**
   * Remove caracteres separadores de documentos e retorna somente o código
   * @param documento valor a ser limpo
   */
  static getDocumentoLimpo(documento: string): string {
    if (this.isNotEmpty(documento)) { // this tests undefined, null only whitespace and actual empty string without using the sometimes misleading falsy
      return documento.emRemove('-', '/', '.');
    }
    return '';
  }
}
</code></pre>
<p>Project structure:</p>
<p><a href=""https://i.stack.imgur.com/I92YU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/I92YU.png"" alt=""Project structure"" /></a></p>
<p>Edit:</p>
<p><code>angular.json</code> (only the projects.architect.test part. If more parts are needed, please ask):</p>
<pre class=""lang-json prettyprint-override""><code>        &quot;test&quot;: {
          &quot;builder&quot;: &quot;@angular-devkit/build-angular:karma&quot;,
          &quot;options&quot;: {
            &quot;main&quot;: &quot;src/test.ts&quot;,
            &quot;polyfills&quot;: &quot;src/polyfills.ts&quot;,
            &quot;tsConfig&quot;: &quot;tsconfig.spec.json&quot;,
            &quot;karmaConfig&quot;: &quot;karma.conf.js&quot;,
            &quot;assets&quot;: [
              &quot;src/favicon.ico&quot;,
              &quot;src/assets&quot;
            ],
            &quot;styles&quot;: [
              &quot;src/styles.scss&quot;
            ],
            &quot;scripts&quot;: []
          }
        },
</code></pre>
",https://stackoverflow.com/questions/66673293/angular-unit-testing-doesnt-recognise-an-extension-method-when-used-in-a-very-s,"['angular', 'unit-testing', 'compilation', 'karma-jasmine', 'extension-methods']",571,True,1,1
Reactjs unit testing : How to cover the code in useEffect hook? Using Jest and Enzyme,"<p>I am using a coverage report generator to automatically check the lines of unit testing coverage in files in the Pull request checks, etc.</p>
<p>However using Jest and Enzyme, I am unable to cover the <code>useEffect()</code> code which is affecting the coverage % as shown below. How can I cover the lines in <code>useEffect</code> hook? Is this possible in Jest/Enzyme?</p>
<p><a href=""https://i.stack.imgur.com/1DUdQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/1DUdQ.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/69894174/reactjs-unit-testing-how-to-cover-the-code-in-useeffect-hook-using-jest-and-e,"['reactjs', 'jestjs', 'enzyme']",303,False,1,1
Why does Visual Studio give an unresolved external symbol error when I do unit testing?,"<p>So I have a project called OpenGLStuffs that I am developing with Visual Studio. I am trying to do tests for this project. I created a separate test project called AppTest. In this test project I have a cpp file called AppTest.cpp that I will use to run the test version of the app. Here is the content of the test file:</p>
<p>AppTest.cpp</p>
<pre><code>#include &quot;pch.h&quot;
#include &quot;CppUnitTest.h&quot;
#include &quot;../openGL/OpenGLStuffs/MainApp.h&quot;

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace AppTest
{
    TEST_CLASS(AppTest)
    {
    public:
        
        TEST_METHOD(TestMethod1)
        {
            runApp();
        }
    };
}

</code></pre>
<p>Here's the content of the header file that is tested, it has a single line:</p>
<p>MainApp.h</p>
<pre><code>const int runApp();
</code></pre>
<p>I already have a MainApp.cpp file that defines the <code>runApp()</code> function. It is too long so I’m not posting it here.</p>
<p>The problem is that as I tried rebuilding the AppTest project, Visual Studio is giving me this error:</p>
<pre><code>Error   LNK2019 unresolved external symbol &quot;int const __cdecl runApp(void)&quot; (?runApp@@YA?BHXZ) 
referenced in function &quot;public: void __thiscall AppTest::AppTest::TestMethod1(void)&quot; (?
TestMethod1@AppTest@1@QAEXXZ)   AppTest C:\my-space\my-stuffs\AppTest\AppTest.obj   1   
</code></pre>
<p>I tried adding references to OpenGLStuffs to AppTests, but it doesn't seem to be working. I also tried changing the configuration type to .lib instead of .dll and the rebuilding succeeded, but this makes the test explorer to not show any tests.</p>
<p>Could somebody please tell me what I got wrong? Thanks in advance!</p>
",https://stackoverflow.com/questions/67629238/why-does-visual-studio-give-an-unresolved-external-symbol-error-when-i-do-unit-t,"['c++', 'visual-studio-2017', 'linker-errors']",181,False,-1,1
How to do unit-testing of TypeScript in a Visual Studio 2019 ASP.NET Core project?,"<p>I've followed the instructions from Microsoft as found <a href=""https://learn.microsoft.com/en-us/visualstudio/javascript/unit-testing-javascript-with-visual-studio?view=vs-2019&amp;tabs=mocha"" rel=""nofollow noreferrer"">here</a>. Writing TypeScript, compiling to JavaScript, debugging the TypeScript all works fine (although not with Firefox), but Mocha TypeScript unit-tests that I add will not be picked up by the Test Explorer.</p>
<p>The error that is shown in the Tests output pane is</p>
<pre><code>Log level is set to Informational (Default).
Test data store opened in 0,072 sec.
---------- Starting test discovery ----------
Processing: d:\Dropbox\projects\MemoryLane\playground\AspNetCoreWebApplication1\tests\UnitTest1.js
Using default Mocha settings
Test discovery error: Error: Cannot find module 'd:\Dropbox\projects\MemoryLane\playground\AspNetCoreWebApplication1\tests\UnitTest1.js'
Require stack:
- d:\Dropbox\projects\MemoryLane\playground\AspNetCoreWebApplication1\node_modules\mocha\lib\mocha.js
- d:\Dropbox\projects\MemoryLane\playground\AspNetCoreWebApplication1\node_modules\mocha\index.js
- C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2019\COMMUNITY\COMMON7\IDE\EXTENSIONS\MICROSOFT\NODEJSTOOLS\TESTADAPTER\TestFrameworks\mocha\mocha.js
- C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2019\COMMUNITY\COMMON7\IDE\EXTENSIONS\MICROSOFT\NODEJSTOOLS\TESTADAPTER\TestFrameworks\find_tests.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:893:15)
    at Function.Module._load (internal/modules/cjs/loader.js:743:27)
    at Module.require (internal/modules/cjs/loader.js:965:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at d:\Dropbox\projects\MemoryLane\playground\AspNetCoreWebApplication1\node_modules\mocha\lib\mocha.js:436:36
    at Array.forEach (&lt;anonymous&gt;)
    at Mocha.loadFiles (d:\Dropbox\projects\MemoryLane\playground\AspNetCoreWebApplication1\node_modules\mocha\lib\mocha.js:433:14)
    at C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2019\COMMUNITY\COMMON7\IDE\EXTENSIONS\MICROSOFT\NODEJSTOOLS\TESTADAPTER\TestFrameworks\mocha\mocha.js:47:23
    at Array.forEach (&lt;anonymous&gt;)
    at C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2019\COMMUNITY\COMMON7\IDE\EXTENSIONS\MICROSOFT\NODEJSTOOLS\TESTADAPTER\TestFrameworks\mocha\mocha.js:41:33 {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'd:\\Dropbox\\projects\\MemoryLane\\playground\\AspNetCoreWebApplication1\\node_modules\\mocha\\lib\\mocha.js',
    'd:\\Dropbox\\projects\\MemoryLane\\playground\\AspNetCoreWebApplication1\\node_modules\\mocha\\index.js',
    'C:\\PROGRAM FILES (X86)\\MICROSOFT VISUAL STUDIO\\2019\\COMMUNITY\\COMMON7\\IDE\\EXTENSIONS\\MICROSOFT\\NODEJSTOOLS\\TESTADAPTER\\TestFrameworks\\mocha\\mocha.js',
    'C:\\PROGRAM FILES (X86)\\MICROSOFT VISUAL STUDIO\\2019\\COMMUNITY\\COMMON7\\IDE\\EXTENSIONS\\MICROSOFT\\NODEJSTOOLS\\TESTADAPTER\\TestFrameworks\\find_tests.js'
  ]
} in d:\Dropbox\projects\MemoryLane\playground\AspNetCoreWebApplication1\tests\UnitTest1.js
Discovered 0 test cases.
No test is available in d:\Dropbox\projects\MemoryLane\playground\AspNetCoreWebApplication1\AspNetCoreWebApplication1.csproj. Make sure that test discoverer &amp; executors are registered and platform &amp; framework version settings are appropriate and try again.
No test is available in d:\Dropbox\projects\MemoryLane\playground\AspNetCoreWebApplication1\bin\Debug\netcoreapp3.1\AspNetCoreWebApplication1.dll. Make sure that test discoverer &amp; executors are registered and platform &amp; framework version settings are appropriate and try again.
========== Test discovery finished: 0 Tests found in 4,9 sec ==========
</code></pre>
<p>So it seems that regular TypeScript is transpiled to JavaScript, but the TypeScript unit-tests are not.</p>
<p>When I setup a Node.js project everything works fine. It's an ASP.NET Core project combined with TypeScript unit-tests that is not working. And according to the documentation it should be possible and I would really like to combine a C# backend with a TypeScript frontend.</p>
<p>Any ideas what's missing?</p>
",https://stackoverflow.com/questions/67322866/how-to-do-unit-testing-of-typescript-in-a-visual-studio-2019-asp-net-core-projec,"['typescript', 'unit-testing', 'asp.net-core', 'visual-studio-2019']",793,False,0,1
I am trying to perform unit testing in my code using jest but getting error,"<p>I tried to perform unit testing in my code that will take two parameters in the function and then test whether the function works or not. I am new to jest and still trying to figure out how to write the test cases.</p>
<pre><code>import React, { FC } from 'react';
import styled from 'styled-components';

interface AlertProps {
  message: string;
  onClose: () =&gt; void
}

const Button = styled.button`
    background-color: white;
    font-size: 15px;
    color: black;
    margin: 1em;
    border: 3px;
    padding: 0.25em 6em;
`;

const Para = styled.p`
  font-size: 20px;
  color: white;
  font-family: sans-serif;
  
`;

const Box = styled.div`
  background-color: #b81c36;
  width: 300px;
  padding: 20px;
  margin: auto;
  border-radius: 10px
 
`;
 
const Alert: FC&lt;AlertProps&gt; = ({ message, onClose }) =&gt; {
  return(
    &lt;&gt;
        &lt;Box&gt;
          &lt;Para &gt;{message}&lt;/Para&gt;
          &lt;Button  onClick={onClose}&gt;Close&lt;/Button&gt;
        &lt;/Box&gt;
    &lt;/&gt;
  );
}

export default Alert;
</code></pre>
",https://stackoverflow.com/questions/65697242/i-am-trying-to-perform-unit-testing-in-my-code-using-jest-but-getting-error,"['reactjs', 'typescript', 'unit-testing', 'jestjs', 'ts-jest']",195,False,-1,1
"Unit Testing with Mocha,Enzyme dispatched functions in functional components which uses React Hooks + Redux","<p>I am trying to test a dispatch from 'mapDispatchToProps' defined with a functional component which uses useEffect() hook and the function is called there.</p>
<pre><code>export const MyComponent = (props) =&gt; {
    useEffect(() =&gt; {
        // Anything in here is fired on component mount.
        props.registerInStore(props.id, false);
        return () =&gt; {
            // Anything in here is fired on component unmount.
            props.resetInStore(props.id);
        };
    }, []);

    const handleOnClick = () =&gt; {
        props.toggle(props.id);
    };

    return (
        &lt;div &gt;
            {!props.isOpen ? (
                &lt;button
                    onClick={handleOnClick}&gt;
                   Open
                &lt;/button&gt;
            ) : (
                &lt;button
                    onClick={handleOnClick}&gt;
                   close
                &lt;/button&gt;
            )}
        &lt;/div&gt;
    );
};


const mapDispatchToProps = (dispatch) =&gt; ({
    registerInStore(id, isOpen) {
        dispatch(registerInStore(id, isOpen));
    },
    resetInStore(id) {
        dispatch(resetInStore(id));
    }
});

export default connect(null, mapDispatchToProps)(MyComponent);

</code></pre>
<p>In my unit tests with Mocha and enzyme i also want to test the dispatches inside 'mapDispatchToProps', what i did below does not seem to work :</p>
<pre><code>describe('&lt;MyComponent/&gt;', () =&gt; {
    let store = mockStore({
                toggles: [
                {
                    id: 10,
                    isOpen: true
                }
            ]
        }
    });
    const options = {
        context: {store},
        childContextTypes: {store: PropTypes.object.isRequired},
        lifecycleExperimental: true
    };
    const setup = (inputProps = {}) =&gt; {
        const props = {
            id: 10,
            isOpen: false,
            registerInStore: expect.createSpy(),
            resetInStore: expect.createSpy(),
            toggle: expect.createSpy(),
            ...inputProps
        };
        const wrapper = mount(&lt;MyComponent {...props} /&gt;, options);
        return {
            props,
            wrapper
        };
    };

    afterEach(() =&gt; {
        expect.restoreSpies();
    });

       it('should dispatch', async () =&gt; {
            const {wrapper}=setup();
            await store.dispatch(wrapper.prop('registerInStore')(10,false));

            /* i tried the commented way too instead of directly dispatching*/
            // wrapper.prop('registerInStore')(10,false);
            //await new Promise((resolve) =&gt; setTimeout(resolve, 50));

            const expectedActions = [{type: 'REGISTER_IN_STORE', id: 10, isOpen: false}];
            expect(store.getActions()).toEqual(expectedActions);
           
        });

</code></pre>
<p>the store.getActions() is returning an empty array, i am new to React Hooks and  testing, what am i doing wrong, any other solutions?.
Thanks in Advance.</p>
",https://stackoverflow.com/questions/66066633/unit-testing-with-mocha-enzyme-dispatched-functions-in-functional-components-whi,"['reactjs', 'redux', 'react-hooks', 'mocha.js', 'enzyme']",334,False,0,1
Visual Studio 2019 unit tests missing in test explorer but show in live unit testing,"<p>I have a solution with about 3000 unit tests.  The test appear and run under the &quot;Live Unit Testing&quot; window but under the &quot;Test Explorer&quot; none appear.   They USED to but suddenly no longer appear in that window.   This is Visual Studio 2019 16.9.1</p>
<p>How can I get them to appear and run in the test explorer window?</p>
",https://stackoverflow.com/questions/66554913/visual-studio-2019-unit-tests-missing-in-test-explorer-but-show-in-live-unit-tes,"['unit-testing', 'visual-studio-2019', 'test-explorer', 'live-unit-tests']",478,False,0,1
Unit Testing firebase in flutter throws Exception &quot;No Firebase App &#39;[DEFAULT]&#39; has been created - call Firebase.initializeApp()&quot;,"<p>I need to unit test an application that uses firebase. My unit tests always says &quot;Unhandled Exception: [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()&quot;. I absolutely understand why this problem occurs. But I still want to unit test my methods without really starting firebase. Even Mocking the firebase stuff did not help. Hopefully you can help me out? What am I misunderstanding?</p>
<p>For Example I rewrote the code from this tutorial: <a href=""https://www.youtube.com/watch?v=4d6hEaUVvuU"" rel=""noreferrer"">https://www.youtube.com/watch?v=4d6hEaUVvuU</a></p>
<p>This is my test class: (&quot;Auth&quot; Class in YT example is &quot;Authentification&quot; in my code)</p>
<pre><code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:hrw_textscanner/firebase/Authentification.dart';
import 'package:mockito/mockito.dart';
import 'package:test/test.dart';

class MockUser extends Mock implements User {}

final MockUser _mockUser = MockUser();

class MockFirebaseAuth extends Mock implements FirebaseAuth {
  @override
  Stream&lt;User&gt; authStateChanges() {
    return Stream.fromIterable([
      _mockUser,
    ]);
  }
}

void main() {
  final MockFirebaseAuth mockFirebaseAuth = new MockFirebaseAuth();
  final Authentification authentification =
      new Authentification(mockFirebaseAuth);

  test(&quot;emit occurs&quot;, () async {
    expectLater(authentification.authStateChanges, emitsInOrder([_mockUser])); //authStateChanges is the same as &quot;user&quot; in example
  });
}
</code></pre>
<p>In the Example in Youtube it works - my code still leads into that error mentioned above :(</p>
",https://stackoverflow.com/questions/68196523/unit-testing-firebase-in-flutter-throws-exception-no-firebase-app-default-h,"['firebase', 'flutter', 'unit-testing', 'testing', 'mocking']",693,False,5,0
"Unit testing react redux thunk dispatches with jest and react testing library for &quot;v: 16.13.1&quot;,","<p>I have following function.</p>
<pre>
const loadUsers= () => {
  return async (dispatch) => {
    dispatch(userRequest());
    let response= null
    try {
      response= await UserService.getUser();
      dispatch(userLoading());
    } catch (error) {
      dispatch(userError(error));
    } finally {
      dispatch(userSuccess(response));
    }
  };
};
</pre>
<p>With the following unit test I was abale to hit the &quot;dispatch(userRequest());&quot;</p>
<pre>
describe('user thunk', () => {
    it('dispatches a userRequest', async () => {
      const dispatch = jest.fn();

      await loadUsers()(dispatch);
      expect(dispatch).toHaveBeenCalledWith(userRequest());
    });
  });
</pre>
<p>However I couldn't figure out how to test lines and below <code>response= await UserService.getUser();</code>. Even though the function is not complex and I won't have much value for writing complex test, I need it for my pipeline to build.</p>
<p>Any help will be appreciated.</p>
<p>Thanks in advance.</p>
<p>UPDATE-&gt; User Service</p>
<pre>import axios from 'axios';

const USERS_ENDPOINT = '/user';

export const getUser= async () => {
  const response = await axios.get(PRODUCTS_ENDPOINT, {});
  return response.data;
};

export default getUser;</pre>
",https://stackoverflow.com/questions/68202239/unit-testing-react-redux-thunk-dispatches-with-jest-and-react-testing-library-fo,"['javascript', 'reactjs', 'redux', 'redux-thunk', 'react-testing-library']",2604,True,0,1
&#39;router-outlet&#39; is a Web Component then add &#39;CUSTOM_ELEMENTS_SCHEMA&#39; when ever i write unit testing,"<p>As you can see I am testing the application using unit testing in angular7, when ever I am running <code>ng test</code>.
I am getting issue like <code>router-outlet</code> is a Web Component then add <code>CUSTOM_ELEMENTS_SCHEMA</code> to the <code>@NgModule.schemas</code> of this component to suppress this message and the issue is related to app component and patient-group component no where they are getting called each other in testing application please have a look.</p>
<pre><code>patient-group.component.spec.ts
</code></pre>
<p>Here the entire testing goes here and i am including all the imports require to this application please check.</p>
<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {tick, fakeAsync} from '@angular/core/testing';
import { Location} from '@angular/common';

import { PatientGroupComponent } from './patient-group.component';
import { Router, RouterOutlet, RouterModule } from &quot;@angular/router&quot;;
import { RouterTestingModule} from  '@angular/router/testing';
import  { HttpClientTestingModule} from '@angular/common/http/testing';
import { AppComponent} from '../app.component';

describe('PatientGroupComponent', () =&gt; {
  let location : Location;
  let  router : Router;
  let component: PatientGroupComponent;
  let fixture: ComponentFixture&lt;PatientGroupComponent&gt;;
  let fixture1;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports : [RouterTestingModule,RouterModule, HttpClientTestingModule],
      declarations: [ PatientGroupComponent , AppComponent],
      providers : [ RouterOutlet , Router,
         { provide: Router, useClass: RouterModule }
      
      ]
    })
    .compileComponents();

     location = TestBed.get(Location);
     router = TestBed.get(Router);
     fixture1 = TestBed.createComponent(AppComponent);
    router.initialNavigation();

  }));

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

  it('should navigate to  /patientGroup', fakeAsync(()=&gt;{
    router.navigate(['']);
    tick();
    expect(location.path()).toBe('/patientGroup');
  }))

  it('should create', () =&gt; {
    const btn = fixture.debugElement.nativeElement.querySelector('group-btn');
    btn.click();
    const h1 = fixture.debugElement.nativeElement.querySelector('group-data')
    expect(h1.innerHTML).toBeTruthy();
  });
});

patient-group.component.html

&lt;form&gt;
    &lt;div *ngIf = &quot;data&quot;&gt;  
        &lt;div *ngFor=&quot;let arrayList of data let index = i&quot; style=&quot;text-align: center;&quot;&gt;
            &lt;span style=&quot;font-size: 30px;&quot;&gt;[&lt;/span&gt;&lt;span *ngFor=&quot;let arrayList2 of arrayList&quot;&gt;
                &lt;span style=&quot;font-size:30px !important; color: red; margin: 10px;&quot;
                contenteditable=&quot;true&quot; [ngModelOptions]=&quot;{standalone: true}&quot;   [(ngModel)] = &quot;data[i]&quot; ngDefaultControl &gt;{{arrayList2}}&lt;/span&gt;
            &lt;/span&gt;&lt;span style=&quot;font-size: 30px;&quot;&gt;]&lt;/span&gt;
        &lt;/div&gt;

        &lt;div style=&quot;text-align: center;&quot;&gt;
            &lt;button class=&quot;group-btn&quot;
                style=&quot;padding: 22px;color: white; font-size : 20px;background-color: blue;border-radius: 50%; margin: 20px 0px;&quot;
                (click)=&quot;getPatientGroups()&quot;&gt;Click for Patient groups&lt;/button&gt;
        &lt;/div&gt;

        &lt;h1 class=&quot;group-data&quot; *ngIf=&quot;patientData &gt;= 0&quot; style=&quot;color: green; text-align: center;&quot;&gt; The Patient Group &lt;span
                *ngIf=&quot;patientData &gt; 1&quot;&gt;'s&lt;/span&gt; are : &lt;span style=&quot;color: black;&quot;&gt;{{patientData}}&lt;/span&gt;&lt;/h1&gt;
    &lt;/div&gt;
&lt;/form&gt;


app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule,Routes } from '@angular/router';



import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatDialogModule} from '@angular/material/dialog';
import {MatIconModule} from '@angular/material/icon';
import { chatSupportService } from './services/chat-support.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {MatFormFieldModule, MatFormFieldControl} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import {MatButtonModule, MatCheckboxModule} from '@angular/material';

import { TokenInterceptor } from './app.interceptor';
import { PatientGroupComponent } from './patient-group/patient-group.component';
//import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/compiler/src/core';

const routes : Routes = [
  { path : '', redirectTo : 'patientGroup', pathMatch : 'full'},
  { path : 'patientGroup', component : PatientGroupComponent}
]

@NgModule({
  declarations: [
    AppComponent,
    PatientGroupComponent,
    
    
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    MatFormFieldModule,
    BrowserAnimationsModule,
    MatInputModule,
    MatDialogModule,
    MatIconModule,
    HttpClientModule,
    MatButtonModule, 
    MatCheckboxModule,
    FormsModule, ReactiveFormsModule
    
    
    
  ],
  entryComponents:[
   
    
    

  ],
  providers: [chatSupportService,
  
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    },



  ],
  //schemas : [CUSTOM_ELEMENTS_SCHEMA],
  
  bootstrap: [AppComponent]
})
export class AppModule { }


app.component.html
</code></pre>
<p>This is app component i am not using any dom here.
But in main.component.html file when I do  . It shows errors:</p>
<pre><code>If 'router-outlet' is an Angular component, then verify that it is part of this module.
If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.


&lt;div&gt;
  &lt;router-outlet&gt;&lt;/router-outlet&gt;
&lt;/div&gt;
</code></pre>
",https://stackoverflow.com/questions/69615141/router-outlet-is-a-web-component-then-add-custom-elements-schema-when-ever-i,"['javascript', 'angular', 'typescript', 'karma-jasmine', 'angular-test']",190,False,-1,1
(Python Unit testing) Patch same object differently for different method in the same python file,"<p>My python file has many methods defined in it. In many of the methods in the file, I am calling a function - let's say &quot;fun1&quot;.</p>
<p>I want to mock the 'fun1' function for each of the methods differently. Is there a way to patch an object differently at method level and not at file level?</p>
<pre><code> Contents of aPythonFile.py
=======================================
    import fun from a_module

    def a():
        res= fun(aarg1, aarg2)
        return res

    def b():
        res = fun(barg1, barg2)
        return res
</code></pre>
<p>This came to my mind, as I know, the same &quot;fun&quot; can be patched differently for different files, then why not be able to patch differently based on the method in the file where it is called :-</p>
<pre><code>@mock.patch(&quot;package.aPythonFile.fun&quot;) - Is Valid

@mock.patch(&quot;package.aPythonFile.a.fun&quot;) - ?? (possible?)
@mock.patch(&quot;package.aPythonFile.b.fun&quot;) - ?? (possible?)
</code></pre>
",https://stackoverflow.com/questions/66707457/python-unit-testing-patch-same-object-differently-for-different-method-in-the,"['python', 'unit-testing', 'pytest', 'python-unittest']",824,False,0,1
How to access private service which is provided by the component itself for unit testing,"<p>I have this component which provides a service by itself</p>
<pre><code>@Component({
    selector: 'my-component',
    providers: [MyService],
    ...
})
export class MyComponent { 
  constructor(@Self() private service: MyService) {}
  ...
}
</code></pre>
<p>During unit testing I noticed the following</p>
<pre><code>beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [MyService],
    }).compileComponents();
    service = TestBed.inject(MyService);
});
</code></pre>
<p>That <code>service</code> is not the same instance as the service inside my component. I guess this makes sense, but I cannot find a solution for this, because for my tests I need access to that service inside my component. Any suggestions?</p>
",https://stackoverflow.com/questions/67502690/how-to-access-private-service-which-is-provided-by-the-component-itself-for-unit,"['angular', 'unit-testing', 'dependency-injection']",202,True,0,2
How to do unit testing using Jest and enzyme for these type of code segmentations?,"<p>I tried so hard to implement the unit testing using jest and enzyme to the below code, but i haven't idea about how to write the unit test correctly. Always i got the test result as 'failed'.</p>
<p>I really appreciate the little support you give me to figure it out and pass the unit testing.</p>
<p>I used context API to fetch data.
I need to unit test the exact path navigation in App.js,</p>
<p>code:</p>
<pre><code>import React, { Component } from &quot;react&quot;;
import { BrowserRouter as Router, Route, Switch } from &quot;react-router-dom&quot;;

import Navbar from &quot;./components/layout/Navbar&quot;;
import Index from &quot;./components/layout/Index&quot;;
import Lyrics from &quot;./components/tracks/Lyrics&quot;;

import { Provider } from &quot;./context&quot;;

class App extends Component {
  render() {
    return (
      &lt;Provider&gt;
        &lt;Router&gt;
          &lt;React.Fragment&gt;
            &lt;Navbar /&gt;
            &lt;div className=&quot;container&quot;&gt;
              &lt;Switch&gt;
                &lt;Route exact path=&quot;/&quot; component={Index} /&gt;
                &lt;Route path=&quot;/lyrics/track/:id&quot; component={Lyrics} /&gt;
              &lt;/Switch&gt;
            &lt;/div&gt;
          &lt;/React.Fragment&gt;
        &lt;/Router&gt;
      &lt;/Provider&gt;
    );
  }
}

export default App;
</code></pre>
<p><a href=""https://i.stack.imgur.com/05YSE.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
",https://stackoverflow.com/questions/69548685/how-to-do-unit-testing-using-jest-and-enzyme-for-these-type-of-code-segmentation,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",53,False,-1,1
NestJS Unit Testing of the Service: Mocking getManager resulting in &#39;Connection &quot;default&quot; was not found&#39; error,"<p>I am currently unit testing my NestJS Service. My entity is called 'User' and I established a basic Service that allows me to interact with a MS SQL server, with GET and POST endpoints established in my Controller.</p>
<p>One of the service methods I am trying to mock is the <code>deleteV2</code> function, which you can find below:</p>
<pre><code>
// service file 
import { Injectable } from '@nestjs/common';
import { InjectConnection, InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { Connection, createConnection, EntityManager, getConnection, getManager, getRepository, Repository } from &quot;typeorm&quot;;
import {User} from '../entities/user.entity';


@Injectable()
export class ServiceName {
  constructor(@InjectRepository(User) private usersRepository: Repository&lt;User&gt;,
              @InjectConnection() private connection: Connection,
              @InjectEntityManager() private manager: EntityManager
              ) {}

  async delete(id: number): Promise&lt;any&gt; {
    return await this.manager.delete(User, id);
  }
  async deleteV2(id: number): Promise&lt;any&gt; {
    return await getManager().delete(User, id);
  }
</code></pre>
<p>Note that the reason I have imported <code>EntityManager</code> AND injected (with <code>@InjectEntityManager()</code>) a <code>manager: EntityManager</code> into my service is for the simple reason that I wanted some more practice working with different methods (I'm a new intern working with NestJS). The fact that I have the <code>delete</code> method defined where I use the injected <code>manager</code> and then the <code>deleteV2</code> method defined where I use the imported <code>getManager</code> is also for the pure reason of practicing unit testing with different ways. And the fact that I'm injecting Repository, Connection, and EntityManager, is also for the same reason.</p>
<p>In my spec.ts unit testing file for the service, I have:</p>
<pre><code>// unit testing file for the service

type MockType&lt;T&gt; = { 
    [P in keyof T]?: jest.Mock&lt;{}&gt;;
};

describe('service tests', () =&gt; {
    const mockManagerFactory = jest.fn(() =&gt; ({
        delete: jest.fn().mockReturnValue(undefined),
    }))
 
    let service: ServiceName;
    // mock repository and mock connection also defined similarly to mockManager
    let mockManager: MockType&lt;EntityManager&gt;; 

    beforeEach(async () =&gt; {     
        const module: TestingModule = await Test.createTestingModule({
            providers: [
                ServiceName,
                // tokens for Repository and Connection are also provided along with their respective Factories
                {
                    provide: getEntityManagerToken(),
                    useFactory: mockManagerFactory,
                },
            ],
        }).compile();

        service = module.get&lt;ServiceName&gt;(ServiceName);
        // mockRepository and mockConnection also defined but not shown
        mockManager = module.get(getEntityManagerToken());
    });
})

</code></pre>
<p>Staying on the same spec.ts file, I defined multiple tests. The one that is causing problem is the one that involves <code>deleteV2</code> below:</p>
<pre><code>// same unit testing file for the service 
         
        // first test
        it('first test', async () =&gt; {
            expect(await service.delete(1000)).toEqual(undefined);
            expect(mockManager.delete).toBeCalled();
        });
        
        // second test 
        it('second test', async () =&gt; {
            expect(await service.deleteV2(1000)).toEqual(undefined);
            expect(mockManager.delete).toBeCalled();
        })
</code></pre>
<p>While the first test has no problem running (the first test is associated with <code>delete</code> in the service file), the second test (associated with <code>deleteV2</code> in the service file) does not pass and results in the following error:</p>
<pre><code>● service tests › Service Functions › second test

ConnectionNotFoundError: Connection &quot;default&quot; was not found.

      at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)
      at ConnectionManager.Object.&lt;anonymous&gt;.ConnectionManager.get (connection/ConnectionManager.ts:40:19)
      at Object.getManager (index.ts:260:35)

</code></pre>
<p>Any ideas how to approach this error? It seems as though providing <code>getEntityManagerToken()</code> works with the injected <code>manager</code> but not with the <code>getManager</code> that is imported, since <code>deleteV2</code> uses <code>getManager</code> while <code>delete</code> (which passes the test) uses the imported <code>manager</code></p>
",https://stackoverflow.com/questions/67528680/nestjs-unit-testing-of-the-service-mocking-getmanager-resulting-in-connection,"['typescript', 'nestjs']",2916,True,3,1
"Get single object from MOQ using Unit Testing, Unit of Work and Generic Repository Pattern framework","<p>I'm new to Moq, currently, the problem is when I try to get a collection of the object (eg WebStore) its works as expected,
but when I try to get a single object from it's not work as expected,</p>
<p>could you please guide me on how to get a single object from the repository</p>
<pre><code>private Mock&lt;WebStore&gt; _webstore; 
[SetUp]
public void SetUp()
{
  ...
               
    _unitOfWork = new Mock&lt;IUnitOfWork&gt;();           
    _webstore = new Mock&lt;WebStore&gt;();
    ...
}    
</code></pre>
<h3>Methods</h3>
<pre><code>public WebStore GetAllWebstore()
{            
   var webstoreDat = unitOfWork.GetRepository&lt;WebStore&gt;().GetAll();
   return webstoreData;
}

public WebStore GetWebstorebyId(int webstoreId)
{            
     var webstoreData = unitOfWork.GetRepository&lt;WebStore&gt;()
          .Get(store =&gt; store.WebStoreId == webstoreId).FirstOrDefault();
     return webstoreData;
}
</code></pre>
<h3>Test methods</h3>
<pre><code>[Test]
public void GetWebstore_All()
{
    //
    var webStoreId = 1;
    var customerName = &quot;A&quot;;
    var listWebstore = new List&lt;WebStore&gt;() { new WebStore { WebStoreId = webStoreId, CustomerName = customerName } };
    var webstore = new WebStore { WebStoreId = webStoreId, CustomerName = customerName };
   
   //Set up Mock        
    _unitOfWork.Setup(uow =&gt; uow.GetRepository&lt;WebStore&gt;().GetAll()).Returns(listWebstore); // working

    ...
}
</code></pre>
<pre><code>[Test]
public void GetWebstore_GetSingle()
{
    //
    var webStoreId = 1;
    var customerName = &quot;A&quot;;
    var listWebstore = new List&lt;WebStore&gt;() { new WebStore { WebStoreId = webStoreId, CustomerName = customerName } };
    var webstore = new WebStore { WebStoreId = webStoreId, CustomerName = customerName };
   
   //Set up Mock
    _unitOfWork.Setup(uow =&gt; uow.GetRepository&lt;WebStore&gt;()
    .Get(store =&gt; store.WebStoreId == webStoreId, null, &quot;&quot;, 0, 0).FirstOrDefault()).Returns(webstore);  **//Not working** 

    ...
}
</code></pre>
",https://stackoverflow.com/questions/69691555/get-single-object-from-moq-using-unit-testing-unit-of-work-and-generic-reposito,"['c#', 'unit-testing', 'moq', 'repository-pattern', 'unit-of-work']",536,True,1,2
adding java spark code unit testing in the build fat jar fails the spark run later,"<p>I try to add unit test code for some java spark method. However, I found the spark job run failed after I add them. Here are the things I found</p>
<p>a) After I added the unit test code, they will be run when I build the java fat jar.</p>
<p>b) Then, after build, if I ran the spark submit job, it will failed with the exception below</p>
<pre><code> Error in trying to obtain a connection. Retrying in 7000ms
java.sql.SQLException: A read-only user or a user in a read-only database is not permitted to disable read-only mode on a connection.
        at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
......
</code></pre>
<p>c) To fix this issue, I have to remove the metastore_db folder under the code root directory.</p>
<p>d) If I don't build the jar again, but directly run the spark job (after fix the issue in step c), then, it will run fine.</p>
<p>Based on what I see above, my guessing is that the unit test during the building jar process started a spark session (something like that). And this session is not being closed. Therefore, when the actual code run later, the job will failed to have a new session connection.</p>
<p>Again, this is my guessing. Below is my unit testing code.</p>
<pre><code>@Before
public void setUp() throws IllegalArgumentException, IOException {
    SparkConf conf = new SparkConf();
    conf.setMaster(&quot;local[2]&quot;);
    conf.setAppName(&quot;sparkHelperTest&quot;);
    sparkContext = new JavaSparkContext(conf);
    sqlContext = new org.apache.spark.sql.hive.HiveContext(sparkContext);
    sparkHelper = new DSERunEnvironmentSparkHelper(sparkContext, sqlContext, aktanaServiceConfiguration);
}
                                                       
@Test
public void testAccountDF() {
    ArrayList&lt;Account&gt; mockList = new ArrayList&lt;&gt;();
    Account account = new Account();
    account.setId(1);
    account.setName(&quot;name&quot;);

    List&lt;StructField&gt; listOfStructField= new ArrayList&lt;&gt;();
    listOfStructField.add(DataTypes.createStructField(&quot;id&quot;, DataTypes.IntegerType, false));
    listOfStructField.add(DataTypes.createStructField(&quot;name&quot;, DataTypes.StringType, true));

    StructType structType=DataTypes.createStructType(listOfStructField);


    JavaRDD&lt;Row&gt; rowRDD = sparkContext.parallelize(mockList).map(
            account -&gt; RowFactory.create(repAccount.getId(), account.getName());

    DataFrame df1 = sqlContext.createDataFrame(rowRDD, structType);
    df1.show();
}

@After
public void postProcess () {
    sparkContext.stop();
    sparkContext.close();
}
</code></pre>
<p>Another notice is that let's see if I fix the metastore_db issue by c). If I build the fat jar and run the job again, it still fail. However, if I run the unit testing directly (NOT re-build the jar) and run the job again, the job is running OK. So the testing run in the build failed the spark job, while the directly running unit test through IntelliJ is OK.</p>
<p>Please help!! Thanks in advance.</p>
",https://stackoverflow.com/questions/69862352/adding-java-spark-code-unit-testing-in-the-build-fat-jar-fails-the-spark-run-lat,"['java', 'unit-testing', 'apache-spark']",96,False,1,1
Assert.Inconclusive analogue for MS C++ unit testing framework or how to skip test on the run?,"<p>I want to be able to skip a current test from its body. Of course, I could simply do this:</p>
<pre><code>if (condition) return;
</code></pre>
<p>But this will show the test as &quot;passed&quot;. I want to keep the user informed that the test is neither passed nor failed if <code>(condition)</code> happens.</p>
<p>In C# we have <code>Assert.Inconclusive()</code>, so some C++ analogue of this function would be the best. Is there anything like this in <em>Microsoft Cpp Unit Testing Framework</em> or can it be implemented?</p>
",https://stackoverflow.com/questions/68815485/assert-inconclusive-analogue-for-ms-c-unit-testing-framework-or-how-to-skip-te,"['c++', 'unit-testing', 'microsoft-cpp-unit-test']",95,False,1,0
How to mock and write Unit testing for Azure Service Bus Topic using Junit and Java?,"<p>I have a method to send and receive a messages from Azure service Bus Topic, I need to mock and write test cases for that method using Junit 5.</p>
<p>Sample code based on Microsoft documentation</p>
<pre><code>    public class MyServiceBusTopicClient {

    static final Gson GSON = new Gson();
    
    public static void main(String[] args) throws Exception, ServiceBusException {
        // TODO Auto-generated method stub

        TopicClient sendClient;
        String connectionString = &quot;Endpoint=sb://&lt;NameOfServiceBusNamespace&gt;.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=&lt;AccessKey&gt;&quot;;
        sendClient = new TopicClient(new ConnectionStringBuilder(connectionString, &quot;BasicTopic&quot;));       
        sendMessagesAsync(sendClient).thenRunAsync(() -&gt; sendClient.closeAsync());
    }

    static CompletableFuture&lt;Void&gt; sendMessagesAsync(TopicClient sendClient) {
        List&lt;HashMap&lt;String, String&gt;&gt; data =
                GSON.fromJson(
                        &quot;[&quot; +
                                &quot;{'name' = 'Einstein', 'firstName' = 'Albert'},&quot; +
                                &quot;{'name' = 'Heisenberg', 'firstName' = 'Werner'},&quot; +
                                &quot;{'name' = 'Curie', 'firstName' = 'Marie'},&quot; +
                                &quot;{'name' = 'Hawking', 'firstName' = 'Steven'},&quot; +
                                &quot;{'name' = 'Newton', 'firstName' = 'Isaac'},&quot; +
                                &quot;{'name' = 'Bohr', 'firstName' = 'Niels'},&quot; +
                                &quot;{'name' = 'Faraday', 'firstName' = 'Michael'},&quot; +
                                &quot;{'name' = 'Galilei', 'firstName' = 'Galileo'},&quot; +
                                &quot;{'name' = 'Kepler', 'firstName' = 'Johannes'},&quot; +
                                &quot;{'name' = 'Kopernikus', 'firstName' = 'Nikolaus'}&quot; +
                                &quot;]&quot;,
                        new TypeToken&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt;() {
                        }.getType());

        List&lt;CompletableFuture&gt; tasks = new ArrayList&lt;&gt;();
        for (int i = 0; i &lt; data.size(); i++) {
            final String messageId = Integer.toString(i);
            Message message = new Message(GSON.toJson(data.get(i), Map.class).getBytes(UTF_8));
            message.setContentType(&quot;application/json&quot;);
            message.setLabel(&quot;Scientist&quot;);
            message.setMessageId(messageId);
            message.setTimeToLive(Duration.ofMinutes(2));
            System.out.printf(&quot;Message sending: Id = %s\n&quot;, message.getMessageId());
            tasks.add(
                    sendClient.sendAsync(message).thenRunAsync(() -&gt; {
                        System.out.printf(&quot;\tMessage acknowledged: Id = %s\n&quot;, message.getMessageId());
                    }));
        }
        return CompletableFuture.allOf(tasks.toArray(new CompletableFuture&lt;?&gt;[tasks.size()]));
    }
}
</code></pre>
<p>Method used to receive messages from the azure service bus subscription.</p>
<pre><code>import com.microsoft.azure.servicebus.*;
import com.microsoft.azure.servicebus.primitives.ConnectionStringBuilder;
import com.microsoft.azure.servicebus.primitives.ServiceBusException;
import com.google.gson.Gson;
import static java.nio.charset.StandardCharsets.*;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.*;

public class MyServiceBusSubscriptionClient {
    static final Gson GSON = new Gson();
    
    public static void main(String[] args) throws Exception, ServiceBusException {
        String connectionString = &quot;Endpoint=sb://&lt;NameOfServiceBusNamespace&gt;.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=&lt;AccessKey&gt;&quot;;
        
        SubscriptionClient subscription1Client = new SubscriptionClient(new ConnectionStringBuilder(connectionString, &quot;BasicTopic/subscriptions/Subscription1&quot;), ReceiveMode.PEEKLOCK);
        SubscriptionClient subscription2Client = new SubscriptionClient(new ConnectionStringBuilder(connectionString, &quot;BasicTopic/subscriptions/Subscription2&quot;), ReceiveMode.PEEKLOCK);
        SubscriptionClient subscription3Client = new SubscriptionClient(new ConnectionStringBuilder(connectionString, &quot;BasicTopic/subscriptions/Subscription3&quot;), ReceiveMode.PEEKLOCK);        

        ExecutorService executorService = Executors.newCachedThreadPool();
        registerMessageHandlerOnClient(subscription1Client, executorService);
        registerMessageHandlerOnClient(subscription2Client, executorService);
        registerMessageHandlerOnClient(subscription3Client, executorService);
    }
    
    static void registerMessageHandlerOnClient(SubscriptionClient receiveClient, ExecutorService executorService) throws Exception {
        // register the RegisterMessageHandler callback
        receiveClient.registerMessageHandler(
                new IMessageHandler() {
                    // callback invoked when the message handler loop has obtained a message
                    public CompletableFuture&lt;Void&gt; onMessageAsync(IMessage message) {
                        // receives message is passed to callback
                        if (message.getLabel() != null &amp;&amp;
                                message.getContentType() != null &amp;&amp;
                                message.getLabel().contentEquals(&quot;Scientist&quot;) &amp;&amp;
                                message.getContentType().contentEquals(&quot;application/json&quot;)) {

                            byte[] body = message.getBody();
                            Map scientist = GSON.fromJson(new String(body, UTF_8), Map.class);

                            System.out.printf(
                                    &quot;\n\t\t\t\t%s Message received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s,&quot; +
                                            &quot;\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \&quot;%s\&quot;,  \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n&quot;,
                                    receiveClient.getEntityPath(),
                                    message.getMessageId(),
                                    message.getSequenceNumber(),
                                    message.getEnqueuedTimeUtc(),
                                    message.getExpiresAtUtc(),
                                    message.getContentType(),
                                    scientist != null ? scientist.get(&quot;firstName&quot;) : &quot;&quot;,
                                    scientist != null ? scientist.get(&quot;name&quot;) : &quot;&quot;);
                        }
                        return receiveClient.completeAsync(message.getLockToken());
                    }

                    // callback invoked when the message handler has an exception to report
                    public void notifyException(Throwable throwable, ExceptionPhase exceptionPhase) {
                        System.out.printf(exceptionPhase + &quot;-&quot; + throwable.getMessage());
                    }
                },
                // 1 concurrent call, messages are auto-completed, auto-renew duration
                new MessageHandlerOptions(1, false, Duration.ofMinutes(1)),
                executorService);
    }
}
</code></pre>
<p>I'm not sure about the exact implementation for mocking the above methods. It would be helpful If I get any documentation for the Implemenation.</p>
<p>Any one please advise on this ?</p>
",https://stackoverflow.com/questions/65624060/how-to-mock-and-write-unit-testing-for-azure-service-bus-topic-using-junit-and-j,"['java', 'azure', 'mockito', 'azureservicebus', 'junit5']",4711,True,2,1
Unit testing Spring Boot based REST endpoint which returns collection of objects ordered by given direction,"<p>I am new to spring boot and still learning. Please bear with me if I am asking a question which is not much relevant. I have seen a code something like below and as I understood this code is essentially searching some record based on given sorting order ASC or DESC and return the ordered result set. Do we really need to write a unit test to verify the order of the result set serialized by rest controller or do you think unit testing ordering behaviour is not belong to controller level responsibility ? Your suggestions and thoughts are very much appreciated.</p>
<pre><code>@RestController
@RequestMapping
@RequiredArgsConstructor
public class OrderController {
    
    private final OrderService orderService;

    @GetMapping(&quot;/orders&quot;)
    public ResponseEntity&lt;List&lt;Order&gt;&gt; getAllOrders(@RequestParam(required = false) String direction){
        return ResponseEntity.ok(orderService.getAllOrdersSortedByName(direction));
    }

}
</code></pre>
<p>If we write a unit test like below with mocking service call behaviour, can it be consider as a meaningful test case ?</p>
<pre><code>@Test
void findAllOrderDesc() {

    Order o1 = Order.id(1).name(&quot;A&quot;).build();
    Order o2 = Order.id(2).name(&quot;B&quot;).build();

        
    when(orderService.getAllOrdersSortedByName(anyString())).thenReturn(List.of(o2,o1));

        mockMvc.perform(get(&quot;/orders?direction=DESC&quot;))
                .andExpect(status().isOk())
                .andExpect(jsonPath(&quot;$&quot;,hashSize(2)))
                .andExpect(jsonPath(&quot;$.[0].name&quot;,is(&quot;B&quot;)))
                .andExpect(jsonPath(&quot;$.[1].name&quot;,is(&quot;A&quot;)));
                

}
</code></pre>
",https://stackoverflow.com/questions/68869736/unit-testing-spring-boot-based-rest-endpoint-which-returns-collection-of-objects,"['java', 'spring-boot', 'unit-testing', 'spring-restcontroller', 'spring-boot-test']",548,False,1,1
How to mock (simulate) MyBatis-Plus data access layer for unit testing for Model&lt;&gt; Active Record?,"<p>In codebase where model classes use Model from <a href=""https://github.com/baomidou/mybatis-plus"" rel=""nofollow noreferrer"">https://github.com/baomidou/mybatis-plus</a></p>
<pre><code>public class SomeDomainClass extends Model&lt;SomeDomainClass&gt; {
</code></pre>
<p>How to mock (simulate) MyBatis-Plus data access layer for unit testing?</p>

<hr />
<p>Longer code example</p>
<pre class=""lang-java prettyprint-override""><code>package com.company.project.domain;

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import lombok.experimental.Tolerate;

import java.io.Serializable;
import java.math.BigDecimal;

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName(&quot;t_order&quot;)
@Builder
public class Order extends Model&lt;Order&gt; {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(name = &quot;id&quot; , value = &quot;id&quot;)
    @TableId(value = &quot;f_id&quot;, type = IdType.AUTO)
    private Long id;

    @ApiModelProperty(name = &quot;orderId&quot; , value = &quot;orderId&quot;)
    private Long orderId;
    
</code></pre>
",https://stackoverflow.com/questions/66756355/how-to-mock-simulate-mybatis-plus-data-access-layer-for-unit-testing-for-model,"['java', 'mybatis']",204,False,1,0
Unit testing of internal functions of a module while avoiding dependencies to test framework and HUnit,"<h2>Background</h2>
<p>Using stack, and its preset file <code>Spec.hs</code>, as far as I know you need to import the following test framework modules in order to execute a proper test:</p>
<pre><code>import qualified Test.Framework as TF
import qualified Test.Framework.Providers.HUnit as FHU
import qualified Test.Framework.Providers.QuickCheck2 as QC2
import qualified Test.HUnit as HU
import qualified Test.QuickCheck as QC
</code></pre>
<p>Hence, you also need to add the add dependecies into the <code>package.yaml</code> file, as follows:</p>
<pre><code>tests:
  XYZ-test:
    main:                Spec.hs
    source-dirs:         test
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - Test4
    - test-framework
    - test-framework-hunit
    - test-framework-quickcheck2
    - HUnit
    - QuickCheck
</code></pre>
<p>If you import the subject to test (calling it <code>MyModule</code>) and implement test cases in <code>Spec.hs</code> for that module then you cannot test the functions that are internally used in the module (<code>MyModule</code>).</p>
<p>To test the internal functions you could implement the tests inside the module (<code>MyModule</code>) and export the tests.</p>
<pre><code>module MyModule
    (
        ...
        testCases, -- exported test cases
        -- fun1 -- internal function not exported
    ) where

...

import qualified Test.Framework as TF
import qualified Test.Framework.Providers.HUnit as FHU
import qualified Test.HUnit as HU

fun1 :: [Bool] -&gt; Integer -- internal function not exported
fun1 ...

testCases =
    (FHU.testCase &quot;MyModule.fun1 #1&quot; ((fun1 []) HU.@?= 0)) : 
    (FHU.testCase &quot;MyModule.fun1 #2&quot; ((fun1 [True]) HU.@?= 0)) : 
    (FHU.testCase &quot;MyModule.fun1 #2&quot; ((fun1 [True, True]) HU.@?= 2)) : 
    []
</code></pre>
<p>But then you also need to import the test framework (at least, Test.Framework, Test.Framework.Providers.HUnit, and Test.HUnit) and need to add additional dependencies also to the library of (<code>MyModule</code>). Hence, package.yaml would look like this:</p>
<pre><code>...
dependencies:
- ...
- test-framework
- test-framework-hunit
- HUnit

library:
  source-dirs: src
...
</code></pre>
<h2>Question</h2>
<p>Is there a more lean aproach to export the unit test of module <code>MyModule</code>?</p>
",https://stackoverflow.com/questions/67903279/unit-testing-of-internal-functions-of-a-module-while-avoiding-dependencies-to-te,"['haskell', 'hunit']",170,False,0,1
Android Unit Test get code coverage that how much covered the working functions from unit testing,"<p>There is an in-build way to get code coverage by using &quot;createDebugCoverageReport&quot;. but that's NOT I want. I just want something like how much I covered my functions of the project from Unit test.</p>
",https://stackoverflow.com/questions/69765666/android-unit-test-get-code-coverage-that-how-much-covered-the-working-functions,"['android', 'unit-testing', 'code-coverage', 'jacoco']",190,True,-2,1
"Should mocks be used when unit testing a method that calls other, already unit tested methods?","<p>I have a method for validating an object. The validation that should be applied is dependant on some other value(s). Simple Example:</p>
<pre><code>public void ValidateObject(Object object, TestEnum enum, bool required)
{
    if(enum == TestEnum.A)
    {
        ValidateObjectPropertyA(object.PropertyA, required);
        ValidateObjectPropertyB(object.PropertyB, required);
        //Other Calls to Validation Methods
    }
    else
    {
        if(enum == TestEnum.C)
        {
            required = false;
        }

        ValidateObjectPropertyC(object.PropertyC, required);
        //Other Calls to Validation Methods
    }
}
</code></pre>
<p>In the above example, the methods ValidateObjectPropertyA, ValidateObjectPropertyB and ValidateObjectPropertyC are fully unit tested. I am now looking to unit test the &quot;ValidateObject&quot; method.</p>
<p>Given that the 3 methods have been fully unit tested, is this a good situation to use mocks to validate that the correct values are being passed to each method?</p>
",https://stackoverflow.com/questions/69036655/should-mocks-be-used-when-unit-testing-a-method-that-calls-other-already-unit-t,"['c#', 'unit-testing']",128,False,0,1
Unit testing a method that creates a JWT and returns Error: secretOrPrivateKey must have a value,"<p>I am trying to write a unit test for the method I wrote which generates a JWT. I am doing the following</p>
<pre><code>describe('returns a token', function() {
        it('should return a token', function() {
            let req = {};
            const a = authenticatorClass.returnToken(req);
            console.log(a);
        });
</code></pre>
<p>Note: I am not using expect yet, and seeing if the method works in first place by logging the result of the method to the console</p>
<p>And I receive the following error: <code>Error: secretOrPrivateKey must have a value</code></p>
<p>This is the method that I am trying to test:</p>
<pre><code>returnToken(expressRequestObject) {
        const payload = {};

        return jwt.sign(
            payload,
            SECRET,
            { expiresIn: '30d' },
        );
    }
</code></pre>
<p>What am I doing wrong here? TIA</p>
",https://stackoverflow.com/questions/67642506/unit-testing-a-method-that-creates-a-jwt-and-returns-error-secretorprivatekey-m,"['javascript', 'node.js', 'express', 'jwt', 'chai']",335,True,0,1
"Spring Boot Unit testing with Mockito and Junit 5, How do I set password to user","<p>I have the following test classes to create a mock user and check service that changes users passwords, but somehow when I initialize the user object password is always null.</p>
<pre><code>@Slf4j
@ExtendWith(MockitoExtension.class)
class UserServiceTest {

   @Mock UserRepository userRepository;

   @Mock ApiUtil apiUtil;
   @Mock PasswordEncoder passEncoder;
   @Mock EmailService emailService;

   @InjectMocks UserServiceV1 userService;
   @InjectMocks FakeUUIDProvider provider;
   @InjectMocks BCryptPasswordEncoder bcrypt;

   User user1;

   @BeforeEach
   public void setUp() {
     this.user1 = new User(
       this.provider.uuid(), 
       &quot;username1&quot;, 
       &quot;email1&quot;, &quot;password1&quot;, 
       &quot;displayName1&quot;, true
     );
   }

   @Test
   void shouldChangeUserPassword() throws Exception {

      // Stub
      when(this.userRepository.findByUsernameOrEmailAndIsActiveTrue(
        this.user1.getEmail(), this.user1.getEmail()))
            .thenReturn(Optional.of(this.user1));

      // Action
      final var retrivedUser = this.userService.forgotPassword(this.user1.getEmail());

      log.info(this.user1.getPassword());
   }
}
</code></pre>
<p>The <strong>retrivedUser</strong> object has all the other field values but password, the password field is always null. I have tried Mock creating PasswordEncoder and BycryptPasswordEncoder, but still no luck.</p>
<p>The expected result would be user1 having a password with the value &quot;passsword1&quot; not null;</p>
",https://stackoverflow.com/questions/69188721/spring-boot-unit-testing-with-mockito-and-junit-5-how-do-i-set-password-to-user,"['spring-boot', 'mockito', 'spring-boot-test']",673,False,0,0
"Masstransit Problem adding Payload to request/response in Unit Testing, alternativly using Pipes in Unit Tests","<p>currently I have the problem that I want to write unit tests for Masstransit in .NET. My request/response consumer has some consumer filters, one of these filters are generating extra data as message payload and attaching this to the request message. In order to test my consumer in a unit test I would like to add the Payload.</p>
<p>Q1) Is it possible to add the payload to the request message
Q2) Alternativly, can I make a mocking filter and set it as consumer filter in the pipeline? (Which sets the payload)</p>
<p>This is my latest attempt:</p>
<pre><code>    public class ContactCommandConsumerTest
    {
        [Fact]
        public async Task CreateContactOnUserRequestConsumer_RequestConsumer_IsAttached()
        {
            var harness = new InMemoryTestHarness { TestTimeout = TimeSpan.FromSeconds(5) };

[...]


            var consumer = harness.Consumer&lt;CreateContactOnUserRequestCommandConsumer&gt;(() =&gt; new CreateContactOnUserRequestCommandConsumer(loggerConsumer, mapper,kontakteintragRep,machineTime));
            var pipe = Pipe.New&lt;PipeContext&gt;(x =&gt; x.UseFilter(new MockFilter&lt;PipeContext&gt;()));


            // harness.Consumer&lt;CreateContactOnUserRequestCommandConsumer&gt;();
            await harness.Start();

            

            try
            {
                harness.Bus.ConnectConsumePipe&lt;CreateContactOnUserRequestCommandConsumer&gt;(pipe);

                var requestClient = await harness.ConnectRequestClient&lt;CreateContactOnUserRequestCommand&gt;();

                var response = await requestClient.GetResponse&lt;AcceptedResponse, FaultedResponse&gt;(new
                {
                    EntityInfo = &quot;Vb48cc135-4593-4b96-bb29-2cf136b3d1ee&quot;,

                });


                Assert.True(consumer.Consumed.Select&lt;CreateContactOnUserRequestCommand&gt;().Any());
                Assert.True(harness.Sent.Select&lt;FaultedResponse&gt;().Any());


            }
            finally
            {
                await harness.Stop();
            }
        }
    }

    internal class MockFilter&lt;T&gt; : IFilter&lt;T&gt; where T: class, PipeContext
    {
        public void Probe(ProbeContext context)
        {
            context.CreateFilterScope(&quot;mock&quot;);
        }

        public async Task Send(T context, IPipe&lt;T&gt; next)
        {
            context.GetOrAddPayload(() =&gt; new ContextUserPayload() { ContextUser = new Guid(&quot;dc6e091f-669e-45b3-9dd6-a36316f70527&quot;) });
            await next.Send(context);
        }
    }
</code></pre>
<p>I tried to build a pipe and add it to &quot;harness.bus.ConnectConsumerPipe&quot;. But the mock filter is never called ???</p>
",https://stackoverflow.com/questions/66694245/masstransit-problem-adding-payload-to-request-response-in-unit-testing-alternat,"['c#', '.net', 'unit-testing', 'masstransit']",608,False,0,1
How to send Properties file in src/test data to src/main application in Unit Testing,"<p>Hi I am new to Java and Spring boot.</p>
<p>I have a little project in which I have a main class under <code>src/main/java/MainApp.java</code>
and properties are <code>src/main/resources/application.properties</code>.</p>
<p>When i read the <code>src/main/resouces/application.properties</code> from <code>MainApp.java</code> it works fine.</p>
<p>Similarly i have <code>src/test/java/MainAppTest.java</code> and <code>src/test/resources/application.properties</code>.</p>
<p>When i read <code>src/test/resouces/application.properties</code> from <code>MainAppTest.java</code> it works fine.</p>
<p>Problem: I want to test a method in the <code>MainApp.java</code> which uses a property to create a file in a particular directory. When i call that method from <code>MainAppTest.java</code> the property can be read from <code>src/test/resources</code> but when the program execution goes to <code>MainApp.java</code> it shows that properties are <code>null</code>.</p>
<p><strong>How to transfer the properties read from <code>src/test/resources</code> to <code>src/main/java/MainApp.java</code></strong></p>
<p>Code:</p>
<p>MainApp.java</p>
<pre><code>@SpringBootApplication
@EnableJms
@EnableScheduling
public class EquensfilemqApplication {

@Value(&quot;${dir.location}&quot;)
private String directoryLocation;

protected void processMessage(String message)
    {
        String fileName = &quot;first.txt&quot;;
        FileWriter writer = new FileWriter (directoryLocation + fileName);
        
        // shows null when test is executed
        System.out.println(&quot;dir in main: &quot; + directoryLocation);
        
        writer.write (message);
        writer.close();
    }
}
</code></pre>
<p>MainAppTest.java</p>
<pre><code>class EquensfilemqApplicationTests {
    @Value(&quot;${dir.location}&quot;)
    private String directoryLocation;
    
    @Test
    void processMessageTest() {
        String testMessage = &quot;test content...&quot;;
        
        // prints correct value when test is executed
        System.out.println(&quot;dir in test: &quot; + directoryLocation);

        MainApp app = new MainApp();
        app.processMessage(testMessage);
        
    }
}
</code></pre>
<p>I am not aware of any methods/ways by which we can achieve this.</p>
",https://stackoverflow.com/questions/67232140/how-to-send-properties-file-in-src-test-data-to-src-main-application-in-unit-tes,"['java', 'spring-boot', 'junit5']",960,False,0,1
How to perform unit testing a react filter component using jest and &#39;react-dom/test-utils&#39;?,"<p>This is the react component which I am trying to unit test using <code>react-dom/test-utils</code></p>
<pre><code>import React from 'react'
import DatePicker from '../../../../../client/src/components/DatePicker.jsx'
import { Input } from '../../../../../client/src/forms/components.js'
import Select from 'react-select'
 
export class ListFilter extends React.PureComponent {
 render() {
   const { users, filters, filterHandler, filterSubmitHandler } = this.props
   return (
     &lt;div className='filter row'&gt;
       &lt;div className='col-lg-3 pb-1 pr-lg-1'&gt;
         &lt;Select
           labelKey='user'
           name='select-user'
           onChange={e =&gt; filterHandler('userId', e)}
           options={programs}
           placeholder='Filter by User...'
           simpleValue
           value={filters['userId'] &amp;&amp; parseInt(filters['userId'])}
           valueKey='id'
           disabled={false}
         /&gt;
       &lt;/div&gt;
       &lt;div className='col-lg-3 pb-1 pr-lg-1'&gt;
         &lt;DatePicker
           className='form-control'
           onChange={e =&gt; filterHandler('createdAt', e)}
           value={filters['createdAt']}
           placeholder={'Filter by Date...'}
         /&gt;
       &lt;/div&gt;
       &lt;div className='col-lg-3 pb-1 pr-lg-1'&gt;
         &lt;Input
           className='form-control mb-1 mr-md-1'
           key={'role'}
           name={'role'}
           onChange={e =&gt; filterHandler('role', e)}
           placeholder={'Search by Role...'}
           value={filters['role']}
         /&gt;
       &lt;/div&gt;
       &lt;div className='col-lg-1.5 pb-1 pr-lg-1'&gt;
         &lt;button
           className='btn btn-primary form-control mb-1'
           type='submit'
           onClick={filterSubmitHandler}
         &gt;
           &lt;i className='fa fa-search' /&gt; Search
         &lt;/button&gt;
       &lt;/div&gt;
     &lt;/div&gt;
   )
 }
}
</code></pre>
<p>Here is the unit test code that I started with and confused to proceed.</p>
<pre><code>jest.unmock('../ListFilter.jsx')
 
import { ListFilter } from '../ListFilter.jsx'
import React from 'react'
import ReactDOM from 'react-dom'
import Select from 'react-select'
import TestUtils, { Simulate } from 'react-dom/test-utils'
 
describe('ListFilter', () =&gt; {
 let props
 beforeEach(() =&gt; {
   props = {
     filters: {
       createdAt: null,
       order: 'event,desc',
       page: 1,
       userId: '',
       role: ''
     },
     users: [
       {
         id: 573,
         name: 'Gokul',
       },
       {
         id: 993,
         name: 'Vimal'
       },
       {
         id: 93,
         name: 'Bimal'
       }
     ]
   }
 })
 
 let component, onChange, filterHandler, filterSubmitHandler, node
 function render() {
   filterHandler = jest.fn()
   filterSubmitHandler = jest.fn()
 }
 
 describe('onChange', () =&gt; {
   beforeEach(render)
   it('should call onChange when user changes', () =&gt; {
     const container = document.createElement('div')
     ReactDOM.render(
       &lt;ListFilter
         {...props}
         filterHandler={filterHandler}
         filterSubmitHandler={filterSubmitHandler}
       /&gt;,
       container
     )
     
     container.querySelector('select').simulate('change')
     expect(container.querySelector('select').text()).toEqual('Gokul')
   })
 })
})
</code></pre>
<p>Can anyone please help me out to perform the full unit testing of the above component. Many thanks in advance.</p>
",https://stackoverflow.com/questions/69969278/how-to-perform-unit-testing-a-react-filter-component-using-jest-and-react-dom-t,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",1213,False,0,0
How can I do the Unit testing of these custom permissions in my Django/Django REST project?,"<p>everyone. I hope you're doing well. I'm a Django newbie, trying to learn the basics of RESTful development. I only know Python, so this is my best fit for the moment.</p>
<p>Right now I'm trying to implement Unit tests for my API. It's a simple model to implement CRUD on the names and heights of NBA players. In my models I added a class to describe this data and translated it to a view with ModelViewSets. I wanted to make this data editable only for a specific type of user (a read-write user), only readable for another (read-only user) as well as unaccesible to non-authenticated users. To do so, I created a custom User Model and translated it to my views with a custom permission. Now I want to write a few Unit tests to check that:</p>
<ol>
<li>r/w user can create a new player</li>
<li>r/w user can get a list of players</li>
<li>r/o user cannot create a new player</li>
<li>r/o user can get a list of players</li>
<li>unauthenticated user cannot create a new player</li>
<li>unauthenticated user cannot get a list of players</li>
</ol>
<p>Here is my <code>models.py</code>:</p>
<pre><code>from django.db import models
from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    ROLES = [('read-only', 'read-only'), ('read-write', 'read-write'),]
    role = models.CharField(max_length=32, choices=ROLES, default='read-only')
# Create your models here.
class NBAplayers(models.Model):
    first_name = models.CharField(max_length=100)
    h_in = models.DecimalField(max_digits=5, decimal_places=2)
    h_meters = models.DecimalField(max_digits=5, decimal_places=2)
    last_name = models.CharField(max_length=120)

    def __str__(self):
        return self.first_name
</code></pre>
<p>And my <code>views.py</code>:</p>
<pre><code>from .models import NBAplayers, User
from .serializers import NBAplayersSerializer
from rest_framework.response import Response
from rest_framework import status, viewsets, permissions

class ReadOnlyPermission(permissions.BasePermission):

    def has_permission(self, request, view):
        requests = ('POST', 'PUT', 'DELETE', 'PATCH')
        user = request.user
        role = User.role
        if user.is_anonymous:  # Not Authenticated
            return request.method == 'GET'            
        else:    
            if role == 'read-write':
                return request.method in requests + ('GET',)
            else:  # Read Only User
                return request.method == 'GET'

class NBAPlayersViewSet(viewsets.ModelViewSet):
    serializer_class = NBAplayersSerializer
    queryset = NBAplayers.objects.all()
    permission_classes = [ReadOnlyPermission] 
</code></pre>
<p>And Finally, my <code>urls.py</code>:</p>
<pre><code>from django.contrib import admin
from django.urls import path, include
from .views import  NBAPlayersViewSet
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('players', NBAPlayersViewSet, basename = 'Players list')


urlpatterns = [
    #djoser basic authentication
    #Routers URLs
    path('', include(router.urls)),
    path('players/&lt;int:pk&gt;/', include(router.urls)),
    path('', include('djoser.urls')),
    path('', include('djoser.urls.authtoken')),
]
</code></pre>
<p>All the code above required to add the custom user to the global settings with <code>AUTH_USER_MODEL = 'api_basic.User'</code>. So, I've read the documentation and watched a few videos trying to understand how to write the proper tests, but the examples are not that close to this problem. I wanted to ask for a few pointers in the right direction, so that I can use it to build the rest of the tests. This is my first time writing unit tests.</p>
<p>Thank you beforehand for any help or input you can give. Cheers!</p>
",https://stackoverflow.com/questions/67443402/how-can-i-do-the-unit-testing-of-these-custom-permissions-in-my-django-django-re,"['python', 'django', 'unit-testing', 'django-rest-framework', 'automated-tests']",603,True,2,1
"Jest unit testing &#39;expected mock functin to have been called last with, but it was not called&#39;","<p>I am new to Jest unit test, I try to write a test but it keep saying <code>'expected mock function to have been called last with, but it was not called'</code> not sure where is the issue. Below is APIClient.js file which I wrote a API call and in the test file I have mock the data, it logged</p>
<pre><code>Expected mock function to have been last called with: 
</code></pre>
<p><code>[&quot;/.../test1/...&quot;, {&quot;argu4&quot;: &quot;test4&quot;, &quot;argu5&quot;: &quot;test5&quot;, &quot;name&quot;: [{&quot;argu3&quot;: &quot;test3&quot;}, &quot;argu2&quot;: &quot;test2&quot;]}, {&quot;headers&quot;: {&quot;Content-Type&quot;: &quot;application/json&quot;, &quot;guest&quot;: false, &quot;locale&quot;: 'US'}}}]</code></p>
<pre><code>but it was not called. 
</code></pre>
<p>APIClient.js</p>
<pre><code>const { getLeapFrogHeaders } = require('...');

async myFunc(argu1, argu2, argu3, argu4, argu5) {
 const header = getLeapFrogHeaders();
 const requestBody = {
  name: [{ argu2, argu3}],
  argu4,
  argu5
 }

const response = await this.connector.patch(`/.../${argu1}/...`, requestBody, { headers });
return response.data;
}
</code></pre>
<p>APIClient.test.js</p>
<pre><code>import APIClient from './';
import MockConnector from './';

const mockConnector = new MockConnector({});
const APIClient = new APIClient(mockConnector);

describe('APIClient test', () =&gt; {
 const headers = {
  'Content-Type' : 'application/json',
   guest: false,
   locale: 'US'
 };

 it('successfully create API', () =&gt;{
  const requestBody = {
      name: [{ argu2: 'test2', argu3: 'test3'}],
      argu4: 'test4',
      argu5: 'test5'
     };
  const argu1 = 'test1';
  const spy = jest.spyOn(mockConnector, 'post');
  getLeapFrogHeaders.mockImplementation(() =&gt; headers);
  APIClient.myFunc(argu1, 'test2', 'test3', 'test4', 'test5');
  expect(spy).toHaveBeenLastCalledWith(`/.../${argu1}/...`, requestBody, { headers })

})
})
</code></pre>
",https://stackoverflow.com/questions/66757736/jest-unit-testing-expected-mock-functin-to-have-been-called-last-with-but-it-w,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",65,False,1,0
Laravel: How to check every element attribute value of an array of JSON data in unit testing,"<p>I am trying to test if the filter response has the right JSON data (every item should have the filtered group_code). I tried the following code but it doesn't work.</p>
<pre><code> public function test_filter_items_by_group_code_work_properly()
 {
    $filterCode = '026';

    $response = $this-&gt;get($this-&gt;ITEMS_URL . '?' . $this-&gt;groupAttribute . '='. $filterCode);

    $response-&gt;assertStatus(200);

    $items = $response-&gt;json()['data'];
    
    foreach ($items as $item) {
        $item_group = strval($item['group_code']);
        self::assertJson($item_group, $filterCode);
    }
  }
</code></pre>
<p>I get the following error:</p>
<pre><code>Illuminate\Foundation\Bootstrap\HandleExceptions::handleError(&quot;Trying to access array offset 
on value of type int&quot;,
</code></pre>
<p>The JSON response structure is like that:</p>
<pre><code>{
&quot;message&quot;: &quot;Items fetched successfully.&quot;,
&quot;data&quot;: {
    &quot;current_page&quot;: 1,
    &quot;data&quot;: [
        {
            &quot;group_code&quot;: &quot;026&quot;,
             ...
        },
        ...
</code></pre>
",https://stackoverflow.com/questions/69041527/laravel-how-to-check-every-element-attribute-value-of-an-array-of-json-data-in,"['php', 'laravel', 'laravel-8', 'laravel-testing']",170,False,1,0
Unit testing in Angular: How to test the error in the get request to obtain 100% coverage,"<p>Using Angular 11 I can't test the error in the get request to obtain 100% coverage
<a href=""https://i.stack.imgur.com/ptvZL.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
<p>from the oninit of the AppComponent I call the &quot;loadNotifications&quot; method which makes an asynchronous get call which controls both the correct and incorrect output</p>
<p><strong>app.component.ts</strong></p>
<pre><code>...
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  ...
  private cargarNotificaciones(): void {
    this._http.get&lt;any&gt;(environment.API_BASE_PATH + environment.endPointNotification).subscribe(
      (data: any[]) =&gt; {
        cosole.log(data);
      },
      (error) =&gt; {
        this._ir.interpretarRespuesta(error);
      }
    );
  }
</code></pre>
<p>The problem is that from the tests, I am not able to go through the error and be able to have 100% coverage</p>
<p><strong>app.component.spec.ts</strong></p>
<pre><code>...
describe('AppComponent', () =&gt; {
  let fixture: ComponentFixture&lt;any&gt;;
  let injector: TestBed;
  let httpClientSpy: { get: jasmine.Spy };
  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [
        ...
      ],
      declarations: [
        AppComponent
      ],
      providers: [
        ...
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
    fixture = TestBed.createComponent(AppComponent);
    injector = getTestBed();
    httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
  });

  it('Debería funcionar el método getNotificaciones con error', waitForAsync(() =&gt; {
    const app = fixture.componentInstance;
    spyOn(app._http, 'get').and.returnValue(new Error('error 404'));
    fixture.detectChanges();
    const resultado = app.cargarNotificaciones();
    expect(resultado).toBe(undefined);
  }));
});
</code></pre>
",https://stackoverflow.com/questions/68647119/unit-testing-in-angular-how-to-test-the-error-in-the-get-request-to-obtain-100,"['angular', 'testing', 'jasmine', 'karma-runner', 'angular11']",140,True,0,1
Unit Testing Quarkus with quarkus-smallrye-openapi causing InvalidDefinitionException Java 8 date/time type `java.time.LocalDate` not supported,"<p>I'am using quarkus-smallrye-openapi in a quarkus 1.13.0.Final application. Everything works fine when I execute the program with <code>mvnw compile quarkus:dev</code>. However, when I execute the unit tests having some variable of LocalDate data type by running <code>mvn test</code> the program then fails to marshal and unmarshal LocalDate type objects from json and it produces<pre> &quot;com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
Java 8 date/time type <code>java.time.LocalDate</code> not supported by default: add Module &quot;com.fasterxml.jackson.datatype:jackson-datatype-jsr310&quot; to enable handling&quot;</pre></p>
<p>when I remove the quarkus-smallrye-openapi dependency and relevant annotations, then the test run fine.</p>
",https://stackoverflow.com/questions/66986252/unit-testing-quarkus-with-quarkus-smallrye-openapi-causing-invaliddefinitionexce,"['jackson', 'quarkus']",925,True,0,1
How to do unit testing of method which is reading data from App_Data folder in ASP.Net MVC?,"<p>I am reading data from a JSON file which is placed App_Data folder, my method is like below.</p>
<pre><code>    public List&lt;CounterModel&gt; ReadData()
    {
        string file = HttpContext.Current.Server.MapPath(&quot;~/App_Data/counter.json&quot;);
        string Json = File.ReadAllText(file);
        List&lt;CounterModel&gt; items = JsonConvert.DeserializeObject&lt;List&lt;CounterModel&gt;&gt;(Json);
        var res = items.OrderByDescending(x =&gt; x.year).ToList();
        return res;
    }
</code></pre>
<p>I have written test method using nunit to test ReadData method like below,</p>
<pre><code>    [TestFixture]
    public class ReadJsonTest
    {
        [Test]
        public void ReadDataTestMain()
        {
            ReadFile rf = new ReadFile();
            int output = rf.ReadData().Count();
            Assert.IsTrue(output &gt; 0, &quot;The file is not having any data&quot;);

        }
    }
</code></pre>
<p>When I try to debug the test method(ReadDataTestMain) it is throwing error in my actual method(ReadData) in the very first line of HttpContext that <strong>Object reference not to set as an instance of object</strong>. How can I unit test my method?</p>
",https://stackoverflow.com/questions/65951804/how-to-do-unit-testing-of-method-which-is-reading-data-from-app-data-folder-in-a,"['c#', 'asp.net', 'asp.net-mvc', 'unit-testing', 'nunit']",11,False,0,0
"TypeError: Attempted to wrap findById which is already wrapped: Unit testing with mocha, sinon, node and mongodb","<p>I am trying to unit test my controller method and this is what it returns when I try to stub it : <code>TypeError: Attempted to wrap findById which is already wrapped</code>. I have tried using the before and after hooks but it does not fix the issue. I am using <code>sinon-express-mock</code> for req and res and <code>sinon</code> for stubs.</p>
<pre><code>describe('controller getUserData', function() {
    beforeEach(function() {
        sinon.stub(UserData, &quot;findById&quot;);
    });
    afterEach(function() {
        UserData.findById.restore();
    });
    it('getUserData by Id', async function() {
        const mockId = sinon.stub(UserData, 'findById').returns(mockIdData[0]);
        req = mockReq();
        res = mockRes();
        next = null;
        req.params.id = mockIdData[0]._id;
        await Controller.getUserData(req, res, next);
        assert(mockId.calledWith(req.params.id));
        assert(res.status.calledWith(200));
    });
    it('should return 404 when user data is not found', async function() {
        sinon.stub(UserData, 'findById').returns(null);
        req = mockReq();
        res = mockRes();
        next = null;
        await Controller.getUserData(req, res, next);
        assert(res.status.calledWith(404));
    });
});
</code></pre>
<p>Here is my controller method:</p>
<pre><code>exports. getUserData = async (req, res, next) =&gt; {

    const userData = await UserData.findById(req.params.id);

    if (!userData) {
        
        res.status(404).send();
    }

    res.status(200)
        .json(
            userData,
        );
};
</code></pre>
",https://stackoverflow.com/questions/66269126/typeerror-attempted-to-wrap-findbyid-which-is-already-wrapped-unit-testing-wit,"['javascript', 'node.js', 'unit-testing', 'mocha.js', 'sinon']",63,False,0,0
How to make a new instance method call in a java class do nothing in unit testing,"<p>In the method below, how do i ensure that while unit testing that the call to
new Job instance
does nothing and skips over to other code?</p>
<pre><code>public class TestedClass {
  public void methodToBeTested() {
    new Job(&quot;abc&quot;).start(&quot;123&quot;, &quot;ggg&quot;); //make this do nothing in unit test
    //other code
  }
}

public class Job {
  public String start(String a, String b){
    //some code
  }
}
</code></pre>
<p>Maybe using PowerMock, @Spy or simply mock?</p>
",https://stackoverflow.com/questions/67803561/how-to-make-a-new-instance-method-call-in-a-java-class-do-nothing-in-unit-testin,"['java', 'unit-testing', 'junit', 'mockito']",63,False,0,0
Mocking an OpenFeign client for Unit Testing in a spring library and NOT for a spring boot application,"<p>I've implemented a feign client that calls a get API based on this <a href=""https://github.com/OpenFeign/feign"" rel=""nofollow noreferrer"">official repository</a>. I have a rule class <code>UserValidationRule</code> that needs to call that get API call <code>getUser()</code> and validate some stuff. That works as expected but when I get to testing that rule class, mocking the feign client is not successful and it continues to call the actual API. I've simplified the situation so please ignore the simplicity lol. This is a follow up question I have after i found this <a href=""https://stackoverflow.com/questions/56383675/using-feign-in-a-standalone-library-vs-a-springboot-application"">stackoverflow</a> question</p>
<p>The API returns this model:</p>
<pre><code>@Data
public class userModel {
    private long id;
    private String name;
    private int age;

}
</code></pre>
<p>The interface with the rest client method:</p>
<pre><code>public interface UserServiceClient {

    @RequestLine(&quot;GET /users/{id}&quot;)
    UserModel getUser(@Param(&quot;id&quot;) int id);
}
</code></pre>
<p>And in the rule class, i build the feign client and call the API:</p>
<pre><code>@RequiredArgsConstructor
@Component
public class UserValidationRule {

    private static final String API_PATH = &quot;http://localhost:8080&quot;;

    private UserServiceClient userServiceClient;


    public void validate(String userId, ...) {
            // some validations 
            validateUser(userId);

    }

    private void validateUser(String userId) {
            userServiceClient = getServiceClient();
            UserModel userModel = userServiceClient.gerUser(userId);
            
            // validate the user logic
        }
    }

    private UserServiceClient getServiceClient() {
           return Feign.builder()
                  .encoder(new GsonEncoder())
                  .decoder(new GsonDecoder())
                  .target(UserServiceClient.class, API_PATH);
    }
}
</code></pre>
<p>And here comes the test class:</p>
<pre><code>public class UserValidationRuleTest {

    private UserServiceClient userServiceClient = mock(UserServiceClient.class);
    private UserValidationRule validationRule = new UserValidationRule();
    private UserModel userModel;

    @Before
    public void init() {
        userModel = generateUserModel();
    }


    @Test
    public void validateWhenAgeIsNotBlank() {

        doReturn(userModel).when(userServiceClient).getUser(any());
        validationRule.validate(&quot;123&quot;, ...);
        // some logic ...
        assertEquals(.....);
        verify(userServiceClient).getUser(any());
    }



    private UserModel generateUserModel() {
        UserModel userModel = new UserModel();
        userModel.setName(&quot;Cody&quot;);
        userModel.setAge(&quot;22&quot;);
        return accountModel;
    }
}
</code></pre>
<p>As I debug <code>validateWhenAgeIsNotBlank()</code>, i see that the userModel is not the one that's generated in the test class and the values are all null. If I pass in an actual <code>userId</code>, i get an actual UserModel that I have in my db.</p>
<p>I think the problem is that <code>UserServiceClient</code> is not being mocked. The <code>verify</code> is failing as it says the <code>getUser()</code> is not invoked. It might be something to do with how the feign client is declared in the <code>UserValidationRule</code> with the feign.builder()...
Please correct me if I'm wrong and tell me what I'm missing or any suggestions on how to mock it correctly.</p>
",https://stackoverflow.com/questions/66714825/mocking-an-openfeign-client-for-unit-testing-in-a-spring-library-and-not-for-a-s,"['java', 'spring', 'microservices', 'spring-cloud-feign', 'openfeign']",9693,True,4,1
I am working on unit testing using sanctum. I was testing as acting as a admin using sanctum,"<p>I have make a unit test case as :</p>
<pre><code>public function test_user_registration(){
         $this-&gt;withoutExceptionHandling();
         $this-&gt;withoutMiddleware();
         Bus::fake();
         $user = User::find(1);
         Sanctum::actingAs($user,['*']);
         $response = $this-&gt;post('/api/users',[
             &quot;firstName&quot;=&gt;&quot;Kamal&quot;,
             &quot;lastName&quot;=&gt;&quot;Garu&quot;,
             &quot;email&quot;=&gt;&quot;Kamasll@gmail.com&quot;,
             &quot;roleId&quot;=&gt;[4],
             &quot;defaultRoleId&quot;=&gt;4,
             &quot;investorId&quot;=&gt;[15],
             &quot;defaultInvestorId&quot;=&gt;15,
             &quot;streetAddress&quot;=&gt;&quot;Jalur Banj&quot;,
             &quot;postalCode&quot;=&gt;&quot;977&quot;,
             &quot;city&quot;=&gt;&quot;bhaktapur&quot;,
             &quot;countryId&quot;=&gt;160,
             &quot;phone&quot;=&gt;9741801138,
             &quot;status&quot;=&gt;1,
             &quot;emailPortfolioReport&quot;=&gt;0,
             &quot;emailInvestorActivities&quot;=&gt;0,
             &quot;emailMarketUpdate&quot;=&gt;1,
             &quot;isdCodeId&quot;=&gt;149,
             &quot;roleType&quot;=&gt;[&quot;investorInternational&quot;]
         ]);
         VerifyUser::dispatch($response);
         Bus::assertDispatched(VerifyUser::class);
         $response-&gt;assertStatus(200);
     }
</code></pre>
<p>And everytime i run this code this throw error as &quot;Illuminate\Auth\Access\AuthorizationException: not authorized
&quot;
Here 1 is the id of admin so m acting as a admin user. Need Help..</p>
",https://stackoverflow.com/questions/70078186/i-am-working-on-unit-testing-using-sanctum-i-was-testing-as-acting-as-a-admin-u,"['mysql', 'laravel', 'phpunit', 'laravel-sanctum']",578,False,2,0
How to test the return values of methods/queries called inside a method under test in unit testing?,"<p>The method under test has parts like this.</p>
<pre><code>public bool Method1()
{
 var List=Engine.GetList(id);//engine is from business layer
 var List1 = list.where(x=&gt;x.id== id);
 var List2 = list.where(x=&gt; x.score &gt; 400);
 
 StringBuilder sb = new StringBuilder();
 m_content1 = GetContent(list1,sb);

 StringBuilder sb2 = new StringBuilder();
 m_content2 = GetContent(list2,sb2);
          

}
</code></pre>
<p>GetContent is in the same class. This was written by someone else.
I feel its imperative have to  add  if statements  for checks on potential empty lists  and null string builder  in the method since they are return values that can break the case. And then  add unit test cases for these ifs in the unit test.</p>
<p>The key question is to figure out how to test the lists and stringbuilders  for empty/null cases.</p>
",https://stackoverflow.com/questions/69474326/how-to-test-the-return-values-of-methods-queries-called-inside-a-method-under-te,['unit-testing'],65,False,1,0
Mockito unit testing: Can&#39;t test REST ressource - RESTEASY003135: Class must be annotated with @Path to invoke path(Class),"<p>I'm trying to test a REST resource with Mockito. Here is the code:</p>
<pre><code>  @Mock
  private Service service;
  @InjectMocks
  private Resource resource;
  ....
  doNothing().when(service).createItem(anyLong(), any(Item.class));
  Response response = resource.createItem(item);
  ...
</code></pre>
<p>It raises the following exception:</p>
<pre><code>[INFO] Running ...TestItems
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.447 s &lt;&lt;&lt; FAILURE! - in ...TestItems
[ERROR] testCreateItem  Time elapsed: 0.373 s  &lt;&lt;&lt; ERROR!
java.lang.IllegalArgumentException: RESTEASY003135: Class must be annotated with @Path to invoke path(Class)
    at ...Tests.testCreateItem(TestItems.java:62)
</code></pre>
<p>The REST resource looks like this:</p>
<pre><code>@Path(&quot;/items&quot;)
public class Resource
{
  ....
  @POST
  public Response createItem (Item item)
  {
    ...
  }
}
</code></pre>
<p>I understand that calling a REST endpoint requires a REST client but in unit tests with Mockito this is supposed to work 'cause I've seen several examples doing that. What am I doing wrong here ?</p>
<p>Many thanks in advance.</p>
<p>Seymour</p>
",https://stackoverflow.com/questions/65833610/mockito-unit-testing-cant-test-rest-ressource-resteasy003135-class-must-be,"['rest', 'mockito']",190,False,1,1
"Unit Testing Events in Laravel 8 throw EventFake::__construct() must implement interface Illuminate\Contracts\Events\Dispatcher, null given","<p>I'm trying to fake an event using Unit Testing, so no DB, no Application, just pure classes.</p>
<p>I'm following the documentation for Laravel 8, my current version, but I'm still getting the error</p>
<pre><code>1) Tests\Unit\HandShake\ConfirmApplicationHandShakeActionTest::BasedOnAnExistentAppIConfirmTheHandShake
TypeError: Argument 1 passed to Illuminate\Support\Testing\Fakes\EventFake::__construct() must implement interface Illuminate\Contracts\Events\Dispatcher, null given, called in /Users/pablo/Workspace/xxxx/vendor/laravel/framework/src/Illuminate/Support/Facades/Event.php on line 38
</code></pre>
<p>As you can see is asking for an object implementing the interface Dispatch, my Event has the trait dispatch, but anyways here it says that I'm passing <code>null</code></p>
<p>My Test code is the one as follow</p>
<pre><code>&lt;?php

namespace Tests\Unit\HandShake;

use App\Actions\ConfirmApplicationHandShakeAction;
use App\Events\HandShakeReceivedEvent;
use App\Exceptions\NotFoundApplicationException;
use App\Models\Application;
use Illuminate\Support\Facades\Event;
use Mockery\MockInterface;
use Mockery;

use PHPUnit\Framework\TestCase;

class ConfirmApplicationHandShakeActionTest extends TestCase
{

    /**
     *
     * @test
     * @throws NotFoundApplicationException
     */
    public function BasedOnAnExistentAppIConfirmTheHandShake()
    {

        $appName = 'testDummy';

        Event::fake([HandShakeReceivedEvent::class]);

        $applicationModel = Mockery::mock(Application::class, function (MockInterface $mock) {
            $mock-&gt;shouldReceive('exists')
                -&gt;andReturn(true)
                -&gt;once();
        });
        $confirmation = new ConfirmApplicationHandShakeAction($applicationModel);
        $confirmation-&gt;execute($appName);
</code></pre>
<p>The Class that I'm testing is</p>
<pre><code>    &lt;?php
declare(strict_types=1);

namespace App\Actions;

use App\Events\HandShakeReceivedEvent;

use App\Exceptions\NotFoundApplicationException;
use App\Models\Application;


/**
 * Class ConfirmApplicationHandShakeAction
 * @package App\Actions
 */
class ConfirmApplicationHandShakeAction
{
    /**
     * @var Application
     */
    private $application;

    /**
     * ConfirmApplicationHandShakeAction constructor.
     * @param Application $application
     */
    public function __construct(Application $application)
    {
        $this-&gt;application = $application;
    }

    /**
     * @param string $appName
     * @throws NotFoundApplicationException
     */
    public function execute(string $appName)
    {

        if ( ! $this-&gt;application-&gt;exists($appName)) {
            throw new NotFoundApplicationException('The Application do not exists or is not active');
        }

        HandShakeReceivedEvent::dispatch($appName);
    }
}
</code></pre>
<p>Lastly the event is</p>
<pre><code>    &lt;?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class HandShakeReceivedEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}
</code></pre>
<p>Probably is one of those moments where I'm missing a stupid character, but I went through this error, and I cannot find the right solution.</p>
<p><strong>UPDATE</strong></p>
<p>I keep digging and I found that the getFacadeRoot() is returning null, so I'm assuming that something is not properly initialized, still not clue</p>
<p>static::swap($fake = new EventFake(static::getFacadeRoot(), $eventsToFake));</p>
<p>Thank you in advance if you find the issue or can point me in the right direction. I also tried FakeFor and Fake without sending the event as a parameter</p>
",https://stackoverflow.com/questions/66105051/unit-testing-events-in-laravel-8-throw-eventfake-construct-must-implement-i,['laravel'],1049,True,1,1
Espresso Unit Testing NullPointerException,"<p>I'm have a problem with my unit testing.
when set favorite value from unit testing, but return always NullPointerException.</p>
<p>this is my repository:</p>
<pre><code>class FakeFilmRepository(
    private val remoteDataSource: RemoteDataSource,
    private val localDataSource: LocalDataSource,
    private val appExecutors: AppExecutors) : FilmDataSource {

    override fun setFilmFavorite(film: FilmEntity, state: Boolean) =
        appExecutors.diskIO().execute { localDataSource.setFilmFavorite(film, state) }}
</code></pre>
<p>And this is my unit testing:</p>
<pre><code>class FilmRepositoryTest {

@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()

private val remote = mock(RemoteDataSource::class.java)
private val local = mock(LocalDataSource::class.java)
private val appExecutors = mock(AppExecutors::class.java)
private val filmRepository = FakeFilmRepository(remote, local, appExecutors)

private val movieResponses = DataDummy.generateRemoteDummyMovies()
private val movieId = movieResponses[0].id
private val movieCastResponses = DataDummy.generateRemoteDummyCasts(movieId)

@Mock
private lateinit var observer: Observer&lt;FilmWithCast&gt;

@Test
fun setFavoriteFilm() {
    val dummyFilmWithCast = Resource.success(DataDummy.generateDummyFilmWithCasts(DataDummy.generateDummyMovies()[0], false))
    val film = MutableLiveData&lt;Resource&lt;FilmWithCast&gt;&gt;()
    film.value = dummyFilmWithCast
    `when`(filmRepository.getFilmWithCasts(movieId)).thenReturn(film)

    val castResource = film.value
    if (castResource != null) {
        val filmWithCast = castResource.data
    
        if (filmWithCast != null) {
            val filmEntity = filmWithCast.mFilm
            val newState = !filmEntity.favorite
            filmRepository.setFilmFavorite(DataDummy.generateDummyMovies()[0], newState) //ERROR NULL
        }
    }

    verify(observer).onChanged(dummyFilmWithCast.data)
} }
</code></pre>
<p>Result ERROR NULL:</p>
<pre><code>java.lang.NullPointerException
at com.pamungkasrizall.films.data.FakeFilmRepository.setFilmFavorite(FakeFilmRepository.kt:188)
at com.pamungkasrizall.films.data.FilmRepositoryTest.setFavoriteFilm(FilmRepositoryTest.kt:115)
</code></pre>
<p>How to fix it?</p>
",https://stackoverflow.com/questions/66435859/espresso-unit-testing-nullpointerexception,"['android', 'unit-testing', 'kotlin']",189,False,1,1
How to meet the test coverage in the following Unit testing in Nodejs?,"<p>I am doing Unit testing in NodeJS. I have managed to see the coverage of my unit testing using NYC. I would like to know how can i widen my unit testing scope to increase the coverage of Statement branch and condition branch. I have the following code for testing.</p>
<pre><code>const value = () =&gt; {
  const def = &quot;defvalue&quot;;
  const abc = &quot;abcvalue&quot;;

  if(abc &amp;&amp; abc !== &quot;undefined&quot;){
    return abc
  }else if (def &amp;&amp; def !== &quot;undefined&quot;){
    return def
  }else{
    return false
  }
}

//Function to do unit testing.
describe(&quot;the result function&quot;, () =&gt; {    
  it(&quot;should return false&quot;, () =&gt; {
    const result = value();
    console.log(&quot;The result is:&quot;, result);
    expect(result).to.be.false;
  });
  
  it(&quot;should return abc&quot;, () =&gt; {
    const result = value();
    console.log(&quot;The result is:&quot;, result);
    expect(result).to.be.eq(&quot;abc&quot;);
  });
  
  it(&quot;should return def&quot;, () =&gt; {
    const result = value();
    console.log(&quot;The result is:&quot;, result);
    expect(result).to.be.eq(&quot;def&quot;);
  });
});
</code></pre>
",https://stackoverflow.com/questions/68812371/how-to-meet-the-test-coverage-in-the-following-unit-testing-in-nodejs,"['node.js', 'unit-testing', 'npm', 'test-coverage', 'nyc']",492,True,0,1
Why is this code not good for unit testing?,"<p>Apparently this code is not good for unit testing, I'm wondering why? What does it mean that a code is &quot;good&quot; for unit testing?</p>
<pre><code> public class B 
  {
        public int Y { get ; }
        public int X { get ; }
        public B() 
        {
          X = 3;
          Y = 7;
        }

        public B(int x) 
        {
          X = x;
          Y = 2 * x;
        }
  }

 public class A 
 {
        public B MyB { get ; set ; }
        public A() {MyB = new B ();}

        bool M1( int a, int b) 
        {
           if (a &gt; MyB.X) return false;
           if (b &lt; MyB.Y) return false;
           return true;
        }

        public B M2(int x) { return new B(x);}
}
</code></pre>
",https://stackoverflow.com/questions/68268578/why-is-this-code-not-good-for-unit-testing,"['c#', 'unit-testing']",70,True,1,1
Are Unit Tests with Google Test exported with project?,"<p>I've been studying Unit Testing with Google Test in C++.</p>
<p>If the purpose of Unit Testing is to ensure certain segments or objects of the code are working the way they are supposed to, I would assume it's not necessary to compile and export the unit testing code with the final project, right? It's not like the user will be using it anyway. It just seems like it makes the project size unnecessarily larger.</p>
<p>My main question is: will all the Unit Testing code be compiled and exported with the final project or will I have to manually delete all the Unit Tests before exporting it?</p>
<p>Is there a best (or common) practice for Unit Testing and exporting projects?</p>
",https://stackoverflow.com/questions/66872573/are-unit-tests-with-google-test-exported-with-project,"['c++', 'unit-testing', 'googletest']",105,True,0,2
Is Google Unit Test compatible with IEC 62304?,"<p>I have the following Questions About embedded unit testing:</p>
<ol>
<li>Can Google unit testing be used for embedded C Code?</li>
<li>Is Google unit test compatible with IEC 62304?</li>
</ol>
<p>I tried to find a document, which could answer my Question but unable to find that. Even in the Google Unit Test Official Documentation<a href=""https://github.com/google/googletest"" rel=""nofollow noreferrer"">1</a>, I was not able to find the answer. Also, I have the following Question:</p>
<ol start=""3"">
<li>How would I know an open source Unit Testing Tool is compatible with IEC 62304 Standard?</li>
</ol>
<p>Please help me with your Knowledge in Unit Testing.
Thanks in Advance.</p>
",https://stackoverflow.com/questions/69434259/is-google-unit-test-compatible-with-iec-62304,"['c', 'unit-testing', 'embedded']",217,True,0,2
how to make connection between visual studio project and unit test project?,"<p>I have big C# solution.<br />
I added to this solution an unit testing project.</p>
<p>I want to make somehow a connection between the unit testing and all the other project -
what I mean is I want to make a automation that will run the unit testing on the end of the project build and if there will be any test fail =&gt; the project build will show fail</p>
<p>How to do it ?</p>
",https://stackoverflow.com/questions/70345198/how-to-make-connection-between-visual-studio-project-and-unit-test-project,"['c#', 'visual-studio', 'unit-testing']",74,True,1,1
ngx-leaflet-draw: Importing module which does not have a ɵmod property,"<blockquote>
<p>Importing LeafletDrawModule which does not have a ɵmod property</p>
</blockquote>
<p>I am seeing this error during my unit testing(jest).</p>
<p>The code works fine when I run the ng application. Leaflet draw function works perfectly.</p>
<pre><code>Angular: 11
@asymmetrik/ngx-leaflet: 8.1.0
@asymmetrik/ngx-leaflet-draw: 7.0.0
</code></pre>
<p>This error happens when unit testing components referencing  LeafletDrawModule</p>
",https://stackoverflow.com/questions/67202351/ngx-leaflet-draw-importing-module-which-does-not-have-a-%c9%b5mod-property,"['angular', 'leaflet', 'leaflet.draw', 'ngx-leaflet', 'ngx-leaflet-draw']",4364,True,5,1
Mocking Local Method Inside of a Service Class in Mockito Spring Boot Java,"<pre><code>@Service
public class MyServiceImpl implements MyService {

    @Autowired
    SomeOtherService otherService;    

    @Override
    public List&lt;Something&gt; getSomething(Integer id) {
        Something s = otherService.getOfSomething(id)
        return doSomething(s.getId());
    }

    @Override
    public List&lt;Something&gt; doSomething(Integer id) {
        List&lt;Something&gt; list = new ArrayList&lt;&gt;();
        // --- Some Logic ---
        return list;
    }
}
</code></pre>
<p>I have a Service Class with the simpler structure as above. I've been figuring out how to mock a method that is present in the same service class whose method I am unit testing (that is how to mock doSomething() method while unit testing getSomething). Can someone please help me with mocking a method local to the service method I am unit testing? Thank you</p>
<p>My test Look as follows now</p>
<pre><code>@Mock
SomeOtherService otherService;

@InjectMock
MyServiceImpl myServiceImpl;

@Test
public void testGetSomething() {
    Something s = new Something();
    when(otherService.getOfSomething(anyInt())).thenReturn(s);
    List&lt;Something&gt; list = myServiceImpl.getSomething(10);
    verify(otherService, times(1)).getOfSomething(anyInt());
}
</code></pre>
",https://stackoverflow.com/questions/69309773/mocking-local-method-inside-of-a-service-class-in-mockito-spring-boot-java,"['java', 'spring-boot', 'unit-testing', 'mockito', 'junit4']",1131,False,0,1
How to unit test this function?,"<p>I am trying to write unit testing for the following code:</p>
<p>This is my logic</p>
<pre><code>public async Task RemoveUser(string id)
{
    var response = await _graphQLClient.SendMutationAsync&lt;Response&gt;(request);
    if (response.Errors != null)
    {
         throw new ClientException(errorMessages);
    }
}
</code></pre>
<p>This is my unit testing</p>
<pre><code>[Test]
public void RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
     _mockGraphQLClient
                .Setup(client =&gt; client.SendMutationAsync&lt;object&gt;(It.IsAny&lt;GraphQLRequest&gt;(), It.Is&lt;CancellationToken&gt;(token =&gt; token == default)))
                .ReturnsAsync( new GraphQLResponse&lt;object&gt;());

     var psClient = new PsClient(_mockGraphQLClient.Object);
     var removeUserResults = psClient.RemoveUser(id);
     Assert.AreEqual(removeUserResults, /* what to put here? */ );
}
</code></pre>
<p>I am confused with what should I compare my results?</p>
<p>And how to handle:</p>
<blockquote>
<p>&lt;System.Threading.Tasks.Task`1[System.Threading.Tasks.VoidTaskResult]</p>
</blockquote>
<p>?</p>
",https://stackoverflow.com/questions/66791985/how-to-unit-test-this-function,"['c#', 'unit-testing', 'asp.net-core', 'async-await', 'graphql']",746,True,1,1
Make unit tests on xamarin forms project that don&#39;t use MVVM pattern,"<p>I want to add tests in an mobile app developped with Xamarin Forms but I didn't find any topics about unit testing without MVVM.</p>
<p>I saw : <a href=""https://learn.microsoft.com/fr-fr/xamarin/xamarin-forms/enterprise-application-patterns/unit-testing"" rel=""nofollow noreferrer"">https://learn.microsoft.com/fr-fr/xamarin/xamarin-forms/enterprise-application-patterns/unit-testing</a></p>
<p>but nothing without MVVM pattern</p>
<p>My questions are :</p>
<ul>
<li>Is it possible to make unit testing without MVVM pattern ?</li>
<li>Is it better to implement MVVM pattern before add unit tests ?</li>
</ul>
<p>Thank's a lot for your replies.</p>
",https://stackoverflow.com/questions/68527867/make-unit-tests-on-xamarin-forms-project-that-dont-use-mvvm-pattern,"['c#', 'testing', 'xamarin.forms']",280,False,0,0
ReferenceError: Cannot access &#39;jest_mock_extended_1&#39; before initialization,"<p>I have the following code.</p>
<p>singleton.ts</p>
<pre><code>import prisma from &quot;../prismaClient&quot;;
import { mockDeep, mockReset } from &quot;jest-mock-extended&quot;;
import { PrismaClient } from &quot;@prisma/client&quot;;
import { DeepMockProxy } from &quot;jest-mock-extended/lib/cjs/Mock&quot;;

jest.mock(&quot;../prismaClient&quot;, () =&gt; ({
  __esModule: true,

  default: mockDeep&lt;PrismaClient&gt;(),
}));

beforeEach(() =&gt; {
  mockReset(prismaMock);
});

export const prismaMock = prisma as unknown as DeepMockProxy&lt;PrismaClient&gt;;
</code></pre>
<p>prismaClient.ts</p>
<pre><code>import { PrismaClient } from &quot;@prisma/client&quot;;

const prisma = new PrismaClient({
  log: [
    {
      emit: &quot;event&quot;,
      level: &quot;query&quot;,
    },
    {
      emit: &quot;stdout&quot;,
      level: &quot;error&quot;,
    },
    {
      emit: &quot;stdout&quot;,
      level: &quot;info&quot;,
    },
    {
      emit: &quot;stdout&quot;,
      level: &quot;warn&quot;,
    },
  ],
});

export default prisma;
</code></pre>
<p>I am following prisma's guide to unit testing here: <a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""nofollow noreferrer"">https://www.prisma.io/docs/guides/testing/unit-testing</a>. I don't know why I keep getting this error:</p>
<p><strong>This the error message</strong>
ReferenceError: Cannot access 'jest_mock_extended_1' before initialization</p>
<pre><code>       7 |   __esModule: true,
       8 |
    &gt;  9 |   default: mockDeep&lt;PrismaClient&gt;(),
         |            ^
      10 | }));
      11 |
      12 | beforeEach(() =&gt; {

      at src/utils/testUtils/singleton.ts:9:12
      at Object.&lt;anonymous&gt; (src/utils/testUtils/singleton.ts:1:1)
      at Object.&lt;anonymous&gt; (src/resolvers/functions/user.test.ts:1:1)
</code></pre>
",https://stackoverflow.com/questions/70068335/referenceerror-cannot-access-jest-mock-extended-1-before-initialization,"['typescript', 'unit-testing', 'jestjs', 'prisma']",2515,True,3,2
How to add unit testing in strapi version 4 using jest?,"<p>I'm trying to add unit testing on a brand new strapi application. The official documentation is still in progress. So, until the documentation is being ready is there a way to add jest unit testing to strapi application ? i followed the approach in the v3 documentation with no luck.</p>
",https://stackoverflow.com/questions/70283992/how-to-add-unit-testing-in-strapi-version-4-using-jest,"['node.js', 'unit-testing', 'jestjs', 'strapi']",573,True,5,1
$router.push not triggering in unit testing,"<p>I have the following problem while trying to unit test my Vue application.
Even spying and mocking $router.push, I still can't make it to be called while inside unit testing:</p>
<p>This is my unit testing (<strong>Home.spec.js</strong>)</p>
<pre><code>const localVue = createLocalVue();

localVue.use(Vuex);
localVue.use(VueRouter);

describe('Home.vue', () =&gt; {
  let actions;
  let getters;
  let store;
  let router;

  beforeEach(() =&gt; {
    actions = {
        [FETCH_USER_REPOSITORIES]: jest.fn()
    };

    getters = {
       getTopThreeRepositories: jest.fn(repositoryMock.getRepositories)
    };

    store = new Vuex.Store({ getters, actions });
    router = new VueRouter();
  });

  it('should redirect when 404 status code received', async () =&gt; {
    jest.spyOn(store, 'dispatch').mockRejectedValue({ statusCode: 404 });
    jest.spyOn(router, 'push').mockResolvedValue({});

    const wrapper = await shallowMount(Home, {
        store,
        localVue,
        router
    });
    
    expect(router.push).toHaveBeenCalledWith('/not-found');
});
</code></pre>
<p>});</p>
<p>Now, this is my <strong>Home.vue</strong>:</p>
<pre><code>import { mapGetters } from 'vuex';
  import { FETCH_USER_REPOSITORIES } from &quot;../store/actions&quot;;

  import RepositoryList from &quot;@/components/RepositoryList&quot;;
  import Card from &quot;@/components/Card&quot;;

  export default {
    name: 'view-home',
    components: {
      Card,
      RepositoryList
    },

    async beforeMount() {
      try {
        await this.$store.dispatch(FETCH_USER_REPOSITORIES, 'some-repo');
      } catch(err) {
        console.log(this.$router);
        await this.$router.push('/not-found');
      }
    },

    computed: {
      ...mapGetters([&quot;getTopThreeRepositories&quot;])
    }
  }
</code></pre>
<p>The console log shows the $router correctly, with the spy.
If I force the calling inside the unit testing, it works, but the expects always fails giving me back that $router.push hasn't been called.</p>
<p>Can anyone help me, please?
Thanks!</p>
",https://stackoverflow.com/questions/67046602/router-push-not-triggering-in-unit-testing,"['vue.js', 'jestjs', 'vue-router']",1369,False,1,1
Mock Python async multi function,"<p>How to mock async multi-function in python tornado framework. I want to do unit testing for the async function. inside the async function, I have an await multi() function call. how do I patch this multi-function for unit testing?</p>
<pre><code>from tornado.gen import multi

async def get_session_details(request_param, docs):
     sesson = await multi([doc for doc in docs])
     # session result is [[],[],[],[],[]]
     return session

# unit test
import pytest
from tornodo.gen import multi
import mock

@mock.patch(tornoda.gen.multi)
async def test_get_session(mock_multi)
    mock_multi.return_value = [[],[],[],[],[]]
    session = get_session_detals(request_param, docs)
    assert session[0][session] is None

# The above code I tried but mock multi is not patching with get_session_details.
</code></pre>
",https://stackoverflow.com/questions/67747427/mock-python-async-multi-function,"['python', 'async-await', 'microservices', 'tornado']",941,False,0,2
How to unit test a Close Modal function for closing a modal dialog container?,"<p>I am totally new to unit testing and have no idea about it, so I want help unit testing a javascript modal function which is responsible for closing a modal dialog container. I just want to unit test the <strong>closeModal()</strong> function.</p>
<p><strong>Javascript part</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code> closeModal() {
    const mod = document.getElementsByClassName('mat-dialog-container');
    mod[0].classList.add('close-modal-animation');
    setTimeout(() =&gt; {
      this.dialog.closeAll();
    }, 500);
  }</code></pre>
<pre class=""snippet-code-css lang-css prettyprint-override""><code>**Html part**</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;ng-template #callDialog&gt;
  &lt;div class=""modal-base""&gt;
    &lt;span
      [ngClass]=""{'icon-close' : closeButton}""
      (click)=""closeModal()""
    &gt;&lt;/span&gt;
  &lt;/div&gt;
  &lt;mat-dialog-content&gt;
    &lt;ng-content&gt;&lt;/ng-content&gt;
  &lt;/mat-dialog-content&gt;
&lt;/ng-template&gt;</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/68866792/how-to-unit-test-a-close-modal-function-for-closing-a-modal-dialog-container,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",148,False,0,0
Python Google Cloud Storage Connector Unit Test,"<p>I've developed the following connector in python for google cloud storage:</p>
<pre><code>from google.cloud import storage


class StorageConnector:
    
    @staticmethod
    def download_as_string(bucket_name: str, source_blob_name: str):
        return (
            storage.Client()
            .bucket(bucket_name=bucket_name)
            .blob(blob_name=source_blob_name)
            .download_as_bytes()
            .decode(&quot;utf-8&quot;)
        )
</code></pre>
<p>I want to do unit testing. I've implemented the following test but it seems to be uncorrect:</p>
<pre><code>import unittest
from unittest.mock import patch

import google.cloud.storage
import mock
import requests

from six.moves import http_client

PROJECT = &quot;PROJECT&quot;
BUCKET_NAME = &quot;BUCKET&quot;
BLOB_NAME = &quot;BLOB&quot;

class StorageConnectorTest(unittest.TestCase):

    @patch(&quot;google.cloud.storage.Client&quot;)
    @patch(&quot;google.cloud.storage.Bucket&quot;)
    @patch(&quot;google.cloud.storage.Blob&quot;)
    def test_download_as_string(self, BlobMock, BucketMock, ClientMock):
        from my_custom_package.gcloud.connectors.storage._storage_connector import StorageConnector

        self.assertIs(ClientMock, google.cloud.storage.Client)
        self.assertIs(BucketMock, google.cloud.storage.Bucket)
        self.assertIs(BlobMock, google.cloud.storage.Blob)

        source_blob_name = &quot;source_blob_name&quot;
        data = bytes(&quot;This is the content of source_blob_name&quot;.encode(encoding=&quot;utf-8&quot;))

        BlobMock.return_value = data
        self.assertEqual(
            StorageConnector.download_as_string(bucket_name=BUCKET_NAME, source_blob_name=source_blob_name), data
        )
</code></pre>
<p>Because I get the error:</p>
<pre><code>======================================================================
FAIL: test_download_as_string (tests.gcloud.connectors.storage.test_storage_connector.StorageConnectorTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File &quot;/usr/lib/python3.8/unittest/mock.py&quot;, line 1325, in patched
    return func(*newargs, **newkeywargs)
  File &quot;.../package/tests/gcloud/connectors/storage/test_storage_connector.py&quot;, line 91, in test_download_as_string
    self.assertEqual(
AssertionError: &lt;MagicMock name='Client().bucket().blob()[47 chars]424'&gt; != 'This is the content of source_blob_name'

</code></pre>
<p>How can I do unit testing to fully cover the code?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/69080866/python-google-cloud-storage-connector-unit-test,"['python', 'unit-testing', 'google-cloud-platform', 'google-cloud-storage', 'storage']",166,False,1,0
Error when running unit test &quot;You should not use &lt;Link&gt; outside a &lt;Router&gt;&quot;,"<p>I have a unit test here and I am performing a click event. I am getting the error:<br />
<code>Invariant failed: You should not use &lt;Link&gt; outside a &lt;Router&gt;</code></p>
<pre><code>describe(&quot;when the menu icon has been clicked&quot;, () =&gt; {
    test(&quot;the account menu should be displayed&quot;, () =&gt; {
        const { getByTestId } = render(&lt;AccountMenu userDetails={fakeUser}&gt;&lt;/AccountMenu&gt;);
        const button = getByTestId(&quot;button-icon-element&quot;);
        fireEvent.click(button);
        screen.debug();
    });
});
</code></pre>
<p>I am pretty sure I know why it's crying but wondering if there is a simple way to get around this whilst unit testing.
The unit testing frame work I'm using is <code>@testing-libary/react</code>.</p>
",https://stackoverflow.com/questions/66789264/error-when-running-unit-test-you-should-not-use-link-outside-a-router,"['reactjs', 'react-router', 'react-testing-library', 'react-typescript', 'react-test-renderer']",900,True,3,2
Unit testing of complex objects C#,"<p>I wrote a short application, but I ran into the problem of writing a unit test Method MaximumRowSum_DefectiveLines. Please tell me how I should act, my class for testing</p>
<pre><code>public class OutputtingStrings
{
    public class MaxSumLineResult
    {
        public int MaxSumLineIndex { get; set; }
        public List&lt;string&gt; DefectiveLines { get; set; }
        public override string ToString()
        {
            return $&quot;Line number with maximum sum of elements: { MaxSumLineIndex + 1}&quot;; /* + &quot;\n&quot; +
                 $&quot;Defective lines:{string.Join(&quot;\n&quot;, DefectiveLines)}&quot;;*/
        }
    }

    public static bool IsValidateFileExist(string filePath)
    {
        if (File.Exists(filePath))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public MaxSumLineResult MaximumRowSum_DefectiveLines(string[] fileData)
    {
        List&lt;string&gt; defectiveLines = new List&lt;string&gt;();
        int lineNumber = 0;
        var indexOfLines = new Dictionary&lt;int, double&gt;();
        foreach (var line in fileData)
        {
            NumberStyles style = NumberStyles.Number;
            CultureInfo culture = CultureInfo.CreateSpecificCulture(&quot;en-GB&quot;);

            var stringElements = line.Split(&quot;,&quot;,  StringSplitOptions.RemoveEmptyEntries);
            if (stringElements.Any(n =&gt; double.TryParse(n, style, culture, out var number)))
            {
                indexOfLines.Add(lineNumber, stringElements.Sum(n =&gt;
                {
                    return double.Parse(n, style, culture);
                }));
            }
             else  
            {
                 defectiveLines.Add(line);
            }

            lineNumber++;

        }
        var maxSumLineIndex = indexOfLines.FirstOrDefault(x =&gt;
           x.Value == indexOfLines.Values.Max()).Key;

        var resultLines = new MaxSumLineResult
        {
            MaxSumLineIndex = maxSumLineIndex,
            DefectiveLines = defectiveLines
        };

        return resultLines;
    }
}
</code></pre>
<p>My unit testing class:</p>
<pre><code>[TestClass]
public class UnitTestOutputtingStrings
{
    [TestMethod]
    public void Should_FindingMaximumRowSum_TheFileIsValidAndReadable()
    {
        /* Arrange*/
        var maxsumlineresult = new MaxSumLineResult();
        var sut = new OutputtingStrings();

        /* Act*/

        /* Assert*/
    }
}
</code></pre>
<p>I have read the book &quot;The Art of Unit Testing. With Examples in C#&quot;. I understand the principles, but I do not know how to work with complex classes. Thank you guys in advance, I will be glad to every answer or link to a source with materials on unit testing.</p>
",https://stackoverflow.com/questions/66854304/unit-testing-of-complex-objects-c,"['c#', '.net', 'unit-testing']",323,False,-1,1
how to unit test on window object in angular,"<p>calling a function from ts file.</p>
<pre><code>this.userDataService.getUserInfo()
</code></pre>
<p>userDataService.ts</p>
<pre><code> getUserInfo() {
return this.windowService.nativeWindow.$abc?.abcProfile?.UserProfileClient.getUser();
</code></pre>
<p>}</p>
<p>now when I try to do unit testing getting error abcProfile undefined.</p>
<p>I have no clue how to mock window data also I'm new to unit testing and project itself.its a angular project integrated on AEM</p>
<p>Please help.TIA</p>
",https://stackoverflow.com/questions/68526218/how-to-unit-test-on-window-object-in-angular,"['angular', 'jasmine', 'karma-jasmine']",34,False,0,0
how create sql.mock in golang for insert query,"<p>I want to make a unit test 100% coverage but many commands or checks are missed in the unit testing, how do I fix it so that it can be 100% coverage</p>
<pre><code>func (db *Database) SaveBook(id string, url string, username string, email string, password string, data string) error {
    sqlStatement := &quot;INSERT INTO book (id, cerator,name_book) VALUES (?, ?, ?)&quot;
    stmt, err := db.DB.Prepare(sqlStatement)
    if err != nil {
        return err
    }

    result, errExec := stmt.Exec(id, url, username, email, password, data)
    if errExec != nil {
        return errExec
    }
    rows, err := result.RowsAffected()
    if err != nil {
        return err
    }
    if rows != 1 {
        return err
    }

    return nil
}
</code></pre>
<p>and for the unit testing example I use this. what's wrong with this</p>
<pre><code>func TestSavetWsSuccesss(t *testing.T) {
    db, mock := NewMock()
    repo := data.NewDatabase(db)
    query := &quot;INSERT INTO book (id, cerator,name_book) VALUES (?, ?, ?)&quot;
    prep := mock.ExpectPrepare(regexp.QuoteMeta(query))
    prep.ExpectExec().WithArgs(id,creator,name).WillReturnError(errors.New(&quot;sql error&quot;))
}
</code></pre>
",https://stackoverflow.com/questions/69297939/how-create-sql-mock-in-golang-for-insert-query,"['mysql', 'unit-testing', 'go', 'go-sqlmock']",1193,False,0,0
Unit test assignment of property inside ngOnInit after service gets data,"<p>When unit-testing in angular, how can I test that property in map.component.ts userRole = 'Admin'? Right now it fails on Expected undefined to equal 'Admin'. I try to mock service that gets the real data with testData. I am complete beginner in unit testing, please help. Thanks!</p>
<p>map.component.ts</p>
<pre><code>export class MapComponent implements OnInit, OnDestroy {
userRole:string
...
constructor(
    private zone: NgZone,
    public deskDialog: MatDialog,
    private userFloorService: UserFloorService,
    private _snackBar: MatSnackBar,
    private route: ActivatedRoute,
    private router: Router
  ) {}

async ngOnInit(): Promise&lt;void&gt; {
    const userData = await this.userFloorService.getUser().toPromise();
    this.userRole = userData.records[0].user_role; 
    ...
}
</code></pre>
<p>user-floor.service.ts</p>
<pre><code>export class UserFloorService {
public getUser(): Observable&lt;any&gt; {
    return this.http.get(
      `https://XXX`);
  }
}
</code></pre>
<p>map.component.spec.ts</p>
<pre><code>class UserService {
  testData = {
    message: 'Succes',
    records: [
      {
        floor_id: 3,
        reservations: [
          {
            desk_id: 11,
            reservation_date: '2021-02-22',
            reservation_id: 585,
            user_id: 7,
          },
        ],
        user_gid: 'xxx',
        user_id: 7,
        user_role: 'Admin',
      },
    ],
  };
  public getUser(): Observable&lt;any&gt; {
    return of(this.testData);
  }
}

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

  beforeEach(() =&gt; {
    userService = jasmine.createSpyObj(['getUser']);

    TestBed.configureTestingModule({
      declarations: [MapComponent],
      imports: [
        MatSnackBarModule,
        AppRoutingModule,
        HttpClientModule,
        BrowserModule,
        MatDialogModule,
        HttpClientTestingModule,
      ],
      providers: [{ provide: UserFloorService, useClass: UserService }],
    }).compileComponents();
    fixture = TestBed.createComponent(MapComponent);
    component = fixture.componentInstance;
    userService = TestBed.inject(UserFloorService);
    fixture.detectChanges();
  });

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

  describe('Given the component is loaded', () =&gt; {
    describe('When getUser returns mock data', () =&gt; {
      it('Then the userRole should be Admin', (done) =&gt; {
        userService.getUser().subscribe(() =&gt; {
          expect(component.userRole).toEqual('Admin');
          done();
        });
      });
    });
  });
});
</code></pre>
",https://stackoverflow.com/questions/66662754/unit-test-assignment-of-property-inside-ngoninit-after-service-gets-data,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",3454,True,2,2
Testing BLE(Bluetooth Low Energy) in xamarin forms,"<p>How can I do <strong>unit testing</strong> for <strong>BLE(Bluetooth Low Energy)</strong> in xamarin forms. I am testing methods which implements the <strong>BLE Gatt operation</strong> using <strong>Nunit</strong> . I am able to do <strong>unit testing</strong> for the <strong>viewmodel</strong>. But how will I test the <strong>singleton classes</strong> where the <strong>BLE gatt operation</strong> is going on. This is the <strong>Data transfer</strong> class which acts as intermediate.</p>
<pre><code>public class DataTransfer:IManager
{
  
    public ICharacteristic _characteristicsBLE;
    private static readonly object padlock = new object(); //Using Padloc to make code thread safe
    private static DataTransfer instance = null;
    public string _result;
    public IDevice _deviceBLE; //Contains information of BLE device
    private DataTransfer()
    {
    }

    //Instance of Singeleton class
    public static DataTransfer   Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new DataTransfer();
                    }
                }
            }
            return instance;
        }
    }
    public async Task connect(ScanData scanData, CancellationTokenSource token)
    {
        try
        {
            await BleManager.Instance.BleState(scanData, token);
           // await getCharacteristics(scanData, token);
        }
        catch(Exception ex)
        {
            await UserDialogs.Instance.AlertAsync(&quot;The data is incomplete scan again. Datatransfer&quot;);
        }
      
    }
    public async Task getCharacteristics(ScanData scanData, CancellationTokenSource token)
    {
        try
        {
            await BleManager.Instance.GetCharacteristics(scanData);
        }
        catch (Exception ex)
        {
            await UserDialogs.Instance.AlertAsync(&quot;The data is incomplete scan again. Datatransfer&quot;);
        }
    }     
}
</code></pre>
<p>This is the <strong>BLE manager class</strong> which has <strong>BLE gatt operations</strong>.</p>
<pre><code>public class BleManager 
{
    
    private IBluetoothLE _bluetoothLe; 
    public IBluetoothService _bleState; //Reference for BluetoothService which has execution for turning ON bluetooth using Dependency service
    public IDevice _device; //Contains information of BLE device
    public IAdapter _adapter;
    public static readonly Guid SERVICE_ID =  Guid.Parse(&quot;00001805-0000-1000-8000-00805f9b34fb&quot;);  //Sevice ID of BLE GATT
    public static readonly Guid CHARACTERISTIC_ID_WRITE = Guid.Parse(&quot;00002B0F-0000-1000-8000-00805f9b34fb&quot;);  //Characteristic ID of BLE GATT Write
 
    public static readonly Guid CHARACTERISTIC_ID_READ = Guid.Parse(&quot;00002a2b-0000-1000-8000-00805f9b34fb&quot;);
 
    public string concat { get; set; }
    public string BLEresultnew { get; set; }
    public ICharacteristic _characteristicsBLE;
    public NativeDevice NativeDeviceAdd { get; private set; } //Class which contain name and address of BLE
    public string BleDeviceName { get; private set; }
    private const string SERVICE_NAME = &quot;Current Time Service&quot;; //Service Name of BLE GATT
    private static readonly object padlock = new object(); //Using Padloc to make code thread safe
    private static BleManager instance = null;

    private BleManager()
    {
    }

    //Instance of Singeleton class
    public static BleManager Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new BleManager();
                    }
                }
            }
            return instance;
        }
    }
   
   
    //Check if Bluetooth is ON or OFF. If Bluetooth is switched OFF in android then switch it ON.
    public async Task BleState(ScanData scanData, CancellationTokenSource token)
    {
            _bluetoothLe = CrossBluetoothLE.Current;
            if (_bluetoothLe.State == BluetoothState.Off)
            {
                if (Device.RuntimePlatform == Device.iOS)
                {
                await UserDialogs.Instance.AlertAsync(&quot;Switch On bluetooth&quot;);
                   
                }
                else
                {
                    _bleState = DependencyService.Get&lt;IBluetoothService&gt;();
                    _bleState.OpenBluetooth();
                    await ScanForDevices(scanData);
                }
            }
            else
            {
                await ScanForDevices(scanData);
            }
       
    }

    //Scan for BLE devices
    private async Task ScanForDevices(ScanData scanData, ConnectParameters connectParameters = default, CancellationToken token = default)
    {
        try
        {
            _device = null;
            _adapter = CrossBluetoothLE.Current.Adapter;
            _adapter.ScanMode = ScanMode.LowLatency;
            _adapter.ScanTimeout = 5000;
            Device.BeginInvokeOnMainThread(async () =&gt;
            {
                _adapter.DeviceDiscovered += async (s, a) =&gt;
            {
                NativeDeviceAdd = DependencyService.Get&lt;INativeDevice&gt;().ConvertToNative(a.Device);
                PropertyInfo propInfo = NativeDeviceAdd.GetType().GetProperty(&quot;Name&quot;);
                BleDeviceName = (string)propInfo.GetValue(NativeDeviceAdd, null);
         
            string substr = scanData.blename;
                if (BleDeviceName == substr)
                {

                    _device = a.Device;

                    await _adapter.StopScanningForDevicesAsync();
                    await ConnectForDevice(scanData);

                }

            };
            });
            await _adapter.StartScanningForDevicesAsync();
        }
        catch (DeviceConnectionException ex)
        {
          
            await UserDialogs.Instance.AlertAsync(&quot;Device got disconnected please scan again 1&quot;);
            return;

        }
        catch (Exception ex)
        {
            await UserDialogs.Instance.AlertAsync(&quot;Device got disconnected please scan again.The CancellationTokenSource has been disposed&quot;);
            return;
        }
    }


    //If the device is selected the connection is done here
    private async Task ConnectForDevice(ScanData scanData, ConnectParameters connectParameters = default, CancellationToken token = default)
    {
      
       
        try
        {
           
            _adapter.DeviceConnectionLost += async (s, a) =&gt;
            {
                
                Device.BeginInvokeOnMainThread(async () =&gt;
                {
                    Console.WriteLine(&quot;Device ConnectionLost : &quot; + a.ErrorMessage);
                    await UserDialogs.Instance.AlertAsync(&quot;Device ConnectionLost :&quot;+a.ErrorMessage);
                    var parameters2 = new ConnectParameters(forceBleTransport: true, autoConnect: true);
                    await _adapter.ConnectToDeviceAsync(_device, parameters2);
                    await GetCharacteristics(scanData);
                });

            };

            _adapter.DeviceDisconnected += async (s, a) =&gt;
             {
                 Console.WriteLine(&quot;Device Disconnected : &quot;);
                 await UserDialogs.Instance.AlertAsync(&quot;Device Disconnected :&quot;);
             };

            var parameters = new ConnectParameters(forceBleTransport: true,autoConnect:true);


            await _adapter.ConnectToDeviceAsync(_device, parameters);
            await GetCharacteristics(scanData);
        }
        catch (DeviceConnectionException ex)
        {
          
            Console.WriteLine(&quot;Exception while connecting and registering callbacks &quot; + ex.Message);
            await UserDialogs.Instance.AlertAsync(&quot;Device got disconnected please scan again 2&quot; + ex.Message);
         
        }
     

     }
    public async void disconnected()
    {
        await Application.Current.MainPage.Navigation.PopAsync();
        return;
        
    }

 
    public async Task GetCharacteristics(ScanData scanData, ConnectParameters connectParameters = default, CancellationToken token = default)
    {
        try
        {
        concat = null;
       
            var service = await _device.GetServiceAsync(SERVICE_ID);
            
       
            var characteristicRead = await service.GetCharacteristicAsync(CHARACTERISTIC_ID_READ);
            await ReadConfigData(characteristicRead);
      
            }
        catch (DeviceConnectionException ex)
        {

            await UserDialogs.Instance.AlertAsync(&quot;Device got disconnected please scan again 3&quot;);
         
        }
        catch (TaskCanceledException tce)
        {
            Console.WriteLine(&quot;Scan was cancelled&quot;);
        }
      

    }
    private async void OnDeviceDisconnected(object sender, DeviceEventArgs e) //Is OK to use async void here
    {
     
        await UserDialogs.Instance.AlertAsync(&quot;Device got disconnected  after scan&quot;);
     
    }
    private async void OnDeviceconnected(object sender, DeviceEventArgs e) //Is OK to use async void here
    {
        
            await UserDialogs.Instance.AlertAsync(&quot;Device got disconnected please scan again event&quot;);
    }
    public async  Task  WriteDataAsync(String data)
    {
        if (_characteristicsBLE != null)
        {
            try
            {

            
                byte[] senddata = Encoding.UTF8.GetBytes(data);
                int start = 0;
                while (start &lt; senddata.Length)
                {
                    
                    int chunkLength = Math.Min(20, senddata.Length - start);
                    byte[] chunk = new byte[chunkLength];
                    Array.Copy(senddata, start, chunk, 0, chunkLength);
                    Device.BeginInvokeOnMainThread(async () =&gt;
                   {
                   
                    await _characteristicsBLE.WriteAsync(chunk);
                    });
                    start += 20;
                    
                }

               
            }
            catch (Exception ex)
            {
                 
                Console.WriteLine(ex);
            }
        }


    }

    public async Task ReadConfigData(ICharacteristic characteristics)
    {
        if (characteristics != null)
        {
            try
            {
                await _adapter.ConnectToDeviceAsync(_device);
               
                    characteristics.ValueUpdated += (o, e) =&gt;
                {
                      Device.BeginInvokeOnMainThread(async () =&gt;
                     {
                 
                    var bytes = e.Characteristic.Value;
                 
                    BLEresultnew = System.Text.Encoding.UTF8.GetString(bytes);

                    Console.WriteLine(BLEresultnew);
                   
                    concat += BLEresultnew;
                  
                     });
                };
                
                    await characteristics.StartUpdatesAsync();
          
            }

            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            
        }

    }
}
</code></pre>
<p>I have no clue how can I test these singeleton classes. Is there any other tests which I have to perform for BLE other than Unit testing  in xamarin forms?</p>
",https://stackoverflow.com/questions/65830039/testing-blebluetooth-low-energy-in-xamarin-forms,"['c#', 'unit-testing', 'bluetooth-lowenergy', 'nunit']",437,False,2,0
Is there a way to unit test data under moor sqlite db which is in application directory?,"<p>Im trying to perform unit testing on moor sqlite db but unable to do it because it tries to fetch the db from path provider(file path) which fails in unit testing file. Mock framework is not working in this case. Is there any workaround to get path containing db?</p>
",https://stackoverflow.com/questions/67803508/is-there-a-way-to-unit-test-data-under-moor-sqlite-db-which-is-in-application-di,"['flutter', 'sqlite', 'unit-testing', 'dart', 'flutter-moor']",405,False,0,0
Should initialisation of class-level variable with by lazy in Kotlin be avoided because it prevents Unit Testing?,"<p>Having a class-level variable and instantiating the object at the same time creates a problem for Unit Testing because you can't really mock the dependency.</p>
<p>Does this mean the Kotlin feature <code>by lazy</code> should be avoided as it hinders proper unit testing, or is there a way to overcome this? Thanks.</p>
",https://stackoverflow.com/questions/69333796/should-initialisation-of-class-level-variable-with-by-lazy-in-kotlin-be-avoided,['kotlin'],409,False,-1,1
Pyqt unit testing,"<p>I have written small desktop app which save, quit and pop up window. I would like to write unit test for them I have gone through Qt unit testing but Qt unit testing has very costly unit test framework. is it possible to any opensource along with example to test functionality.</p>
",https://stackoverflow.com/questions/69554290/pyqt-unit-testing,['pyqt5'],18,False,0,0
TypeError: r.node.getBBox is not a function&quot;.] { code: &#39;ERR_UNHANDLED_REJECTION&#39; },"<p>I am using <code>jest</code> and <code>testing-library/react</code> to write unit testing. Before this, I have never written any unit testing. After writing the test I am getting an error something like this.</p>
<pre><code> FAIL  src/__test__/components/Barchart.test.tsx
  ● Test suite failed to run

    Call retries were exceeded

      at ChildProcessWorker.initialize (node_modules/jest-worker/build/workers/ChildProcessWorker.js:193:21)

node:internal/process/promises:245
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason &quot;TypeError: r.node.getBBox is not a function&quot;.] {
  code: 'ERR_UNHANDLED_REJECTION'
}
node:internal/process/promises:245
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason &quot;TypeError: r.node.getBBox is not a function&quot;.] {
  code: 'ERR_UNHANDLED_REJECTION'
}
node:internal/process/promises:245
          triggerUncaughtException(err, true /* fromPromise */);
          ^

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason &quot;TypeError: r.node.getBBox is not a function&quot;.] {
  code: 'ERR_UNHANDLED_REJECTION'
}
</code></pre>
<p>I have no idea why I am getting this. This is the component I am trying to test.</p>
<pre><code>import { useState } from &quot;react&quot;;
import Chart from &quot;react-apexcharts&quot;;

const ChartComponent = (props: any) =&gt; {
  const [series, setSeries] = useState([
    {
      name: &quot;Net Profit&quot;,
      data: [44, 55, 57, 56, 61, 58, 63, 60, 66],
    },
    {
      name: &quot;Revenue&quot;,
      data: [76, 85, 101, 98, 87, 105, 91, 114, 94],
    },
  ]);
  const [optionsRadial, setOptionRadial] = useState({
    chart: {
      type: &quot;bar&quot;,
      height: 350,
    },
    plotOptions: {
      bar: {
        horizontal: false,
        columnWidth: &quot;55%&quot;,
        borderRadius: 4,
        radius: 10,
      },
    },
    dataLabels: {
      enabled: false,
    },
    stroke: {
      show: true,
      width: 2,
      colors: [&quot;transparent&quot;],
    },
    xaxis: {
      categories: [
        &quot;Feb&quot;,
        &quot;Mar&quot;,
        &quot;Apr&quot;,
        &quot;May&quot;,
        &quot;Jun&quot;,
        &quot;Jul&quot;,
        &quot;Aug&quot;,
        &quot;Sep&quot;,
        &quot;Oct&quot;,
      ],
    },
    yaxis: {
      title: {
        text: &quot;$ (thousands)&quot;,
      },
    },
    fill: {
      opacity: 1,
    },
    tooltip: {
      y: {
        formatter: function (val: any) {
          return &quot;$ &quot; + val + &quot; thousands&quot;;
        },
      },
    },
  });
  return (
    &lt;Chart data-testid=&quot;chart&quot;  options={optionsRadial} series={series} type=&quot;bar&quot; height=&quot;186&quot; /&gt;
  );
};

export default ChartComponent;

</code></pre>
<blockquote>
<p>Barchart.test.tsx</p>
</blockquote>
<pre><code>import React from &quot;react&quot;;
import ApexCharts from &quot;apexcharts&quot;;
import ReactApexChart from &quot;react-apexcharts&quot;;
import { render, screen } from &quot;@testing-library/react&quot;;
import ChartComponent from &quot;../../components/BarChart/index&quot;;


describe(&quot;&lt;ChartComponent/&gt;&quot;, () =&gt; {
  jest.mock(&quot;react-apexcharts&quot;, () =&gt;
    jest.fn(() =&gt; {
      return null;
    })
  );
  jest.mock(&quot;apexcharts&quot;, () =&gt; ({
    exec: jest.fn(() =&gt; {
      return new Promise((resolve, reject) =&gt; {
        resolve(&quot;uri&quot;);
      });
    }),
  }));

  it(&quot;ChartComponent render without crashing&quot;, async() =&gt; {
    const { container } = render(&lt;ChartComponent /&gt;);
   
    const chart = container.querySelector('#chart');
    expect(chart).toBeInTheDocument();
   
  
  });

  it('ChartComponent Debug', () =&gt; {
    render(&lt;ChartComponent /&gt;);
    screen.debug();
  })
});

</code></pre>
<p>Any help would be great.</p>
",https://stackoverflow.com/questions/67209367/typeerror-r-node-getbbox-is-not-a-function-code-err-unhandled-rejection,"['javascript', 'reactjs', 'jestjs', 'react-testing-library', 'apexcharts']",1451,True,1,1
How to write mocks for Google Sign In Async await Callbacks with jest enzyme and perform Unit Testing in react-native?,"<p>I have a class GoogleSign.js</p>
<pre><code>import {GoogleSignin, statusCodes} from '@react-native-community/google-signin';
import React, {useEffect} from 'react';
import {Text, View, TouchableOpacity, Image, Alert} from 'react-native';
import {RFValue} from 'react-native-responsive-fontsize';
 
import ColorConstants from '../../constants/ColorConstants';
import ImageConstants from '../../constants/ImageConstants';
import {Fonts} from '../../constants/Constants';
import {verticalScale} from '../../helpers/Functions';
import {WEB_CLIENT_ID} from '../../utils/keys.js';
 
const GoogleMainButton = ({text, onPress, parentCallback}) =&gt; {
  const googleLoginStyle = {
    backgroundColor: ColorConstants.white,
    borderRadius: 8,
    marginBottom: 8,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    height: verticalScale(40),
  };
 
  const textGoogleStyle = {
    color: ColorConstants.black,
    fontSize: RFValue(16),
    textAlign: 'center',
    fontFamily: Fonts.InterSemibold,
    paddingVertical: 10,
  };
 
  const _isSignedIn = async (userInfo, errorCallBack) =&gt; {
    await GoogleSignin.isSignedIn().then((isSignedIn) =&gt; {
      if (isSignedIn) {
        // Alert.alert('User is already signed in');
        getCurrentUserInfo(
          (result) =&gt; {
            userInfo(result);
          },
          (error) =&gt; {
            errorCallBack(error);
          },
        );
      } else {
        //Alert.alert('Please Login');
        signIn(
          (result) =&gt; {
            userInfo(result);
          },
          (error) =&gt; {
            errorCallBack(error);
          },
        );
      }
    });
  };
 
  const getCurrentUserInfo = async (result, errorCallBack) =&gt; {
    try {
      await GoogleSignin.signInSilently().then((res) =&gt; {
        result(res.user);
      });
    } catch (error) {
      errorCallBack(error);
      if (error.code === statusCodes.SIGN_IN_REQUIRED) {
        // when user hasn't signed in yet
      } else {
        Alert.alert('Something else went wrong... ', error.toString());
        // this.setState({isLoggedIn: false});
      }
    }
  };
 
  const signIn = async (userInfoCallBack, errorCallBack) =&gt; {
    try {
      await GoogleSignin.hasPlayServices().then(async (res) =&gt; {
        if (res) {
          await GoogleSignin.signIn().then((result) =&gt; {
            userInfoCallBack(result.user);
          });
        }
      });
    } catch (error) {
      errorCallBack(error);
      if (error.code === statusCodes.SIGN_IN_CANCELLED) {
        // when user cancels sign in process,
        Alert.alert('Process Cancelled');
      } else if (error.code === statusCodes.IN_PROGRESS) {
        // when in progress already
        Alert.alert('Process in progress');
      } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
        // when play services not available
        Alert.alert('Play services are not available');
      } else {
        // some other error
        Alert.alert('Something else went wrong... ', error.code.toString());
      }
    }
  };
 
  const googleLoginButton = (props) =&gt; {
    useEffect(() =&gt; {
      GoogleSignin.configure({
        webClientId: WEB_CLIENT_ID,
        offlineAccess: false,
      });
    }, []);
    return (
      &lt;TouchableOpacity
        onPress={() =&gt; {
          _isSignedIn(
            (res) =&gt; {
              parentCallback({response: res});
            },
            (error) =&gt; {
              console.log(error);
            },
          );
        }}&gt;
        &lt;View style={googleLoginStyle}&gt;
          &lt;Image source={ImageConstants.googleLogo} /&gt;
          &lt;Text style={[textGoogleStyle]}&gt; {props.text} &lt;/Text&gt;
        &lt;/View&gt;
      &lt;/TouchableOpacity&gt;
    );
  };
 
  return googleLoginButton({text, onPress, parentCallback});
};
 
export default GoogleMainButton;
</code></pre>
<p>Also I have I mock class <strong>google-signin.ts</strong> inside <strong>@react-native-community</strong> folder which is inside <strong><strong>mocks</strong></strong> folder</p>
<pre><code>it('mock google login', () =&gt; {
  jest.mock('@react-native-community/google-signin', () =&gt; {});
});
</code></pre>
<p>And I have a class <strong>GoogleSignIn.test.js</strong>
In this class I have used the code to match the snapshot and
have simulated the button click.</p>
<pre><code>import 'react-native';
import React from 'react';
import GoogleSignin from '../src/components/utilities/PrimaryGoogleSignIn';

import {shallow, render, mount} from 'enzyme';

it('renders correctly', () =&gt; {
  const mockFunc = jest.fn();
  const info = {};

  const wrapper = shallow(&lt;GoogleSignin parentCallback={mockFunc} /&gt;);
  wrapper.dive().simulate('press');
  expect(wrapper).toMatchSnapshot();
  //expect(mockFunc).toHaveBeenCalledTimes(1);
});
</code></pre>
<p>So the problem is here I am not able to complete it's unit testing to 100%
the percentage it is covering is near to 29.</p>
<p>I have written few lines of code for unit testing which I guess works till the simulation of onPress.
<br>
<strong>I am not able get the full coverage.</strong></p>
<p><a href=""https://i.stack.imgur.com/rrqft.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/rrqft.png"" alt=""enter image description here"" /></a>
<a href=""https://i.stack.imgur.com/iK5M5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/iK5M5.png"" alt=""enter image description here"" /></a>
<a href=""https://i.stack.imgur.com/MQ3Lr.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/MQ3Lr.png"" alt=""enter image description here"" /></a><a href=""https://i.stack.imgur.com/AjJRs.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/AjJRs.png"" alt=""enter image description here"" /></a></p>
<p>As I am new to Unit testing. Please I need help.</p>
",https://stackoverflow.com/questions/68378735/how-to-write-mocks-for-google-sign-in-async-await-callbacks-with-jest-enzyme-and,"['javascript', 'react-native', 'unit-testing']",838,False,3,0
How to do unit testing for session timeout in VB?,"<p>I am working on a VB project where I had to increase the session timeout of the page to 9 hours. I achieved it by adding <code>&lt;sessionState mode=&quot;InProc&quot; timeout=&quot;540&quot;&gt;&lt;/sessionState&gt;</code> in the <code>web.config</code> file</p>
<p>Now I have to write the unit testing for the same in VB. I have not written any unit test ever before. I know unit testing can be done on individual unit or group of interrelated units of the software. Is there a way to unit test session timeout? There is no login involved here.</p>
<p>Please give some reference. Some blog or existing question(s).
I am new to both VB and unit testing.</p>
",https://stackoverflow.com/questions/68621482/how-to-do-unit-testing-for-session-timeout-in-vb,"['vb.net', 'unit-testing', 'web-config', 'session-state', 'session-timeout']",146,False,0,0
Mocking functions inside a for loop in R,"<p>I'm using testthat package for unit testing in R. I have a function <strong>CalcByResultSubModel</strong> which has one more function <strong>CalculateX</strong> which is called  inside the main function. This is the main function,</p>
<pre><code>
CalcByResultSubModel = function(doll_data, fn_master, modelPath) {
  # load sub model result
  load(modelPath)
  
  # calculation
  for(abc in c(&quot;ABC&quot;, fn_master$fn_a)) {
    
    # columns
    col_name = paste0(&quot;x&quot;, abc)    
    iterModel = resultSubmodel[[abc]]
    
    # calculate yhat X
    doll_data[, col_name] = iterModel %&gt;% 
      purrr::map(., function(imodel) {
        CalculateX(data, imodel)
      }) %&gt;% 
      as.data.frame(.) %&gt;%
      apply(., 1, mean)
    
    message(paste(col_name, &quot;calculated&quot;))      
  }
</code></pre>
<p>This is the function <strong>CalculateX</strong></p>
<pre><code>CalculateX = function(data, model) {
  iterData = data %&gt;% 
    dplyr::select(model$feature_names) %&gt;% 
    as.matrix(.)
  set.seed(131)
  result = predict(model, iterData, missing = NA)
  result = matrix(result, 2)[2, ]
  
  return(result)
}
</code></pre>
<p>Inorder to perform unit testing we have to mock the function <em>CalculateX</em>. But the complexity here is that, the function is called inside for loop in the main function. I'm quite new to this scenario in my unit testing. Can anyone help me with the mocking of the function in a for loop? This is the code for mocking and I tried this.</p>
<pre><code>local_mock(CalculateX = function(data, model){
                  for (abc in c(&quot;ABC&quot;, fn_master$fn_a)
                  case_when(
                    abc == &quot;feature1&quot; ~ .ReadCsvWrapper(&quot;feature1.csv&quot;),
                    abc == &quot;feature2&quot; ~ .ReadCsvWrapper( &quot;feature2.csv&quot;),
                    abc == &quot;feature3&quot; ~ .ReadCsvWrapper(&quot;feature3.csv&quot;))
            })
But the above approach doesn't seem to work for me. Can anyone help me with this?
</code></pre>
",https://stackoverflow.com/questions/67971517/mocking-functions-inside-a-for-loop-in-r,"['r', 'loops', 'unit-testing', 'testthat']",76,False,-1,1
If statement not covered in Code Coverage in Jasmine,"<p>When I use Jasmine marbles for unit testing for if condition those specific blocks don't cover in code coverage report.</p>
<p>Is there a way to unit test if blocks so that they would be covered in code coverage report?</p>
<p>below is the code ts 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>onSubscribe(): void {
  this.menuData$.subscribe((menuValue): void =&gt; {
    this.menuList = MenuUtils.menuformt(menuValue, this.data);
    this.menuList &amp;&amp; this.menuList.map((element: MenuList) =&gt; {
      if (this.router.url.includes(element.url)) {
        element.active = true;
      } else {
        element.active = false;
      }
    })
  });
}</code></pre>
</div>
</div>
</p>
<p>Below is the unit testing code:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>const menuList: MenuList[] = [{
  menu_name: 'MENU_LIST.NEW_BOOKING',
  class: '',
  url: 'services',
  is_hosted: true,
  is_shown_login: true,
  showOnCondition: 'isHostedWithLogin',
  is_hide_login: true,
  hidden: false,
  displayOrder: 1,
  options: null,
  active: false,
}, ];

describe('onSubscribe', (): void =&gt; {
  it('should call onSubscribe', fakeAsync(() =&gt; {
    spyOn(component, 'onSubscribe').and.callThrough();
    fixture.detectChanges();
    component.onSubscribe();
    expect(component.onSubscribe).toHaveBeenCalled();
  }));

  const menu: MenuList = menuList[0];
  const menuListdata: MenuList[] = menuList;
  it('should includes url', fakeAsync(() =&gt; {
    const router = TestBed.get(Router);
    const mockUrlTree = router.parseUrl('/booking/_m/sites/56793/services');
    router.currentUrlTree = mockUrlTree;
    store.refreshState();
    fixture.detectChanges();
    component.onSubscribe();
    menuList.forEach((element) =&gt; {
      expect(router.url).toContain(element.url)
    });
  }));
  it('should active be true', fakeAsync(() =&gt; {
    const router = TestBed.get(Router);
    const mockUrlTree = router.parseUrl('/booking/_m/sites/56793/services');
    router.currentUrlTree = mockUrlTree;
    store.refreshState();
    fixture.detectChanges();
    component.onSubscribe();
    menuList.forEach((element) =&gt; {
      if (expect(router.url).toContain(element.url)) {
        expect(element.active).toBe(true);
      }
    });
  }));
  it('should active be true', fakeAsync(() =&gt; {
    const router = TestBed.get(Router);
    const mockUrlTree = router.parseUrl('/booking/_m/sites/56793/login');
    router.currentUrlTree = mockUrlTree;
    store.refreshState();
    fixture.detectChanges();
    component.onSubscribe();
    menuList.forEach((element) =&gt; {
      if (expect(router.url).not.toContain(element.url)) {
        expect(element.active).toBe(false);
      }
    })
  }));
});</code></pre>
</div>
</div>
</p>
<p>Not sure whether the coding style for unit testing is correct or not let me know if needed any improvement.</p>
<p>from above ts file from if block code is not covered not sure where i am going</p>
<p>this is case i am trying to write it
Thanks.</p>
",https://stackoverflow.com/questions/66228795/if-statement-not-covered-in-code-coverage-in-jasmine,"['angular', 'jasmine']",943,False,0,0
How to unit test window.location.reload in angular 12 unit testing?,"<p>In my angular project, I have a function</p>
<pre><code>reloadPage(): void {
  window.location.reload();
}
</code></pre>
<p>So when ever I need to reload the page, I used to call this function.</p>
<p>Now I am trying to add the unit testing for this function but it is not working.</p>
<pre><code>it(&quot;reloadPage: should be validated&quot;, () =&gt; {
    spyOn(window.location, 'reload').and.callFake(() =&gt; {
      //test
    });
    component.reloadPage();
});
</code></pre>
<p>It still reloads the page on unit testing</p>
<p>How can I achieve a unit test for this function? Any help could be appreciated. Thanks in advance</p>
",https://stackoverflow.com/questions/68607971/how-to-unit-test-window-location-reload-in-angular-12-unit-testing,"['angular', 'unit-testing', 'angular-unit-test', 'angular12']",7365,True,6,4
Get return value of invoked method in UnitTest using Moq,"<p>I'm using Moq to do unit testing. In the method I'm trying to unit test I'm trying to ensure that it doesn't throw an exception but I'd also like to get the return value of the method I'm unit testing to verify the result.</p>
<pre><code>_myService.Invoking(x =&gt; x.TestMethod(request)).Should().NotThrow();
</code></pre>
<p>The above works. The test passes. However, I'd like to get the return value of <code>TestMethod</code>.</p>
",https://stackoverflow.com/questions/66663311/get-return-value-of-invoked-method-in-unittest-using-moq,"['c#', 'unit-testing', 'moq', 'xunit']",504,True,2,2
How to pass an object as parameter in unit test? (laravel),"<p>I have a data object below that I tried to test using postman. I just don't know how to make this possible also in laravel's unit testing. I have visited this <a href=""https://stackoverflow.com/questions/18242578/how-to-pass-json-to-route-from-unit-test"">link</a> but it doesn't helped in my case.</p>
<pre><code>{
    &quot;user_id&quot;: 1,
    &quot;name&quot;: &quot;juan&quot;,
    &quot;address&quot;: [
        &quot;state&quot;: &quot;Auckland&quot;,
        &quot;country&quot;: &quot;New Zealand&quot;,
    ],
    &quot;school&quot;: [
        {
            &quot;school_name&quot;: &quot;Kristin School&quot;,
            &quot;year&quot;: 2016
        },
        {
            &quot;school_name&quot;: &quot;ACG Parnell College&quot;,
            &quot;year&quot;: 2018
        },
    ],
    // and more...
}
</code></pre>
<p>How can we pass such an object above in unit testing? Is there any way to achieve this?</p>
<pre><code>$response = $this-&gt;post('/logbooks/user', ['Authorization': 'Bearer' + $token]);
</code></pre>
",https://stackoverflow.com/questions/66303690/how-to-pass-an-object-as-parameter-in-unit-test-laravel,"['php', 'laravel', 'unit-testing', 'laravel-unit-test']",931,True,0,2
How do unit testing on whether data is available oninit from activatedRoute,"<p>Am new to unit testing in angular . We are using jest and don't really know how to make to test whether the route is returning data or not . Am wondering can we do unit testing to check if data is return from the route in angular. Any help much appreciated</p>
<p>In my class component.ts</p>
<pre><code>public data$: Observable&lt;Data&gt;;
  public salariesPerHours: salariesPerHoursViewModel[];

  private destroy$ = new Subject&lt;boolean&gt;();

  constructor(private activatedRoute: ActivatedRoute) {}

  public ngOnInit(): void {

    this.data$ = this.activatedRoute.data;
    this.data$?.pipe(takeUntil(this.destroy$)).subscribe((data: Data) =&gt; {
      this.salariesPerHours= data?.Salary?.salaryPerHour;
    });
  }
</code></pre>
<p>In test class compontent</p>
<pre><code>import { ActivatedRoute, Data } from '@angular/router';
import { salariesPerHoursViewModel,SalaryType } from 'lib/store/store.barrel';
import { Subject } from 'rxjs';

import { SalaryComponent } from './salary.component';

const dataMock: salariesPerHoursViewModel[] = [
  {
      year:2018,
      salaryModifications:[
         {
            date:'2018-02-01T00:00:00',
            type: 'Salary',
            action:[
               {
                  logical :'0212834',
                  label:''
               }
            ]
         },
        ]
  }
]


describe('SalaryComponent', () =&gt; {
  let component: SalaryComponent;
  let activatedRoute: ActivatedRoute;

  beforeEach(() =&gt; {
    activatedRoute = new ActivatedRoute();
    component = new SalaryComponent(activatedRoute);
  });

  describe('ngOnInit', () =&gt; {
    beforeEach(() =&gt; {
      jest.spyOn(component, 'ngOnInit');
    });
   //how to  test if data is coming up
   
  });

  describe('ngOnDestroy', () =&gt; {
    test('should complete the destroy observable', () =&gt; {
      component['destroy$'].next = jest.fn();
      component['destroy$'].complete = jest.fn();

      component.ngOnDestroy();

      expect(component['destroy$'].next).toHaveBeenCalledWith(true);
      expect(component['destroy$'].complete).toHaveBeenCalled();
    });
  });
});

</code></pre>
",https://stackoverflow.com/questions/66763748/how-do-unit-testing-on-whether-data-is-available-oninit-from-activatedroute,"['angular', 'typescript', 'unit-testing', 'rxjs', 'jestjs']",541,False,0,1
How to perform integration testing in Netty 4,"<p>In <a href=""https://www.manning.com/books/netty-in-action"" rel=""nofollow noreferrer"">Netty in Action</a>, I read about <a href=""https://netty.io/4.1/api/io/netty/channel/embedded/EmbeddedChannel.html"" rel=""nofollow noreferrer"">EmbeddedChannel</a> which can be used for unit testing.</p>
<p>My use case now goes beyond unit testing, and more of integration testing. I want to be able to start the server and then, and within the test, configure/modify the channel handlers.</p>
<p>How is such an integration test setup possible in Netty 4?</p>
",https://stackoverflow.com/questions/66159539/how-to-perform-integration-testing-in-netty-4,"['netty', 'netty4']",151,False,0,1
Angular SpyOn Service with Another Parameter,"<p>How do I Spy on and Mock a Service with another service Parameter?
Example, My New Authservice has this parameter,</p>
<pre><code>export class AuthService{
    constructor(public serviceAbcd: ServiceAbcd) {}
</code></pre>
<p>This is an example resource, Without a constructor parameter on AuthService.</p>
<p><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></p>
<pre><code>describe('Component: Login', () =&gt; {

  let component: LoginComponent;
  let service: AuthService;
  let spy: any;

  beforeEach(() =&gt; {
    service = new AuthService();
    component = new LoginComponent(service);
  });
    
  it('needsLogin returns true when the user has not been authenticated', () =&gt; {
    spy = spyOn(service, 'isAuthenticated').and.returnValue(false);
    expect(component.needsLogin()).toBeTruthy();
    expect(service.isAuthenticated).toHaveBeenCalled(); 
  });

  afterEach(() =&gt; { 
    service = null;
    component = null;
  });

});
</code></pre>
<p>We are trying to test without Testbed <a href=""https://dev.to/angular/unit-testing-in-angular-to-testbed-or-not-to-testbed-3g3b"" rel=""nofollow noreferrer"">https://dev.to/angular/unit-testing-in-angular-to-testbed-or-not-to-testbed-3g3b</a></p>
",https://stackoverflow.com/questions/67829672/angular-spyon-service-with-another-parameter,"['angular', 'typescript', 'karma-jasmine', 'angular11']",1247,True,1,2
How to test Retry attempts in python using the request library,"<p>I have the following:</p>
<pre><code>from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

retry_strategy = Retry(
    total=3,
    status_forcelist=[429, 500, 502, 503, 504],
    method_whitelist=[&quot;HEAD&quot;, &quot;GET&quot;, &quot;OPTIONS&quot;]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
http = requests.Session()
http.mount(&quot;https://&quot;, adapter)
http.mount(&quot;http://&quot;, adapter)

response = http.get(&quot;some_endpoint&quot;)
</code></pre>
<p>How can unit testing that effectively I'm retrying N times (in this case, 3)?</p>
",https://stackoverflow.com/questions/66497627/how-to-test-retry-attempts-in-python-using-the-request-library,"['python', 'python-unittest', 'retry-logic']",1227,True,5,1
No ParameterResolver registered for parameter XXXX in constructor Junit5 java,"<p>Trying to perform simple JUnit 5 testing as below</p>
<pre><code>@Singleton
        record Repository(MongoClient mongoClient, MongodbConfiguration mongodbConfiguration) implements IRepository {
    @Override
    public &lt;T&gt; MongoCollection&lt;T&gt; getCollection(String collectionName, Class&lt;T&gt; typeParameterClass) {
        return mongoClient
                .getDatabase(mongodbConfiguration.database())
                .getCollection(collectionName, typeParameterClass);
    }
}
</code></pre>
<p><strong>Interface</strong></p>
<pre><code>public interface IRepository {
    &lt;T&gt; MongoCollection&lt;T&gt; getCollection(String collectionName, Class&lt;T&gt; typeParameterClass);
}
</code></pre>
<p><strong>Unit testing</strong></p>
<pre><code>public record RepositoryTest(IRepository iRepository) {

    @Test
    @DisplayName(&quot;Should return product collection&quot;)
    void shouldReturnProductCollection() {
        Assertions.assertTrue(true);
    }
}
</code></pre>
<p><strong>Exception</strong></p>
<pre><code>No ParameterResolver registered for parameter [fete.bird.repository.IRepository iRepository] in constructor [public fete.bird.RepositoryTest(fete.bird.repository.IRepository)].
org.junit.jupiter.api.extension.ParameterResolutionException: No ParameterResolver registered for parameter [fete.bird.repository.IRepository iRepository] in constructor [public fete.bird.RepositoryTest(fete.bird.repository.IRepository)].
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameter(ExecutableInvoker.java:200)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.resolveParameters(ExecutableInvoker.java:183)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:74)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestClassConstructor(ClassBasedTestDescriptor.java:342)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateTestClass(ClassBasedTestDescriptor.java:289)
    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.instantiateTestClass(ClassTestDescriptor.java:79)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:267)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:259)
    at java.base/java.util.Optional.orElseGet(Optional.java:364)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:258)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:101)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:100)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:79)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at jdk.proxy1/jdk.proxy1.$Proxy2.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:135)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:831)
</code></pre>
<p><strong>Gradle configuration</strong></p>
<pre><code>plugins {
    id 'java'
}

group 'fete.bird'
version '0.1'

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'
    implementation(&quot;fete.bird:common:1.0-SNAPSHOT&quot;)
    implementation 'io.micronaut.mongodb:micronaut-mongo-reactive:3.1.0'

    implementation(&quot;javax.annotation:javax.annotation-api:1.3.2&quot;)
    implementation &quot;io.micronaut:micronaut-inject:2.5.4&quot;
    annotationProcessor &quot;io.micronaut:micronaut-inject-java:2.5.4&quot;
    annotationProcessor &quot;io.micronaut:micronaut-validation:2.5.4&quot;

    testImplementation project(':domain')
}

test {
    useJUnitPlatform()
    jvmArgs(['--enable-preview'])
}
</code></pre>
",https://stackoverflow.com/questions/67645739/no-parameterresolver-registered-for-parameter-xxxx-in-constructor-junit5-java,"['java', 'gradle', 'junit', 'junit5']",510,False,1,1
How to mock the dependency injection object in unit test,"<p>My project requires unit testing. I am using constructor dependency injection in my controller. When I mock the injected dependency object in my unit testing project and call it in a test method. Returns null in all cases.</p>
<p>Controller Class:</p>
<pre><code>public class Owner:Controller
{
    private readonly IComRepository repository;
    private readonly DbContext context;
    
    public Owner(IComRepository repository, DbContext context)
    {
      this.repository=repository;
      this.context=context;
    }

    [HttpGet(&quot;GetAllTypes&quot;)]
    public async Task&lt;IActionResult&gt; GetAllTypes()
    {
      var ownerTypes=repository.GetTypes();
        return Ok(ownerTypes);
    }
}
</code></pre>
<p>My Repository Class</p>
<pre><code>public Interface IComRepository
{
    IList&lt;Type&gt; GetTypes();
}
        
public Class ComRepository : IComRepository
{
    private readonly DbContext context;
    public ComRepository(DbContext context)
    {
        this.context=context;
    }
    public IList&lt;Type&gt; GetTypes()
    {
        var allTypes= context.Types.ToList();
        return allTypes;
    }
}
</code></pre>
<p>Now I need to test the GetAllTypes methods in my controller class. My Test Class is below mentioned:</p>
<pre><code>using moq;
[TestClass]
public Class OwnerTest
{
    public OwnerTest()
    {
        var mockIcomrepo = new Mock&lt;IComRepository&gt;();
        var mockDbcontext = new Mock&lt;Dbcontext&gt;();
        OwnerController owner = new OwnerController(mockDbContext.Object, mockIcomrepo.Object);
    
    }
    [TestMethod]
    public void GetTypes()
    {
        var allTypes= owner.GetAllTypes(); //It's not trigger to my controller
        Assert.AreEqual(5,allTypes.count());
    }
}
</code></pre>
<p>How can I do it? Any one know the answer for this question.</p>
",https://stackoverflow.com/questions/68275461/how-to-mock-the-dependency-injection-object-in-unit-test,"['c#', 'unit-testing', 'mocking', 'moq']",12568,True,3,1
Vue test utils with Vue-router4 and Vue3 Composition API,"<p>I am unable to mount a component during unit testing due to the the route object being undefined in the setup method during mounting. The guides seem aimed at Vue2 and the options API</p>
<p><em><strong>References</strong></em>:
<br/>
<br/>
<a href=""https://stackoverflow.com/questions/41458736/how-to-write-test-that-mocks-the-route-object-in-vue"">How to write test that mocks the $route object in vue components</a>
<br/>
<a href=""https://stackoverflow.com/questions/60377091/how-to-unit-testing-with-jest-in-vue-composition-api-component"">How to unit testing with jest in vue composition api component?</a>
<br/>
<a href=""https://vue-test-utils.vuejs.org/guides/#using-with-typescript"" rel=""nofollow noreferrer"">https://vue-test-utils.vuejs.org/guides/#using-with-typescript</a>
<br/>
<a href=""https://vue-test-utils.vuejs.org/guides/#using-with-vue-router"" rel=""nofollow noreferrer"">https://vue-test-utils.vuejs.org/guides/#using-with-vue-router</a></p>
<p><em><strong>Error</strong></em></p>
<pre><code>● CoachItem.vue › displays alert when item is clicked

    TypeError: Cannot read property 'path' of undefined

      64 |       fullName: computed(() =&gt; props.firstName + &quot; &quot; + props.lastName),
      65 |       coachContactLink: computed(
    &gt; 66 |         () =&gt; route.path + &quot;/&quot; + props.id + &quot;/contact&quot;

</code></pre>
<pre><code>// @/tests/unit/example.spec.ts

import CoachItem from &quot;@/components/coaches/CoachItem.vue&quot;
import router from &quot;@/router&quot;


  describe(&quot;CoachItem.vue&quot;, () =&gt; {
    it(&quot;displays alert when item is clicked&quot;, async () =&gt; {

      //const route = { path: 'http://www.example-path.com' }
      router.push('/')
      await router.isReady()
      const wrapper = mount(CoachItem); //adding this line causes failure
      //await wrapper.trigger('click');
      //const dialog = wrapper.find('dialog');
      //(dialog.exists()).toBeTruthy()
    })
  })
</code></pre>
<pre><code>// @/components/UserAlert.vue

&lt;template&gt;
  &lt;div class=&quot;backdrop&quot; @click=&quot;closeDialog&quot;&gt;&lt;/div&gt;
  &lt;dialog open&gt;
    &lt;header&gt;
      &lt;h2&gt;{{ title }}&lt;/h2&gt;
    &lt;/header&gt;
    &lt;div&gt;
      &lt;slot name=&quot;content&quot;&gt;&lt;/slot&gt;
    &lt;/div&gt;
    &lt;menu&gt;
      &lt;button @click=&quot;closeDialog&quot;&gt;Close&lt;/button&gt;
    &lt;/menu&gt;
  &lt;/dialog&gt;
&lt;/template&gt;

&lt;script lang=&quot;ts&gt;
import { defineComponent } from &quot;vue&quot;;

export default defineComponent({
  props: ['title'],
  emits: ['close'],
  setup(_, context) {
    function closeDialog() {
      context.emit('close');
    }

    return { closeDialog };
  },
});
&lt;/script&gt;
</code></pre>
<pre><code>// @/components/coaches.CoachItem.vue

&lt;template&gt;
&lt;user-alert v-if=&quot;alertIsVisible&quot; title=&quot;Alert!&quot; @close=&quot;hideAlert&quot;&gt;
    &lt;template v-slot:content&gt;&lt;p&gt;this is a slot&lt;/p&gt;&lt;/template&gt;
  &lt;/user-alert&gt;
  &lt;li @click=&quot;showAlert&quot;&gt;
    &lt;h3&gt;{{ fullName }}&lt;/h3&gt;
    &lt;h4&gt;${{ rate }}/hour&lt;/h4&gt;
    &lt;div&gt;
      &lt;base-badge
        v-for=&quot;area in areas&quot;
        :key=&quot;area&quot;
        :type=&quot;area&quot;
        :title=&quot;area&quot;
      &gt;&lt;/base-badge&gt;
    &lt;/div&gt;
    &lt;div class=&quot;actions&quot;&gt;
      &lt;base-button mode=&quot;outline&quot; link :to=&quot;coachContactLink&quot;
        &gt;Contact&lt;/base-button
      &gt;
      &lt;base-button link :to=&quot;coachDetailsLink&quot;&gt;View Details&lt;/base-button&gt;
    &lt;/div&gt;
  &lt;/li&gt;
&lt;/template&gt;

&lt;script lang=&quot;ts&quot;&gt;
import { computed, defineComponent, PropType, ref } from &quot;vue&quot;;
import { useRoute } from &quot;vue-router&quot;;
import useAlert from &quot;../../components/hooks/useAlert&quot;;
export default defineComponent({
  props: {
    id: {
      type: String,
      required: true,
    },
    firstName: {
      type: String,
      required: true,
    },
    lastName: {
      type: String,
      required: true,
    },
    rate: {
      type: Number,
      required: true,
    },
    areas: {
      type: Object as PropType&lt;Array&lt;string&gt;&gt;,
      required: true,
    },
  },
  setup(props) {
    const route = useRoute();
    const alertTitle = ref(&quot;delete user?&quot;);
    return {
      fullName: computed(() =&gt; props.firstName + &quot; &quot; + props.lastName),
      coachContactLink: computed(
        () =&gt; route.path + &quot;/&quot; + props.id + &quot;/contact&quot;
      ),
      coachDetailsLink: computed(() =&gt; route.path + &quot;/&quot; + props.id),
      ...useAlert()
    };
  },
});
&lt;/script&gt;
</code></pre>
<pre><code>// @/main.ts
import { createApp } from &quot;vue&quot;;
import App from &quot;./App.vue&quot;;
import router from &quot;./router&quot;;
import {store, key }  from &quot;./store&quot;;
import UserAlert from &quot;@/components/UserAlert.vue&quot;;

createApp(App)
.component('UserAlert', UserAlert)
  .use(store, key)
  .use(router)
  .mount(&quot;#app&quot;);
</code></pre>
<pre><code>// @/router/index.ts

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
});

export default router;
</code></pre>
",https://stackoverflow.com/questions/65592988/vue-test-utils-with-vue-router4-and-vue3-composition-api,"['typescript', 'vuejs3', 'vue-test-utils', 'vue-composition-api', 'vue-router4']",1111,False,4,0
how to test react-native-qrcode-scanner with @testing-library/react-native and jest,"<p>I have used this qr scanner in my application but I'm having trouble doing unit testing on the qr scanner. how to do unit testing on this qr scanner? should i mock that or there is a way to send values to onRead props?</p>
<p>before, I have tried to mock react-native-qrcode-scanner with this code</p>
<pre class=""lang-js prettyprint-override""><code>jest.mock('react-native-qrcode-scanner', () =&gt; {
    const React = require('react');
    const PropTypes = require('prop-types');
    return class MockQRCodeScanner extends React.Component {
        static propTypes = { children: PropTypes.any };
        static defaultProps = { reactivate: false }
    
        render() {
          return React.createElement('react-native-qrcode-scanner', this.props, this.props.children);
        }
    }
})
</code></pre>
<p>but gives an error &quot;TypeError: scanner.current.reactivate is not a function&quot;</p>
<p>this my code :
ScanQRCodeScreen.js</p>
<pre class=""lang-js prettyprint-override""><code>'use strict';
import React, {useEffect} from 'react';
import { 
    View, 
    StyleSheet
} from 'react-native';
import QRCodeScanner from 'react-native-qrcode-scanner';

const ScanQRCodeScreen = ({navigation}) =&gt; {
    const scanner = React.useRef(null);
    useEffect(() =&gt; {
        navigation.addListener('focus', async() =&gt; {
            await scanner.current.reactivate();
        });
    },[]);

    const onSuccess = e =&gt; {
        console.log(e.data);
    }
 
    return (
        &lt;View&gt;
            &lt;QRCodeScanner
                onRead={onSuccess}
                ref={scanner}
                showMarker={true}
            /&gt;
        &lt;/View&gt;
    );
};
</code></pre>
<p>ScanQRCodeScreen-test.js</p>
<pre class=""lang-js prettyprint-override""><code>import React, {useRef} from 'react';
import { render, act } from '@testing-library/react-native';

import ScanQRCodeScreen from '../screens/ScanQRCodeScreen';

jest.mock('react-native-qrcode-scanner', () =&gt; {
    const React = require('react');
    const PropTypes = require('prop-types');
    return class MockQRCodeScanner extends React.Component {
        static propTypes = { children: PropTypes.any };
        static defaultProps = { reactivate: false }
    
        render() {
          return React.createElement('react-native-qrcode-scanner', this.props, this.props.children);
        }
    }
});

let wrapper = null;
const map = {};
const mockedParams = {
    navigation: {
        addListener: jest.fn((events, cb) =&gt; {
            map[events] = cb
        })
    },
};
beforeEach(() =&gt; {
    wrapper = render(
        &lt;ScanQRCodeScreen {...mockedParams}/&gt;
    );
})

describe('&lt;Renderable&gt;', () =&gt; {
    test('ScanQRCodeScreen snapshot', async() =&gt; {
        await act(async() =&gt; map.focus());
        expect(wrapper).toMatchSnapshot();
    })
})
</code></pre>
",https://stackoverflow.com/questions/68518095/how-to-test-react-native-qrcode-scanner-with-testing-library-react-native-and-j,"['react-native', 'unit-testing', 'jestjs', 'mocking', 'react-native-testing-library']",1224,False,0,0
Connection &quot;default&quot; was not found with NestJS Unit Testing of Service,"<p>I am currently unit testing my NestJS service. My entity is called 'User' and I established a basic Service that allows me to interact with a MS SQL server, with GET and POST endpoints established in my Controller.</p>
<p>While I was able to mock the <code>Repository</code> that is used in the Service, I was unable to establish a mock <code>getConnection</code> in a method that had to call <code>getConection()</code>.</p>
<p>When I tried unit testing with <code>npm run test:watch</code>, I get the error that <code>ConnectionNotFoundError: Connection &quot;default&quot; was not found.</code> I have looked into (and in fact, taken much from) <a href=""https://stackoverflow.com/questions/61637468/how-to-stub-entitymanager-and-connection-in-typeorm-with-jest"">How to stub EntityManager and Connection in TypeORM with Jest</a>, but this post does not seem to elaborate on a connection that was not established, which is my problem.</p>
<p>In any case, here's my service with the relevant parts:</p>
<pre><code>import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getConnection, Repository } from &quot;typeorm&quot;;
import {User} from '../entities/user.entity';


@Injectable()
export class ServiceName {
  constructor(@InjectRepository(User) private usersRepository: Repository&lt;User&gt;) {}

  // Creating and inserting a new user into the database table using Repository
  // unit testing for this one works fine
  async createUserRepository(user: User): Promise&lt;User&gt; {
    const newUser = this.usersRepository.create(user); 
    return await this.usersRepository.save(newUser);
  }

  // Creating and inserting a new user into the database table using QueryBuilder and getConnection
  // unit testing for this one does not work so well 
  async createUserQueryBuilder(user: User): Promise&lt;User&gt; {
    await getConnection()
    .createQueryBuilder()
    .insert()
    .into(User)
    .values([
        user, 
     ])
    .execute();
    return user;  
  }
</code></pre>
<p>And here's my spec.ts file for unit testing:</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { ServiceName } from './app_codes_rms_area.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { User } from '../entities/user.entity';
import { Connection, Repository } from 'typeorm';

describe('service tests', () =&gt; {

    const repositoryMockFactory: () =&gt; MockType&lt;Repository&lt;any&gt;&gt; = jest.fn(() =&gt; ({ 
        create: jest.fn(),
        save: jest.fn(),
        // other functions
    }));

    const mockConnectionFactory = jest.fn(() =&gt; ({
        getConnection: jest.fn().mockReturnValue({
            createQueryBuilder: jest.fn().mockReturnThis(),
            getMany: jest.fn().mockReturnValue(allUsers),
            insert: jest.fn().mockReturnThis(),
            into: jest.fn().mockReturnThis(),
            values: jest.fn().mockReturnThis(),
            execute: jest.fn().mockReturnValue(user),
        })
    }));
 
    let service: ServiceName;
    let mockRepository: MockType&lt;Repository&lt;User&gt;&gt;;
    let mockConnection: Connection;

    beforeEach(async () =&gt; {
        const module: TestingModule = await Test.createTestingModule({
            providers: [
                ServiceName,
                {
                    provide: getRepositoryToken(User), // a User Repository is injected to the service 
                    useFactory: repositoryMockFactory, // using factory ensures that a new mock is used for every test
                },
                {
                    provide: Connection,
                    useFactory: mockConnectionFactory,
                }
            ],
        }).compile();

        service = module.get&lt;ServiceName&gt;(ServiceName);
        mockRepository = module.get(getRepositoryToken(User));
        mockConnection = module.get&lt;Connection&gt;(Connection);
    });
        it('should create a new user and return it using Repository', async () =&gt; {
            // some test that passes using mockRepository
        });

        it('should create a new user and return it using QueryBuilder (with mocked Connection)', async () =&gt; {
            expect(await service.createUserQueryBuilder(user)).toEqual(user);
            expect(mockConnection.createQueryBuilder).toBeCalled();
            expect(mockConnection.createQueryBuilder()['insert']).toBeCalled();
            expect(mockConnection.createQueryBuilder()['into']).toBeCalled();
            expect(mockConnection.createQueryBuilder()['values']).toBeCalled();
            expect(mockConnection.createQueryBuilder()['execute']).toBeCalled();
        })
</code></pre>
<p>It is the second test, <code>it('should create a new user and return it using QueryBuilder (with mocked Connection)'</code>, that triggers the following error:</p>
<pre><code>  ● service tests › Service Functions › should create a new user and return it using QueryBuilder (with mocked Connection)

    ConnectionNotFoundError: Connection &quot;default&quot; was not found.

      at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)
      at ConnectionManager.Object.&lt;anonymous&gt;.ConnectionManager.get (connection/ConnectionManager.ts:40:19)
      at Object.getConnection (index.ts:252:35)
      at ServiceName.createUserQueryBuilder (somefile:19:11)
      at Object.it (somefile:134:34)
</code></pre>
",https://stackoverflow.com/questions/67521900/connection-default-was-not-found-with-nestjs-unit-testing-of-service,"['typescript', 'unit-testing', 'mocking', 'nestjs', 'typeorm']",1759,True,3,1
How to mock a @Header request for NestJS unit testing,"<p>I am attempting to implement unit testing in NestJS. However, I am new to both NestJS and unit testing in general.
So, what I need to do is to pass a test that gets all projects from a gitlab profile.</p>
<pre><code>@Get()
getProjects(@Headers() headers: any): Observable&lt;Project[]&gt; {
if (!headers.token) {
  throw new HttpException('Missing User Token', HttpStatus.BAD_REQUEST);
 }
 return this.projectsService.listProjects(headers.token);
}
</code></pre>
<p>This is the code in the project.controller.ts file. It works well, and returns an observable with the list of projects. However, it requires a header to be sent through the HTTP request(Which is received using the @Headers decorator), as the gitlab is locked behind an authentication that requires a token to be passed through the header of the request.</p>
<p>I have attempted to mock the header to no success, and I was wondering if anyone has any idea how to proceed with the unit testing for that get request.</p>
",https://stackoverflow.com/questions/70497975/how-to-mock-a-header-request-for-nestjs-unit-testing,"['unit-testing', 'jestjs', 'mocking', 'nestjs']",2136,True,0,1
Endpoint unit testing with Lacinia-Pedestal in Clojure,"<p>I have been using <code>Pedestal</code> for RESTful API servers and its endpoint unit testing. This approach is to set the server up and test it on endpoint level. The so-called &quot;endpoint unit testing&quot; is well documented in below page.</p>
<p><a href=""http://pedestal.io/reference/unit-testing#_testing_your_service_with_response_for"" rel=""nofollow noreferrer"">http://pedestal.io/reference/unit-testing#_testing_your_service_with_response_for</a></p>
<p>This time, however, I am using <code>Lacinia-Pedestal</code> for GraphQL (not RESTful, in other words) and am wondering if I can apply the same endpoint testing logic. In Lacinia-Pedestal repository (<a href=""https://github.com/walmartlabs/lacinia-pedestal"" rel=""nofollow noreferrer"">https://github.com/walmartlabs/lacinia-pedestal</a>), I could not find a relevant instruction. In fact it doesn't mention about unit testing at all.</p>
<p>If anyone has experience with this approach, can you please share?
Thanks!</p>
<p>-- edit
I am adding my testing code here.</p>
<p><strong>resources/main-schema.edn:</strong></p>
<pre><code>{:queries
 {:hello
  {:type String}}}
</code></pre>
<p><strong>core.clj</strong></p>
<pre><code>(ns lacinia-pedestal-lein-clj.core
  (:require [clojure.edn :as edn]
            [clojure.java.io :as io]
            [com.walmartlabs.lacinia.pedestal2 :as p2]
            [com.walmartlabs.lacinia.schema :as schema]
            [com.walmartlabs.lacinia.util :as util]
            [io.pedestal.http :as http]))

(defn resolve-hello
  [_ _ _]
  &quot;hello, darren&quot;)

(defn hello-schema
  []
  (-&gt; (io/resource &quot;main-schema.edn&quot;)
      slurp
      edn/read-string
      (util/inject-resolvers {:queries/hello resolve-hello})
      schema/compile))

(def service
  (-&gt; (hello-schema)
      (p2/default-service nil)
      http/create-server
      http/start))
</code></pre>
<p>and <code>Pedestal</code> (not <code>Lacinia-Pedestal</code>) says that the server instance can be set up and tested by the following code snippet:</p>
<pre><code>(ns lacinia-pedestal-lein-clj.core-test
  (:require [lacinia-pedestal-lein-clj.core :as core]
            [clojure.test :as t]
            [io.pedestal.http :as http]
            [io.pedestal.test :as ptest]
            [com.walmartlabs.lacinia.pedestal2 :as p2]
            [com.walmartlabs.lacinia.util :as util]))

(def service 
  (:io.pedestal.http/service-fn 
    (io.pedestal.http/create-servlet service-map)))

(is (= &quot;Hello!&quot; (:body (response-for service :get &quot;/hello&quot;))))
</code></pre>
<p>But, I believe this way works for RESTful but not for GraphQL because GraphQL needs to set schema (.edn file) and resolvers for a server.</p>
<p>So, I tried to tweak this.</p>
<pre><code>(ns lacinia-pedestal-lein-clj.core-test
  (:require [lacinia-pedestal-lein-clj.core :as core]
            [clojure.test :as t]
            [io.pedestal.http :as http]
            [io.pedestal.test :as ptest]
            [com.walmartlabs.lacinia.pedestal2 :as p2]
            [com.walmartlabs.lacinia.util :as util]))

(defonce service
  (-&gt; (core/hello-schema)
      (p2/default-service nil)
      http/create-server
      http/start))

(t/is (= &quot;Hello!&quot;
         (:body 
          (util/response-for service
                             :get &quot;/hello&quot;)))) ;; NOT WORKING
</code></pre>
<p>But it does not work this way because <code>response-for</code> expects <code>interceptor-service-fn</code> type.
So, as far as I know, the real question is how to use <code>response-for</code> function with GraphQL server instance.</p>
",https://stackoverflow.com/questions/68575488/endpoint-unit-testing-with-lacinia-pedestal-in-clojure,"['unit-testing', 'clojure', 'graphql', 'pedestal']",126,False,0,1
how to mock redis in python?,"<p>I want to mock &amp; patch this redis_client in the handler function for unit testing.</p>
<pre class=""lang-py prettyprint-override""><code>def handler(event, context):
    try:
        criteria = event[&quot;queryParams&quot;]
        msg = &quot;Search count initiated&quot;
  **redis_client = redis_util.RedisUtil(os.environ.get('redis_host'), int(os.environ.get('redis_port')))**     
        name = criteria.get('name', '')
        name = name.replace('&quot;', &quot;'&quot;)```

here redis_util is a local module that contain code mentioned below

</code></pre>
<p>class RedisUtil:
sqs = None</p>
<pre><code>def __init__(self, host, port):
    &quot;&quot;&quot;
    The AWS SQS Util constructor
    :param host: Redis host
    :param poart: Redis port
    &quot;&quot;&quot;
    self.redis_db = redis.Redis(host=host, port=port, db=0)

def get_redis(self):
    return self.redis_db
</code></pre>
<pre><code>Thanks
</code></pre>
",https://stackoverflow.com/questions/67136210/how-to-mock-redis-in-python,"['python', 'unit-testing', 'redis', 'pytest-mock']",348,False,1,1
Are Child Packages safe in ADA?,"<p>I am very new to ADA language and, during my learning process, I have been seeing a lot of examples which uses this ADA functionality.
It seems to me that it could be useful only for unit testing in order to being able to test the private types and methods of the parent package, but I don't see any advantage for coding in such way, it seems that breaks encapsulation.</p>
<p>Is it a good practice to use them apart from unit testing?</p>
",https://stackoverflow.com/questions/66029496/are-child-packages-safe-in-ada,"['ada', 'encapsulation']",169,True,3,3
How to Mock Kotlin LifecycleCoroutineScope for Unit Test?,"<p>How can I mock the following function <code>act</code>.</p>
<pre><code>class Some {
    internal lateinit var coroutineScope: LifecycleCoroutineScope

    ...

    fun act() {
        coroutineScope.launch {
            ...
        }
    }
}
</code></pre>
<p>I am using <code>mockk</code> and <code>kotlinx-coroutines-test</code> for unit-testing this. But it can only mock <code>CoroutineScope</code> and not <code>LifecycleCoroutineScope</code>.</p>
",https://stackoverflow.com/questions/67059431/how-to-mock-kotlin-lifecyclecoroutinescope-for-unit-test,"['android', 'unit-testing', 'kotlin', 'kotlin-coroutines', 'mockk']",1323,False,3,0
Gatsby + Jest - How to enable support for the experimental syntax &#39;jsx&#39;?,"<p>Following Gatsby unit test docs:
<a href=""https://www.gatsbyjs.com/docs/how-to/testing/unit-testing/#writing-tests"" rel=""nofollow noreferrer"">https://www.gatsbyjs.com/docs/how-to/testing/unit-testing/#writing-tests</a></p>
<p>I got this error:</p>
<p>Details:</p>
<pre><code>SyntaxError: ../Projects/gatsby/testing-first-steps/src/components/__tests__/header.js: Support for the experimental syntax 'jsx' isn't currently enabled (9:15):
</code></pre>
<pre><code>       7 |   it(&quot;renders correctly&quot;, () =&gt; {
       8 |     const tree = renderer
    &gt;  9 |       .create(&lt;Header siteTitle=&quot;Default Starter&quot; /&gt;)
         |               ^
      10 |       .toJSON()
      11 |     expect(tree).toMatchSnapshot()
      12 |   })
</code></pre>
<pre><code>Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
</code></pre>
",https://stackoverflow.com/questions/69087351/gatsby-jest-how-to-enable-support-for-the-experimental-syntax-jsx,"['jestjs', 'babeljs', 'gatsby']",487,True,1,1
How to do unit testing using Jest and enzyme for these type of code segmentations?,"<p>I tried so hard to implement the unit testing using jest and enzyme to the below code, but i haven't idea about how to write the unit test correctly. Always i got the test result as 'failed'.</p>
<p>I really appreciate the little support you give me to figure it out and pass the unit testing.</p>
<p>I used context API to fetch data.
I need to unit test the exact path navigation in App.js,</p>
<p>code:</p>
<pre><code>import React, { Component } from &quot;react&quot;;
import { BrowserRouter as Router, Route, Switch } from &quot;react-router-dom&quot;;

import Navbar from &quot;./components/layout/Navbar&quot;;
import Index from &quot;./components/layout/Index&quot;;
import Lyrics from &quot;./components/tracks/Lyrics&quot;;

import { Provider } from &quot;./context&quot;;

class App extends Component {
  render() {
    return (
      &lt;Provider&gt;
        &lt;Router&gt;
          &lt;React.Fragment&gt;
            &lt;Navbar /&gt;
            &lt;div className=&quot;container&quot;&gt;
              &lt;Switch&gt;
                &lt;Route exact path=&quot;/&quot; component={Index} /&gt;
                &lt;Route path=&quot;/lyrics/track/:id&quot; component={Lyrics} /&gt;
              &lt;/Switch&gt;
            &lt;/div&gt;
          &lt;/React.Fragment&gt;
        &lt;/Router&gt;
      &lt;/Provider&gt;
    );
  }
}

export default App;
</code></pre>
<p><a href=""https://i.stack.imgur.com/05YSE.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
",https://stackoverflow.com/questions/69548685/how-to-do-unit-testing-using-jest-and-enzyme-for-these-type-of-code-segmentation,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",53,False,-1,1
Spark Dataframe comparison in Unit testing to check the Functionality,"<p>I have created few methods that will transform dataframes into required format and to filter multiple error checks and to update the dataframe based on error rules.</p>
<p>I am new to write unit testing in scala on intelliJ.
I have to write unit testing to compare the actual dataframes with expected result.</p>
<p>Below is the unit test case i wrote for pivot functionality of the dataframe. Similar way i have to compare the obtained datasets with expected dataframe.</p>
<pre><code> @Test
  def testPivotingDataFramePositive(): Unit = {

    val inputDf = spark.read.option(&quot;header&quot;,true).csv(&quot;src/test/resources/input-test-files/pivotInput.csv&quot;)
    val expectedResult = spark.read.option(&quot;header&quot;,true).csv(&quot;src/test/resources/output-test-files/pivotOutput.csv&quot;)
    val actualResult = parserObj.pivotingDataFrame(inputDf)
    assertEquals(expectedResult, actualResult)
}
</code></pre>
<p>Even the above test case is failing by throwing differences, even though both dataframes are same (might be because of the dataframe records ordering at each time).</p>
<p>Even tried the below comparison and it failed by giving output as 0 even though the dataframes are same.</p>
<pre><code>assert (actualResult.except(expectedResult).count() != 0 &amp;&amp; expectedResult.except(actualResult).count != 0)
</code></pre>
<p>How could i test the dataframe transform functionality effectively in unit testing?</p>
",https://stackoverflow.com/questions/69161373/spark-dataframe-comparison-in-unit-testing-to-check-the-functionality,"['scala', 'dataframe', 'unit-testing', 'apache-spark', 'apache-spark-sql']",763,True,1,1
How do i apply unit testing to check leap year with golang?,"<p>I want to do unit testing and check if dates are leap year or not, how do i apply unit testing in this case, i don’t t know how to go about it in this situation?</p>
<p>I have already created my function and it works fine, i also have a JSON file that contains list of people and their Birthday dates !</p>
<p>Would appreciate some feedback or advice on how to tackle this problem ! Thanks</p>
<p>BD.go:</p>
<pre><code> package main

import (
    &quot;encoding/json&quot;
    &quot;fmt&quot;
    &quot;io/ioutil&quot;
    &quot;log&quot;
    &quot;os&quot;
    &quot;time&quot;
)

// Users struct which contains
// an array of users
type Users struct {
    Users []User `json:&quot;users&quot;`
}

// User struct which contains a name
// a type and a list of social links
type User struct {
    Firstname  string `json:&quot;fname&quot;`
    Secondname string `json:&quot;lname&quot;`
    Date       string `json:&quot;date&quot;`
}

var users Users
var user User

func Birthday() {
    // Open our jsonFile
    jsonFile, err := os.Open(&quot;users.json&quot;)
    // if we os.Open returns an error then handle it
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(&quot;Successfully Opened users.json&quot;)
    // defer the closing of our jsonFile so that we can parse it later on
    defer jsonFile.Close()

    // read our opened xmlFile as a byte array.
    byteValue, _ := ioutil.ReadAll(jsonFile)

    // we initialize our Users array
    // we unmarshal our byteArray which contains our
    // jsonFile's content into 'users' which we defined above
    json.Unmarshal(byteValue, &amp;users)
    IsLeapYear(&quot;users.json&quot;)
}

func IsLeapYear(user string) bool {
    // we iterate through every user within our users array and
    // print out the user Type, their name
    for i := 0; i &lt; len(users.Users); i++ {
        date, err := time.Parse(&quot;2006/01/02&quot;, users.Users[i].Date)
        if err != nil {
            date, err = time.Parse(&quot;2006-01-02&quot;, users.Users[i].Date)
            // date, err = time.Parse(&quot;2006 01 02&quot;, users.Users[i].Date)
            if err != nil {
                log.Fatal(&quot;unsupported date format:&quot;, err)
            }
        }

        // check if the date is a leap year, ex: 29 is not a leap year but 28th is !

        if date.Day()%400 == 0 || (date.Day()%4 == 0 &amp;&amp; date.Day()%100 != 0) {
            fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
            fmt.Println(&quot;User Second Name: &quot; + users.Users[i].Secondname)
            fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
            fmt.Println(users.Users[i].Date, &quot;is a Leap Year ✨ ✨ ✨&quot;)

            // checking if the date.day matches today's date
            if date.Day() == time.Now().Day() {
                fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
                fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
                fmt.Println(&quot;TODAY IS YOUR BIRTHDAY, Happy birthday !!!🎉 🎉 🍾 🍾 &quot;)

                // not ur birthday today because the date in the json doesn't match todays date
            } else {

                fmt.Println(&quot;TODAY IS NOT YOUR BIRTHDAY..!!!&quot;)

            }

        } else {
            fmt.Println(&quot;User First Name: &quot; + users.Users[i].Firstname)
            fmt.Println(&quot;User Second Name: &quot; + users.Users[i].Secondname)
            fmt.Println(&quot;User Date: &quot; + users.Users[i].Date)
            fmt.Println(users.Users[i].Date, &quot; is Not a Leap Year 💥 💥 💥 &quot;)
        }

    }

    return false
}

func main() {
    Birthday()

}
</code></pre>
<p>bd_test.go:</p>
<p>package main</p>
<pre><code>import (
    &quot;testing&quot;
    &quot;time&quot;

    &quot;github.com/stretchr/testify/assert&quot;
)

//main_test.go
type dateTest struct {
    date   time.Time
    expect bool
}

var dateTests = []dateTest{
    {&quot;2021-07-28&quot;, true},
    {time.Date(2021,9,10), false},
}

func TestIsLeapYear(t *testing.T) {
    for _, tc := range dateTests {
        result := IsLeapYear(tc.date)
        assert.Equal(t, tc.expect, result)
    }
}
</code></pre>
<p>users.JSON:</p>
<pre><code>{
    &quot;users&quot;: [
      {
        &quot;Fname&quot;: &quot;Johnny&quot;,
        &quot;Lname&quot;:&quot;mane&quot;,
        &quot;date&quot;:&quot;1982/01/08&quot;
      },
      {
        &quot;Fname&quot;: &quot;Wayne&quot;,
        &quot;Lname&quot;:&quot;Bruce&quot;,
        &quot;date&quot;:&quot;1965/01/30&quot;
      },
      {
        &quot;Fname&quot;: &quot;Gaga&quot;,
        &quot;Lname&quot;:&quot;Lady&quot;,
        &quot;date&quot;:&quot;1986/03/08&quot;
      },
      {
        &quot;Fname&quot;: &quot;radio&quot;,
        &quot;Lname&quot;:&quot;head&quot;,
        &quot;date&quot;:&quot;1988/02/29&quot;
      },
      {
        &quot;Fname&quot;: &quot;Mario&quot;,
        &quot;Lname&quot;:&quot;torres&quot;,
        &quot;date&quot;:&quot;1996/09/04&quot;
      },
      
      {
        &quot;Fname&quot;: &quot;robert&quot;,
        &quot;Lname&quot;:&quot;Alex&quot;,
        &quot;date&quot;:&quot;1991/12/05&quot;
      },
      {
        &quot;Fname&quot;: &quot;Julia&quot;,
        &quot;Lname&quot;:&quot;sevak&quot;,
        &quot;date&quot;:&quot;1991-03-28&quot;

      },
      {
        &quot;Fname&quot;: &quot;feb&quot;,
        &quot;Lname&quot;:&quot;robert&quot;,
        &quot;date&quot;:&quot;1995-05-24&quot;

      },
      {
        &quot;Fname&quot;: &quot;Liam&quot;,
        &quot;Lname&quot;:&quot;Noah&quot;,
        &quot;date&quot;:&quot;2002-10-04&quot;

      },
      {
        &quot;Fname&quot;: &quot;alex&quot;,
        &quot;Lname&quot;:&quot;sam&quot;,
        &quot;date&quot;:&quot;2021/10/21&quot;

      }
      
      }

    ]
  }
</code></pre>
",https://stackoverflow.com/questions/69673616/how-do-i-apply-unit-testing-to-check-leap-year-with-golang,"['unit-testing', 'go', 'testing']",480,True,-2,2
Uncaught TypeError: Cannot read property &#39;filter&#39; of undefined thrown Unit Testing Jasmine,"<p>I have this error in unit testing with jasmine:</p>
<p><strong>Uncaught TypeError: Cannot read property 'filter' of undefined thrown</strong></p>
<p>My function:</p>
<pre><code>info() {
  this.requestService.postRequest('Reports', 'getInfo', {})
   .subscribe(
    data =&gt; {
      this.places = data.places;
      this.types = data.types.filter(obj =&gt; obj.id != 20);
      this.loading = false;
    },
    error =&gt; {
      console.log(error);
      this.loading = false;
    });
  };
</code></pre>
<p>The test:</p>
<pre><code>it('When call requestService.postRequest', () =&gt; {
  
  spyOn(component.requestService, 'postRequest').and.returnValue(of({}));
  
  component.info();
  
  expect(component.requestService.postRequest).toHaveBeenCalled();
  expect(component.requestService.postRequest).toHaveBeenCalledTimes(1);
});
</code></pre>
",https://stackoverflow.com/questions/68036457/uncaught-typeerror-cannot-read-property-filter-of-undefined-thrown-unit-testi,"['javascript', 'typescript', 'karma-jasmine']",1516,True,2,1
How to cover arrow functions in unit testing in angular?,"<p><code>this.service = () =&gt; { -- statements -- }</code></p>
<p>The above statement is to be tested using jasmine unit testing in angular.
Can i get some suggestions for that ?</p>
<p><code>it(&quot;should service call&quot;,()=&gt;{ // i want to call the arrow function here like component.service.? what to use in place of '?'. })</code></p>
",https://stackoverflow.com/questions/66257552/how-to-cover-arrow-functions-in-unit-testing-in-angular,"['node.js', 'angular', 'typescript', 'unit-testing', 'jasmine']",1427,True,-1,1
how to setup Jest for a React Native app with Redux toolkit and typescript,"<p>My team has been trying to implement unit testing for our React Native App using Jest Framework, but we have been encountering a lot of issues that we are not able to understand how to face.</p>
<p>Here is one of the components we are trying to test.
<strong>recipe.test.ts</strong></p>
<pre><code>import 'react-native';
import React from 'react';

import RicettaStep6 from '../src/pages/ricetta-new/ricetta-step6';
import {fireEvent} from '@testing-library/react-native';
import {render} from '@testing-library/react-native';

describe('Sezione ingredienti', () =&gt; {
  test(&quot;correctly converts ingredients's text&quot;, () =&gt; {
    let { queryByTestId } = render(&lt;RicettaStep6/&gt;);
    let firstInput = queryByTestId('input-ingrediente0');

    fireEvent.changeText(firstInput, '20g di farina');

    expect(firstInput.value).toBe('20 grammi farina');
  });
});
</code></pre>
<p>Here is my jest config in jest.config.js
<strong>jest.config.js</strong></p>
<pre><code>const { defaults: tsjPreset } = require('ts-jest/presets');

module.exports = {
  preset: 'react-native',
  globals: {
    'ts-jest': {
      tsconfig: 'tsconfig.spec.json',
      diagnostics: {
        warnOnly: true
      }
    }
  },
  transform: {
    '^.+\\.jsx$': 'babel-jest',
    '^.+\\.tsx?$': 'ts-jest'
  },
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};
</code></pre>
<p>Here is the error that we are continously getting
<a href=""https://i.stack.imgur.com/ghaWd.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ghaWd.png"" alt=""enter image description here"" /></a></p>
<p>What can be the issue? And if not, how do you implement the unit testing for your application?</p>
",https://stackoverflow.com/questions/70474121/how-to-setup-jest-for-a-react-native-app-with-redux-toolkit-and-typescript,"['reactjs', 'react-native', 'unit-testing', 'jestjs', 'ts-jest']",61,False,1,0
Angular Unit Test + SignalR - Error: Failed to complete negotiation with the server: Error: Not Found&#39;,"<p>I have Angular 9 project with Asp.Net core which uses SignalR. Everything is working perfectly fine, but I'm trying to figure out how to do proper unit testing on the component that its using signalr service inside Angular.</p>
<p>library used on frontend: &quot;@aspnet/signalr&quot;: &quot;^1.1.4&quot;</p>
<p>This happens only on unit testing. The error that I'm getting is</p>
<pre><code>Error: Failed to complete negotiation with the server: Error'
    Chrome 91.0.4472 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.304 secs / 0.274 secs)
Error: Failed to start the connection: Error'
    Chrome 91.0.4472 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.304 secs / 0.274 secs)
    ERROR: 'Error'
    Chrome 91.0.4472 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.304 secs / 0.274 secs)
    ERROR: 'Error'
    Chrome 91.0.4472 (Windows 10.0.0): Executed 0 of 1 SUCCESS (0 secs / 0 secs)
    Chrome 91.0.4472 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.3 secs / 0.271 secs)
</code></pre>
<p>My signalr.service.ts</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HubConnection } from '@aspnet/signalr';
import * as signalR from '@aspnet/signalr';
import { Observable } from 'rxjs';
import { SignalRConnectionInfo } from './signalr-connection-info.model';
import { Subject } from 'rxjs';
import { ApiService } from '../../api.service';

    @Injectable()
    export class SignalRService {
    
        private hubConnection: HubConnection;
        private apiHubConnection: HubConnection;
        modelChange: Subject&lt;any&gt; = new Subject();
        change: Subject&lt;any&gt; = new Subject();
        constructor(private http: HttpClient, private apiService: ApiService, private authService: AuthenticationService) {}
    
        private getConnectionInfo(): Observable&lt;SignalRConnectionInfo&gt; {
            return this.http.get&lt;SignalRConnectionInfo&gt;(this.apiService.functionUrl + 'negotiate');
        }
    
        init() {
            this.initApiHub();
            this.getConnectionInfo().subscribe(info =&gt; {
                const options = {
                    accessTokenFactory: () =&gt; info.accessToken
                };
    
                this.hubConnection = new signalR.HubConnectionBuilder()
                    .withUrl(info.url, options)
                    .configureLogging(signalR.LogLevel.Information)
                    .build();
    
                this.hubConnection.start().catch(err =&gt; console.error(err.toString())); // this is the error where it happens. 
    
                this.hubConnection.on('NotifyModelRunStatus', (data: any) =&gt; {
                    this.modelChange.next(data);
                });
    
                this.hubConnection.on('NotifyMoveOrderStatus', (data: any) =&gt; {
                    this.modelChange.next(data);
                    this.change.next(data);
                });
            });
        }
        initApi() {
            const options = {
                accessTokenFactory: () =&gt; this.authService.getAccessToken()
            };
            this.apiHubConnection = new signalR.HubConnectionBuilder()
                .withUrl(this.apiService.apiBaseUrl, options)
                .configureLogging(signalR.LogLevel.Error)
                .build();

            this.apiHubConnection.start()
                .catch(err =&gt; console.error(err ? err.toString() : err));
    
            // Add different SignalR methods from API signalR below
            this.apiHubConnection.on('Some change', (data: any) =&gt; {
                this.change.next(data);
            });
    
            this.apiHubConnection.on('Some change', (data: any) =&gt; {
                this.change.next(data);
            });

        }
    }
</code></pre>
<p>The component unit test where error is shown:</p>
<pre><code>describe('MyComponent', () =&gt; {
    let component: MyComponent;
    let fixture: ComponentFixture&lt;MyComponent&gt;;
    let signalRService: SignalRService;
    
    beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
            imports: [
                RouterTestingModule,
                CommonModule,
                HttpClientTestingModule,
                HttpClientModule,
                ReactiveFormsModule,
                FormsModule,
                BrowserAnimationsModule,
            ],
            declarations: [MyComponent],
            providers: [
                SignalRService,
                ApiService,
                HttpClient,
            ],
        }).compileComponents();
        
        apiService = TestBed.inject(ApiService);
    }));

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

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

});
</code></pre>
<p>I guess the issue is that I'm not mocking the signalr service in test component.</p>
",https://stackoverflow.com/questions/68408897/angular-unit-test-signalr-error-failed-to-complete-negotiation-with-the-ser,"['angular', 'unit-testing', 'signalr', 'karma-jasmine']",513,False,1,1
C# - Unit testing - initializing private fields - ASP.NET Core 5 - NUnit test,"<p>I am new to unit testing, and is currently trying to test a method that gets rows of data using Entity Framework from a SQL Server database.</p>
<p>The problem is that I have 3 fields that are private readonly, and I need to pass those three fields to a method. But since I cant make a constructor, all 3 values are null as default.</p>
<p>How do I make initialize private readonly fields, that talk with a database when unit testing?</p>
",https://stackoverflow.com/questions/70317504/c-unit-testing-initializing-private-fields-asp-net-core-5-nunit-test,"['c#', 'entity-framework', 'unit-testing', 'initialization', 'nunit']",287,False,1,1
"Error: Missing expected firebase config value databaseURL, when hit firebase deploy command","<p>Error: Missing expected firebase config value databaseURL, config is actually</p>
<pre><code>{
  &quot;projectId&quot;:&quot;app-production&quot;,
  &quot;storageBucket&quot;:&quot;app-production.appspot.com&quot;,
  &quot;locationId&quot;:&quot;asia-south1&quot;
}
</code></pre>
<p>If you are unit testing, please set process.env.FIREBASE_CONFIG</p>
<p>when hit <code>firebase deploy</code> command</p>
",https://stackoverflow.com/questions/69507190/error-missing-expected-firebase-config-value-databaseurl-when-hit-firebase-dep,"['node.js', 'database', 'firebase', 'google-cloud-functions', 'firebase-tools']",620,True,0,1
If else statement not covered in Code Coverage in Jasmine,"<p>When I use Jasmine marbles for unit testing for if condition those specific blocks don't cover in code coverage report.
Is there a way to unit test if blocks so that they would be covered in code coverage report?</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>activeClass(menu: MenuList): void {
  this.menuList &amp;&amp; this.menuList.map((element: MenuList) =&gt; {
    if (element.menu_name === menu.menu_name) {
      element.active = true;
      this.gotoSelectedRoute(element);
    } else {
      element.active = false;
    }
  });
}</code></pre>
</div>
</div>
</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>const menuList: MenuList[] = [{
  menu_name: 'MENU_LIST.NEW_BOOKING',
  class: '',
  url: 'services',
  is_hosted: true,
  is_shown_login: true,
  showOnCondition: 'isHostedWithLogin',
  is_hide_login: true,
  hidden: false,
  displayOrder: 1,
  options: null,
  active: false,
}, ];
describe('activeClass', (): void =&gt; {
  const menu: MenuList = menuList[0];
  const menuListdata: MenuList[] = menuList;
  it('should call activeClass', fakeAsync(() =&gt; {
    selectMenuDataMock.setResult(menuList);
    store.refreshState();
    fixture.detectChanges();
    component.activeClass(menuList[0]);
    expect(component.activeClass).toBeTruthy();
  }));

  it('should both the menu name needs to be same', fakeAsync(() =&gt; {
    selectMenuDataMock.setResult(menuList);
    store.refreshState();
    fixture.detectChanges();
    component.activeClass(menu);
    menuList.forEach((element) =&gt; {
      element.menu_name = 'MENU_LIST.NEW_BOOKING';
      menu.menu_name = 'MENU_LIST.NEW_BOOKING';
      expect(element.menu_name).toEqual(menu.menu_name);
    });
  }));

  it('should active be true', fakeAsync(() =&gt; {
    selectMenuDataMock.setResult(menuList);
    store.refreshState();
    fixture.detectChanges();
    component.activeClass(menu);
    menu.active = true;
    menuList.forEach((element) =&gt; {
      expect(element.active).toBe(true);
    });
  }));

  it('should gotoselected', fakeAsync(() =&gt; {
    selectMenuDataMock.setResult(menuList);
    store.refreshState();
    fixture.detectChanges();
    component.activeClass(menu);
    const spy = spyOn(component, 'gotoSelectedRoute').and.callThrough();
    menuList.forEach((element) =&gt; {
      element.active = true;
      component.gotoSelectedRoute(element);
      expect(spy).toHaveBeenCalledWith(element);
    });
  }));

  it('should active be false', fakeAsync(() =&gt; {
    selectMenuDataMock.setResult(menuList);
    store.refreshState();
    fixture.detectChanges();
    component.activeClass(menu);
    menu.active = false;
    menuList.forEach((element) =&gt; {
      expect(element.active).toBe(false);
    });
  }));

});</code></pre>
</div>
</div>
</p>
<p>Not sure whether the coding style for unit testing is correct or not let me know if needed any improvement.</p>
<p>from above ts file from if block code is not covered not sure where i am going</p>
<p>this is case i am trying to write it Thanks.</p>
<p><a href=""https://i.stack.imgur.com/zCj9o.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/zCj9o.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/66234006/if-else-statement-not-covered-in-code-coverage-in-jasmine,"['angular', 'jasmine']",1501,False,1,1
C++/CMake/azure DevOps code coverage and unit testing,"<p>I’m developing few modules for my IoT project in C++, and CMake.
Finally, The module is built into a docker image, and pulled to the device, using azure IoT platform.
Also, i have a azure devops CI/CD pipeline to automate the deployment.</p>
<p>Now, i came across unit testing and codec overage.
I used gtest to do unit testing, and lcov to calculate code coverage,locally</p>
<p>But i want this to integrate with my pipeline.</p>
<p>Can someone suggest a best methode,or any alternative to do this.</p>
",https://stackoverflow.com/questions/66567260/c-cmake-azure-devops-code-coverage-and-unit-testing,"['c++', 'docker', 'azure-pipelines', 'code-coverage', 'googletest']",1151,True,1,1
Why I receive ModuleNotFoundError while testing using pytest?,"<p>I use <code>pytest</code> for unit testing, but I received this error:</p>
<pre class=""lang-none prettyprint-override""><code>ModuleNotFoundError: No module named 'package'
</code></pre>
<p>when I import two modules locally:</p>
<pre class=""lang-py prettyprint-override""><code>from package import module1
from package import module2
</code></pre>
<p>The current working directory looks like this:</p>
<pre class=""lang-none prettyprint-override""><code>├── package
│   ├── __init__.py
│   ├── module1.py
│   └── module2.py
├── requirements.txt
├── setup.py
├── test-requirements.txt
└── tests
    ├── test_module1.py
    ├── test_module2.py
</code></pre>
",https://stackoverflow.com/questions/68997788/why-i-receive-modulenotfounderror-while-testing-using-pytest,"['python', 'unit-testing', 'pytest']",21,True,0,1
How to Unit test the logging in Java springboot,"<p>Hi I'm new to java Spring boot. Currently I'm working on a java application and I was asked to write unit testing for the service layer. However when I checked with the JaCoCo code coverage it shows that the below logging statements are not covered from the unit testing. So how Can I write unit test for logging? Is it a must to write unit test for loggings?</p>
<p>Can anyone please help me with this matter?
Here I have attached the uncovered logging statement.</p>
<p><a href=""https://i.stack.imgur.com/kwTb1.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/kwTb1.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/69062302/how-to-unit-test-the-logging-in-java-springboot,"['java', 'spring-boot', 'unit-testing']",149,False,0,0
What is the difference between @TestOnly and @VisibleForTesting in unit test,"<p>As per my understanding, these annotations used for methods with an access modifier that allows method invocation from another class for unit testing</p>
<p>@VisibleForTesting - com.google.common.annotations.VisibleForTesting<br />
@TestOnly - org.jetbrains.annotations.TestOnly</p>
",https://stackoverflow.com/questions/67207970/what-is-the-difference-between-testonly-and-visiblefortesting-in-unit-test,"['java', 'annotations', 'guava', 'encapsulation', 'jetbrains-ide']",2349,True,3,2
Testing components in oidc-react,"<p>I'm using oidc-react library to authentication and auth flow.
I have to unit testing my components.
How can I inject a user to ?</p>
",https://stackoverflow.com/questions/68305251/testing-components-in-oidc-react,"['javascript', 'reactjs', 'openid-connect']",266,False,0,1
"mockito, how to coverage test the catch block","<p>Android app, Having a function calling another function, that function may throw</p>
<pre><code>static string SOME_DEFINE_1 = &quot;some_define_1&quot;;
......
void myFunc() {
        try {
            HashMap&lt;String, String&gt; data = new HashMap&lt;&gt;();
            data.put(&quot;key_1&quot;, SOME_DEFINE_1);
            otherObject.func(data);
        } catch (Throwable ex){
            Log.e(TAG, &quot;+++ exception from otherObject.func(), &quot;+ ex.toString());
            // do something
            anotherFunc();
        }
    }
</code></pre>
<p>How to test the catch block is called when unit testing the myFunc?</p>
",https://stackoverflow.com/questions/67743915/mockito-how-to-coverage-test-the-catch-block,"['mockito', 'test-coverage', 'android-junit']",1451,True,1,1
How do I do an Angular unit testing karma jasmine of this string function?,"<p>Angular unit testing karma jasmine of this string function, layouts come from the backend (layout.ts) - it should return a string like (1-&quot;ABC&quot;-(active))</p>
<pre><code>getSelectedLayout(): string {
const p = new ActivePipe();
if(this.layoutId === ''){
this.layoutId = this.layouts.find((x)=&gt;x.status ===true)?.gridId.toString() as string;
}
const selectedLayout = this.layouts.find((x)=&gt;x.gridId.toString() === this.layoutId);
return(
selectedLayout?.gridId + '-' + selectedLayout?.name + '(' + p.transform(selectedLayout?.status) + ')' ); }
</code></pre>
",https://stackoverflow.com/questions/68588132/how-do-i-do-an-angular-unit-testing-karma-jasmine-of-this-string-function,"['angular', 'unit-testing', 'testing', 'jasmine', 'karma-runner']",167,False,0,0
facing issue in method channel internet connectivity in unit testing in flutter,"<p>I have checked internet connectivity in flutter while calling api in store class like this using 'connectivity' library.</p>
<pre><code>    Future&lt;bool&gt; callApi() async {

    final isInternet = await Util.checkInternetAndShowDialog(context);

    if (isInternet) {

      final future = _repository.callApi();

      var res = await future;

      return true;

    }

return false;

    }
</code></pre>
<p>In Util class network connectivity is been checked like this::</p>
<pre><code>class Util {

  static Future&lt;bool&gt; checkInternetAndShowDialog(BuildContext context) async{
    var internet = await NetworkConnectivity.rechability();
    if (internet == false) {
      AlertMessage().showAlertDialog(context, 'error message');
    }
    return internet;
  }

}
</code></pre>
<p>In NetworkConnectivity class network connectivity is been checked using Connectivity library.</p>
<pre><code>class NetworkConnectivity {

static Future&lt;bool&gt; rechability() async {

    var connectivityResult = await (Connectivity().checkConnectivity());

    if (connectivityResult == ConnectivityResult.mobile) {

      return true;

    } else if (connectivityResult == ConnectivityResult.wifi) {

      return true;

    }

    return false;

  }

}
</code></pre>
<p>my test cases code is like below:</p>
<pre><code>test('call api successfully', () async {

      when(mockStore.callApi()).thenAnswer((realInvocation) =&gt; Future.value());
      expect(await store.callApi(), true);
    });
</code></pre>
<p>so while writing unit testing I am facing error of connectivity and method channel.
<a href=""https://i.stack.imgur.com/1wEjN.png"" rel=""nofollow noreferrer"">connectivity error image</a></p>
<p>Can any one help please me how I can mock for internet connectivity in unit testing and pass the test in flutter. I shall be thankful for this.</p>
",https://stackoverflow.com/questions/68659780/facing-issue-in-method-channel-internet-connectivity-in-unit-testing-in-flutter,"['flutter', 'dart', 'flutter-test', 'connectivity']",303,False,1,0
How to call the subscribe error block in unit testing Angular?,"<p>i have tried unit testing in Angular subscribe, i write below testcase but its not 100% reach not accessin error block section</p>
<p>componant</p>
<pre><code>   this.Servive.methof(value).subscribe(res =&gt; {
   
    this.router.navigate('url');
  },
  error =&gt; {
    this.error= true;
  });
</code></pre>
<p>spec file</p>
<pre><code>   const spy = jest.spyOn(servive, 'method').mockReturnValue(of(appDataCreateResponse));
   component.dunction();
    expect(spy).Error(); 
    expect(component.apiError).toBeTruthy;
</code></pre>
",https://stackoverflow.com/questions/68282436/how-to-call-the-subscribe-error-block-in-unit-testing-angular,"['angular', 'jestjs', 'jasmine', 'karma-jasmine']",183,True,0,1
Jest: How to mock db response from controller?,"<p>I am learning unit testing. I wanted to mock the database response from the controller.
How can I do that?
here is my code:</p>
<p>imageController.ts</p>
<pre><code> const getImages = async (req: Request, res: Response) =&gt; {
  const images = await Image.find({}).sort({ date: -1 });
  return res.status(200).json(images);
};
</code></pre>
<p>image.test.ts</p>
<pre><code>describe(&quot;It shuld be get methoad&quot;, () =&gt; {
  test(&quot;get all image url&quot;, async () =&gt; {
    const res = await request(app).get(&quot;/api/v1/all&quot;);
    expect(res.statusCode).toBe(200);
    // console.log(res.body);
    let images = res.body
    // expect(images.length).toBeGreaterThan(0);
  });
});
</code></pre>
",https://stackoverflow.com/questions/69926874/jest-how-to-mock-db-response-from-controller,"['node.js', 'express', 'jestjs']",682,False,1,2
Unit Test viewModel using mockito and kotlin coroutine flow,"<p>I'm learning unit testing using Mockito, but I don't understand how to do this unit test on my viewModel, on this below the code of my viewModels,</p>
<pre><code>    private val _state = MutableLiveData&lt;Resource&lt;ResponseMealsCategory&gt;&gt;()
    val states: LiveData&lt;Resource&lt;ResponseMealsCategory&gt;&gt; get() = _state

    fun loadAllCategories(){
        viewModelScope.launch {
            repository.getAllCategories()
                ?.onStart {
                    _state.postValue(Resource.onLoading(data = null))
                }
                ?.catch {
                    _state.postValue(Resource.onFailed(data = null, message = null))
                }
                ?.collect { category -&gt;
                    _state.postValue(Resource.onSuccess(data = category))
                }
        }
    }
}

maybe someone can help me to do unit test on my viewModel?
</code></pre>
",https://stackoverflow.com/questions/66956496/unit-test-viewmodel-using-mockito-and-kotlin-coroutine-flow,"['android', 'mockito', 'viewmodel', 'kotlin-coroutines', 'kotlin-flow']",327,False,1,0
Test Cases Fail On Null Assertion,"<pre><code>&quot;packages&quot;: [
           {
             &quot;TriggerType&quot;: &quot;sample&quot;,
             &quot;StatusDescription&quot;: &quot;&quot;,
             &quot;Score&quot;: null,
             &quot;Percentile&quot;: null,
             &quot;Band&quot;: &quot;&quot;
           }
         ]
</code></pre>
<p>When I parse this JSON using <code>JObject attachmentData = JObject.Parse(targetPayload);</code></p>
<p>and perform the unit testing.</p>
<pre><code>
Assert.AreEqual(&quot;&quot;, attachmentData.SelectToken(&quot;packages&quot;)[0].SelectToken(&quot;Score&quot;).ToString());
</code></pre>
<p><strong>This works fine but I want to check</strong></p>
<pre><code>
Assert.AreEqual(null, attachmentData.SelectToken(&quot;packages&quot;)[0].SelectToken(&quot;Score&quot;).ToString());

or 
Assert.IsNull(attachmentData.SelectToken(&quot;packages&quot;)[0].SelectToken(&quot;Score&quot;).ToString());

</code></pre>
<p><strong>These are giving the following errors.</strong></p>
<pre><code>
Assert.AreEqual failed. Expected:&lt;(null)&gt;. Actual:&lt;&gt;

{&quot;Assert.IsNull failed. &quot;}


</code></pre>
<p>Thanks!</p>
",https://stackoverflow.com/questions/67310082/test-cases-fail-on-null-assertion,"['c#', '.net', 'visual-studio', 'unit-testing']",961,True,0,1
Angular 9 FormModule Unit Testog,"<p>So I have an @Input form: FormGroup.</p>
<p>Unit Testing</p>
<pre><code>    describe('Component', () =&gt; {
      let component: Component;
      let fixture: ComponentFixture&lt;Component&gt;;
      let apiService: ApiService;
      let fb: FormBuilder = new FormBuilder();
    
      beforeEach(async () =&gt; {
        await TestBed.configureTestingModule({
          declarations: [Component, TranslatePipeMock],
          imports: [ReactiveFormsModule, FormsModule],
          providers: [
            ChangeDetectorRef,
            { provide: FormBuilder, useValue: fb },
            {
              provide: ApiService,
              useValue: apiServiceStub,
            },
            {
              provide: TranslateService,
              userValue: translateServiceStub,
            },
          ],
          schemas: [NO_ERRORS_SCHEMA],
        }).compileComponents();
      });

  beforeEach(() =&gt; {
   apiLookupService = TestBed.inject(ApiLookupService);
   fixture = TestBed.createComponent(InputWhtComponent);
   fb = TestBed.inject(FormBuilder);
   component = fixture.componentInstance;

    const expectedForm = fb.group({
      isWithholdingTaxEnabled: new FormControl(true),
    });
    component.form = expectedForm;
    fixture.detectChanges();

    });
</code></pre>
<p>But i am having this error right now,
<strong>No value accessor for form control with name: 'isWithholdingTaxEnabled'</strong></p>
",https://stackoverflow.com/questions/65787212/angular-9-formmodule-unit-testog,['javascript'],36,False,0,0
How to mock (simulate) MyBatis-Plus data access layer for unit testing for Model&lt;&gt; Active Record?,"<p>In codebase where model classes use Model from <a href=""https://github.com/baomidou/mybatis-plus"" rel=""nofollow noreferrer"">https://github.com/baomidou/mybatis-plus</a></p>
<pre><code>public class SomeDomainClass extends Model&lt;SomeDomainClass&gt; {
</code></pre>
<p>How to mock (simulate) MyBatis-Plus data access layer for unit testing?</p>

<hr />
<p>Longer code example</p>
<pre class=""lang-java prettyprint-override""><code>package com.company.project.domain;

import com.baomidou.mybatisplus.annotation.*;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import lombok.experimental.Tolerate;

import java.io.Serializable;
import java.math.BigDecimal;

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName(&quot;t_order&quot;)
@Builder
public class Order extends Model&lt;Order&gt; {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(name = &quot;id&quot; , value = &quot;id&quot;)
    @TableId(value = &quot;f_id&quot;, type = IdType.AUTO)
    private Long id;

    @ApiModelProperty(name = &quot;orderId&quot; , value = &quot;orderId&quot;)
    private Long orderId;
    
</code></pre>
",https://stackoverflow.com/questions/66756355/how-to-mock-simulate-mybatis-plus-data-access-layer-for-unit-testing-for-model,"['java', 'mybatis']",204,False,1,0
Laravel 6 PHP unit testing - Session store not set on request,"<p>I got a run time error (RuntimeException: Session store not set on request.) while running the unit testing</p>
<pre><code>public function testUserCanLoginCorrectCredentials()
{
    $this-&gt;withoutExceptionHandling();
    $user = factory(Users::class)-&gt;create();
    $response = $this-&gt;post('/admin/login', [
        'email' =&gt; $user-&gt;email,
        'password' =&gt; '123456789',
    ]);
    $response-&gt;withSession(['user_id' =&gt; $user-&gt;id]);
    $response-&gt;assertRedirect('/admin/dashboard');
    $this-&gt;assertAuthenticatedAs($user);
}
</code></pre>
<p>In Controller :</p>
<pre><code>$checkUserExist =$this-&gt;users-&gt;where('email',$request-&gt;email)-&gt;where('password',$request-&gt;password)-&gt;first();
if(isset($checkUserExist)){

    $user = Auth::guard('users');
    $users = Auth::login($checkUserExist);
    //Authentication passed...
    $request-&gt;session()-&gt;put('admin_user_id', $checkUserExist-&gt;id);
    return redirect('admin/dashboard')-&gt;with('success', 'You are Logged in !');
} else {
    return redirect('/admin')-&gt;with('error','Invalid Password, Please Entered Correct Credentials!');
}
</code></pre>
<p>While running the command I'm getting this error</p>
<pre><code>Time: 1.76 seconds, Memory: 52.00 MB

There was 1 error:

1) Tests\Unit\HostLoginTest::testUserCanLoginCorrectCredentials
RuntimeException: Session store not set on request.

C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Http\Request.php:482
C:\xampp\htdocs\parkk-web\app\Http\Controllers\Auth\LoginController.php:107
C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Routing\Controller.php:54
C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php:45
C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Routing\Route.php:219
C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Routing\Route.php:176
C:\xampp\htdocs\parkk-web\vendor\laravel\framework\src\Illuminate\Routing\Router.php:680
</code></pre>
",https://stackoverflow.com/questions/70096316/laravel-6-php-unit-testing-session-store-not-set-on-request,"['php', 'laravel']",1273,False,1,1
How to automate the process of IVR,"<p>Could anyone let me know how to automate the process of IVR like to make unit testing on IVR composer without making testing calling every time? Thanks</p>
",https://stackoverflow.com/questions/66525227/how-to-automate-the-process-of-ivr,['ivr'],138,False,0,2
Why do I get the error &quot;Received value must be an HTMLElement or an SVGElement&quot; when using react-native?,"<p>I'm new to unit testing and I'm trying to render a component to learn more about the library.</p>
<p>I'm trying to follow <a href=""https://testing-library.com/docs/react-native-testing-library/example-intro"" rel=""noreferrer"">this</a> guide.</p>
<p><strong>Component</strong></p>
<pre class=""lang-js prettyprint-override""><code>&lt;TouchableOpacity
    style={style}
    onPress={onPress}
    accessibilityRole=&quot;button&quot;
&gt;
    &lt;AppText style={textStyle}&gt;{title.toUpperCase()}&lt;/AppText&gt;
&lt;/TouchableOpacity&gt; 
</code></pre>
<p><strong>Test</strong></p>
<pre class=""lang-js prettyprint-override""><code>it(&quot;Has the correct title in the button&quot;, () =&gt; {
    const { getByText } = render(&lt;AppButton title=&quot;Hello&quot; /&gt;);
  
    expect(getByText(&quot;HELLO&quot;)).toBeInTheDocument();
});
</code></pre>
<p>I'm simply trying to see that the component renders correctly but I get the error</p>
<pre><code>received value must be an HTMLElement or an SVGElement.
    Received has type:  object
    Received has value: {&quot;_fiber&quot;: {&quot;_debugHookTypes&quot;: null, &quot;_debugID&quot;: 40, &quot;_debugIsCurrentlyTiming&quot;: false, &quot;_debugNeedsRemount&quot;: false, &quot;_debugOwner&quot;: [FiberNode], &quot;_debugSource&quot;: null, &quot;actualDuration&quot;: 0, &quot;actualStartTime&quot;: -1, &quot;alternate&quot;: null, &quot;child&quot;: [FiberNode], &quot;childExpirationTime&quot;: 0, &quot;dependencies&quot;: null, &quot;effectTag&quot;: 1, &quot;elementType&quot;: [Function Component], &quot;expirationTime&quot;: 0, &quot;firstEffect&quot;: null, &quot;index&quot;: 0, &quot;key&quot;: null, &quot;lastEffect&quot;: null, &quot;memoizedProps&quot;: [Object], &quot;memoizedState&quot;: null, &quot;mode&quot;: 0, &quot;nextEffect&quot;: null, &quot;pendingProps&quot;: [Object], &quot;ref&quot;: null, &quot;return&quot;: [FiberNode], &quot;selfBaseDuration&quot;: 0, &quot;sibling&quot;: null, &quot;stateNode&quot;: [Component], &quot;tag&quot;: 1, &quot;treeBaseDuration&quot;: 0, &quot;type&quot;: [Function Component], &quot;updateQueue&quot;: [Object]}}
</code></pre>
<p>Any advice on what I'm doing wrong?</p>
",https://stackoverflow.com/questions/66516348/why-do-i-get-the-error-received-value-must-be-an-htmlelement-or-an-svgelement,"['react-native', 'jestjs', 'react-native-testing-library', 'jest-dom']",44123,True,19,2
"TypeError: Cannot read property &#39;pipe&#39; of undefined (jasmine, angular)","<p>I have an error regarding unit testing in Angular. The error is TypeError: Cannot read property 'pipe' of undefined. For this I used an observable and i tried to test the output of the subscribe. I will appreciate any help! Thank you!</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>  obs1$: Observable&lt;number&gt;;
  pos=12345;

  constructor(
    private service1: Service) {
  }

  ngOnInit() {

    this.obs1$ = this.service1.retrieveData1(this.pos)
      .pipe(
        map(item =&gt; item.value || null))

  }</code></pre>
<pre class=""snippet-code-css lang-css prettyprint-override""><code> let component: ComponentName;
  let fixture: ComponentFixture&lt;ComponentName&gt;;

  const serviceSpy = jasmine.createSpyObj('Service',['retrieveData1']);

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ComponentName],
      providers: [{ provide:Service, useValue: {} }
    })
      .overrideComponent(ComponentName, {
        set: {
          providers: [
            { provide: ComponentName, useValue: serviceSpy }
          ]
        }
      })
      .compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ComponentName);
    component = fixture.componentInstance;
  });
 
 fit('should retrieve value', done =&gt; {
    component.pos = 12345;
    fixture.detectChanges();
    component.obs1$.subscribe(value =&gt; {
      expect(value).toEqual(1);
      done();
    })
  })</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;div *ngIf=""obs1$ | async as obs""&gt;
    &lt;div [ngSwitch]=""obs"" class=""col-2 p-0""&gt;
      &lt;div *ngSwitchCase=""0""&gt;
         &lt;p&gt;red&lt;/p&gt;
       &lt;/div&gt;
     &lt;/div&gt;
 &lt;/div&gt;</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/66600829/typeerror-cannot-read-property-pipe-of-undefined-jasmine-angular,"['angular', 'testing', 'jasmine']",34016,True,13,2
How can we test useState hooks inside a void function with jest and enzyme?,"<p>I'm new to unit-testing and writing test cases using jest and enzyme in React. Can someone please help me to write the test case for this example?</p>
<pre><code>const [open, setOpen] = useState(false);
const handleClose = () =&gt; {
    setOpen(!open);
}

//this handleClose is an onClick event
</code></pre>
",https://stackoverflow.com/questions/68668247/how-can-we-test-usestate-hooks-inside-a-void-function-with-jest-and-enzyme,"['reactjs', 'unit-testing', 'jestjs', 'onclick', 'enzyme']",371,True,-1,1
Sequelize findAll not returning expected output on sequelize-mock,"<p>I'm trying to do unit testing on my nodejs-express method with sequelize-mock.</p>
<p><strong>Controller</strong></p>
<pre><code>const getDetailsByUserId = async (id) =&gt; {
        try {
            const userId = id ?? 0;
            const details = await Model.findAll(
                {
                    raw: true,
                    where: { user_id: userId  }
                }
            );
            
            if (details &amp;&amp; details .length &gt; 0) {
                return {
                    status: 200,
                    success: true,
                    message: 'details found.',
                    data: details 
                }
            }
    
            return {
                status: 404,
                success: false,
                message: 'details not found',
                data: []
            }
        } catch (error) {
            return {
                status: 500,
                success: false,
                message: error.message || &quot;An error occurred while getting details.&quot;,
                data: null
            }
        }
    }
</code></pre>
<p><strong>Test</strong></p>
<pre><code>jest.mock('../models/details', () =&gt; () =&gt; {
    const SequelizeMock = require(&quot;sequelize-mock&quot;);
    const dbMock = new SequelizeMock();
    return dbMock.define('users', [
        {
            id: 1,
            user_id: 123
            name: 'John Doe 1'
        },
        {
            id: 2,
            user_id: 456
            name: 'John Doe 2'
        },
        {
            id: 3,
            user_id: 789
            name: 'John Doe 3'
        }
    ]);
});

test('should return 404 and an empty array', async () =&gt; {
            const userId = 147;
            const details = await controller.getDetailsByUserId(userId);

            expect(details.status).toEqual(404);
        });
</code></pre>
<p>I always get the status of 200 instead of 404 here. I checked the returned data and it's returning the records of the defined mocked model.</p>
<p><strong>Actual Result:</strong></p>
<pre><code>[
      fakeModelInstance {
        options: {
          timestamps: true,
          paranoid: undefined,
          createdAt: undefined,
          updatedAt: undefined,
          deletedAt: undefined,
          isNewRecord: true
        },
        _values: {
          '0': [Object],
          '1': [Object],
          '2': [Object],
          user_id: 147,
          id: 1,
          createdAt: 2021-09-18T00:55:25.976Z,
          updatedAt: 2021-09-18T00:55:25.976Z
        },
        dataValues: {
          '0': [Object],
          '1': [Object],
          '2': [Object],
          user_id: 147,
          id: 1,
          createdAt: 2021-09-18T00:55:25.976Z,
          updatedAt: 2021-09-18T00:55:25.976Z
        },
        hasPrimaryKeys: true,
        __validationErrors: []
      }
    ]
</code></pre>
<p><strong>QUESTIONS:</strong></p>
<ol>
<li>Is there something I can do to get the expected result (empty array) for this scenario?</li>
<li>the <code>raw: true</code> seems to be not working when it is mocked. Is there a way could log the result on raw object?</li>
</ol>
<p><strong>NOTE:</strong> This only happens on the unit testing. When accessing the endpoint on postman it returns the expected result.</p>
",https://stackoverflow.com/questions/69230853/sequelize-findall-not-returning-expected-output-on-sequelize-mock,"['mysql', 'node.js', 'unit-testing', 'mocking', 'sequelize.js']",872,False,1,2
Unit test a TypeScript void function with sinon,"<p>I am developing a VS Code extension and currently I am in the process of doing unit tests. I am complete new to unit testing and I am quite lost on how I should go about unit testing a void function.</p>
<pre><code>export const getChecklistItems = async (id: number): Promise&lt;any&gt; =&gt; {
  const checklistItems: ChecklistItem[] = [];
  const items: any[] = await getItemsFromUrl(`path_to_url/{id}`);

  items.map((item) =&gt; checklistItems.push(new ChecklistItem(item.checklist_items_id, item.checklist_items_content)));

  return checklistItems;
};

export const onSelectInsertComment = async (id: number): Promise&lt;void&gt; =&gt; {
  const editor: TextEditor | undefined = window.activeTextEditor;
  const items: any[] = await getChecklistItems(id);

  items.reverse(); // Workaround to output comments in correct numerical order inside the TextEditor

  if (!editor) {
    window.showWarningMessage('No editors are open in you workspace');
  } else {
    items.forEach((item) =&gt; {
      editor?.insertSnippet(new SnippetString(`$LINE_COMMENT ${item.label}\n`));
    });

    window.showInformationMessage('Great. Checklist items have been inserted');
  }
};
</code></pre>
<p>I am using mocha, chai and sinon for my unit tests. I am trying to use a spy to check whether <code>getCheckListItems(id)</code> is called when <code>onSelectInsertComment(id)</code> is called. One the the things I tried is the following:</p>
<pre><code>describe('#onSelectInsertComment', () =&gt; {
  it('should be resolved', () =&gt; {
    const id = 1;
    const spy = sinon.spy(getChecklistItems);
    spy.withArgs(id);

    onSelectInsertComment(id);

    sinon.assert.calledOnce(spy);
  });
});
</code></pre>
<p>The result is: <code> AssertError: expected getChecklistItems to be called once but was called 0 times</code>.</p>
<p>What am I doing wrong? I would appreciate it if I was pointed into the right direction. Thanks.</p>
",https://stackoverflow.com/questions/67217406/unit-test-a-typescript-void-function-with-sinon,"['javascript', 'typescript', 'unit-testing', 'sinon', 'vscode-extensions']",1182,False,0,1
Ktor Unit Testing with JWT and Firebase Auth,"<p>I have Ktor Jwt authentication setup with Firebase Auth and working except in my unit testing. Getting <code>TRACE io.ktor.auth.jwt - Failed to get JWK: Failed to get key with kid null</code></p>
<p>I'm wondering if <code>FirebaseAuth.getInstance().createCustomToken(UUID.randomUUID().toString())</code> is not working.</p>
<p>Here is one of my unit tests:</p>
<pre><code>test(&quot;when register for game and userId is not found then NotFound is returned&quot;) {
    coEvery { userRepositoryMock.getUser(any()) } returns null
    withServer {
        val req = handleRequest(HttpMethod.Get, &quot;/api/game/1/2&quot;) {
            addJwtHeader()
        }
        req.response.status() shouldBe HttpStatusCode.NotFound
        req.response.content shouldBe &quot;Could not find user.&quot;
    }
}

private fun TestApplicationRequest.addJwtHeader() = addHeader(&quot;Authorization&quot;, &quot;Bearer ${getToken()}&quot;)

private fun getToken() = FirebaseAuth.getInstance().createCustomToken(UUID.randomUUID().toString())

private fun withServer(block: TestApplicationEngine.() -&gt; Unit) {
    withTestApplication({ module() }, block)
}
</code></pre>
",https://stackoverflow.com/questions/66056024/ktor-unit-testing-with-jwt-and-firebase-auth,"['firebase-authentication', 'jwt', 'ktor']",288,False,1,0
"SuperTest / JEST , how to force or mock a 400 status code?","<p>I'm doing unit testing with Jest and SuperTest, and I can't figure out a way to force a route to give throw an error.</p>
<p>I've attached snippets of my code :</p>
<pre><code>    const router = require('express').Router();
    const Thoughts = require('../models/thought.model')
    
    router.get('/thoughts', (req,res)=&gt;{
      Thoughts.find().then((thought)=&gt;{
        res.status(200).send({thought})
      }).catch((err)=&gt;{
        res.sendStatus(400).send(err)
      })
    })
</code></pre>
<pre><code>   const normRoutes = require('../routes/normRoutes')
   const request = require('supertest');
   const express = require('express');
   const mongoose = require('mongoose')


    const app = express();

    app.use('/api', normRoutes)

    beforeAll(async () =&gt; {
        const url = &quot;MONGO_URL&quot;
        await mongoose.connect(url, {    
            useNewUrlParser: true,
            useCreateIndex: true,
            useUnifiedTopology: true })
      })


    test('GET /api/thoughts --&gt; 400 if error', () =&gt; { 
       ## missing logic to force a 400 
        request(app)
        .get('/api/thoughts)
        .expect(400)
        .done()
    })
</code></pre>
",https://stackoverflow.com/questions/68353437/supertest-jest-how-to-force-or-mock-a-400-status-code,"['javascript', 'testing', 'jestjs', 'supertest']",5019,True,1,1
TypeError: cannot read properties of undefined (reading &#39;split&#39;),"<p>I am new to Angular unit testing (Jasmine karma). I am getting <strong>TypeError: cannot read properties of undefined (reading 'split')</strong> . How to solve it? Thanks in advance.</p>
<p>ts file:</p>
<pre><code>export class SelectedComponent extends OnInit {
paidReference: string; 
timeReference: string;
constructor(public activatedRoute: ActivatedRoute) {} 
ngOnInit() { let tempData=
this.activatedRoute.snapshot.queryParams.Ref.split('-');
this.paidReference = tempData[0]; }
} 

spec file: 

describe('SelectedComponent', () =&gt; {
let component:SelectedComponent;
let fixture:ComponentFixture&lt;SelectedComponent
    &gt;; beforeEach(async(() =&gt; { TestBed.ConfigureTestingModule({
    declarations: [SelectedComponent],
    schemas:[CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
    imports:[modules],
    providers:[{provide: ActivatedRoute, UseValue: {**snapshot: {queryParams:
    {Ref: '123456-15/12/2021'**}}} }]
    }).compileComponents();
    }))

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

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

</code></pre>
",https://stackoverflow.com/questions/70364235/typeerror-cannot-read-properties-of-undefined-reading-split,"['angular', 'karma-jasmine']",3168,False,-1,2
Unit testing and mocking,"<p>I am new to ASP.NET Core MVC and I was wondering if any one could help me with the unit testing to remove a user from the database</p>
<p>Controller</p>
<pre><code>public async Task&lt;ActionResult&gt; RemoveIdAsync(string Id)
{
        try
        {
            var result = await _udService.RemoveId(Id);
            return Ok(result);
        }
        catch (ServiceException)
        {
            return _internalServerErrorStatusCode;
        }
}
</code></pre>
",https://stackoverflow.com/questions/66428652/unit-testing-and-mocking,"['c#', 'unit-testing', 'asp.net-core', 'graphql', 'mocking']",380,True,-1,2
React Unit-Testing - Could not find &quot;store&quot; in the context of &quot;Connect(Connect(AddUserProfile))&quot;,"<p>I tried to build a simple component that will popup to allow a user to create a new acocunt like below.</p>
<p>NewAccount.jsx</p>
<pre><code>import React from 'react';
import {
  Button, Modal, ModalHeader, ModalBody, ModalFooter,
} from 'reactstrap';
import UserProfile from '../UserProfile/AddNewUserProfile';
import { useHistory } from 'react-router-dom';

const NewAccount = React.memo((props) =&gt; {
  const closePopup = (e) =&gt; { props.onUserPopupClose(); };
  const history = useHistory()
  const userCreated = () =&gt; {
    props.userCreated();
  }

  return (
    &lt;Modal isOpen={props.open} toggle={closePopup} className={&quot;modal-dialog modal-lg&quot;}&gt;
      &lt;ModalHeader toggle={closePopup}&gt;New User&lt;/ModalHeader&gt;
      &lt;ModalBody&gt;
        &lt;UserProfile isAddNewUser={true} history={history} userCreated={userCreated} /&gt;
      &lt;/ModalBody&gt;
      &lt;ModalFooter&gt;
        &lt;Button color=&quot;secondary&quot; onClick={closePopup}&gt;Close&lt;/Button&gt;
      &lt;/ModalFooter&gt;
    &lt;/Modal&gt;
  );
});
export default NewAccount;
</code></pre>
<p>This is my NewAccount.test.js just to test out if it render the modal or not.</p>
<pre><code>import React from 'react';
import { screen, render, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import NewAccount from '../../components/UserManagement/NewAccount';

jest.mock('../../components/UserProfile', () =&gt; {
  const userprofile = () =&gt; &lt;div&gt;&lt;h4&gt;User Profile&lt;/h4&gt;&lt;/div&gt;;
  return userprofile;
});
describe('new user popup', () =&gt; {
  const userCreated = jest.fn();
  const onUserPopupClose = jest.fn();
  beforeEach(() =&gt; {
    render(&lt;NewAccount 
      open 
      onUserPopupClose={onUserPopupClose} 
      userCreated={userCreated}/&gt;);
  });
  describe('Structure', () =&gt; {
    it('should render the modal', () =&gt; {
      expect(screen.getByRole('dialog')).toBeInTheDocument();
    });
  });
});
</code></pre>
<p>This is the error that I got</p>
<pre><code>FAIL src/__tests__/UserManagement/NewAccount.test.js
  Stop Error
    ✓ should not error out due to no tests (popper.js.js) (2ms)
  new user popup
    Structure
      ✕ should render the modal (111ms)

  ● new user popup › Structure › should render the modal

    Could not find &quot;store&quot; in the context of &quot;Connect(Connect(AddUserProfile))&quot;. Either wrap the root component in a &lt;Provider&gt;, or pass a custom React context provider to &lt;Provider&gt; and the corresponding React context consumer to Connect(Connect(AddUserProfile)) in connect options.

      12 |   const onUserPopupClose = jest.fn();
      13 |   beforeEach(() =&gt; {
    &gt; 14 |     render(&lt;NewAccount 
         |     ^
      15 |       open 
      16 |       onUserPopupClose={onUserPopupClose} 
      17 |       userCreated={userCreated}/&gt;);

      at ConnectFunction (node_modules/react-redux/lib/components/connectAdvanced.js:259:15)
      at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14803:18)
      at updateFunctionComponent (node_modules/react-dom/cjs/react-dom.development.js:17034:20)
      at updateSimpleMemoComponent (node_modules/react-dom/cjs/react-dom.development.js:16972:10)
      at updateMemoComponent (node_modules/react-dom/cjs/react-dom.development.js:16861:14)
      at beginWork (node_modules/react-dom/cjs/react-dom.development.js:18682:16)
      at HTMLUnknownElement.callCallback (node_modules/react-dom/cjs/react-dom.development.js:188:14)
      at HTMLUnknownElement.callTheUserObjectsOperation (node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
      at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:318:25)
      at invokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
      at HTMLUnknownElementImpl._dispatch (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
      at HTMLUnknownElementImpl.dispatchEvent (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
      at HTMLUnknownElement.dispatchEvent (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
      at Object.invokeGuardedCallbackDev (node_modules/react-dom/cjs/react-dom.development.js:237:16)
      at invokeGuardedCallback (node_modules/react-dom/cjs/react-dom.development.js:292:31)
      at beginWork$1 (node_modules/react-dom/cjs/react-dom.development.js:23203:7)
      at performUnitOfWork (node_modules/react-dom/cjs/react-dom.development.js:22157:12)
      at workLoopSync (node_modules/react-dom/cjs/react-dom.development.js:22130:22)
      at performSyncWorkOnRoot (node_modules/react-dom/cjs/react-dom.development.js:21756:9)
      at node_modules/react-dom/cjs/react-dom.development.js:11089:24
      at unstable_runWithPriority (node_modules/scheduler/cjs/scheduler.development.js:653:12)
      at runWithPriority$1 (node_modules/react-dom/cjs/react-dom.development.js:11039:10)
      at flushSyncCallbackQueueImpl (node_modules/react-dom/cjs/react-dom.development.js:11084:7)
      at flushSyncCallbackQueue (node_modules/react-dom/cjs/react-dom.development.js:11072:3)
      at batchedUpdates$1 (node_modules/react-dom/cjs/react-dom.development.js:21862:7)
      at act (node_modules/react-dom/cjs/react-dom-test-utils.development.js:929:14)
      at render (node_modules/@testing-library/react/dist/pure.js:96:26)
      at Object.&lt;anonymous&gt; (src/__tests__/UserManagement/NewAccount.test.js:14:5)

  ● new user popup › Structure › should render the modal

    TestingLibraryElementError: Unable to find an accessible element with the role &quot;dialog&quot;

    There are no accessible roles. But there might be some inaccessible roles. If you wish to access them, then set the `hidden` option to `true`. Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole

    &lt;body
      class=&quot;&quot;
    &gt;
      &lt;div /&gt;
    &lt;/body&gt;

      19 |   describe('Structure', () =&gt; {
      20 |     it('should render the modal', () =&gt; {
    &gt; 21 |       expect(screen.getByRole('dialog')).toBeInTheDocument();
         |                     ^
      22 |     });
      23 |   });
      24 | });

      at Object.getElementError (node_modules/@testing-library/dom/dist/config.js:37:19)
      at node_modules/@testing-library/dom/dist/query-helpers.js:92:38
      at node_modules/@testing-library/dom/dist/query-helpers.js:64:17
      at getByRole (node_modules/@testing-library/dom/dist/query-helpers.js:108:19)
      at Object.&lt;anonymous&gt; (src/__tests__/UserManagement/NewAccount.test.js:21:21)

  console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
    Error: Uncaught [Error: Could not find &quot;store&quot; in the context of &quot;Connect(Connect(AddUserProfile))&quot;. Either wrap the root component in a &lt;Provider&gt;, or pass a custom React context provider to &lt;Provider&gt; and the corresponding React context consumer to Connect(Connect(AddUserProfile)) in connect options.]
        at reportException (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:62:24)
        at innerInvokeEventListeners (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:333:9)
        at invokeEventListeners (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
        at HTMLUnknownElementImpl._dispatch (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
        at HTMLUnknownElementImpl.dispatchEvent (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
        at HTMLUnknownElement.dispatchEvent (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
        at Object.invokeGuardedCallbackDev (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:237:16)
        at invokeGuardedCallback (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:292:31)
        at beginWork$1 (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:23203:7)
        at performUnitOfWork (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:22157:12) Error: Could not find &quot;store&quot; in the context of &quot;Connect(Connect(AddUserProfile))&quot;. Either wrap the root component in a &lt;Provider&gt;, or pass a custom React context provider to &lt;Provider&gt; and the corresponding React context consumer to Connect(Connect(AddUserProfile)) in connect options.
        at ConnectFunction (/home/user1/WebApplication/webapp1/node_modules/react-redux/lib/components/connectAdvanced.js:259:15)
        at renderWithHooks (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:14803:18)
        at updateFunctionComponent (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:17034:20)
        at updateSimpleMemoComponent (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:16972:10)
        at updateMemoComponent (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:16861:14)
        at beginWork (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:18682:16)
        at HTMLUnknownElement.callCallback (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:188:14)
        at HTMLUnknownElement.callTheUserObjectsOperation (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/generated/EventListener.js:26:30)
        at innerInvokeEventListeners (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:318:25)
        at invokeEventListeners (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:274:3)
        at HTMLUnknownElementImpl._dispatch (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:221:9)
        at HTMLUnknownElementImpl.dispatchEvent (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:94:17)
        at HTMLUnknownElement.dispatchEvent (/home/user1/WebApplication/webapp1/node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:231:34)
        at Object.invokeGuardedCallbackDev (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:237:16)
        at invokeGuardedCallback (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:292:31)
        at beginWork$1 (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:23203:7)
        at performUnitOfWork (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:22157:12)
        at workLoopSync (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:22130:22)
        at performSyncWorkOnRoot (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:21756:9)
        at /home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:11089:24
        at unstable_runWithPriority (/home/user1/WebApplication/webapp1/node_modules/scheduler/cjs/scheduler.development.js:653:12)
        at runWithPriority$1 (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:11039:10)
        at flushSyncCallbackQueueImpl (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:11084:7)
        at flushSyncCallbackQueue (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:11072:3)
        at batchedUpdates$1 (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom.development.js:21862:7)
        at act (/home/user1/WebApplication/webapp1/node_modules/react-dom/cjs/react-dom-test-utils.development.js:929:14)
        at render (/home/user1/WebApplication/webapp1/node_modules/@testing-library/react/dist/pure.js:96:26)
        at Object.&lt;anonymous&gt; (/home/user1/WebApplication/webapp1/src/__tests__/UserManagement/NewAccount.test.js:14:5)
        at Object.asyncJestLifecycle (/home/user1/WebApplication/webapp1/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:53:37)
        at /home/user1/WebApplication/webapp1/node_modules/jest-jasmine2/build/queueRunner.js:43:12
        at new Promise (&lt;anonymous&gt;)
        at mapper (/home/user1/WebApplication/webapp1/node_modules/jest-jasmine2/build/queueRunner.js:26:19)
        at /home/user1/WebApplication/webapp1/node_modules/jest-jasmine2/build/queueRunner.js:73:41

  console.error node_modules/react-dom/cjs/react-dom.development.js:19527
    The above error occurred in the &lt;ConnectFunction&gt; component:
        in ConnectFunction (at NewAccount.jsx:26)
        in div (created by ModalBody)
        in ModalBody (at NewAccount.jsx:25)
        in div (created by Modal)
        in div (created by Modal)
        in div (created by Transition)
        in Transition (created by Fade)
        in Fade (created by Modal)
        in div (created by Modal)
        in Portal (created by Modal)
        in Modal (at NewAccount.jsx:23)
        in Unknown (at NewAccount.test.js:14)
    
    Consider adding an error boundary to your tree to customize error handling behavior.


Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        3.745s, estimated 4s
</code></pre>
<p>I'm new to unit-testing .... so I don't know what I did wrong here :(. I have tried to google for few hours and I still can't figure out what wrong with this.</p>
<p>Also if you guys have some video/articles/documentation about how to do unit-testing for React.js noob like me, feel free to share them with me :(</p>
",https://stackoverflow.com/questions/65822304/react-unit-testing-could-not-find-store-in-the-context-of-connectconnecta,"['javascript', 'reactjs', 'unit-testing']",312,False,0,0
How to unit test a gRPC server&#39;s asynchronous methods?,"<p>Following the suggestions in <a href=""https://stackoverflow.com/questions/44718078/how-to-write-a-grpc-python-unittest"">this question</a> I was able to unit test the synchronous methods of my gRPC service (which is built with the <a href=""https://grpc.github.io/grpc/python/grpc_asyncio.html"" rel=""nofollow noreferrer""><code>grpc.aio</code></a> API) using the <a href=""https://pypi.org/project/grpcio-testing/"" rel=""nofollow noreferrer""><code>grpc_testing</code></a> library. However, when I follow <a href=""https://github.com/grpc/grpc/blob/7f6a27a4d3675adc0de263d291346aab2f46e733/src/python/grpcio_tests/tests/testing/_server_test.py#L77-L100"" rel=""nofollow noreferrer"">this example</a> on an asynchronous method of my gRPC service I get:</p>
<pre><code>ERROR    grpc_testing._server._rpc:_rpc.py:92 Exception calling application!
Traceback (most recent call last):
  File &quot;/home/jp/venvs/grpc/lib/python3.8/site-packages/grpc_testing/_server/_service.py&quot;, line 63, in _stream_response
    response = copy.deepcopy(next(response_iterator))
TypeError: 'async_generator' object is not an iterator
</code></pre>
<p>Looking through the <a href=""https://pypi.org/project/grpcio-testing/"" rel=""nofollow noreferrer""><code>grpc_testing</code></a> codebase and searching more broadly, I cannot find examples of unit testing async gRPC methods.  The closest thing I could find is an <a href=""https://github.com/nils-werner/pytest-grpc/tree/asyncio"" rel=""nofollow noreferrer"">unmerged branch</a> of <a href=""https://github.com/kataev/pytest-grpc"" rel=""nofollow noreferrer""><code>pytest-grpc</code></a>, but <a href=""https://github.com/nils-werner/pytest-grpc/blob/asyncio/pytest_grpc/tests/servicer.py"" rel=""nofollow noreferrer"">the example service</a> does not have any async methods.</p>
<p>Can anyone share an example of unit testing an asynchronous gRPC method in python?</p>
",https://stackoverflow.com/questions/66895906/how-to-unit-test-a-grpc-servers-asynchronous-methods,['grpc-python'],2126,True,0,3
How can I unit test Custom Date Deserializer using Java,"<p>I just started to learn Unit testing.</p>
<p>I would like to Unit test custom date deserializer which looks like this:</p>
<p><strong>CustomDateDeserializer.java</strong></p>
<pre><code>import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

public class CustomDateDeserializer extends JsonDeserializer {
    @Override
    public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {

        Long toParse = p.getLongValue();
        SimpleDateFormat format = new SimpleDateFormat(&quot;dd MMM yyyy HH:mm:ss z&quot;);
        format.setTimeZone(TimeZone.getTimeZone(&quot;GMT+1&quot;));

        String formattedActualDate = format.format(new Date(toParse));

        return formattedActualDate;
    }
}
</code></pre>
<p>What is the best way to test it?
Any advice appreciated.</p>
",https://stackoverflow.com/questions/66413620/how-can-i-unit-test-custom-date-deserializer-using-java,"['java', 'unit-testing']",837,True,2,1
Unit testing Room android - This job has not completed yet,"<p>I am currently unit testing my local data source which uses Room.
I created a test class:</p>
<pre><code>/**
 * Integration test for the [WatchListLocalDataSource].
 */
@RunWith(AndroidJUnit4::class)
@MediumTest
class WatchListLocalDataSourceTest {

    private lateinit var sut: WatchListLocalDataSourceImpl
    private lateinit var database: ShowsDatabase
    private lateinit var entityMapper: ShowEntityMapper

    private lateinit var testDispatcher: TestCoroutineDispatcher
    private lateinit var testScope: TestCoroutineScope

    @Before
    fun setup() {
        entityMapper = ShowEntityMapper()
        testDispatcher = TestCoroutineDispatcher()
        testScope = TestCoroutineScope(testDispatcher)
        val context = InstrumentationRegistry.getInstrumentation().context
        // using an in-memory database for testing, since it doesn't survive killing the process
        database = Room.inMemoryDatabaseBuilder(
            context,
            ShowsDatabase::class.java
        )
            .setTransactionExecutor(testDispatcher.asExecutor())
            .setQueryExecutor(testDispatcher.asExecutor())
            .build()

        sut = WatchListLocalDataSourceImpl(database.watchListDao(), entityMapper)
    }

    @After
    @Throws(IOException::class)
    fun cleanUp() {
        database.close()
    }

    @Test
    @Throws(Exception::class)
    fun observeWatchedShows_returnFlowOfDomainModel()  = testScope.runBlockingTest {

        val showId = 1
        sut.addToWatchList(mockShow(showId))

        val watchedShows: List&lt;Show&gt; = sut.observeWatchedShows().first()

        assertThat(&quot;Watched shows should contain one element&quot;, watchedShows.size == 1)
        assertThat(&quot;Watched shows element should be ${mockShow(showId).name}&quot;, watchedShows.first() == mockShow(showId))
    }
}
</code></pre>
<p>However, the test does not complete, noting:</p>
<pre><code>java.lang.IllegalStateException: This job has not completed yet
</code></pre>
<p>The actual method in the <code>sut</code> is:</p>
<pre><code>override suspend fun addToWatchList(show: Show) = withContext(Dispachers.IO) {
    watchListDao.insertShow(WatchedShow(entityMapper.mapFromDomainModel(show)))
}
</code></pre>
",https://stackoverflow.com/questions/65550564/unit-testing-room-android-this-job-has-not-completed-yet,"['android', 'android-room', 'kotlin-coroutines', 'android-unit-testing']",834,True,0,1
When testing controllers post method how do I mock primary key returned by MySql database,"<p>My xunit test is failing because the expected Id isn't updated by the database when unit testing.
How do I mock the id/primary key being created by the database?</p>
<pre><code>[HttpPost]
public async Task&lt;ActionResult&lt;AccountReadDto&gt;&gt; CreateAccountAsync(AccountCreateDto createAccountDto)
{
    var account = _mapper.Map&lt;Account&gt;(createAccountDto); // Id is int equal to 0
    await _accountRepo.CreateAccountAsync(account); // repo calls db and updates Id with pk
    _accountRepo.SaveChanges();

    var accountReadDto = _mapper.Map&lt;AccountReadDto&gt;(account);
    return CreatedAtRoute(nameof(GetAccountByIdAsync), new { AccountId = accountReadDto.AccountId }, accountReadDto);
}

[Fact]
public async Task CreateAccountAsync_NewAccount_ReturnsAccountReadDto()
{
    var expectedAccount = CreateRandomAccount(); // has id
    var createDto = _mapperStub.Map&lt;AccountCreateDto&gt;(expectedAccount); // doesn't have id

    _repoStub
        .Setup(repo =&gt; repo.CreateAccountAsync(expectedAccount))
        .Returns(Task.CompletedTask);
    var controller = new AccountController(_repoStub.Object, _mapperStub);

    var actionResult = await controller.CreateAccountAsync(createDto);

    var result = (actionResult.Result as CreatedAtRouteResult).Value as AccountReadDto;
    result.Should().BeEquivalentTo(
        expectedAccount,
        options =&gt; options.ComparingByMembers&lt;AccountReadDto&gt;().ExcludingMissingMembers() // excluding login info
    );
}
</code></pre>
",https://stackoverflow.com/questions/67390548/when-testing-controllers-post-method-how-do-i-mock-primary-key-returned-by-mysql,"['c#', 'mysql', '.net', 'model-view-controller', 'moq']",73,True,0,1
How to write a pytest or unittest on my code?,"<p>I am new to unit testing. I am trying to test if function is called and if the schedule time is correct on the below.</p>
<blockquote>
<p>The python filename is #schedule.py</p>
</blockquote>
<pre><code>def screenshot():
   ob=Screenshot_Clipping.Screenshot()
   driver.get(url)
   img_url=ob.full_Screenshot(driver, save_path = path)
   email_it(path)
   driver.close()
screenshot()
</code></pre>
",https://stackoverflow.com/questions/67014124/how-to-write-a-pytest-or-unittest-on-my-code,"['python', 'unit-testing', 'pytest', 'python-unittest', 'python-mock']",509,True,-1,1
Nestjs overrideProvider vs provider in unit testing,"<p>I see two ways of mocking services in NestJS for unit testing, the first one is the same as we define providers in real modules like:</p>
<pre class=""lang-js prettyprint-override""><code>const module = await Test.createTestingModule({
  providers: [
    UserService,
    {
      provide: getRepositoryToken(User),
      useValue: mockUsersRepository,
    }
  ],
}).compile();
</code></pre>
<p>And the other way with <code>overrideProvider</code> method. As following:</p>
<pre class=""lang-js prettyprint-override""><code>const module = await Test.createTestingModule({
  imports: [UserModule]
})
.overrideProvider(getRepositoryToken(User))
.useValue(mockUsersRepository)
.compile();
</code></pre>
<p>What is the difference?</p>
",https://stackoverflow.com/questions/69000993/nestjs-overrideprovider-vs-provider-in-unit-testing,"['unit-testing', 'nestjs', 'nestjs-testing']",4197,True,7,2
Asserting values of window object using jest,"<p>I am trying to assert the values of windows object using jest.
For example:
Asserting google tag manager's window.dataLayer values.</p>
<p>How can I implement that using unit testing jest framework?</p>
",https://stackoverflow.com/questions/69397585/asserting-values-of-window-object-using-jest,"['unit-testing', 'jestjs', 'google-tag-manager', 'window-object']",548,False,0,1
How to do unit testing for guard in nest?,"<p>I'v done unit testing for controllers and services like this:</p>
<pre><code>import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

describe('CatsController', () =&gt; {
 let catsController: CatsController;
 let catsService: CatsService;

 beforeEach(() =&gt; {
   catsService = new CatsService();
   catsController = new CatsController(catsService);
 });

 describe('findAll', () =&gt; {
   it('should return an array of cats', async () =&gt; {
     const result = ['test'];
     jest.spyOn(catsService, 'findAll').mockImplementation(() =&gt; result);

     expect(await catsController.findAll()).toBe(result);
   });
 });
});
</code></pre>
<p>but I hava a global guard, this guard is independent of any controller or service, I do not know how to write the .spec file. PLZ</p>
",https://stackoverflow.com/questions/67496417/how-to-do-unit-testing-for-guard-in-nest,"['typescript', 'unit-testing', 'jestjs', 'nestjs']",3941,True,5,1
How to mock the controller,"<p>I have a method in a controller that check's the user's role to see which page the user should be redirected.
I am trying to do unit testing for the following code</p>
<pre><code>public class HomeController: Controller {

    //...

    public IActionResult Home()
    {
        if (User.IsInRole(&quot;Administrators&quot;)
        {
            return RedirectToAction(&quot;/administrator&quot;);
        }
        else
        {
            return RedirectToAction(&quot;/user&quot;);
        }
    }

    //...other actions
}
</code></pre>
",https://stackoverflow.com/questions/66355498/how-to-mock-the-controller,"['c#', 'asp.net-core', 'asp.net-core-mvc', 'nunit']",745,True,1,1
Need to create unit testcase using jasmine marble in withLatestFrom,"<p>I am completely new at doing unit testing using jasmine-marble.</p>
<p>I have a component, with the following code:</p>
<pre class=""lang-js prettyprint-override""><code>getData() : void {
  this.firstObservableClass.pipe(withLatestFrom(this.secObservableClass))
    .subscribe(([firstObservResult, secObserveResult]) =&gt; {
       // expected subscription results are true and true
    });
}
</code></pre>
<p>I the spec I have:</p>
<pre class=""lang-js prettyprint-override""><code>const expected = cold('(cd|)', { c: true,d: true});
expect(app.getData).toBeObservable(expected)
</code></pre>
<p>And getting an error while running ng test:</p>
<pre class=""lang-sh prettyprint-override""><code>Expected $.length = 1 to equal 4.
Expected $[0].notification.kind = 'N' to equal 'C'.
</code></pre>
",https://stackoverflow.com/questions/69065540/need-to-create-unit-testcase-using-jasmine-marble-in-withlatestfrom,"['angular', 'rxjs', 'karma-jasmine', 'ngrx', 'jasmine-marbles']",51,False,1,0
How to unit test callback based method (Firebase&#39;s verifyPhoneNumber(...)),"<p>I'm trying to unit test a my AuthenticationService class, which acts as an abstraction of Flutter's plugin <code>firebase_auth</code>. Specifically, I want to test following method:</p>
<pre><code>Future&lt;void&gt; startAuthFlow(String phoneNumber) async {
  await _firebaseAuth.verifyPhoneNumber(
    phoneNumber: phoneNumber,
    verificationCompleted: _onVerificationCompleted,
    verificationFailed: _onVerificationFailed,
    codeSent: _onCodeSent,
    codeAutoRetrievalTimeout: _onCodeAutoRetrievalTimeout,
  );
}
</code></pre>
<p>I'm not sure about how to approach the unit testing, as I would like to assure that after SMS is sent, verification is completed, etc, the logic in the private callbacks is executed. However, I don't know how to mock such a function.</p>
<p>I've also thought about the possibility of just unit-testing the callbacks independently, and considering their calling by <code>_firebaseAuth.verifyPhoneNumber</code> as subject of an integration test. However, as those callbacks are private, there is no a good way to test them.</p>
",https://stackoverflow.com/questions/69130366/how-to-unit-test-callback-based-method-firebases-verifyphonenumber,"['flutter', 'unit-testing', 'dart', 'firebase-authentication', 'callback']",113,False,2,0
initializeAdminApp and clearFirestoreData method no longer available after update to @firebase/rules-unit-testing 2.0,"<p>I just update my dependency to <code>&quot;@firebase/rules-unit-testing&quot;: &quot;^2.0.0&quot;</code></p>
<p>and it breaks my code. my code was</p>
<pre><code>import * as firebase from &quot;@firebase/rules-unit-testing&quot;;

function getAdminFirestore() {
    return firebase.initializeAdminApp({ projectId: projectID }).firestore();
}

function getFirestore(auth?: TokenOptions) {
    return firebase.initializeTestApp({ projectId: projectID, auth: auth }).firestore();
}

beforeEach(async () =&gt; {
    await firebase.clearFirestoreData({ projectId: projectID });
});

after(async () =&gt; {
    await firebase.clearFirestoreData({ projectId: projectID });
});
</code></pre>
<p>but I have a lot of errors because some methods no longer available like this</p>
<p><a href=""https://i.stack.imgur.com/Le0A3.png"" rel=""noreferrer""><img src=""https://i.stack.imgur.com/Le0A3.png"" alt=""enter image description here"" /></a></p>
<p>so what is the equivalent method in firebase/rules-unit-testing 2.0.0 ?</p>
",https://stackoverflow.com/questions/69060666/initializeadminapp-and-clearfirestoredata-method-no-longer-available-after-updat,"['node.js', 'firebase', 'firebase-security', 'firebase-tools']",530,True,8,1
Unit test on a 16-bit embedded target,"<p>I am currently trying to evaluate the best way of unit testing some code written for a <a href=""https://www.microchip.com/wwwproducts/en/dsPIC33EP512MU810"" rel=""nofollow noreferrer"">16-bit based dsPIC device</a>. The compiler used for compiling the C code for the target is <a href=""https://www.microchip.com/en-us/development-tools-tools-and-software/mplab-xc-compilers"" rel=""nofollow noreferrer"">Microchip's XC16</a>.</p>
<p>I was not able to find any emulation tools, such as QEMU for ARM. I would really like to use a unit testing framework like GTest or Cpputest for this. My last resort is to run these unit test on the target, but the chance of using any framework there is legible (build and space concerns). Another idea that popped in my head is to use GCC on the host with m16 flag to generate 16-bit code, but that a workaround that does not guarantee the same results, since XC16 is a different compiler (even though based on GCC).</p>
<p>Is there a generic, proper way of approaching this problem? The goal is to be able to use a unit testing framework, on a host PC, for a target with a different architecture.</p>
",https://stackoverflow.com/questions/65577416/unit-test-on-a-16-bit-embedded-target,"['unit-testing', 'embedded', 'cross-compiling', 'bare-metal']",393,True,-1,1
How to access the database from unit test in Fast API?,"<p>I'm struggling accessing SQLAlchemy while unit testing in Fast API.</p>
<pre><code>def test_successful_register_ios():
    response = client.post(&quot;/register/&quot;,headers={},json={})
    assert response.status_code == 201
    device = get_db().query(Device).get(&quot;a1&quot;)
    assert device.expires_at == mydate
</code></pre>
<blockquote>
<p>AttributeError: 'generator' object has no attribute 'query'</p>
</blockquote>
<p>In my test class I'm applying all the overrides:</p>
<pre><code>from database.database import Base
from main import app, get_db

settings = Settings()
engine = create_engine(settings.sqlalchemy_database_uri)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base.metadata.create_all(bind=engine)
client = TestClient(app)

def override_get_db():
    try:
        db = TestingSessionLocal()
        yield db
    finally:
        db.close()

app.dependency_overrides[get_db] = override_get_db
</code></pre>
<p>I don't think <code>get_db().query(Device).get(&quot;a1&quot;)</code> is the right way to do it. But I'm quite stuck and the documentation doesn't cover this case.</p>
",https://stackoverflow.com/questions/65982681/how-to-access-the-database-from-unit-test-in-fast-api,"['unit-testing', 'sqlalchemy', 'fastapi']",5493,True,13,1
How do you write a java unit test of a class method that does not return a value?,"<p>I am a newbie to Java unit testing and need help writing a unit test that just needs to handle 2 paths of an &quot;if&quot; statement where the method has no return value.</p>
<pre><code>public class Consumer extends KafkaConsumer {
    private final MessageService service;

    public Consumer(MessageService service) {
        this.service = service;
    }

    @Override
    protected void processRecords(ConsumerRecords&lt;Long, String&gt; records) {
        for (ConsumerRecord&lt;Long, String&gt; records) {
            if (record.value().startsWith(&quot;{&quot;)) {
                OldFormatMessageObject mo = new OldFormatMessageObject(record.value());
                service.processMessage(mo);
            } else if (record.value().startsWith(&quot;metadata&quot;)) {
                NewFormatMessageObject mo = new NewFormatMessageObject(record.value());
                service.processMessage(mo);
            }
        }
    }
</code></pre>
",https://stackoverflow.com/questions/70379390/how-do-you-write-a-java-unit-test-of-a-class-method-that-does-not-return-a-value,"['java', 'unit-testing']",1076,True,1,1
unit test with jUnit in java soft delete method,"<p>I wanted some help to unit test a controller in java, with jUnit and using the Spring Mock MVC tool. I don't know much about unit testing.</p>
<p>Controller:</p>
<pre><code>@DeleteMapping(&quot;/{id_document}/delete&quot;)
    public void deleteById (@PathVariable (value = &quot;id_document&quot;) String documentId) {
        documentService.deleteDocument(documentId);
    }
</code></pre>
<p>** It's a soft delete</p>
",https://stackoverflow.com/questions/68444311/unit-test-with-junit-in-java-soft-delete-method,"['java', 'unit-testing', 'junit', 'controller']",151,True,-1,1
Testing library asserting multiple objects are equal,"<p>It's common in libraries designed for unit testing to have different methods like</p>
<pre><code>assertEquals
assertTrue
assertFalse
</code></pre>
<p>etc. (e.g. Mockito for instance).</p>
<p>However, these methods compare (equals method f.e.) only two arguments.
Let's say i have four values, that I want to compare.</p>
<pre><code>Integer a = 4; 
Integer b = 4; 
Integer c = 4; 
Integer d = 4;
</code></pre>
<p>If I want to compare them, I have to write four lines like this:</p>
<pre><code> assertEquals(a, 4);
 assertEquals(b, 4);
 assertEquals(c, 4);
 assertEquals(d, 4);
</code></pre>
<p>What I am searching for is, a library that could take more arguments and check if all are equal</p>
<pre><code> assertAllEquals(a, b, c, d, 4);
</code></pre>
<p>I know that might be not implemented, since there was a discussion in unit-testing only asserting one fact at a time (and this could break the concept). Still, is there any testing library that provides that handy feature?</p>
",https://stackoverflow.com/questions/69312195/testing-library-asserting-multiple-objects-are-equal,"['java', 'unit-testing']",516,True,1,1
Why does my Flask app return a response with status code 308 under test?,"<p>I'm unit testing my Flask app.
The code under test is as follows:</p>
<pre class=""lang-py prettyprint-override""><code>@app.route(&quot;/my_endpoint/&quot;, methods=[&quot;GET&quot;])
def say_hello():
    &quot;&quot;&quot;
    Greets the user.
    &quot;&quot;&quot;
    name = request.args.get(&quot;name&quot;)
    return f&quot;Hello {name}&quot;

</code></pre>
<p>The test looks like this:</p>
<pre class=""lang-py prettyprint-override""><code>class TestFlaskApp:
    def test_my_endpoint(self):
        &quot;&quot;&quot;
        Tests that my endpoint returns the result as plain text.
        :return:
        &quot;&quot;&quot;
        client = app.test_client()
        response = client.get(&quot;/my_endpoint?name=Peter&quot;)
        assert response.status_code == status.HTTP_200_OK
        assert response.data.decode() == &quot;Hello Peter&quot;
</code></pre>
<p>The error is:</p>
<blockquote>
<p>Expected :200
Actual   :308</p>
</blockquote>
<p>So instead of &quot;OK&quot; (200) I'm getting a &quot;Permanent Redirect&quot; (308)</p>
",https://stackoverflow.com/questions/66612823/why-does-my-flask-app-return-a-response-with-status-code-308-under-test,"['flask', 'pytest']",1057,True,3,2
how to unit test UIApplication extension,"<p>Suppose I use <a href=""https://gist.github.com/houze2311/dcfd2559975974b0e64f319b51d12a18"" rel=""nofollow noreferrer"">this</a> code that extracts the top most viewController</p>
<pre><code>import UIKit

extension UIApplication {
    
    class func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -&gt; UIViewController? {
        
        if let navigationController = base as? UINavigationController, navigationController.viewControllers.count &gt; 0 {
            return topViewController(navigationController.visibleViewController)
        }
        
        if let tabBarController = base as? UITabBarController {
            if let selected = tabBarController.selectedViewController {
                return topViewController(selected)
            }
        }
        
        if let presentedViewController = base?.presentedViewController {
            return topViewController(presentedViewController)
        }
        
        return base
    }
    
}
</code></pre>
<p>How do I facilitate unit testing of this code? I would need to use an instance of <code>UIApplication.shared</code>. Any tips would be appreciated.</p>
",https://stackoverflow.com/questions/66131296/how-to-unit-test-uiapplication-extension,"['ios', 'swift']",176,True,0,1
How can I test swiper with Jest?,"<p>I'm creating unit testing of Swiper using Jest.</p>
<p>Here is my code:</p>
<p><a href=""https://codesandbox.io/s/swiper-default-react-forked-v0dnz?file=/src/App.test.jsx"" rel=""noreferrer"">https://codesandbox.io/s/swiper-default-react-forked-v0dnz?file=/src/App.test.jsx</a></p>
<pre><code>● Test suite failed to run

    Cannot find module 'swiper/react' from 'src/App.jsx'

    Require stack:
      src/App.jsx
      src/App.test.jsx

      1 | import React from &quot;react&quot;;
      2 | // Import Swiper React components
    &gt; 3 | import { Swiper, SwiperSlide } from &quot;swiper/react&quot;;
        | ^
      4 |
      5 | // Import Swiper styles
      6 | import &quot;swiper/css&quot;;

      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:322:11)
      at Object.&lt;anonymous&gt; (src/App.jsx:3:1)
</code></pre>
<p>This error has been reported all the time, but the program can run normally. Can anyone help me solve this problem?</p>
",https://stackoverflow.com/questions/69249400/how-can-i-test-swiper-with-jest,"['jestjs', 'swiper.js']",7507,True,10,4
How to write test case to if Condition which is in UseEffect in react js,"<p>I am new to unit testing, I tried writing this simple test case but not able to do it.
Could some one help me to write test case for if condition in useEffect.</p>
<pre><code>import React, { useEffect } from &quot;react&quot;;
import { useDispatch, useSelector } from &quot;react-redux&quot;;
    
const Greet = () =&gt; {
      const dispatch = useDispatch();
      //I am getting data from redux file
      const stateData = useSelector((state) =&gt; state.stateDatalist);
      const countryData = useSelector((state) =&gt; state.CountryDatalist);
      useEffect(() =&gt; {
        if (stateData.length === 0 &amp;&amp; countryData.length === 0) {
          // calling another API data
          dispatch(getDetails());
        }
      }, []);
    
      return (
        &lt;div&gt;
          &lt;h1&gt;Hello&lt;/h1&gt;
        &lt;/div&gt;
      );
};
    
export default Greet;
</code></pre>
",https://stackoverflow.com/questions/68904328/how-to-write-test-case-to-if-condition-which-is-in-useeffect-in-react-js,"['reactjs', 'react-redux', 'jestjs', 'react-hooks', 'enzyme']",3966,True,-1,1
"Angular Unit Test : Expected 3 arguments, but got 1","<p>I'm currently doing unit testing of an Angular app. I'm new to Angular Unit Testing.
I have downloaded the angular app from <a href=""https://github.com/gothinkster/angular-realworld-example-app"" rel=""nofollow noreferrer"">https://github.com/gothinkster/angular-realworld-example-app</a> for the interest of time. As I'm new to Unit Test I saw some videos related to unit test from <a href=""https://www.youtube.com/watch?v=ylJUkPlmdAg"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=ylJUkPlmdAg</a>, and <a href=""https://www.youtube.com/watch?v=45BuZAfFU0o"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=45BuZAfFU0o</a></p>
<p>I'm trying to unit test of <code>HomeComponent</code>. You can find the HomeComponent code from <a href=""https://github.com/gothinkster/angular-realworld-example-app/blob/master/src/app/home/home.component.ts"" rel=""nofollow noreferrer"">https://github.com/gothinkster/angular-realworld-example-app/blob/master/src/app/home/home.component.ts</a>. The <code>home.component.spec.ts</code> file code is under:</p>
<pre><code>import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ApiService, TagsService, UserService, JwtService } from '../core';
import { HttpClient, HttpErrorResponse, HttpClientModule, HttpHandler } from '@angular/common/http';

import { HomeComponent } from './home.component';
import { of } from 'rxjs';

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

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [ HomeComponent ],
      providers: [
        TagsService, 
        UserService, 
        ApiService, 
        JwtService, 
        HttpClient, 
        HttpClientModule, 
        HttpHandler
      ]
    })
    .compileComponents();
  });

  beforeEach(() =&gt; {
    // fixture = TestBed.createComponent(HomeComponent);
    // component = fixture.componentInstance;
    // fixture.detectChanges();

    TAGS = [{&quot;tags&quot;:[&quot;HuManIty&quot;,&quot;Hu‌Man‌Ity&quot;,&quot;Gandhi&quot;,&quot;HITLER&quot;,&quot;SIDA&quot;,&quot;BlackLivesMatter&quot;,&quot;Black‌Lives‌Matter&quot;,&quot;test&quot;,&quot;dragons&quot;,&quot;butt&quot;]}];

    mockTagsService = jasmine.createSpyObj(['getAll']);
    component = new HomeComponent(mockTagsService);
  });

  // it(&quot;should create the component&quot;, () =&gt; {

  //   expect(component).toBeTruthy();

  // });
  
  it(&quot;getall tags&quot;, () =&gt; {
    mockTagsService.getAll.and.returnValue(of(true));
  });
});
</code></pre>
<p>The Visual Studio code shows an error message <code>Expected 3 arguments, but got 1</code> in here: <code>component = new HomeComponent(mockTagsService);</code>. Its also suggesting that - <code>home.component.ts(14, 5): An argument for 'tagsService' was not provided.</code>.</p>
<p>How can I rectify the issue?</p>
",https://stackoverflow.com/questions/67855850/angular-unit-test-expected-3-arguments-but-got-1,"['angular', 'angular-unit-test']",749,False,-1,1
Unit test before the build in. Net azure pipelines,"<p>How do we include unit test in .Net azure build pipeline. Unit testing should happen before before the build process and when the unit test is Succeeded only then the build should happen.</p>
",https://stackoverflow.com/questions/69253187/unit-test-before-the-build-in-net-azure-pipelines,"['azure', 'azure-devops', 'azure-pipelines']",964,True,-1,1
.NET Core/Standard: unable to install Microsoft.NET.Test.Sdk,"<p>Using:<br>
<a href=""https://i.stack.imgur.com/hJGkS.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/hJGkS.png"" alt=""Visual Studio Community 2019 v16.9.4"" /></a></p>
<p>Unable to install <strong>Microsoft.NET.Test.Sdk</strong> (in .NET Core/Standard project for unit testing), getting this following error:<br>
<a href=""https://i.stack.imgur.com/oFHL2.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/oFHL2.png"" alt=""Unable to find package 'microsoft.net.test.sdk' at source ''"" /></a></p>
<p>I can install other packages, like <strong>NUnit</strong> and <strong>NUnit3TestAdapter</strong>.</p>
<p>I have the following package sources configured:<br>
<a href=""https://i.stack.imgur.com/GB8ds.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/GB8ds.png"" alt=""Package Sources"" /></a></p>
",https://stackoverflow.com/questions/67433146/net-core-standard-unable-to-install-microsoft-net-test-sdk,"['visual-studio', 'unit-testing', '.net-core', 'nuget']",256,False,0,1
"C# unit testing MoQ, Mock DB context, issue when transactions are used","<p>I need to write unit testing for legacy code. I'm using MoQ for wring DB Context based unit testing.  One repository method contains saving 2 entities in a transaction.</p>
<p>And when the test execution hit the dbContext.Database.BeginTransaction() it gives the error &quot;No connection string named 'LimaV3DbContext' could be found in the application config file&quot;.</p>
<p>It seems the test trying the execute the actual db context rather than using the mock db context. Is there a way to force the test execution to use the mock db context used in the test initialization.</p>
<p>I've setup the tests based on the following article.</p>
<p><a href=""https://learn.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking</a></p>
",https://stackoverflow.com/questions/68405222/c-unit-testing-moq-mock-db-context-issue-when-transactions-are-used,"['c#', 'unit-testing', 'moq']",457,False,0,0
How to unit test when using LocaleKeys with easy_localization?,"<p>I'm unit testing a login method that uses <code>LocaleKeys.errors_msg.tr()</code> for an error message. I get the following error when my unit test runs:</p>
<pre><code>NoSuchMethodError: The method 'get' was called on null.
Receiver: null
Tried calling: get(&quot;errors.msg&quot;)
</code></pre>
<p>How do I avoid this error so that my test passes?</p>
",https://stackoverflow.com/questions/66010742/how-to-unit-test-when-using-localekeys-with-easy-localization,"['flutter', 'unit-testing', 'localization']",442,False,0,0
ignite microservice cicd issues,"<p>I am implementing an Ignite cluster with data node, service, node and API node (Spring Boot with embedded ignite client). I have common POJO classes and DTO. Is there a good solution to store all nodes at single repository (sharing common POJO) to implement entire unit testing for the cluster. Same time I need to separate cicd pipelines for different node commits.
1st target: redeploy all nodes when the changes in common POJOs.
2nd target: deploy service nodes only when business logic changes.</p>
<p>My goal is complex unit-testing and change safety for neighbor nodes.
Also, if it matters, we plan to put each node to a docker container.</p>
",https://stackoverflow.com/questions/66025789/ignite-microservice-cicd-issues,"['java', 'git', 'ignite']",64,True,0,1
Getting Cannot find module &#39;react-apollo/test-utils&#39; error in jest teact native,"<p>I am doing unit testing using jest . But getting below error .I tried some solutions but still same . Please suggest me where I am wrong .</p>
<p>FAIL  <strong>tests</strong>/login-test.js
● Test suite failed to run</p>
<pre><code>Cannot find module 'react-apollo/test-utils' from 'login-test.js'

  3 | import Login from '../app/components/Login';
  4 | import LoginContainer from '../app/components/container/LoginContainer';
&gt; 5 | import { MockedProvider } from 'react-apollo/test-utils';
    | ^
</code></pre>
<p>//  package.json</p>
<pre><code>&quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;7.9.0&quot;,
    &quot;@babel/runtime&quot;: &quot;7.9.2&quot;,
    &quot;@react-native-community/eslint-config&quot;: &quot;^0.0.5&quot;,
    &quot;babel-cli&quot;: &quot;^6.26.0&quot;,
    &quot;babel-jest&quot;: &quot;^24.9.0&quot;,
    &quot;eslint&quot;: &quot;6.8.0&quot;,
    &quot;jest&quot;: &quot;^24.9.0&quot;,
    &quot;jetifier&quot;: &quot;^1.6.4&quot;,
    &quot;metro-react-native-babel-preset&quot;: &quot;^0.56.0&quot;,
    &quot;react-test-renderer&quot;: &quot;16.8.6&quot;
  },
  &quot;jest&quot;: {
    &quot;preset&quot;: &quot;react-native&quot;,
    &quot;collectCoverage&quot;: true,
    &quot;coverageReporters&quot;: [
      &quot;json&quot;,
      &quot;html&quot;
    ],
    &quot;setupFiles&quot;: [
      &quot;./jestSetupFile.js&quot;,
      &quot;./node_modules/react-native-gesture-handler/jestSetup.js&quot;
    ],
    &quot;transformIgnorePatterns&quot;: [
      &quot;node_modules/(?!react-native|native-base-shoutem-theme|@shoutem/animation|@shoutem/ui|tcomb-form-native|@react-native-community/async-storage|native-base/node_modules/react-native-vector-icons|react-navigation|@codler/react-native-keyboard-aware-scroll-view|react-native-device-info|rn-sliding-up-panel|@react-native-community/masked-view|@react-navigation/bottom-tabs/node_modules/react-native-iphone-x-helper|rn-tooltip|@react-native-community/datetimepicker|node_modules/react-native-tab-view|jsbarcode|@react-native-community/art|@react-native-firebase/analytics|@react-native-firebase|jail-monkey|@dudigital/react-native-zoomable-view/src/ReactNativeZoomableView|@haskkor/react-native-pincode|Platform)&quot;
    ]
  },
  &quot;rnpm&quot;: {
    &quot;assets&quot;: [
      &quot;./assets/fonts/&quot;
    ]
  }
</code></pre>
",https://stackoverflow.com/questions/70076468/getting-cannot-find-module-react-apollo-test-utils-error-in-jest-teact-native,"['reactjs', 'react-native', 'jestjs', 'graphql', 'react-apollo']",1141,True,1,1
Unit testing a c# Method using Moq,"<p>I'm new to unit testing and the language c sharp and I'm trying to unit test by mocking <code>ISessionStorageService</code> to test the <code>HasGlobaladminaccess</code>  function but my setup does not seem to work as expected.</p>
<pre class=""lang-cs prettyprint-override""><code>public class Context
{
    public asyncTask&lt;bool&gt;HasGlobalAdminAccessAsync(Blazored.SessionStorage.ISessionStorageService sessionStorage)
    {
        return await HasAccessAsync(sessionStorage, Config.Constants.HAS_GLOBALE_ADMIN_ACCESS);
    }

    private async Task&lt;bool&gt; HasAccessAsync(Blazored.SessionStorage.ISessionStorageService sessionStorage, string sessionStorageKey)
    {
        ILogger _logger = Log.ForContext&lt;ContextHelpers&gt;();

        try
        {
            _logger.Debug(&quot;HasAccessAsync({sessionStorageKey})&quot;, sessionStorageKey);
            var access = await sessionStorage.GetItemAsync&lt;bool&gt;(sessionStorageKey);
            _logger.Debug(&quot;HasAccessAsync({sessionStorageKey})::access={access}&quot;, sessionStorageKey, access);
            return access;
        }
        catch (Exception ex)
        {
            _logger.Debug(&quot;HasAccessAsync({sessionStorageKey})::exception={ex}&quot;, sessionStorageKey, ex.Message);
            return false;
        }
    }
}
</code></pre>
<p>My test method</p>
<pre class=""lang-cs prettyprint-override""><code>private readonly Mock&lt;ISessionStorageService&gt; MockStorage = new Mock&lt;ISessionStorageService&gt;();

[Fact()]
public async Task HasGlobalAdminAccessAsyncTest()
{
    string guid = System.Guid.NewGuid().ToString();
    Context context = new Context();
    MockStorage.Setup(foo =&gt; foo.GetItemAsync&lt;bool&gt;(guid)).ReturnsAsync(true);
    var person = await context.HasGlobalAdminAccessAsync(MockStorage.Object);
    Assert.True(person , guid);
}
</code></pre>
",https://stackoverflow.com/questions/68757431/unit-testing-a-c-method-using-moq,"['c#', 'unit-testing', 'moq']",156,True,1,1
"Unit testing, assert equals if difference is not bigger than 1","<p>Im new to Unit testing. I use Junit4, I have to compare two double numbers. But if difference is not longer than 1, it should pass.
For example:</p>
<pre><code>Assert.assertEquals(240, 241); //should pass
Assert.assertEquals(240, 239); //should pass

Assert.assertEquals(240, 242); //should fail
Assert.assertEquals(240, 238); //should fail
</code></pre>
<p>Is there way to implement it?</p>
",https://stackoverflow.com/questions/66007085/unit-testing-assert-equals-if-difference-is-not-bigger-than-1,"['java', 'unit-testing', 'testing', 'junit4']",193,True,0,2
How do I unit test an angular component that subscribes to an EventEmitter from a service?,"<p>I have a component that looks like this:</p>
<pre><code>export class MyComponent {
    myattr: boolean = true;
    constructor(public myService: MyService) {
        this.myService.stateUpdate.subscribe((event: number) =&gt; {
            this.myattr = event == 10;
        });
    }
</code></pre>
<p>the service:</p>
<pre><code>export class MyService {
    stateUpdate: EventEmitter&lt;number&gt; = new EventEmitter&lt;number&gt;();
    onSomeEvent(): void {
        this.stateUpdate.emit(130);
    }
}
</code></pre>
<p>my attempt at unit testing:</p>
<pre><code>    beforeEach(() =&gt; {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        component.myService = new MyService();
    });
    it(&quot;emitting 130 should set myattr to false&quot;, async()=&gt;{
        component.myService.stateUpdate.subscribe((event: number) =&gt; {
            expect(event).toEqual(130); // this is detected correctly
        })
        component.myService.onSomeEvent();
        fixture.whenStable();
        expect(component.myattr).toEqual(false); // this does not work
    });
</code></pre>
<p>Basically, I want to test what happens when whatever code inside <code>subscribe</code> finishes executing. How do I do this?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/66200312/how-do-i-unit-test-an-angular-component-that-subscribes-to-an-eventemitter-from,"['angular', 'typescript', 'jasmine', 'karma-jasmine', 'angular-event-emitter']",990,False,0,3
How to make a new instance method call in a java class do nothing in unit testing,"<p>In the method below, how do i ensure that while unit testing that the call to
new Job instance
does nothing and skips over to other code?</p>
<pre><code>public class TestedClass {
  public void methodToBeTested() {
    new Job(&quot;abc&quot;).start(&quot;123&quot;, &quot;ggg&quot;); //make this do nothing in unit test
    //other code
  }
}

public class Job {
  public String start(String a, String b){
    //some code
  }
}
</code></pre>
<p>Maybe using PowerMock, @Spy or simply mock?</p>
",https://stackoverflow.com/questions/67803561/how-to-make-a-new-instance-method-call-in-a-java-class-do-nothing-in-unit-testin,"['java', 'unit-testing', 'junit', 'mockito']",63,False,0,0
Unit tests for Gridgain Client,"<p>Can I know a method to implement unit test for Gridgain client written in maven project as thick client. Need to test SQL, Transactions, locking and other basic APIs of cache features in unit testing.</p>
",https://stackoverflow.com/questions/68570243/unit-tests-for-gridgain-client,"['maven', 'ignite', 'gridgain']",70,True,1,1
How to unit test a model controller using a singleton,"<p>I went to a boot camp for coding some time ago and while they were very good, they didn't teach anything about unit testing. I've been doing some self-teaching about unit testing and the idea of TDD makes so much sense on why you would do it. I recently went back to some of my old apps and wanted to try unit testing them, but I feel like I can't make heads or tails of it with how they taught. Here is a few bits of code, maybe someone could help me understand how to make sense of this.</p>
<p>Model</p>
<pre><code>import Foundation

struct Entry {
    let title: String
    let body: String
}

</code></pre>
<p>Model Controller</p>
<pre><code>import Foundation

class EntryController {
    //Singleton
    static let shared = EntryController()

    //Source of Truth
    var entries: [Entry] = []

    //CRUD functions
    func newEntry(title: String, body: String) {
        let entry = Entry(title: title, body: body)
        entries.append(entry)
    }

    func updateEntry(title: String, body: String, entry: Entry) {
        entry.title = title
        entry.body = body
    }

    func destroyEntry(entry: Entry) {
        guard let index = entries.index(of: entry) else {return}
        entries.remove(at: index)
    }
}
</code></pre>
<p>View Controller</p>
<pre><code>import UIKit

class EntryViewController: TableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {
        return EntryController.shared.entries.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;entry&quot;, for: indexPath) //reuse identifier declared on storyboard
        let entry = EntryController.shared.entries[indexPath.row]
        
        cell.textLabel.text = entry.title
        cell.detailTextLabel.text = entry.body
        
        return cell
    }
}
</code></pre>
<p>There's a bit more code than this, but I put up what effectively amounts to three different files of code here. The question I have is how would I test the crud functions in the singleton. Is there more that I should test than just the CRUD functions, does unit testing cover more than just testing individual functions? And if I made the CRUD functions static instead, how would those be unit tested instead. Also, how does one unit test a UIViewController? I've done more than a little searching online, but I'm really struggling to make sense of the answers, in part because the answers are given on a much higher level than I am.</p>
<p>Any help would be appreciated.</p>
<p>.....</p>
<p>Edit: I should mention that I think I understand how to mock a class and create Protocols to be inherited from for both the production class and the mocked class if that helps.</p>
",https://stackoverflow.com/questions/68837206/how-to-unit-test-a-model-controller-using-a-singleton,"['swift', 'unit-testing']",64,False,0,0
store is undefined in vue 3 class component unit testing,"<p>I am new to unit testing in vue 3 class component. I getting error says store is undefined. Here is my code in Home.vue file.</p>
<pre><code>&lt;script lang=&quot;ts&quot;&gt;
import { Options, Vue } from &quot;vue-class-component&quot;;
import HelloWorld from &quot;@/components/HelloWorld.vue&quot;;
import { useStore } from &quot;vuex&quot;;
import { key } from &quot;@/store&quot;;
import { ProductType } from &quot;@/types/commonTypeDefinitions&quot;;

@Options({
  components: {
    HelloWorld,
  },
})
export default class Home extends Vue {
  store = useStore(key);
  get getAllProducts() {
    return this.store.state.products ? this.store.state.products.groups : null;
  }
  mounted() {
    if (!this.store.state.products) {
      this.store.dispatch(&quot;getJsonData&quot;);
    }

  }
  goToDetail(item: ProductType) {
    localStorage.setItem(&quot;productDetail&quot;, JSON.stringify(item));
    this.store.commit(&quot;setProductDetail&quot;, item);
    const name = item.name.replaceAll(&quot; &quot;, &quot;-&quot;);
    console.log(name);
    this.$router.push(&quot;/detail/&quot; + name);
  }
}
&lt;/script&gt;
</code></pre>
<p>I am using jest for testing. Please help me with this.Thanks.</p>
",https://stackoverflow.com/questions/68402827/store-is-undefined-in-vue-3-class-component-unit-testing,"['vuejs3', 'vuex4']",183,False,1,0
shall we set continuous integration for laravel without unitest in jenkins.?,"<p>I try to build a laravel project and I want to setup continuous integration using jenkins, How should I create a project in jenkins of laravel. And shall we build without unit testing in jenkins.</p>
",https://stackoverflow.com/questions/69360359/shall-we-set-continuous-integration-for-laravel-without-unitest-in-jenkins,"['laravel', 'jenkins', 'automation', 'jenkins-plugins', 'jetstream']",29,False,0,1
How to mock redis client in nodejs using jest,"<p>I have tried to mock the redisClient.js using <code>redis-mock</code> using <code>jest</code>. But I couldn't find the solution for it. please give me a code sample for it. I need to mock it in <code>controller</code>.</p>
<p><strong>redisClient.js</strong></p>
<pre><code>const redis = require('redis');
const asyncRedis = require(&quot;async-redis&quot;);

//Redis
const connection = redis.createClient(process.env.REDIS_PORT,
    {
        retry_strategy: function(options) {
          if (options.error &amp;&amp; options.error.code === &quot;ECONNREFUSED&quot;) {
            // End reconnecting on a specific error and flush all commands with
            // a individual error
            return new Error(&quot;The server refused the connection&quot;);
          }
          if (options.total_retry_time &gt; 1000 * 60 * 60) {
            // End reconnecting after a specific timeout and flush all commands
            // with a individual error
            return new Error(&quot;Retry time exhausted&quot;);
          }
          if (options.attempt &gt; 10) {
            // End reconnecting with built in error
            return undefined;
          }
          // reconnect after
          return Math.min(options.attempt * 100, 3000);
        },
    }
);

module.exports = asyncRedis.decorate(connection);
</code></pre>
<p><strong>Controller</strong></p>
<pre><code>const logger = require('../../helper/logger');
const response = require(&quot;../../config/response&quot;);
const constant = require('../../config/constant');
const QuizService = require('../../services/quiz/quizService');

class QuizController {

    constructor() {
        this.quizService = new QuizService();
    }

    async getQuiz(req, res) {
        const { userId, query: { campaignId } } = req;
        try {
            const question = await this.quizService.getQuestion(userId, campaignId);

            res.send(response.res(true, constant.MSG.Quiz_FETCHED, question));

        } catch (error) {

            res.status(constant.RESPONSE.INTERNAL_ERROR.CODE)
                .send(response.res(false, error.message, null, error.code))
        }
    }
}
</code></pre>
<p><strong>Service</strong></p>
<pre><code>const _ = require('lodash');
const moment = require('moment');
const { Op } = require('sequelize');
const { v4: uuidv4 } = require(&quot;uuid&quot;);
const shuffle = require('shuffle-array');
const serialize = require(&quot;serialize-javascript&quot;);
const utill = require(&quot;../../helper/util&quot;);
const redis = require(&quot;../../cache/redisClient&quot;);
const constant = require('../../config/constant');
const scoreHelper = require('./../../helper/scoreHelper');
const db = require(&quot;../../models&quot;);
const Quiz = db.quiz;
const Campaign = db.campaign;
const campaign = require('../campaign/campaignService')
const SubscriberAnswer = require('../subscriberAnswer/subscriberAnswerService')
const SubscriberProgram = require('../subscriberProgram/SubsciberProgramService')

class quizService {

    constructor() {
        this.subscriberAnswer = new SubscriberAnswer()
        this.subscriberProgram = new SubscriberProgram()
        this.campaign = new campaign()
    }

    async getQuestion(userId, campaignId) {
        const subscribedProgramData = await this._checkAvailableQuestionLimit(userId, campaignId)
        if(!subscribedProgramData){
            throw { message: constant.MSG.TRY_AGAIN }
        }
        if (subscribedProgramData.no_of_questions &gt; 0) {
            const question = await Quiz.findQuestion(userId, campaignId);
            if (question.length) {
                const data = {
                    subscriber_id: userId,
                    campaign_id: campaignId,
                    questions_id: question[0].id
                }
                const updateData = {
                    id: subscribedProgramData.id,
                    no_of_questions: (subscribedProgramData.no_of_questions - 1)
                }
                await this.subscriberAnswer.create(data);
                await this.subscriberProgram.updateQuota(updateData);
                const id = uuidv4();
                const {answer, ...questionData } = question[0];
                const responseData = await this.handleQuestionData(id, userId, campaignId, questionData, answer);
                return responseData;
            } else {
                throw { code:constant.RESPONSE_COEDES.ALL_ANSWERED, message: constant.MSG.ANSWER_ALL }
            }
        } else {
            throw { message: constant.MSG.QUOTA_OVER }
        }
    }
}
</code></pre>
<p><strong>My Unit Testing Code</strong></p>
<pre><code>const QuizService = require(&quot;../../src/services/quiz/quizService&quot;);
const QuizController = require(&quot;../../src/controllers/quiz/quizController&quot;);
const quizService = new QuizService();
const quizController = new QuizController();
const httpMocks = require(&quot;node-mocks-http&quot;);

jest.mock(&quot;../../src/helper/logger&quot;);
jest.mock(&quot;../../src/cache/redisClient.js&quot;);

beforeEach(() =&gt; {
    req = httpMocks.createRequest();
    res = httpMocks.createResponse();
    next = jest.fn();
    jest.resetAllMocks();
    quizService.getQuestion = jest.fn();
});
quizService.getQuestion = jest.fn();
const response = {
    id: 1,
    name: 'Sandun',
    msisdn: '94704377575',
    otp: '1234',
    deleted: 0,
    attempts: 0,
    img_url: 'https://'
}

// This test shows how the constructor can be mocked, and how to spy on passed parameters.
describe(&quot;Test QuizController&quot;, () =&gt; {
    afterEach(() =&gt; {
      jest.resetAllMocks();
    });

    //Because getQuestion is prototype method
    it(&quot;Test - GetQuiz - Success&quot;, async () =&gt; {
        req.query.programId = 1;
        req.userId = 1;
        jest.spyOn(QuizService.prototype, &quot;getQuestion&quot;).mockReturnValue(response);
        await quizController.getQuiz(req, res);
        expect(res.statusCode).toBe(200);
    });

});
</code></pre>
<p><strong>ERROR</strong></p>
<pre><code> FAIL  test/controllers/quiz.controller.test.js
  ● Test suite failed to run

    TypeError: Cannot read property 'startsWith' of undefined

       
       //Redis
     const connection = redis.createClient(process.env.REDIS_PORT,
                                  ^
           {
               retry_strategy: function(options) {
                if (options.error &amp;&amp; options.error.code === &quot;ECONNREFUSED&quot;) {

      at normalizeUrl (node_modules/redis-mock/lib/utils/parseRedisUrl.js:4:11)
      at Object.&lt;anonymous&gt;.module.exports (node_modules/redis-mock/lib/utils/parseRedisUrl.js:61:34)
      at generateUrlOptions (node_modules/redis-mock/lib/client/createClient.js:25:30)
      at unifyOptions (node_modules/redis-mock/lib/client/createClient.js:61:10)
      at Object.createClient (node_modules/redis-mock/lib/client/createClient.js:64:47)
      at Object.&lt;anonymous&gt; (src/cache/redisClient.js:5:26)
      at Object.&lt;anonymous&gt; (src/services/quiz/quizService.js:8:15)
      at Object.&lt;anonymous&gt; (test/controllers/quiz.controller.test.js:1:21)
</code></pre>
",https://stackoverflow.com/questions/65666234/how-to-mock-redis-client-in-nodejs-using-jest,"['node.js', 'unit-testing', 'redis', 'mocking']",3633,False,3,0
DataBricks Python unit test error help needed,"<p>I have a problem with unit testing in DataBricks. I have not found any similar error message yet. Could someone please help me?</p>
<p>Below you can find my code:</p>
<pre><code>import unittest

def add(n1, n2):
  a = n1+n2
 
  return a

class addTest(unittest.TestCase):
  
  def test_add(self):
    self.assertEqual(add(5,5), 10)

unittest.main()
</code></pre>
<p>The error message is this:</p>
<pre><code>EEEEEEEE
======================================================================
ERROR: 36941 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '36941'

======================================================================
ERROR: 0 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '0'

======================================================================
ERROR: 50000 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '50000'

======================================================================
ERROR: 923 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '923'

======================================================================
ERROR: dcc9864f9b334f05b20e25d63062f770 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'dcc9864f9b334f05b20e25d63062f770'

======================================================================
ERROR: 3 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '3'

======================================================================
ERROR: 4b8784f2c9e2dd8ccd5890b026495bf12fc0671c88baa508721606e240ca39b2 (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '4b8784f2c9e2dd8ccd5890b026495bf12fc0671c88baa508721606e240ca39b2'

======================================================================
ERROR: unpinned (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'unpinned'
</code></pre>
<p>Can someone please help me? Thank you!</p>
",https://stackoverflow.com/questions/67314705/databricks-python-unit-test-error-help-needed,"['python', 'unit-testing', 'databricks', 'python-unittest']",934,True,4,2
Angular Reactive Form Unit Testing: HTML value and control value out of sync,"<p>I am following the Angular reactive form unit testing guide <a href=""https://medium.com/javascript-frameworks/unit-testing-using-reactive-forms-in-angular-66b9fc4ee429"" rel=""nofollow noreferrer"">here</a> but am perpetually unable to get the control value and the HTML value to synchronize.  Below is my implementation; note that I am trying to call <code>setValue</code> in addition to specifying default values:</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'user',
    templateUrl: './user.component.html',
    styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

    loginForm!: FormGroup;

    constructor(private formBuilder: FormBuilder) { }

    ngOnInit(): void {
        this.initLoginForm();

        const usernameControl = this.loginForm.get('username');
        usernameControl?.valueChanges.subscribe(username =&gt; {
            debugger; // This doesn't fire
            this.loginForm.patchValue({username: username});
        });
    }

    initLoginForm() {
        this.loginForm = this.formBuilder.group({
            username: ['jack', Validators.compose([Validators.required])],
            password: ['JacksPassword']
        });

        this.loginForm.setValue({
            username: 'jack',
            password: 'JacksPassword'
        })

        this.loginForm.updateValueAndValidity();
    }
}
</code></pre>
<pre class=""lang-html prettyprint-override""><code>&lt;form [formGroup]=&quot;loginForm&quot; id=&quot;loginForm&quot;&gt;
    &lt;div&gt;
        &lt;input formControlName=&quot;username&quot; placeholder=&quot;Username&quot; required id=&quot;usernameInput&quot;/&gt;
    &lt;/div&gt;
    &lt;div&gt;
        &lt;input formControlName=&quot;password&quot; placeholder=&quot;Password&quot; type=&quot;password&quot;/&gt;
    &lt;/div&gt;
&lt;/form&gt;
</code></pre>
<p>And here are my tests:</p>
<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormBuilder } from '@angular/forms';
import { UserComponent } from './user.component';

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

    beforeEach(async () =&gt; {
        await TestBed.configureTestingModule({
            declarations: [UserComponent],
            providers: [FormBuilder]
        })
            .compileComponents();
    });

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

    it('should have same values between control and UI', () =&gt; {
        const loginFormUserElement: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#loginForm').querySelector('#usernameInput');
        const userNameValueFromGroup = component.loginForm.get('username');
        expect(loginFormUserElement.value).toEqual(userNameValueFromGroup?.value);
    });

    it('should accept username', () =&gt; {
        const loginFormUserElement: HTMLInputElement = fixture.debugElement.nativeElement.querySelector('#loginForm').querySelector('#usernameInput');
        loginFormUserElement.value = 'joe';
        loginFormUserElement.dispatchEvent(new Event('input'));
        fixture.detectChanges();
        fixture.whenStable().then(() =&gt; {
            const userNameValueFromGroup = component.loginForm.get('username');
            expect(loginFormUserElement.value).toEqual('joe');
            expect(loginFormUserElement.value).toEqual(userNameValueFromGroup?.value);
        });
    });
});
</code></pre>
<p>And here are the results.  Setting defaults doesn't update the UI.  Calling <code>setValue</code> doesn't update the UI.  And setting a value on the UI element doesn't update the control.</p>
<p><a href=""https://i.stack.imgur.com/2V3rb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2V3rb.png"" alt=""enter image description here"" /></a></p>
<p>It must be something basic.  Whatever am I missing?</p>
<p><strong>EDIT</strong>: I attempted to set up a StackBlitz implementation based on an isolated unit testing example, but the <code>formGroup</code> directive doesn't seem to be recognized under Jasmine; I am importing <code>ReactiveFormsModule</code> into app.module.  The link is <a href=""https://stackblitz.com/edit/angular-unit-testing-examples-jvzhzg"" rel=""nofollow noreferrer"">here</a> in case anyone can provide insight about what I'm missing on this front.</p>
<p><strong>EDIT</strong>: The problem here seems actually seems related to my unit testing effort.  When I use the component directly, default values are displayed on the HTML input element correctly; however, when inspecting messages via the console on Chrome running Karma, I see the same error message indicating that the <code>formGroup</code> directive isn't recognized.  I've updated the title accordingly.</p>
",https://stackoverflow.com/questions/69412403/angular-reactive-form-unit-testing-html-value-and-control-value-out-of-sync,"['javascript', 'html', 'angular', 'typescript']",623,True,1,1
test input type file in jest,"<p>How i  can simply make unit testing for the value of input type file :</p>
<pre><code>&lt;input required type=&quot;file&quot; class=&quot;form-control blue-border&quot; accept=&quot;.jpg, .jpeg, .png&quot; data-testid=&quot;file&quot; /&gt; 
</code></pre>
<p>I tryed</p>
<pre><code>descripe('ex....',()=&gt;{
     test('ex.....',()=&gt;{
     const file=screen.getByTestId('file')
     expect(file.value='myfile.png').toContain(/(\.jpg|\.jpeg|\.png)$/i)
})
})
</code></pre>
<p>but i have error :
InvalidStateError: This input element accepts a filename, which may only be programmatically set to the empty string.</p>
",https://stackoverflow.com/questions/69952756/test-input-type-file-in-jest,"['javascript', 'unit-testing', 'jestjs']",459,False,1,1
Error with unit testing using selfassertAlmostEqual,"<p>right so I am getting an error with unit testing where I can't use selfassertAlmostEqual</p>
<pre><code>in assertAlmostEqual
    diff = abs(first - second)
TypeError: unsupported operand type(s) for -: 'list' and 'list
</code></pre>
<p>this is my unittest method where I am getting the error any ideas as to how could I fix it thank you.</p>
<pre><code>def test_method_04(self):
        self.set_up()
        actual = self.bookshop.method_4(self.orders)
        expected = [(1, 678.33),(2, 494.46),(3, 364.8),(4, 492.57)]
        self.assertAlmostEqual(actual, expected, places = 2)
        print(&quot;METHOD4 \nACTUAL:&quot;)
        for line in actual:
            print(line)
        print(&quot;EXPECTED:&quot;)
        for line in expected:
            print(line)
'
</code></pre>
",https://stackoverflow.com/questions/69980505/error-with-unit-testing-using-selfassertalmostequal,"['python', 'computer-science']",133,False,1,1
How to mock function which are part of packages and are not declared with interface,"<p>I am using github.com/confluentinc/confluent-kafka-go/kafka as a package to deal with kafka.</p>
<p>It has functions like NewConsumer, SubscribeTopics, Poll which are not declared using interface. How do I mock them for unit testing?</p>
",https://stackoverflow.com/questions/69254533/how-to-mock-function-which-are-part-of-packages-and-are-not-declared-with-interf,"['unit-testing', 'go', 'mocking']",374,False,1,1
How to write unit test in angular for setTimeout function and activeElement?,"<p>I want to write a unit test case for the following function:</p>
<pre><code>onfactorblur():void{
  var that=this;
  setTimeout(function(){
    var target=document.activeElement;
    if(target.tagName==&quot;BUTTON&quot;){
      if(target.textContent==&quot;CONTINUE&quot;){
        that.onContinueClick();
      }
      else{
        that.activeModal.close();
      }
     }
   },.5);
 }
</code></pre>
<p>I am new to angular unit testing and never faced a scenario where I had to test setTimeout within a function. I have tried:</p>
<pre><code>    it('Should close the modal if target element is button',fakeAsync(()=&gt;{
    spyOn(component,'onContinueClick');
    spyOn(component.activeModal,'close');
    tick(1);
    fixture.detectChanges();
    fixture.whenStable().then(()=&gt;{
    //What should I write here
      })
    }));
</code></pre>
",https://stackoverflow.com/questions/66635886/how-to-write-unit-test-in-angular-for-settimeout-function-and-activeelement,"['javascript', 'angular', 'unit-testing', 'karma-jasmine', 'angular-test']",1527,False,0,1
"Error CS0119;	class is a type, which is not valid in the given context","<p>Upon becoming familiar with C#, I'm getting the following error when unit testing on the line where an assertion is made <code>Assert.IsInstanceTypeOf</code>.</p>
<p><code>Error  CS0119  'Product' is a type, which is not valid in the given context</code></p>
<p>The matter of creating a type has been performed. What is causing this error to be raised?</p>
<p><strong>UnitTest1.cs</strong></p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using ProductNamespace;

namespace TestProject2
{
    [TestClass]
    public class TestProduct
    {
        [TestMethod]
        public void TestNewProduct()
        {
            Product mock_product = new Product(4.95);
            Assert.IsInstanceOfType(mock_product, Product);
        }
    }
}
</code></pre>
<p><strong>Product.cs</strong></p>
<pre><code>namespace ProductNamespace
{
    public class Product
    {
        private double price;

        public Product(double price)
        {
            this.price = price;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/69024853/error-cs0119class-is-a-type-which-is-not-valid-in-the-given-context,"['c#', 'unit-testing', 'mstest']",7537,True,3,2
Unit Testing Specific Part Of Application,"<p>I am trying to test a part of our application. I know I can limit the tests by using fit, fdescribe, and changing the require.context in the test.ts file. However, I would like a way to test a specific folder, and all files under it, plus a couple of services outside of this folder.</p>
<pre><code>src
   app
      folder1
      folder2
      folder3
          services
             service1.service.ts
             service2.service.ts
</code></pre>
<p>As an example, I would like test test folder2, its children, and service2.service.ts.</p>
<p>Do you have any suggestions for doing such? By doing this, we will be able to automate our unit testing and be able to test grouped together pieces of functionality that are in different folders.</p>
<p>Note: I am using jasmine and karma for unit testing.</p>
",https://stackoverflow.com/questions/70282614/unit-testing-specific-part-of-application,"['angular', 'unit-testing', 'karma-jasmine', 'angular-unit-test']",797,True,1,2
How to do Unit testing in Object Box for flutter project?,"<p>How can we do unit testing for object box in flutter project for all crud operations?</p>
<pre><code>class ShapeRepo {

final _box = store.box&lt;ShapeModel&gt;();

void saveShape(ShapeModel model) {
    _box.put(model);
}

</code></pre>
<p>This is one example. There are many box operations. I was wondering if a separate object box store is available for testing?</p>
",https://stackoverflow.com/questions/68711698/how-to-do-unit-testing-in-object-box-for-flutter-project,"['flutter', 'unit-testing', 'dart', 'flutter-objectbox']",745,True,1,1
Angular Unit test case for File uploading in xlsx format,"<p>I'm trying to write the unit testing for the file upload method (not integrated with API yet) in angular. Can someone help me on adding mock files and to get the full code coverage without errors pls?</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>onFileUpload(event) {
    this.successMsg = '';
    this.errorMsg = '';
    this.sheetJsExcelName = event.target.files.item(0).name;
    const target : DataTransfer = &lt;DataTransfer&gt;(event.target);
    const reader : FileReader = new FileReader();
    reader.onload = (e : any) =&gt; {
      const bstr : string = e.target.result;
      const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary'});
      const wsname: string = wb.SheetNames[1];
      const ws: XLSX.WorkSheet = wb.Sheets[wsname];
      this.data = (XLSX.utils.sheet_to_json(ws, { header: 1 }));
      if(this.data.length &gt; 20) {
        this.errorMsg = ""Record limit is exceeding"";
      } else {
        setTimeout(() =&gt; {
        this.successMsg = this.sheetJsExcelName + "" is uploaded succesfully"";
      }, 5000);
    }
    }
    reader.readAsBinaryString(target.files[0]);


  }
  
  // in spec file
    it('should detect file input change', () =&gt; {
    component.onFileUpload('Upload.xlsx');
    fixture.detectChanges();
    expect(data.length).toBeLessThanOrEqual(20);
    expect(component.sheetJsExcelName).toBeTruthy()
    expect(component.sheetJsExcelName).toBe('Upload.xlsx') 
    })</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;input type=""file"" (change)=""onFileUpload($event)"" accept="".xlsx""  multiple=""false"" style=""display: none;""&gt;Bulk Upload</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/69618803/angular-unit-test-case-for-file-uploading-in-xlsx-format,"['angular', 'typescript', 'file-upload', 'jasmine', 'xlsx']",848,False,0,0
How to test API Controller with xUnit,"<p>I am new to unit testing and .net. I want to test an api controller, which returns and IEnumerable.
What is the best way to test this controller? Do you have any suggestions?</p>
<pre><code>[Route(&quot;api/[controller]&quot;)]
[ApiController]
public class PersonController 
{

    [HttpGet]
    public IEnumerable&lt;Person&gt; GetListOfPerson([FromQuery] FilterRequest request)
    {
        return new Person[]
        {
            new()
            {
              Name =&quot;Peter&quot;
              Age = &quot;23&quot;
              
            },
            new()
            {
              Name =&quot;John&quot;
              Age = &quot;54&quot;        
            }
        }
        .Where(person=&gt; request.MatchesFilter(person))
        .Skip(request.Page * request.ItemsPerPage)
        .Take(request.ItemsPerPage);
    }
    ...
}
</code></pre>
<p>Thank you in advance!</p>
",https://stackoverflow.com/questions/67968109/how-to-test-api-controller-with-xunit,"['c#', 'asp.net-web-api', 'xunit.net']",1656,True,0,2
Jest - Unit Testing a Namespaced File,"<p>Is it possible to write a unit test with Jest for a JavaScript file that is namespaced using the below format?</p>
<pre><code>// utilities.js

var MyApp = MyApp || {};
MyApp.Common = MyApp.Common || {};
MyApp.Common.Utilities = new function(){
    this.getSomething = function(){  // Need to unit test this function
        return 'Something';
    }
}
</code></pre>
<p>If not, is there a better way to structure the namespaces to allow for unit testing?</p>
",https://stackoverflow.com/questions/69230785/jest-unit-testing-a-namespaced-file,"['javascript', 'unit-testing', 'jestjs']",44,True,0,1
unit testing a vue component,"<p>I have a component that looks like this,</p>
<pre><code>&lt;template&gt;
&lt;!-- eslint-disable vue/no-v-html --&gt;
&lt;div class=&quot;c-dialog&quot; :class=&quot;{'u-block': show}&quot; @triggerOpen=&quot;handleOpen&quot;&gt;
    &lt;div class=&quot;c-dialog__background&quot; @click=&quot;handleClose&quot;&gt;
        &lt;div class=&quot;c-dialog__wrapper u-mt-4 u-mb-1&quot;&gt;
            &lt;div class=&quot;c-dialog__action u-flex&quot;&gt;
                &lt;button class=&quot;c-dialog__close u-bg-denim-blue u-border-0 u-text-white&quot; @click=&quot;handleClose&quot;&gt;Close&lt;/button&gt;
            &lt;/div&gt;
            &lt;div class=&quot;c-dialog__main u-px-2 u-py-4 u-border u-bg-white&quot;&gt;
                &lt;h4&gt;{{ content.title }}&lt;/h4&gt;
                &lt;div class=&quot;c-dialog__content u-mt-2&quot; v-html=&quot;content.content&quot; /&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p>I am wanting to unit test it, but I am very rusty when it comes to unit testing, the component is very simple, it is either show or hidden based on data value (show: true/false).</p>
<p>I assume that I would need 1 test for asserting that the component is hidden when show = false and another for asserting that modal is visible when show = true. But in a component that is so simple should I be unit testing anything else? There are 2 methods in the component <code>handleClose</code> (sets show to false) and handleOpen (sets show to true), does these methods need there own tests also? So far my test looks like,</p>
<pre><code>import { shallowMount } from '@vue/test-utils'
import Dialog from './Dialog.vue'

test('Dialog', () =&gt; {

});
</code></pre>
",https://stackoverflow.com/questions/69286803/unit-testing-a-vue-component,"['javascript', 'vue.js', 'unit-testing']",522,False,0,1
Angular TestBed.inject,"<p>I am doing angular unit testing. Does TestBed.inject(service) create a new instance of the service?
I was always under the assumption that TestBed.configureTestingModule() created the service and by inject we just accessed a reference of the created service.</p>
",https://stackoverflow.com/questions/67815435/angular-testbed-inject,"['angular', 'unit-testing', 'jasmine', 'angular-dependency-injection']",5817,True,1,1
Passing dbcontext and UserManager to a controller when testing,"<p>I am trying to unit test a controller which takes in a dbcontext and a usermanager object. How could I go about passing these into the controller when performing unit testing?</p>
<h2>Controller</h2>
<pre><code>public ProjectsController(ApplicationDbContext context,
    UserManager&lt;ApplicationUser&gt; userManager)
{
    _context = context;
    _userManager = userManager;
}
</code></pre>
<h2>ApplicationDbContext</h2>
<pre><code>public ApplicationDbContext(
    DbContextOptions options,
    IOptions&lt;OperationalStoreOptions&gt; operationalStoreOptions) : base(options, operationalStoreOptions)
{


}

public DbSet&lt;Project&gt; Projects { get; set; }
</code></pre>
<h2>Test</h2>
<pre><code>[Fact]
public void test4()
{
//....
    var controller = new ProjectsController(null, null);
    var result = controller.GetProject(p.ProjectId);
}
</code></pre>
<h2>Controller method being tested</h2>
<pre><code>[HttpGet(&quot;{id}&quot;)]
public async Task&lt;ActionResult&lt;Project&gt;&gt; GetProject(Guid id)
{
    var project = await _context.Projects.FindAsync(id); // Find project by id
    var query = _context.Users.Where(u =&gt; u.Projects.Any(p =&gt; p.ProjectId.ToString().Equals(project.ProjectId.ToString()))); //find all users for the project
    project.AssignedUsersToProject = query.ToList(); //set found users to the assigned users list

    if (project == null)
    {
        return NotFound();
    }

    return project;
}
</code></pre>
",https://stackoverflow.com/questions/70287390/passing-dbcontext-and-usermanager-to-a-controller-when-testing,"['c#', 'asp.net', 'unit-testing', 'moq', 'xunit']",138,False,0,0
Angular Unit Testing facing problem in initialization form and subscribing value changes of form,"<p>i'm new in unit testing in angular actually i facing a issue while initialization of form group</p>
<pre><code>  it('should be able to init forms', () =&gt; {

        service.organizationForm = formBuilder.group({})
        service.initOrganizationForm()
})
</code></pre>
<p>while initOrganizationForm function is called in this function there is catch</p>
<pre><code>this.organizationForm.valueChanges.
            subscribe(form =&gt; {
                this.organizationButtonsData[1]['disabled'] = this.organizationForm.valid ? false : true;
                this.getRequiredCount();
            });
</code></pre>
<p>so becuase of this code i am getting this error</p>
<pre><code> should be able to init forms
     Setting Management Service
     TypeError: Cannot read property 'valueChanges' of undefined
    at &lt;Jasmine&gt;
    at SettingManagementService.valueChanges [as initOrganizationForm] (http://localhost:9876/_karma_webpack_/src/app/core/services/settings.management.service.ts:465:31)
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/src/app/core/services/settings.management.service.spec.ts:74:17)
</code></pre>
",https://stackoverflow.com/questions/65577331/angular-unit-testing-facing-problem-in-initialization-form-and-subscribing-value,"['angular', 'unit-testing', 'angular-unit-test']",101,False,0,0
Jest test coverage output contains no data,"<p>I am unit testing in React using Jest. When I run <code>npm test</code> the test cases pass, but the coverage code does not contain any data:</p>
<p><a href=""https://i.stack.imgur.com/cAZHQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/cAZHQ.png"" alt=""enter image description here"" /></a></p>
<p>How can I see the code coverage data?</p>
<p><strong>My Component is:</strong></p>
<pre class=""lang-js prettyprint-override""><code>import React, { Component } from 'react';
import Tooltip from '@material-ui/core/Tooltip';

export default class HeaderCreate extends Component {

  render() {

    const { name, description, closeRightSection } = this.props;

    return (

      &lt;div className=&quot;header&quot;&gt;
        &lt;h1 className=&quot;header-text&quot; title={name} data-testid=&quot;header&quot;&gt;{name}&lt;/h1&gt;
        &lt;p data-testid= &quot;description-para&quot;&gt;{description}&lt;/p&gt;

        &lt;Tooltip title=&quot;Close Section&quot;&gt;
          &lt;div className=&quot;icon-close&quot;&gt;
            &lt;i className=&quot;material-icons&quot; onClick={() =&gt; closeRightSection()} data-testid=&quot;id&quot;&gt;close&lt;/i&gt;
          &lt;/div&gt;
        &lt;/Tooltip&gt;
      &lt;/div&gt;
    )
  }
}
</code></pre>
<p><strong>Unit Test Case</strong></p>
<pre class=""lang-js prettyprint-override""><code>import React from 'react'
import { render , fireEvent} from &quot;@testing-library/react&quot;;

import HeaderCreate from '../components/createHeader';


test(&quot;render header correctly&quot;, () =&gt; {
    const { getByTestId } = render(&lt;HeaderCreate name=&quot;My Name is Test&quot;&gt;&lt;/CreateHeader&gt;);
    expect(getByTestId('header').textContent).toBe('My Name is Test')
});

test(&quot;render Description Paragraph correctly&quot;, () =&gt; {
    const { getByTestId } = render(&lt;HeaderCreate description=&quot;Hi I am Description box&quot;&gt;&lt;/CreateHeader&gt;);
    expect(getByTestId('description-para').textContent).toBe('Hi I am Description box')
});

test(&quot;render close tooltip correctly&quot;, () =&gt; {
    const { getByTestId } = render(&lt;HeaderCreate closeRightSection=&quot;&quot;&gt;&lt;/CreateHeader&gt;);
    expect(getByTestId('id')).toBeTruthy();
});
</code></pre>
",https://stackoverflow.com/questions/68901787/jest-test-coverage-output-contains-no-data,"['javascript', 'reactjs', 'code-coverage']",424,True,0,1
"Argument of type &#39;(content: string, node: Element | null) =&gt; boolean | null | undefined&#39; is not assignable to parameter of type &#39;Matcher&#39;","<p>I have a React Typescript app and while unit testing I used below code to find an element by its textContent:</p>
<pre class=""lang-js prettyprint-override""><code>import { screen } from &quot;@testing-library/react&quot;;

export function getByTextContent(textMatch: string | RegExp): HTMLElement {
  return screen.getByText((content, node) =&gt; {
    const hasText = (node: Element) =&gt;
      node.textContent === textMatch || node.textContent?.match(textMatch);
    const nodeHasText = hasText(node as Element);
    const childrenDontHaveText = Array.from(node?.children || []).every(
      (child) =&gt; !hasText(child)
    );
    return nodeHasText &amp;&amp; childrenDontHaveText;
  });
}
</code></pre>
<p>I took the code from <a href=""https://github.com/testing-library/dom-testing-library/issues/410#issuecomment-797486513"" rel=""nofollow noreferrer"">here</a></p>
<p>My tests passes, but the app crashes with the below error:</p>
<pre class=""lang-js prettyprint-override""><code>Argument of type '(content: string, node: Element | null) =&gt; boolean | null | undefined' is not assignable to parameter of type 'Matcher'.
  Type '(content: string, node: Element | null) =&gt; boolean | null | undefined' is not assignable to type 'MatcherFunction'.
    Type 'boolean | null | undefined' is not assignable to type 'boolean'.
      Type 'undefined' is not assignable to type 'boolean'.  TS2345

    2 | 
    3 | export function getByTextContent(textMatch: string | RegExp): HTMLElement {
  &gt; 4 |   return screen.getByText((content, node) =&gt; {
      |                           ^
    5 |     const hasText = (node: Element) =&gt;
    6 |       node.textContent === textMatch || node.textContent?.match(textMatch);
    7 |     const nodeHasText = hasText(node as Element);
</code></pre>
",https://stackoverflow.com/questions/68504415/argument-of-type-content-string-node-element-null-boolean-null-un,"['javascript', 'reactjs', 'typescript', 'react-testing-library']",587,True,0,1
Why I am getting %E2%80%8B in my URL during unit testing,"<p>I am writing the unit testing for my controller and am getting 404 instead of 200 success.<br/>
When I search on the console it is showing we WARN log like</p>
<pre><code>WARN  [2021-02-12T11:53:27.711+0530] servlet.PageNotFound ||${fallback:user}|No mapping for GET /person%E2%80%8B/contacts%E2%80%8B/details
</code></pre>
<p>Why mapping changed to <code>/person%E2%80%8B/contacts%E2%80%8B/details</code> instead of <code>/person/contacts/details</code></p>
<p><strong>Test Class</strong></p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
@ActiveProfiles(&quot;test&quot;)
@SpringBootTest
public class PersonControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @InjectMocks
    private PersonController personController;

    @Mock
    private PersonService personService;

    @Before
    public void setupMethod() {

        mockMvc = MockMvcBuilders.standaloneSetup(personController).build();
    }

    @Test
    public void getPersonContactDetailTest() throws Exception {
    
        Person person = new Person();
        person.setName(&quot;Test&quot;);

        Mockito.when(personService.getPersonContactDetail()).thenReturn(person);

        RequestBuilder rqBuilder = MockMvcRequestBuilders.get(&quot;/person/contacts/details&quot;)
                .accept(MediaType.APPLICATION_JSON);

        mockMvc.perform(rqBuilder).andExpect(MockMvcResultMatchers.status().isOk());

        Mockito.verify(personService, times(1)).getPersonContactDetail());
    }
}
</code></pre>
",https://stackoverflow.com/questions/66167816/why-i-am-getting-e2808b-in-my-url-during-unit-testing,"['java', 'unit-testing', 'mockito', 'urlencode']",603,True,0,1
Java/Scala Create test Directory for testing write failures,"<p>I am unit testing I/O code roughly of the following form. I want to test that the fallback logic works if the write fails initially. How can I create a file path such that it will fail the initial write?</p>
<pre><code>def myMethod(dirPath: String): File = {
  val tempFile = File.createTempFile(PREFIX, &quot;.zip&quot;, new File(dirPath))
  // write to tempfile
  tempFile
}

try {
  myMethod(DIR_PATH)
} catch {
  // some fallback logic
  if (ALT_PATH != null) {
    myMethod(ALT_PATH)
  }
}
</code></pre>
",https://stackoverflow.com/questions/70119897/java-scala-create-test-directory-for-testing-write-failures,"['java', 'scala', 'unit-testing', 'file', 'io']",83,False,1,0
How to test suspend function using MockK?,"<p>I am writing a unit test for my Datarepository layer which simply calls an interface.
I am using Kotlin, coroutines and MockK for unit testing.
In MockK, how can I verify that I have called <code>apiServiceInterface.getDataFromApi()</code> and has happened only once?
Should I put the code in runBlocking?</p>
<p>This is my code:</p>
<p>UnitTest</p>
<pre><code>import com.example.breakingbad.api.ApiServiceInterface
import com.example.breakingbad.data.DataRepository
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import org.junit.Test
</code></pre>
<p>Repository</p>
<pre><code>class DataRepositoryTest {
    @MockK
    private lateinit var apiServiceInterface: ApiServiceInterface

    @InjectMockKs
    private lateinit var dataRepository: DataRepository

    @Test
    fun getCharacters() {
            val respose = dataRepository.getCharacters()
            verify { apiServiceInterface.getDataFromApi() }
    }
}

    class DataRepository @Inject constructor(
    private val apiServiceInterface: ApiServiceInterface
) {
    suspend fun getCharacters(): Result&lt;ArrayList&lt;Character&gt;&gt; = kotlin.runCatching{
        apiServiceInterface.getDataFromApi()
    }
}
</code></pre>
<p>Interface</p>
<pre><code>interface ApiServiceInterface {
    @GET(&quot;api/characters&quot;)
    suspend fun getDataFromApi(): ArrayList&lt;Character&gt;
}
</code></pre>
",https://stackoverflow.com/questions/69014652/how-to-test-suspend-function-using-mockk,"['android', 'unit-testing', 'kotlin', 'mockito', 'mockk']",6395,True,13,2
Mock Data from Redis unit testing python,"<p>I have a class</p>
<pre><code>class ReferenceData(celery.Task):
    def __init__(self):
        redis_pool = redis.ConnectionPool()
        self.redis = redis.StrictRedis(connection_pool=redis_pool)

    def get_agents(self,id):
        if condition:
            return self.agents.get(id)
        return self.agents.get(external_id
</code></pre>
<p>and there is celery task which calls up the following method</p>
<pre><code>def save_raisr_event(self, event):
    # Get attributes:
    transcriptions = []
    if trans is not None:
       transcriptions.append(trans)
        self.redis.append(f&quot;{crn}-transcription&quot;, ' ' + transcription)
        return 'transcription saved'
</code></pre>
<p>In the unit testing how to mock the redis connection and mock data from redis in this case the value pf transcription saved in redis</p>
",https://stackoverflow.com/questions/69351844/mock-data-from-redis-unit-testing-python,"['python', 'unit-testing', 'mocking', 'python-unittest']",670,True,1,1
(local variable) List holidays Argument 1: cannot convert from &#39;System.Collections.Generic.List&lt;DateProject.Holiday&gt;&#39; to &#39;?&#39;,"<p>This is the code I have below. It's for unit testing. I have an error for <strong>Returns(holidays)</strong>. It says &quot;(local variable) List holidays Argument 1: cannot convert from 'System.Collections.Generic.List&lt;DateProject.Holiday&gt;' to '?'&quot;</p>
<p>The error showed when I added &quot;using System.Collections.Generic;&quot;</p>
<pre><code>[Fact]
public void WhatHolidaysAreOnThisDay_FindHolidays_ReturnsHolidays() {

    // Arrange

    var holidayProvider = new Mock&lt;IHolidayProvider&gt;();
    List&lt;Holiday&gt; holidays = new List&lt;Holiday&gt;() {
        new Holiday() {TheDate=new Date(2020, 6, 2), Name=&quot;Beach Day&quot;},
        new Holiday() {TheDate= new Date(2020, 6, 2), Name = &quot;Pizza Day&quot;}
    };
    holidayProvider.Setup(m=&gt; m.GetHolidays(2020)).Returns(holidays);  

    Date date = new Date(2020, 6, 2, holidayProvider.Object);

    // Act

    List&lt;string&gt; findHolidays = date.WhatHolidaysAreOnThisDay();

    // Assert
    Assert.Equal(&quot;Beach Day&quot;, findHolidays[0]);
    Assert.Equal(&quot;Pizza Day&quot;, findHolidays[1]);
}
</code></pre>
",https://stackoverflow.com/questions/67439606/local-variable-list-holidays-argument-1-cannot-convert-from-system-collectio,['c#'],42,False,1,0
Nest can&#39;t resolve dependencies: NettJS Unit testing with TypeORM,"<p>i have following error when try to Unit testing with NestJS.</p>
<p>Nest can't resolve dependencies of the UsersService (UsersRepository, ?, UserRoleRepository, RoleRepository, JWTService). Please make sure that the argument CredentialsRepository at index [1] is available in the RootTestModule context.</p>
<p>test code</p>
<pre><code>  describe(&quot;UsersService&quot;, () =&gt; {
  let service: UsersService;
  let repositoryMock: MockType&lt;Repository&lt;Users&gt;&gt;;
  let model: typeof Users;

  let repo: Repository&lt;Users&gt;;
  let userController: UsersController;
  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        TypeOrmModule.forRoot({
          type: &quot;mysql&quot;,
          host: config.db.host,
          port: config.db.port,
          username: config.db.username,
          password: config.db.password,
          database: config.db.database,
          autoLoadEntities: true,
          synchronize: true,
        }),
        CredentialsModule,
      ],
      providers: [
        UsersService,
        CredentialsService,
        AuthService,
        JWTService,
        {
          provide: getRepositoryToken(Users),
          // useValue: {
          //   find: jest.fn(() =&gt; [Alluser]),
          // },
          useFactory: repositoryMockFactory,
        },
      ],
    }).compile();

    service = module.get&lt;UsersService&gt;(UsersService);
    repositoryMock = module.get(getRepositoryToken(Users));
  });
  it(&quot;User details get by Id&quot;, async () =&gt; {
    repositoryMock.findOne.mockReturnValue(testUser);
    expect(service.findUser(testUser.id)).toEqual(testUser);
    expect(repositoryMock.findOne).toHaveBeenCalledWith(testUser.id);
    // expect(await service.findOne(1)).toBeCalledWith(testUser);
  });

  // it(&quot;All Users details &quot;, async () =&gt; {
  //   expect(await service.find()).toEqual([Alluser]);
  // });
  // it('Create new User ', async () =&gt; {
  //   expect(await service.createNewUser(createUser)).toEqual(testUser);
  // });
});
</code></pre>
",https://stackoverflow.com/questions/70270182/nest-cant-resolve-dependencies-nettjs-unit-testing-with-typeorm,['nestjs'],2787,True,1,1
PyTest shows a wrong answer,"<p>Can you guys tell me what am I doing wrong with my unit testing?</p>
<pre><code>class Blizzard(Storm):
    def __init__(self, name, wind_speed, temp):
        self.temp = temp
        super().__init__(name, wind_speed)

    def calculate_classification(self) -&gt; str:
        if self.wind_speed &gt;= 35:
            return &quot;Blizzard&quot;
        elif self.wind_speed &gt;= 45 and self.temp &lt;= -12:
            return &quot;Severe Blizzard&quot;
        return &quot;Snow Storm&quot;
</code></pre>
<p>Here is my class to check what kind of blizzard is there and below you can see my unit test code:</p>
<pre><code>def test_severe_blizzard():
    b1 = Blizzard(&quot;Wendy&quot;, 46, -12)
    assert b1.calculate_classification() == 'Severe Blizzard'
</code></pre>
<p><a href=""https://i.stack.imgur.com/wxU0L.png"" rel=""nofollow noreferrer"">Here is the output</a></p>
",https://stackoverflow.com/questions/66973710/pytest-shows-a-wrong-answer,"['python', 'pytest']",98,True,0,1
react js jest unit testing,"<p>Inside the <code>Login</code> functional component I have a function <code>validateForm</code> which checks that <code>username</code> and <code>password</code> lengths are greater than zero.</p>
<pre><code>function validateForm() {
  return username.length &gt; 0 &amp;&amp; password.length &gt; 0;
}
</code></pre>
<p>I use Jest as unit testing tool.</p>
<pre><code>import React from &quot;react&quot;;
import Login, { validateForm } from &quot;./Login&quot;;
import { render, screen } from &quot;@testing-library/react&quot;;

describe(&quot;LoginUser&quot;, () =&gt; {
  test(&quot;validate username and password should be greater than 0&quot;, () =&gt; {
    var username = &quot;name&quot;;
    var password = &quot;pass&quot;;
    expect(validateForm(username.length)).toBeGreaterThan(0);
  });
});
</code></pre>
<pre class=""lang-none prettyprint-override""><code>TypeError: (0 , _Login.validateForm) is not a function
</code></pre>
<p>I'm facing the above error while running the test case. How to solve this error?</p>
",https://stackoverflow.com/questions/70163320/react-js-jest-unit-testing,"['reactjs', 'react-hooks', 'jestjs', 'ts-jest']",316,False,0,1
Could not find required `intl` object. &lt;IntlProvider&gt; needs to exist in the component ancestry. while using wrapper.html(),"<p>I am implementing unit testing, with jest &amp; enzyme for react project. I am using <code>react-intl</code> for multiple language support.</p>
<p>My basic unit test code is</p>
<pre><code>import React from 'react'; 
import MobileRechargeComponent from './'; 
import {  shallowWithIntl, mountWithIntl } from '../../../../setupTestsHelper'; 

const wrapper = shallowWithIntl(&lt;MobileRechargeComponent /&gt;); 
describe('Title', () =&gt; {
    it(&quot;should render initial layout&quot;, () =&gt; {
        expect(wrapper.getElements()).toMatchSnapshot();
    });
    it('renders master components properly', () =&gt; {
        console.log('wrapper&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;', wrapper.html())
        expect(wrapper.length).toEqual(1);
    }); 
});
</code></pre>
<p>I am getting error as like in following picture</p>
<p><a href=""https://i.stack.imgur.com/tnSlb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tnSlb.png"" alt=""enter image description here"" /></a></p>
<p>My <code>setupTestsHelper</code> file code is as below</p>
<pre><code>import React from 'react'; 
import { IntlProvider, intlShape, createIntl } from 'react-intl'; 
import { mount, shallow } from 'enzyme';
import { getCurrentLanguage } from './Lang'; 

const LocalLanguage = {
    french: {},
    arabic: {},
    english: {}
}

const lang = getCurrentLanguage('en', LocalLanguage)
const intl = createIntl({ locale: 'en', lang }, {});
const nodeWithIntlProp = (node) =&gt; {
    return React.cloneElement(node, { intl });
}
export const shallowWithIntl = (node) =&gt; {
    return shallow(nodeWithIntlProp(node), { context: { intl } });
} 
export const mountWithIntl = (node) =&gt; {
    return mount(nodeWithIntlProp(node), {
        context: { intl },
        childContextTypes: { intl: intlShape }
    });
}
</code></pre>
",https://stackoverflow.com/questions/68543943/could-not-find-required-intl-object-intlprovider-needs-to-exist-in-the-comp,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",886,True,1,1
Mock Repository but the Repository didn&#39;t found [NestJS],"<p>my unit testing</p>
<pre><code>
describe('AssetService', ()=&gt;{
    let assetService: AssetService;
    let assetRepository: AssetRepository;

    beforeEach(async () =&gt;{
        const module = await Test.createTestingModule({
            providers: [AssetService, TenantProfileService, ProfileUserService, 
                TenantsService, UsersService,
                {provide: AssetRepository, useFactory: ()=&gt;({
                    find: jest.fn(()=&gt;[])
                })},
            ],

        }).compile();

        assetService = await module.get(AssetService);
        assetRepository = await module.get(AssetRepository);

    });

    describe('getAssets',()=&gt;{
        it('call assetRepository.find and should return all assets', async ()=&gt;{
            const result = await assetService.findAll(null, null);
            expect(assetRepository.find).toHaveBeenCalled();
        });
    })
})
</code></pre>
<p>Hi, I am just trying to mock my repository but I got error. It like my repository never exists. I use jest.fn but it still didn't work.</p>
<p>my code</p>
<pre><code>  async findAll(limit:number=50, keyword:string): Promise&lt;Asset[]&gt; {
    let options: FilterQuery&lt;AssetDocument&gt;;
    if (keyword){
      options = {assetName: {$regex: keyword, $options: 'i'}}
    }else{
      options = {}
    }
    return this.assetRepository.find(options, limit);
  }
</code></pre>
<p>I used mongoose and build own repository</p>
<p><a href=""https://i.stack.imgur.com/fncJx.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fncJx.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/69963480/mock-repository-but-the-repository-didnt-found-nestjs,"['mocking', 'nestjs']",202,False,0,0
Wrong response from PHP Closure,"<p>I trying to understand closures more but I cannot get the correct response from the below code. I get a response of 31 instead of 60 for some reason. My aim is to eventually start unit testing closures.</p>
<p>Thanks</p>
<pre><code>
&lt;?php


class Closuretest
{

    /**
     * Closuretest constructor.
     */
    public function __construct()
    {
    }

    /**
     * @return mixed
     */
    public function getToken()
    {


            $response = $this-&gt;getEntry('abcde', function() {
                return 30;
            }, 30);

        // Return access token
        return $response;
    }


    /**
     * @param $a
     * @param $b
     * @param $c
     * @return mixed
     */
    private function getEntry($a, $b, $c)
    {
        return $b+$c;
    }

}

$testinstance = new Closuretest();

echo $testinstance-&gt;getToken();
</code></pre>
",https://stackoverflow.com/questions/67168045/wrong-response-from-php-closure,"['php', 'closures', 'anonymous-function']",45,True,0,1
"How to cover Junit test cases for FutureCallback&lt;HttpResponse&gt; completed, failed and canceled api in below code","<p>CloseableHttpAsyncClient execute() method is working with FutureCallback,is there any way to write unit testing for that response, I have to increase the coverage but I am unable to cover for FutureCallback completed, failed and canceled api in below code.</p>
<pre><code>@Service
public class SplunkLogger {

    private Logger logger = LoggerFactory.getLogger(SplunkLogger.class);

    @Autowired
    private Environment environment;

    @Autowired
    CloseableHttpAsyncClient httpClient;     

    private void log(SplunkMessage splunkMessage) {
        String messageStr = new Gson
                ().toJson(splunkMessage);
        logger.info(messageStr);
           if(this.environment.getActiveProfiles()[0].contains(&quot;local&quot;)){
            return;
        }
        HttpPost post = new HttpPost(url);
        post.addHeader(Constants.AUTHORIZATION_HEADER, Constants.SPLUNK_TOKEN_PREFIX + token);
        post.addHeader(Constants.CONTENT_TYPE_HEADER, Constants.CONTENT_TYPE_VALUE_HEADER);
        SplunkRequest request = SplunkRequest.builder().event(messageStr).build();
        try {
            post.setEntity(new StringEntity(new Gson().toJson(request)));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        httpClient.start();
        httpClient.execute(post, new FutureCallback&lt;HttpResponse&gt;() {
            @Override
            public void completed(HttpResponse httpResponse) {
                try {
                    System.out.println(&quot;Request completed: &quot; + IOUtils.toString(httpResponse.getEntity().getContent()));
                } catch (IOException ignored) {
                }
            }
            @Override
            public void failed(Exception e) {
                System.out.println(&quot;Request failed: &quot; + e);
            }

            @Override
            public void cancelled() {
                System.out.println(&quot;Request failed: &quot;);
            }
        });
    }
}
</code></pre>
",https://stackoverflow.com/questions/69089027/how-to-cover-junit-test-cases-for-futurecallbackhttpresponse-completed-failed,"['java', 'junit', 'testcase']",153,False,0,0
How to pass an array of structs inside a struct?,"<p>I'm passing array of structs inside a struct, in unit testing, i have used a dto of ServiceAccounts and my testing code TestStoreServiceAccounts.How to pass an array of structs inside a struct?Nesting of structs is what i'm failing to understand.</p>
<pre><code>func TestStoreServiceAccounts(t *testing.T) {
StoreServiceAccounts = func(serviceAccounts []models.ServiceAccount) ([]string, error) {
    ServiceAccounts := []string{&quot;service-account-details-inserted&quot;}
    return ServiceAccounts, nil
}
Data := dto.ServiceAccountRequestDTO{
    ServiceAccounts : []{ //error on this line
        WorkspaceID:        1,
        ServiceAccountName: &quot;sa-10&quot;,
        ServiceAccountKey: dto.ServiceAccountKey{
            Type:                    &quot;service_account&quot;,
            ProjectID:               &quot;abc&quot;,
            PrivateKeyID:            &quot;123&quot;,
            PrivateKey:              &quot;234&quot;,
            ClientEmail:             &quot;read-clusters&quot;,
            ClientID:                &quot;cdf&quot;,
            AuthURI:                 &quot;https://accounts.google.com/o/oaut&quot;,
            TokenURI:                &quot;https://oauth2.googleapis.com/token&quot;,
            AuthProviderX509CertURL: &quot;https://www.googleapis.com&quot;,
            ClientX509CertURL:       &quot;xwy&quot;,
        },
        CreatedAt: &quot;2021-03-08 17:05:21.0&quot;,
        UpdatedAt: &quot;2021-03-08 17:05:21.0&quot;,
        CreatedBy: &quot;user-01&quot;,
        UpdatedBy: &quot;user-01&quot;,
    },
}

responseData, err := clusterService.StoreServiceAccountsService(context.Background(), Data)
serviceAccountsdata := []string{&quot;service-account-details-inserted&quot;}

assert.Nil(t, err)
assert.NotNil(t, responseData)
assert.EqualValues(t, serviceAccountsdata, responseData)
</code></pre>
<p>}</p>
<pre><code>    // ServiceAccountRequestDTO - DTO of service account model
type ServiceAccountRequestDTO struct {
    ServiceAccounts []struct {
        WorkspaceID        int64             `json:&quot;workspace_id&quot;`
        ServiceAccountName string            `json:&quot;serviceAccountName&quot;`
        ServiceAccountKey  ServiceAccountKey `json:&quot;serviceAccountKey&quot;`
        CreatedAt          string            `json:&quot;created_at&quot;`
        UpdatedAt          string            `json:&quot;updated_at&quot;`
        CreatedBy          string            `json:&quot;created_by&quot;`
        UpdatedBy          string            `json:&quot;updated_by&quot;`
    } `json:&quot;serviceAccounts&quot;`
}```
</code></pre>
",https://stackoverflow.com/questions/67499036/how-to-pass-an-array-of-structs-inside-a-struct,"['unit-testing', 'go', 'struct', 'dto', 'go-gorm']",174,True,-1,1
Spring Boot : JAXBElement null pointer exception,"<p>I am totally new to Junit 5 and Mockito framework. Now I am trying to implement JUnit test cases for the function. Can someone help in Mocking, because the below test implementation throws a NullPointerException at the specified line.</p>
<pre><code>Class XYZ{

       @Autowired
       private SoapCall soapCall;

       public void validate(){
 
                 //code....

            JAXBElement &lt;SubDTO&gt; jax = (JAXBElement &lt;Sub_DTO&gt;) soapCall.callSoapService(val1, val2, val3, val4, val5);
 
            SubDTO  response = jax.getValue();  // Getting null pointer exception while Unit testing at this line   

        }
}
</code></pre>
<p><strong>Unit Testing</strong></p>
<pre><code>Class TestValid{

   @Mock
   SoapCall soapCall;

   @InjectMocks
   XYZ xyzzy;

   @BeforeEach
   void setUp(){
      MockitoAnnotations.initMocks(this);
   }

   @Test
   public void test1(){
        SubDTO dto= new SubDTO(&quot;a&quot;,&quot;b&quot;,&quot;c&quot;);

        JAXBElement&lt;SubDTO&gt; jax = new JAXBElement &lt;&gt; (any(), any(), any());

        jax.setValue(dto)            

   Mockito.when(soapCall.callSoapService(any(),any(),any(),anyInt(),anyInt())).thenReturn( jax );

        Assertions.assertDoesNotThrow(()-&gt;xyz.validate());
   }
}
</code></pre>
",https://stackoverflow.com/questions/67272119/spring-boot-jaxbelement-null-pointer-exception,"['java', 'spring-boot', 'junit', 'mockito']",153,True,0,1
How to unit test this c function?,"<p>I have a simple c function,</p>
<pre><code>uint_8 tempM_main()
{
  if(g_variable1 &gt; g_variable2) 
    tempM = g_variable1;
  else 
    tempM = g_variable2;
} 
</code></pre>
<p>where g_variable1 and g_variable2 are the global variable.
How can i able to unit test this scenario?
equivalent class and boundary class need to apply for this?</p>
<p>I am using Tessy tool for unit testing.</p>
",https://stackoverflow.com/questions/69587449/how-to-unit-test-this-c-function,"['c', 'unit-testing']",67,True,-4,1
Android unit testing how to test observable and Subscriber,"<p>Hi Following is my part of code which I want to test with various requests but I am unable to test as it is observable subscriber patter any idea how to mock subscriber or how to wait for a result in unit testing</p>
<pre><code>api.loadData(request)
            .observeOn(schedulers.main())
            .doOnNext(this::addDataCheck)
            .subscribe(
                    data -&gt; onDataLodaded(listener, data),
                    e -&gt; onAdFailedToLoad(listener, Api.error(request), e)
            )
            .addTo(disposables);
</code></pre>
",https://stackoverflow.com/questions/69942177/android-unit-testing-how-to-test-observable-and-subscriber,"['android', 'unit-testing', 'mockito', 'android-testing', 'android-junit']",1538,False,2,1
How to remove duplicate cases in switch in java,"<p>I have sonarQube running but it says that there are duplicates within these lines of code. How do resolve this in a switch statement? I am just learning how unit testing in java works so any help would be great!</p>
<pre class=""lang-java prettyprint-override""><code>switch () {
    case &quot;M&quot;:
        campusLogo = &quot;/watermark_main.png&quot;;
        break;
    case &quot;IN&quot;:
        campusLogo = &quot;/Watermark_IN.png&quot;;
        break;
    case &quot;WA&quot;:
        campusLogo = &quot;/Watermark_WA.png&quot;;
        break;
    case &quot;MO&quot;:
        campusLogo = &quot;/Watermark_MO.png&quot;;
        break;
    case &quot;NC&quot;:
        campusLogo = &quot;/Watermark_NC.png&quot;;
        break;
    case &quot;NV&quot;:
        campusLogo = &quot;/Watermark_NV.png&quot;;
        break;
    case &quot;OH&quot;:
        campusLogo = &quot;/Watermark_OH.png&quot;;
        break;
    case &quot;TN&quot;:
        campusLogo = &quot;/Watermark_TN.png&quot;;
        break;
    case &quot;TX&quot;:
        campusLogo = &quot;/Watermark_TX.png&quot;;
        break;

    default:
        campusLogo = &quot;/watermark_main.png&quot;;
}
</code></pre>
",https://stackoverflow.com/questions/67609105/how-to-remove-duplicate-cases-in-switch-in-java,"['java', 'duplicates', 'sonarqube']",1085,True,0,2
The type or namespace name &#39;IHolidayProvider&#39; could not be found (are you missing a using directive or an assembly reference?),"<p>This is the code I have below. It's for unit testing. I also have an error for Returns(holidays). It says &quot;(local variable) List holidays
Argument 1: cannot convert from 'System.Collections.Generic.List&lt;DateProject.Holiday&gt;' to '?'&quot;</p>
<p>The error showed when I added &quot;using System.Collections.Generic;&quot;</p>
<pre><code>[Fact]
public void WhatHolidaysAreOnThisDay_FindHolidays_ReturnsHolidays() {

    // Arrange

    var holidayProvider = new Mock&lt;IHolidayProvider&gt;();
    List&lt;Holiday&gt; holidays = new List&lt;Holiday&gt;() {
        new Holiday() {TheDate=new Date(2020, 6, 2), Name=&quot;Beach Day&quot;},
        new Holiday() {TheDate= new Date(2020, 6, 2), Name = &quot;Pizza Day&quot;}
    };
    holidayProvider.Setup(m=&gt; m.GetHolidays(2020)).Returns(holidays);  

    Date date = new Date(2020, 6, 2, holidayProvider.Object);

    // Act

    List&lt;string&gt; findHolidays = date.WhatHolidaysAreOnThisDay();

    // Assert
    Assert.Equal(&quot;Beach Day&quot;, findHolidays[0]);
    Assert.Equal(&quot;Pizza Day&quot;, findHolidays[1]);
}
</code></pre>
",https://stackoverflow.com/questions/67438040/the-type-or-namespace-name-iholidayprovider-could-not-be-found-are-you-missin,"['c#', 'visual-studio-code']",119,False,0,0
when performing Unit Testing with Jest in React Js function component getting &quot;symbol is not a function error &quot;,"<p>I am new to React Js and Jest I tried to perform unit testing with jest I am getting the below error.</p>
<p><strong>DemoContainer.js</strong></p>
<pre><code>import React, { useContext } from 'react';

import { AuthContext, UiContext } from 'Stores';

const DemoContainer = () =&gt; {
    const { user } = useContext(AuthContext);

    return (
        &lt;div data-testid='demo-container' className='demo__container'&gt;
            &lt;h1&gt;{user}&lt;/h1&gt;
        &lt;/div&gt;
    );
};

export default memo(DemoContainer);
</code></pre>
<p><strong>DemoContainer.test.js</strong></p>
<pre><code>import React from 'react';
import DemoContainer from '../demoContainer';
import { render, fireEvent, cleanup } from '@testing-library/react';
import '@testing-library/jest-dom';

afterEach(cleanup);

it('renders correctly', async () =&gt; {
    const mockAction = jest.fn();
    const { getByTestId } = render(&lt;DemoContainer className='demo-container'&gt;&lt;/DemoContainer&gt;);
    const container = getByTestId('demo-container');
    expect(accAction).toHaveClass('met-accordion__title-box');
});
</code></pre>
<p>and the error is</p>
<p><a href=""https://i.stack.imgur.com/IKqLJ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/IKqLJ.png"" alt=""enter image description here"" /></a></p>
<p>I did explore a lot still not able to find the answer.</p>
",https://stackoverflow.com/questions/69521751/when-performing-unit-testing-with-jest-in-react-js-function-component-getting-s,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",129,False,0,0
Is this a unit test or integration test?,"<p>I am learning how to create a unit test in Spring Boot JPA with JUnit and Mockito</p>
<p>I have done up a test class,</p>
<pre><code>public void testInsertionMethod() throws Exception {

    String URI = &quot;/insertionURL&quot;;
    ShoppingList list = new ShoppingList (3, new Fruit(1), new Vegetable(1));
    String inputJson= this.jsonConversionMethod(list);

    Assert.assertEquals(1, list.getNumOfItems());
    Assert.assertEquals(1, list.getFruit().getFruitId);
    Assert.assertEquals(1, list.getVegetable.getVegetableId());

    Mockito.when(shoppingListSvc.save(Mockito.any(ShoppingList.class))).thenReturn(list);

    MvcResult mvcResult = this.mockMvc.perform(MockMvcRequestBuilders.post(URI).param(&quot;fruitId&quot;, &quot;1&quot;).param(&quot;vegId&quot;, &quot;1&quot;). accept(MediaType.APPLICATION_JSON).content(inputJson).contentType(MediaType.APPLICATION_JSON)).andReturn();

    MockHttpServletResponse mockHttpServletResponse = mvcResult.getResponse();
    String jsonOutput = mockHttpServletResponse.getContentAsString();
    assertThat(outputJson).isEqualTo(inputJson);
    Assert.assertEquals(HttpStatus.OK.value(), mockHttpServletResponse.getStatus());

}
</code></pre>
<p>Can anyone advise on how I can improve my unit testing? Am I doing anything wrong here?</p>
",https://stackoverflow.com/questions/69850645/is-this-a-unit-test-or-integration-test,"['java', 'spring-boot', 'unit-testing', 'junit', 'mockito']",347,True,0,1
Coverage Report with Jest and Vue not working,"<p>I am unit testing my Vue project with Jest and I get the code coverage in the console, no problems there, however the HTML report is not working -</p>
<p><a href=""https://i.stack.imgur.com/SPO3i.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/SPO3i.png"" alt=""enter image description here"" /></a></p>
<p>package.json:</p>
<pre><code>...
&quot;unit&quot;: &quot;jest --config test/unit/jest.conf.js --coverage&quot;,
...
</code></pre>
<p>jest.conf.js:</p>
<pre><code>const path = require('path')

module.exports = {
  verbose: true,
  testURL: &quot;http://localhost/&quot;,
  rootDir: path.resolve(__dirname, '../../'),
  moduleFileExtensions: [
    'js',
    'json',
    'vue'
  ],
  moduleNameMapper: {
    '^@/(.*)$': '&lt;rootDir&gt;/src/$1'
  },
  transform: {
    '^.+\\.js$': '&lt;rootDir&gt;/node_modules/babel-jest',
    '.*\\.(vue)$': '&lt;rootDir&gt;/node_modules/vue-jest'
  },
  testPathIgnorePatterns: [
    '&lt;rootDir&gt;/test/e2e'
  ],
  snapshotSerializers: ['&lt;rootDir&gt;/node_modules/jest-serializer-vue'],
  setupFiles: ['&lt;rootDir&gt;/test/unit/setup'],
  mapCoverage: true,
  coverageDirectory: '&lt;rootDir&gt;/test/unit/coverage',
  collectCoverageFrom: [
    'src/**/*.{js,vue}',
    '!src/main.js',
    '!src/router/index.js',
    '!src/plugins/vuetify.js',
    '!**/node_modules/**'
  ]
}

</code></pre>
<p>What might be the cause of that? Thank you in advance.</p>
",https://stackoverflow.com/questions/65860239/coverage-report-with-jest-and-vue-not-working,"['vue.js', 'jestjs']",2700,False,0,1
Unit testing a Web API controller actualResult using moq does not behave as expected,"<p>Unit testing a controller returning <code>IHttpActionResult</code> causes</p>
<blockquote>
<p>System.NullReferenceException: 'Object reference not set to an instance of an object.</p>
</blockquote>
<pre><code>[HttpGet]
public async Task&lt;IHttpActionResult&gt; Get(Guid myId)
{    
    var myaccount = await _myaccountService.GetMyAccount(myId);
    return Ok(myaccount);
}
</code></pre>
<p>In Test Method the code</p>
<pre><code>var actualResult = (await controller.Get(It.IsAny&lt;Guid&gt;()) as OkNegotiatedContentResult&lt;IEnumerable&lt;MyAccount&gt;&gt;).Content;
</code></pre>
<p>Returns</p>
<blockquote>
<p>System.NullReferenceException: 'Object reference not set to an instance of an object.**</p>
</blockquote>
<pre><code>[TestMethod]
public async Task GeMyAccount_Returns_CorrectData()
{
      // Arrange         
      var expectedResult = new List&lt;MyAccount&gt;
     {
         new  MyAccount
          {
           Id = &quot;1&quot;,
           Name = &quot;Name1&quot;
          },
         new  MyAccount
          {
           Id = &quot;2&quot;,
           Name = &quot;Name2&quot;
          },
     };

    //Act 
    var mockMyAccountService = new Mock&lt;IMyAccountService&gt;();
    mockMyAccountService.Setup(mock =&gt; 
    mock.GetMyAccount(It.IsAny&lt;Guid&gt;())).Returns(Task.FromResult(expectedResult));
    var controller = new MyAccountController(mockMyAccountService.Object);

     var actualResult = (await controller.Get(It.IsAny&lt;Guid&gt;()) as 
    OkNegotiatedContentResult&lt;IEnumerable&lt;MyAccount&gt;&gt;).Content;
    mockOnrAccountService.Verify(m =&gt; m.GetMyAccount(It.IsAny&lt;Guid&gt;()));
    Assert.AreEqual(expectedResult, actualResult);
</code></pre>
<p>Not sure what I am doing wrong.</p>
",https://stackoverflow.com/questions/68764689/unit-testing-a-web-api-controller-actualresult-using-moq-does-not-behave-as-expe,"['c#', 'unit-testing', 'asp.net-web-api', 'nunit', 'moq']",100,True,0,1
Is it possible to run UNIT TEST with Cypress standalone version similar to how Jasmine does it? (in browser),"<p>Cypress allows for GUI testing in browser as well as Unit Testing using the NodeJS installation version.
But I was wondering if the standalone version, aside for UI testing, it also allows for Unit testing.
I don't seem to find any information in regards.</p>
<p>I am working on a website project that uses <strong>plain HTML + JS</strong>, meaning that there is <strong>no NodeJS involved</strong> nor anything similar.
I need to write some Unit tests for it.</p>
<p>If I was to use Jasmine, that provides a simple inline script linking such as <code>&lt;script type=&quot;text/javascript&quot; src=&quot;lib/jasmine-{#.#.#}/jasmine.js&quot;&gt;&lt;/script&gt;</code>.</p>
<p>But I'm not sure how it is done in Cypress, or if it is even possible.
It would be handy to be able to do Unit test and UI test with the same testing library.</p>
",https://stackoverflow.com/questions/67152773/is-it-possible-to-run-unit-test-with-cypress-standalone-version-similar-to-how-j,"['unit-testing', 'jasmine', 'cypress']",247,False,1,0
Email working in Test case but not in IIS (localdev or server),"<p>I have an issue where emails are sent out correctly when executed in unit testing in Visual Studio.</p>
<p>However, the exact same piece of code and configuration does not work on IIS.
Instead I receive a IO Exception error:</p>
<p><code>System.Net.Mail.SmtpException: Failure sending mail. ---&gt; System.IO.IOException: The handshake failed due to an unexpected packet format</code></p>
<pre><code>public void SendEmail(List&lt;string&gt; toAddress, string fromAddress, string subject, string htmlBody)
        {
            var mail = new MailMessage();

            mail.From = new MailAddress(fromAddress);

            toAddress.ForEach(x=&gt;mail.To.Add(x));
            var client = new SmtpClient();

            mail.Subject = subject;
            mail.Body = htmlBody;
            mail.IsBodyHtml = true;
            client.Send(mail);
}

&lt;system.net&gt;
    &lt;mailSettings&gt;
      &lt;smtp from=&quot;mail@domain.com.au&quot;&gt;
        &lt;network host=&quot;mail.blah.com.au&quot; port=&quot;26&quot; userName=&quot;username&quot; password=&quot;password&quot; enableSsl=&quot;false&quot; 
                  defaultCredentials=&quot;false&quot;/&gt;
      &lt;/smtp&gt;
    &lt;/mailSettings&gt;
  &lt;/system.net&gt;
</code></pre>
<p>Anyone had similar experience?</p>
",https://stackoverflow.com/questions/66073682/email-working-in-test-case-but-not-in-iis-localdev-or-server,"['c#', 'visual-studio', 'unit-testing', 'mailmessage']",412,False,1,0
How to have a dependency set as a @propertyWrapper be a @ObservableObject?,"<p>I have a first @property wrapper that is made to be UserDefaults called <code>@UserDefault(key: .isSignedIn, defaultValue: false) var isSignedIn: Bool</code>. it is working fine as a publisher by using it this way, <code>$isSignedIn</code> to update my SwiftUI view when used by itself. But I would like to make it in a dependency set in a view model.</p>
<p>Now, to hold UserDefaults values, I create a dependency set as a @propertyWrapper called <code>@Injection(\.localDataManager) var localDataManager</code> that will also be used in unit tests using a subscript solution associated with key called <code>InjectedDependency[\.localDataManager] = LocalDataManagerMock()</code></p>
<p>The problem is that <code>LocalDataManager</code> class is not a <code>@ObservableObject</code> and does not update my SwiftUI view over time.</p>
<ul>
<li>How can <code>LocalDataManager</code> be an <code>@ObservableObject</code> using this <code>InjectedDependency</code> unit testing solution?</li>
</ul>
<p><strong>The SwiftUI view with the view model:</strong></p>
<pre><code>import SwiftUI

struct ContentView: View {

  @StateObject var viewModel = DataViewModel()

  var body: some View {
    VStack(spacing: 16) {
      Text(viewModel.localDataManager.isSignedIn.description)

      Button(action: { viewModel.localDataManager.isSignedIn.toggle() }) {
        Text(&quot;Toggle boolean button&quot;)
      }
    }
  }
}

class DataViewModel: ObservableObject {

  @Injection(\.localDataManager) var localDataManager
}
</code></pre>
<p><strong>What I would like to use as a <code>@ObservableObject</code>:</strong></p>
<pre><code>import Foundation

protocol LocalDataManagerProtocol {
  var isSignedIn: Bool { get set }
}

final class LocalDataManager: LocalDataManagerProtocol {

  @UserDefault(key: .isSignedIn, defaultValue: false)
  var isSignedIn: Bool
}

@propertyWrapper
struct Injection&lt;T&gt; {

  private let keyPath: WritableKeyPath&lt;InjectedDependency, T&gt;

  var wrappedValue: T {
    get { InjectedDependency[keyPath] }
    set { InjectedDependency[keyPath] = newValue }
  }

  init(_ keyPath: WritableKeyPath&lt;InjectedDependency, T&gt;) {
    self.keyPath = keyPath
  }
}
</code></pre>
<p><strong>The <code>@UserDefault</code> code:</strong></p>
<pre><code>import Combine
import SwiftUI

enum UserDefaultsKey: String {
  case isSignedIn
}

protocol UserDefaultsProtocol {
  func object(forKey defaultName: String) -&gt; Any?
  func set(_ value: Any?, forKey defaultName: String)
}
extension UserDefaults: UserDefaultsProtocol {}

@propertyWrapper
struct UserDefault&lt;Value&gt; {

  let key: UserDefaultsKey
  let defaultValue: Value
  var container: UserDefaultsProtocol = UserDefaults.standard

  private let publisher = PassthroughSubject&lt;Value, Never&gt;()

  var wrappedValue: Value {
    get {
      return container.object(forKey: key.rawValue) as? Value ?? defaultValue
    }
    set {
      container.set(newValue, forKey: key.rawValue)
      publisher.send(newValue)
    }
  }

  var projectedValue: AnyPublisher&lt;Value, Never&gt; {
    publisher.eraseToAnyPublisher()
  }
}
</code></pre>
<p><strong>The <code>InjectedDependency</code> solution for Unit Testing:</strong></p>
<pre><code>// Use in Unit Test code in SetUp()
// `InjectedDependency[\.localDataManager] = LocalDataManagerMock()`

protocol InjectedKeyProtocol {
  associatedtype Value
  static var currentValue: Self.Value { get set }
}

struct InjectedDependency {

private static var current = InjectedDependency()

static subscript&lt;K&gt;(key: K.Type) -&gt; K.Value where K: InjectedKeyProtocol {
    get { key.currentValue }
    set { key.currentValue = newValue }
  }

  static subscript&lt;T&gt;(_ keyPath: WritableKeyPath&lt;InjectedDependency, T&gt;) -&gt; T {
    get { current[keyPath: keyPath] }
    set { current[keyPath: keyPath] = newValue }
  }

  var localDataManager: LocalDataManagerProtocol {
    get { Self[LocalDataManagerKey.self] }
    set { Self[LocalDataManagerKey.self] = newValue }
  }
}

private struct LocalDataManagerKey: InjectedKeyProtocol {
  static var currentValue: LocalDataManagerProtocol = LocalDataManager()
}
</code></pre>
",https://stackoverflow.com/questions/69020974/how-to-have-a-dependency-set-as-a-propertywrapper-be-a-observableobject,"['swiftui', 'subscript', 'observableobject', 'property-wrapper']",222,True,0,1
Memory exhausted while running phpunit,"<p>I'm using pest PHP testing framework for unit testing in laravel. Memory is getting exhausted each time when my test cases are run. How can I increase my memory limit for test cases? Below I'm attaching a screenshot of my terminal output <a href=""https://i.stack.imgur.com/EsSCr.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/EsSCr.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/69642927/memory-exhausted-while-running-phpunit,"['laravel', 'phpunit']",1480,True,1,1
Test Cases Method in c# .Net Worker Service,"<p>I'm new to doing unit testing in c# and trying to understand how to do test cases using NUnit in a worker service and I don't know how to replicate it so it tests the same as the method. This is a service that runs and sends SMS's in the background of a computer.</p>
<p>IMessagingInfo.cs - this is the model that I retrieve the information from</p>
<pre><code>public interface IMessagingInfo
{
    public int? ID { get; set; }
    [DataType(DataType.Date)]
    DateTime? APPT_DATE { get; set; }

    string Location { get; set; }

    string TreatmentLocation { get; set; }
    
    string Ward { get; set; }

    string APPT_START { get; set; }

    Guid? ApptId { get; set; }

    string MobilePhone { get; set; }

}
</code></pre>
<p>TwilioHandler.cs: - this is  the method that will check to ensure the values from the database are correct and have values so that the service doesn't send blank information in a text.</p>
<pre><code>public bool CheckModelFieldsValid(IMessagingInfo item)
    {

        if(item == null)
        {
            return false;
        }

        //implement this later as the mobile phone numbers have some that are null in DB
       // if (string.IsNullOrEmpty(item.MobilePhone))
       //{
       //   return false;
       // }
       // 

        if (item.APPT_START == null)
        {
            return false;
        }

        if (string.IsNullOrEmpty(item.TreatmentLocation))
        {
            return false;
        }

        if (string.IsNullOrEmpty(item.Location))
        {
            return false;
        }

        if(string.IsNullOrEmpty(item.Ward))
        {
            return false;
        }

        if (item.ApptId == null)
        {
            return false;
        }
        return true;
    }
</code></pre>
<p>This is what I have so far in TwilioHandlerTests.cs where I dont understand the logistics of Unit testing on how to set up the framework and test cases.</p>
<pre><code>public class Tests
{
    //dbcontext, TwilioHandler, TwilioAccount
    private Mock&lt;DbContextConn&gt; _MockDbContext;
    private Mock&lt;IOptions&lt;TwilioAccount&gt;&gt; _mockoptions;
    private Mock&lt;ILogger&lt;TwilioHandler&gt;&gt; _mockLogger;
    TwilioHandler _twh;

    private Mock&lt;IMessagingInfo&gt; _MessagingInfoMock = new Mock&lt;IMessagingInfo&gt;();


    [SetUp]
    public void Setup()
    {
        _MockDbContext = new Mock&lt;DbContextConn&gt;();
        _mockLogger = new Mock&lt;ILogger&lt;TwilioHandler&gt;&gt;();
        _mockoptions = new Mock&lt;IOptions&lt;TwilioAccount&gt;&gt;();
        //inmemorydatabase routine to add records 
    }
    [Test]
    public void CheckTwilioAccount_ModelFields_Valid_Test()
    {
     //want to replicate method here
    }
</code></pre>
<p>Thank you!</p>
",https://stackoverflow.com/questions/66026694/test-cases-method-in-c-net-worker-service,"['c#', '.net', 'unit-testing', 'testing', 'nunit']",439,True,0,1
Separate ServiceProviders for Unit Testing and Production Code,"<p>I am using ServiceLoader to dynamically load Plugins.
In purpose of unit testing I want to Mock some behavior of these Plugins.
These Mock-Plugins should be used when unit testing, but not when building the Project.
How would one do this though?</p>
<p>I feel like this question is IDE / build tool specific, for that matter I am using Eclipse.</p>
<p>Project Structure:</p>
<ul>
<li>src
<ul>
<li>app
<ul>
<li>app.java</li>
</ul>
</li>
<li>scraper
<ul>
<li>ScraperController.java</li>
<li>Scraper.java</li>
</ul>
</li>
</ul>
</li>
<li>Scrapers</li>
<li>tests
<ul>
<li>mockups
<ul>
<li>FailingScraperMock.jar</li>
<li>...</li>
</ul>
</li>
<li>unit_tests
<ul>
<li>ServiceLoaderWithProvidedMockScrapersTest.java</li>
<li>...</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>scraper.Scraper.java is the provider interface</p>
<p>Scrapers is where all the Scraper-Providers go</p>
<p>I tried to exclude the Mock-Plugins for the source folder: src/ .
Either I am doing it wrong or that's not intended for what I am trying to do.</p>
<p>Would appreciate any kind of help / information.</p>
",https://stackoverflow.com/questions/66507659/separate-serviceproviders-for-unit-testing-and-production-code,"['java', 'eclipse', 'unit-testing', 'plugins', 'serviceloader']",58,False,0,1
Suppress react error in console log during unit testing,"<p>I'm experiencing an error when I am unit testing:</p>
<pre><code>console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
  Error: Uncaught [Error: Invariant failed: You should not use &lt;Redirect&gt; outside a &lt;Router&gt;]
</code></pre>
<p>I know that this is due to the component I am testing having an un-wrapped <code>&lt;Redirect&gt;</code> element:</p>
<pre><code>return &lt;Redirect to={`${myRedirUrl}`}/&gt;;
</code></pre>
<p>however this is being returned as part of a fully-fledged and wrapped <code>&lt;ConnectedRouter&gt;</code> so there is no issue with the app actually working. This complaint is merely during unit testing.</p>
<p>Is there anyway in which I can suppress this message during testing? The unit test is passing as I have been checking during trial runs, it's just annoying that the result is being buried...</p>
<hr />
<p><strong>Component.jsx</strong></p>
<pre><code>export const MyComp = () =&gt; {
  // /my-url will cause redirect to RedirectComponent
  return &lt;Redirect to=&quot;/my-url&quot; /&gt;
}
</code></pre>
<p><strong>Test</strong></p>
<pre><code>it('should redirect without error', () =&gt; {
  const rendered = render(
      &lt;Provider store={store(state)}&gt;
          &lt;BrowserRouter&gt;
              &lt;MyComponent /&gt;
              &lt;Route path='/my-url'&gt;Redirected&lt;/Route&gt;
           &lt;/BrowserRouter&gt;
       &lt;/Provider&gt;
  );

  expect(rendered.container.textContent).toBe('Redirected');
});
</code></pre>
<p>This test passes as I have told it to expect the mock component, however I am getting the error as above due to the <code>MyComp</code> not having a wrapped <code>&lt;Redirect&gt;</code></p>
",https://stackoverflow.com/questions/66210330/suppress-react-error-in-console-log-during-unit-testing,"['javascript', 'reactjs', 'unit-testing', 'error-handling']",183,False,0,0
Cosmos Javascript API for creating collection with Autoscale,"<p>I am using <code>@azure/cosmos</code> with version <code>3.9.5</code> for creating Container and collection in <code>Cosmos DB</code>. I am trying to create collection with maxThroughput parameter so that auto scaling will be enabled.</p>
<p><code>comosRefClient.database(&quot;sample&quot;).containers.createIfNotExists({ id: &quot;samplecoll1&quot;, 5000 });</code></p>
<p>As per documentation, this should create collection with Autoscaling with Max RU of 5000. But collection is created with Manual Mode and 5000 RUs.</p>
<p>I checked in the documentation as well as unit testing code from SDK and ideally things should work fine.</p>
<ol>
<li>API - <a href=""https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/cosmosdb/cosmos/src/client/Container/ContainerRequest.ts"" rel=""nofollow noreferrer"">https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/cosmosdb/cosmos/src/client/Container/ContainerRequest.ts</a></li>
<li>Documentation - <a href=""https://learn.microsoft.com/en-us/javascript/api/@azure/cosmos/containerrequest?view=azure-node-latest"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/javascript/api/@azure/cosmos/containerrequest?view=azure-node-latest</a></li>
<li>Unit Testing from SDK - <a href=""https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/cosmosdb/cosmos/test/public/functional/container.spec.ts"" rel=""nofollow noreferrer"">https://github.com/Azure/azure-sdk-for-js/blob/master/sdk/cosmosdb/cosmos/test/public/functional/container.spec.ts</a></li>
</ol>
<p>Appreciate your help on this question.</p>
",https://stackoverflow.com/questions/66702922/cosmos-javascript-api-for-creating-collection-with-autoscale,"['javascript', 'api', 'collections', 'azure-cosmosdb', 'autoscalemode']",176,True,0,1
Unit Testing Flask-Admin modules?,"<p>I was wondering, is there any way to test a given defined BaseView? can I just integrate it with the Flask testing facilities? I had been looking around and I couldn't find anything about unit testing Flask-Admin views.</p>
<p>I will appreciate any guidance.</p>
",https://stackoverflow.com/questions/65945685/unit-testing-flask-admin-modules,"['flask', 'flask-admin']",76,False,2,0
Resolved: Mocking Angular Dialog afterClosed() for unit test,"<p>I have troubles with mocking popup data for unit testing. Getting an error like: <strong>TypeError: Cannot read property 'showFilterModal' of undefined</strong>
What am I doing wrong?</p>
<p><strong>FilterComponent</strong></p>
<pre><code>public openFilterModal() {
  this.filterModal = this.modalService.showFilterModal(this.filtersOptions, this.userRole, 'bills');
  this.filterModal.afterClosed
    .subscribe(
      (result) =&gt; {
        this.selectedFiltersAmount = result.total;
        this.filtersOptions = result.filters;
      },
      (err) =&gt; {

      });
}
</code></pre>
<p>The idea was to create fake service with necessary observables and functions. Much thanks @Naren</p>
<p><strong>Correct test mocking:</strong></p>
<pre><code>describe('Component', () =&gt; {
  let component: Component;
  let fixture: ComponentFixture&lt;Component&gt;;

  const mockModelService = {
    showFilterModal: 
    jasmine.createSpy('showFilterModal').and.returnValue({ 
      afterClosed: of({
        total: 1,
        filters: null,
        reqObj: {
          status: 'active',
        }
      })})
    };

   beforeEach(() =&gt; {
    TestBed.configureTestingModule({
     imports: [NecessaryModules],
     providers: [
      { provide: LocalModalService, useValue: mockModelService }
     ],
     declarations: [ Component]
    }).compileComponents();
    fixture = TestBed.createComponent(Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create subscription after close modal', () =&gt; {
    component.openFilterModal();
    expect(mockModelService.showFilterModal).toHaveBeenCalled();
    expect(component.selectedFiltersAmount).toBe(1);
  });
});
</code></pre>
",https://stackoverflow.com/questions/65612224/resolved-mocking-angular-dialog-afterclosed-for-unit-test,"['angular', 'testing']",2049,True,2,1
How to test services in angular using jasmine,"<p>I am a beginner in unit testing in Angular using jasmine. How do I test a service using jasmine?
Below is a service:</p>
<pre><code>import { Injectable } from &quot;@angular/core&quot;;
import { environment } from &quot;src/environments/environment&quot;;
import { MessageService } from &quot;../message/message.service&quot;;
import { Observable } from &quot;rxjs&quot;;
import { catchError } from &quot;rxjs/operators&quot;;
import { ShareDto } from &quot;src/app/model/share/share-dto&quot;;
import { HttpHandlerService } from &quot;../http-handler/http-handler.service&quot;;
 
@Injectable({
  providedIn: &quot;root&quot;
})
export class xxxService {
  private apiUrl = environment.requestUrl;
  private shareDefaultUrl = &quot;/share&quot;;
 
  constructor(
    private http: HttpHandlerService,
    private messageService: MessageService
  ) {}
 
  sharing(body: ShareDto): Observable&lt;any&gt; {
    const url = `${this.shareDefaultUrl}`;
 
    return this.http
      .post(this.apiUrl + url, body)
      .pipe(catchError(this.messageService.handleError));
  }
}
</code></pre>
<p>How do I write the testcase in spec file to test the methods present in this service? Please help.</p>
",https://stackoverflow.com/questions/66747072/how-to-test-services-in-angular-using-jasmine,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",71,False,0,1
I am trying to perform unit testing in my code using jest but getting error,"<p>I tried to perform unit testing in my code that will take two parameters in the function and then test whether the function works or not. I am new to jest and still trying to figure out how to write the test cases.</p>
<pre><code>import React, { FC } from 'react';
import styled from 'styled-components';

interface AlertProps {
  message: string;
  onClose: () =&gt; void
}

const Button = styled.button`
    background-color: white;
    font-size: 15px;
    color: black;
    margin: 1em;
    border: 3px;
    padding: 0.25em 6em;
`;

const Para = styled.p`
  font-size: 20px;
  color: white;
  font-family: sans-serif;
  
`;

const Box = styled.div`
  background-color: #b81c36;
  width: 300px;
  padding: 20px;
  margin: auto;
  border-radius: 10px
 
`;
 
const Alert: FC&lt;AlertProps&gt; = ({ message, onClose }) =&gt; {
  return(
    &lt;&gt;
        &lt;Box&gt;
          &lt;Para &gt;{message}&lt;/Para&gt;
          &lt;Button  onClick={onClose}&gt;Close&lt;/Button&gt;
        &lt;/Box&gt;
    &lt;/&gt;
  );
}

export default Alert;
</code></pre>
",https://stackoverflow.com/questions/65697242/i-am-trying-to-perform-unit-testing-in-my-code-using-jest-but-getting-error,"['reactjs', 'typescript', 'unit-testing', 'jestjs', 'ts-jest']",195,False,-1,1
Groovy + Spock testing void method of type &quot;Validator&quot; that throws error when conditions are not met,"<p>I use Groovy + Spock as unit testing tool and I wonder how to write testing methods that return void - sth like validator that can throw an error when conditions are not fulfilled. WHat with then clause?</p>
<pre><code>def &quot;should pass without errors when...&quot;() {
        given:
        //preparing data

        when:
        validator.validate(preparedObject) /// of type void, throws error when conditions not met

        then:
        ???????????????
    }
</code></pre>
<p>What's the best practice for tha situation:</p>
<pre><code>then:
true
</code></pre>
<p>???</p>
",https://stackoverflow.com/questions/66188847/groovy-spock-testing-void-method-of-type-validator-that-throws-error-when-co,"['java', 'groovy', 'spock']",384,False,0,1
How do I setup Dispatcher InvokeAsync Method using moq,"<p>I'm new to unit testing and trying to Mock Dispatcher by writing a wrapper method, but I'm unable to setup the <code>InvokeAsync</code> method to callback.</p>
<p>IDispatcher:</p>
<pre><code>public interface IDispatcher
    {
        // other implementations

        DispatcherOperation InvokeAsync(Action action);

        DispatcherOperation&lt;TResult&gt; InvokeAsync&lt;TResult&gt;(Func&lt;TResult&gt; callback);
    }
</code></pre>
<p>DispatcherWrapper:</p>
<pre><code>public class DispatcherWrapper : IDispatcher
{
        // Other implementations
        public DispatcherOperation InvokeAsync(Action action)
        {
            return this.UIDispatcher.InvokeAsync(action);
        }

        public DispatcherOperation&lt;TResult&gt; InvokeAsync&lt;TResult&gt;(Func&lt;TResult&gt; callback)
        {
            return this.UIDispatcher.InvokeAsync(callback);
        }
}
</code></pre>
<p>The way I'm trying to set it up:</p>
<pre><code>// this works as expected
this.mockDispatcher.Setup(x =&gt; x.BeginInvoke(It.IsAny&lt;Action&gt;())).Callback((Action a) =&gt; a());
</code></pre>
<pre><code>// get an exception : System.ArgumentException : Invalid callback. Setup on method with parameters (Func&lt;Action&gt;) cannot invoke callback with parameters (Action).
this.mockDispatcher.Setup(x =&gt; x.InvokeAsync(It.IsAny&lt;Func&lt;It.IsAnyType&gt;&gt;())).Callback((Action a) =&gt; a());
</code></pre>
<p>Usage:</p>
<pre><code>var res = await this.dispatcher.InvokeAsync(() =&gt;
                                             {
                                                // returns a result by computing some logic
                                             });
</code></pre>
<p>I'm facing the issue only with the test project.</p>
",https://stackoverflow.com/questions/66229155/how-do-i-setup-dispatcher-invokeasync-method-using-moq,"['c#', 'wpf', 'nunit', 'moq', 'dispatcher']",267,True,1,1
How to make a unit test for upload img? React testing library,"<p>Have a problem to simulate uploading the image file via unit testing with Jest and testing library in react.</p>
<p>This is my JSX / component part of the code:</p>
<pre><code> &lt;ChangeImgForm&gt;
        &lt;Image img={uploadedImg || avatarImg} alt=&quot;User profile&quot; /&gt;

        &lt;ButtonsContainer&gt;
          &lt;UploadBtn&gt;
            &lt;FileUploadBtn
              handleFile={handleUploadFile}
              allowExtensions=&quot;.png,.jpeg,.webp&quot;
            /&gt;
          &lt;/UploadBtn&gt;
          &lt;RemoveBtn&gt;
            &lt;Button&gt;Remove&lt;/Button&gt;
          &lt;/RemoveBtn&gt;
        &lt;/ButtonsContainer&gt;
      &lt;/ChangeImgForm&gt;

</code></pre>
<p>This is a UNIT test that I am trying to make work:</p>
<pre><code>test(&quot;Select an image and upload will make a request to upload it&quot;, () =&gt; {
  const { container, getByLabelText, getByText, getByAltText } = render(
    &lt;Settings /&gt;
  );
  const file = new File([&quot;dummy content&quot;], &quot;example.png&quot;, {
    type: &quot;image/png&quot;,
  });
  const uploadBtn = screen.getByTestId(&quot;uploadBtn&quot;);
  const inputFile = screen.getByTestId(&quot;inputFile&quot;);
  fireEvent.change(inputFile, { target: { files: [file] } });

  inputFile.files = [file];
  fireEvent.change(inputFile);

  expect(inputFile.files).toBe(file);
});
</code></pre>
<p>Any comment is welcome</p>
",https://stackoverflow.com/questions/67221178/how-to-make-a-unit-test-for-upload-img-react-testing-library,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",2000,False,1,0
Angular unit testing functions,"<p>I have just started exploring unit testing in angular.
I have a function in .ts file</p>
<pre><code>onValueChange(val: number): void {
this.formGroup.get(this.controlName).setValue(val);
}
</code></pre>
<p>I am trying to test if the controlName has the value passed in the onValueChange parameters</p>
<p>I tried this in the spec.ts file</p>
<pre><code>it('form value should update from form changes', fakeAsync(() =&gt; {
onValueChange(5);
expect(component.formGroup.get(component.controlName)).toEqual(5); 
}));
function onValueChange(val: number): void {
component.formGroup.get(component.controlName).setValue(val);
}
</code></pre>
<p>what am I doing wrong</p>
",https://stackoverflow.com/questions/66438919/angular-unit-testing-functions,"['angular', 'jasmine', 'angular-test']",410,True,0,1
Angular configuration when using Jest,"<p>I've recently switched to Jest for unit testing</p>
<p>Previously I was doing this:</p>
<pre><code>ng test --configuration=unit-tests
</code></pre>
<p>But I am not sure how to run my Jest tests with an Angular configuration, I want something like this:</p>
<pre><code>jest --configuration=unit-tests
</code></pre>
<p>How do I run my Jest tests with a specified Angular configuration?</p>
",https://stackoverflow.com/questions/66011004/angular-configuration-when-using-jest,"['angular', 'jestjs']",99,True,0,2
Unit testing list extension function - Kotlin,"<p>I am new to unit testing, and facing issue with a extension function, which is kind of:</p>
<pre><code>fun List&lt;Water&gt;.getFileteredList() = return listOf(filteredWater)
</code></pre>
<p>Now if I want to test this function, how can I provide the list to the function while testing.</p>
<blockquote>
<p>Water is just and example in this scenario.</p>
</blockquote>
",https://stackoverflow.com/questions/69127385/unit-testing-list-extension-function-kotlin,"['android', 'unit-testing', 'kotlin', 'junit', 'extension-function']",180,False,0,0
React Intl Could not find required `intl` object. &lt;IntlProvider&gt; needs to exist in the component ancestry,"<p>I have used latest version of React-intl(^5.20.2). Trying to achieve Enzyme Unit testing in React hook component. but throwing this error &quot;[React Intl] Could not find required <code>intl</code> object.  needs to exist in the component ancestry.&quot; on UseIntl() inside functional component while running tests</p>
<pre><code>{intl.formatMessage({ id: &quot;Welcome&quot; })}

</code></pre>
",https://stackoverflow.com/questions/68887949/react-intl-could-not-find-required-intl-object-intlprovider-needs-to-exist,"['reactjs', 'jestjs', 'enzyme', 'react-intl', 'react-hooks-testing-library']",5135,False,-1,2
my sonarqube always said no code coverage for java,"<p>hi all i have build unit testing for controller, repository and Service but why in my sonarqube code coverage always give me code coverage only 0 percent. my question is how to make my percentage up ?</p>
<p><a href=""https://i.stack.imgur.com/lFbRQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/lFbRQ.png"" alt=""enter image description here"" /></a></p>
<p>here what i was code in my testing</p>
",https://stackoverflow.com/questions/66468581/my-sonarqube-always-said-no-code-coverage-for-java,"['java', 'sonarqube']",138,False,0,1
How to mock AWS SDK v3 for Node.js?,"<p>I develop some AWS Lambdas using Node.js, which utilizes DynamoDB via AWS SDK v3.</p>
<p>I have no idea how to mock <code>DynamoDBClient</code> using jest properly for the unit testing.</p>
<pre class=""lang-js prettyprint-override""><code>const LambdaTester = require('lambda-tester')

const {DynamoDBClient} = require(&quot;@aws-sdk/client-dynamodb&quot;)
const handler = require('./my-handler').handler

describe('handler', function () {
  it('Handler should work properly', async function () {
    const response = {
      Item: {
        a: {S: 'a'},
        b: {S: 'b'}
      }
    }

    DynamoDBClient.mockImplementation(() =&gt; {
      return {
        send: () =&gt; response
      }
    })

    await LambdaTester(handler)
      .event({
         // ...
      })
      .expectResult((res) =&gt; {
         // ...
      })
    })
})
</code></pre>
<p>When I run the test, it seems like trying to execute the real code and throws me an exception.</p>
<pre><code>ResourceNotFoundException: Requested resource not found
   at deserializeAws_json1_0GetItemCommandError (./node_modules/@aws-sdk/client-dynamodb/protocols/Aws_json1_0.ts:3128:39)
</code></pre>
",https://stackoverflow.com/questions/66027085/how-to-mock-aws-sdk-v3-for-node-js,"['node.js', 'unit-testing', 'jestjs', 'aws-sdk-nodejs']",1690,False,1,1
How to configure code coverage for .vue files?,"<p>I'm using mocha for unit testing and want to add code coverage. For that I added nyc, istanbul-instrumenter-loader and babel-plugin-istanbul and it works for js files but for .vue files an error occurs: &quot;TypeError: Cannot read property 'fileCoverage' of undefined&quot;. Please help me</p>
<p>package.json</p>
<pre><code>{
&quot;name&quot;: &quot;ZINGUI&quot;,
&quot;version&quot;: &quot;1.0.0&quot;,
&quot;description&quot;: &quot;ZINGWHEEEE&quot;,
&quot;author&quot;: &quot;John Matos &lt;rDr4g0n@gmail.com&gt;&quot;,
&quot;private&quot;: true,
&quot;browserslist&quot;: [
    &quot;defaults&quot;
],
&quot;workspaces&quot;: [
    &quot;packages/z-common&quot;,
    &quot;packages/z-search&quot;,
    &quot;packages/z-ui&quot;,
    &quot;packages/z-admin-module&quot;,
    &quot;packages/z-smartviewz-module&quot;,
    &quot;packages/z-theme&quot;,
    &quot;packages/z-dashboard-module&quot;,
    &quot;packages/z-dashboard-base-tiles&quot;,
    &quot;packages/z-events-module&quot;,
    &quot;packages/z-user-module&quot;,
    &quot;packages/z-mock-client&quot;,
    &quot;packages/z-catalog&quot;
],
&quot;scripts&quot;: {
    &quot;dev&quot;: &quot;yarn run z-ui&quot;,
    &quot;z-ui&quot;: &quot;yarn run --cwd=packages/z-ui dev&quot;,
    &quot;watch&quot;: &quot;node scripts/watch.js&quot;,
    &quot;build&quot;: &quot;npm-run-all lint test build-ui&quot;,
    &quot;build-ui&quot;: &quot;yarn run --cwd=packages/z-ui build&quot;,
    &quot;lint&quot;: &quot;yarn workspaces run lint&quot;,
    &quot;test&quot;: &quot;yarn workspaces run test&quot;,
    &quot;test:coverage&quot;: &quot;nyc yarn run test&quot;,
    &quot;bootstrap&quot;: &quot;yarn install&quot;,
    &quot;clean&quot;: &quot;yarn workspaces run clean &amp;&amp; rm -rf node_modules&quot;,
    &quot;add-package&quot;: &quot;cd packages &amp;&amp; vue init ../scripts/package-template&quot;,
    &quot;playground&quot;: &quot;yarn run --cwd=playground playground&quot;,

},
&quot;dependencies&quot;: {
    &quot;@vue/composition-api&quot;: &quot;^0.3.4&quot;,
    &quot;atob&quot;: &quot;^2.1.0&quot;,
    &quot;cryptiles&quot;: &quot;^4.1.2&quot;,
    &quot;dot-prop&quot;: &quot;^4.2.1&quot;,
    &quot;fstream&quot;: &quot;^1.0.12&quot;,
    &quot;graphql&quot;: &quot;^0.13.2&quot;,
    &quot;sshpk&quot;: &quot;^1.13.2&quot;,
    &quot;stringstream&quot;: &quot;^0.0.6&quot;,
    &quot;vue&quot;: &quot;^2.6.6&quot;,
    &quot;vue-router&quot;: &quot;3.0.1&quot;,
    &quot;vuetify&quot;: &quot;2.4.0&quot;,
    &quot;vuex&quot;: &quot;^3.5.1&quot;,
    &quot;clone&quot;: &quot;^2.1.2&quot;,
    &quot;cookies-js&quot;: &quot;^1.2.3&quot;,
    &quot;d3&quot;: &quot;^5.7.0&quot;,
    &quot;d3-format&quot;: &quot;^1.4.3&quot;,
    &quot;deep-equal&quot;: &quot;^2.0.1&quot;,
    &quot;deepmerge&quot;: &quot;^4.2.2&quot;,
    &quot;graphql-tag&quot;: &quot;^2.10.3&quot;,
    &quot;humanize&quot;: &quot;^0.0.9&quot;,
    &quot;humanize-duration&quot;: &quot;^3.22.0&quot;,
    &quot;moment&quot;: &quot;^2.24.0&quot;,
    &quot;throttle-debounce&quot;: &quot;^2.2.1&quot;,
    &quot;yamr-js&quot;: &quot;zenoss/yamr-js#4.6.2&quot;,
    &quot;z-admin-module&quot;: &quot;^1.0.0&quot;,
    &quot;z-catalog&quot;: &quot;^1.0.0&quot;,
    &quot;z-common&quot;: &quot;^1.0.0&quot;,
    &quot;z-dashboard-module&quot;: &quot;^1.0.0&quot;,
    &quot;z-events-module&quot;: &quot;^1.0.0&quot;,
    &quot;z-mock-client&quot;: &quot;^1.0.0&quot;,
    &quot;z-search&quot;: &quot;^1.0.0&quot;,
    &quot;z-smartviewz-module&quot;: &quot;^1.0.0&quot;,
    &quot;z-theme&quot;: &quot;^1.0.0&quot;,
    &quot;z-user-module&quot;: &quot;^1.0.0&quot;,
    &quot;z-in-time&quot;: &quot;zenoss/z-in-time#1.1.7&quot;
},
&quot;devDependencies&quot;: {
    &quot;chai-sorted&quot;: &quot;^0.2.0&quot;,
    &quot;backstopjs&quot;: &quot;^4.5.0&quot;,
    &quot;babel-plugin-istanbul&quot;: &quot;^6.0.0&quot;,
    &quot;chai&quot;: &quot;^4.1.2&quot;,
    &quot;core-js&quot;: &quot;3&quot;,
    &quot;chokidar&quot;: &quot;^2.0.1&quot;,
    &quot;eslint&quot;: &quot;^4.19.1&quot;,
    &quot;eslint-config-airbnb-base&quot;: &quot;^13.0.0&quot;,
    &quot;eslint-friendly-formatter&quot;: &quot;^3.0.0&quot;,
    &quot;eslint-import-resolver-webpack&quot;: &quot;^0.8.3&quot;,
    &quot;eslint-loader&quot;: &quot;^2.0.0&quot;,
    &quot;eslint-plugin-import&quot;: &quot;^2.20.0&quot;,
    &quot;eslint-plugin-vue&quot;: &quot;^6.2.2&quot;,
    &quot;eslint-plugin-vuetify&quot;: &quot;^1.0.0-beta.7&quot;,
    &quot;inject-loader&quot;: &quot;^4.0.1&quot;,
    &quot;istanbul-instrumenter-loader&quot;: &quot;^3.0.1&quot;,
    &quot;jsdom&quot;: &quot;^11.12.0&quot;,
    &quot;jsdom-global&quot;: &quot;^3.0.2&quot;,
    &quot;mocha&quot;: &quot;^5.2.0&quot;,
    &quot;mocha-webpack&quot;: &quot;2.0.0-beta.0&quot;,
    &quot;npm-run-all&quot;: &quot;^4.1.2&quot;,
    &quot;nyc&quot;: &quot;^15.1.0&quot;,
    &quot;sinon&quot;: &quot;^6.1.4&quot;,
    &quot;sinon-chai&quot;: &quot;^3.2.0&quot;,
    &quot;webpack-merge&quot;: &quot;^4.1.0&quot;,
    &quot;webpack-node-externals&quot;: &quot;^1.7.2&quot;,
    &quot;yargs&quot;: &quot;^15.1.0&quot;
}
</code></pre>
<p>}</p>
<p>.babelrc</p>
<pre><code>{
  &quot;env&quot;: {
    &quot;development&quot;: {
      &quot;presets&quot;: [
        [&quot;env&quot;, { &quot;modules&quot;: false }],
        &quot;stage-3&quot;
      ]
    },
    &quot;production&quot;: {
      &quot;presets&quot;: [
        [&quot;env&quot;, { &quot;modules&quot;: false }],
        &quot;stage-3&quot;
      ]
    },
    &quot;test&quot;: {
      &quot;presets&quot;: [
        [&quot;env&quot;, {
          &quot;modules&quot;: false,
          &quot;targets&quot;: { &quot;node&quot;: &quot;current&quot; }
        }],
        &quot;stage-3&quot;
      ],
        &quot;plugins&quot;: [
            [&quot;istanbul&quot;, {
                &quot;exclude&quot;: [
                    &quot;**/*.spec.js&quot;
                ]
            }]
        ]
    }
  }
}
</code></pre>
<p>webpack.base.conf.js</p>
<pre><code>            {
            test: /\.js$|\.vue$/,
            use: {
                loader: &quot;istanbul-instrumenter-loader&quot;,
                options: { esModules: true }
            },
            enforce: 'post',
            exclude: /node_modules|\.spec\.js$/
        }
</code></pre>
",https://stackoverflow.com/questions/67210393/how-to-configure-code-coverage-for-vue-files,"['javascript', 'vue.js', 'unit-testing', 'code-coverage', 'nyc']",452,False,4,0
ViewModel unit testing with Repository + LiveData + Coroutines,"<p>So I'm confused about how to implement the unit testing to my ViewModel. I'm using retrofit for my API fetching and using the repository.</p>
<p>ViewModel.kt</p>
<pre><code>@HiltViewModel
class MoviesViewModel @Inject constructor(private val moviesRepository: MoviesRepository) :
ViewModel() {
private val _navigatetoDetail = MutableLiveData&lt;Movies?&gt;()

fun getPopularMovies() = liveData(Dispatchers.Default) {
    emit(Resource.loading(null))
    try {
        emit(Resource.success(moviesRepository.getPopularMovies()))
    } catch (e: Exception) {
        emit(
            Resource.error(
                null,
                e.message ?: &quot;Unknown Error&quot;
            )
        )
        Log.e(&quot;viewModel&quot;, &quot;popularMovies error: ${e.message}&quot;)
    }
}

fun getMovieDetails(movie_id: String) = liveData(Dispatchers.Default) {
    emit(Resource.loading(null))
    try {
        emit(Resource.success(moviesRepository.getMovieDetails(movie_id)))
    } catch (e: Exception) {
        emit(
            Resource.error(
                null,
                e.message ?: &quot;Unknown Error&quot;
            )
        )
        Log.e(&quot;viewModel&quot;, &quot;movieDetails error: ${e.message}&quot;)
    }
}

fun navigatetoDetail(): LiveData&lt;Movies?&gt; {
    return _navigatetoDetail
}

fun onMovieClicked(movies: Movies?) {
    _navigatetoDetail.value = movies
}

fun onMovieDetailNavigated() {
    _navigatetoDetail.value = null
}
</code></pre>
<p>Repository.kt</p>
<pre><code>class MoviesRepository @Inject constructor(private var apiInterface: ApiInterface) {
init {
    apiInterface = ApiBuilder.createService()
}

suspend fun getPopularMovies() = apiInterface.getPopularMovies()

suspend fun getMovieDetails(movie_id: String) = apiInterface.getMovieDetails(movie_id)

suspend fun getPopularTvShows() = apiInterface.getPopularTvShows()

suspend fun getTvShowDetails(tvshow_id: String) = apiInterface.getTvShowDetails(tvshow_id)
</code></pre>
<p>apiInterface.kt</p>
<pre><code>interface ApiInterface {
@GET(&quot;/3/movie/popular?api_key=$API_KEY&amp;language=en-US&quot;)
suspend fun getPopularMovies(): Envelope&lt;List&lt;Movies&gt;&gt;

@GET(&quot;/3/movie/{movie_id}?api_key=$API_KEY&amp;language=en-US&quot;)
suspend fun getMovieDetails(@Path(&quot;movie_id&quot;) movie_id: String?): Movies

@GET(&quot;3/tv/popular?api_key=$API_KEY&amp;language=en-US&amp;page=1&quot;)
suspend fun getPopularTvShows(): Envelope&lt;List&lt;TvShows&gt;&gt;

@GET(&quot;/3/tv/{tvshow_id}?api_key=$API_KEY&amp;language=en-US&quot;)
suspend fun getTvShowDetails(@Path(&quot;tvshow_id&quot;) tvshow_id: String?): TvShows
</code></pre>
<p>I already tried to test my ViewModel by making it like this:</p>
<pre><code> @Test
fun testGetPopularMovies() = coroutinesTestRule.testDispatcher.runBlockingTest {
    val moviesList = viewModel.getPopularMovies().value
    viewModel.getPopularMovies().observeForever(observer)
    verify(observer).onChanged(argumentCaptor.capture())
    assertEquals(20, moviesList?.data?.results?.size)
}
</code></pre>
<p>but it return NullPointerException on <em><strong>viewModel.getPopularMovies().observeForever(observer)</strong></em></p>
",https://stackoverflow.com/questions/67613391/viewmodel-unit-testing-with-repository-livedata-coroutines,"['android', 'unit-testing', 'kotlin', 'retrofit']",1509,True,1,2
Calling a function which is inside a Thread,"<p>I was doing Unit Testing and finding code coverage using gtest and lcov.
My function is</p>
<pre><code>void MyClass::MyFunction(const std::string&amp; argument1, const std::string&amp; argument2) {
    std::thread([this, argument1, argument2]() {
        std::unique_lock&lt;std::mutex&gt; live_lock_(live_mutex_);
        int64_t time_stamp = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(std::chrono::system_clock::now().time_since_epoch()).count();
        int64_t time_to_live = myList[argument1] - (time_stamp % myList[argument1]); 
        cond_var_.wait_for(time_to_live_lock_, std::chrono::milliseconds(time_to_live), [this, argument1] { return cond_var_status_[argument1]; });
        if (message_master_.find(argument1) != message_master_.end()) {
            //something
        }
    }).detach();
    std::cout&lt;&lt; &quot;end line is executed&quot;&lt;&lt;std::endl; }
</code></pre>
<p>and my test function is</p>
<pre><code>TEST(test, test1) {
    Myclass testObj;
    testObj.MyFunction(&quot;arg1&quot;, &quot;arg2&quot;);
    ASSERT_EQ(&quot;&quot;,&quot;&quot;);
};
</code></pre>
<p>When I run the test, all codes except those inside thread are executed.
So is there any solution to call those codes inside thread too?</p>
",https://stackoverflow.com/questions/65881112/calling-a-function-which-is-inside-a-thread,"['c++', 'pthreads', 'googletest', 'gcov', 'lcov']",96,False,1,2
SSIS Unit-test not run well (incompatible),"<p>I tried find and use a open source framework for <strong>start BI project</strong> with TDD .</p>
<p>I choose <a href=""https://github.com/johnwelch/ssisUnit"" rel=""nofollow noreferrer"">SSISUNIT</a> for step one. ssisUnit is a unit testing framework for SQL Server Integration Services. It is loosely based on the xUnit family of unit testing frameworks, but is tailored to better support the SSIS environment.</p>
<p>Download <a href=""https://github.com/johnwelch/ssisUnit"" rel=""nofollow noreferrer"">SSISUNIT</a> project and run solution 2017 in VS. But I've error when sln open.</p>
<p>Problem :</p>
<p><a href=""https://i.stack.imgur.com/gcpIT.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gcpIT.png"" alt=""enter image description here"" /></a></p>
<p><a href=""https://i.stack.imgur.com/94zxg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/94zxg.png"" alt=""enter image description here"" /></a></p>
<p><a href=""https://i.stack.imgur.com/i4zXV.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/i4zXV.png"" alt=""enter image description here"" /></a></p>
<p>I tried :</p>
<ul>
<li>Install the latest version of SSDT recommendation (<a href=""https://stackoverflow.com/questions/18148445/cannot-open-sqlproj-because-it-is-not-supported"">in this question</a>)
I have SQL Server Integration Services Project, Microsoft reporting service project, Microsoft analysis service project</li>
</ul>
<p><a href=""https://i.stack.imgur.com/6r2sS.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/6r2sS.png"" alt=""enter image description here"" /></a></p>
<ul>
<li>Read <a href=""https://stackoverflow.com/questions/45613218/unsupported-this-version-of-visual-studio-is-unable-to-open-the-following-projec"">same question</a> but not worked for me in vs 2019.</li>
<li>I tried changed the Project platform to x86,x64 and AnyCPU.</li>
</ul>
<blockquote>
<p>We use SQL-SERVER 2019 SSIS SSAS(MDX), Visual Studio 2019, Power BI</p>
</blockquote>
",https://stackoverflow.com/questions/65580692/ssis-unit-test-not-run-well-incompatible,"['c#', 'visual-studio', 'unit-testing', 'ssis', 'xunit']",135,True,0,1
control return automatically and last line not executing in unit test case using mocha and chai,"<p>I'm new in unit testing in node.js using mocha and chai.
I'm stuck at the problem in which control return automatically and not executing
chai.expect(123).to.be.a(&quot;string&quot;);</p>
<p>code is here</p>
<pre><code>it.only(&quot;should fetch status&quot;,()=&gt;{
        return chai.request(server)
        .get(&quot;/user/status&quot;)
        .then((result)=&gt;{
            let data = result.body;
            console.log(&quot;till here execute&quot;);

            //this line is not executed and test case is passed even when the below line expect to fail the test
            chai.expect(123).to.be.a(&quot;string&quot;);
            
        })
        .catch(err=&gt;err);
    });
</code></pre>
<p>Console show that above test case is passed I don't know how and why</p>
<pre><code>chai.expect(123).to.be.a(&quot;string&quot;);
</code></pre>
<p>not executing</p>
",https://stackoverflow.com/questions/66655132/control-return-automatically-and-last-line-not-executing-in-unit-test-case-using,"['node.js', 'mocha.js', 'chai']",45,True,0,1
Releasing WKNavigationAction subclass crashes on iOS 15,"<p>For unit testing I have subclassed <code>WKNavigationAction</code>. It's a common practice and can be found across the internet and in big SDKs, too.</p>
<p>On iOS 15 releasing an instance of it leads to a crash inside WebKit.</p>
<p>Stacktrace:</p>
<pre class=""lang-none prettyprint-override""><code>Thread 1 Queue : com.apple.main-thread (serial)
#0  0x0000000130d8b702 in WTF::RunLoop::dispatch(WTF::Function&lt;void ()&gt;&amp;&amp;) ()
#1  0x0000000134ed41e4 in WebCoreObjCScheduleDeallocateOnMainRunLoop(objc_class*, objc_object*) ()
#2  0x000000011290711d in -[WKNavigationAction dealloc] ()
#3  0x000000010cf2f9f7 in objc_object::sidetable_release(bool, bool) ()
</code></pre>
<p>Example Playground:</p>
<pre class=""lang-swift prettyprint-override""><code>import WebKit

class MockNavigationAction: WKNavigationAction {}

var navigationAction: WKNavigationAction? = MockNavigationAction()

navigationAction = nil
</code></pre>
<p>Suggestions about how to solve this are very appreciated.</p>
",https://stackoverflow.com/questions/69736487/releasing-wknavigationaction-subclass-crashes-on-ios-15,"['ios', 'swift', 'webkit', 'ios15']",427,True,2,1
How to test a function inside React functional component using jest.spyOn with React Testing Library,"<p>This is a simple React component. I'm using React Testing Library for unit testing components and I was not able to test the <code>handleClick</code> function of <code>TestComponent</code> using <code>jest.spyOn()</code>. Could anyone please help?</p>
<p><strong>Component</strong></p>
<pre><code>import React from 'react';

const Button = (props) =&gt; (
  &lt;button onClick={props.handleClick}&gt; {props.text}&lt;/button&gt;
);

const TestComponent = () =&gt; {
  const handleClick = () =&gt; {
    console.log('clicked!');
  };
  return (
    &lt;div&gt;
      &lt;Button text=&quot;Test Button&quot; handleClick={handleClick} /&gt;
    &lt;/div&gt;
  );
};

export default TestComponent;
</code></pre>
<p><strong>Test</strong></p>
<pre><code>  it('expect spy to be called', () =&gt; {
    const { getByText } = render(&lt;TestComponent /&gt;);
    
    const spy = jest.spyOn(TestComponent, 'handleClick');
    
    const button = getByText('Test Button');
    fireEvent.click(button);
    expect(spy).toHaveBeenCalled();
  });
</code></pre>
<p>The error that I'm getting is below. I tried using <code>TestComponent.prototype</code> in <code>jest.spyOn</code> but that does not help either.</p>
<pre><code>Cannot spy the handleClick property because it is not a function; undefined given instead
</code></pre>
",https://stackoverflow.com/questions/68060782/how-to-test-a-function-inside-react-functional-component-using-jest-spyon-with-r,"['javascript', 'reactjs', 'jestjs', 'react-testing-library']",879,True,2,1
How to mock &#39;replace&#39; function with Jest Javascript React Native?,"<p>I use Jest as unit testing on the React Native App I created. For currency formatting purposes I use the 'replace' function from Javascript as below:</p>
<p>This my code :</p>
<pre><code>amount.replace(/(\d)(?=(\d{3})+(?!\d))/g,'$1.',)

</code></pre>
<p>I'm getting a 'TypeError: Cannot read property' replace 'of undefined' while running my TDD Jest</p>
<p>Please help, thank you</p>
",https://stackoverflow.com/questions/66074852/how-to-mock-replace-function-with-jest-javascript-react-native,"['javascript', 'reactjs', 'react-native', 'jestjs', 'tdd']",1408,True,2,1
How to perform unit testing a react filter component using jest and &#39;react-dom/test-utils&#39;?,"<p>This is the react component which I am trying to unit test using <code>react-dom/test-utils</code></p>
<pre><code>import React from 'react'
import DatePicker from '../../../../../client/src/components/DatePicker.jsx'
import { Input } from '../../../../../client/src/forms/components.js'
import Select from 'react-select'
 
export class ListFilter extends React.PureComponent {
 render() {
   const { users, filters, filterHandler, filterSubmitHandler } = this.props
   return (
     &lt;div className='filter row'&gt;
       &lt;div className='col-lg-3 pb-1 pr-lg-1'&gt;
         &lt;Select
           labelKey='user'
           name='select-user'
           onChange={e =&gt; filterHandler('userId', e)}
           options={programs}
           placeholder='Filter by User...'
           simpleValue
           value={filters['userId'] &amp;&amp; parseInt(filters['userId'])}
           valueKey='id'
           disabled={false}
         /&gt;
       &lt;/div&gt;
       &lt;div className='col-lg-3 pb-1 pr-lg-1'&gt;
         &lt;DatePicker
           className='form-control'
           onChange={e =&gt; filterHandler('createdAt', e)}
           value={filters['createdAt']}
           placeholder={'Filter by Date...'}
         /&gt;
       &lt;/div&gt;
       &lt;div className='col-lg-3 pb-1 pr-lg-1'&gt;
         &lt;Input
           className='form-control mb-1 mr-md-1'
           key={'role'}
           name={'role'}
           onChange={e =&gt; filterHandler('role', e)}
           placeholder={'Search by Role...'}
           value={filters['role']}
         /&gt;
       &lt;/div&gt;
       &lt;div className='col-lg-1.5 pb-1 pr-lg-1'&gt;
         &lt;button
           className='btn btn-primary form-control mb-1'
           type='submit'
           onClick={filterSubmitHandler}
         &gt;
           &lt;i className='fa fa-search' /&gt; Search
         &lt;/button&gt;
       &lt;/div&gt;
     &lt;/div&gt;
   )
 }
}
</code></pre>
<p>Here is the unit test code that I started with and confused to proceed.</p>
<pre><code>jest.unmock('../ListFilter.jsx')
 
import { ListFilter } from '../ListFilter.jsx'
import React from 'react'
import ReactDOM from 'react-dom'
import Select from 'react-select'
import TestUtils, { Simulate } from 'react-dom/test-utils'
 
describe('ListFilter', () =&gt; {
 let props
 beforeEach(() =&gt; {
   props = {
     filters: {
       createdAt: null,
       order: 'event,desc',
       page: 1,
       userId: '',
       role: ''
     },
     users: [
       {
         id: 573,
         name: 'Gokul',
       },
       {
         id: 993,
         name: 'Vimal'
       },
       {
         id: 93,
         name: 'Bimal'
       }
     ]
   }
 })
 
 let component, onChange, filterHandler, filterSubmitHandler, node
 function render() {
   filterHandler = jest.fn()
   filterSubmitHandler = jest.fn()
 }
 
 describe('onChange', () =&gt; {
   beforeEach(render)
   it('should call onChange when user changes', () =&gt; {
     const container = document.createElement('div')
     ReactDOM.render(
       &lt;ListFilter
         {...props}
         filterHandler={filterHandler}
         filterSubmitHandler={filterSubmitHandler}
       /&gt;,
       container
     )
     
     container.querySelector('select').simulate('change')
     expect(container.querySelector('select').text()).toEqual('Gokul')
   })
 })
})
</code></pre>
<p>Can anyone please help me out to perform the full unit testing of the above component. Many thanks in advance.</p>
",https://stackoverflow.com/questions/69969278/how-to-perform-unit-testing-a-react-filter-component-using-jest-and-react-dom-t,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",1213,False,0,0
Request-promise + post+ mock,"<p>I am using jest as Unit testing framework. I just tried to mock the <strong>POST</strong> method of <strong>request-promise</strong> library. But i am gettign error</p>
<p><strong>a.js</strong> file:</p>
<pre><code>const rp = require('request-promise');
async abc(req, res){
const options = {      
      port: 8888,      
      body:data,
      url: 'http://url',
      method: 'POST',      
      headers: {
        'Content-Type': 'application/json'        
      }
    let response = await rp(options);
    console.log(&quot;rrreess&quot;, response);
    response = JSON.parse(response);
    }
});
</code></pre>
<p><strong>a.spec.ts</strong></p>
<pre><code>jest.mock('request-promise', () =&gt; ({
    post: jest.fn()
  }));
const rp = require('request-promise');
jest.spyOn(rp, 'post').mockResolvedValue({            
        }); 
</code></pre>
<p>But i am receiving error <strong>TypeError: rp is not a function</strong> in a.js file. Is i am mocking correctly?</p>
",https://stackoverflow.com/questions/66550206/request-promise-post-mock,"['node.js', 'unit-testing', 'jestjs']",683,True,0,1
Vue Jest Testing await in loop,"<p>I'm pretty new in unit testing and I'm having some issues writing a function test for await in a loop.</p>
<p>code to test:</p>
<pre><code>export default {
  name: 'MyComponent',
  setup() {
    const count = ref&lt;number&gt;(0);

    function foo(count: number, delay: number): Promise&lt;void&gt; {
      const resolver = async (resolve: () =&gt; void) =&gt; {
    
        count.value = count;

        while (count.value &gt;= 0) {
          await yoo();
          await wait(delay);
          
          count.value -= 1;
        }
      }
      
      return new Promise&lt;void&gt;(resolver);
    }
    
    async function yoo() {
      // something
      await koo();
      // something else
    }

    function wait(waitTime: number): Promise&lt;void&gt; {
      const resolver = (resolve: () =&gt; void) =&gt; {
        setTimeout(resolve, waitTime);
      };

      return new Promise(resolver);
    }
  }
}
</code></pre>
<p>test:</p>
<pre><code>let wrapper = mount(MyComponent);
let promise: Promise&lt;void&gt;;
let count = 5;

jest.useFakeTimers();

beforeAll(() =&gt; {
  promise = wrapper.vm.foo(count, 100);
})

test(`count value decreases at each iteration`, async () =&gt; {
  while (wrapper.vm.count &gt;= 0) {
    const prevCountValue = wrapper.vm.count;

    await flushPromises();
    jest.runAllTimers();

    expect(wrapper.vm.count).toBe(prevCountValue - 1);
  }
}
</code></pre>
<p>Writing the test in this way breaks due to jest.setTimeout.Error:
<a href=""https://i.stack.imgur.com/F6RrE.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/F6RrE.png"" alt=""enter image description here"" /></a></p>
<p>Any ideas on what is the correct way to write this test?</p>
",https://stackoverflow.com/questions/67018531/vue-jest-testing-await-in-loop,"['vue.js', 'asynchronous', 'async-await', 'jestjs', 'ts-jest']",390,False,0,0
Unable to add reference through suggested action in VS Community,"<p>While trying to add a reference to class in a unit testing class, it takes infinitly long time to execute. I am adding the reference through &quot;Suggested action&quot; shortcut.
I've attached an image below. This keeps going on. I have reinstalled VS, but the problem still there.</p>
<br>
<p><a href=""https://i.stack.imgur.com/cDPhl.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/cDPhl.jpg"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/65664582/unable-to-add-reference-through-suggested-action-in-vs-community,"['c#', 'visual-studio']",261,True,0,1
How can I fix this Unit Test?,"<p>I'm fairly new to unit testing my .tsx files and I am currently having trouble testing this (sorry if the format is off)</p>
<pre><code>//this is Banner.tsx

import React, {useCallback} from &quot;react&quot;;
type Properties = {
    close: () =&gt; void;
   text: string;

const Banner: React.FC&lt;Properties&gt; = ({close, text}) =&gt; {
const onClick = useCallback(() =&gt; {
               close();},
               [close, text]);
return (
  &lt;div className = &quot;BannerBox&quot;&gt;
       &lt;div className = &quot;banner&quot;&gt;
      &lt;span className = &quot;popup&quot;&gt; onClick={onClick}[x]
      &lt;/span&gt;
      {text}
      &lt;/div&gt;
 &lt;/div&gt;
 );
 };
export default Banner;


//this is App.tsx

import Banner from &quot;./Components/Banner&quot;;
function App(): JSX.Element {

const [isOpen, setIsOpen]=useState(false);
  const toggleBanner = () =&gt; {
  SetIsOpen(!isOpen);
};

return (
&lt;div&gt;
  &lt;input type = &quot;button&quot;
      value = &quot;popup&quot;
      onClick={toggleBanner}/&gt;
      &lt;p&gt;hi&lt;/p&gt;
      {isOpen &amp;&amp; &lt;Banner text = {&quot;hello&quot;} close={() =&gt; isOpen(false)}/&gt;}
&lt;/div&gt;
  export default App;
</code></pre>
<p>this is what i have so far</p>
<pre><code>//Banner.test.tsx
test(&quot;Check that all type Properties are being used&quot;, () =&gt; {
render(&lt;Banner /&gt;);
})
</code></pre>
<p>it gives this error -&gt; &quot;type {} is missing the following properties  from type Banner: close and text&quot;</p>
",https://stackoverflow.com/questions/70028619/how-can-i-fix-this-unit-test,"['reactjs', 'typescript', 'unit-testing', 'tsx']",269,True,0,1
jest stop working after setting &quot;type&quot;: &quot;module&quot; in tsconfig.json,"<p>I am using jest for unit testing in typescript. When setting &quot;type&quot;: &quot;module&quot; in the tsconfig.json, i can run my app, but my jest stops working and say &quot;ReferenceError: require is not defined&quot;.</p>
<pre><code>const { pathsToModuleNameMapper } = require(&quot;ts-jest/utils&quot;);

const { compilerOptions } = require(&quot;./tsconfig&quot;);

const paths = pathsToModuleNameMapper(compilerOptions.paths, { prefix: &quot;&lt;rootDir&gt;/src&quot; });

delete paths[&quot;^(.*)$&quot;];
</code></pre>
<p>Eslint is giving me &quot;Parsing error: &quot;parserOptions.project&quot; has been set for @typescript-eslint/parser&quot;.</p>
",https://stackoverflow.com/questions/67011729/jest-stop-working-after-setting-type-module-in-tsconfig-json,"['node.js', 'typescript', 'jestjs']",224,False,0,1
How can i make DateUtil throw an exception?,"<pre><code>
    @Override
        public void contextDestroyed(ServletContextEvent sce) {
            try{
                DateUtil.clean();
            }catch(Exception e){
                LOGGER.error(&quot;MyServletContextListener contextDestroyed error: &quot;, e);
            }

</code></pre>
<p>I am doing unit testing on the above piece of code, and am trying to get 100% line coverage by hitting the Exception clause, however, i cant seem to make it work with my implementation. Would appreciate any help yall. Please look below for my implementation.</p>
<pre><code> @Test (expected= Exception.class)
    public void test_contextDestroyed_Exception() {

        DateUtil wrapper = Mockito.spy(new DateUtil());
        Exception e = mock(Exception.class);

        when(wrapper).thenThrow(e);
       Mockito.doThrow(e)
                .when(myServletContextListener)
                .contextDestroyed(sce);

        myServletContextListener.contextDestroyed(sce);
    } 
</code></pre>
",https://stackoverflow.com/questions/67669034/how-can-i-make-dateutil-throw-an-exception,"['java', 'mockito', 'junit4']",110,True,0,2
How to Handle Subscribe in component.spec.ts Jasmine?,"<p>I am still learn about Jasmine x Karma and I got stuck when I need to create unit testing for function which have .subscribe()
In <strong>component.ts</strong> the code look like this</p>
<pre><code> loadListDownloadRequestGroup() {
this.noItem = false;
this.listDownloadService.getDownloadRequestGroup(
  this.offsetPage,
  this.getGroupId,
  this.setOrder,
  this.keywordSend
).subscribe(resp =&gt; {
  const getResp: DownloadModel[] = [];
  if (resp.items.length) {
    resp.items.forEach(item =&gt; {
      const listArr: DownloadModel = {};
      listArr.id = item.id;
      listArr.queryId = item.queryId;
      listArr.createdAt = item.createdAt;
      listArr.filename = item.filename;
      listArr.queryName = item.queryName;
      listArr.widgetName = item.widgetName;
      listArr.type = item.type;
      listArr.labelName = item.labelName;
      listArr.createdByName = item.createdByName;
      listArr.expiredAt = item.expiredAt;
      listArr.status = item.status;
      listArr.group = item.group;
      listArr.groupId = item.group ? item.group.id : null;
      listArr.groupName = item.group ? item.group.name : '-';
      getResp.push(listArr);
    });
  } else {
    this.noItem = true;
    this.emptyDataText = (this.isInitGetlistData == false) ? 
      'There is no data to display' : 
      'There is no search result. Please input different keyword';
  }
  this.dataSourceDT = new MatTableDataSource(getResp);
  this.dataSourceDT.sort = this.sort;
  this.totalData = resp.total;
  this.totalOffset = Math.ceil(this.totalData / 5);
}, (error) =&gt; {
  if (error.graphQLErrors[0].statusCode === 403) {
    this.route.navigate(['unauthorized']);
  }
});
</code></pre>
<p>}</p>
<p>on <strong>.spec.ts</strong> I write like this but it's doesn't effect the code coverage</p>
<p>it('loadListDownloadRequestGroup', () =&gt; {</p>
<pre><code>// const getAllDownload =  spyOn(listDownloadService, 'getAllDownload').and.callThrough();

const event = { items: [{
  id: 2,
  queryId: 2,
  createdAt: '2019-09-09',
  filename: 'test',
  queryName: 'test lagi',
  widgetName: 'test widget',
  type: 'test type',
  labelName: 'test labelName',
  createdByName: 'test createdByName',
  expiredAt: '2019-08-08',
  status: 'published',
  group: {
    id: 1,
    name: 'test group'
  }
}] };

component.loadListDownloadRequestGroup();
// expect(getAllDownload).toHaveBeenCalled();
expect(component.isInitGetlistData).toBeFalsy();
expect(component.noItem).toBeFalsy();
expect(event.items.length).toEqual(1);
</code></pre>
<p>})</p>
",https://stackoverflow.com/questions/68147881/how-to-handle-subscribe-in-component-spec-ts-jasmine,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",50,False,0,1
Creating a unit test for the angular directive using Karma,"<p>I am new to unit testing and would like to create a unit test suite for the angular directive that will set the focus of the form to the first invalid field.
Can someone provide me the unit test and this will help me learn Karma.</p>
<pre><code>import { Directive, HostListener, ElementRef } from '@angular/core';
@Directive({
  selector: '[focusInvalidInput]'
})
export class FocusFormDirective {
  constructor(private el: ElementRef) {}
  @HostListener('submit')
  onFormSubmit() {
    const invalidControl = this.el.nativeElement.querySelector('.ng-invalid');
    
    if (invalidControl) {
      invalidControl.focus();
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/68370084/creating-a-unit-test-for-the-angular-directive-using-karma,"['angular', 'karma-jasmine']",45,False,0,1
Returning a Promise from &quot;describe&quot; is not supported In Nestjs Unit testing,"<p>I want to do unit testing of service in nestjs using mongoose.
This error comes up at the end</p>
<blockquote>
<p>Returning a Promise from &quot;describe&quot; is not supported. Tests must be defined synchronously.</p>
</blockquote>
<blockquote>
<p>Returning a value from &quot;describe&quot; will fail the test in a future version of Jest.</p>
</blockquote>
<p><img src=""https://i.stack.imgur.com/PGSai.png"" alt=""enter image description here"" /></p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { MongooseModule } from '@nestjs/mongoose';

import { closeInMongodConnection, rootMongooseTestModule } from '../test-utils/mongo/MongooseTestModule';
import { UserSchema } from './user.model';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

describe('UserController', async () =&gt; {
  let controller: UsersController;
  let service: UsersService;

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      imports: [rootMongooseTestModule(), MongooseModule.forFeature([{ name: 'User', schema: UserSchema }])],
      controllers: [UsersController],
      providers: [UsersService],
    }).compile();

    controller = module.get&lt;UsersController&gt;(UsersController);
    service = module.get&lt;UsersService&gt;(UsersService);
  });

  it('should be defined', () =&gt; {
    expect(controller).toBeDefined();
  });

  it('should return all the events', async () =&gt; {
    const result = {
      totalDocs: 0,
      resource: [],
    };

    const data = await service.findAll();
    expect(data).toEqual(result);
  });
  

  afterAll(async () =&gt; {
    await closeInMongodConnection();
  });
});
</code></pre>
<p><img src=""https://i.stack.imgur.com/bs1oz.png"" alt="""" /></p>
",https://stackoverflow.com/questions/66744886/returning-a-promise-from-describe-is-not-supported-in-nestjs-unit-testing,"['javascript', 'node.js', 'unit-testing', 'testing', 'nestjs']",2243,True,0,1
hibernate FetchType.LAZY fetching 0 record even the records being inserted,"<p>The FetchType.LAZY is not working under the unit testing and showing 0 records</p>
<p>The line below showing 0 records
log.info(&quot;Starting Lazy Search size ==&gt;&quot; + setLazy.size());</p>
<p>The line below showing 1k records being inserted</p>
<p>There are one parent (StockEntity) and one child (StockDailyRecordEntity)</p>
<p>Total StockDailyRecordEntity Inserted -----&gt;1000</p>
<pre><code>package repo;

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

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.test.context.junit4.SpringRunner;

import com.app.advance.entity.StockDailyRecordEntity;
import com.app.advance.entity.StockEntity;
import com.app.advance.repo.StockDailyRecordRepo;
import com.app.advance.repo.StockRepo;

import lombok.extern.slf4j.Slf4j;

@RunWith(SpringRunner.class)
@Slf4j
@SpringBootTest

public class StockRepoPerformance {

    @Autowired
    StockRepo stockRepo;

    @Autowired
    StockDailyRecordRepo stockDailyReportRepo;

    @Test
    public void testPerformanceInsert() {
        StockEntity stockEntity = new StockEntity();
        stockEntity.setStockCode(&quot;Code&quot;);
        stockEntity.setStockName(new Date().toString());
        stockRepo.save(stockEntity);
        for (int i = 0; i &lt; 1000; i++) {

            StockDailyRecordEntity stockDailyRecordEntity = new StockDailyRecordEntity();
            stockDailyRecordEntity.setStock(stockEntity);
            stockDailyRecordEntity.setDesc(new Date().toString());
            Set&lt;StockDailyRecordEntity&gt; stockDailyRecords = new HashSet&lt;StockDailyRecordEntity&gt;();
            stockDailyRecords.add(stockDailyRecordEntity);
            stockDailyReportRepo.save(stockDailyRecordEntity);

        }
        log.info(&quot;Total StockDailyRecordEntity Inserted -----&gt;&quot; + stockDailyReportRepo.findAll().size());
        stockRepo.save(stockEntity);
        log.info(&quot;Starting Lazy Search&quot;);
        Set&lt;StockDailyRecordEntity&gt; setLazy = stockEntity.getStockDailyRecords();
        log.info(&quot;Starting Lazy Search size ==&gt;&quot; + setLazy.size());

        log.info(&quot;Starting Eager Search&quot;);
        log.info(&quot;testPerformanceInsert ends&quot;);
    }
}

package com.app.advance.entity;

import static javax.persistence.GenerationType.IDENTITY;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

import lombok.Getter;
import lombok.Setter;

// https://mkyong.com/hibernate/cascade-jpa-hibernate-annotation-common-mistake/

@Entity
@Table(name = &quot;trx_stock&quot;)
@Getter
@Setter
public class StockEntity implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 4174876690328458921L;

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = &quot;STOCK_ID&quot;, unique = true, nullable = false)
    private Integer stockId;

    @Column(name = &quot;STOCK_CODE&quot;, nullable = false, length = 10)
    private String stockCode;

    @Column(name = &quot;STOCK_NAME&quot;, nullable = false, length = 200)
    private String stockName;
    
    @OneToMany(fetch = FetchType.LAZY, mappedBy = &quot;stock&quot;, orphanRemoval = true)
    @Cascade({CascadeType.ALL})
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Set&lt;StockDailyRecordEntity&gt; stockDailyRecords = new HashSet&lt;StockDailyRecordEntity&gt;();
    
    //@OneToMany(fetch = FetchType.EAGER, mappedBy = &quot;stock&quot;, orphanRemoval = true)
    //@Cascade({CascadeType.ALL})
    //@OnDelete(action = OnDeleteAction.CASCADE)
    //private Set&lt;StockDailyRecordEntity&gt; stockDailyRecordsEager = new HashSet&lt;StockDailyRecordEntity&gt;();
}

package com.app.advance.entity;

import static javax.persistence.GenerationType.IDENTITY;

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import lombok.Getter;
import lombok.Setter;

@Entity
@Table(name = &quot;trx_stock_daily_record&quot;)
@Getter
@Setter
public class StockDailyRecordEntity implements java.io.Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = -7102491956593238645L;

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = &quot;RECORD_ID&quot;, unique = true, nullable = false)
    private Integer recordId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = &quot;STOCK_ID&quot;, nullable = false)
    private StockEntity stock;
    
    @Column(name = &quot;STOCK_DESC&quot;, length = 200)
    private String desc;

}
</code></pre>
",https://stackoverflow.com/questions/69157070/hibernate-fetchtype-lazy-fetching-0-record-even-the-records-being-inserted,"['java', 'hibernate', 'jpa']",33,True,0,1
How can i get the code coverage percentage information?,"<p>I'm trying to do unit testing in swift. I have a two-class named <code>MyFileManager</code> and <code>SomeViewModel</code></p>
<pre><code>class MyFileManager {
    static let shared = MyFileManager()
    
    func isStored(atPath path: String) -&gt; Bool {
        return FileManager.default.fileExists(atPath: path)
    }
    func readData(atPath path: String) -&gt; Data? {
        return try? Data(contentsOf: URL(fileURLWithPath: path))
    }
}

class SomeViewModel {
    func getCachedData() -&gt; Data? {
        let path = &quot;xxxxx&quot;
        
        if MyFileManager.shared.isStored(atPath: path) {
            return MyFileManager.shared.readData(atPath: path)
        } else {
            return nil
        }
    }
}
</code></pre>
<p>I've written a test code. I'm not sure whether this code will give me 100% code coverage or not. Here is the unit test</p>
<pre><code>class LinePhoneTests: XCTestCase {

    override func setUpWithError() throws {
        testGetCachedData()
    }

    func testGetCachedData() {
        let viewModel = SomeViewModel()
        
        let data = viewModel.getCachedData()
        XCTAssertFalse((data != nil))
        
        XCTAssertTrue((data == nil))
    }

}
</code></pre>
<p>How can I get code coverage percentage information?</p>
",https://stackoverflow.com/questions/68423973/how-can-i-get-the-code-coverage-percentage-information,"['ios', 'swift', 'unit-testing', 'code-coverage']",503,True,0,1
Unit testing - Comparing environment,"<p>I would like to implement unit testing in R by comparing list of objects in an environment stored as rds with the current environment. I am sharing some of the codes I was trying to implement to provide an idea on what I would want</p>
<pre><code>
library(rlang)

a = FALSE
b = &quot;a&quot;
c = 2.3
d = 1:3


saveRDS(mget(ls()), file = &quot;unit.rds&quot;)

# unit_t &lt;- readRDS(file = &quot;unit.rds&quot;)

env &lt;- new_environment(readRDS(file = &quot;unit.rds&quot;))

identical(global_env(), current_env())

identical(new_environment(readRDS(file = &quot;unit.rds&quot;)), global_env())

identical(mget(ls()), list(readRDS(file = &quot;unit.rds&quot;)))

</code></pre>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/67823642/unit-testing-comparing-environment,"['r', 'unit-testing']",24,False,1,0
How To Unit Test NextJS API Route That Uses Repository Pattern?,"<p>I am new prisma / nextjs user and I am trying to understand how to unit test an API route that uses prisma. I have read the <a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""nofollow noreferrer"">unit testing guide</a>.</p>
<p>I like the dependency injection approach and have started trying to implement it. However I am struggling with the following development issue. Can anybody help?</p>
<ul>
<li>With the dependency injection approach the <a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""nofollow noreferrer"">unit testing guide</a> explains how to setup the mock context and use this in the data access layer. Does anyone have any examples of how and where the real context could be initialised and used with an API route that uses a repository pattern? Is it possible to expand the next.js api handler with middleware to include the context to facilitate testing?</li>
</ul>
<pre class=""lang-js prettyprint-override""><code>import type { NextApiRequest, NextApiResponse } from 'next'

import { PublishRepository } from '../../../repository'

// PUT /api/publish/:id
export default async function handle(
    req: NextApiRequest,
    res: NextApiResponse
) {
    if (req.method == 'PUT') {
        const postId = req.query.id;


        let repo = new PublishRepository( // where does the live context come from and how is it initialised??? )
        const post = repo.set_published(postId)

        res.json(post);
    }
}
</code></pre>
<p><strong>Repository - Initialised using Context instance - How is this initialise for development and how is it mocked?</strong></p>
<pre class=""lang-js prettyprint-override""><code>import { Post, PrismaClient } from &quot;@prisma/client&quot;
import { Context } from &quot;../context&quot;

import prisma from &quot;lib/prisma&quot;


export class PublishRepository {
    private prisma: PrismaClient

    constructor(context: Context) {
        this.prisma = context.prisma
    }

    async set_published(post_id: string | string[]): Promise&lt;Post&gt; {
        return await prisma.post.update({
            where: { id: Number(post_id) },
            data: { published: true },
        });
    }
}
</code></pre>
",https://stackoverflow.com/questions/68792648/how-to-unit-test-nextjs-api-route-that-uses-repository-pattern,"['next.js', 'prisma']",604,False,2,0
how to unit test httpParams in Jasmine,"<p>I'm pretty new in unit testing. I have a function which is setting query params:</p>
<pre><code>setParams(scale): HttpParams {
    return this.params = new HttpParams()
        .set('scale', scale);
}
</code></pre>
<p>The output is passing right to the http get method. But I have no idea how to test if the function above is really giving http params. Can anyone give me some advice? Thanks!</p>
",https://stackoverflow.com/questions/66549847/how-to-unit-test-httpparams-in-jasmine,"['javascript', 'angular', 'jasmine', 'karma-runner']",529,True,1,1
GitHub Actions Django Testing errors with ValueError: Port could not be cast to integer value as &#39;None&#39;,"<p>I have a Django and Django REST app, and when I run my unit testing locally, every test runs and passes.  However, when I create a GitHub Action to run my unit testing, 6 of my unit tests failure with the following message:</p>
<pre><code>File &quot;/opt/hostedtoolcache/Python/3.9.5/x64/lib/python3.9/urllib/parse.py&quot;, line 178, in port
    raise ValueError(message) from None
ValueError: Port could not be cast to integer value as 'None'
</code></pre>
<p>Here is my Action:</p>
<pre><code>django-test-lint:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:12.3-alpine
        env:
          POSTGRES_USER: postgres
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: github_actions
        ports:
          - 5432:5432
        options: --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Set up Python 3.9
        uses: actions/setup-python@v1
        with:
          python-version: 3.9
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
      - name: psycopg2 prerequisites
        run: sudo apt-get install libpq-dev
      - name: Run migrations
        run: python app/manage.py migrate
      - name: Run tests and lint with coverage
        run: |
          cd app
          coverage erase
          coverage run manage.py test &amp;&amp; flake8
          coverage report -m
</code></pre>
<p>The impression I get, is this happens with these 6 tests when it is trying to send a post, patch, or delete to my endpoints.  It's like Github Actions can't fine my container host when running my Django RF app. Maybe it's something to do with my allowed hosts.  I've tried many configs in my settings.py, but nothing is working. Here is my current settings around allowed hosts, have I got something wrong?</p>
<pre><code>if os.environ.get('GITHUB_WORKFLOW'):
    ALLOWED_HOSTS = os.getenv('DJANGO_ALLOWED_HOSTS', '127.0.0.1').split(',')
else:
    ALLOWED_HOSTS = [os.environ.get('HOST_IP'), '127.0.0.1', 'localhost']
</code></pre>
<p>Whilst the whole Django-test-lint job completes, I get theses errors and therefore no longer get 100% coverage on my unit tests.</p>
",https://stackoverflow.com/questions/68003504/github-actions-django-testing-errors-with-valueerror-port-could-not-be-cast-to,"['python-3.x', 'django', 'django-rest-framework']",296,False,2,0
Jest-Native &quot;SyntaxError: Cannot use import statement outside a module&quot;,"<p>Trying to do some unit testing using <a href=""https://github.com/callstack/react-native-testing-library"" rel=""nofollow noreferrer"">https://github.com/callstack/react-native-testing-library</a> + <a href=""https://github.com/testing-library/jest-native"" rel=""nofollow noreferrer"">https://github.com/testing-library/jest-native</a>, I have no problem testing plain javascript files, but I encounter the following error when testing on components :</p>
<pre><code> ● Test suite failed to run

    Jest encountered an unexpected token

    Details:

    C:\Users\admin\Documents\my_project\node_modules\@expo\vector-icons\FontAwesome5.js:1
    ({&quot;Object.&lt;anonymous&gt;&quot;:function(module,exports,require,__dirname,__filename,global,jest){import FontAwesome5 from './build/FontAwesome5';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | import React from 'react'
      2 | import View from 'react-native'
    &gt; 3 | import FontAwesome5 from &quot;react-native-vector-icons/FontAwesome5&quot;
        | ^

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
      at Object.&lt;anonymous&gt; (src/components/file1.js:3:1)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.853 s, estimated 2 s
Ran all test suites.
</code></pre>
<p>package.json :</p>
<pre><code>{
  &quot;main&quot;: &quot;node_modules/expo/AppEntry.js&quot;,
  &quot;scripts&quot;: {
    &quot;start&quot;: &quot;expo start&quot;,
    &quot;android&quot;: &quot;expo start --android&quot;,
    &quot;ios&quot;: &quot;expo start --ios&quot;,
    &quot;web&quot;: &quot;expo start --web&quot;,
    &quot;eject&quot;: &quot;expo eject&quot;,
    &quot;test&quot;: &quot;jest&quot;
  },
  &quot;dependencies&quot;: {
    &quot;@react-native-community/masked-view&quot;: &quot;^0.1.10&quot;,
    &quot;@react-navigation/material-bottom-tabs&quot;: &quot;^5.3.14&quot;,
    &quot;@react-navigation/native&quot;: &quot;^5.9.3&quot;,
    &quot;@react-navigation/stack&quot;: &quot;^5.14.3&quot;,
    &quot;expo&quot;: &quot;~40.0.0&quot;,
    &quot;expo-linear-gradient&quot;: &quot;^8.4.0&quot;,
    &quot;expo-status-bar&quot;: &quot;~1.0.3&quot;,
    &quot;galio-framework&quot;: &quot;^0.8.0&quot;,
    &quot;react&quot;: &quot;16.13.1&quot;,
    &quot;react-dom&quot;: &quot;16.13.1&quot;,
    &quot;react-native&quot;: &quot;https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz&quot;,
    &quot;react-native-appearance&quot;: &quot;~0.3.3&quot;,
    &quot;react-native-bouncy-checkbox&quot;: &quot;^2.0.0&quot;,
    &quot;react-native-drop-shadow&quot;: &quot;^0.0.2&quot;,
    &quot;react-native-gesture-handler&quot;: &quot;^1.10.3&quot;,
    &quot;react-native-modal&quot;: &quot;^11.7.0&quot;,
    &quot;react-native-paper&quot;: &quot;^4.7.2&quot;,
    &quot;react-native-progress-bar-animated&quot;: &quot;^1.0.6&quot;,
    &quot;react-native-safe-area-context&quot;: &quot;^3.1.9&quot;,
    &quot;react-native-vector-icons&quot;: &quot;^8.1.0&quot;,
    &quot;react-native-web&quot;: &quot;~0.13.12&quot;,
    &quot;react-navigation-stack&quot;: &quot;^2.10.4&quot;,
    &quot;remove-accents&quot;: &quot;^0.4.2&quot;,
    &quot;tslib&quot;: &quot;^2.1.0&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;^7.9.0&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.13.12&quot;,
    &quot;@babel/preset-react&quot;: &quot;^7.13.13&quot;,
    &quot;@testing-library/jest-native&quot;: &quot;^4.0.1&quot;,
    &quot;@testing-library/react-native&quot;: &quot;^7.2.0&quot;,
    &quot;@types/react&quot;: &quot;~16.9.35&quot;,
    &quot;@types/react-native&quot;: &quot;~0.63.2&quot;,
    &quot;babel-jest&quot;: &quot;^26.6.3&quot;,
    &quot;jest&quot;: &quot;^26.6.3&quot;,
    &quot;react-test-renderer&quot;: &quot;^16.14.0&quot;,
    &quot;ts-jest&quot;: &quot;^26.5.4&quot;,
    &quot;typescript&quot;: &quot;~4.0.0&quot;
  },
  &quot;jest&quot;: {
    &quot;preset&quot;: &quot;react-native&quot;
  },
  &quot;private&quot;: true
}
</code></pre>
<p>babel.config.js :</p>
<pre><code>module.exports = function (api) {
  api.cache(true);
  return {
    presets:
      ['babel-preset-expo'],
  };
};
</code></pre>
<p>jest.config.js :</p>
<pre><code>module.exports = {
    preset: 'react-native',
    moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
    transformIgnorePatterns: [
        &quot;node_modules/(?!(react-native&quot;
        + &quot;|react-native-vector-icons/FontAwesome5&quot;
        + &quot;)/)&quot;,
    ],
}
</code></pre>
<p>How can I fix this ? Thanks for you help !</p>
",https://stackoverflow.com/questions/66975634/jest-native-syntaxerror-cannot-use-import-statement-outside-a-module,"['javascript', 'reactjs', 'react-native', 'unit-testing', 'jestjs']",997,True,2,1
set_target_properties does not work with multiple --wrap functions,"<pre><code>#include &lt;stdarg.h&gt;
#include &lt;setjmp.h&gt;
#include &lt;stddef.h&gt;
#include &lt;cmocka.h&gt;
#include &quot;stdint.h&quot;

typedef enum {
    eSTATE_STARTUP,
    eSTATE_ADDRESSING,
    eSTATE_RANDOMISE,
    eSTATE_SELECTED
}e_State_t;

void test_main()
{
    static e_State_t e_state = eSTATE_STARTUP;

    if(get_rx_dali_flag())
      {
          application_process(&amp;e_state);
      }

      switch(e_state)
      {
          case eSTATE_STARTUP:
          {
              set_led_frequency(0);
              break;
          }
          case eSTATE_ADDRESSING:
          {
              set_led_frequency(1);
              break;
          }
          case eSTATE_RANDOMISE:
          {
              set_led_frequency(10);
              break;
          }
          case eSTATE_SELECTED:
          {
              set_led_frequency(100);
              break;
          }
          default:
              break;
      }
}



int __wrap_get_rx_dali_flag(void)
{
    int data_available = mock_type(uint8_t);
    return data_available;
}

void __wrap_application_process(e_State_t * ptr_state)
{   
    check_expected_ptr(ptr_state);
    *ptr_state = mock_type(e_State_t);
}

void __wrap_set_led_frequency(uint16_t frequency)
{
    assert_int_equal(frequency, 1);
}



void main_should_setLedFreq_1_when_stateADDRESSING()
{
    will_return(__wrap_get_rx_dali_flag, 1);
    will_return(__wrap_application_process, eSTATE_ADDRESSING);

    test_main();
}



int main()
{
    const struct CMUnitTest tests[] =
    {
        cmocka_unit_test(main_should_setLedFreq_1_when_stateADDRESSING),
    };

    return cmocka_run_group_tests(tests, NULL, NULL);
}
</code></pre>
<p>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++</p>
<pre><code>cmake_minimum_required(VERSION 3.21 FATAL_ERROR)
    
SET(CMAKE_C_COMPILER &quot;C:/msys64/mingw64/bin/gcc.exe&quot;)
SET(GCC_COVERAGE_COMPILE_FLAGS &quot;-g&quot;)
    
project(beTheLight-unit-tests VERSION 1.0 LANGUAGES C)

include(cmake/FetchCMocka.cmake)

add_executable(beTheLight-unit-tests main.c)
target_compile_features(beTheLight-unit-tests PRIVATE c_std_99)
target_link_libraries(beTheLight-unit-tests PRIVATE cmocka-static)

enable_testing()
add_test(NAME beTheLight-unit-tests COMMAND beTheLight-unit-tests)

set_target_properties(beTheLight-unit-tests PROPERTIES LINK_FLAGS &quot;-Wl, --wrap=get_rx_dali_flag, --wrap=set_led_frequency, --wrap=application_process&quot;)
</code></pre>
<p>==============================================================</p>
<pre><code> [ 50%] Linking C executable beTheLight-unit-tests.exe
    gcc.exe: error: unrecognized command-line option '--wrap=get_rx_dali_flag,'
    gcc.exe: error: unrecognized command-line option '--wrap=set_led_frequency,'
    gcc.exe: error: unrecognized command-line option '--wrap=application_process'
    make[2]: *** [beTheLight-unit-tests.exe] Error 1
    make[1]: *** [CMakeFiles/beTheLight-unit-tests.dir/all] Error 2
    make: *** [all] Error 2
</code></pre>
<p>I am trying to get cmocka unit testing to work but for some reason the linker does not accept multiple --wrap linker flags. I have seen people doing it this way at another post in stackoverflow. I am using gcc version 10.3.0 built by MSYS2 project on win10.</p>
",https://stackoverflow.com/questions/70045411/set-target-properties-does-not-work-with-multiple-wrap-functions,"['c', 'unit-testing', 'cmake', 'linker-flags', 'cmocka']",229,True,0,1
Angular unit test case for @HostListener escape key event,"<p>I have below code in my component</p>
<pre><code>@HostListener('document:keydown', ['$event']) onKeydownHandler(event: KeyboardEvent) {
if (event.key === 'Escape') {
  this.showDialogPopup = false;
  this.showPortfolioDialogPopup = false;
}
}
</code></pre>
<p>And I am using ngneat spectator as my unit testing framework, below is my test case which needs to be corrected</p>
<pre><code>it('Close popups on Escape key press', () =&gt; {
const keyboardEvent = createKeyboardEvent('keydown', 'Escape');
const spy = spyOn(keyboardEvent, 'preventDefault'); 
spectator.component.showPopup(false);  
spectator.component.showPortfolioPopup(false);
expect(spectator.component.showPortfolioDialogPopup).toBeFalsy();
expect(spectator.component.showDialogPopup).toBeFalsy();
});
</code></pre>
<p>Here I am not able to understand how to mock the escape key event. Any help would be appreciated. Thanks.</p>
",https://stackoverflow.com/questions/66167986/angular-unit-test-case-for-hostlistener-escape-key-event,"['angular', 'jasmine', 'spectator']",1595,True,0,1
SharePoint Framework SPFx using @pnp/sp/presets/all with react + SharePoint SPFx,"<p>I have SharePoint SPFx projects using react.</p>
<p>I have configured the jest unit testing framework. While running the test case it displays the error related to Unexpected token.</p>
<p>Configured the jest framework using the below link:</p>
<p><a href=""https://github.com/Voitanos/jest-preset-spfx-react16%5B%5D%5B1%5D"" rel=""nofollow noreferrer"">https://github.com/Voitanos/jest-preset-spfx-react16[][1]</a></p>
<p><strong>PnpSpCrud.tsx</strong></p>
<pre><code>import * as React from 'react';
import styles from './PnpSpCrud.module.scss';
import { IPnpSpCrudProps } from './IPnpSpCrudProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { sp } from &quot;@pnp/sp/presets/all&quot;;
import BlockUi from 'react-block-ui';

export class PnpSpCrud extends React.Component&lt;IPnpSpCrudProps, {
  name: any,
  tech: any,
  employees: any[],
  isUpdate: boolean,
  empId: any,
  empIndex: any,
  blocking: boolean
}&gt; {

  constructor(props) {
    super(props);
    this.state = {
      name: '',
      tech: '',
      employees: [],
      isUpdate: false,
      empId: '',
      empIndex: '',
      blocking: false
    };

    this.getEmployee();
    this.enterName = this.enterName.bind(this);
    this.enterTechnology = this.enterTechnology.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  private enterName(event) {
    this.setState({ name: event.target.value });
  }

  private enterTechnology(event) {
    this.setState({ tech: event.target.value });
  }

  private handleSubmit(event) {
    this.addEmployee(this.state);
    event.preventDefault();
  }

  public render(): React.ReactElement&lt;IPnpSpCrudProps&gt; {
    return (
      &lt;BlockUi tag=&quot;div&quot; blocking={this.state.blocking}&gt;
        &lt;div className={styles.pnpSpCrud}&gt;
          &lt;div className={styles.container}&gt;
            &lt;div className={styles.row}&gt;
              &lt;div className={styles.column}&gt;
                {/* &lt;span className={styles.title}&gt;Welcome to SharePoint!&lt;/span&gt;
              &lt;p className={styles.subTitle}&gt;Customize SharePoint experiences using Web Parts.&lt;/p&gt;
              &lt;p className={styles.description}&gt;{escape(this.props.description)}&lt;/p&gt; */}
                &lt;h4&gt;Add Employee&lt;/h4&gt;
                &lt;form&gt;
                  &lt;div className=&quot;row&quot;&gt;
                    &lt;div className=&quot;col-md-6&quot;&gt;
                      &lt;div className=&quot;form-group&quot;&gt;
                        &lt;label&gt;Employee Name&lt;/label&gt;
                        &lt;input type=&quot;text&quot; className=&quot;form-control&quot; placeholder=&quot;Enter name&quot; value={this.state.name} onChange={this.enterName} /&gt;
                      &lt;/div&gt;
                    &lt;/div&gt;
                    &lt;div className=&quot;col-md-6&quot;&gt;
                      &lt;div className=&quot;form-group&quot;&gt;
                        &lt;label&gt;Technology&lt;/label&gt;
                        &lt;input type=&quot;text&quot; className=&quot;form-control&quot; placeholder=&quot;Enter Technology&quot; value={this.state.tech} onChange={this.enterTechnology} /&gt;
                      &lt;/div&gt;
                    &lt;/div&gt;
                    {/* &lt;input type=&quot;text&quot; placeholder=&quot;Employee Name&quot; value={this.state.name} onChange={this.enterName}&gt;&lt;/input&gt;
                  &lt;input type=&quot;text&quot; style={{ marginLeft: 5 }} placeholder=&quot;Technology&quot; value={this.state.tech} onChange={this.enterTechnology}&gt;&lt;/input&gt;
                  &lt;div style={{ marginTop: 5 }}&gt;
                    &lt;input type=&quot;submit&quot; value=&quot;Submit&quot; /&gt;
                  &lt;/div&gt; */}
                  &lt;/div&gt;
                &lt;/form&gt;
                &lt;button className=&quot;btn btn-primary mb-5&quot; onClick={this.handleSubmit}&gt;Submit&lt;/button&gt;
                &lt;h4&gt;Employees&lt;/h4&gt;
                &lt;table className=&quot;table table-dark&quot;&gt;
                  &lt;tbody&gt;
                    &lt;tr&gt;
                      &lt;th&gt;#&lt;/th&gt;
                      &lt;th&gt;Name&lt;/th&gt;
                      &lt;th colSpan={2}&gt;Technology&lt;/th&gt;
                    &lt;/tr&gt;
                    {
                      this.state.employees.map((ele, index) =&gt; {
                        return (
                          &lt;tr&gt;
                            &lt;td&gt;{index + 1}&lt;/td&gt;
                            &lt;td&gt;{ele.Title}&lt;/td&gt;
                            &lt;td&gt;{ele.tech}&lt;/td&gt;
                            &lt;td style={{ color: 'while', cursor: 'pointer' }}&gt;&lt;i className=&quot;fa fa-pencil&quot; aria-hidden=&quot;true&quot; onClick={() =&gt; this.updateEmployee(ele.ID, index)}&gt;&lt;/i&gt;&lt;/td&gt;
                            &lt;td style={{ color: 'while', cursor: 'pointer' }}&gt;&lt;i className=&quot;fa fa-trash&quot; style={{ color: 'while' }} aria-hidden=&quot;true&quot; onClick={() =&gt; this.deleteEmployee(ele.ID, index)}&gt;&lt;/i&gt;&lt;/td&gt;
                          &lt;/tr&gt;
                        );
                      })
                    }
                  &lt;/tbody&gt;
                &lt;/table&gt;
                {/* &lt;a href=&quot;https://aka.ms/spfx&quot; className={styles.button}&gt;
                &lt;span className={styles.label}&gt;Learn more&lt;/span&gt;
              &lt;/a&gt; */}
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/BlockUi&gt;
    );
  }

  private getEmployee() {
    return new Promise((resolve, reject) =&gt; {
      sp.web.lists.getByTitle('EmployeeList').items.select('ID, Title, tech').get().then((result: any[]) =&gt; {
        console.log(&quot;get employees result&quot;, result);
        resolve(result);
        this.setState({
          employees: result
        });
      }).catch((err) =&gt; {
        console.log(&quot;error in get employees&quot;, err);
      });
    });
  }

  private addEmployee(state) {
    if (this.state.name &amp;&amp; this.state.tech) {
      if (this.state.isUpdate) {
        this.setState({ blocking: true });
        return new Promise((resolve, reject) =&gt; {
          let data = {
            Title: state.name,
            tech: state.tech
          };
          sp.web.lists.getByTitle('EmployeeList').items.getById(this.state.empId).update(data).then((result: any) =&gt; {
            resolve(result);
            alert('Employee Updated');
            this.state.employees[this.state.empIndex].Title = data.Title;
            this.state.employees[this.state.empIndex].tech = data.tech;
            this.setState({ name: '', tech: '', isUpdate: false, empId: '', empIndex: '', blocking: false });
          }).catch((err) =&gt; {
            alert('Employee Not Updated');
            this.setState({ blocking: false });
            console.log(&quot;error in update employee&quot;, err);
          });
        });
      }
      else {
        this.setState({ blocking: true });
        return new Promise((resolve, reject) =&gt; {
          let data = {
            Title: state.name,
            tech: state.tech
          };
          sp.web.lists.getByTitle('EmployeeList').items.add(data).then((result: any) =&gt; {
            console.log(&quot;result from add employee&quot;, result);
            resolve(result);
            alert('Employee added');
            this.state.employees.push({
              ID: result.data.ID,
              Title: state.name,
              tech: state.tech
            });
            this.setState({ name: '', tech: '', blocking: false });
          }).catch((err) =&gt; {
            alert('Employee not added');
            this.setState({ blocking: false });
            console.log(&quot;error in add employee&quot;, err);
          });
        });
      }
    }
    else {
      alert(&quot;Enter Name and Technology&quot;);
    }
  }

  private updateEmployee(id, index) {
    this.setState({ blocking: true });
    return new Promise((resolve, reject) =&gt; {
      sp.web.lists.getByTitle('EmployeeList').items.getById(id).get().then((result: any) =&gt; {
        console.log(&quot;get employee by id result&quot;, result);
        resolve(result);
        this.setState({
          name: result.Title,
          tech: result.tech,
          isUpdate: true,
          empId: id,
          empIndex: index,
          blocking: false
        });
      }).catch((err) =&gt; {
        this.setState({ blocking: false });
        console.log(&quot;error in get employee by id&quot;, err);
      });
    });
  }

  private deleteEmployee(id, index) {
    this.setState({ blocking: true });
    return new Promise((resolve, reject) =&gt; {
      sp.web.lists.getByTitle('EmployeeList').items.getById(id).delete().then((result: any) =&gt; {
        console.log(&quot;delete employee by id result&quot;, result);
        resolve(result);
        alert(&quot;Employee deleted&quot;);
        this.state.employees.splice(index, 1);
        this.setState({
          empId: '',
          empIndex: '',
          blocking: false
        });
      }).catch((err) =&gt; {
        this.setState({ blocking: false });
        console.log(&quot;error in delete employee by id&quot;, err);
      });
    });
  }

}
</code></pre>
<p><strong>PnpSpCrud.spec.tsx</strong></p>
<pre><code>import * as React from 'react';

import 'jest';
import { shallow } from 'enzyme';
import { PnpSpCrud } from '../PnpSpCrud';

test('should render Sample component correctly', () =&gt; {

    const wrapper = shallow(&lt;PnpSpCrud /&gt;);
    expect(wrapper.find('label').first().text()).toBe('Employee Name');
    expect(wrapper.find('th').length).toBe(3);
    expect(wrapper.find(&quot;button&quot;).type).toBe('button');
});
</code></pre>
<p><a href=""https://i.stack.imgur.com/asC7W.png"" rel=""nofollow noreferrer"">Thow an error</a></p>
",https://stackoverflow.com/questions/69973511/sharepoint-framework-spfx-using-pnp-sp-presets-all-with-react-sharepoint-spfx,"['reactjs', 'react-native', 'unit-testing', 'jestjs', 'spfx']",910,False,0,0
Nunit unit testing of .Net core Web API 5.0,"<p>Is there any proper good resource to learn unit testing of .Net core Web API with EF Core/Dapper as ORM &amp; having N-tier architecture using NUnit ?? I am not finding any proper resource on controller testing, service layer testing, Data access layer testing, middleware testing etc</p>
",https://stackoverflow.com/questions/69584527/nunit-unit-testing-of-net-core-web-api-5-0,"['unit-testing', 'nunit', 'asp.net-core-webapi']",187,False,0,1
External link not working in Spring Unit Testing,"<p>In my code for token I used external link . External link open in browser but not working in unit testing code. Any suggestion.</p>
<p>My code</p>
<pre><code>           private String getHRCToken() throws Exception {
            
            String token=&quot;&quot;;
            
            
            MultiValueMap&lt;String, String&gt; variables = new LinkedMultiValueMap&lt;&gt;();
            variables.add(&quot;email&quot;, HRC_LOGIN_EMAIL);
            variables.add(&quot;password&quot;, HRC_LOGIN_PASSWORD);
            
            HttpHeaders requestHeaders = new HttpHeaders();
            requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            requestHeaders.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
            HttpEntity&lt;MultiValueMap&lt;String, String&gt;&gt; requestEntity = new HttpEntity&lt;MultiValueMap&lt;String, String&gt;&gt;(variables ,
                    requestHeaders);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity&lt;String&gt; response = restTemplate.exchange(BASE_URL, HttpMethod.POST,
                    requestEntity, String.class);
            System.out.println(response.getStatusCode());
        }

        @Test
            public void updateData() throws Exception {
                String URI = &quot;/reviewData/leads/update&quot;;
                String token = getHRCToken();
                MvcResult result = mockMvc.perform(MockMvcRequestBuilders.put(URI)
                        .accept(MediaType.APPLICATION_JSON_VALUE)
                        .header(&quot;Authorization&quot;, token).param(&quot;status&quot;, &quot;New&quot;)
                        .param(&quot;lead_id&quot;, &quot;1&quot;)
                        ).andReturn();
                //Checking if our service has issues
                assertEquals(200, result.getResponse().getStatus());
                String response = result.getResponse().getContentAsString();
                int i = response.indexOf(&quot;{&quot;);
                response = response.substring(i);
                JSONObject json = new JSONObject(response.trim());
                JSONObject responseObject = json;
                String message = responseObject.getString(&quot;message&quot;);
                //Checking if process as exepected
                assertTrue(message.equalsIgnoreCase(&quot;success&quot;));
            }
</code></pre>
<p>Error</p>
<p>org.springframework.web.client.HttpClientErrorException: 415 null
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:85)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:708)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:661)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:621)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:539)</p>
",https://stackoverflow.com/questions/68110275/external-link-not-working-in-spring-unit-testing,"['java', 'spring-boot', 'spring-mvc']",49,False,-1,1
UnhandledPromiseRejectionWarning after upgrade from Angular 9 to 10,"<p>After updating to Angular 9 to 10 and run</p>
<pre><code>ng serve -o
</code></pre>
<p>I got the following error</p>
<pre><code>(node:34728) UnhandledPromiseRejectionWarning: Error: spawn UNKNOWN
    at ChildProcess.spawn (internal/child_process.js:407:11)
    at Object.spawn (child_process.js:548:9)
    .....
    at AsyncSeriesHook.lazyCompileHook (C:\work\code\vespa-ui-service\vespa-web\node_modules\tapable\lib\Hook.js:154:20)(node:34728) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:34728) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit cod
</code></pre>
<p>I also updated all other lib (eg primeNG) to the relevant version.
Building and unit testing the project won't return any error also.</p>
<p>So i wondering if I did anything wrong during migration process.</p>
",https://stackoverflow.com/questions/66757931/unhandledpromiserejectionwarning-after-upgrade-from-angular-9-to-10,"['angular', 'migration', 'angular10']",362,False,0,0
unit test fail with NullInjectorError in Angular,"<p>I have configured the unit testing of the jest framework and also remove jasmine karma (default unit test)</p>
<p>So we need to mock anything or do I missing something in imports?</p>
<p>Bellow I mentions test code</p>
<p><strong>toolbar.component.spec.ts</strong></p>
<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ToolbarComponent } from './toolbar.component';
import { ColorPickerModule } from 'ngx-color-picker';
import { NgxImageZoomModule } from 'ngx-image-zoom';
import { UiSwitchModule } from 'ngx-toggle-switch';
import { SharepointService } from '../../services/sharepoint.service';
import { CommonService } from '../../services/common.service';
import { InjectionToken } from '@angular/core';
import { HttpClientModule, HttpClient } from '@angular/common/http'
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

export const BASE_URL = new InjectionToken&lt;string&gt;('BASE_URL');

describe('ToolbarComponent', () =&gt; {
  let component: ToolbarComponent;
  let fixture: ComponentFixture&lt;ToolbarComponent&gt;;
  let sharepointService: SharepointService;
  let commonService: CommonService;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        ColorPickerModule,
        NgxImageZoomModule,
        UiSwitchModule,
        HttpClientTestingModule],
      declarations: [ToolbarComponent],
      providers: [{ provide: ToolbarComponent, useValue: &quot;test&quot; },
        SharepointService,
        CommonService,
        HttpClient]
    })
      .compileComponents();
  }));

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

    sharepointService = TestBed.inject&lt;SharepointService&gt;(SharepointService);
    commonService = TestBed.inject&lt;CommonService&gt;(CommonService);
  });

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
<p>It's thrown an error:</p>
<pre><code>NullInjectorError: StaticInjectorError(DynamicTestModule)[adalConfig]:
StaticInjectorError(Platform: core)[adalConfig]:
NullInjectorError: No provider for adalConfig!
</code></pre>
<p><a href=""https://i.stack.imgur.com/TOxPn.png"" rel=""nofollow noreferrer"">Here I attached the test result screenshot</a></p>
<p>Thanks</p>
",https://stackoverflow.com/questions/70125956/unit-test-fail-with-nullinjectorerror-in-angular,"['angular', 'unit-testing', 'jestjs']",2963,False,0,1
"The unit test code for Java Spark doesn&#39;t work, but the spark run with the same code runs fine","<p>I am trying to write some unit testing for my Java Spark code. Below are my first simple try</p>
<pre><code>public class SparkHelperTest {

    private JavaSparkContext sparkCtx;

    @Before
    public void setUp() throws IllegalArgumentException, IOException {
        SparkConf conf = new SparkConf();
        conf.setMaster(&quot;local[2]&quot;);
        conf.setAppName(&quot;sparkHelperTest&quot;);
        sparkCtx = new JavaSparkContext(conf);
    }

    @Test
    public void test() {
        final List&lt;Integer&gt; nums = new ArrayList&lt;Integer&gt;();
        nums.add(3);
        nums.add(4);
        nums.add(2);
        JavaRDD&lt;Integer&gt; rdd = sparkCtx.parallelize(nums,1);
        assertEquals(3, rdd.count());
    }
}
</code></pre>
<p>However I got this error</p>
<pre><code>java.lang.NoClassDefFoundError: com/sun/jersey/spi/container/servlet/ServletContainer
        at org.apache.spark.status.api.v1.ApiRootResource$.getServletHandler(ApiRootResource.scala:187)
        at org.apache.spark.ui.SparkUI.initialize(SparkUI.scala:70)
        at org.apache.spark.ui.SparkUI.&lt;init&gt;(SparkUI.scala:76)
        at org.apache.spark.ui.SparkUI$.create(SparkUI.scala:195)
        at org.apache.spark.ui.SparkUI$.createLiveUI(SparkUI.scala:146)
        at org.apache.spark.SparkContext.&lt;init&gt;(SparkContext.scala:473)
        at org.apache.spark.api.java.JavaSparkContext.&lt;init&gt;(JavaSparkContext.scala:59)
        at com.firsttry.spark.SparkHelperTest.setUp(SparkHelperTest.java:29)
        ......
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
        at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
        at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
        at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    Caused by: java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 30 more
</code></pre>
<p>I googled online and basically it is because the jersey version 1 is required. However, I found the jersey v1 was commented in our build.gradle as below</p>
<pre><code>compile (
            'io.dropwizard:dropwizard-core:' + dropwizardVersion,
            ......
)
compile('org.apache.spark:spark-core_2.10:' + sparkVersion) {
        exclude group: 'org.apache.hadoop', module: 'hadoop-common'
}    
configurations.all {
        // all v1 versions of jersey should be excluded. Spark has some of these dependencies
        exclude group: 'com.sun.jersey', module: 'jersey-server'
        ......
}
</code></pre>
<p>if I commented this &quot;<code>exclude group: 'com.sun.jersey', module: 'jersey-server'</code>&quot;, this error will be gone for unit test. However, after I build the task and run the spark job, I will got another error (note that with this &quot;exclude&quot;, the spark job is running fine, so I guess there is a reason people put this exclude there).
However, the mystery is if I simply copy the code in the test() method of the unit testing into the &quot;normal run&quot; code, the spark job is also running fine without requiring this jersey v1 issue. Can any body help, please?</p>
",https://stackoverflow.com/questions/69830439/the-unit-test-code-for-java-spark-doesnt-work-but-the-spark-run-with-the-same,"['java', 'apache-spark', 'gradle', 'build.gradle']",26,False,1,0
WordPress testing error: use of undefined constant,"<p>I sm working with a windows OS created wordpress plugin unit testing code written as below</p>
<pre><code>&lt;?php

class Test_WP_Simple_Plugin extends WP_UnitTestCase {

    public function test_constants () {
        $this-&gt;assertSame( 'wp-simple-plugin', WPSP_NAME );  //Error line

        $url = str_replace( 'tests/phpunit/tests/', '',
                trailingslashit( plugin_dir_url( __FILE__ ) ) );
        $this-&gt;assertSame( $url, WPSP_URL );
    }
}
</code></pre>
<p>that gives an error message</p>
<p>Use of undefined constant WPSP_NAME - assumed 'WPSP_NAME' (this will throw an Error in a future version of PHP)</p>
<p>please help what is wrong in this code? thanks</p>
",https://stackoverflow.com/questions/67154987/wordpress-testing-error-use-of-undefined-constant,"['wordpress', 'unit-testing']",109,False,0,1
Cannot read property &#39;injector&#39; of null,"<p>I was set up the angular project with the jest unit testing framework and after running the test case it's throwing me an error.</p>
<p>TypeError: Cannot read property 'injector' of null</p>
<p><em><strong>app.component.spec.ts</strong></em></p>
<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';

describe('AppComponent', () =&gt; {
  let component: AppComponent;
  let fixture: ComponentFixture&lt;AppComponent&gt;;
  beforeEach(async () =&gt; {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [HttpClientTestingModule],
    }).compileComponents();
  });

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

  it(`should have as title 'Angular-unitTest'`, () =&gt; {
    expect(AppComponent).toBeTruthy();
  });
});
</code></pre>
<p>Let me know if you need more information to figure out where is the problem.</p>
<p><a href=""https://i.stack.imgur.com/zNTAe.png"" rel=""nofollow noreferrer"">screenshot of error</a></p>
<p>Thanks</p>
",https://stackoverflow.com/questions/69313011/cannot-read-property-injector-of-null,"['angular', 'typescript', 'unit-testing', 'jestjs', 'angular-unit-test']",933,False,1,0
Unit Testing : Retrofit 2 Exception - API interfaces must not extend other interfaces,"<p>I am not extending any interface and all my interfaces are independent. While performing unit testing I am getting the following exception. During normal API calls, everything works fine.</p>
<pre><code> val retrofit: Retrofit = Retrofit.Builder()
            .baseUrl(url)
            .client(httpBuilder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build()
        return retrofit.create(MyApi::class.java)
</code></pre>
<p>The exception is thrown at <code>retrofit.create(..)</code> only while performing the unit test. Is there a way to avoid this error?</p>
",https://stackoverflow.com/questions/65829761/unit-testing-retrofit-2-exception-api-interfaces-must-not-extend-other-inter,"['android', 'mockito', 'powermockito', 'android-unit-testing']",181,False,0,1
Problem with testing database laravel 7.x,"<p>I am trying to do unit testing in laravel 7.x.</p>
<p>I created a testing database which is identic to the database I use for my website.</p>
<p>I modified the <strong>phpunit.xml</strong> file, I created a <strong>.env.testing</strong> file and I added a &quot;testing&quot; connection to the <strong>database.php</strong> file but I am getting an <strong>&quot;SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cbs_perform_test.cbs_defis' doesn't exist (SQL: select count(*) as aggregate from <code>cbs_defis</code>)&quot;</strong> error.</p>
<p>I already checked multiple times the name of the database and the table to be sure I am using the correct one.</p>
<p>I already followed these guides : <a href=""https://stackoverflow.com/questions/35227226/laravel-5-use-different-database-for-testing-and-local"">Use different database for testing and local</a> ; <a href=""https://www.phplab.info/categories/laravel/how-to-specify-a-separate-database-for-unit-testing-on-laravel-5"" rel=""nofollow noreferrer"">How to Specify a Separate Database for Unit Testing on Laravel 5</a></p>
<p>Here is my <strong>phpunit.xml</strong></p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;phpunit xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
         xsi:noNamespaceSchemaLocation=&quot;./vendor/phpunit/phpunit/phpunit.xsd&quot;
         bootstrap=&quot;vendor/autoload.php&quot;
         colors=&quot;true&quot;&gt;
    &lt;testsuites&gt;
        &lt;testsuite name=&quot;Unit&quot;&gt;
            &lt;directory suffix=&quot;Test.php&quot;&gt;./tests/Unit&lt;/directory&gt;
        &lt;/testsuite&gt;
        &lt;testsuite name=&quot;Feature&quot;&gt;
            &lt;directory suffix=&quot;Test.php&quot;&gt;./tests/Feature&lt;/directory&gt;
        &lt;/testsuite&gt;
    &lt;/testsuites&gt;
    &lt;filter&gt;
        &lt;whitelist processUncoveredFilesFromWhitelist=&quot;true&quot;&gt;
            &lt;directory suffix=&quot;.php&quot;&gt;./app&lt;/directory&gt;
        &lt;/whitelist&gt;
    &lt;/filter&gt;
    &lt;php&gt;
        &lt;server name=&quot;APP_ENV&quot; value=&quot;testing&quot;/&gt;
        &lt;server name=&quot;BCRYPT_ROUNDS&quot; value=&quot;4&quot;/&gt;
        &lt;server name=&quot;CACHE_DRIVER&quot; value=&quot;array&quot;/&gt;
        &lt;server name=&quot;DB_CONNECTION&quot; value=&quot;testing&quot;/&gt;
        &lt;server name=&quot;DB_DATABASE&quot; value=&quot;cbs_perform_test&quot;/&gt;
        &lt;server name=&quot;MAIL_MAILER&quot; value=&quot;array&quot;/&gt;
        &lt;server name=&quot;QUEUE_CONNECTION&quot; value=&quot;sync&quot;/&gt;
        &lt;server name=&quot;SESSION_DRIVER&quot; value=&quot;array&quot;/&gt;
        &lt;env name=&quot;DB_CONNECTION&quot; value=&quot;testing&quot;/&gt;
    &lt;/php&gt;
</code></pre>

<p>My <strong>database.php connection</strong></p>
<pre><code>'testing' =&gt; [
            'driver' =&gt; 'mysql',
            'url' =&gt; env('DATABASE_URL'),
            'host' =&gt; env('DB_HOST', '127.0.0.1'),
            'port' =&gt; env('DB_PORT', '3306'),
            'database' =&gt; env('DB_DATABASE', 'forge'),
            'username' =&gt; env('DB_USERNAME', 'forge'),
            'password' =&gt; env('DB_PASSWORD', ''),
            'unix_socket' =&gt; env('DB_SOCKET', ''),
            'charset' =&gt; 'utf8mb4',
            'collation' =&gt; 'utf8mb4_unicode_ci',
            'prefix' =&gt; '',
            'prefix_indexes' =&gt; true,
            'strict' =&gt; false,
            'engine' =&gt; null,
            'options' =&gt; extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA =&gt; env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],
</code></pre>
<p>my <strong>.env.testing</strong> file</p>
<pre><code>APP_ENV=testing

DB_CONNECTION=testing
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=cbs_perform_test
DB_USERNAME=root
DB_PASSWORD=
</code></pre>
<p>My <strong>test code</strong></p>
<pre><code>class DefiTest extends TestCase
{
    use DatabaseMigrations;
    use DatabaseTransactions;

    /**
     * A basic unit test example.
     *
     * @return void
     */
    public function testCreateDefi()
    {
        $request = new Request();
        $request-&gt;DEF_NOM = 'test';
        $request-&gt;DEF_DESCRIPTION = 'testdescriptio ajhsg ln';
        $request-&gt;DEF_NBSEMAINES = 2;
        $request-&gt;DEF_CONSEILS = 'jhasnciu launh sl';
        $request-&gt;DEF_VISIBLE = 1;
        $request-&gt;DEF_DATE_VISIBLE = Carbon::now()-&gt;toDate();
        $request-&gt;COA_ID = 3;

        $dfc = new DefiCoachController();
        $response = $dfc-&gt;createDefiTest($request);

        $this-&gt;assertDatabaseHas('cbs_defis', $request-&gt;all());
    }
}
</code></pre>
<p><strong>The command I use for testing : php artisan test --env=testing</strong></p>
",https://stackoverflow.com/questions/67244439/problem-with-testing-database-laravel-7-x,"['php', 'mysql', 'laravel']",1834,True,1,1
Need help to convert a working arrow function to a regular function to write unit tests,"<p>I would like to convert the below working code</p>
<pre><code>const Client = require('node-rest-client').Client;
const Rest = new Client();

const useRestClient = (url,args,_next)=&gt; {
    return new Promise(resolve =&gt; {
        Rest.post(url,args, (data,_response) =&gt;
            {
                resolve(data);
            })
        })
}
</code></pre>
<p>to something like this:</p>
<pre><code>const Client = require('node-rest-client').Client;
const Rest = new Client();

function callRestPost(resolve, url, args) 
{
    return Rest.post(url,args, (data,_response) =&gt;
            {
                resolve(data);
            });
}

const useRestClient = (url,args,_next)=&gt; {
    return new Promise(callRestPost);
}
</code></pre>
<p>Is this correct? The reason I am doing is, is to mock the Rest.post method for unit testing. I am restricted to using mocha sinon for testing and I am new to JS and node.js. Please help.</p>
",https://stackoverflow.com/questions/67951617/need-help-to-convert-a-working-arrow-function-to-a-regular-function-to-write-uni,"['javascript', 'node.js']",46,True,1,2
NestJS Unit Testing of the Service: Mocking getManager resulting in &#39;Connection &quot;default&quot; was not found&#39; error,"<p>I am currently unit testing my NestJS Service. My entity is called 'User' and I established a basic Service that allows me to interact with a MS SQL server, with GET and POST endpoints established in my Controller.</p>
<p>One of the service methods I am trying to mock is the <code>deleteV2</code> function, which you can find below:</p>
<pre><code>
// service file 
import { Injectable } from '@nestjs/common';
import { InjectConnection, InjectEntityManager, InjectRepository } from '@nestjs/typeorm';
import { Connection, createConnection, EntityManager, getConnection, getManager, getRepository, Repository } from &quot;typeorm&quot;;
import {User} from '../entities/user.entity';


@Injectable()
export class ServiceName {
  constructor(@InjectRepository(User) private usersRepository: Repository&lt;User&gt;,
              @InjectConnection() private connection: Connection,
              @InjectEntityManager() private manager: EntityManager
              ) {}

  async delete(id: number): Promise&lt;any&gt; {
    return await this.manager.delete(User, id);
  }
  async deleteV2(id: number): Promise&lt;any&gt; {
    return await getManager().delete(User, id);
  }
</code></pre>
<p>Note that the reason I have imported <code>EntityManager</code> AND injected (with <code>@InjectEntityManager()</code>) a <code>manager: EntityManager</code> into my service is for the simple reason that I wanted some more practice working with different methods (I'm a new intern working with NestJS). The fact that I have the <code>delete</code> method defined where I use the injected <code>manager</code> and then the <code>deleteV2</code> method defined where I use the imported <code>getManager</code> is also for the pure reason of practicing unit testing with different ways. And the fact that I'm injecting Repository, Connection, and EntityManager, is also for the same reason.</p>
<p>In my spec.ts unit testing file for the service, I have:</p>
<pre><code>// unit testing file for the service

type MockType&lt;T&gt; = { 
    [P in keyof T]?: jest.Mock&lt;{}&gt;;
};

describe('service tests', () =&gt; {
    const mockManagerFactory = jest.fn(() =&gt; ({
        delete: jest.fn().mockReturnValue(undefined),
    }))
 
    let service: ServiceName;
    // mock repository and mock connection also defined similarly to mockManager
    let mockManager: MockType&lt;EntityManager&gt;; 

    beforeEach(async () =&gt; {     
        const module: TestingModule = await Test.createTestingModule({
            providers: [
                ServiceName,
                // tokens for Repository and Connection are also provided along with their respective Factories
                {
                    provide: getEntityManagerToken(),
                    useFactory: mockManagerFactory,
                },
            ],
        }).compile();

        service = module.get&lt;ServiceName&gt;(ServiceName);
        // mockRepository and mockConnection also defined but not shown
        mockManager = module.get(getEntityManagerToken());
    });
})

</code></pre>
<p>Staying on the same spec.ts file, I defined multiple tests. The one that is causing problem is the one that involves <code>deleteV2</code> below:</p>
<pre><code>// same unit testing file for the service 
         
        // first test
        it('first test', async () =&gt; {
            expect(await service.delete(1000)).toEqual(undefined);
            expect(mockManager.delete).toBeCalled();
        });
        
        // second test 
        it('second test', async () =&gt; {
            expect(await service.deleteV2(1000)).toEqual(undefined);
            expect(mockManager.delete).toBeCalled();
        })
</code></pre>
<p>While the first test has no problem running (the first test is associated with <code>delete</code> in the service file), the second test (associated with <code>deleteV2</code> in the service file) does not pass and results in the following error:</p>
<pre><code>● service tests › Service Functions › second test

ConnectionNotFoundError: Connection &quot;default&quot; was not found.

      at new ConnectionNotFoundError (error/ConnectionNotFoundError.ts:8:9)
      at ConnectionManager.Object.&lt;anonymous&gt;.ConnectionManager.get (connection/ConnectionManager.ts:40:19)
      at Object.getManager (index.ts:260:35)

</code></pre>
<p>Any ideas how to approach this error? It seems as though providing <code>getEntityManagerToken()</code> works with the injected <code>manager</code> but not with the <code>getManager</code> that is imported, since <code>deleteV2</code> uses <code>getManager</code> while <code>delete</code> (which passes the test) uses the imported <code>manager</code></p>
",https://stackoverflow.com/questions/67528680/nestjs-unit-testing-of-the-service-mocking-getmanager-resulting-in-connection,"['typescript', 'nestjs']",2916,True,3,1
Trying to implement gRPC unit test for c#,"<p>I've been trying to look for examples on the internet or anywhere of how to implement gRPC unit testing in c# but can't for the love of me find anything, or I could just be over seeing things.</p>
<p>If someone could point me in the right direction I would be very grateful.</p>
<p>S</p>
",https://stackoverflow.com/questions/67121378/trying-to-implement-grpc-unit-test-for-c,"['c#', 'grpc']",4272,True,2,2
How do you assert with add object to another object many to many,"<p>I'm unit testing a Spring boot web app with Mockito. One of my methods is returning a Actorrest, but if I try to test it, I get compilation errors.</p>
<p>This is the test I wrote:</p>
<pre class=""lang-java prettyprint-override""><code>@Test
void AddActorToChapters() throws NetflixException{
    when(actorRepository.findById(MockData.getActor().getId())).thenReturn(Optional.of(MockData.getActor()));
    when(chapterService.findChapterById(MockData.getChapter().getId())).thenReturn((MockData.getChapter()));
    service.AddActorToChapter(MockData.getChapter().getId(), MockData.getActor().getId());
    assertEquals(MockData.getActor().getChapters(), MockData.getChapter());

}

</code></pre>
<p>And this is the method I'm trying to test:</p>
<pre class=""lang-java prettyprint-override""><code>@Override
public ActorParticipant AddActorToChapter(Long idActor, Long idChapter) throws NetflixException {
    Actor actor = actorRepository.findById(idActor)
            .orElseThrow(() -&gt; new NotFoundException(&quot;Actor id not found - &quot; + idActor));
    if (actorRepository.existsByIdAndChapters_Id(idActor, idChapter)) {
        throw new DuplicateException(&quot;Actor id  found - &quot; + idActor);
    }
    Chapter chapter = chapterService.findChapterById(idChapter);

    actor.getChapters().add(chapter);
    actorRepository.save(actor);
    ActorParticpateMapper mapper = new ActorParticpateMapper();
    return mapper.mapActorToActorParticipant(actor);

}

</code></pre>
<p>and the database mockdata are</p>
<pre class=""lang-java prettyprint-override""><code>public class MockData {
    public static Actor getActor() {
        Actor actor = new Actor();
        actor.setId(1L);
        actor.setName(&quot;ali&quot;);
        actor.setNationality(&quot;ameriacn&quot;);
        actor.getChapters().add(getChapter());
        return actor;
    }
    
    public static Chapter getChapter() {
        Chapter chapter = new Chapter();
        chapter.setId(1L);
        chapter.setName(&quot;Chapter 7&quot;);
        return chapter;
        
    }}

</code></pre>
<p>log error</p>
<pre class=""lang-java prettyprint-override""><code>
java.lang.Exception: No tests found matching [{ExactMatcher:fDisplayName=AddActorToChapters], {ExactMatcher:fDisplayName=AddActorToChapters(actortest.ActorServiceTesting)], {LeadingIdentifierMatcher:fClassName=actortest.ActorServiceTesting,fLeadingIdentifier=AddActorToChapters]] from org.junit.internal.requests.ClassRequest@64b8f8f4
    at org.junit.internal.requests.FilterRequest.getRunner(FilterRequest.java:40)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createFilteredTest(JUnit4TestLoader.java:83)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.createTest(JUnit4TestLoader.java:74)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestLoader.loadTests(JUnit4TestLoader.java:49)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:513)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:756)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:452)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)

</code></pre>
",https://stackoverflow.com/questions/69124052/how-do-you-assert-with-add-object-to-another-object-many-to-many,"['spring-boot', 'junit', 'mockito']",115,False,-1,1
How do I make Chai handle multiple database queries?,"<p>I'm trying to understand unit testing in <strong>Express + Mocha/Chai</strong>.<br />
The API call I'm trying to test seems to stop after the first async function and times out, see relative code and console output below.<br />
I'm not sure if I'm missing something in the API itself or in the test!</p>
<pre><code>// controller.js
const { Alert } = require('../models');

exports.addAlert = async (req, res) =&gt; {
  const username = req.body.uploader !== &quot;&quot; ? req.body.uploader : &quot;anonymous&quot;
  const rowNumber = await Alert.count()
  const title = req.body.title !== &quot;&quot; ? req.body.title : parseInt(rowNumber) + 1

  const addedAlert = await Alert.findOrCreate({
    where: {
      coordinates: req.body.coordinates
    },
    defaults: {
      username: username,
      path: req.file.path,
      title: title
    }
  })

  addedAlert[1] ? 
    res.send(200).render('home', {
      formMessage: `Added alert ${title}`
    }) :
    res.send(303).render('home', {
      formMessage: 'Coordinates already taken.'
    })
};
</code></pre>
<pre><code>// test.js
let chai = require('chai');
let chaiHttp = require('chai-http');
let server = require('../../app');
let should = chai.should();

chai.use(chaiHttp);
describe('/POST alert', () =&gt; {
  it('it should POST an alert', (done) =&gt; {
    chai.request(server)
      .post('/add-alert')
      .send({ username: &quot;foo&quot;, title: &quot;bar&quot;, coordinates: &quot;baz&quot;, path: &quot;foo/bar/baz&quot; })
      .end((err, res) =&gt; {
        console.log(res.body)
        done();
      });
  });
});
</code></pre>
<pre><code>//mocha tests/**/*.* --exit
/POST alert
Executing (default): SELECT count(*) AS `count` FROM `Alerts` AS `Alert`;
    1) it should POST an alert

  /*
  ** Other tests that are working fine
  */
  1 failing

  1) /POST alert
       it should POST an alert:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure &quot;done()&quot; is called; if returning a Promise, ensure it resolves. (/*..*/test.js)
      at listOnTimeout (internal/timers.js:554:17)
      at processTimers (internal/timers.js:497:7)
</code></pre>
",https://stackoverflow.com/questions/67027389/how-do-i-make-chai-handle-multiple-database-queries,"['javascript', 'node.js', 'express', 'mocha.js', 'chai']",271,True,0,1
How can I make a test a class that has in its __init__ the creation of a connection to a database?,"<p>I have a class that creates a connection to a db (that needs to be alive for the purpose of the execution) and I would like to make Unit-testing of the class' methods (that don't use the connection).
How can I mock, or ignore the connection to the db?</p>
<pre><code>from myutils import MyConnect
class Module:
    def __init__(self, payload):
        self.payload = payload
        format_date = &quot;%Y-%m-%d&quot;
        days = self.payload[&quot;days&quot;]
        self.start_date = (datetime.now() - timedelta(days=days)).strftime(format_date)
        self.end_date = datetime.now().strftime(format_date)
        self.domain = self.payload[&quot;domain&quot;]
        
        self.ms_connection = MyConnect(self.payload[&quot;MYSQL&quot;]) # create connection to db
            
        
</code></pre>
",https://stackoverflow.com/questions/68301143/how-can-i-make-a-test-a-class-that-has-in-its-init-the-creation-of-a-connect,"['python', 'unit-testing', 'mocking']",119,True,0,2
Springboot Unit Tesiting with Jwt spring security,"<p>I am a Newbie to Unit Testing/ Integration Testing
I am getting some errors while testing the rest api which is secured with Jwt Token authentication by spring security.</p>
<p><strong>userControllerTest</strong></p>
<pre><code>@ExtendWith({ RestDocumentationExtension.class, MockitoExtension.class })
@RunWith(SpringJUnit4ClassRunner.class)
@WebMvcTest(UserController.class)
@AutoConfigureRestDocs(outputDir = &quot;target/generated-snippets&quot;)
@ContextConfiguration(classes = ApplicationContext.class)
@AutoConfigureMockMvc
//@WithMockUser
class UserControllerTest {

    @Mock
    private IUserService&lt;User&gt; userService;

    @Autowired
    private MockMvc mockMvc;

    @InjectMocks
    private UserController userController;

    @Spy
    private ModelMapper modelMapper;

    @Autowired 
    private JwtUtility jwtUtil;


    @Spy
    private JwtRequestFilter filer;

    @Autowired
    private ObjectMapper objectMapper;

    @Spy
    private EntityManager entityManager;

    private final static String ACCEPT_TYPE = &quot;application/user-details&quot;;

    @BeforeEach
    public void setUp(WebApplicationContext webApplicationContext, RestDocumentationContextProvider restDocumentation) {

        mockMvc = MockMvcBuilders

                .webAppContextSetup(webApplicationContext)
                .apply(documentationConfiguration(restDocumentation).snippets()
                        .withDefaults(HttpDocumentation.httpRequest(), HttpDocumentation.httpResponse()))// .apply(springSecurity())
                .addFilters(new JwtRequestFilter()).build();
    }

    private User getUser() {
        User user = new User();
        user.setId(1L);
        user.setFirstName(&quot;Saurabh&quot;);
        user.setLastName(&quot;Kohade&quot;);
        user.setEmail(&quot;user@cc.com&quot;);
        user.setReseller(null);
        user.setRoleName(&quot;ADMIN&quot;);
        return user;
    }

    @Test
    @DisplayName(&quot;Will create User&quot;)
//  @WithAnonymousUser
    void testCreate() throws Exception {

        User entity = getUser();

        when(userService.saveUser(entity, 1L)).thenReturn(entity);

        UserDto dtoresponse = userController.create(entity, ACCEPT_TYPE);

        assertNotNull(dtoresponse);

        String token = &quot;Bearer JhbGciOiJIUzI1NiJ9.eyJzdWIiOiuY29tIiwicmVzZWxsZXJJbmZvIjoie1wiZG9tYWluTmFtZTgQ.W0Xnl1j7PAAxqV97uE6s6iGU1IfCZHmiVLYN5iZwsbI&quot;;

        String URI = &quot;/user&quot;;

        String inputToJson = objectMapper.writeValueAsString(entity);

        MvcResult mvcResult = mockMvc
                .perform(post(URI).with(SecurityMockMvcRequestPostProcessors.jwt())
                        .with(SecurityMockMvcRequestPostProcessors.csrf())
                        .contentType(MediaType.APPLICATION_JSON_VALUE)
                        .content(inputToJson).accept(ACCEPT_TYPE))//.header(HttpHeaders.AUTHORIZATION, token))
                .andExpect(status().isOk()).andReturn();

        assertEquals(HttpStatus.OK.value(), mvcResult.getResponse().getStatus());

    }
</code></pre>
<p><strong>junit Stacktrace</strong></p>
<pre><code>java.lang.NoClassDefFoundError: org/springframework/security/oauth2/server/resource/authentication/JwtGrantedAuthoritiesConverter
    at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$JwtRequestPostProcessor.&lt;init&gt;(SecurityMockMvcRequestPostProcessors.java:1032)
    at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors$JwtRequestPostProcessor.&lt;init&gt;(SecurityMockMvcRequestPostProcessors.java:1028)
    at org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.jwt(SecurityMockMvcRequestPostProcessors.java:262)
    at cloudcodes.customermanagement.controller.UserControllerTest.testCreate(UserControllerTest.java:169)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:564)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:210)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:206)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:131)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:84)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:40)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:768)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: java.lang.ClassNotFoundException: org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 71 more


</code></pre>
<p>I think i am missing some configuration for authentication to fake token can anyone help me with this?.....</p>
",https://stackoverflow.com/questions/68620941/springboot-unit-tesiting-with-jwt-spring-security,"['java', 'spring-boot', 'junit', 'spring-security', 'jwt']",422,False,0,0
What is wrong with my Java import statement?,"<p>Hello I am new to Java and new to trying out Unit Testing for the first time on a simple program but my import.main.BalancedQuestionMarks; statement is not getting recognized in my test file. I don't understand why my test file isn't recognizing my main file.
Here is my test file</p>
<pre><code>
import main.BalancedQuestionMarks;
import org.junit.Test;

import static org.junit.Assert.assertTrue;

public class BalancedQuestionMarksTest {

    @Test
    public void onlyQuestionMarkReturnsTrue() {
        assertTrue(BalancedQuestionMarksTest.hasBalancedMarks(&quot;??&quot;), true);
    }
   
}```

Here is the error when I try to run:

java: cannot find symbol
  symbol:   method hasBalancedMarks(java.lang.String)
  location: class test.BalancedQuestionMarksTest

</code></pre>
",https://stackoverflow.com/questions/70105801/what-is-wrong-with-my-java-import-statement,['java'],41,False,0,0
Unit test with mockK - flatMap,"<p>I'm new in Unit Testing, I can't understand how to test this kind of method with kotlin, using MockK:</p>
<pre class=""lang-kotlin prettyprint-override""><code>override fun register(firebaseId: String, uniqueId: String): Completable {
    return Observable.just(0).observeOn(schedulerProvider.io()).flatMap {
        
        val requestRegisterPushes = registerBuilder.build(firebaseId, uniqueId)
        apiServiceFactory.build()
            .registerPushes(requestRegisterPushes)
            .subscribeOn(schedulerProvider.io())
            .observeOn(schedulerProvider.ui())

    }.flatMapCompletable { 
        Completable.complete() 
    }
}
</code></pre>
<p>This is my code for the test, the test was a success but the condition coverage does not increase.</p>
<pre class=""lang-kotlin prettyprint-override""><code>@Test
fun `register_Test()`() {

    val requestRegisterPushes = mockk&lt;RequestRegisterPushes&gt;(relaxed = true)
    every { registerBuilder.build(any(), any(), any(), any()) } returns requestRegisterPushes
    every { apiServiceFactory.build().register(requestRegisterPushes) } returns Observable.just(SimpleResponse())


    val resp = userRepository.register(&quot;x7gbyb68837g78s&quot;, &quot;XXX-XXX-XXX&quot;)
}
</code></pre>
<p>I would really appreciate it if you could help me a little.</p>
",https://stackoverflow.com/questions/69309370/unit-test-with-mockk-flatmap,"['unit-testing', 'kotlin', 'mockito', 'rx-java', 'mockk']",532,True,0,1
Saving data to database in unit testing,"<p>Why it's impossible to create dummy data in unit testing like below?</p>
<pre><code>DB::table('users')-&gt;insert([
[
'name' =&gt; 'test',
],
</code></pre>
<p>I saw that in order to create data you need to create factory, but when I try to insert data like this:</p>
<pre><code>User::factory()-&gt;count(1)-&gt;create([
'name' =&gt; 'test'
]);
</code></pre>
<p>It also don't insert new data.
What is the easiest way to to that? Thank you</p>
",https://stackoverflow.com/questions/68665606/saving-data-to-database-in-unit-testing,"['laravel', 'unit-testing']",161,True,0,1
Read a src file in Unit test,"<p>I am new to c# and unit testing. I have a config file stored in Source folder(on Server). I need to read that file in my Unit test class. This will be running on build server so need to find out a way of working out. Something like GetExecutingAssembly</p>
",https://stackoverflow.com/questions/69666143/read-a-src-file-in-unit-test,"['c#', 'asp.net', 'mstest', 'vs-unit-testing-framework']",664,True,0,2
"TypeError: (0 , _native.createNavigatorFactory) is not a function","<p>Trying to perform <code>npm test</code> on my React Native application, unit testing with Jest are working fine. However with <code>react-test-renderer</code> it complaining the following issue.</p>
<pre><code>FAIL  __tests__/App-test.js
  ● Test suite failed to run

    TypeError: (0 , _native.createNavigatorFactory) is not a function

      at Object.&lt;anonymous&gt; (node_modules/@react-navigation/material-top- tabs/lib/commonjs/navigators/createMaterialTopTabNavigator.tsx:50:16)
      at Object.&lt;anonymous&gt; (node_modules/@react-navigation/material-top-tabs/lib/commonjs/index.tsx:4:1)
</code></pre>
<p>I did not write this test case, it comes default while the project was created. I'm expecting to see a pass unit test from here, what seems to be the issue from the <code>react-test-renderer</code>?</p>
<pre><code>/**
 * @format
 */

import 'react-native';
import React from 'react';
import App from '../App';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

it('renders correctly', () =&gt; {
  renderer.create(&lt;App /&gt;);
});

</code></pre>
",https://stackoverflow.com/questions/66955048/typeerror-0-native-createnavigatorfactory-is-not-a-function,"['javascript', 'react-native', 'ui-testing', 'react-test-renderer']",1483,True,3,1
Doesn&#39;t a test class using MockWebServer require a runner?,"<p>I have a very basic question, I'm new to unit testing and I have a test class in which I'm testing Spring WebClient using MockWebServer. All the tests run fine but why don't we need a runner when using MockWebServer? When using Mockito we annotate the class with @RunWith(MockitoJUnitRunner.class).</p>
",https://stackoverflow.com/questions/67102341/doesnt-a-test-class-using-mockwebserver-require-a-runner,"['java', 'spring-boot', 'mockwebserver']",356,True,0,1
Should fixture.destroy() be explicit in Angular 2+ unit testing,"<p>For unit testing with Karma/Jasmine in Angular 2+, should the fixture destruction be explicit?</p>
<pre><code>afterEach(() =&gt; fixture.destroy());
</code></pre>
<p>and what are the consequences if not destroying the fixture (i.e. is it called behind the scenes by the framework or does the fixture persist leading to side-effects)?</p>
<p>Angular <a href=""https://angular.io/api/core/testing/ComponentFixture#destroy"" rel=""nofollow noreferrer"">docs</a> on the topic don't suggest the right answer. What are your thoughts ? Thanks</p>
",https://stackoverflow.com/questions/66257081/should-fixture-destroy-be-explicit-in-angular-2-unit-testing,"['angular', 'karma-jasmine']",1117,False,4,0
"XUnit + Moq + FluentAssertions, checking for null on Task instead of proper object","<p>I am new to unit testing and moq.</p>
<p>Using Postman to test DeleteItemAsync(),</p>
<pre><code>    [HttpDelete(&quot;{id:length(24)}&quot;)]
    public async Task&lt;IActionResult&gt; DeleteItemAsync(string id)
    {
        var item = _ItemRepo.GetItemByIdAsync(id);
        if (item == null)
            return NotFound();
        await _itemRepo.DeleteItemAsync(id);
        return NoContent();
    }
</code></pre>
<p>when the item isn't found, I get the proper result, NotFound.</p>
<p>When running my unit test it's failing because, in the controller, it is checking for null on the Task object returned by the moq _repoStub call to GetItemByIdAsync(id).</p>
<pre><code>    [Fact]
    public async Task DeleteItemAsync_ItemDoesntExist_ReturnsNotFound()
    {
        // Arrange
        _repoStub
            .Setup(repo =&gt; repo.GetItemByIdAsync(It.IsAny&lt;String&gt;()))
            .ReturnsAsync((Item)null);
        _repoStub
            .SetupSequence(repo =&gt; repo.DeleteItemAsync(It.IsAny&lt;String&gt;()))
            .Returns(Task.FromResult&lt;NotFoundResult&gt;(null));

        var controller = new ItemController(_repoStub.Object, _mapperStub);

        // Act
        var actionResult = await controller.DeleteItemAsync(It.IsAny&lt;String&gt;());

        // Assert
        actionResult.Should().BeOfType&lt;NotFoundResult&gt;();
    }
</code></pre>
",https://stackoverflow.com/questions/67218269/xunit-moq-fluentassertions-checking-for-null-on-task-instead-of-proper-obje,"['c#', 'unit-testing', 'moq', 'xunit']",1106,True,1,1
How to set maximum number of fails in testthat?,"<p>I notice with unit testing using the testthat package in R, when you get 10 or more fails, you get the output message:
<code>Maximum number of failures exceeded; quitting early. You can increase this number by setting options(testthat.progress.max_fails)</code></p>
<p>However, I can't see how and where I can change the options. When I run what is suggested: <code>options(testthat.progress.max_fails)</code>,
I get:<br />
<code>Error in options(testthat.progress.max_fails): object 'testthat.progress.max_fails' not found</code></p>
<p>Any ideas how I can raise the number of max errors?</p>
",https://stackoverflow.com/questions/66444281/how-to-set-maximum-number-of-fails-in-testthat,"['r', 'unit-testing', 'testthat']",316,False,2,0
How to unit test MatSnackbar using Jasmine Karma in Angular,"<p>I want to perform unit testing on this onSubmit function where the positive submission is leading to MatSnackbar with message, &quot;Submitted Successfully&quot;. I am new to Jasmine Karma please guide me about the testing of MatSnackbar in this case.<br></p>
<p><em><strong>Component.ts</strong></em></p>
<pre class=""lang-js prettyprint-override""><code>import { MatSnackBar } from &quot;@angular/material/snack-bar&quot;;

  constructor(
    private snackBar: MatSnackBar,
    private auth: AuthenticateService,

  ) {}
...
...
  onSubmit(e) {
    const newYellow = {
      G1: e.value.Yellow_G1,
      G2: e.value.Yellow_G2,
      G3: e.value.Yellow_G3,
      G4: e.value.Yellow_G4,
      B1: e.value.Yellow_B1,
      B2: e.value.Yellow_B2,
      B3: e.value.Yellow_B3,
      B4: e.value.Yellow_B4,
    };
    console.log(newYellow);
    this.auth.submitnominYellow(newYellow).subscribe(
      (res) =&gt; {
        console.log(res);
        this.snackBar.open(&quot;Submitted Successfully&quot;, &quot;&quot;, {
          duration: 2000,
        });
      },
      (error) =&gt; {
        console.log(error);
      }
    );
  }
</code></pre>
<p>This is code for <code>submitnomin</code> function.
<em><strong>auth.service.ts</strong></em></p>
<pre class=""lang-js prettyprint-override""><code>submitnominYellow(inpobj) {
    console.log(inpobj);
    return this.http.post(environment.apiUrl + '/api/customize/yellow', inpobj);
}
</code></pre>
<p>My unit test case is somewhat like this.<br>
<em><strong>component.spec.ts</strong></em><br></p>
<pre class=""lang-js prettyprint-override""><code>    const mockSnackbarMock = jasmine.createSpyObj(['open']);
    mockSnackbarMock.open
    
    const mockopblue =
      {
        success: true
    }
    
    const MockAuthService = {
      submitnominYellow:(id) =&gt; (mockopblue),
      getuser:() =&gt; (undefined)
    
    };
...
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ YellowCustomizeComponent ],
      imports: [HttpClientTestingModule, MatSnackBarModule, FormsModule, RouterTestingModule],
      providers:[{provide: MatSnackBar, useValue: mockSnackbarMock},
      {provide: AuthenticateService, useValue: MockAuthService}
      ]

    })
    .compileComponents();
  }));
...

          fit('should open the snack bar with correct arguments when form submitted', () =&gt; {
            const e =  {
              value:{
                Yellow_G1: &quot;YGirlName1&quot;,
                Yellow_G2: &quot;GirlName2&quot;,
                Yellow_G3: &quot;GirlName3&quot;,
                Yellow_G4: &quot;GirlName4&quot;,
                Yellow_B1: &quot;BoyName1&quot;,
                Yellow_B2: &quot;BoyName2&quot;,
                Yellow_B3: &quot;BoyName3&quot;,
                Yellow_B4: &quot;BoyName4&quot;,
              }
              
            };
            component.onSubmit(e)
            console.log('mockSnackbarMock',mockSnackbarMock)
            // console.log('yellow onsubmit',component.onSubmit(e)); 
            expect(mockSnackbarMock.open).toHaveBeenCalledWith(&quot;Submitted Successfully&quot;, &quot;&quot;, );
         })
</code></pre>
",https://stackoverflow.com/questions/68334529/how-to-unit-test-matsnackbar-using-jasmine-karma-in-angular,"['angular', 'unit-testing', 'jestjs', 'karma-jasmine', 'angular-unit-test']",1598,True,2,1
How do I use PHPUnit to test __construct with arguments?,"<p>I'm new to PHPUnit, and unit testing in general. I can't seem to find a clear tutorial or resource on how best to test:</p>
<ol>
<li>Passing no argument fails.</li>
<li>How to pass an argument for a constructor test.</li>
<li>Passing an empty argument results in the expected exception.</li>
</ol>
<p>How would I approach testing this constructor?</p>
<pre><code>&lt;?php

class SiteManagement {
    public function __construct (array $config) {
        // Make sure we actually passed a config
        if (empty($config)) {
            throw new \Exception('Configuration not valid', 100);
        }

        // Sanity check the site list
        if (empty($config['siteList'])) {
            throw new \Exception('Site list not set', 101);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/66994196/how-do-i-use-phpunit-to-test-construct-with-arguments,"['php', 'unit-testing', 'phpunit']",491,True,0,2
How to add an equality function that is used in collection comparisons in Python unittest,"<p>I want to use a custom comparison function when I am unit testing a class. unittest has <code>addTypeEqualityFunc</code> but that only works when the two objects are directly compared.  It isn't used inside collections. Is there a way to do this? My specific use case is using <code>MagicMock.assert_has_calls</code> and comparing arguments to the calls.</p>
<pre><code>import unittest


class C:
    def __eq__(self, other):
        return False
        
        
def always_equal(this, that, msg=None):
    return True


class TestCase(unittest.TestCase):

    def test_without_equality_func(self):
        # This passses
        obj = C()
        self.assertEqual(obj, obj)
        
    def test_with_equality_func(self):
        # This fails
        self.addTypeEqualityFunc(C, always_equal)
        obj = C()
        self.assertEqual(obj, obj)      
        
    def test_in_list_with_equality_func(self):
        # This fails
        self.addTypeEqualityFunc(C, always_equal)
        l1 = [C()]
        l2 = [C()]
        self.assertEqual(l1, l2)
</code></pre>
",https://stackoverflow.com/questions/66339564/how-to-add-an-equality-function-that-is-used-in-collection-comparisons-in-python,"['python', 'python-unittest']",94,False,-2,1
Best practice for creating an API resource in unit test - database or POST endpoint?,"<p>What is the best practice for creating resources while unit testing a GET endpoint in a REST API?</p>
<p>Should I create them directly in the database:</p>
<pre><code>  def test_can_get_todos_list(self):

        todo1 = Todo(text='todo1', user_id=self.user.id)
        todo2 = Todo(text='todo2', user_id=self.user.id)

        db.session.add_all([todo1, todo2]) # creating expected response todos directly in the database
        db.session.commit()

        response = self.client.get('api/todos')
        result = [
            {'text': 'todo1', 'id': 1},
            {'text': 'todo2', 'id': 2},
        ]
        
        self.assertEqual(response.status_code, 200)
        self.assertEqual(result, response.json)
</code></pre>
<p>or should I utilize another API endpoint (POST) that I built for creating resources of this type. So instead of doing:</p>
<pre><code>db.session.add_all([todo1, todo2]) 
db.session.commit()
</code></pre>
<p>I could do something like this:</p>
<pre><code>self.client.post(/api/todos, data='todos payload here')
</code></pre>
",https://stackoverflow.com/questions/66676921/best-practice-for-creating-an-api-resource-in-unit-test-database-or-post-endpo,"['python', 'flask', 'rest']",127,True,-1,1
Why are the integers in the array negative after reversing the array and reversing back to the original array?,"<pre><code>void reverseArray(int arrayLength, int sequence[]){
    int temparr[arrayLength];
    int *pointStart = sequence;
    int *pointEnd = sequence + arrayLength - 1;
    for(int i = 0; i &lt; arrayLength; i++){
        temparr[i] = *pointEnd - i;  
    }
    for(int i = 0; i &lt; arrayLength; i++){
        sequence[i] = temparr[i];
    }

}

void printArray(int arrayLength, int sequence[]){
    for(int i = 0; i &lt; arrayLength; i++, sequence++){
        std::cout &lt;&lt; *sequence &lt;&lt; &quot; &quot;;
    }
    std::cout &lt;&lt; &quot;\n&quot;;
}




int main(int argc, char **argv) {
    const int num = 50;
    int arr[num]; 

    for (int i = 0; i &lt; num; i++){
      arr[i] = i;
    }

    reverseArray(num, arr);
    std::cout &lt;&lt; &quot;Printing reverse array...\n&quot;;
    printArray(num, arr);
    reverseArray(num, arr);
    std::cout &lt;&lt; &quot;Printing reverse of the reverse array...\n&quot;;
    printArray(num, arr);
    ASSERT_EQ(0, arr[0]);
    ASSERT_EQ(24, arr[24]);
    ASSERT_EQ(49, arr[49]);

    return 0;
}
</code></pre>
<p>I am able to reverse the array, but when I put the &quot;reversed&quot; array back into the function, it seems to be of negative elements. I am not sure where this happens... Anything will help! The unit testing isn't the problem, but it is a part of the code.
[1]: <a href=""https://i.stack.imgur.com/MkfBC.png"" rel=""nofollow noreferrer"">https://i.stack.imgur.com/MkfBC.png</a></p>
",https://stackoverflow.com/questions/69306238/why-are-the-integers-in-the-array-negative-after-reversing-the-array-and-reversi,"['c++', 'arrays', 'unit-testing', 'pointers']",67,True,0,1
Use AspNetCore.Identity RoleManager and UserManager in an Interface,"<p>I'm implementing RoleManager and UserManager in an Interface, I'm aware of some of the potential benefits, like Unit Testing, is there any drawbacks of doing this?</p>
<p>AdministrationDataService.cs:</p>
<pre><code>public class AdministrationDataService : IAdministrationDataService
  {
    private readonly RoleManager&lt;IdentityRole&gt; _roleManager;

    public AdministrationDataService(RoleManager&lt;IdentityRole&gt; roleManager)
    {
      _roleManager = roleManager;
    }

    public IQueryable&lt;IdentityRole&gt; GetRolesList()
    {
      var roles = _roleManager.Roles;

      return roles;
    }
  }
</code></pre>
<p>IAdministrationDataService.cs:</p>
<pre><code>public interface IAdministrationDataService
  {
    IQueryable&lt;IdentityRole&gt; GetRolesList();
  }
</code></pre>
<p>Then I'm using it like this.</p>
<p>ViewRoles.cshtml.cs:</p>
<pre><code>public class ViewRolesModel : PageModel
  {
    public List&lt;IdentityRole&gt; Roles { get; set; } = new List&lt;IdentityRole&gt;();

    private readonly IAdministrationDataService _administrationDataService;

    public ViewRolesModel(IAdministrationDataService administrationDataService)
    {
      _administrationDataService = administrationDataService;
    }

    public void OnGet()
    {
      Roles = _administrationDataService.GetRolesList().ToList();
    }
  }
</code></pre>
<p>Which other benefit do I get by using this approach instead of just using RoleManager in ViewRoles.cshtml.cs</p>
",https://stackoverflow.com/questions/69240993/use-aspnetcore-identity-rolemanager-and-usermanager-in-an-interface,"['c#', 'asp.net-core', '.net-core', 'dependency-injection', 'asp.net-identity']",364,False,0,1
How to Mock AzureServiceTokenProvider,"<p>I have a function which gets the access token from the AppIdUri. This function calls inside my business logic. While Unit testing the logic GetAccessToken is returning null. I need to mock this  AzureServiceTokenProvider inorder to Pass the testcase. AzureServiceTokenProvider does not have an Interface. Does anyone knows how to Mock AzureServiceTokenProvider.</p>
<pre><code>private async Task&lt;string&gt; GetAccessToken()
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync($&quot;{AppIdUri}&quot;);
            return accessToken;
        }

</code></pre>
",https://stackoverflow.com/questions/70366644/how-to-mock-azureservicetokenprovider,"['c#', 'azure', 'unit-testing', 'azure-functions']",398,False,0,1
How to test HashPassword in WordPress?,"<p>I want to test (unit testing) <code>HashPassword($password)</code> method from WordPress.</p>
<p>How I can check that HashPassword(&quot;123123&quot;) will return the correct hash for it?</p>
<p>For example, I want to do something like:</p>
<pre><code>$hashFor123123 = &quot;$P$P)230230832482349823&quot;;

$result = HashPassword(&quot;123123&quot;);

$this-&gt;assertSame($hashFor123123, $result);
</code></pre>
<p>But, <strong>HashPassword</strong> method each time returns a new string with hash. That is why I cant do assert.</p>
<p>How to test it?</p>
",https://stackoverflow.com/questions/70170175/how-to-test-hashpassword-in-wordpress,"['wordpress', 'unit-testing', 'salt', 'password-hash']",222,True,0,2
Popup is not being garbage collected,"<p>I am unit testing my code for memory leaks. If I call <code>Popup.IsOpen = true</code>, then the garbage collector does not collect the popup or its child. If I comment out <code>Popup.IsOpen = true</code>, the garbage collector will collect both.</p>
<p>I would like to force garbage collection on the popup so I can properly test my own code.</p>
<pre><code>public void MemoryLeak_Popup()
{
    WeakReference weakReferencePopup;
    WeakReference weakReferenceChild;

    {
        Popup popup = new Popup();
        popup.Child = new StackPanel();

        popup.IsOpen = true;
        popup.IsOpen = false;

        weakReferencePopup = new WeakReference(popup);
        weakReferenceChild = new WeakReference(popup.Child);

        popup.Child = null;
    }

    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();

    Assert.IsFalse(weakReferenceChild.IsAlive, &quot;Memory leak for the popup's child.&quot;);
    Assert.IsFalse(weakReferencePopup.IsAlive, &quot;Memory leak for the popup.&quot;);
}
</code></pre>
",https://stackoverflow.com/questions/68105884/popup-is-not-being-garbage-collected,"['c#', 'wpf', 'memory-leaks', 'garbage-collection', 'popup']",121,False,0,0
How to mock a function call in java,"<p>I am new to Unit testing and trying to figure out the different implementations of testing. I m trying to figure out how to mock a particular function call. I came across Mock Spy but didn't quite understand how it's been used. Can someone tell me how mocking is done in such cases...</p>
<pre><code>Class ABC {
   
    void display(String name, int id){
       validateName(name);
       validateId(id);
     }
}


Class TestIt{
   
   @Test
   void testValidation(){

     //how to mock validateName function call and test only validateId ?
     ABC obj=new ABC();
     obj.display(&quot;abc&quot;,2);
   }
}
</code></pre>
",https://stackoverflow.com/questions/66840491/how-to-mock-a-function-call-in-java,"['java', 'spring-boot', 'unit-testing', 'junit', 'mockito']",78,True,0,1
How do I set the storage options in docker-compose v3?,"<p>Docker Compose version 2 has a store_opts key. Docker compose 3 does not.</p>
<blockquote>
<p><a href=""https://docs.docker.com/compose/compose-file/compose-file-v2/"" rel=""nofollow noreferrer"">https://docs.docker.com/compose/compose-file/compose-file-v2/</a></p>
</blockquote>
<p>I want to set the storage options of docker-compose to use the <code>inmemory</code> driver, because I'm using docker-compose for unit testing a database. How can I set the storage driver in docker-compose v3?</p>
",https://stackoverflow.com/questions/66172226/how-do-i-set-the-storage-options-in-docker-compose-v3,"['docker', 'docker-compose']",1668,True,3,3
"Minitest: an array of strings as an input, returns all elements from the array that are substrings of at least one of the other strings in the array","<pre><code>class SubstringFinder
  def self.find_all(set)
    result = []
    set.each { |item|
      set.each { |comparison|
        raise ArgumentError unless comparison.is_a? String
        if comparison.downcase.include?(item.downcase) &amp;&amp; comparison.length &gt; item.length
          result &lt;&lt; item
          break
        else
        end
      }
    }
    result
  end
</code></pre>
<p>Create a test suite to cover the behavior of code, adding as many distinct
test cases as you can.</p>
<p>How many distinct test cases can be derived from the code and how can it be arranged. I am from a python background and now trying to learn ruby and minitest for Unit testing.</p>
",https://stackoverflow.com/questions/69109584/minitest-an-array-of-strings-as-an-input-returns-all-elements-from-the-array-t,"['arrays', 'ruby-on-rails', 'ruby', 'substring', 'minitest']",245,False,-1,1
"FormArray, Form Control for unit testing in angular (jasmine)","<p>I am still new in Angular and Jasmine for unit testing. If code in component.ts like this</p>
<pre><code>formGroup: FormGroup;

regexObj = {
    numberRegex: '^\d+$',
    nameRegex: '^[a-zA-Z0-9-_. ]*$',
    vendorRegex: '^[a-zA-Z0-9-_. ]*$',
    longLatRegex: '^[0-9.-]*$',
    priceRegex: '^[0-9]*$'
};



 
setBillboardIdValidator(index: number) {
     this.getForms().controls[index].get('billboardId').setValidators([Validators.pattern(this.regexObj.nameRegex), Validators.required]);
}


getForms(): FormArray {
    return this.formGroup.get('forms') as FormArray;
}
</code></pre>
<p>in component.spec.ts I write like this:</p>
<pre><code>In component.spec.ts, I create like this
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(UploadFormComponent);
    component = fixture.componentInstance;
    component.form = new FormGroup({
      billboardName: new FormControl('', Validators.required)
    });
    fixture.detectChanges();
  });

  it('setBillboardNameValidator', () =&gt; {
    const control = component.form.controls['billboardName'];
    component.setBillboardNameValidator(9)
    expect(control).toBeTruthy();
  });
</code></pre>
<p>When I running the the unit test, I got message can not read property <strong>TypeError: Cannot read property 'get' of undefined</strong>. Can you help me what's wrong with my code?</p>
",https://stackoverflow.com/questions/68203777/formarray-form-control-for-unit-testing-in-angular-jasmine,"['angular', 'unit-testing', 'jasmine', 'angular-reactive-forms']",743,False,0,0
How can I access a globally defined property that is accessed through a property file using Spock when unit testing,"<p>I'm Trying to unit test a method for which uses a globally defined variable derived from a property file using @Value Annotation. How can I access this global property in a service class in the unit testing without having to pass it to the method signature.</p>
<p>ex:
Spring Boot service named 'SampleService'</p>
<pre><code>@Value(&quot;${sampleproperty.value}&quot;)
private String sampleProperty;

private sampleMethodName(){
     //method which uses the global variable 'sampleProperty'
}
</code></pre>
<p>sample Spock Test</p>
<pre><code>def &quot;Unit Test&quot;(){
    given:
       //ToDo
    when:
       sampleService.sampleMethodName() //How to access the 'sampleProperty'
    then:
       //ToDo
}
</code></pre>
",https://stackoverflow.com/questions/66149526/how-can-i-access-a-globally-defined-property-that-is-accessed-through-a-property,"['java', 'spring-boot', 'unit-testing', 'groovy', 'spock']",219,True,1,1
Immutable Valid annotations not running,"<p>I'm trying to use immutable library <a href=""https://immutables.github.io/"" rel=""nofollow noreferrer"">https://immutables.github.io/</a>
and validate the fields using javax.validation but the annotations are just ignored when the class is generated.  Even on unit testing it just doesn't throw any error.</p>
<pre><code>    import javax.validation.Valid;
    import javax.validation.constraints.Size;
    import org.immutables.value.Value;

    @Value.Immutable
    public interface Entity {
        @Valid @Size(max = 10) 
        String name();
    }
</code></pre>
<p>my pom.xml, I tried to add <strong>spring-boot-starter-validation</strong> and also <strong>javax.validation</strong> but it just doesn't trigger the validations</p>
<pre><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 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&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.5.4&lt;/version&gt;
            &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
        &lt;/parent&gt;
        &lt;groupId&gt;com.example&lt;/groupId&gt;
        &lt;artifactId&gt;immutableTest&lt;/artifactId&gt;
        &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
        &lt;name&gt;immutableTest&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&lt;/artifactId&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
                &lt;scope&gt;test&lt;/scope&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.immutables&lt;/groupId&gt;
                &lt;artifactId&gt;value&lt;/artifactId&gt;
                &lt;version&gt;2.8.8&lt;/version&gt;
                &lt;scope&gt;provided&lt;/scope&gt;
            &lt;/dependency&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;org.assertj&lt;/groupId&gt;
                &lt;artifactId&gt;assertj-core&lt;/artifactId&gt;
                &lt;version&gt;3.21.0&lt;/version&gt;
                &lt;scope&gt;test&lt;/scope&gt;
            &lt;/dependency&gt;
            &lt;!-- https://mvnrepository.com/artifact/javax.validation/validation-api --&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;javax.validation&lt;/groupId&gt;
                &lt;artifactId&gt;validation-api&lt;/artifactId&gt;
                &lt;version&gt;2.0.1.Final&lt;/version&gt;
            &lt;/dependency&gt;
            &lt;!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --&gt;
            &lt;dependency&gt;
                &lt;groupId&gt;com.fasterxml.jackson.core&lt;/groupId&gt;
                &lt;artifactId&gt;jackson-databind&lt;/artifactId&gt;
                &lt;version&gt;2.12.5&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>
",https://stackoverflow.com/questions/69330332/immutable-valid-annotations-not-running,"['java', 'spring', 'spring-boot', 'spring-boot-test', 'immutables-library']",635,False,1,1
Unit testing dependency injections,"<p>I want to mock dependencies in a class but I cannot find the right way to achieve that. Using sinon for the unit testing. For example:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>const { classB } = require(""./classes/classB"");
const { classC } = require(""./classes/classC"");
const sinon = require(""sinon"");

class classA {
    constructor() {
        this.classB = new classB();
        this.classC = new classC();
    }
 
    doSomething() {
        const data = this.classB.getInfo();
        const processed = processInfo(data);
        this.classC.processedData(processed);
        
    }
    
    processInfo(data) {
        // doesSomeProcessing
    }
}

module.exports = {
    classA
};

describe(""classA"", () =&gt; {
    describe(""when instantiated"", () =&gt; {
        it(""calls classB's getInfo once, classC's processedData data once."", () =&gt; {
            sinon.stub(classB);
            let clsA = new classA();
            sinon.assert.calledOnce(classB.getInfo);
            sinon.assert.calledOnce(classC.processedData);
            // Also can we do something like this?
            // when classB.getinfo.then(provideMockData) 
            // so that we can mock the calls being made to avoid actual calls?
        });
    });
});</code></pre>
</div>
</div>
</p>
<p>I tried doing research around this but could not find a workable solution. Any insight will be super helpful! Thanks in advance and apologies for any trouble caused!</p>
",https://stackoverflow.com/questions/66751571/unit-testing-dependency-injections,"['javascript', 'unit-testing', 'mocking', 'sinon', 'sinon-chai']",185,True,1,1
How to import data from another file? laravel,"<p>I want to get the data from the below file. I want to know is this possible to achieve? and how we to import it in another file? Purpose of this, is for my unit testing.</p>
<p>I tried the below code but it returns an error.</p>
<pre><code>dd(userData);
</code></pre>
<blockquote>
<p>ErrorException: Use of undefined constant userData - assumed 'userData'</p>
</blockquote>
<hr>
<p><strong>userData.php</strong></p>
<pre><code>&lt;?php

return [
    [
        'name' =&gt; 'Perla',
        'age' =&gt; 13,
    ],
    [
        'name' =&gt; 'Felepe',
        'age' =&gt; 23,
    ],
    [
        'name' =&gt; 'Timoteo',
        'age' =&gt; 50,
    ]
]
</code></pre>
",https://stackoverflow.com/questions/69390514/how-to-import-data-from-another-file-laravel,"['php', 'laravel']",430,True,1,1
Mocking dependencies of a module singleton in unit testing (Python),"<p>In a simple unit testing scenario, suppose I have the following module:</p>
<pre><code>class DatabaseMediator:
    def __init__(self, mock_connection):
        self.db_connection = mock_connection if mock_connection is not None else connect()


databaseMediator = DatabaseMediator()
</code></pre>
<p>assuming <code>connect</code> is a method that might be imported from another module and establishes a db connection.</p>
<p>Now because we're unit testing, it is desirable to be able to test the class isolated way and therefore instantiate it without an actual database connection, so one could to this:</p>
<pre><code>from database_mediator import DatabaseMediator

mock_mediator = DatabaseMediator(mock())
</code></pre>
<p>in order to get a testable instance of <code>DatabaseMediator</code> that doesn't actually have a database connection. However, as we know, when you import anything from a module in Python, the whole module is executed and therefore, the <code>databaseMediator</code> instance will also be created. This can become a problem however, e. g. when we're in a CI pipeline and there is no database instance to connect to and therefore this method throws an error.</p>
<p>Is there any way to have the dependencies of the singleton mocked? Or an overall better approach to the problem?</p>
",https://stackoverflow.com/questions/68458614/mocking-dependencies-of-a-module-singleton-in-unit-testing-python,"['python', 'unit-testing', 'mocking', 'singleton', 'python-module']",63,False,0,0
How do you test a React function component state with Jest?,"<p>I am only starting with unit testing now and the course I am following has the following syntax for a test:</p>
<p><code>expect(app.state().gifts).toEqual([])</code></p>
<p>This is the syntax for the use of class components but that will be deprecated soon so I am using React function components instead.</p>
<p>How do you accomplish the same test with hooks?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/69461961/how-do-you-test-a-react-function-component-state-with-jest,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",1383,True,-1,1
Mocking a Python object without method calls,"<p>Imagine a class like so:</p>
<pre><code>class Foo():

    def method_1(self):
        bar = Bar()
        bazz = Bazz(bar)
        return bazz.method_2()
</code></pre>
<p>For unit testing, how can we mock the <code>Bar</code> object when we never call any methods on it, we're just passing it as a parameter to the <code>Bazz</code> constructor? (Yes, this is not ideal, but this pattern can be found in a top-level class wiring together different objects via dependency injection).</p>
",https://stackoverflow.com/questions/67488987/mocking-a-python-object-without-method-calls,"['python', 'python-mock', 'pytest-mock']",629,False,0,1
unit testing express middleware,"<p>I have the following middleware function in my express app,</p>
<pre><code>const { getEmployerId } = require(&quot;./employerApi&quot;);

const setEmployerDetails = (employerId) =&gt; {
    return (req, res, next) =&gt; {
        getEmployerId(req, res, next, employerId);
    }
}

module.exports = setEmployerDetails
</code></pre>
<p>I wanting to unit test this middleware, but I am not sure how, the function basically returns whatever the API returns, the API is already unit tested. How would I go about unit testing this function with something like chai?</p>
<p>So far I have,</p>
<pre><code>describe('setEmployerDetails`, () =&gt; {
   it('should be a function', () =&gt; expect(setEmployerDetails).to.be.a('function'));
   it('should take 1 argument', () =&gt; expect(setEmployerDetails.length).to.equal(1));
});`
</code></pre>
",https://stackoverflow.com/questions/66798873/unit-testing-express-middleware,"['javascript', 'node.js', 'express', 'unit-testing', 'chai']",446,False,0,1
org.mockito.exceptions.misusing.InvalidUseOfMatchersException: While writing unit test,"<p>When I want to test my method I got this error, I am new to unit testing. Not able to find the exact issue.Seems like error in the second last line of the test method while printing <code>test6</code> log.
Any suggestion !</p>
<pre><code>12 Jul 2021 13:51:54,915 [INFO ]  (main) amazon.platform.config.AppConfigTree:1756: No appgroup found
test1
test2
test3
test4
test5

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
4 matchers expected, 3 recorded:

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), &quot;raw String&quot;);
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq(&quot;String by matcher&quot;));

For more info see javadoc for Matchers class.
</code></pre>
<p><strong>This is the class that I want to test.</strong></p>
<pre class=""lang-java prettyprint-override""><code>public String addCommitAndPushUntrackedChanges(final String deviceName, final List&lt;String&gt; filesList)
            throws GitAPIException, IOException, DependencyFailureException {
        final String tempCommitBranchName = String.format(&quot;Add Sync &quot;
                + &quot;rules : [%s]&quot;, deviceName);
        final File gitFile = new File(String.join(&quot;/&quot;, CLONED_REPO_PATH, &quot;.git&quot;));
        String CommitId = jgitAccessor.addAndCommitUntrackedChanges(gitFile, deviceName, tempCommitBranchName, filesList);
        gitFarmServiceAccessor.loadTmpSshTicket();
        jgitAccessor.pushToTemporaryBranch(gitFile, REPO_URI, deviceName);
        return CommitId;
    }
</code></pre>
<p><strong>This is the test method</strong></p>
<pre class=""lang-java prettyprint-override""><code>  @InjectMocks
    CreateIngestionRulesTaskBuilder builder;

@Test
    public void addCommitAndPushUntrackedChanges_happyCase() throws Exception {
        System.out.println(&quot;test1&quot;);
        Mockito.doNothing().when(gitFarmServiceAccessor).loadTmpSshTicket();
        System.out.println(&quot;test2&quot;);
        System.out.println(&quot;test3&quot;);
        Mockito.doNothing().when(jgitAccessor).pushToTemporaryBranch(REPO_FILE, REPO_LOCATION,&quot;abc&quot;);
        System.out.println(&quot;test4&quot;);
        when(jgitAccessor.addAndCommitUntrackedChanges(eq(REPO_FILE),eq(TEST_DEVICE_NAME),eq(TEST_COMMIT_MSG), anyList())).thenReturn(eq(TEST_COMMIT_ID));
        System.out.println(&quot;test5&quot;);
        builder.addCommitAndPushUntrackedChanges(any(), anyList());
        System.out.println(&quot;test6&quot;);
    }




</code></pre>
",https://stackoverflow.com/questions/68344250/org-mockito-exceptions-misusing-invaliduseofmatchersexception-while-writing-uni,"['junit', 'mockito']",95,False,0,0
How do I unit test amcharts using jest with react and typescript?,"<p>I have reproduced the compilation error that I came across while working on a project using Jest with amCharts. Apparently, Jest cannot compile anything to do with amchart for unit testing.</p>
<p><strong>Error</strong></p>
<pre><code>/core.js:8
export { System, system } from &quot;./.internal/core/System&quot;;
^^^^^^

SyntaxError: Unexpected token 'export'

  1 | import { useEffect, useRef } from &quot;react&quot;;
&gt; 2 | import * as am4core from &quot;@amcharts/amcharts4/core&quot;;
    | ^
  3 | import * as am4charts from &quot;@amcharts/amcharts4/charts&quot;;
  4 |
  5 | const data = [

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
  at Object.&lt;anonymous&gt; (src/App.tsx:2:1)
</code></pre>
<p>Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.067 s
Ran all test suites.</p>
<p><strong>Jest.config.ts</strong></p>
<pre><code>module.exports = {
  roots: [&quot;&lt;rootDir&gt;/src&quot;],
  collectCoverageFrom: [&quot;src/**/*.{js,jsx,ts,tsx}&quot;, &quot;!src/**/*.d.ts&quot;],
  setupFiles: [&quot;react-app-polyfill/jsdom&quot;],
  testMatch: [
    &quot;&lt;rootDir&gt;/src/**/__tests__/**/*.{js,jsx,ts,tsx}&quot;,
    &quot;&lt;rootDir&gt;/src/**/*.{spec,test}.{js,jsx,ts,tsx}&quot;,
  ],
  testEnvironment: &quot;jsdom&quot;,
  testRunner:
    &quot;/home/xeonrazr/Playground/amcharts-jest-err/node_modules/jest-circus/runner.js&quot;,
  transform: {
    &quot;^.+\\.(js|jsx|mjs|cjs|ts|tsx)$&quot;: &quot;&lt;rootDir&gt;/config/jest/babelTransform.js&quot;,
    &quot;^.+\\.css$&quot;: &quot;&lt;rootDir&gt;/config/jest/cssTransform.js&quot;,
    &quot;^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)&quot;:
      &quot;&lt;rootDir&gt;/config/jest/fileTransform.js&quot;,
  },
  transformIgnorePatterns: [
    &quot;[/\\\\]node_modules[/\\\\].+\\.(js|jsx|mjs|cjs|ts|tsx)$&quot;,
    &quot;^.+\\.module\\.(css|sass|scss)$&quot;,
  ],
  modulePaths: [],
  moduleNameMapper: {
    &quot;^react-native$&quot;: &quot;react-native-web&quot;,
    &quot;^.+\\.module\\.(css|sass|scss)$&quot;: &quot;identity-obj-proxy&quot;,
  },
  moduleFileExtensions: [
    &quot;web.js&quot;,
    &quot;js&quot;,
    &quot;web.ts&quot;,
    &quot;ts&quot;,
    &quot;web.tsx&quot;,
    &quot;tsx&quot;,
    &quot;json&quot;,
    &quot;web.jsx&quot;,
    &quot;jsx&quot;,
    &quot;node&quot;,
  ],
  watchPlugins: [
    &quot;jest-watch-typeahead/filename&quot;,
    &quot;jest-watch-typeahead/testname&quot;,
  ],
  resetMocks: true,
};
</code></pre>
<p><strong>App.tsx</strong></p>
<pre><code>import { useEffect, useRef } from &quot;react&quot;;
import * as am4core from &quot;@amcharts/amcharts4/core&quot;;
import * as am4charts from &quot;@amcharts/amcharts4/charts&quot;;

const data = [
  {
    country: &quot;Lithuania&quot;,
    litres: 501.9,
  },
  {
    country: &quot;Czech Republic&quot;,
    litres: 301.9,
  },
  {
    country: &quot;Ireland&quot;,
    litres: 201.1,
  },
  {
    country: &quot;Germany&quot;,
    litres: 165.8,
  },
  {
    country: &quot;Australia&quot;,
    litres: 139.9,
  },
  {
    country: &quot;Austria&quot;,
    litres: 128.3,
  },
  {
    country: &quot;UK&quot;,
    litres: 99,
  },
  {
    country: &quot;Belgium&quot;,
    litres: 60,
  },
  {
    country: &quot;The Netherlands&quot;,
    litres: 50,
  },
];

function App() {
  const chartRef = useRef(am4core.create(&quot;chartdiv&quot;, am4charts.PieChart));

  useEffect(() =&gt; {
    let series = chartRef.current.series.push(new am4charts.PieSeries());
    series.dataFields.value = &quot;litres&quot;;
    series.dataFields.category = &quot;country&quot;;
    chartRef.current.data = data;
    chartRef.current.legend = new am4charts.Legend();
  }, []);

  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;div
        data-testid=&quot;chartdiv&quot;
        style={{ height: &quot;600px&quot;, width: &quot;100%&quot; }}
        id=&quot;chartdiv&quot;
      &gt;&lt;/div&gt;
    &lt;/div&gt;
  );
}

export default App;


</code></pre>
<p><strong>App.test.tsx</strong></p>
<pre><code>import { render } from &quot;@testing-library/react&quot;;
import App from &quot;./App&quot;;

test(&quot;renders learn react link&quot;, () =&gt; {
  const { getByTestId } = render(&lt;App /&gt;);
  const chartEl = getByTestId(&quot;chartdiv&quot;);
  expect(chartEl).toBeInTheDocument();
});
</code></pre>
<p><a href=""https://github.com/XeonRazr/amcharts-jest-err.git"" rel=""nofollow noreferrer"">Repo Link</a></p>
",https://stackoverflow.com/questions/68951361/how-do-i-unit-test-amcharts-using-jest-with-react-and-typescript,"['reactjs', 'typescript', 'unit-testing', 'jestjs', 'amcharts']",818,False,1,1
jasmine-browser-runner reports: Uncaught ReferenceError: exports is not defined,"<p>I am using Jasmine for unit testing of javascript/typescript server size code. It works as expected for command prompt based testing. When I used jasmine-browser-runner (&gt;npx jasmine-browser-runner) and start the browser, I get:</p>
<pre><code>0 specs, 0 failures, randomized with seed 00949
Error during loading: Uncaught ReferenceError: exports is not defined in http://localhost:8888/__spec__/test.spec.js line 2
</code></pre>
<p>This is the content of most simple test.spec.ts (compiled from typescript to js):</p>
<pre><code>import &quot;jasmine&quot;;
describe(&quot;B suite&quot;, function () {
  it(&quot;contains spec with an expectation&quot;, function () {
    expect(true).toBe(true);
  });
});
</code></pre>
<p>js:</p>
<pre><code>&quot;use strict&quot;;
Object.defineProperty(exports, &quot;__esModule&quot;, { value: true });
require(&quot;jasmine&quot;);
describe(&quot;B suite&quot;, function () {
    it(&quot;contains spec with an expectation&quot;, function () {
        expect(true).toBe(true);
    });
});

//# sourceMappingURL=test.spec.js.map
</code></pre>
<p>in tsconfig.json:</p>
<pre><code>&quot;target&quot;: &quot;ES2015&quot;
 &quot;module&quot;: &quot;commonjs&quot;
</code></pre>
<p>Any idea?
br</p>
",https://stackoverflow.com/questions/68530686/jasmine-browser-runner-reports-uncaught-referenceerror-exports-is-not-defined,"['javascript', 'typescript', 'unit-testing', 'jasmine']",102,False,1,0
Vuetify error: Unknown custom element: &lt;v-app-bar&gt; - did you register the component correctly?,"<p>When i normal start my app (npm run serve) it's all right. But when i want start Unit testing with Jest, the console gives me an error:</p>
<p><strong>[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the &quot;name&quot; option.</strong></p>
<p>Can someone help me?</p>
<p>plugins/vuetify.ts</p>
<pre><code>import '@mdi/font/css/materialdesignicons.css'
import Vue from 'vue'
import Vuetify from 'vuetify'

Vue.use(Vuetify)
</code></pre>
<p>package.json</p>
<pre><code>&quot;dependencies&quot;: {
    &quot;@vue/composition-api&quot;: &quot;^1.0.0-rc.5&quot;,
    &quot;core-js&quot;: &quot;^3.6.5&quot;,
    &quot;register-service-worker&quot;: &quot;^1.7.1&quot;,
    &quot;vue&quot;: &quot;^2.6.11&quot;,
    &quot;vuetify&quot;: &quot;^2.4.0&quot;,
    &quot;webpack&quot;: &quot;^4.45.0&quot;,
    &quot;webpack-assets-manifest&quot;: &quot;^4.0.1&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@mdi/font&quot;: &quot;^5.9.55&quot;,
    &quot;@types/jest&quot;: &quot;^24.0.19&quot;,
    &quot;@typescript-eslint/eslint-plugin&quot;: &quot;^4.18.0&quot;,
    &quot;@typescript-eslint/parser&quot;: &quot;^4.18.0&quot;,
    &quot;@vue/cli-plugin-babel&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-plugin-e2e-cypress&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-plugin-eslint&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-plugin-pwa&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-plugin-typescript&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-plugin-unit-jest&quot;: &quot;^4.5.0&quot;,
    &quot;@vue/cli-service&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/eslint-config-prettier&quot;: &quot;^6.0.0&quot;,
    &quot;@vue/eslint-config-typescript&quot;: &quot;^7.0.0&quot;,
    &quot;@vue/test-utils&quot;: &quot;^1.0.3&quot;,
    &quot;eslint&quot;: &quot;^6.7.2&quot;,
    &quot;eslint-formatter-gitlab&quot;: &quot;^2.2.0&quot;,
    &quot;eslint-plugin-prettier&quot;: &quot;^3.3.1&quot;,
    &quot;eslint-plugin-vue&quot;: &quot;^7.0.0-beta.4&quot;,
    &quot;node-sass&quot;: &quot;^4.12.0&quot;,
    &quot;prettier&quot;: &quot;^2.2.1&quot;,
    &quot;sass&quot;: &quot;^1.32.0&quot;,
    &quot;sass-loader&quot;: &quot;^10.0.0&quot;,
    &quot;typescript&quot;: &quot;~4.1.5&quot;,
    &quot;vue-cli-plugin-vuetify&quot;: &quot;~2.3.1&quot;,
    &quot;vue-template-compiler&quot;: &quot;^2.6.11&quot;,
    &quot;vuetify-loader&quot;: &quot;^1.7.0&quot;
  }
</code></pre>
",https://stackoverflow.com/questions/66851540/vuetify-error-unknown-custom-element-v-app-bar-did-you-register-the-compon,"['vue.js', 'jestjs', 'vuetify.js']",676,False,0,2
C# Mock - Stripe Services - Returns null,"<p>I've got a problem with unit testing Stripe services.</p>
<p>I have a controller, which calls my services and these again call the stripe apis.</p>
<p>I'm trying to mock the CreateAsync Method inside my PaymentIntentService.</p>
<p><em>My Service:</em></p>
<pre><code>   private readonly PaymentIntentService _paymentIntentService;

    #region Constructor


    public StripePaymentIntentService(Stripe.PaymentIntentService paymentIntentService)
    {
        _paymentIntentService = paymentIntentService;
    }

    public async Task&lt;PaymentIntent&gt; CreatePaymentIntentAsync(PaymentIntentCreateRequest request)
    {
        var paymentIntentCreateOptions = new PaymentIntentCreateOptions
        {
            Amount = request.Amount,
            Currency = request.Currency,
            Customer = request.StripeCustomerId,
        };

        if (request.IsHold)
            paymentIntentCreateOptions.CaptureMethod = &quot;manual&quot;;

        if (request.IsSetupForFuturePayments)
            paymentIntentCreateOptions.SetupFutureUsage = &quot;off_session&quot;;

        //I want to Mock the CreateAsync Method.
        var intent = await _paymentIntentService.CreateAsync(paymentIntentCreateOptions);

        return intent;
    }
</code></pre>
<p><em>My test:</em></p>
<pre><code>public class StripePaymentIntentServiceShould
{

    #region members
    private Stripe.PaymentIntentCreateOptions request;
    private readonly StripePaymentIntentService _service;
    private readonly Mock&lt;PaymentIntentService&gt; _mockService;
    #endregion

    #region constructor
    public StripePaymentIntentServiceShould()        {

        _mockService  = new Mock&lt;PaymentIntentService&gt;();

        _mockService.Reset();

        request = new Stripe.PaymentIntentCreateOptions()
        {
            Amount = 123,
            Currency = &quot;&quot;
            CaptureMethod = &quot;&quot;,
            SetupFutureUsage = &quot;&quot;,
            Customer = &quot;&quot;,
        };

        _mockService.Setup(service =&gt; service.CreateAsync(request, null, default)).Returns(Task.FromResult(new PaymentIntent { Id = &quot;dummy&quot; }));
        _service = new StripePaymentIntentService(_mockService.Object);

  
    }
    #endregion

    #region methods

    [Fact]
    public async void CreatePaymentIntentAsync_Should()
    {
        //Arrange      
        PaymentIntentCreateRequest req = new PaymentIntentCreateRequest()
        {
            Amount = 123,
            Currency = &quot;&quot;,
            IsHold = true,
            isSetupForFuturePayments = true,
            StripeCustomerId = &quot;&quot;,
        };

        //Act
        var result = await _service.CreatePaymentIntentAsync(req);


        //Assert
        result.Id.Should().Be(&quot;dummy&quot;);
    }
    #endregion
}
</code></pre>
<p>But the CreateAsync returns null instead of the PaymentIntent Object.</p>
<p>Could you help me with that?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/67705263/c-mock-stripe-services-returns-null,"['c#', 'mocking', 'stripe-payments', 'payment']",569,False,0,0
Avoid or bypass multiple decorators in unit testing with pytest,"<p>Similar questions were asked before:</p>
<ul>
<li><a href=""https://stackoverflow.com/questions/9702219/how-to-skip-or-ignore-python-decorators"">How to skip or ignore python decorators</a></li>
<li><a href=""https://stackoverflow.com/questions/41206565/bypassing-a-decorator-for-unit-testing"">Bypassing a decorator for unit testing</a></li>
</ul>
<p><a href=""https://docs.python.org/3/library/functools.html#functools.wraps"" rel=""nofollow noreferrer""><code>functools.wraps</code></a> creates a magic method called <code>__wrapped__</code> in the decorator, which allows to access the wrapped function. When you have multiple decorators, though, this would return an inner decorator, not the original function.</p>
<p>How to avoid or bypass multiple decorators?</p>
",https://stackoverflow.com/questions/65961706/avoid-or-bypass-multiple-decorators-in-unit-testing-with-pytest,"['python', 'python-3.x', 'unit-testing', 'pytest']",639,True,1,1
How to fix this simple ElementNotFoundException in Blazor?,"<p>I am unit testing a blazor app. I get a ElementNotFoundException. I think the cause for this is an if statement in the the index.razor page. see code below:</p>
<pre><code>&lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;col-12&quot;&gt;
        @if ((challenges != null) &amp;&amp; (challenges.Count &gt; 0))
        {
            &lt;MultiStepComponent Id=&quot;MultiStepContainer&quot; Challenges=&quot;@challenges&quot;&gt;
                &lt;div class=&quot;row p-3&quot;&gt;
                    &lt;div class=&quot;col-6&quot; id=&quot;challengeContainer&quot;&gt;
                        @foreach(var c in challenges)
                        {
                            &lt;MultiStepNavigation Name=&quot;@c.Title&quot;&gt;
                                &lt;h1&gt;@c.Title&lt;/h1&gt;
                                &lt;img class=&quot;float-left&quot; src=&quot;@c.ImagePath&quot; width=&quot;200&quot; /&gt;
                                @foreach(var sentence in c.Description)
                                {
                                    &lt;p&gt;@sentence&lt;/p&gt;
                                }
                            &lt;/MultiStepNavigation&gt;
                        }
                    &lt;/div&gt;
                    &lt;div class=&quot;col-6&quot;&gt;
                        &lt;textarea rows=&quot;26&quot; cols=&quot;120&quot; @bind=&quot;input&quot; id=&quot;input&quot;&gt;&lt;/textarea&gt;

                        &lt;button class=&quot;btn&quot; id=&quot;runBtn&quot; @onclick=&quot;RunAsync&quot;&gt;Run&lt;/button&gt;

                        &lt;br /&gt;
                        &lt;textarea rows=&quot;10&quot; cols=&quot;120&quot; id=&quot;output&quot; readonly&gt;@((MarkupString)Output)&lt;/textarea&gt;
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/MultiStepComponent&gt;
        }
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<p>The code behind of this page (index.razor.cs) has the following initialization code:</p>
<pre><code>protected override async Task OnInitializedAsync()
    {
        jsonRepository = new JSONChallengeRepository();
        challenges = await jsonRepository.GetChallengesAsync();
    }
</code></pre>
<p>The test for this page is here:</p>
<pre><code>[Test]
    public async Task Compile_code_Success()
    {
        _codingChallengeService.Setup(c =&gt; c.SendInputToCompilerAsync(&quot;50+50&quot;)).ReturnsAsync(&quot;100&quot;);
        _testContext.Services.AddScoped(x =&gt; _codingChallengeService.Object);
        var razorComponent = _testContext.RenderComponent&lt;Index&gt;();
        razorComponent.Instance.challenges = GetChallenges();

        if ((razorComponent.Instance.challenges != null) &amp;&amp; (razorComponent.Instance.challenges.Count &gt; 0))
        {
            var runBtn = razorComponent.FindAll(&quot;button&quot;).FirstOrDefault(b =&gt; b.OuterHtml.Contains(&quot;Run&quot;));
            var input = razorComponent.Find(&quot;#input&quot;);
            input.Change(&quot;50+50&quot;);
        
            runBtn.Click();
        
            var outputArea = razorComponent.Find(&quot;#output&quot;);
            var outputAreaText = outputArea.TextContent;
            Assert.AreEqual(&quot;100&quot;, outputAreaText);
        }

        Assert.IsNotNull(razorComponent.Instance.challenges);
    }
</code></pre>
<p>The #input is missing..Why??</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/67487435/how-to-fix-this-simple-elementnotfoundexception-in-blazor,"['c#', 'nunit', 'blazor', 'blazor-webassembly', 'bunit']",454,True,1,1
How to test if ggplot was printed?,"<p>Let's consider very basic function :</p>
<pre><code>plot_ggplot &lt;- function() { 
    print(ggplot() + aes(x = 1:100, y = 1:100) + geom_point())
}
</code></pre>
<p>Is there any possibility to create sensible unit for <strong>such defined</strong> function ? I know that we can easily create unit testing when print is not included. Maybe is there possibility to check if something appears in plot window in R ?</p>
<p>I don't want to redefine the function because it's part of much bigger function.</p>
",https://stackoverflow.com/questions/65954246/how-to-test-if-ggplot-was-printed,"['r', 'unit-testing', 'ggplot2', 'testthat']",168,True,1,1
Reactjs unit testing : How to cover the code in useEffect hook? Using Jest and Enzyme,"<p>I am using a coverage report generator to automatically check the lines of unit testing coverage in files in the Pull request checks, etc.</p>
<p>However using Jest and Enzyme, I am unable to cover the <code>useEffect()</code> code which is affecting the coverage % as shown below. How can I cover the lines in <code>useEffect</code> hook? Is this possible in Jest/Enzyme?</p>
<p><a href=""https://i.stack.imgur.com/1DUdQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/1DUdQ.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/69894174/reactjs-unit-testing-how-to-cover-the-code-in-useeffect-hook-using-jest-and-e,"['reactjs', 'jestjs', 'enzyme']",303,False,1,1
Unit Testing with quarkus-smallrye-graphql,"<p>In a quarkus project with quarkus-smallrye-graphql lib, is there a way to unit test a GraphQL resource object like this one :</p>
<pre><code>@GraphQLApi
public class ProductResource {

    @Inject
    private ProductRepository productRepository;

    @Query(&quot;products&quot;)
    @Description(&quot;Get all Products&quot;)
    @RolesAllowed({&quot;USER&quot;,&quot;ADMIN&quot;})
    public List&lt;Product&gt; findAll() {
        return this.productRepository.findAll().list();
    }

    @Mutation
    @Description(&quot;Create a new Product&quot;)
    @RolesAllowed(&quot;ADMIN&quot;)
    public Boolean createProduct(String name, Double price) {
        return this.productRepository.createProduct(name, price);
    }
}
</code></pre>
<p>I want to be able to send a GraphQL query (with Authentication inactivated/or not) in unit testing in order to validate my annotations but I don't find any documented way to do it.</p>
",https://stackoverflow.com/questions/66545573/unit-testing-with-quarkus-smallrye-graphql,"['unit-testing', 'graphql', 'quarkus']",1158,True,1,3
How do you assert with delete method void,"<p>I'm unit testing a Spring boot web app with Mockito. One of my methods is returning a <code>void</code>, but if I try to test it, I get compilation errors.</p>
<p>This is the test I wrote:</p>
<pre class=""lang-java prettyprint-override""><code>public void testDeleteActor()throws NetflixException {
    when(actorRepository.findById(1L)).thenReturn(Optional.of(Mockito.any(Actor.class)));
    assertEquals(null, service.deleteActorById(Mockito.anyLong());
}
</code></pre>
<p>And this is the method I'm trying to test:</p>
<pre class=""lang-java prettyprint-override""><code>@Override
public void deleteActorById(Long id) throws NetflixException {
    Actor actor = actorRepository
        .findById(id)
        .orElseThrow(() -&gt; new NotFoundException(&quot;Actor id not found - &quot; + id));
    actorRepository.delete(actor);
}
</code></pre>
<p>As you can see in the following screenshot, I'm getting an error with my <code>assertEquals()</code> statement:</p>
<p><a href=""https://i.stack.imgur.com/4k7W5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4k7W5.png"" alt=""Screenshot of code with error"" /></a></p>
",https://stackoverflow.com/questions/69109025/how-do-you-assert-with-delete-method-void,"['spring-boot', 'junit', 'mockito']",1267,True,1,1
"Error: Wrap function is only available for `onCall` HTTP functions, not `onRequest`","<p>I am trying to set up unit testing for my firebase cloud-function. but getting this error</p>
<blockquote>
<p>Error: Wrap function is only available for <code>onCall</code> HTTP functions, not <code>onRequest</code>.</p>
</blockquote>
<p>this is how my app.test.ts looks like</p>
<pre><code>/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable @typescript-eslint/no-unused-vars */
import {stub} from &quot;sinon&quot;;
import * as admin from &quot;firebase-admin&quot;;
import funcTest from &quot;firebase-functions-test&quot;;
admin.initializeApp();

describe(&quot;Index Test&quot;, function() {
  let adminInitStub:any;
  let appCloudFunction:any;
  const test = funcTest();
  before(async () =&gt; {
    adminInitStub = stub(admin, &quot;initializeApp&quot;);
    appCloudFunction = await import(&quot;../index&quot;);
  });

  after(() =&gt; {
    adminInitStub.restore();
    test.cleanup();
  });
  it(&quot;should always pass&quot;, function() {
    const wrapped = test.wrap(appCloudFunction.app);
    wrapped(null);
  });
});
</code></pre>
<p>and my cloud function(index.ts) looks something like this</p>
<pre><code>import * as functions from &quot;firebase-functions&quot;;
import app from &quot;./app/app&quot;;
exports.app = functions.https.onRequest(app);
</code></pre>
<p>here app is an simple express application.</p>
<p>Can anyone help me solve this problem?</p>
",https://stackoverflow.com/questions/70442193/error-wrap-function-is-only-available-for-oncall-http-functions-not-onreque,"['firebase', 'unit-testing', 'google-cloud-functions']",293,True,1,1
Getting the error in python selenium testing for login and logout functionality,"<p>I am getting the error as...</p>
<p><em>AttributeError: 'LoginTestCase' object has no attribute 'driver'</em></p>
<p>And the code is</p>
<pre><code>from selenium import webdriver;
from selenium.webdriver.common.keys import Keys
import time
import unittest

class LoginTest(unittest.TestCase):
    
    @classmethod
    def setUpclass(cls):
        cls.driver = webdriver.Firefox(&quot;D:/Frontend/18-01-2021/selenium-testing&quot;)
        cls.driver.implicitly_wait(10)
        cls.driver.maximize_window()

    
     def test_login_valid(self):
        self.driver.get(&quot;http://localhost:4200&quot;)
        self.driver.find_element_by_name(&quot;username&quot;).send_keys(&quot;admin&quot;)
        self.driver.find_element_by_name(&quot;password&quot;).send_keys(&quot;admin@123&quot;)
        self.driver.find_element_by_id('log').click()
        self.driver.find_element_by_id('ab').click()
        self.driver.find_element_by_id('usersinfo').click()
        self.driver.find_element_by_id('log_out').click()
        time.sleep(8)

    @classmethod
    def tearDownClass(cls):
        cls.driver.close()
        cls.driver.quit()
        print(&quot;Test Completed&quot;)

</code></pre>
<p>I have built the above code for testing login to functionality using selenium with python unit testing .
But while executing the python code showing some errors as</p>
<p>AttributeError: 'LoginTestCase' object has no attribute 'driver'</p>
<p>Can anyone help me regarding this</p>
",https://stackoverflow.com/questions/66438937/getting-the-error-in-python-selenium-testing-for-login-and-logout-functionality,"['selenium', 'unit-testing', 'testing', 'performance-testing']",152,True,0,1
Angular Test case for image map resizer,"<p>I'm using the image-map-resizer <a href=""https://github.com/davidjbradshaw/image-map-resizer"" rel=""nofollow noreferrer"">plugin</a> for a responsive image mapping. And I need help in writing testcase for it.</p>
<p>This is my html : <br/>
<code>&lt;img src=&quot;....&quot; width=&quot;100%&quot;  usemap=&quot;#usaMap&quot; (load)=&quot;imageResized();&quot;&gt;</code></p>
<p>This is my TS file : <br/></p>
<pre><code>declare function imageMapResize(): void;

@Component({...

})
...
imageResized() {
  imageMapResize(); // Javascript function in imageMapResizer.min.js 
}

</code></pre>
<p>and this is my test file :</p>
<pre><code>it('should call imageMapResize() on imageResized method', () =&gt; {
   spyOn(component, 'imageMapResize').and.callThrough();
   component.imageResized();
   expect(component.imageMapResize).toHaveBeenCalled()
});
</code></pre>
<p>And this is the error that I'm getting on compilation :</p>
<pre><code>Argument of type '&quot;imageMapResize&quot;' is not assignable to parameter of type '&quot;ngOnInit&quot; | &quot;currentMap&quot; | &quot;mapDataObj&quot; | &quot;imageResized&quot;'.

 -- spyOn(component, 'imageMapResize').and.callThrough();
</code></pre>
<p>I know it's pretty simple, but I recently started unit testing <br/></p>
",https://stackoverflow.com/questions/69607702/angular-test-case-for-image-map-resizer,"['unit-testing', 'jasmine', 'automated-tests', 'image-resizing', 'angular-test']",392,False,0,1
Create file with Unit Test with Android in the emulator or android device folder,"<p>I am new to Unit Testing.</p>
<p>I was trying to create a folder using a Unit Test</p>
<pre><code>@Test
public void testGenerateFile() throws IOException {
    Context context = ApplicationProvider.getApplicationContext();

    File file = new File(context.getFilesDir(),&quot;myfile&quot;);
    file.createNewFile();
    byte[] data1={1,1,0,0};
    //write the bytes in file
    if(file.exists())
    {
        OutputStream fo = new FileOutputStream(file);
        fo.write(data1);
        fo.close();
        System.out.println(&quot;file created: &quot;+file);
    }
    assertTrue(true);
}
</code></pre>
<p>I also try to get the context from</p>
<pre><code>Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
</code></pre>
<p>But the file that was generated is in the folder</p>
<pre><code>file created: /var/folders/yh/mkknvc7n2qx2k4swl_mtj7lw0000gn/T/robolectric-Method_testGenerateFile9017115247567873084/org.robolectric.default-dataDir/files/myfile
</code></pre>
<p>This is a folder generated for robolectric instrumented test. How can I get the folder to the real emulator or android device?</p>
",https://stackoverflow.com/questions/68841810/create-file-with-unit-test-with-android-in-the-emulator-or-android-device-folder,"['android', 'unit-testing', 'junit']",487,True,0,1
ModuleNotFoundError but only when mocked,"<p>I have a package called <code>my_package</code> with a single module called <code>my_module</code>:</p>
<pre><code>$ tree my_package/
my_package/
├── __init__.py
├── my_module.py
├── my_module.py~
└── __pycache__
    ├── __init__.cpython-36.pyc
    └── my_module.cpython-36.pyc
</code></pre>
<p><code>my_module</code> has a function called <code>compute_something</code>:</p>
<pre><code>$ cat my_package/my_module.py
def compute_something():
    return 0
</code></pre>
<p>I'm trying to mock that function for unit testing purposes:</p>
<pre><code>$ cat mocks.py
import mock

from my_package import my_module

def unmocked():
    print(my_module.compute_something())

@mock.patch('my_module.compute_something')
def mocked(mock_compute_something):
    mock_compute_something.return_value = 1
    print(my_module.compute_something())

unmocked()
mocked()
$ python mocks.py
0
Traceback (most recent call last):
  File &quot;mocks.py&quot;, line 14, in &lt;module&gt;
    mocked()
  File &quot;/home/pcoccoli/.pyenv/versions/3.6.8/lib/python3.6/site-packages/mock/mock.py&quot;, line 1345, in patched
    keywargs) as (newargs, newkeywargs):
  File &quot;/home/pcoccoli/.pyenv/versions/3.6.8/lib/python3.6/contextlib.py&quot;, line 81, in __enter__
    return next(self.gen)
  File &quot;/home/pcoccoli/.pyenv/versions/3.6.8/lib/python3.6/site-packages/mock/mock.py&quot;, line 1325, in decoration_helper
    arg = exit_stack.enter_context(patching)
  File &quot;/home/pcoccoli/.pyenv/versions/3.6.8/lib/python3.6/contextlib.py&quot;, line 330, in enter_context
    result = _cm_type.__enter__(cm)
  File &quot;/home/pcoccoli/.pyenv/versions/3.6.8/lib/python3.6/site-packages/mock/mock.py&quot;, line 1398, in __enter__
    self.target = self.getter()
  File &quot;/home/pcoccoli/.pyenv/versions/3.6.8/lib/python3.6/site-packages/mock/mock.py&quot;, line 1573, in &lt;lambda&gt;
    getter = lambda: _importer(target)
  File &quot;/home/pcoccoli/.pyenv/versions/3.6.8/lib/python3.6/site-packages/mock/mock.py&quot;, line 1245, in _importer
    thing = __import__(import_path)
ModuleNotFoundError: No module named 'my_module'
</code></pre>
<p>As you can see, <code>my_module</code> exists and is found just fine (I call it form the <code>unmocked</code> function, and you can see its output), unless I try to <code>mock.patch</code> it.  I don't understand why this is so.</p>
",https://stackoverflow.com/questions/66752988/modulenotfounderror-but-only-when-mocked,"['python', 'unit-testing', 'mocking']",77,True,0,1
How to mock async method with jest in nodejs,"<p>I have below mentioned files</p>
<p>|_ utils.js
|_methods.js</p>
<p>I am doing unit testing for rest.js methods, file contents are</p>
<p><strong>methods.js</strong></p>
<pre><code>import Express from 'express'
import { add_rec } from './utils'

export const create_rec = () =&gt; async (req: Express.Request, res: Express.Response) =&gt; {
    const rec_body = req.body.rec

    return add_rec(rec_body)
        .then((ret) =&gt; res.status(201).send(ret))
        .catch((e) =&gt; {
            res.status(500).send({ message: e.message })
        })
}
</code></pre>
<p>How can mock the <strong>add_rec</strong> async function so that I can unit-test my <strong>create_rec</strong>
function</p>
<p>I am trying to test create_rec below way but it is not allowing me to mock add_rec method</p>
<pre><code>mport { getMockReq, getMockRes } from '@jest-mock/express'
import { add_rec } from './utils'
jest.mock('./utils')

describe('test create_rec method valid param', () =&gt; {
    it('test create_rec method', async () =&gt; {
        const req = getMockReq({
            body: {
                rec: {},
            },
        })
        const { res } = getMockRes&lt;any&gt;({
            status: jest.fn(),
            send: jest.fn(),
        })
        add_rec.mockResolved({}) // this line is giving error in fact it is not mocked i think
        await create_rec()(req, res)
        expect(res.status).toHaveBeenCalledTimes(1)
        expect(res.send).toHaveBeenCalledTimes(1)
    })
})
</code></pre>
<p>Please help me with this.</p>
",https://stackoverflow.com/questions/68419899/how-to-mock-async-method-with-jest-in-nodejs,"['node.js', 'typescript', 'express', 'unit-testing', 'jestjs']",1919,True,0,1
Visual Studio 2019 Live Unit Testing Crashes,"<p>I'm trying to use Live Unit Testing with my nUnit tests, but it crashes every time I start it.  It crashes whether I start it manually or on solution load.  I've restarted VS multiple times, reinstalled it, <a href=""https://stackoverflow.com/a/63955708/127888"">deleted the persisted data per this answer</a> and now I'm out of ideas.</p>
Output Window
<pre><code>[15:23:48.443 Info] Live Unit Testing started.
[15:23:48.471 Info] Building solution.
[15:23:52.493 Info] - BuildManager - Build performance issue: compiler called to produce 
 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\i\Wa531.SAR_Log\
   Debug\netstandard2.1\Wa531.SAR_Log.dll' 
again after build already succeeded.
[15:23:53.205 Info] Build completed with failures. Errors were logged under 
   'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\diag\'.
[15:23:58.971 Info] Started executing tests from 
   C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\t\Wa531.SAR_Log.Tests\
   Debug\netcoreapp3.1\Wa531.SAR_Log.Tests.dll. 
[15:24:00.741 Info] Finished executing tests. (Passed: 24, Failed: 0, Skipped: 0, Not Executed: 0)
[15:24:05.156 Error] Live Unit Testing is being turned off because a process that it depends on has
   either exited unexpectedly or encountered an unrecoverable exception. Restart Visual Studio before
   trying to start Live Unit Testing again.
[15:24:05.156 Error] Log files present in the '%Temp%\servicehub\logs' folder may contain information 
   that can help diagnose this problem.
[15:24:05.196 Info] Live Unit Testing stopped.
</code></pre>
%Temp%\servicehub\logs
<pre><code>01/02/2021 15:20:09 Pacific Standard Time: Warning : 14 :Aborting pending request &quot;2&quot; because 
   the connection was lost.
01/02/2021 15:20:09 Pacific Standard Time: Warning : 14 :Aborting pending request &quot;12&quot; because 
   the connection was lost.
</code></pre>
Build.log
<pre><code>[15:23:52.493 Info]
 - BuildManager - Build performance issue: compiler called to 
   produce 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\i\Wa531.SAR_Log\
   Debug\netstandard2.1\Wa531.SAR_Log.dll' again after build already succeeded.
[15:23:53.183 Verbose] 
- BuildManager - 
   C:\Users\willi\.nuget\packages\resizetizer.nt\0.2.0\buildTransitive\
   Resizetizer.NT.targets(155,3): error : One or more errors occurred.
[15:23:53.186 Verbose] 
- BuildManager - Some of the file paths defined in the 
   csproj under the Live Unit Testing build path are missing. Verify whether 
   these files should be present under the Live Unit Testing build path and if 
   necessary update the csproj definition to look these files up in a 
   different place.
[15:23:53.188 Verbose] 
- BuildManager - Item _OutputPathItem 
   'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\
   Wa531.SAR_Log.Android\bin\Debug\' evaluated via:
     _OutputPathItem: '$(OutDir)' @ C:\Program Files (x86)\Microsoft Visual 
       Studio\2019\Enterprise\MSBuild\Current\Bin\
       Microsoft.Common.CurrentVersion.targets:275
  OutDir: 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\
           Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\' 
           @ C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\
             Wa531.SAR_Log.Android.csproj:0
[15:23:53.188 Verbose] 
- BuildManager - Item AppConfigFileDestination 
    'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\
    Wa531.SAR_Log.Android\bin\Debug\Wa531.SAR_Log.Android.dll.config' 
    evaluated via:
     AppConfigFileDestination: '$(OutDir)$(TargetFileName).config' 
      @ C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild
\Current\Bin\Microsoft.Common.CurrentVersion.targets:306
  OutDir: 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\
     Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\' 
     @ C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\
       Wa531.SAR_Log.Android.csproj:0
  TargetFileName: '$(TargetName)$(TargetExt)' @ C:\Program Files (x86)\
    Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\
    Bin\Microsoft.Common.CurrentVersion.targets:213
  TargetName: '$(AssemblyName)' @ C:\Program Files (x86)\Microsoft Visual Studio\
    2019\Enterprise\MSBuild\Current\Bin\
    Microsoft.Common.CurrentVersion.targets:205
  AssemblyName: 'Wa531.SAR_Log.Android' @ 
      C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\
      Wa531.SAR_Log.Android.csproj:14
  TargetExt: '.dll' @ C:\Program Files (x86)\Microsoft Visual Studio\2019\
      Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets:184
[15:23:53.188 Verbose] 
- BuildManager - Item _DebugSymbolsOutputPath 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\Wa531.SAR_Log.Android.pdb' evaluated via:
_DebugSymbolsOutputPath: '@(_DebugSymbolsIntermediatePath-&gt;'$(OutDir)%(Filename)%(Extension)')' @ C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets:375
  OutDir: 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\' @ C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\Wa531.SAR_Log.Android.csproj:0
[15:23:53.188 Verbose] 
- BuildManager - Item _ApplicationManifestFinal 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\Native.Wa531.SAR_Log.Android.manifest' evaluated via:
_ApplicationManifestFinal: '$(OutDir)$(_DeploymentTargetApplicationManifestFileName)' @ C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets:413
  OutDir: 'C:\git\Wa531.SAR_Log\.vs\Wa531.SAR_Log\v16\lut\0\b\Wa531.SAR_Log\Wa531.SAR_Log.Android\bin\Debug\' @ C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\Wa531.SAR_Log.Android.csproj:0
  _DeploymentTargetApplicationManifestFileName: 'Native.$(AssemblyName).manifest' @ C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets:229
    AssemblyName: 'Wa531.SAR_Log.Android' @ C:\git\Wa531.SAR_Log\Wa531.SAR_Log\Wa531.SAR_Log.Android\Wa531.SAR_Log.Android.csproj:14
</code></pre>
VS Info
<pre><code>Microsoft Visual Studio Enterprise 2019
Version 16.8.3
VisualStudio.16.Release/16.8.3+30804.86
Microsoft .NET Framework
Version 4.8.03752

Installed Version: Enterprise

Visual C++ 2019   00435-60000-00000-AA025
Microsoft Visual C++ 2019

ADL Tools Service Provider   1.0
ASA Service Provider   1.0
ASP.NET and Web Tools 2019   16.8.554.20160
ASP.NET Core Razor Language Services   16.1.0.2052803+84e121f1403378489b842e1797df2f3f5a49ac3c
ASP.NET Web Frameworks and Tools 2019   16.8.554.20160
Azure App Service Tools v3.0.0   16.8.554.20160
Azure Data Lake Node   1.0
Azure Data Lake Tools for Visual Studio   2.6.3000.0
Azure Functions and Web Jobs Tools   16.8.554.20160
Azure Stream Analytics Tools for Visual Studio   2.6.3000.0
C# Tools   3.8.0-5.20604.10+9ed4b774d20940880de8df1ca8b07508aa01c8cd
Common Azure Tools   1.10
Extensibility Message Bus   1.2.6 (master@34d6af2)
Fabric.DiagnosticEvents   1.0
GitHub.VisualStudio   2.11.106.19330
IntelliCode Extension   1.0
Microsoft Azure HDInsight Azure Node   2.6.3000.0
Microsoft Azure Hive Query Language Service   2.6.3000.0
Microsoft Azure Service Fabric Tools for Visual Studio   16.0
Microsoft Azure Stream Analytics Language Service   2.6.3000.0
Microsoft Azure Stream Analytics Node   1.0
Microsoft Azure Tools   2.9
Microsoft Continuous Delivery Tools for Visual Studio   0.4
Microsoft JVM Debugger   1.0
Microsoft Library Manager   2.1.113+g422d40002e.RR
Microsoft MI-Based Debugger   1.0
Microsoft Visual C++ Wizards   1.0
Microsoft Visual Studio Tools for Containers   1.1
Microsoft Visual Studio VC Package   1.0
Mono Debugging for Visual Studio   16.8.43 (00471f8)
Node.js Tools   1.5.20902.1 Commit Hash:b474efcb6f92db52a8f8e2e6a8cb9648476885cc
NuGet Package Manager   5.8.0
ProjectServicesPackage Extension   1.0
Snapshot Debugging Extension   1.0
SQL Server Data Tools   16.0.62010.06180
ToolWindowHostedEditor   1.0
TypeScript Tools   16.0.21016.2001
Visual Basic Tools   3.8.0-5.20604.10+9ed4b774d20940880de8df1ca8b07508aa01c8cd
Visual F# Tools   16.8.0-beta.20507.4+da6be68280c89131cdba2045525b80890401defd
Visual Studio Code Debug Adapter Host Package   1.0
Visual Studio Container Tools Extensions   1.0
Visual Studio Tools for Containers   1.0
Visual Studio Tools for Kubernetes   1.0
Visual Studio Tools for Unity   4.8.2.0
VisualStudio.DeviceLog   1.0
VisualStudio.Foo   1.0
VisualStudio.Mac   1.0
Xamarin   16.8.000.260 (d16-8@fd405a2)
Xamarin Designer   16.8.0.507 (remotes/origin/d16-8@e87b24884)
Xamarin Templates   16.8.112 (86385a3)
Xamarin.Android SDK   11.1.0.17 (d16-8/c0e2b8e)
Xamarin.Android Reference Assemblies and MSBuild support.
    Mono: be2226b
    Java.Interop: xamarin/java.interop/d16-8@79d9533
    ProGuard: Guardsquare/proguard/proguard6.2.2@ebe9000
    SQLite: xamarin/sqlite/3.32.1@1a3276b
    Xamarin.Android Tools: xamarin/xamarin-android-tools/d16-8@2fb1cbc
Xamarin.iOS and Xamarin.Mac SDK   14.6.0.15 (87a1b18d8)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.
</code></pre>
",https://stackoverflow.com/questions/65545295/visual-studio-2019-live-unit-testing-crashes,"['visual-studio', 'unit-testing', 'visual-studio-2019', 'live-unit-tests']",980,True,0,1
Simple click handler to call method: SPEC HAS NO EXPECTATIONS,"<p>Angular application running Jasmine on Karma for unit testing. I have provided a test to see if the method was called on the click event.</p>
<p><strong>Result: SPEC HAS NO EXPECTATIONS should call method on view item click</strong></p>
<p>Why isn't my expectation that the spy(method) has been called?</p>
<p><strong>HTML</strong></p>
<pre><code>&lt;h3 class=&quot;general-log-heading&quot;&gt;
    &lt;a class=&quot;btn btn-link onViewItemClick&quot; (click)=&quot;onViewItem(searchResultItem)&quot;&gt;test&lt;/a&gt;
&lt;/h3&gt;
</code></pre>
<p><strong>.TS</strong></p>
<pre><code>public onViewItem(item: Results): void {
  //method logic here
}
</code></pre>
<p><strong>.spec(test)</strong></p>
<pre><code>import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { SearchResultItemComponent } from './search-result-item.component';

let component: SearchResultItemComponent;
let fixture: ComponentFixture&lt;SearchResultItemComponent&gt;;

fdescribe('SearchResultItemComponent', () =&gt; {


    beforeEach(() =&gt; {
        
        TestBed.configureTestingModule({
            declarations: [],
            imports: [RouterTestingModule, HttpClientTestingModule],
            providers: []
        }).compileComponents();
        fixture = TestBed.createComponent(SearchResultItemComponent);
        component = fixture.componentInstance;
    });



    it('should call method on view item click', () =&gt; {
    fixture.detectChanges();
    const button = fixture.debugElement.query(By.css('.onViewItemClick'));
    const spy = spyOn(component, 'onViewItem');

    button.triggerEventHandler('click', null);
    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; {
        expect(spy).toHaveBeenCalled();
    });
    
});
})
</code></pre>
<p><strong>UPDATE to .spec</strong> also tried</p>
<pre><code>it('should should trigger a method on view item click', () =&gt; {
    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; {
      let comp = fixture.componentInstance;
      const spy = spyOn(comp, 'onViewItem');
  
      let el = fixture.debugElement.query(By.css('.onViewItemClick')).nativeElement.click();
      fixture.detectChanges();
      expect(spy).toHaveBeenCalled();
    });
  });


it('should should trigger a method on view item click', () =&gt; {
    fixture.detectChanges();

      let comp = fixture.componentInstance;
      const spy = spyOn(comp, 'onViewItem');
  
      let el = fixture.debugElement.query(By.css('.onViewItemClick')).nativeElement.click();
      fixture.detectChanges();
      expect(spy).toHaveBeenCalled();

  });
</code></pre>
",https://stackoverflow.com/questions/68267093/simple-click-handler-to-call-method-spec-has-no-expectations,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",102,True,0,1
Not able to write unit test cases in angular using jasmine karma for this function,"<p>I am very new to unit testing . my project is on angular 12 . i am not able to write unit test cases for this complex function. please help out.</p>
<p>...</p>
<pre><code>   private saveConversionRecords(cookieValue: string, userId: string)
   { 
    let cookies = JSON.parse(cookieValue);
    let cookie: Conversion = new Conversion();
    cookie = cookies[cookies.length - 1];

     if(userId)
     {    
     cookie.lpVersion = 3;
     this.userService.saveConversion(userId, cookie).subscribe(data =&gt; 
     {});
     this.cookieService.delete('conv');
     }
   }




export class Conversion{
userId: string
source: string
category: string
keyword: string
landingPage: string
matchType: string
placement: string
target: string
adPosition: string
ad: string
lpVersion: number
conversionDate: Date
}



     public saveConversion(userId: string, conversion: Conversion): 
     Observable&lt;number&gt;{
     return this.http.post&lt;number&gt;(environment.baseUrl + 'auth/' + 
     'SaveConversion?userId=' + userId, conversion);
     }



      delete(name: string, path?: string, domain?: string): void;



      fdescribe('LoginFormComponent', () =&gt; {
          let component: LoginFormComponent;
          let fixture: ComponentFixture&lt;LoginFormComponent&gt;;

           beforeEach(async(() =&gt; {
           TestBed.configureTestingModule({
           imports: [ReactiveFormsModule, FormsModule,],
           declarations: [ LoginFormComponent ],
           providers: 
           [AuthService,UserService,LoaderService,CookieService]
           })
           .compileComponents();
           }));

            beforeEach(() =&gt; {
            fixture = TestBed.createComponent(LoginFormComponent);
            component = fixture.componentInstance;
            fixture.detectChanges();
            });
</code></pre>
<p>...</p>
<p>Please help out ,  i am stuck at this middle of project .  just give me overview  or idea , how to write the unit test cases for this function.</p>
",https://stackoverflow.com/questions/69101580/not-able-to-write-unit-test-cases-in-angular-using-jasmine-karma-for-this-functi,"['angular', 'unit-testing']",95,False,0,0
How to setup a temporary git-repo for testing?,"<p>Hi i want to test this function below with unit-testing:</p>
<pre><code>public String cloneRepo(String sshURL){
  System.out.println(&quot;Cloning repository &quot;+ sshURL);
  String cloneStatus;

  try {
    Runtime.getRuntime().exec(&quot;git clone &quot; + sshURL + &quot; ./cloned-repo&quot;);
    cloneStatus = &quot;Cloning OK&quot;;
  } catch (IOException e) {
    System.out.print(&quot;Could not clone repo.&quot;);
    cloneStatus = &quot;Cloning Failed&quot;;
  }

  return cloneStatus;
}
</code></pre>
<p>And i want to create a temporary git-repo to test is it possible.
Because if you run a the tests again the tests are going to fail!
Because of the cloned repository already exists is it possible to create
a temporary Git-repo under run-time?</p>
",https://stackoverflow.com/questions/66188875/how-to-setup-a-temporary-git-repo-for-testing,"['java', 'git']",338,False,0,0
How to access private service which is provided by the component itself for unit testing,"<p>I have this component which provides a service by itself</p>
<pre><code>@Component({
    selector: 'my-component',
    providers: [MyService],
    ...
})
export class MyComponent { 
  constructor(@Self() private service: MyService) {}
  ...
}
</code></pre>
<p>During unit testing I noticed the following</p>
<pre><code>beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        declarations: [MyComponent],
        providers: [MyService],
    }).compileComponents();
    service = TestBed.inject(MyService);
});
</code></pre>
<p>That <code>service</code> is not the same instance as the service inside my component. I guess this makes sense, but I cannot find a solution for this, because for my tests I need access to that service inside my component. Any suggestions?</p>
",https://stackoverflow.com/questions/67502690/how-to-access-private-service-which-is-provided-by-the-component-itself-for-unit,"['angular', 'unit-testing', 'dependency-injection']",202,True,0,2
How do we unit test spring integration xml configuration?,"<p>I am new to spring integration and currently stuck on unit testing my integration flow. My flow looks something like this.</p>
<ol>
<li>Recieve some data from TCP channel adapter in XML format.</li>
<li>Convert it to JSON.</li>
<li>Send JSON message to amazon sqs queue.</li>
</ol>
<p>and XML file is :</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;beans xmlns=&quot;http://www.springframework.org/schema/beans&quot;
   xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
   xmlns:int=&quot;http://www.springframework.org/schema/integration&quot;
   xmlns:int-ip=&quot;http://www.springframework.org/schema/integration/ip&quot;
   xmlns:int-aws=&quot;http://www.springframework.org/schema/integration/aws&quot;
   xmlns:aws-messaging=&quot;http://www.springframework.org/schema/cloud/aws/messaging&quot;
   xsi:schemaLocation=&quot;http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans.xsd
   http://www.springframework.org/schema/integration
   http://www.springframework.org/schema/integration/spring-integration.xsd
   http://www.springframework.org/schema/integration/ip
   http://www.springframework.org/schema/integration/ip/spring-integration-ip.xsd
   http://www.springframework.org/schema/integration/aws
   http://www.springframework.org/schema/integration/aws/spring-integration-aws.xsd
   http://www.springframework.org/schema/cloud/aws/messaging 
   https://www.springframework.org/schema/cloud/aws/messaging/spring-cloud-aws-messaging.xsd&quot;&gt;

&lt;!-- --&gt;
&lt;!-- receive callbacks --&gt;
&lt;!-- --&gt;
&lt;int-ip:tcp-connection-factory
        id=&quot;inboundServerTCPFactory1&quot;
        deserializer=&quot;customSerializerDeserializer&quot;
        serializer=&quot;customSerializerDeserializer&quot;
        type=&quot;server&quot;
        port=&quot;8085&quot;
        using-nio=&quot;true&quot;
        single-use=&quot;true&quot;/&gt;

&lt;!-- --&gt;
&lt;!-- receive callbacks --&gt;
&lt;!-- --&gt;
&lt;int-ip:tcp-connection-factory
        id=&quot;inboundServerTCPFactory2&quot;
        deserializer=&quot;customSerializerDeserializer&quot;
        serializer=&quot;customSerializerDeserializer&quot;
        type=&quot;server&quot;
        port=&quot;8086&quot;
        using-nio=&quot;true&quot;
        single-use=&quot;true&quot;/&gt;

&lt;!-- --&gt;
&lt;!-- Inbound channel adapter --&gt;
&lt;!-- --&gt;
&lt;int-ip:tcp-inbound-channel-adapter id=&quot;inboundChannelAdapter1&quot;
                                    channel=&quot;inboundReceivingChannel&quot;
                                    connection-factory=&quot;inboundServerTCPFactory1&quot;/&gt;

&lt;int-ip:tcp-inbound-channel-adapter id=&quot;inboundChannelAdapter2&quot;
                                    channel=&quot;inboundReceivingChannel&quot;
                                    connection-factory=&quot;inboundServerTCPFactory2&quot;/&gt;

&lt;!-- --&gt;
&lt;!-- Inbound channel adapter --&gt;
&lt;!-- --&gt;
&lt;int:channel id=&quot;inboundReceivingChannel&quot;&gt;
    &lt;int:interceptors&gt;
        &lt;int:wire-tap channel=&quot;logger&quot;/&gt;
    &lt;/int:interceptors&gt;
&lt;/int:channel&gt;


&lt;!--Transfrom XML message to Json--&gt;
&lt;int:transformer ref=&quot;xmlToJsonTransformer&quot; input-channel=&quot;inboundReceivingChannel&quot;
                 method=&quot;transform&quot; output-channel=&quot;outChannel&quot;/&gt;

&lt;int:channel id=&quot;outChannel&quot; /&gt;

&lt;!--&lt;aws-messaging:sqs-async-client id=&quot;amazonSqs&quot;/&gt;--&gt;

&lt;int-aws:sqs-outbound-channel-adapter id= &quot;out&quot;
                                      sqs=&quot;sqs&quot;
                                      channel=&quot;outChannel&quot;
                                      queue=&quot;SendQueue&quot;/&gt;
&lt;/beans&gt;
</code></pre>
<p>How do I mock every component and unit test the complete flow?</p>
",https://stackoverflow.com/questions/69159042/how-do-we-unit-test-spring-integration-xml-configuration,"['spring-integration', 'spring-integration-aws']",184,True,0,1
Firebase Storage error in Firebase Cloud Function,"<p>I use <code>const bucket = admin.storage().bucket();</code> in the cloud function, and at the very top, I have:</p>
<pre><code>const functions = require('firebase-functions')
const admin = require(&quot;firebase-admin&quot;);
admin.initializeApp();
</code></pre>
<p>When I try to deploy, it gives me an error:</p>
<blockquote>
<p>i  functions: Loaded environment variables from. Error: Missing bucket name. If you are unit testing, please provide a bucket name through functions.storage.bucket(bucketName), or set process.env.FIREBASE_CONFIG.`</p>
</blockquote>
<p>This only started happening after I updated, I believe. Thank you for your help.</p>
",https://stackoverflow.com/questions/68761554/firebase-storage-error-in-firebase-cloud-function,"['firebase', 'google-cloud-functions', 'firebase-storage']",419,True,3,2
Mocking output of generator called inside a function in Python,"<p>We are unit testing an Orchestrator in Azure durable function in Python where we want to  assert that records created by <code>context.call_activity(&quot;GetRecords&quot;, reader_activity_input)</code> are passed to <code>context.call_activity(&quot;ProcessRecords&quot;, records</code>) in the following function but in-spite of mocking a return_value in the test ,it returns a None instead of the value setup by <code>mocked_context.call_activity.return_value = iter(records)</code></p>
<p>Function:</p>
<pre><code> def orchestrator_function(context: df.DurableOrchestrationContext):
        .....
        records = yield context.call_activity(&quot;GetRecords&quot;, reader_activity_input)
        response = yield context.call_activity(&quot;ProcessRecords&quot;, records)
        return response
</code></pre>
<p>Test:</p>
<pre><code>  def test_Orchestrator_function_calls_Process(mocker):
        mocked_context = mocker.MagicMock()
        records = [1,2,3]
        mocked_context.call_activity.return_value = iter(records)
        list(generator)
        mocked_context.call_activity.assert_has_calls([mocker.call(&quot;ProcessRecords&quot;, records)]) 
</code></pre>
<p>The above assert fails because value of <code>records</code> is None</p>
",https://stackoverflow.com/questions/68061471/mocking-output-of-generator-called-inside-a-function-in-python,"['python', 'mocking', 'python-mock', 'azure-durable-functions']",208,False,0,0
Flask - unittest raising assertionError,"<p>I'm reading a book called Flask Web Development. Im currently at unit testing. When I run my simple test it raises an AssertionError. I know it will be something easy, but I just can't figure it out myself. I just dont understand what is going on wrong there.</p>
<pre><code>test_app_exists (test_basics.BasicsTestCase) ... ok
test_app_is_testing (test_basics.BasicsTestCase) ... FAIL

======================================================================
FAIL: test_app_is_testing (test_basics.BasicsTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File &quot;C:\Users\danie\PycharmProjects\flaskWebDevelopment\tests\test_basics.py&quot;, line 22, in test_app_is_testing
    self.assertTrue(current_app.config['TESTING'])
AssertionError: False is not true

----------------------------------------------------------------------
Ran 2 tests in 0.018s

FAILED (failures=1)
</code></pre>
<p>My test</p>
<pre><code>import unittest
from flask import current_app
from app import create_app, db

class BasicsTestCase(unittest.TestCase):
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()
        self.app_context.pop()

    def test_app_exists(self):
        self.assertFalse(current_app is None)

    def test_app_is_testing(self):
        self.assertTrue(current_app.config['TESTING'])
</code></pre>
<p>and config.py</p>
<pre><code>    import os
    basedir = os.path.abspath(os.path.dirname(__file__))
    
    class Config:
...
        @staticmethod
        def init_app(app):
            pass
    
    class DevelopmentConfig(Config):
        DEBUG = True
        SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data-dev.sqlite')
    
    class TestingConfig(Config):
        DEBUG = True
        SQLALCHEMY_DATABASE_URI = 'sqlite://' # only store info in temp memory
    
    class ProductionConfig(Config):
        SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
    
    config = {
        'development': DevelopmentConfig,
        'testing': TestingConfig,
        'production': ProductionConfig,
        'default': DevelopmentConfig
    }
</code></pre>
<p>unit test launcher command:</p>
<pre><code>@app.cli.command()
def test():
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
</code></pre>
",https://stackoverflow.com/questions/65816615/flask-unittest-raising-assertionerror,"['python', 'flask', 'python-unittest']",108,False,0,0
Visual Studio 2019 unit tests missing in test explorer but show in live unit testing,"<p>I have a solution with about 3000 unit tests.  The test appear and run under the &quot;Live Unit Testing&quot; window but under the &quot;Test Explorer&quot; none appear.   They USED to but suddenly no longer appear in that window.   This is Visual Studio 2019 16.9.1</p>
<p>How can I get them to appear and run in the test explorer window?</p>
",https://stackoverflow.com/questions/66554913/visual-studio-2019-unit-tests-missing-in-test-explorer-but-show-in-live-unit-tes,"['unit-testing', 'visual-studio-2019', 'test-explorer', 'live-unit-tests']",478,False,0,1
Spring Boot: How to test a class which is using gson object using autowiring,"<p>I am new to JUnit and unit testing in java. I am having an issue while testing my code. Any help is appreciated.</p>
<p>My java class: <code>AService.java</code></p>
<pre><code>@Service
public class AService {

    @Autowired
    private ServiceB serviceB;

    @Autowired
    private Gson gson;

    public MyEntity getEntity() {
        String jsonResponse = serviceB.getResponse();
        return gson.fromJson(jsonResponse, MyEntity.class);
    }
}
</code></pre>
<p>My test class: <code>AServiceTest.java</code></p>
<pre><code>@ExtendWith(MockitoExtension.class)
public class AServiceTest {

    @Mock
    private ServiceB serviceB;

    @Autowired
    private Gson gson;

    @InjectMocks
    private AService aService;

    @Test
    public void getEntityTest() {
        String serviceBResponse = &quot;{\&quot;id\&quot;:55,\&quot;name\&quot;:\&quot;My entity\&quot;,\&quot;address\&quot;:\&quot;XYZ\&quot;}&quot;;
        when(serviceB.getResponse()).thenReturn(serviceBResponse);

        MyEntity entity = aService.getEntity();
        assertEquals(&quot;My entity&quot;, entity.getName());
    }
}
</code></pre>
<p>This is giving NullPointerException because <code>gson</code> object is not getting initialized. Also we can not mock <code>gson</code> as <code>Gson</code> class is <code>final</code>.</p>
<p>How can I test this code. I am using <strong>spring boot</strong> and <strong>junit5.</strong></p>
",https://stackoverflow.com/questions/66973273/spring-boot-how-to-test-a-class-which-is-using-gson-object-using-autowiring,"['java', 'spring-boot', 'mockito', 'gson', 'junit5']",5047,True,3,2
WrapperTestResponse&#39; object has no attribute &#39;text&#39;,"<ol>
<li>Currently I'm writing a unite testing for my flask project. I wrote a function to test the login feature. When I run the unit test, it showed some error message.</li>
</ol>
<p><strong>FAILED unit_test.py::TestClass::test_login - AttributeError: 'WrapperTestResponse' object has no attribute 'text'</strong></p>
<p>2.Here is my code for the unit testing implementation, I can get the status code successfully but not the text. Did I make some mistakes?</p>
<pre><code>import unittest
from app import app
import requests
from flask import request
import json



class TestClass(unittest.TestCase):
    def setup_class(self):
        app.config['TESTING'] = True  
        self.app = app.test_client()

    def teardown_class(self):
        &quot;&quot;&quot;Do the testing &quot;&quot;&quot;
        pass

    def test_login(self):
        response = self.app.get('/login')
        print(response)
        data = {'username': '123456@qq.com', 'password': '12345678'}
        response = app.test_client().post('/login', data=json.dumps(data))
        self.assertEqual(response.status_code, 200)
        print('--------------')
        self.assertEqual(response.text, &quot;Invalid login credentials&quot;)
</code></pre>
",https://stackoverflow.com/questions/67655736/wrappertestresponse-object-has-no-attribute-text,"['unit-testing', 'http', 'flask', 'flask-testing']",5945,True,6,1
Mock context manager inside a class,"<p>I have the below context manager inside a class method, which I would like to mock for unit testing.</p>
<pre><code>def load_yaml_config(self) -&gt; dict:
    &quot;&quot;&quot;
    Load the config based on the arguments provided.

    Returns: dict
        dictionary which will be used for configuring the logger, handlers, etc.
    &quot;&quot;&quot;

    with open(self.yaml_path, 'r') as config_yaml:
        return yaml.safe_load(config_yaml.read())
</code></pre>
<p>How could I achieve it?</p>
<p>EDIT:</p>
<p>As @chepner suggested (I can't accept his/her answer since it was via comment), the best way to go seems to be by using the unittest's mock_open functionality.</p>
<p>This way, I can simply go:</p>
<pre><code>import unittest.mock as um

with um.patch('builtins.open', um.mock_open(read_data=YAML_TEST)):
    h = MyClass.load_yaml_config()
</code></pre>
",https://stackoverflow.com/questions/70424848/mock-context-manager-inside-a-class,"['python', 'unit-testing', 'mocking', 'contextmanager']",811,True,0,2
Mock is not returning setup value,"<p>I've below method which I'm unit testing using Xunit and Moq.</p>
<pre><code>public class PersonService : IPersonService
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IMapper _mapper;

    public PersonService(IUnitOfWork unitOfWork, IMapper mapper)
    {
        _unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
        _mapper = mapper;
    }

    public async Task&lt;int&gt; PostPersonAsync(PersonModel person)
    {
        int result = 0;

        using (_unitOfWork.Connection)
        {
            try
            {
                _unitOfWork.OpenConnection();

                _unitOfWork.Begin();

                var PersonDto = _mapper.Map&lt;PersonDto&gt;(person);

                result = await _unitOfWork.PersonRepository.PostPersonAsync(PersonDto, _unitOfWork.Transaction);

                _unitOfWork.Commit();

                _unitOfWork.CloseConnection();
            }
            catch (Exception ex)
            {
                _unitOfWork.Rollback();
                throw;
            }
        }
        return result;
    }

}
</code></pre>
<p>Below is my Xunit method:</p>
<pre><code>[Fact]
public void PostPersonAsync_Should_SavePerson()
{
    //Arrange
    var _IDbTransaction = new Mock&lt;IDbTransaction&gt;();
    var _unitOfWorkMock1 = new Mock&lt;IUnitOfWork&gt;();
  
    
    var PersonDto = _mapper.Map&lt;PersonDto&gt;(PersonServiceData.PersonModel);
    int numberofAffectedRows = 5;
    _unitOfWorkMock1.Setup(s =&gt; s.OpenConnection());
    _unitOfWorkMock1.Setup(s =&gt; s.PersonRepository.PostPersonAsync(PersonDto, _IDbTransaction.Object)).ReturnsAsync(()=&gt;numberofAffectedRows);
    _unitOfWorkMock1.Setup(s =&gt; s.CloseConnection());
    
    _target = new PersonService(_unitOfWorkMock1.Object, _mapper);

    //Act
    var result = _target.PostPersonAsync(PersonServiceData.PersonModel).Result;

    //Assert
    Assert.Equal(5, result);
}
</code></pre>
<p>I'm not sure why it still returns zero, and my test case fails.</p>
<p>I've also tried with the below, but still, my test case fails.</p>
<pre><code>_unitOfWorkMock1.Setup(s =&gt; s.PersonRepository.PostPersonAsync(PersonDto, _IDbTransaction.Object)).ReturnsAsync(()=&gt;numberofAffectedRows);
</code></pre>
<p>Even after setting up the return value for the repository method call, it is returning zero.</p>
",https://stackoverflow.com/questions/68228035/mock-is-not-returning-setup-value,"['asp.net-core', 'moq', 'repository-pattern', 'unit-of-work', 'xunit.net']",348,True,0,1
Error While Configure Jest With anglular 6,"<p>I create the angualr Project with following Configuration and Try use jest the install</p>
<p>package.json file is follwing:</p>
<pre><code>{
    &quot;name&quot;: &quot;angular-assessment&quot;,
    &quot;version&quot;: &quot;0.0.0&quot;,
    &quot;scripts&quot;: {
        &quot;ng&quot;: &quot;ng&quot;,
        &quot;start&quot;: &quot;ng serve&quot;,
        &quot;build&quot;: &quot;ng build&quot;,
        &quot;test&quot;: &quot;jest&quot;,
        &quot;lint&quot;: &quot;ng lint&quot;,
        &quot;e2e&quot;: &quot;ng e2e&quot;
    },
    &quot;private&quot;: true,
    &quot;dependencies&quot;: {
        &quot;3d-force-graph&quot;: &quot;^1.56.5&quot;,
        &quot;@angular/animations&quot;: &quot;^6.1.0&quot;,
        &quot;@angular/cdk&quot;: &quot;^6.1.0&quot;,
        &quot;@angular/common&quot;: &quot;^6.1.0&quot;,
        &quot;@angular/compiler&quot;: &quot;^6.1.0&quot;,
        &quot;@angular/core&quot;: &quot;^6.1.0&quot;,
        &quot;@angular/forms&quot;: &quot;^6.1.0&quot;,
        &quot;@angular/http&quot;: &quot;^6.1.0&quot;,
        &quot;@angular/platform-browser&quot;: &quot;^6.1.0&quot;,
        &quot;@angular/platform-browser-dynamic&quot;: &quot;^6.1.0&quot;,
        &quot;@angular/router&quot;: &quot;^6.1.0&quot;,
        &quot;@ckeditor/ckeditor5-angular&quot;: &quot;^1.1.0&quot;,
        &quot;@ckeditor/ckeditor5-build-classic&quot;: &quot;^12.4.0&quot;,
        &quot;@gustafguner/angular-tooltip&quot;: &quot;^1.0.0&quot;,
        &quot;@ng-bootstrap/ng-bootstrap&quot;: &quot;^4.1.3&quot;,
        &quot;circular-json&quot;: &quot;^0.5.9&quot;,
        &quot;core-js&quot;: &quot;^2.5.4&quot;,
        &quot;event-stream&quot;: &quot;^4.0.1&quot;,
        &quot;gojs&quot;: &quot;^2.1.12&quot;,
        &quot;gulp-cli&quot;: &quot;^2.2.0&quot;,
        &quot;gulp-replace&quot;: &quot;^1.0.0&quot;,
        &quot;gulp-util&quot;: &quot;^3.0.8&quot;,
        &quot;microsoft-adal-angular6&quot;: &quot;^1.3.0&quot;,
        &quot;ngx-color&quot;: &quot;^4.0.0&quot;,
        &quot;ngx-color-picker&quot;: &quot;^7.5.0&quot;,
        &quot;ngx-contextmenu&quot;: &quot;^5.2.0&quot;,
        &quot;ngx-draggable-widget&quot;: &quot;^1.0.7&quot;,
        &quot;ngx-image-zoom&quot;: &quot;^0.3.4&quot;,
        &quot;ngx-order-pipe&quot;: &quot;^2.0.2&quot;,
        &quot;ngx-toggle-switch&quot;: &quot;^2.0.5&quot;,
        &quot;ngx-ui-loader&quot;: &quot;^7.2.2&quot;,
        &quot;rxjs&quot;: &quot;~6.2.0&quot;,
        &quot;sp-pnp-js&quot;: &quot;^3.0.10&quot;,
        &quot;zone.js&quot;: &quot;~0.8.26&quot;
    },
    &quot;devDependencies&quot;: {
        &quot;@angular-devkit/build-angular&quot;: &quot;~0.8.0&quot;,
        &quot;@angular/cli&quot;: &quot;~6.2.5&quot;,
        &quot;@angular/compiler-cli&quot;: &quot;^6.1.0&quot;,
        &quot;@angular/language-service&quot;: &quot;^6.1.0&quot;,
        &quot;@types/jasmine&quot;: &quot;~2.8.8&quot;,
        &quot;@types/jasminewd2&quot;: &quot;~2.0.3&quot;,
        &quot;@types/jest&quot;: &quot;^26.0.23&quot;,
        &quot;@types/node&quot;: &quot;~8.9.4&quot;,
        &quot;codelyzer&quot;: &quot;~4.3.0&quot;,
        &quot;gulp&quot;: &quot;^4.0.2&quot;,
        &quot;gulp-spsave&quot;: &quot;^3.1.1&quot;,
        &quot;husky&quot;: &quot;^4.2.5&quot;,
        &quot;jasmine-core&quot;: &quot;~2.99.1&quot;,
        &quot;jasmine-spec-reporter&quot;: &quot;~4.2.1&quot;,
        &quot;jest&quot;: &quot;^27.0.4&quot;,
        &quot;jest-preset-angular&quot;: &quot;^9.0.4&quot;,
        &quot;karma&quot;: &quot;~3.0.0&quot;,
        &quot;karma-chrome-launcher&quot;: &quot;~2.2.0&quot;,
        &quot;karma-coverage-istanbul-reporter&quot;: &quot;~2.0.1&quot;,
        &quot;karma-jasmine&quot;: &quot;~1.1.2&quot;,
        &quot;karma-jasmine-html-reporter&quot;: &quot;^0.2.2&quot;,
        &quot;lint-staged&quot;: &quot;^10.2.11&quot;,
        &quot;prettier&quot;: &quot;2.0.5&quot;,
        &quot;protractor&quot;: &quot;~5.4.0&quot;,
        &quot;ts-node&quot;: &quot;~7.0.0&quot;,
        &quot;tslint&quot;: &quot;~5.11.0&quot;,
        &quot;typescript&quot;: &quot;~2.9.2&quot;
    },
    &quot;jest&quot;: {
        &quot;preset&quot;: &quot;jest-preset-angular&quot;,
        &quot;setupTestFrameworkScriptFile&quot;: &quot;&lt;rootDir&gt;/setupJest.ts&quot;
      }
}
</code></pre>
<p>setupJest.ts File Contain following code:</p>
<pre><code>import 'jest-preset-angular';
</code></pre>
<p>geeting this error while npm test</p>
<pre><code>Error: Cannot find module '@angular/compiler-cli/src/ngtsc/reflection'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
    at Function.Module._load (internal/modules/cjs/loader.js:562:25)
    at Module.require (internal/modules/cjs/loader.js:692:17)
    at require (internal/modules/cjs/helpers.js:25:18)
</code></pre>
<p>I follow this Links:</p>
<p>1]<a href=""https://timdeschryver.dev/blog/integrate-jest-into-an-angular-application-and-library"" rel=""nofollow noreferrer"">https://timdeschryver.dev/blog/integrate-jest-into-an-angular-application-and-library</a>
2]<a href=""https://www.amadousall.com/how-to-set-up-angular-unit-testing-with-jest/"" rel=""nofollow noreferrer"">https://www.amadousall.com/how-to-set-up-angular-unit-testing-with-jest/</a></p>
",https://stackoverflow.com/questions/68035875/error-while-configure-jest-with-anglular-6,"['jestjs', 'angular6', 'ts-jest']",89,False,0,1
Ceedling uses wrong startup file,"<p>I am unit-testing STM32 code with Ceedling. My issue is that Ceedling uses crt0.S as startup file, but I need it to use .S instead (otherwise it keeps failing).
Can it be specified somewhere in project.yml?</p>
<p>Here is my compiler setup:</p>
<pre><code>:tools:
  :test_compiler:
    :executable: arm-none-eabi-gcc
    :arguments:
      - &quot;${1}&quot;
      - '-c'
      - '-g'
      - '-mthumb' 
      - '-mcpu=cortex-m4' 
      - '-mfloat-abi=hard' 
      - '-mfpu=fpv5-sp-d16' 
      - '-mthumb' 
      - '-mabi=aapcs'
      - '-ffunction-sections'
      - '-ffreestanding' 
      - '-fdata-sections'
      - '-Wall'
      - '-Wno-address'
      #- '-std=c99'
      #- '-pedantic'
      - -I&quot;$&quot;: COLLECTION_PATHS_TEST_TOOLCHAIN_INCLUDE               #expands to -I search paths
      - -I&quot;$&quot;: COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR   #expands to -I search paths
      - -D$: COLLECTION_DEFINES_TEST_AND_VENDOR  #expands to all -D defined symbols
      - -I&quot;$&quot;: COLLECTION_PATHS_SOURCE_INCLUDE_VENDOR
      - '-DTEST'
      - '-DUNITY_EXCLUDE_STDINT_H'
      - '-DUNITY_EXCLUDE_LIMITS_H'
      - '-DUNITY_EXCLUDE_SIZEOF'
      - '-DUNITY_INCLUDE_DOUBLE'
      - '-DUNITY_SUPPORT_TEST_CASES'
      - '-DUNITY_INT_WIDTH=32'
      - '-DUNITY_LONG_WIDTH=32'
  :test_linker:
    :executable: arm-none-eabi-gcc
    :arguments:
      - '-lm'
      - '-mcpu=cortex-m4'
      - '-mthumb'
      - '-specs=nosys.specs'
      - '-T STM32F412VGTx_FLASH.ld'
      - '-ffreestanding'
</code></pre>
<p>Here is the error message:</p>
<pre><code>/usr/lib/gcc/arm-none-eabi/9.2.1/../../../arm-none-eabi/bin/ld: warning: cannot find entry symbol Reset_Handler; defaulting to 0000000008000000
/usr/lib/gcc/arm-none-eabi/9.2.1/../../../arm-none-eabi/bin/ld: /usr/lib/gcc/arm-none-eabi/9.2.1/../../../arm-none-eabi/lib/thumb/v7e-m/nofp/crt0.o: in function `_mainCRTStartup':
/build/newlib-CVVEyx/newlib-3.3.0/build/arm-none-eabi/thumb/v7e-m/nofp/libgloss/arm/semihv2m/../../../../../../../../libgloss/arm/crt0.S:545: undefined reference to `main'
collect2: error: ld returned 1 exit status
ERROR: Shell command failed.

&gt; Shell executed command:
'arm-none-eabi-gcc -lm -mcpu=cortex-m4 -mthumb -specs=nosys.specs -T STM32F412VGTx_FLASH.ld'
&gt; And exited with status: [1].
</code></pre>
<p>And my CMake config:</p>
<pre><code>set(OBJECT_GEN_FLAGS &quot;-ffunction-sections -fdata-sections&quot;)

set(CMAKE_C_FLAGS   &quot;${OBJECT_GEN_FLAGS}&quot; CACHE INTERNAL &quot;C Compiler options&quot;)
set(CMAKE_CXX_FLAGS &quot;${OBJECT_GEN_FLAGS}&quot; CACHE INTERNAL &quot;C++ Compiler options&quot;)
set(CMAKE_ASM_FLAGS &quot;${OBJECT_GEN_FLAGS}&quot; CACHE INTERNAL &quot;ASM Compiler options&quot;)

# -Wl,--gc-sections     Perform the dead code elimination.
# --specs=nano.specs    Link with newlib-nano.
# --specs=nosys.specs   No syscalls, provide empty implementations for the POSIX system calls.
set(CMAKE_EXE_LINKER_FLAGS &quot;-Wl,--gc-sections -ffunction-sections -fdata-sections -Wl,-Map=${CMAKE_PROJECT_NAME}.map&quot; CACHE INTERNAL &quot;Linker options&quot;)
</code></pre>
<pre><code># source files
set(SOURCES

    src/main.c
    src/ledblink.c
    src/sum2nums.c 
    Drivers/system_stm32f4xx.c

    inc/ledblink.h
    inc/sum2nums.h

    Drivers/stm32f4xx.h
    Drivers/system_stm32f4xx.h

    startup/startup_stm32f412vx.s
)

add_executable(${PROJECT_NAME}.elf ${SOURCES})
</code></pre>
<p>The projects builds just fine...</p>
",https://stackoverflow.com/questions/66750743/ceedling-uses-wrong-startup-file,"['c', 'unit-testing', 'yaml', 'stm32', 'ceedling']",312,False,0,0
Mocked method always returns empty Optional,"<p>So I'm new to Unit Testing.</p>
<p>I'm trying to test the behavior of the method findAll() in IngredientServiceImplTest.</p>
<p>The problem that I'm facing has to do with the return value of the method mocked. It always return empty thus throwing the exception.</p>
<p>Can someone tell me what I'm missing?</p>
<p><em>Testing class.</em></p>
<pre><code>@ExtendWith(MockitoExtension.class)
class IngredientServiceImplTest {
   @Mock
   private MenuItemIngredientRepository menuItemIngredientRepository;

   @Mock
   private IngredientRepository ingredientRepository;

   @InjectMocks
   private IngredientServiceImpl ingredientService;

   @Mock
   private JpaRepository&lt;Ingredient, Long&gt; jpaRepository;

   @Mock
   private BaseMapper&lt;IngredientCreateDto, IngredientUpdateDto, IngredientResponseDto, 
   Ingredient&gt; baseMapper;


   @BeforeEach
   void init() {
       ingredientService.jpaRepository = jpaRepository;
       ingredientService.baseMapper = baseMapper;
   }

  @Test
  void When_FindById_ReturnIngredient() {

      Ingredient ingredient = new Ingredient();
      ingredient.setId(1L);
      ingredient.setName(&quot;Name&quot;);

      IngredientCreateDto ingredientCreateDto = new IngredientCreateDto();
      ingredientCreateDto.setName(&quot;Name&quot;);

      when(jpaRepository.findById(ingredient.getId())).thenReturn(Optional.of(ingredient));
      when(baseMapper.createDtoToEntity(ingredientCreateDto)).thenReturn(ingredient);
      assertEquals(ingredientService.findById(ingredient.getId()).getName(), 
 
    }
</code></pre>
<p><em>Base service class</em></p>
<pre><code>@AllArgsConstructor
@NoArgsConstructor
public class BaseServiceImpl&lt;CREATE_DTO, UPDATE_DTO, RESPONSE_DTO, ENTITY&gt; implements BaseService&lt;CREATE_DTO, UPDATE_DTO, RESPONSE_DTO, ENTITY&gt; {

@Autowired
protected JpaRepository&lt;ENTITY, Long&gt; jpaRepository;

@Autowired
protected BaseMapper&lt;CREATE_DTO, UPDATE_DTO, RESPONSE_DTO, ENTITY&gt; baseMapper;

@Override
public List&lt;RESPONSE_DTO&gt; findAll() {
    return jpaRepository.findAll()
                        .stream()
                        .map(baseMapper::entityToResponseDto)
                        .collect(Collectors.toList());
}

@Override
public RESPONSE_DTO findById(Long id) {
    return jpaRepository.findById(id)
            .map(baseMapper::entityToResponseDto)
            .orElseThrow(() -&gt; {
                throw new RuntimeException(&quot;Entity with id: &quot; + id + &quot; does not exist!&quot;);
            });
}

@Override
public RESPONSE_DTO save(CREATE_DTO entity) {
    return baseMapper.entityToResponseDto(jpaRepository.save(baseMapper.createDtoToEntity(entity)));
}
}
</code></pre>
<p><em>Ingredient Service class</em></p>
<pre><code>@Service
@AllArgsConstructor
@Validated
public class IngredientServiceImpl extends BaseServiceImpl&lt;IngredientCreateDto, IngredientUpdateDto, IngredientResponseDto, Ingredient&gt; implements IngredientService{

private final MenuItemIngredientRepository menuItemIngredientRepository;
private final IngredientRepository ingredientsRepository;

@Override
public IngredientResponseDto update(Long id, IngredientUpdateDto ingredient) {
    super.findById(id);
    Ingredient entityIngredient = baseMapper.updateDtoToEntity(ingredient);
    entityIngredient.setId(id);
    entityIngredient.setUpdatedAt(LocalDateTime.now());
    return baseMapper.entityToResponseDto(jpaRepository.save(entityIngredient));

}

@Override
public List&lt;IngredientResponseDto&gt; findTopIngredients(Integer n) {
    return menuItemIngredientRepository.findTopIngredients(n)
            .stream()
            .map(id -&gt; baseMapper.entityToResponseDto(jpaRepository.getOne(id)))
            .collect(Collectors.toList());
}

@Override
public List&lt;IngredientResponseDto&gt; findAllByFilter(IngredientFilter ingredientFilter) {
    return ingredientsRepository.findAllByFilter(ingredientFilter)
            .stream()
            .map(ingredient -&gt; baseMapper.entityToResponseDto(ingredient))
            .collect(Collectors.toList());
}


}
</code></pre>
",https://stackoverflow.com/questions/67893164/mocked-method-always-returns-empty-optional,"['spring-boot', 'junit', 'mockito']",366,False,0,0
What is the best way to test a custom assertion using google test in C++?,"<p>I am getting started with c++ unit testing. I have been verifying an assert macro using the google test framework. I am using <code>LOG_FATAL</code> to print the <code>ASSERT(...)</code> error message. I am also aborting the process by <code>std::abort()</code> if the log type is <code>FATAL</code>.</p>
<p>my unit test:</p>
<pre><code>TEST(Logger_DeathTest, assertionTest) {
    int test_val = 5;
    EXPECT_DEATH(SN_ASSERT(test_val &lt; 0, &quot;Value should not be less than zero&quot;), &quot;*&quot;);
    exit(0);
}
</code></pre>
<p>Failed test output:</p>
<pre><code>Logger_DeathTest.assertionTest
   Source: logger_test.cpp line 112
   Duration: &lt; 1 ms

  Message: 
    
    !! This test has probably CRASHED !!
    Test output:
    
    C:\dev\robo-galaxy\supernova\third_party\googletest\googletest\src/gtest-port.cc(869): error: Failed
    Syntax error at index 0 in simple regular expression &quot;*&quot;: '*' can only follow a repeatable token.
    Running main() from ../../../third_party/googletest/googletest/src/gtest_main.cc
    ../../../tests/logging/logger_test.cpp(116): error: Death test: { if (!(test_val &lt; 0)) { SN::Log::LogMessageShink_C(SN::Log::LogSeverityLevel_C::LOG_FATAL, &quot;../../../tests/logging/logger_test.cpp&quot;,  __FSTREXP __FUNCTION__   , 116) .GetStream() &lt;&lt; &quot;Assertion Failed: &quot; &lt;&lt; &quot;test_val &lt; 0&quot; &lt;&lt; &quot; :: &quot; &lt;&lt; &quot;Value should not be less than zero&quot;; __debugbreak(); } }
        Result: died but not with expected error.
      Expected: contains regular expression &quot;*&quot;
    Actual msg:
    [  DEATH   ] [Sat Jun 26 19:47:54 2021] [../../../tests/logging/logger_test.cpp:116 Log_Test::Logger_DeathTest_assertionTest_Test::TestBody] [FATAL] :: Assertion Failed: test_val &lt; 0 :: Value should not be less than zero
    [  DEATH   ] [ERROR] : A fatal log has been encountered.
    [  DEATH   ] 
</code></pre>
<p>Could someone please help to pass my unit test successfully?</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/68147063/what-is-the-best-way-to-test-a-custom-assertion-using-google-test-in-c,"['c++', 'googletest']",460,False,0,0
How to test a function in lisp and emacs,"<p>How can I assert that <code>2012/08</code> (instead of Aug 2012) is returned from this function?</p>
<p>Thus I can start learning lisp on the job/with the function itself until the output satisfies.</p>
<p>I know some python unit testing (pytest) and am looking for something similar for lisp. However, my first attempt[0] <code>C-c eval-buffer</code> fails with <code>Invalid function: &quot;&lt;2012-08-12 Mon&gt;&quot;</code></p>
<pre class=""lang-lisp prettyprint-override""><code>(assert (= (org-cv-utils-org-timestamp-to-shortdate (&quot;&lt;2012-08-12 Mon&gt;&quot;)) &quot;Aug 2012&quot;))

(defun org-cv-utils-org-timestamp-to-shortdate (date_str)
&quot;Format orgmode timestamp DATE_STR  into a short form date.
Other strings are just returned unmodified

e.g. &lt;2012-08-12 Mon&gt; =&gt; Aug 2012
today =&gt; today&quot;
  (if (string-match (org-re-timestamp 'active) date_str)
      (let* ((abbreviate 't)
             (dte (org-parse-time-string date_str))
             (month (nth 4 dte))
             (year (nth 5 dte))) ;;'(02 07 2015)))
        (concat
         (calendar-month-name month abbreviate) &quot; &quot; (number-to-string year)))
    date_str))

</code></pre>
<p>[0] <a href=""https://www.emacswiki.org/emacs/UnitTesting"" rel=""nofollow noreferrer"">https://www.emacswiki.org/emacs/UnitTesting</a></p>
",https://stackoverflow.com/questions/65593037/how-to-test-a-function-in-lisp-and-emacs,"['unit-testing', 'lisp', 'elisp', 'org-mode']",264,True,0,1
How to write or mock interface methods available in jar?,"<p>Having Method like</p>
<pre><code>public boolean getConfirmation(int timeout) {
  Selection Selection;
 try {                                                                            
      Selection = XYZ.getHelperCommands().getDisplayConfirmation(timeout);               
      } catch (Exception e) {                                                                   
         return false;                                                                               
       }                                                                                       
        boolean result=false;
    if(Selection!=null) {
        result= (Selection.compareTo(Selection.YES) == 0);
    } 
    logger.info(&quot;getConfirmation() completed with result : &quot; + result);
    return result ;
}
</code></pre>
<p>in above method helperCommands is a interface in my Jar file that contains getDisplayConfirmation() method my question is how can i mock this method i check below link but no help</p>
<p><a href=""https://stackoverflow.com/questions/36638554/unit-testing-of-jar-methods-in-java"">Unit testing of Jar methods in java</a>
i'm using below dependency</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;
    
    &lt;dependency&gt;
        &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
        &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;
        &lt;version&gt;${junit.vintage.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;5.0.0&lt;/version&gt;
        &lt;/dependency&gt;
</code></pre>
<p>is it mendatory to use powerMockRunner ? or above code is enough to write junit?</p>
",https://stackoverflow.com/questions/66363450/how-to-write-or-mock-interface-methods-available-in-jar,"['java', 'junit4', 'powermock']",236,True,0,1
"How to fix this error: Msg 50000, Level 17, State 2, Procedure tSQLt.FakeTable, Line 13 [Batch Start Line 0] Please run this inside a unit test","<p>I am currently working on my SQL Server project unit testing using TSQLT and I'm getting the below error, and don't know how to fix it.</p>
<p>Has anyone faced it before? Can anyone suggest a tutorial for TSQLT?</p>
<blockquote>
<p>Msg 50000, Level 17, State 2, Procedure tSQLt.FakeTable, Line 13 [Batch Start Line 0]<br />
Please run this inside a unit test</p>
</blockquote>
",https://stackoverflow.com/questions/69108052/how-to-fix-this-error-msg-50000-level-17-state-2-procedure-tsqlt-faketable,"['sql-server', 'unit-testing', 'tsqlt']",724,True,0,1
equivalent of TypeInfo.getMethod for privates methods,"<p>I want to test private methods.</p>
<blockquote>
<p><a href=""https://stackoverflow.com/questions/9122708/unit-testing-private-methods-in-c-sharp"">Unit testing private methods in C#</a></p>
</blockquote>
<p>I tried the fifth solution. ie : using reflection</p>
<pre><code>using System;
using System.Reflection;

namespace tobeDEleted
{
    static class classA {
        private static void method1() { Console.WriteLine(1); }
    }

    class classB
    {
        private void method2() { Console.WriteLine(2); }
        private static void method3() { Console.WriteLine(3); }
    }

    class Program
    {
        static void Main(string[] args)
        {

            var objb = new classB();
            MethodInfo methodInfo1 = typeof(classA).GetMethod (&quot;method1&quot;, BindingFlags.NonPublic | BindingFlags.Instance);
            MethodInfo methodInfo2 = typeof(classB).GetMethod(&quot;method2&quot;, BindingFlags.NonPublic | BindingFlags.Instance);
            MethodInfo methodInfo3 = typeof(classB).GetMethod(&quot;method3&quot;, BindingFlags.NonPublic | BindingFlags.Instance);


            object[] parameters = { };
            methodInfo2.Invoke(obj, parameters);
            methodInfo3.Invoke(obj, parameters);


        }
    }
}
</code></pre>
<p>as expected methodInfo3 throw a exception:</p>
<blockquote>
<p>System.NullReferenceException: 'Object reference not set to an instance of an object.'</p>
</blockquote>
<p>Is there a similar method as GetMethod for static methods.</p>
<p>I don't know too, how to test an static class.</p>
",https://stackoverflow.com/questions/67122349/equivalent-of-typeinfo-getmethod-for-privates-methods,['c#'],23,False,0,0
Using Visual Studio&#39;s Unit Testing Framework,"<p>I am using Visual Studio's Unit Testing Framework (that uses cpp) to test some cases regarding my program.
I am getting error <code>E0304</code> and get the red squiggly line under <code>Assert::</code> (see screenshot at the end of the question).</p>
<p>This is my cpp code:</p>
<pre><code>TEST_METHOD(T001_TriangleAngleTest_EquilateralTriangle_true)
    {
        //float angles[3] = { 67, 60, 60 };
        //float sum = angles[0] + angles[1] + angles[2];

        //float* result = getTriangleAngles(angles[0], angles[1], angles[2]);
        //Assert::AreEqual(sum, angles);

        float angles[3] = {60, 60, 60};

        float* result = getTriangleAngles(angles[0], angles[1], angles[2]);

        float expected = 180;

        Assert::AreEqual(expected, result);

    }
</code></pre>
<p>And this is my C code(my actual program):</p>
<pre><code>float* getTriangleAngles(float side1, float side2, float side3)
float pi, s, area, R;

pi = acos(-1);

s = (side1 + side2 + side3) / 2;
area = sqrt(s * (s - side1) * (s - side2) * (s - side3));

R = (side1 * side2 * side3) / (4 * area);

float angles[3] = { 0.f, 0.f, 0.f };
angles[0] = (180 / pi) * asin(side1 / (2 * R));
angles[1] = (180 / pi) * asin(side2 / (2 * R));
angles[2] = (180 / pi) * asin(side3 / (2 * R));

printf(&quot;Angles: %6.2f %6.2f %6.2f\n&quot;, angles[0], angles[1], angles[2]);

float sum = angles[0] + angles[1] + angles[2];

return angles;
</code></pre>
<p>My problem is that while still learning (as you can see in my poorly written unit test), I am having a lot of trouble trying to come with a few test cases. My program essentially asks for user input on 3 sides and displays the type of triangle that it is (equilateral, scalene, isosceles) and, depending on what type of triangle and side factor, it will display the 3 angles.
My code works, it's just the unit testing that I am having problems with trying to make it work.</p>
<p>Please let me know what I can do or if you could point me into the right direction so I can learn.</p>
<p><a href=""https://i.stack.imgur.com/7Pns1.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7Pns1.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/70052555/using-visual-studios-unit-testing-framework,"['c++', 'c', 'visual-studio', 'unit-testing', 'testing']",55,False,1,0
How can I mock Prisma client with es6 (Without typescript) in jest?,"<p>The Prisma Documentation has examples of mocking the client and doing unit testing using jest and typescript. Is there any way to mock the client in jest without using TypeScript?</p>
<p>I would be grateful if you can give a simple example.</p>
<p>Small Thing to add: I am using dependency injection in my project in all the functions that use the prisma.</p>
",https://stackoverflow.com/questions/68657823/how-can-i-mock-prisma-client-with-es6-without-typescript-in-jest,"['node.js', 'unit-testing', 'orm', 'jestjs', 'prisma']",2525,True,3,2
mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column in &#39;where clause&#39;,"<p>There is the function <code>get_show_listing</code> that queries a MySQL database and filters the set based on the passed argument (or lack of). Upon unit testing for the case of an argument being passed, the following error is being raised. I'm looking to understand what is causing this error; especially with whatever argument is passed into the function.</p>
<pre><code>mysql.connector.errors.ProgrammingError: 1054 (42S22): Unknown column 'Action' in 'where clause'
</code></pre>
<pre><code>def db_connect(func):
    def wrapper_db_connect(*args, **kwargs):
        with mysql.connector.connect(**credentials) as db_connection:
            cursor = db_connection.cursor(dictionary=True)
            return func(cursor, *args, **kwargs)
    return wrapper_db_connect

@db_connect
def get_show_listing(cursor, genre=None):
    if not genre:
        cursor.execute(&quot;&quot;&quot;
            SELECT t.title, t.view_rating, YEAR(t.release_date), t.score, t.votes, g.name
            FROM tvshow AS t LEFT JOIN show_genre as s
            ON t.title = s.tvshow_title RIGHT JOIN genre as g
            ON s.genre_name = g.name ORDER BY votes DESC LIMIT 5;
        &quot;&quot;&quot;)
    else:
        cursor.execute(f&quot;&quot;&quot;
            SELECT t.title, t.view_rating, YEAR(t.release_date), t.score, t.votes, g.name
            FROM tvshow AS t LEFT JOIN show_genre as s
            ON t.title = s.tvshow_title RIGHT JOIN genre as g
            ON s.genre_name = g.name WHERE g.name = {genre}
            ORDER BY votes DESC LIMIT 5;
        &quot;&quot;&quot;)
    return cursor.fetchall()
</code></pre>
<pre><code>class TestShowListing(unittest.TestCase):


    @patch.dict('main.credentials', test_db_config)
    def test_db_query_show_listing_with_genre(self):
        shows = get_show_listing(genre=&quot;Action&quot;)
        self.assertTrue(all(
            shows[i]['votes'] &gt; shows[i + 1]['votes'] and show[i]['votes']
            for i in range(len(shows) - 1)
        ))
</code></pre>
<pre><code>genre_table = &quot;&quot;&quot;
    CREATE TABLE IF NOT EXISTS genre (
        name VARCHAR(20) PRIMARY KEY
    );
&quot;&quot;&quot;

show_table = &quot;&quot;&quot;
    CREATE TABLE IF NOT EXISTS tvshow (
        title VARCHAR(20) NOT NULL,
        view_rating VARCHAR(8),
        release_date DATE,
        summary TEXT,
        score DECIMAL(2, 1),
        votes INT,
        PRIMARY KEY(title)
    );
&quot;&quot;&quot;

show_genre_table = &quot;&quot;&quot;
    CREATE TABLE IF NOT EXISTS show_genre (
        id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
        genre_name VARCHAR(20) NULL,
        tvshow_title VARCHAR(20) NOT NULL,
        FOREIGN KEY (genre_name) REFERENCES genre(name),
        FOREIGN KEY (tvshow_title) REFERENCES tvshow(title)
    );
&quot;&quot;&quot;

</code></pre>
",https://stackoverflow.com/questions/68279645/mysql-connector-errors-programmingerror-1054-42s22-unknown-column-in-where,"['mysql', 'mysql-python']",658,False,0,0
sqlite3.OperationalError: near &quot;&lt;&quot;: syntax error: Issue with sql in python formatting?,"<p>I'm doing a Software Engineering Project for one of my final courses as a Comp Sci major and I'm getting hungup on this particular error while I'm trying to do my data/unit testing of the methods before merging my methods with our teammates GUI. Anyone who can help me solve this issue is my hero</p>
<pre><code>class Student:
def __init__(self, StudentID, StudentName, conn: sql.Connection, curs: sql.Cursor):
    self.StudentID = StudentID
    self.StudentName = StudentName

def addStudent(self, curs: sql.Cursor):
    query = f&quot;&quot;&quot;INSERT INTO Student
            (StudentID, StudentName)
            VALUES ({self.StudentID},{self.StudentName})&quot;&quot;&quot;
    curs.execute(query)
</code></pre>
",https://stackoverflow.com/questions/70114270/sqlite3-operationalerror-near-syntax-error-issue-with-sql-in-python-forma,"['python', 'sql', 'sqlite', 'syntax-error', 'operationalerror']",1415,True,0,1
How to unit test SourceGenerator?,"<p>I writed a SourceGenerator, but how do I test it?</p>
<p>Main issue is how to imitate <code>GeneratorExecutionContext</code> (or just <code>Compilation</code> inside it) which generator gets into <code>Execute</code> method. I think there is a proper way to make fake SyntaxTrees for unit testing, but I cant find it. There are many articles about source generators itself, but none of them explain how to test generators.</p>
",https://stackoverflow.com/questions/67053841/how-to-unit-test-sourcegenerator,"['c#', 'roslyn', 'sourcegenerators']",1262,True,2,3
How to wrap Messenger and IMessenger from Microsoft Toolkti Mvvm for UnitTesting,"<p>I want to migrate from MVVM Light to Microsoft Toolkit MVVM and I have a problem with my unit tests.
I don't know how properly wrap IMessengerExtensions and IMessenger to use it in unit testing.</p>
<p>Example of test I have in my project:</p>
<pre><code>public void LoadingFinishedTest()
    {
        var messengerMock = new Mock&lt;IMessenger&gt;();
        messengerMock.Setup(mock =&gt; mock.Send(It.Is&lt;IsLoadingMessage&gt;()));

        var testedViewModelMock = new Mock&lt;SomeViewModel&gt;(messengerMock.Object);

        testedViewModelMock.Object.LoadingFinished();

        messengerMock.Verify(mock =&gt; mock.Send(It.Is&lt;IsLoadingMessage&gt;(), Times.Once);
    }
</code></pre>
<p>And of course if I do not wrap anything and just try to run test I get:</p>
<pre><code>System.NotSupportedException : Type to mock must be an interface, a delegate, or a non-sealed, non-static class.
</code></pre>
",https://stackoverflow.com/questions/68889718/how-to-wrap-messenger-and-imessenger-from-microsoft-toolkti-mvvm-for-unittesting,"['c#', 'unit-testing', 'moq', 'word-wrap']",303,False,1,2
spark unit testing with SharedSparkSession (org.apache.spark.sql.test.SharedSparkSession.eventually),"<p>I tried to write a simple unit for Spark join from the tutorial - <a href=""https://medium.com/@eugene_lopatkin/apache-spark-unit-testing-part-2-spark-sql-35c76ed592b0"" rel=""nofollow noreferrer"">Apache Spark Unit Testing Part 2 — Spark SQL</a>.
Added all dependencies from reference and</p>
<pre><code>  &quot;org.apache.spark&quot; %% &quot;spark-core&quot; % &quot;2.4.7&quot; % Test,
  &quot;org.apache.spark&quot; %% &quot;spark-core&quot; % &quot;2.4.7&quot; % Test classifier &quot;tests&quot;,
  &quot;org.scalatest&quot; %% &quot;scalatest&quot; % &quot;3.2.3&quot; % Test,
</code></pre>
<p>but can't add extended QueryTest because it involves AnyFunSuite in private class. Now the code looks like</p>
<pre><code>class TestScalaCheck extends AnyFunSuite with SharedSparkSession {
  import testImplicits._

  test(&quot;join - join using&quot;) {
    val df = Seq(1, 2, 3).map(i =&gt; (i, i.toString)).toDF(&quot;int&quot;, &quot;str&quot;)
    val df2 = Seq(1, 2, 3).map(i =&gt; (i, (i + 1).toString)).toDF(&quot;int&quot;, &quot;str&quot;)

    checkAnswer(
      df.join(df2, &quot;int&quot;),
      Row(1, &quot;1&quot;, &quot;2&quot;) :: Row(2, &quot;2&quot;, &quot;3&quot;) :: Row(3, &quot;3&quot;, &quot;5&quot;) :: Nil)
  }
</code></pre>
<p>And it generates the exception message:</p>
<pre><code>An exception or error caused a run to abort: org.apache.spark.sql.test.SharedSparkSession.eventually(Lorg/scalatest/concurrent/PatienceConfiguration$Timeout;Lorg/scalatest/concurrent/PatienceConfiguration$Interval;Lscala/Function0;Lorg/scalactic/source/Position;)Ljava/lang/Object; 
java.lang.NoSuchMethodError: org.apache.spark.sql.test.SharedSparkSession.eventually(Lorg/scalatest/concurrent/PatienceConfiguration$Timeout;Lorg/scalatest/concurrent/PatienceConfiguration$Interval;Lscala/Function0;Lorg/scalactic/source/Position;)Ljava/lang/Object;
    at org.apache.spark.sql.test.SharedSparkSession.afterEach(SharedSparkSession.scala:135)
    at org.apache.spark.sql.test.SharedSparkSession.afterEach$(SharedSparkSession.scala:129)
    at lesson2.TestScalaCheck.afterEach(TestScalaCheck.scala:14)
    at org.scalatest.BeforeAndAfterEach.$anonfun$runTest$1(BeforeAndAfterEach.scala:247)
    at org.scalatest.Status.$anonfun$withAfterEffect$1(Status.scala:377)
    at org.scalatest.Status.$anonfun$withAfterEffect$1$adapted(Status.scala:373)
    at org.scalatest.SucceededStatus$.whenCompleted(Status.scala:462)
    at org.scalatest.Status.withAfterEffect(Status.scala:373)
    at org.scalatest.Status.withAfterEffect$(Status.scala:371)
    at org.scalatest.SucceededStatus$.withAfterEffect(Status.scala:434)
    at org.scalatest.BeforeAndAfterEach.runTest(BeforeAndAfterEach.scala:246)
    at org.scalatest.BeforeAndAfterEach.runTest$(BeforeAndAfterEach.scala:227)
    at lesson2.TestScalaCheck.runTest(TestScalaCheck.scala:14)
    at org.scalatest.funsuite.AnyFunSuiteLike.$anonfun$runTests$1(AnyFunSuiteLike.scala:233)
    at org.scalatest.SuperEngine.$anonfun$runTestsInBranch$1(Engine.scala:413)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at org.scalatest.SuperEngine.traverseSubNodes$1(Engine.scala:401)
    at org.scalatest.SuperEngine.runTestsInBranch(Engine.scala:396)
    at org.scalatest.SuperEngine.runTestsImpl(Engine.scala:475)
    at org.scalatest.funsuite.AnyFunSuiteLike.runTests(AnyFunSuiteLike.scala:233)
    at org.scalatest.funsuite.AnyFunSuiteLike.runTests$(AnyFunSuiteLike.scala:232)
    at org.scalatest.funsuite.AnyFunSuite.runTests(AnyFunSuite.scala:1563)
    at org.scalatest.Suite.run(Suite.scala:1112)
    at org.scalatest.Suite.run$(Suite.scala:1094)
    at org.scalatest.funsuite.AnyFunSuite.org$scalatest$funsuite$AnyFunSuiteLike$$super$run(AnyFunSuite.scala:1563)
    at org.scalatest.funsuite.AnyFunSuiteLike.$anonfun$run$1(AnyFunSuiteLike.scala:237)
    at org.scalatest.SuperEngine.runImpl(Engine.scala:535)
    at org.scalatest.funsuite.AnyFunSuiteLike.run(AnyFunSuiteLike.scala:237)
    at org.scalatest.funsuite.AnyFunSuiteLike.run$(AnyFunSuiteLike.scala:236)
    at lesson2.TestScalaCheck.org$scalatest$BeforeAndAfterAll$$super$run(TestScalaCheck.scala:14)
    at org.scalatest.BeforeAndAfterAll.liftedTree1$1(BeforeAndAfterAll.scala:213)
    at org.scalatest.BeforeAndAfterAll.run(BeforeAndAfterAll.scala:210)
    at org.scalatest.BeforeAndAfterAll.run$(BeforeAndAfterAll.scala:208)
    at lesson2.TestScalaCheck.run(TestScalaCheck.scala:14)
    at org.scalatest.tools.SuiteRunner.run(SuiteRunner.scala:45)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13(Runner.scala:1320)
    at org.scalatest.tools.Runner$.$anonfun$doRunRunRunDaDoRunRun$13$adapted(Runner.scala:1314)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at org.scalatest.tools.Runner$.doRunRunRunDaDoRunRun(Runner.scala:1314)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24(Runner.scala:993)
    at org.scalatest.tools.Runner$.$anonfun$runOptionallyWithPassFailReporter$24$adapted(Runner.scala:971)
    at org.scalatest.tools.Runner$.withClassLoaderAndDispatchReporter(Runner.scala:1480)
    at org.scalatest.tools.Runner$.runOptionallyWithPassFailReporter(Runner.scala:971)
    at org.scalatest.tools.Runner$.run(Runner.scala:798)
    at org.scalatest.tools.Runner.run(Runner.scala)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.runScalaTest2or3(ScalaTestRunner.java:38)
    at org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestRunner.main(ScalaTestRunner.java:25)
 
</code></pre>
<p>Could you help me to resolve it?</p>
<p>The original code is - <a href=""https://github.com/apache/spark/blob/master/sql/core/src/test/scala/org/apache/spark/sql/DataFrameJoinSuite.scala"" rel=""nofollow noreferrer"">DataFrameJoinSuite.scala</a></p>
",https://stackoverflow.com/questions/65915911/spark-unit-testing-with-sharedsparksession-org-apache-spark-sql-test-sharedspar,['apache-spark'],497,False,1,0
StackOverflow error on unit testing API controllers?,"<p>I'm working on a Spring Boot MVC project and I'm getting the following error when unit testing my CRUD controllers :</p>
<pre><code>java.lang.StackOverflowError
at java.base/java.lang.Throwable.getOurStackTrace(Throwable.java:840)
at java.base/java.lang.Throwable.getStackTrace(Throwable.java:832)
at ch.qos.logback.classic.spi.ThrowableProxy.&lt;init&gt;(ThrowableProxy.java:55)
at ch.qos.logback.classic.spi.ThrowableProxy.&lt;init&gt;(ThrowableProxy.java:60)

java.lang.StackOverflowError
at java.base/java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:834)
at java.base/java.lang.StringBuilder.append(StringBuilder.java:247)
at ch.qos.logback.classic.pattern.ThrowableProxyConverter.subjoinSTEPArray(ThrowableProxyConverter.java:216)
at ch.qos.logback.classic.pattern.ThrowableProxyConverter.recursiveAppend(ThrowableProxyConverter.java:161)
at ch.qos.logback.classic.pattern.ThrowableProxyConverter.recursiveAppend(ThrowableProxyConverter.java:168)
</code></pre>
<p>Here's one of the controllers unit test, the others follow the same logic.</p>
<pre><code>@Autowired
private MockMvc mockMvc;

@MockBean
private PessoaRepository pessoaRepository;

@Test
public void deletarPessoa_quandoDelete() throws Exception {
    Pessoa pessoa = new Pessoa();
    pessoa.setNome(&quot;Test Nome&quot;);
    pessoa.setId(89L);
    doNothing().when(pessoaRepository).delete(pessoa);
    mockMvc.perform(delete(&quot;/pessoas/&quot; + pessoa.getId().toString())
            .contentType(MediaType.APPLICATION_JSON))
            .andExpect(status().isNoContent());
}
</code></pre>
<p>What could this be? I have no idea why I'm getting this error.</p>
<p>EDIT : here's the controller, it basically calls for the repo to delete a Pessoa object</p>
<pre><code>@DeleteMapping(&quot;/{id}&quot;)
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deletar(@ApiParam(value = &quot;ID&quot;, example = &quot;1&quot;) @PathVariable Long id) {
    Pessoa pessoaDeletada = pessoaRepository.getOne(id);
    pessoaRepository.delete(pessoaDeletada);
}
</code></pre>
",https://stackoverflow.com/questions/66765956/stackoverflow-error-on-unit-testing-api-controllers,"['java', 'spring', 'unit-testing', 'testing', 'stack-overflow']",432,False,1,0
JEST Testing for Axios - transformResponse,"<p>I have following axios get code which uses transformResponse</p>
<pre><code>const downloadAttachment = ({attachmentId, id, oId}) =&gt; {
  return axios.get(`${url}/attachments/file/${attachmentId}/v1`, {
    headers: buildHeaders(),
    params: getUrlSearchParams({id, oId}),
    responseType: 'blob',
    timeout: REQUEST_TIMEOUT,
    transformResponse: [(data) =&gt; ({file: data})],
  });
};
</code></pre>
<p>I am using JEST for unit testing. I could get unit test passed with following code</p>
<pre><code>it('should call milo with correct arguments', () =&gt; {
    expect(axios.get).toHaveBeenCalledWith(mockdownloadAttachmentUrl, {
      headers: mockHeaders,
      params: {
        id: 'ABCD',
        oId: 'XYZ',     
      },
      responseType: 'blob',
      timeout: 5000,
      transformResponse: [expect.any(Function)],
    });
  });
</code></pre>
<p>However JEST is not able to complete 100% code coverage and pointing to line transformResponse: [(data) =&gt; ({file: data})] in code which is not covered. How to write test to cover this part of code? Please advice.</p>
",https://stackoverflow.com/questions/66579132/jest-testing-for-axios-transformresponse,"['javascript', 'jestjs', 'axios', 'code-coverage']",992,True,1,1
how to mock/unit test downloads from amazon s3?,"<p>I am new to unit testing/moq and was wondering how this could be done. I have a function that downloads a file from s3 to local. How can I mock this so that it doesn't actually use transferUtility to download anything from s3?</p>
<pre><code>bool downloadFileFromS3(string localPathToSave, string filenameToDownloadAs, string bucketName, string objectKey)
{
    try
    {
        string accessKey = &quot;xxx&quot;;
        string secretKey = &quot;xxx&quot;;
        // do stuff before
        TransferUtility transferUtility = new TransferUtility(accessKey, secretKey);
        transferUtility.Download( Path.Combine(localPathToSave, filenameToDownloadAs), bucketName, objectKey );
        // do stuff after
        return true;
    }

    catch (Exception e)
    {
        // stuff
    }
}
</code></pre>
<p>I've created the mock but I don't know how to use it for testing the function that I wrote.</p>
<pre><code>[Test]
public void testDownloadFromS3()
{
    string filePath = null;
    string bucketName = null;
    string key = null;

    Mock&lt;Amazon.S3.Transfer.TransferUtility&gt; mock = new Mock&lt;Amazon.S3.Transfer.TransferUtility&gt;();
    //mock.Setup(x =&gt; x.Download(filePath, bucketName, key)).Verifiable();
    //Mock.Verify();
}
</code></pre>
",https://stackoverflow.com/questions/68474838/how-to-mock-unit-test-downloads-from-amazon-s3,"['c#', 'unit-testing', 'amazon-s3', 'moq', 'awss3transferutility']",2598,True,1,1
Go Unit test - could not match actual sql with expected regexp while mocking gorm using go-sqlmock?,"<p>When unit testing I mock gorm using sqlmock. But when running all initial setup are fine but error happen when the actual query and testing query matches. I have given below all codes.</p>
<p>user.go</p>
<pre class=""lang-golang prettyprint-override""><code>func (r *users) GetUserByID(userID uint) (*domain.User, *errors.RestErr) {
    var resp domain.User

    res := r.DB.Model(&amp;domain.User{}).Where(&quot;id = ?&quot;, userID).First(&amp;resp)

    if res.RowsAffected == 0 {
        logger.Error(&quot;error occurred when getting user by user id&quot;, res.Error)
        return nil, errors.NewNotFoundError(errors.ErrRecordNotFound)
    }

    return &amp;resp, nil
}
</code></pre>
<blockquote>
<p>Mock</p>
</blockquote>
<p>user_test.go</p>
<pre><code>type Suite struct {
    suite.Suite
    DB         *gorm.DB
    mock       sqlmock.Sqlmock
    db         *sql.DB
    err        error
    repository repository.IUsers
}

func (s *Suite) SetupSuite() {
    s.db, s.mock, s.err = sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))

    require.NoError(s.T(), s.err)

    dialector := mysql.New(mysql.Config{
        DSN:                       &quot;sqlmock_db_0&quot;,
        DriverName:                &quot;mysql&quot;,
        Conn:                      s.db,
        SkipInitializeWithVersion: true,
    })

    s.DB, s.err = gorm.Open(dialector, &amp;gorm.Config{})

    require.NoError(s.T(), s.err)
    s.repository = impl.NewMySqlUsersRepository(s.DB)
}

func (s *Suite) AfterTest(_, _ string) {
    require.NoError(s.T(), s.mock.ExpectationsWereMet())
}

func TestInit(t *testing.T) {
    suite.Run(t, new(Suite))
}

// .................Start Testing....................

func (s *Suite) Test_repository_Get() {
    var (
        id        = uint(1)
        user_name = &quot;user-name&quot;
        fast_name = &quot;fast-name&quot;
    )

    s.mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM &quot;users&quot; WHERE (id = $1) ORDER BY &quot;users&quot;.&quot;id&quot; LIMIT 1`)).
        WithArgs(uint(id)).
        WillReturnRows(sqlmock.NewRows([]string{&quot;id&quot;, &quot;user_name&quot;, &quot;fast_name&quot;}).
            AddRow(uint(id), user_name, fast_name))

    res, _ := s.repository.GetUserByID(uint(id))
    require.Nil(s.T(), deep.Equal(&amp;domain.User{ID: uint(id), UserName: user_name, LastName: fast_name}, res))
}
</code></pre>
<p>when I execute <code>res, _ := s.repository.GetUserByID(uint(id))</code> this line it goes user.go file. Here in sql query line Getting error Like this given below .</p>
<pre><code>actual sql: &quot;SELECT * FROM `users` WHERE id = ? ORDER BY `users`.`id` LIMIT 1&quot; 
does not equal to expected &quot;SELECT \* FROM &quot;users&quot; WHERE \(id = \$1\) ORDER BY &quot;users&quot;\.&quot;id&quot; LIMIT 1&quot;


=&gt; expecting Query, QueryContext or QueryRow which:
     - matches sql: 'SELECT \* FROM &quot;users&quot; WHERE \(id = \$1\) ORDER BY &quot;users&quot;\.&quot;id&quot; LIMIT 1'
     - is with arguments:
                0 - 1
     - should return rows:
                row 0 - [1 user-name fast-name]
</code></pre>
<p>What is the issue here?</p>
",https://stackoverflow.com/questions/68528616/go-unit-test-could-not-match-actual-sql-with-expected-regexp-while-mocking-gor,"['unit-testing', 'go', 'mocking', 'go-gorm', 'go-sqlmock']",2253,True,1,1
getting error Subscribe is not a function in jasmine,"<p>I am getting error, subscribe is not a function in angular unit testing</p>
<p>this is the call that I am using in component</p>
<pre><code>this.myService.employees.subscribe(emp =&gt; this.emp = emp);
</code></pre>
<p>when I create a mock service for this to test the above code getting error.</p>
<p>Can anyone suggest how can I test the above observable.</p>
<p>I want to send mock data when <code>this.myService.employees.subscribe(emp =&gt; this.emp = emp);</code> subscribe from component</p>
<p><strong>employees</strong> is <strong>BehaviorSubject</strong> observable</p>
",https://stackoverflow.com/questions/66344445/getting-error-subscribe-is-not-a-function-in-jasmine,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",2965,True,1,1
expect(received).toEqual(expected) // deep equality - Throws this error when the response has the ternary condition,"<p>I am learning unit testing with Jest,
This is the function I trying to test.</p>
<pre><code>import axios from &quot;axios&quot;;

export const call = async () =&gt; {

 return axios.get(&quot;https://www.example.com&quot;).then((resp) =&gt;{
     const response = resp.data
     let userData = {
         title : response.title ? response.title : &quot;&quot;,
         url : response.url ? response.url : &quot;&quot;,
         date : response.date ? response.date : &quot; &quot;,
         id : response.id ? response.id : &quot;&quot;,
         email: response.email ? response.email : &quot;&quot;
     }
     return Promise.resolve(userData)
 })
}
</code></pre>
<p>here is the test.js file ---</p>
<pre><code>import axios from &quot;axios&quot;
import {call} from './components/call'

jest.mock('axios')

const expectedResult = {
    title:&quot;hello&quot;
}

const resp ={
    data : expectedResult
}

describe(&quot;test&quot;, ()=&gt;{
    test(&quot;demo-test&quot;, async ()=&gt;{
        axios.get.mockResolvedValueOnce(resp)
        const response = await call()
        expect(response).toEqual(expectedResult)
        
        console.log(&quot;axios.get() returns &gt;&gt;&gt;&quot;, axios.get.mock.results[0]);
        expect(axios.get).toHaveBeenCalledWith(&quot;https://www.example.com&quot;)
    })

})
</code></pre>
<p>Here is the error I am getting</p>
<pre><code>expect(received).toEqual(expected) // deep equality

    - Expected  - 0
    + Received  + 4

      Object {
    +   &quot;date&quot;: &quot; &quot;,
    +   &quot;email&quot;: &quot;&quot;,
    +   &quot;id&quot;: &quot;&quot;,
        &quot;title&quot;: &quot;hello&quot;,
    +   &quot;url&quot;: &quot;&quot;,
      }

      16 |         axios.get.mockResolvedValueOnce(resp)
      17 |         const response = await call()
    &gt; 18 |         expect(response).toEqual(expectedResult)
         |                          ^
      19 |
      20 |         console.log(&quot;axios.get() returns &gt;&gt;&gt;&quot;, axios.get.mock.results[0]);
      21 |         expect(axios.get).toHaveBeenCalledWith(&quot;https://google.com&quot;)
 FAIL  src/call.test.js (7.597 s)
</code></pre>
<p>In the call.js, when userData dosen't have ternary conditions then the test passes. But when I put ternary condition the test gets failed with the above error. Please help me. How to resolve this issue.</p>
",https://stackoverflow.com/questions/69605476/expectreceived-toequalexpected-deep-equality-throws-this-error-when-the,"['javascript', 'reactjs', 'jestjs', 'react-testing-library']",6858,False,1,0
How to disable inclusion of header when using `#pragma once` (similiary to when using include guards)?,"<p>From time to time I have to retrofit unit testing into an unfriendly environment.<br />
In these cases include guards are pretty useful, because:</p>
<ol>
<li>I could suppress inclusion of unwanted header file,</li>
<li>I could check whether specific file was (not)included into test environment.</li>
</ol>
<p>It seems that both these options are gone with <code>#pragma once</code>.</p>
<p>Are there any workarounds beyond replacing <code>#pragma</code> with guards for critical files?</p>
",https://stackoverflow.com/questions/69340813/how-to-disable-inclusion-of-header-when-using-pragma-once-similiary-to-when,"['c++', 'unit-testing', 'include', 'pragma', 'include-guards']",96,False,1,0
How to mock aws-amplify in react unit testing?,"<p>I am using <a href=""https://aws.amazon.com/ru/cognito/"" rel=""nofollow noreferrer"">AWS co</a>, <a href=""https://aws.amazon.com/ru/amplify/"" rel=""nofollow noreferrer"">Amplify</a> and <a href=""https://en.reactjs.org/"" rel=""nofollow noreferrer"">React</a>
I want to mock API.graphql imported from AWS.
This is my helper function for asynchronous functions
<code>useAsync.ts</code></p>
<pre><code>import { ErrorHandle } from '@app/components/ErrorHandle';
import { useCallback, useState } from 'react';

const getRetryWaitTime = (retryCount: number): number =&gt; {
  const httpRetryMaxWaitTime = 10 * 60 * 1000;
  const suggestedRetryWaitTime = 1000 * 2 ** retryCount;
  const retryWaitTime = Math.min(httpRetryMaxWaitTime, suggestedRetryWaitTime);
  return retryWaitTime;
};

const delay = (ms: number) =&gt; {
  return new Promise((resolve) =&gt; setTimeout(resolve, ms));
};

const retry = (retryFunc: () =&gt; Promise&lt;any&gt;, retryCount = -1): Promise&lt;any&gt; =&gt; {
  return retryFunc().catch((err: any) =&gt; {
    if (err &amp;&amp; retryCount) {
      retryCount -= 1;
      const waitTime = getRetryWaitTime(retryCount);
      return delay(waitTime).then(() =&gt; retry(retryFunc, retryCount));
    }
    throw err;
  });
};

export const useAsync = (
  asyncFunction,
  options: {
    onError?: (error, response) =&gt; any;
    onSuccess?: (data) =&gt; any;
    retryCount?: number;
  } = {},
) =&gt; {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  options.retryCount = options.retryCount || 1;
  options.onError = options.onError || ((error, response) =&gt; ErrorHandle(error, response));

  const execute = useCallback(
    async (payload?: any) =&gt; {
      setLoading(true);
      setData(null);
      setError(null);

      return retry(() =&gt; asyncFunction(payload), options.retryCount)
        .then((response) =&gt; {
          setData(response);
          if (options.onSuccess) {
            options.onSuccess(response);
          }
          setLoading(false);
          return { ok: true, data: response.data, response };
        })
        .catch((error: any) =&gt; {
          setError(error);
          if (options.onError) {
            options.onError(error, error ? error.response : null);
          }
          setLoading(false);
          return { error, ok: false, response: error, data: error };
        });
    },
    [asyncFunction, options],
  );

  return { execute, loading, data, error };
};
</code></pre>
<p>This is an example for my graphql mutations file.
<code>mutations.ts</code></p>
<pre><code>export const createLanguage = /* GraphQL */ `
  mutation CreateLanguage($input: CreateLanguageInput!, $condition: ModelLanguageConditionInput) {
    createLanguage(input: $input, condition: $condition) {
      id
      name
      code
      createdAt
      updatedAt
      createdBy
      updatedBy
      direction
      owner
    }
  }
`;
</code></pre>
<p>This is actual code for mocking and unit testing my useLanguages file
<code>useLanguages.ts</code></p>
<pre><code>import { createLanguage } from '@app/graphql/mutations';
import { API, graphqlOperation } from 'aws-amplify';
const useLanguages = () =&gt; {

  const [state, dispatch] = useStore();
  const languageAdd = useAsync(
   (value) =&gt; {
     const input: any = value;
     input.createdBy = state.user.attributes.email;
     input.updatedBy = state.user.attributes.email;
     return API.graphql(graphqlOperation(createLanguage, { input }));
   },
   {
     onSuccess: (result) =&gt; dispatch({ type: Actions.ADD_LANGUAGE, payload: result.data.createLanguage }),
   },
  );
  return { languageAdd };
}
</code></pre>
<p>I tried multiple variants <a href=""https://stackoverflow.com/questions/59215244/how-to-mock-aws-amplify-library-in-angular"">this</a> <a href=""https://stackoverflow.com/questions/60454057/how-do-i-properly-mock-amplify-for-unit-testing-in-jasmine"">that</a> and read a lot of documentations and articles like
<a href=""https://www.apollographql.com/docs/react/development-testing/testing/"" rel=""nofollow noreferrer"">this</a> <a href=""https://dev.to/rakannimer/testing-your-amplify-application-with-jest-and-cypress-1g0i"" rel=""nofollow noreferrer"">that</a></p>
",https://stackoverflow.com/questions/70150882/how-to-mock-aws-amplify-in-react-unit-testing,"['reactjs', 'unit-testing', 'graphql', 'aws-amplify']",606,True,1,1
How to unit test private Windows Forms?,"<p>I'm a beginner at unit testing and I am currently confronted with my 1st problem.</p>
<p>I want to unit test my <code>CheckedChange</code> function:</p>
<pre><code>protected void rbtnMSSQL_CheckedChanged(object sender, EventArgs e)
{
    if (rbtnMSSQL.Checked &amp;&amp; rbtnOracle.Checked)
    {
        rbtnOracle.Checked = false;
    }
}
</code></pre>
<p>Well, if Iwant to assert, I need the bool value from <code>rbtnMSSQL.Checked</code> and <code>rbtnOracle.Checked</code>, but they are private.</p>
<p>I guess it would work with internal and</p>
<pre><code>[assembly: InternalsVisibleTo(&quot;UnitTests&quot;)]
</code></pre>
<p>but is it a good approach to chance every private value to an internal value?</p>
",https://stackoverflow.com/questions/69765265/how-to-unit-test-private-windows-forms,"['c#', 'unit-testing', 'private']",92,True,0,2
Mocking HttpClient in xunit for different endpoint,"<p>I am mocking <code>HttpClient</code> for unit testing following <a href=""https://stackoverflow.com/a/44028625/947889"">this SO suggestion</a>. It works as expected for a single endpoint, and I am wondering how I can adjust it for a different endpoint. Please see the following sample:</p>
<pre><code>class Agent
{
    private HttpClient _client;
    private string _baseUri = &quot;http://example.com/&quot;;
    public Agent(HttpClient client)
    { _client = client; }

    public bool Run()
    {
        var res1 = client.GetAsync(new Uri(_baseUri, &quot;endpoint1&quot;));
        var res2 = client.GetAsync(new Uri(_baseUri, &quot;endpoint2&quot;));
        return res1 == res2
    }
}

// In the test method:
var responseMessage = new HttpResponseMessage
{
    StatusCode = HttpStatusCode.OK,
    Content = new StringContent(&quot;test_return&quot;)
};

var mock = new Mock&lt;HttpMessageHandler&gt;();
mock.Protected()
    .Setup&lt;Task&lt;HttpResponseMessage&gt;&gt;(
        &quot;SendAsync&quot;,
        ItExpr.IsAny&lt;HttpRequestMessage&gt;(),
        ItExpr.IsAny&lt;CancellationToken&gt;())
    .ReturnsAsync(responseMessage);

client = new HttpClient(mock.Object);

var agent = new Agent(client);
var resp = agent.Run();

Assert.True(resp)
</code></pre>
<p>In the above example, <code>resp</code> will be always <code>true</code> because as a result of mocking, the response from both endpoints in the <code>Run</code> method will be equal.</p>
",https://stackoverflow.com/questions/70517010/mocking-httpclient-in-xunit-for-different-endpoint,"['c#', 'unit-testing', 'mocking', 'httpclient']",305,True,0,1
Chai being ambiguous with failings on Arrays,"<p>I'm running Chai unit testing. However, I'm testing a schema property, and getting this failing unit test:</p>
<pre><code>Foo Schema functionality
  Bar
    should return data Array if appropriate values are passed
AssertionError: expected [ Array(2) ] to deeply equal [ Array(2) ]
</code></pre>
<p>And this is with code that says</p>
<pre><code>Baz = myFunction(data)
expect(Baz).to.have.same.members([null, {Foo:Bar, Bash:Baz}])
</code></pre>
<p>Is there a way to get it to actually print out the full arrays with objects so I can see if its my unit test screwing up or my code?</p>
<p>I <em>want</em> output that looks more like</p>
<pre><code>Foo Schema functionality
  Bar
    should return data Array if appropriate values are passed
AssertionError: expected [null, {Foo:Barf, Bash:Baz}] to deeply equal [null, {Foo:Bar, Bash:Baz}]
</code></pre>
<p>Thanks!</p>
",https://stackoverflow.com/questions/68716015/chai-being-ambiguous-with-failings-on-arrays,"['node.js', 'unit-testing', 'chai']",34,False,0,0
Can I use PowerMockito in Quarkus with JUnit5?,"<p>Im am currently building a Quarkus application and for unit testing I am using JUnit5. Currently I have no other option then using PowerMockito to mock my static functions but I cant seem to find the dependencies for it in my Quarkus project.</p>
<p>Does anyone know what the best set of dependecies should be used in a Quarkus app for PowerMockito with JUnit5?</p>
",https://stackoverflow.com/questions/70493926/can-i-use-powermockito-in-quarkus-with-junit5,"['java', 'junit', 'mockito', 'quarkus', 'powermockito']",853,True,0,1
CLion tutorial for GoogleTest: changing STATIC to SHARED library crashes,"<p>I followed the tutorial here <a href=""https://www.jetbrains.com/help/clion/unit-testing-tutorial.html"" rel=""nofollow noreferrer"">https://www.jetbrains.com/help/clion/unit-testing-tutorial.html</a> and got it all to work as promised (Windows 10 Pro, CLion 2021.1.2, Debug MinGW Lavavej + boost toolchain <a href=""https://nuwen.net/mingw.html"" rel=""nofollow noreferrer"">https://nuwen.net/mingw.html</a>)</p>
<p>I changed one word in <code>DateConverter_lib\CMakeLists.txt</code></p>
<pre><code>add_library(DateConverter_lib STATIC
</code></pre>
<p>to</p>
<pre><code>add_library(DateConverter_lib SHARED
</code></pre>
<p>The project builds but no longer runs, printing</p>
<pre><code>Test framework quit unexpectedly 
Process finished with exit code -1073741515 (0xC0000135)
</code></pre>
<p>which, apparently, is a failure to load the DLL (shared library). Any advice for me?</p>
<p><a href=""https://i.stack.imgur.com/4WdMQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4WdMQ.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/68202605/clion-tutorial-for-googletest-changing-static-to-shared-library-crashes,"['googletest', 'clion']",155,False,0,1
Chaining `and` function to `selectAll` in spec file throws an error,"<p>I'm trying to follow official <code>Akita</code> docs on unit testing with <code>Angular</code>: <a href=""https://datorama.github.io/akita/docs/angular/tests/"" rel=""nofollow noreferrer"">https://datorama.github.io/akita/docs/angular/tests/</a>.</p>
<p>However I'm having problems with mocking <code>TodosQuery</code> return value. This is the specific line:</p>
<pre><code>todosQuery.selectAll.and.returnValue(of([createTodo(), createTodo()]))
</code></pre>
<p>And this is the error thrown:</p>
<pre><code>Property 'and' does not exist on type '{ (options: SelectAllOptionsA&lt;Todo&gt;): Observable&lt;HashMap&lt;Todo&gt;&gt;; (options: SelectAllOptionsB&lt;Todo&gt;): Observable&lt;...&gt;; (options: SelectAllOptionsC&lt;...&gt;): Observable&lt;...&gt;; (options: SelectAllOptionsD&lt;...&gt;): Observable&lt;...&gt;; (options: SelectAllOptionsE&lt;...&gt;): Observable&lt;...&gt;; (): Observable&lt;...&gt;; }'.
</code></pre>
<p>Maybe the docs are outdated and this is no longer supported? Is this still the preferred way to mock <code>Query</code> returning value?</p>
<p>These are my package.json dependencies:</p>
<pre><code>&quot;dependencies&quot;: {
    &quot;@angular/animations&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/common&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/compiler&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/core&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/forms&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/platform-browser&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/platform-browser-dynamic&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/router&quot;: &quot;~12.2.0&quot;,
    &quot;@datorama/akita&quot;: &quot;^6.2.3&quot;,
    &quot;@datorama/akita-ng-entity-service&quot;: &quot;^6.2.0&quot;,
    &quot;@datorama/akita-ng-router-store&quot;: &quot;^6.0.0&quot;,
    &quot;rxjs&quot;: &quot;~6.6.0&quot;,
    &quot;tslib&quot;: &quot;^2.3.0&quot;,
    &quot;zone.js&quot;: &quot;~0.11.4&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@angular-devkit/build-angular&quot;: &quot;~12.2.5&quot;,
    &quot;@angular/cli&quot;: &quot;~12.2.5&quot;,
    &quot;@angular/compiler-cli&quot;: &quot;~12.2.0&quot;,
    &quot;@datorama/akita-ngdevtools&quot;: &quot;^6.0.0&quot;,
    &quot;@types/jasmine&quot;: &quot;~3.8.0&quot;,
    &quot;@types/node&quot;: &quot;^12.11.1&quot;,
    &quot;jasmine-core&quot;: &quot;~3.8.0&quot;,
    &quot;karma&quot;: &quot;~6.3.0&quot;,
    &quot;karma-chrome-launcher&quot;: &quot;~3.1.0&quot;,
    &quot;karma-coverage&quot;: &quot;~2.0.3&quot;,
    &quot;karma-jasmine&quot;: &quot;~4.0.0&quot;,
    &quot;karma-jasmine-html-reporter&quot;: &quot;~1.7.0&quot;,
    &quot;typescript&quot;: &quot;~4.3.5&quot;
  }
</code></pre>
",https://stackoverflow.com/questions/69205538/chaining-and-function-to-selectall-in-spec-file-throws-an-error,"['angular', 'chaining', 'akita']",72,True,0,1
nestjsx-automapper profiles not found in nestjs test modules,"<p>Im trying to make unit testing for some features in my NestJS API.</p>
<p>I make use of <code>nestjsx-automapper</code>. The exception happens only while testing any service that uses mappings. I use <code>@nestjs/testing</code> and <code>jest</code>.
I have managed to replicate the error in this test:</p>
<pre><code>describe('UserController', () =&gt; {
  let userServiceInterface: UserServiceInterface;

  beforeEach(async () =&gt; {
    const app: TestingModule = await Test.createTestingModule({
      imports: [AutomapperModule.withMapper('user')],
      providers: [
        {
          provide: 'UserServiceInterface',
          useClass: UserService,
        },
      ],
    }).compile();

    userServiceInterface = app.get&lt;UserServiceInterface&gt;(
      'UserServiceInterface',
    );
  });

  describe('find', () =&gt; {
    it(`should return user with name 'pipo'`, () =&gt; {
      const user = userServiceInterface.find('pipo');
      expect(user.username).toBe('pipo');
    });
  });
});

</code></pre>
<p>I've been looking for different ways to configure profiles, but importing them is the only way I've found.</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/69912696/nestjsx-automapper-profiles-not-found-in-nestjs-test-modules,"['testing', 'jestjs', 'automapper', 'nestjs']",511,True,0,1
How to test all the paths of this function?,"<p>I'm barely new with Unit Testing, and I'm stuck in this functionality.</p>
<pre><code>onPreview(value: any): void {
    this.showLoading('Cargando PDF...');
    if (value) {
      this._restService.getDocument(value).subscribe(
        (restResult: any) =&gt; {
 
          this._dialog.open(DialogPreviewDocument, {
            data: restResult.data
          });
        },
        error =&gt; {
          Swal.fire({
            icon: 'error',
            title: 'Ocurrió un error al abrir este documento',
            confirmButtonColor: '#3085d6',
            confirmButtonText: 'Cerrar'
          }).then(r =&gt; {
          });
        }
      );
    }
  }
</code></pre>
<p>This are my Tests, the first one works well, but when I try to test when I receive an error from the service I received an error.</p>
<pre><code>it('should call onPreview with error', (done =&gt; {
        spyOn(component, 'onPreview');
        let getDocument = spyOn(service, 'getDocument')
        spyOn(Swal, 'fire')
        component.onPreview(&quot;1614210817503&quot;);
        setTimeout(() =&gt;{
            getDocument.and.throwError(&quot;Error&quot;)
            expect(service.getDocument).toHaveBeenCalled();
            expect(Swal.fire).toHaveBeenCalled()

        })
    }));
</code></pre>
<pre><code>Error: Expected spy getDocument to have been called.
        at &lt;Jasmine&gt;
        at http://localhost:4200/_karma_webpack_/src/app/modules/home/components/dashboard-details/dashboard-details.component.spec.ts:468:41
        at ZoneDelegate.invokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:399:1)
        at ProxyZoneSpec.push.QpwO.ProxyZoneSpec.onInvokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:323:1)
    Error: Expected spy fire to have been called.
        at &lt;Jasmine&gt;
        at http://localhost:4200/_karma_webpack_/src/app/modules/home/components/dashboard-details/dashboard-details.component.spec.ts:469:31
        at ZoneDelegate.invokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:399:1)
        at ProxyZoneSpec.push.QpwO.ProxyZoneSpec.onInvokeTask (http://localhost:4200/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:323:1)
</code></pre>
<p>If anyone can give a example or a explanation about what I'm doing wrong I would be grateful.
Thanks in advance</p>
",https://stackoverflow.com/questions/66834326/how-to-test-all-the-paths-of-this-function,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",58,False,-1,2
RestSharp AdvancedResponseWriter in Unit tests,"<p>I use <code>AdvancedResponseWriter</code>  as depicted <a href=""https://stackoverflow.com/questions/31443111/process-restsharp-response-as-a-stream-after-checking-the-response-status"">here</a> to save incoming stream in file. Code works fine:</p>
<pre><code>var request = new RestRequest(uri)
    .AddUrlSegment(&quot;drillingProgramId&quot;, session.DrillingProgramId);
request.Method = Method.GET;
request.AdvancedResponseWriter = (stream, response) =&gt;
{
    // Should be able to access response which is an IHttpResponse
    if (response.StatusCode != HttpStatusCode.OK) return;
    string tempFilePath = Path.GetTempPath() + session.SessionId;
    
    if (uri.EndsWith(&quot;initial&quot;)) tempFilePath += &quot;_initial&quot;;
    if (uri.EndsWith(&quot;nnb&quot;)) tempFilePath += &quot;_nnb&quot;;
    
    using var fileStream = File.Create(tempFilePath);
    stream.CopyTo(fileStream);
    filePathOne = tempFilePath;
};
await _download.ExecuteAsync(request);
</code></pre>
<p>But when I use <code>RestResponse</code> mock, action for <code>AdvancedResponseWriter</code> is not called. Here is code for mock:</p>
<pre><code>mock
    .Setup(m =&gt; m.ExecuteAsync(It.IsAny&lt;RestRequest&gt;(), It.IsAny&lt;CancellationToken&gt;()))
    .ReturnsAsync(() =&gt; new RestResponse 
    {
        Content = Guid.NewGuid().ToString(),
        StatusCode = HttpStatusCode.OK,
        RawBytes = Encoding.UTF8.GetBytes(&quot;gfgdfgdfgdfg&quot;)       
    });
</code></pre>
<p>I checked that response <code>Content</code>, <code>StatusCode</code> and <code>RawBytes</code> fields are filled, so my mock works. How to engage <code>AdvancedResponseWriter</code> with unit tests?</p>
<p><strong>UPDATE</strong></p>
<p>If I rewrite code without using stream and <code>AdvancedResponseWriter</code>, unit testing works as expected.</p>
<pre><code>var request = new RestRequest(uri)
    .AddUrlSegment(&quot;drillingProgramId&quot;, session.DrillingProgramId);
request.Method = Method.GET;              
var response = await _download.ExecuteAsync(request);

if (response.StatusCode != HttpStatusCode.OK) return filePathOne;
string tempFilePath = Path.GetTempPath() + session.SessionId;

if (uri.EndsWith(&quot;initial&quot;)) tempFilePath += &quot;_initial&quot;;
if (uri.EndsWith(&quot;nnb&quot;)) tempFilePath += &quot;_nnb&quot;;

await File.WriteAllTextAsync(tempFilePath,response.Content);
filePathOne = tempFilePath; 
</code></pre>
",https://stackoverflow.com/questions/69267045/restsharp-advancedresponsewriter-in-unit-tests,"['c#', 'unit-testing', 'moq', 'restsharp']",550,False,0,0
What to actually unit test in api resource in Java using Mockito?,"<p>I am new to unit testing and still not completely getting it.</p>
<p>Suppose I have a resource <code>/shop/:itemId</code> which calls a service and can throw various response codes like <code>ITEM_NOT_FOUND</code>, <code>SUCCESS</code>, <code>FAILURE</code>, INVALID_EMAIL etc.</p>
<p>I am confused in what should I actually mock and what to test for the api end point? It would be great if you can explain with any small example.</p>
",https://stackoverflow.com/questions/70005812/what-to-actually-unit-test-in-api-resource-in-java-using-mockito,"['java', 'unit-testing', 'mockito']",64,False,0,0
Unit Testing on Nginx custom Modules,"<p>I'd like to find a way to make unit testing on my custom nginx modules but failed. Could anyone provide some suggestions? I once found the Test::Nginx framework, but it works as system test. Some people told me that I can use ngx_lua_module to expose C function in nginx module by the way of FFI. Could anyone know how to do that?</p>
",https://stackoverflow.com/questions/68374844/unit-testing-on-nginx-custom-modules,"['unit-testing', 'nginx']",164,False,0,1
Is there a way to dynamically build a robot framework suite setup with multiple keywords?,"<p>I am building robot framework suites and tests dynamically for unit testing. We have a <code>Global Setup</code> that applies to all tests at the suite level. However, some sets of tests have additional setup that could also be applied at the suite level. Is there any built-in way to append more keywords to the suite setup?</p>
<p>I have something like this:</p>
<pre class=""lang-py prettyprint-override""><code>from robot.api import TestSuite

suite = TestSuite(&quot;Foo&quot;)
suite.setup.config(name=&quot;Global Setup&quot;)
# i want to then append to suite.setup based on some condition
if bar:
    # append more keywords to suite.setup
...
# add tests etc
...
result = suite.run(output=&quot;out.xml&quot;, loglevel=&quot;TRACE&quot;)
</code></pre>
",https://stackoverflow.com/questions/69575275/is-there-a-way-to-dynamically-build-a-robot-framework-suite-setup-with-multiple,"['python', 'robotframework']",201,False,0,1
Unit Testing TelemetryProcessor and TelemetryInitializer (Application Insights)?,"<p>I've been looking around the web for a way to unit test my processor and initializer. So far, I have the following code setup from another article, yet I'm a bit lost in how to proceed.</p>
<pre><code>public class TelemetryClientTests
{
    private TelemetryClient telemetryClient;
    private List&lt;ITelemetry&gt; sendItems;

    [TestInitialize]
    public void TestInit()
    {
        var httpContext = Substitute.For&lt;IHttpContextAccessor&gt;();
        var configuration = new TelemetryConfiguration();
        //this.sendItems = new List&lt;ITelemetry&gt;();
        configuration.TelemetryChannel = new RequeteTelemtry();
        configuration.InstrumentationKey = Guid.NewGuid().ToString();
        configuration.TelemetryInitializers.Add(new OperationCorrelationTelemetryInitializer());
        this.telemetryClient = new TelemetryClient(configuration);
    }

    /// &lt;summary&gt;
    /// Ensure that context being propagated via async/await.
    /// &lt;/summary&gt;
    [TestMethod]
    public void ContextPropogatesThruAsyncAwait()
    {
        var task = this.TestAsync();
        task.Wait();
    }
}
</code></pre>
<p>I'm not sure where I should add my telemtryprocessor so that Application Inisight knows that I'm unit testing it. If anybody knows how to do it, it would be greatly appreciated.</p>
",https://stackoverflow.com/questions/68292097/unit-testing-telemetryprocessor-and-telemetryinitializer-application-insights,"['unit-testing', 'azure-application-insights', 'open-telemetry']",1146,True,3,1
ERROR NullInjectorError: R3InjectorError(DynamicTestModule)[KDSDialogService -&gt; MatDialog -&gt; MatDialog]: NullInjectorError: No provider for MatDialog,"<p>I'm doing unit testing on my application. I'm new to testing, so I need your help.</p>
<p>In my application I make a service that uses MatDialog ( KDSDialogService).
I've tried putting many import alternatives, my service or matdialog as providers I have no idea what to do</p>
<pre><code>export declare class KDSDialogService {
    dialog: MatDialog;
    private dialogRef;
    constructor(dialog: MatDialog);
    open(componentOrTemplateRef: ComponentType&lt;any&gt; | TemplateRef&lt;any&gt;, title?: string, data?: any, size?: DialogSize, showClose?: boolean): MatDialogRef&lt;any, any&gt;;
    static ɵfac: ɵngcc0.ɵɵFactoryDef&lt;KDSDialogService, never&gt;;
}
</code></pre>
<p>And in my home.component.spec I import and make the declarations here, but I still get this error.</p>
<pre><code>describe('HomeComponent', () =&gt; {
   let component: HomeComponent;
   let fixture: ComponentFixture&lt;HomeComponent&gt;;

   beforeEach(async(() =&gt; {
      TestBed.configureTestingModule({
         declarations: [HomeComponent ],
         imports:[KDSDialogService, MatDialogModule],
  
      }).compileComponents();
   }));

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

   it('should create', () =&gt; {
      fixture.detectChanges();
      expect(component).toBeTruthy();
   });
});
</code></pre>
<p><a href=""https://i.stack.imgur.com/ysGCy.png"" rel=""nofollow noreferrer"">Print of the error</a></p>
",https://stackoverflow.com/questions/68682619/error-nullinjectorerror-r3injectorerrordynamictestmodulekdsdialogservice,"['angular', 'testing', 'jasmine', 'karma-runner']",3909,True,2,1
Jest Unit test case for React functional component Api call,"<p>I am new to Jest Unit testing. I need to write a test case for a React functional Component. Below is the code snippet for API call</p>
<pre><code>  useEffect(() =&gt; {
    getInitialData(props.id, props.baseUrl).then((response: any) =&gt; {
      setInitialResponse(response.initialResponse);
      if (props.initialData) props.initialData(response.initialResponse);
      setLoader(false);
    });
  }, []);
</code></pre>
<p>I don't know how to cover these lines in the jest test case. Passing id and baseUrl to this component, not covering lines after 'then'. I don't know How can I mock this also as it is present inside <code>useEffect</code>.</p>
",https://stackoverflow.com/questions/70487315/jest-unit-test-case-for-react-functional-component-api-call,"['reactjs', 'jestjs', 'react-typescript']",1894,True,2,2
JUnit5 Test coverage for catch block of a Spring Boot Controller,"<p>I am trying to write test for my controller with the code below. I want to cover the test for the code in the catch block statement but I'm not able to write one. I want to return a Server Response with failure code and message in the catch block.</p>
<pre class=""lang-java prettyprint-override""><code>@PostMapping(COUNTERS)
public ResponseEntity&lt;?&gt; getCounters(@Valid @RequestBody ApartmentCounterListRequest requestData) {
    try {
        log.debug(&quot;Entering API for counter list&quot;);
        ApartmentCounterListResponse apartmentCounterListResponse = counterService.getAllCounters();
        return ResponseEntity.ok(apartmentCounterListResponse);
    } catch (Exception exception) {
        log.error(&quot;Exception in counter list :: &quot;, exception);
        ServerResponse serverResponse = ResponseBuilder.buildVendorFailureMessage(new ServerResponse(),
                RequestResponseCode.EXCEPTION);
        return ResponseEntity.ok(JsonResponseBuilder.enquiryResponse(serverResponse));
    }
}
</code></pre>
<p>My test code is as follows:</p>
<pre class=""lang-java prettyprint-override""><code>@Test
@DisplayName(&quot;Should return ServerResponse with failure data.&quot;)
void Should_Return_Server_Response_On_Exception() throws Exception {

    /*given*/
    ApartmentCounterListRequest apartmentCounterListRequest = ApartmentTestUtil.getApartmentCounterListRequest.
            apply(&quot;test&quot;, &quot;test&quot;);
    Mockito.when(counterServic.getAllCounters()).thenThrow(new Exception());
//        ServerResponse serverResponse = ApartmentTestUtil.getServerExceptionServerResponse.get();

    /*then*/
    mockMvc.perform(
            post(COUNTER_URL)
                    .contentType(APPLICATION_JSON)
                    .content(objectMapper.writeValueAsString(apartmentCounterListRequest)))
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath(&quot;$.resultCode&quot;, Matchers.is(&quot;-6&quot;)));
    verify(counterService, times(1)).getAllCounters();
}
</code></pre>
<p>When I run this test I am getting the following error:</p>
<pre><code>org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: java.lang.Exception
</code></pre>
<p>I have gone through some of the following posts but haven't found a suitable answer yet.</p>
<p><a href=""https://stackoverflow.com/questions/43019566/unit-testing-code-in-catch-block-of-a-spring-controller"">Unit testing code in catch block of a Spring Controller</a></p>
<p><a href=""https://stackoverflow.com/questions/51003098/java-how-to-test-catch-block"">Java - How to Test Catch Block?</a></p>
<p><a href=""https://stackoverflow.com/questions/43019566/unit-testing-code-in-catch-block-of-a-spring-controller"">Unit testing code in catch block of a Spring Controller</a></p>
<p><a href=""https://stackoverflow.com/questions/42508323/junit-for-both-try-and-catch-block-coverage"">JUnit for both try and catch block coverage</a></p>
<p>Can anyone help me write test that covers the catch block or tell me the way to do it?</p>
<p>I have this try catch in my controller to handle any unexpected exceptions. And for different api's I have to send a response with different response code and messages which doesnot allow me to use Exception handler.</p>
",https://stackoverflow.com/questions/67614851/junit5-test-coverage-for-catch-block-of-a-spring-boot-controller,"['java', 'spring-boot', 'unit-testing', 'mockito', 'junit5']",1391,True,3,2
How to mock a slice pipe in angular,"<p><em>I am trying to write test cases for a component that uses a slice pipe. I checked several links telling how to mock a pipe for component unit testing. Here issue is that it is an inbuilt pipe so I don't know how tranform method will be.</em></p>
<pre><code>         &lt;tr *ngFor=&quot;let item of filteredUsers  |slice: (page-1) * pageSize : page * pageSize | searchFilter:searchText
            &quot;&gt;
                &lt;td&gt;&lt;input type=&quot;checkbox&quot; (change)=&quot;onChange(item.id, $event.target.checked)&quot;&gt;&lt;/td&gt;
                &lt;td&gt;{{item.firstName}}&lt;/td&gt;
                &lt;td&gt;{{item.surname}}&lt;/td&gt;
                &lt;td&gt;{{item.phoneNumber}}&lt;/td&gt;
                &lt;td&gt;{{item.email}}&lt;/td&gt;
                &lt;td&gt;{{item.grossIncome}}&lt;/td&gt;
                &lt;!-- &lt;td&gt;{{item.createdDate | date: 'dd/MM/yyyy' }} &lt;/td&gt; --&gt;

            &lt;/tr&gt;
</code></pre>
<p><strong>Code for spec</strong></p>
<pre><code>  describe('fetchUserList()',()=&gt;{
    it('should get list of users from notification service',()=&gt;{
  // component.pageSize=10;
 
  component.pageOptions=[10,20,50,100];
  notificationServiceSpy.fetchUserList.and.returnValue(of({}))
  fixture.detectChanges();
  expect(component.userList.length).toBe(0);
  expect(component.userList).toEqual(component.filteredUsers);
  expect(component.userCountLogs.length).toBe(0);
  expect(notificationServiceSpy.fetchUserList).toHaveBeenCalled();
})
</code></pre>
<p><strong>Here is the code for ngOnit hook</strong></p>
<pre><code> ngOnInit() {
this.pageOptions=[10,20,50,100];
this.pageSize=this.pageOptions[0];
this.userMappingForm = this.formBuilder.group({
  topicId: ['', Validators.required],
  users: this.formBuilder.array([])
});

 this.fetchNotificationTopic();
 this.fetchUserList();
}
</code></pre>
<p><strong>Here is the code for fetching user's list</strong></p>
<pre><code>fetchUserList() {
this.topicList = [];
this.notificationService.fetchUserList(null).subscribe((data: any) =&gt; {
  if (data) {
     this.userList =this.filteredUsers= data;

    this.userCountLogs = data.length;
  }

}, (err: HttpErrorResponse) =&gt; {

});

}
</code></pre>
<p><a href=""https://i.stack.imgur.com/FsDjH.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/FsDjH.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/69990105/how-to-mock-a-slice-pipe-in-angular,"['angular', 'unit-testing', 'jasmine']",304,False,2,0
Eclipse Maven project facade,"<p>I had a dynamic web project which I configured to use Maven. Now I am trying to run unit testing the login servlet(with JUnit, without spring), but eclipse always gives me the same error when I try to run the test case. The error is: 'An internal error occurred during: &quot;Launching LoginPatientTest&quot;.
Cannot invoke &quot;org.eclipse.m2e.core.project.IMavenProjectFacade.getMavenProject (org.eclipse.core.runtime.IProgressMonitor)&quot; because &quot;facade&quot; is null'.
My test case is :</p>
<pre><code>package control;

import static org.mockito.Mockito.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import model.ProfileManager;
import model.Bean.PatientBean;

public class LoginPatientTest {

    String fiscal_code;
    String user_password;
    
    @Before
    public void setUp() throws Exception {
        fiscal_code = &quot;aaaaaaa&quot;;
        user_password = &quot;bbbbb&quot;;
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testPresent() throws IOException, ServletException{
           HttpServletRequest req = mock(HttpServletRequest.class);
           HttpServletResponse res = mock(HttpServletResponse.class);
           HttpSession session = mock(HttpSession.class);
           when(req.getSession()).thenReturn(session);
           ProfileManager pm = mock(ProfileManager.class);
           when(pm.ReturnPatientByKey(fiscal_code, user_password)).thenReturn(new PatientBean());
           LoginPatient servlet = new LoginPatient();
           servlet.doPost(req, res);
        }

}

</code></pre>
",https://stackoverflow.com/questions/65978396/eclipse-maven-project-facade,"['java', 'eclipse', 'maven']",2712,False,2,1
Return a bool or string inside a Callback in NodeJS,"<p>I am writing Unit Testing which require me to hit the exceptions. Incase of promises, I cannot really send any boolean or string values. My intended output and the one I am getting is mentioned below.</p>
<pre><code>function mainFunction(registry, name,....){
    justAnotherPromiseFunction(name, function (err, twin) {
        if (err) {          
            return &quot;I want to return a failure message here!&quot;;
        } else {
            &lt;MyLogic Goes Here&gt;
        }
    });
}
console.log(mainFunction(registry, name,....));
</code></pre>
<p>This returns <code>Promise { &lt;rejected&gt; [ArgumentError: The connection string is missing the property: Something] }</code>.</p>
<p>Instead of <code>I want to return a failure message here!</code>.</p>
<p>Any ideas on how I can manage to do this?</p>
<p>Edit: I am implementing a function from azure sdk that uses promises.
So looks like this:</p>
<pre><code>function mainFunction(){
    registry.getTwin(name, function (err, twin) {
        if (err) {          
            return &quot;I want to return a failure message here!&quot;;
        } else {
            &lt;My Business Logic Goes Here&gt;
        }
    });
}
console.log(mainFunction());
</code></pre>
",https://stackoverflow.com/questions/66162355/return-a-bool-or-string-inside-a-callback-in-nodejs,"['javascript', 'node.js', 'promise']",134,True,1,1
How to write unit tests for a Slack Bolt application?,"<p>I'm attempting to transition an app from the hubot library to the official @slack/bolt library.  The app uses hubot-test-helper for unit testing, which mocks out a chatroom.  Is there anything equivalent for the bolt library?</p>
<p>Yes, most of the logic can be (and in many cases is) split away from the actual chat implementation; the exception being middleware which I believe still benefits from testing closer to integration.</p>
",https://stackoverflow.com/questions/67926835/how-to-write-unit-tests-for-a-slack-bolt-application,"['unit-testing', 'slack']",391,False,4,0
jest.fn() does not cover line of code written inside the mock function,"<p>I have the following function and inside it a self invoke highcharts function.
I want to unit test this function with help of jest.fn() but it does not cover all lines mentioned inside the main function. Following is the actual funciton.</p>
<pre><code>highChartsExtensionToReachZero() {
(function (H: any) {
  H.addEvent(H.Axis, 'afterInit', function () {
    const logarithmic = this.logarithmic;

    if (logarithmic &amp;&amp; this.options.custom.allowNegativeLog) {

      // Avoid errors on negative numbers on a log axis
      this.positiveValuesOnly = false;

      // Override the converter functions
      logarithmic.log2lin = num =&gt; {
        const isNegative = num &lt; 0;

        let adjustedNum = Math.abs(num);

        if (adjustedNum &lt; 10) {
          adjustedNum += (10 - adjustedNum) / 10;
        }

        const result = Math.log(adjustedNum) / Math.LN10;
        return isNegative ? -result : result;
      };

      logarithmic.lin2log = num =&gt; {
        const isNegative = num &lt; 0;

        let result = Math.pow(10, Math.abs(num));
        if (result &lt; 10) {
          result = (10 * (result - 1)) / (10 - 1);
        }
        return isNegative ? -result : result;
      };
    }
  });
}(Highcharts));
</code></pre>
<p>}</p>
<p>The following is the jest code was written to mock and cover unit testing for the above code.</p>
<pre><code>component.highChartsExtensionToReachZero = jest.fn();
component.highChartsExtensionToReachZero();
expect(component.highChartsExtensionToReachZero).toBeCalled();
</code></pre>
<p>Thanks in advance for the help.</p>
",https://stackoverflow.com/questions/65584608/jest-fn-does-not-cover-line-of-code-written-inside-the-mock-function,"['angular', 'highcharts', 'jestjs']",153,False,1,0
In MochaJS: How to run asynchronous tests sequentially?,"<p>I'm using the <a href=""https://mochajs.org/"" rel=""nofollow noreferrer"">MochaJS</a> framework for unit testing NodeJS code.</p>
<p>The tests look like this:</p>
<pre><code>import 'mocha';
import { assert } from 'chai';
import { describe } from 'mocha';

describe('Test Suite', () =&gt; {
    function execute(testData: string) {
        it('Individual Test', async function() {
            // await some asynchronous call using testData
            // do some asserts
        });
    }

    const testData: string[] = [&quot;test 1&quot;, &quot;test 2&quot;, &quot;test 3&quot;];

    for (const data: string of testData) {
        execute(data);
    }
});
</code></pre>
<p>It turns out that multiple tests (named 'Individual Test') will run in parallel. Is there any way to await each test so that it completes before the next one starts? I do not want to declare individual tests for each of the <code>testData</code> items, since that would be a lot of copy/paste.</p>
",https://stackoverflow.com/questions/66991580/in-mochajs-how-to-run-asynchronous-tests-sequentially,"['node.js', 'mocha.js', 'chai']",560,True,1,1
ReflectionTestUtils - Setting field of type [null] on target object,"<p>I am new with Unit testing and Mockito. I'm trying to write tests for my Dao class:</p>
<pre><code>@Repository
@NoArgsConstructor
public class UserDaoImpl implements UserDao {
    
    private NamedParameterJdbcTemplate template;
    
    @Value(&quot;${users.find.by_id}&quot;)
    private String findByIdQuery;
    
    private RowMapper&lt;User&gt; rowMapper = (rs, rowNum) -&gt; {
        User user = new User();
        user.setId(rs.getInt(&quot;id&quot;));
        user.setFirstName(rs.getString(&quot;firstname&quot;));
        user.setLastName(rs.getString(&quot;lastname&quot;));
        user.setEmail(rs.getString(&quot;email&quot;));
        user.setPassword(rs.getString(&quot;password&quot;));
        user.setEnabled(rs.getBoolean(&quot;enabled&quot;));
        return user;
    };

    public UserDaoImpl(NamedParameterJdbcTemplate template) {
        super();
        this.template = template;
    }

    @Override
    public Optional&lt;User&gt; findById(int id) {
        SqlParameterSource param = new MapSqlParameterSource(&quot;id&quot;, id);
        User user = null;
        try {
            user = template.queryForObject(findByIdQuery, param, BeanPropertyRowMapper.newInstance(User.class));
        } catch (DataAccessException ex) {
            ex.printStackTrace();
        }
        return Optional.ofNullable(user);
    }
}
</code></pre>
<p>In my simple test I simply added @Mock anotation for my <em>NamedParameterJdbcTemplate</em>, and trying to put it into the <em>UserDaoImpl</em>:</p>
<pre><code>public class UserDaoTest {
    
    @Mock
    public NamedParameterJdbcTemplate template;
    @InjectMocks
    public UserDao userDao;
    
    @Test
    public void findByIdTest() {
        template = new NamedParameterJdbcTemplate(new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript(&quot;classpath:db/schema.sql&quot;)
                .addScript(&quot;classpath:db/test-data.sql&quot;)
                .build());
        userDao = new UserDaoImpl();
        ReflectionTestUtils.setField(userDao, &quot;template&quot;, template);
        Mockito.when(userDao.findById(1).get().getEmail()).thenReturn(&quot;Keanu@gmail.com&quot;);
        
        User user = userDao.findById(1).get();
        assertNotNull(user);
        assertEquals(&quot;Keanu@gmail.com&quot;, user.getEmail());
    }
}
</code></pre>
<p>Each time I run the test, I get <strong>java.lang.NullPointerException</strong> for the field <em>template</em>. Cant find what is the correct way of implementing the test.</p>
<p>Here is my pom.xml:</p>
<pre><code>&lt;parent&gt;
        &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
        &lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;
        &lt;version&gt;2.6.0&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
&lt;properties&gt;
    &lt;java.version&gt;11&lt;/java.version&gt;
&lt;/properties&gt;
...
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
    &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
    &lt;scope&gt;test&lt;/scope&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.liquibase&lt;/groupId&gt;
    &lt;artifactId&gt;liquibase-core&lt;/artifactId&gt;
&lt;/dependency&gt;
&lt;dependency&gt;
    &lt;groupId&gt;org.springframework.security&lt;/groupId&gt;
    &lt;artifactId&gt;spring-security-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;/dependency&gt;
</code></pre>
",https://stackoverflow.com/questions/70226215/reflectiontestutils-setting-field-of-type-null-on-target-object,"['java', 'unit-testing', 'mockito']",6517,True,1,1
Second function in unit testing isn&#39;t running,"<p>I am doing this simple unittesting and I am a newbie to python.  Heres the code</p>
<pre><code>caplet.py
    
def capeach(text):
        return text.capitalize()
</code></pre>
<p>and the unit testing code is below.</p>
<pre><code>UT.py

import unittest
import caplet


class TestCap(unittest.TestCase):
    
    def test_one_word(self):
        text = 'python'
        result = caplet.capeach(text)
        self.assertEqual(result,'Python')

    def multiple_words(self):
        text = 'python is good'
        result = caplet.capeach(text)
        self.assertEqual(result,'Python Is Good')


if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>When I run <code>UT.py</code>, I get <code>Ran 1 test in 0.001s</code>. Somehow second part of the code <code>multiple_words</code> is not running.</p>
<p>I am using Spyder IDE for running the code.  I also tried with the command line <code>python3 UT.py</code></p>
<p>I don't know what I am missing. Can anyone help. Thank you.</p>
",https://stackoverflow.com/questions/68486279/second-function-in-unit-testing-isnt-running,"['python-3.x', 'unit-testing']",22,False,1,0
How to use mockk in view binding,"<p>Hi i am new in Mockk library Kotlin. I want to mock view binding in unit testing. But i am unable to get proper example. I search <a href=""https://stackoverflow.com/questions/60965983/possible-to-mock-test-android-viewbinding-interactions"">Possible to mock/test Android ViewBinding interactions?
</a> I don't want to use <strong>@RunWith(PowerMockRunner::class)</strong>. Does any one have better solution for this.</p>
<p>After @Eddie reply i tried my basic code.</p>
<pre><code>class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setText()
    }

    internal fun setText() {
        binding.test.text = &quot;shh&quot;
    }
}
</code></pre>
<p>Test class</p>
<pre><code>class MainActivityTest {

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

    private lateinit var mainActivity: MainActivity

    @MockK
    private lateinit var mainBinding: ActivityMainBinding

    @Before
    fun setUp() {
        MockKAnnotations.init(this, relaxed = true)
        mockkStatic(ActivityMainBinding::class)
        mainActivity = spyk(MainActivity())
    }

    @Test
    fun `setupText - set text`() {
        verify { mainBinding.test.text = &quot;2&quot; }
        mainActivity.setText()
    }
}
</code></pre>
<p>I am getting this error</p>
<pre><code>java.lang.NullPointerException
    at com.example.test.MainActivityTest$setupText - set text$1.invoke(MainActivityTest.kt:34)
    at com.example.test.MainActivityTest$setupText - set text$1.invoke(MainActivityTest.kt:34)
    at io.mockk.impl.eval.RecordedBlockEvaluator$record$block$1.invoke(RecordedBlockEvaluator.kt:24)
    at io.mockk.impl.eval.RecordedBlockEvaluator$enhanceWithRethrow$1.invoke(RecordedBlockEvaluator.kt:74)
    at io.mockk.impl.recording.JvmAutoHinter.autoHint(JvmAutoHinter.kt:23)
    at io.mockk.impl.eval.RecordedBlockEvaluator.record(RecordedBlockEvaluator.kt:36)
    at io.mockk.impl.eval.VerifyBlockEvaluator.verify(VerifyBlockEvaluator.kt:30)
    at io.mockk.MockKDsl.internalVerify(API.kt:118)
    at io.mockk.MockKKt.verify(MockK.kt:149)
    at io.mockk.MockKKt.verify$default(MockK.kt:146)
    at com.example.test.MainActivityTest.setupText - set text(MainActivityTest.kt:34)
    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.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:61)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
</code></pre>
",https://stackoverflow.com/questions/67928482/how-to-use-mockk-in-view-binding,"['android', 'kotlin', 'mockk', 'mockk-verify']",1904,False,1,0
Infinispan Junit 5: CacheConfigurationException: ISPN000501: Cannot persist cache configuration as global state is disabled,"<p>Using below code block I am able to create a infinispan test factory using Junit5 fraemwork.</p>
<pre><code>{

     TestResourceTracker.setThreadTestName(&quot;InfinispanServer&quot;);
     ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
     EmbeddedCacheManager ecm = TestCacheManagerFactory.createCacheManager(
           new GlobalConfigurationBuilder().nonClusteredDefault().defaultCacheName(&quot;default&quot;),
           configurationBuilder);

     HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder();
     serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler());
     hotRodServer = HotRodTestingUtil.startHotRodServer(ecm, host, port, serverBuilder);
}
</code></pre>
<p>When I access infinispan using the host and port for unit testing getting below exception, what could be the problem:</p>
<blockquote>
<p>Caused by:
org.infinispan.client.hotrod.exceptions.HotRodClientException:
org.infinispan.commons.CacheConfigurationException: ISPN000501: Cannot
persist cache configuration as global state is disabled</p>
</blockquote>
<p>-- This piece of code works well with Infinispan 9.4.15 version. Getting exception in Infinispan 11.0.4 version.</p>
",https://stackoverflow.com/questions/65770090/infinispan-junit-5-cacheconfigurationexception-ispn000501-cannot-persist-cach,"['java', 'infinispan']",752,True,1,1
"jest unit tests failing, setData does not seem to be working","<p>I'm trying to learn unit testing my vue application with jest by following a tutorial. I set up this component called AppHeader containing a button that is only visible when the variable &quot;loggedIn&quot; is true.</p>
<p>In order to set the value &quot;loggedIn&quot; to true, I use .setData to change its value. Am i using setData incorrectly or is there something else going on?</p>
<p>AppHeader:</p>
<pre><code>&lt;template&gt;
  &lt;div&gt;
    &lt;button v-show=&quot;loggedIn&quot;&gt;Logout&lt;/button&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  data() {
    return {
      loggedIn: false,
    };
  },
};
&lt;/script&gt;
</code></pre>
<p>AppHeader.spec.js:</p>
<pre><code>import AppHeader from &quot;@/components/AppHeader.vue&quot;;
import { mount } from &quot;@vue/test-utils&quot;;

describe(&quot;AppHeader&quot;, () =&gt; {
  test(&quot;hide button when user is logged off&quot;, () =&gt; {
    const wrapper = mount(AppHeader);
    expect(wrapper.find(&quot;button&quot;).isVisible()).toBe(false);
  });

  test(&quot;show button when user is logged in&quot;, () =&gt; {
    const wrapper = mount(AppHeader);
    wrapper.setData({ loggedIn: true });
    expect(wrapper.find(&quot;button&quot;).isVisible()).toBe(true);
  });
});
</code></pre>
<p>output:</p>
<pre><code> FAIL  tests/unit/AppHeader.spec.js
  AppHeader
    √ hide button when user is logged off (23ms)
    × show button when user is logged in (7ms)

  ● AppHeader › show button when user is logged in

    expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

      11 |     const wrapper = mount(AppHeader);
      12 |     wrapper.setData({ loggedIn: true });
    &gt; 13 |     expect(wrapper.find(&quot;button&quot;).isVisible()).toBe(true);
         |                                                ^
      14 |   });
      15 | });
      16 |

      at Object.&lt;anonymous&gt; (tests/unit/AppHeader.spec.js:13:48)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        2.85s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! music_gym@0.1.0 test:unit: `vue-cli-service test:unit`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the music_gym@0.1.0 test:unit 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\HP\AppData\Roaming\npm-cache\_logs\2021-10-25T10_35_11_082Z-debug.log
</code></pre>
",https://stackoverflow.com/questions/69706591/jest-unit-tests-failing-setdata-does-not-seem-to-be-working,"['node.js', 'vue.js', 'jestjs']",901,True,1,1
How can i mock configparser.ConfigParser read method in python,"<p>I am working with python and new to it. i am trying to write unit tests for my class method where we are using configparse to fetch the config file details located at specific path.</p>
<p>While doing unit testing its giving me an error as KeyError for &lt;configparser.ConfigParser object at 0x000001E8AEBC1F40&gt;</p>
<p><a href=""https://i.stack.imgur.com/Mt0cU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Mt0cU.png"" alt=""snapshot of error"" /></a></p>
<p>the code for configparser is like</p>
<pre><code> algor_conf = configparser.ConfigParser()
 self.algor_conf.read('./path')
 self.algor_conf['DynamicProgramingParamaters']['wealth_state_total']
</code></pre>
<p>Can anyone please help me to mock this</p>
",https://stackoverflow.com/questions/68864769/how-can-i-mock-configparser-configparser-read-method-in-python,"['python', 'python-3.x', 'unit-testing', 'mocking', 'pytest']",1508,True,1,1
Jest mocking request.res.setHeader always return error - not a function,"<p>My login method using request.res.setHeader() to return refresh token info in header, in unit test, I try to mock this function, but always got error - &quot;TypeError: request.res.setHeader is not a function&quot;, if I remove this request.res.setHeader(...) line, test passed. Following is my mocking script for request:</p>
<pre><code>export const mockRequest = {
  user: readerStub(),
  res: jest.fn().mockImplementation(() =&gt; {
    return { setHeader: jest.fn() };
  }),
};
</code></pre>
<p>Can anyone tell what is the problem here?</p>
<p>Complete login unit is here</p>
<pre><code>async login(request) {
    const readerID = request.user._id;
    const accessToken = this.getJwtAccessToken(readerID);
    const refreshToken = this.getCookieJwtRefreshToken(readerID);
    await this.setRefreshToken(refreshToken[1], readerID);
    request.res.setHeader('Set-Cookie', refreshToken[0]);
    //create the log for success activity
    this.logger.info(`Success login for reader ${request.user.username}`);
    return {
      token_info: accessToken,
      expireIn: process.env.ACCESS_TOKEN_TIMER,
    };
  }
</code></pre>
<p>The unit testing code is here</p>
<pre><code>describe('login', () =&gt; {
    describe('when login is called', () =&gt; {
      let token: TAccessToken;

      beforeEach(async () =&gt; {
        jest
          .spyOn(readerService, 'getJwtAccessToken')
          .mockImplementationOnce(() =&gt; accessTokenStub().token_info);
        jest
          .spyOn(readerService, 'getCookieJwtRefreshToken')
          .mockImplementationOnce(() =&gt; {
            return [
              refreshTokenStub().refreshToken_Cookie,
              refreshTokenStub().refreshToken,
            ];
          });
        jest
          .spyOn(readerService, 'setRefreshToken')
          .mockImplementationOnce(async () =&gt; Promise.resolve('OK'));
        token = await readerService.login(mockRequest);
      });

      test('then it should call setRefreshToken', () =&gt; {
        expect(readerService.setRefreshToken).toHaveBeenCalledWith(
          refreshTokenStub().refreshToken,
          readerStub()._id,
        );
      });

      test('then it should return a access token in body', () =&gt; {
        expect(token).toEqual(accessTokenStub());
      });
    });
  });
</code></pre>
",https://stackoverflow.com/questions/68446787/jest-mocking-request-res-setheader-always-return-error-not-a-function,"['unit-testing', 'testing', 'jestjs', 'mocking', 'nestjs']",1217,True,1,1
React snapshot testing - react-test-renderer vs. react-testing-library,"<p>I am trying to do snapshot testing in my React app. I am already using react-testing-library for unit testing in general. However for snapshot testing I have seen different ways of doing it on the net, either using react-test-renderer or react-testing library. Here are 3 examples, what is the difference between them and what is preferred?</p>
<p><strong>1. Using react-test-renderer</strong></p>
<pre><code>test('renders correctly', () =&gt; {
  const tree = renderer
    .create(&lt;Link page=&quot;http://www.facebook.com&quot;&gt;Facebook&lt;/Link&gt;)
    .toJSON();
  expect(tree).toMatchSnapshot();
});
</code></pre>
<p><strong>2. Using react-testing-library and asFragment()</strong></p>
<pre><code>test('renders correctly', () =&gt; {
  const { asFragment } = render(&lt;NotFound /&gt;);
  expect(asFragment()).toMatchSnapshot();
});
</code></pre>
<p><strong>3. Using react-testing-library and container</strong></p>
<pre><code>test('renders the component', () =&gt; {
  const container = render(&lt;Component /&gt;)
  expect(container.firstChild).toMatchSnapshot()
})
</code></pre>
",https://stackoverflow.com/questions/66362759/react-snapshot-testing-react-test-renderer-vs-react-testing-library,"['react-testing-library', 'react-test-renderer']",3101,True,12,1
How to debug unit test while developping a package in Julia,"<p>Say I develop a package with a limited set of dependencies (for example, LinearAlgebra).
In the Unit testing part, I might need additional dependencies (for instance, CSV to load a file). I can configure that in the <code>Project.toml</code> all good.</p>
<p>Now from there and in VS Code, how can I debug the Unit tests? I tried running the &quot;runtests.jl&quot; in the debugger; however, it unsurprisingly complains that the CSV package is unavailable.</p>
<p>I could add the CSV package (as a temporary solution), but I would prefer that the debugger run with the configuration for the unit testing; how can I achieve that?</p>
<p>As requested, here is how it can be reproduced (it is not quite minimal, but instead I used a commonly used package as it give confidence the package is not the problem). We will use DataFrames and try to execute the debugger for its unit tests.</p>
<ul>
<li>Make a local version of <code>DataFrames</code> for the purpose of developing a feature in it. I execute <code>dev DataFrames</code> in a new REPL.</li>
<li>Select the correct environment (in <code>.julia/dev/DataFrames</code>) through the VS-code user interface.</li>
<li>Execute the &quot;proper&quot; unit testing by executing <code>test DataFrames</code> at the pkg prompt. Everything should go smoothly.</li>
<li>Try to execute the tests directly (open the <code>runtests.jl</code> and use the &quot;Run&quot; button in vs-code). I see some errors of the type:</li>
</ul>
<pre><code>LoadError: ArgumentError: Package CategoricalArrays not found in current path:
- Run `import Pkg; Pkg.add(&quot;CategoricalArrays&quot;)` to install the CategoricalArrays package.
</code></pre>
<p>which is consistent with CategoricalArrays being present in the <code>[extras]</code> section of the Project.toml but not present in the <code>[deps]</code>.</p>
<ul>
<li>Finally, instead of the &quot;Run&quot; command, execute the &quot;Run and Debug&quot;. I encounter similar errors here is the first one:</li>
</ul>
<pre><code>Test Summary: | Pass  Total
merge         |   19     19
        PASSED: index.jl
        FAILED: dataframe.jl
LoadError: ArgumentError: Package DataStructures not found in current path:
- Run `import Pkg; Pkg.add(&quot;DataStructures&quot;)` to install the DataStructures package.
</code></pre>
<p>So I can't debug the code after the part requiring the extras packages.</p>
<ul>
<li>After all that I delete this package with the command <code>free DataFrames</code> at the pkg prompt.</li>
</ul>
<p>I see the same behavior in my package.</p>
",https://stackoverflow.com/questions/69134046/how-to-debug-unit-test-while-developping-a-package-in-julia,"['visual-studio-code', 'julia']",473,True,3,2
dependency inversion for data class(classes that define the structure of certain type),"<p>So I have this data class:</p>
<pre><code>    public class RecentProject
    {
    public string ProjectName { get; set; }

    public string ProjectPath { get; set; }

    public DateTime CreationDate { get; set; }

    public string OutputFolder { set; get; } = &quot;&quot;;
    }
</code></pre>
<p>It just defines the properties of the recent project, and I wanted to apply dependency inversion so I extracted an interface from the class:</p>
<pre><code>    public interface IRecentProject
   {
    DateTime CreationDate { get; set; }
    string OutputFolder { get; set; }
    string ProjectName { get; set; }
    string ProjectPath { get; set; }
    }
</code></pre>
<p>then I made an ioc container(inversion of control) and registered the class type as the interface:</p>
<pre><code>Mvx.IoCProvider.RegisterType&lt;IRecentProject, RecentProject&gt;();
</code></pre>
<p>so anywhere in my app when I want to create a recent project I just use:</p>
<pre><code>Mvx.IoCProvider.Resolve&lt;IRecentProject&gt;();
</code></pre>
<p>but after I did this I ran into some problems that would be hard to solve with the current setup so I thought that maybe this is not the correct way to apply dependency inversion in this class because none of the dependency inversion benefits would apply like:</p>
<ul>
<li>unit testing: as I will not be unit testing a data class</li>
<li>The ability to change the class implementation: as any changes in the class will require a change in the interface to be able to use the new features added</li>
</ul>
<p>So what should I do, I have searched a lot on this topic and could not find a clear answer,<br>
please help and thanks in advance.</p>
",https://stackoverflow.com/questions/66720969/dependency-inversion-for-data-classclasses-that-define-the-structure-of-certain,"['c#', '.net', 'inversion-of-control', 'dependency-inversion']",72,True,1,1
Unittest for a function throws an exception in Python,"<pre><code>class Kill_Tasks:
   def __init__(self):
      self.action = None
      self.cmd=[]
   def kill_tasks(self):
      self.action = False
      #exp task = chrome.exe
      target = 'chrome.exe'
      try:
         self.cmd = suprocess.run(['taskkill','/im', target,'/f'],capture_output=True, check=True)
         self.action = True
      except subprocess.CalledProcessError as e:
         print(e)
         self.action = False
      return self.cmd
</code></pre>
<p>Unit Test for a function throws an exception in Python.
The question is: how can I do the Unit Testing for the exception part. I'm doing Code Coverage for this function. But I am not able to check the exception because it's always True. Do I need to do a fake connection to be able to test the exception? Please help me out! Thanks</p>
",https://stackoverflow.com/questions/66848842/unittest-for-a-function-throws-an-exception-in-python,"['python-3.x', 'unit-testing', 'subprocess', 'code-coverage', 'python-unittest']",750,False,0,1
Unit testing for React JS,"<p>I have a component of buttons..</p>
<pre><code>export default class ButtonAction extends Component {

  render() {

    const { id, disabled, onClose, onSave, onRemove, isDelete } = this.props;

    return (

      &lt;div className=&quot;footer&quot;&gt;
        &lt;div className=&quot;button-container&quot;&gt;
          &lt;button data-testid=&quot;cancel&quot; onClick={() =&gt; onClose()}&gt; Cancel &lt;/button&gt;
          {
            isDelete
              ? &lt;button data-testid=&quot;remove&quot; disabled={!disabled} onClick={() =&gt; onRemove()} className='primary'&gt; Yes &lt;/button&gt;
              : &lt;button data-testid=&quot;save&quot; disabled={!disabled} onClick={() =&gt; onSave()} className={disabled ? 'primary' : 'disabled'}&gt; { id ? 'Update' : 'Save' } &lt;/button&gt;
          }
        &lt;/div&gt;
      &lt;/div&gt;
    )
  }
}
</code></pre>
<p>This is how I have made components. I am trying to do unit testing but test case does not pass..</p>
<pre><code>test(&quot;id exists&quot;, () =&gt; {
  const { getByTestId } = render(&lt;ButtonAction id={''} isDelete={false} /&gt;);
  expect(getByTestId('cancel')).toBeTruthy();
});

test(&quot;delete button exists&quot;, () =&gt; {
  const { getByTestId } = render(&lt;ButtonAction id={'remove'} isDelete={true} /&gt;);

  expect(getByTestId('cancel').textContent).toBe(' Yes ')
});

test('save button exists', () =&gt; {
  const { getByTestId } = render(&lt;ButtonAction id={''} isDelete={false} /&gt;)

  expect(getByTestId('save').textContent).toBe(' Save ')
})

test('calling render with the same component on the same container does not remount', () =&gt; {
  const { getByTestId } = render(&lt;ButtonAction id={'1'} isDelete={false} /&gt;)

  expect(getByTestId('save').textContent).toBe(' Update ')
})
</code></pre>
<p>This my unit test case.. None of my test case pass.. i HAVE REFERED MY other sources but couldn't help. I am new to react.. please help me to resolve this..</p>
<pre><code>The error below may be caused by using the wrong test environment, see jestjs.io/docs/configuration#testenvironment-string. Consider using the &quot;jsdom&quot; test environment. ReferenceError: document is not defined
</code></pre>
<p>This is the error I am getting</p>
",https://stackoverflow.com/questions/68888477/unit-testing-for-react-js,"['javascript', 'reactjs', 'unit-testing', 'react-testing-library']",297,True,0,1
Write unit test for a method in a component in Vue with Jest,"<p>I'm starting with unit testing with Jest Vue. I want to test an existing method in a Vue component, I write a test but it does not pass. And I do not have any idea how to mock and call that method in test.</p>
<p>How can I write a good unit test, to pass the functionality of 'goPage()' method?</p>
<p>My method is:</p>
<pre><code>goPage(id, name, categoryId) {
   this.headerSearchInput = name
   this.$router.push({
      path: '/categories/' + categoryId + '/courses/' + id,
      query: { query: this.headerSearchInput },
   })
}
</code></pre>
<p>My test is:</p>
<pre><code>import { shallowMount, createLocalVue } from '@vue/test-utils'
import HeaderSearch from '../../components/header/HeaderSearch.vue'

const localVue = createLocalVue()
localVue.use(VueRouter)
const router = new VueRouter()

describe('Header search component', () =&gt; {
   const mockRoute = {
      path: '/categories/' + 2 + '/courses/' + 4,
      query: {
        query: searchedText,
      },
   }
   const mockRouter = {
      push: jest.fn(),
   }
   const wrapper = shallowMount(HeaderSearch, {
      router,
      localVue,
      stubs: {
        NuxtLink: true,
      },
      global: {
        mocks: {
          $route: mockRoute,
          $router: mockRouter,
        },
      },
   })
   test('redirect to course page, goPage', async () =&gt; {
      const courseId = 4
      const courseTitle = 'Inbound Marketing'
      const categoryId = 2

      const mockedFunction = jest.fn()
      wrapper.vm.goPage(courseId, courseTitle, categoryId)
      await wrapper.setData({
        headerSearchInput: courseTitle,
      })
      const expectedRouter = {
        path: '/categories/3/courses/4',
        query: { query: wrapper.vm.headerSearchInput },
      }
      expect(mockedFunction).toBeCalledWith(courseId, courseTitle, categoryId)
      expect(wrapper.vm.$router.path).toEqual(expectedRouter.path)
   })
})
</code></pre>
",https://stackoverflow.com/questions/68078480/write-unit-test-for-a-method-in-a-component-in-vue-with-jest,"['vue.js', 'unit-testing', 'jestjs']",1064,True,-1,2
my data test id is there but my test cannot find it react enzyme jest unit tests,"<p>I am still new to unit testing with jest and enzyme,
I have a data-test-id and I am trying to make a unit test using that. Yet, I get an error saying that the data-test-id was not found.</p>
<p>I have the following</p>
<pre><code>import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { configure, mount, shallow } from 'enzyme';
import { shallowToJson } from 'enzyme-to-json';

import ConfirmationModal from '../src/components/GlobalForm/ConfirmationModal/ConfirmationModal';

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

describe('ConfirmationModal', () =&gt; {
  it('should be defined', () =&gt; {
    expect(ConfirmationModal).toBeDefined();
  });

  it('should render correctly', () =&gt; {
    const tree = mount(&lt;ConfirmationModal /&gt;);
    expect(shallowToJson(tree)).toMatchSnapshot();
  });

  it('should have a cancel button', () =&gt; {
    const wrapper = shallow(&lt;ConfirmationModal /&gt;);
    const ConfirmationModalComponent = wrapper.find(&quot;[data-test-id='cancel-submit-btn']&quot;);
    expect(ConfirmationModalComponent.length).toBe(1);
  });
});
</code></pre>
<p>Even my snapshot test shows that I have this data-test-id</p>
<pre><code>exports[`ConfirmationModal should render correctly 1`] = `
&lt;confirmationModal&gt;
  &lt;Styled(div)&gt;
    &lt;div
      className=&quot;css-d2ogfy&quot;
    &gt;
      &lt;Styled(div)&gt;
        &lt;div
          className=&quot;css-ywnjte&quot;
        &gt;
          Confirm your submission
        &lt;/div&gt;
      &lt;/Styled(div)&gt;
      &lt;Styled(p)&gt;
        &lt;p
          className=&quot;css-1v1a1rr&quot;
        &gt;
          The submission of your changes will directly affect the call center with which they are assigned.
        &lt;/p&gt;
      &lt;/Styled(p)&gt;
      &lt;Styled(p)&gt;
        &lt;p
          className=&quot;css-1v1a1rr&quot;
        &gt;
          Are you sure that you want to proceed with these changes?
        &lt;/p&gt;
      &lt;/Styled(p)&gt;
      &lt;Styled(div)&gt;
        &lt;div
          className=&quot;css-wqsxq7&quot;
        &gt;
          &lt;Button
            dataTestId=&quot;cancel-submit-btn&quot;
            name=&quot;Cancel&quot;
          &gt;
            &lt;Styled(button)
              data-test-id=&quot;cancel-submit-btn&quot;
            &gt;
              &lt;button
                className=&quot;css-2ba12r&quot;
                data-test-id=&quot;cancel-submit-btn&quot;
              &gt;
                Cancel
              &lt;/button&gt;
            &lt;/Styled(button)&gt;
          &lt;/Button&gt;
          &lt;Button
            dataTestId=&quot;confirm-submit-btn&quot;
            name=&quot;Confirm&quot;
          &gt;
            &lt;Styled(button)
              data-test-id=&quot;confirm-submit-btn&quot;
            &gt;
              &lt;button
                className=&quot;css-2ba12r&quot;
                data-test-id=&quot;confirm-submit-btn&quot;
              &gt;
                Confirm
              &lt;/button&gt;
            &lt;/Styled(button)&gt;
          &lt;/Button&gt;
        &lt;/div&gt;
      &lt;/Styled(div)&gt;
    &lt;/div&gt;
  &lt;/Styled(div)&gt;
&lt;/confirmationModal&gt;
`;
</code></pre>
<p>but my test results with the error:</p>
<blockquote>
<p>ConfirmationModal › should have a cancel button</p>
<pre><code>expect(received).toBe(expected) // Object.is equality

Expected: 1
Received: 0
</code></pre>
</blockquote>
<p>How???? it's right there...</p>
",https://stackoverflow.com/questions/67194679/my-data-test-id-is-there-but-my-test-cannot-find-it-react-enzyme-jest-unit-tests,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",15556,True,6,2
Unit Testing in API ASP.NET Core,"<p>I would like to make some unit-test about all my methods, (DELETE, PUT, POST ETC..) but i don't know how can i instanciate my clases in unit, now i have this in unit class:</p>
<pre><code> //Arrange
 var mockRepo = new Mock&lt;IRebelRepository&gt;();
 var controller = new RebelsController(mockRepo.Object);
 //Act
 var rebel = controller.Delete(2);
</code></pre>
<p>but now i want to check if the id is correct or not watching the response of my API (OK or BadResponse)</p>
<pre><code>public ActionResult&lt;Rebel&gt; Delete(int id)
        {
            _logger.LogInformation(&quot;Start of RebelsController.Delete()&quot;);
            var result = new ApiResult();
            ActionResult response = null;
            _logger.LogDebug($&quot;Trying to delete rebel ID: {id}&quot;);

            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.LogWarning(&quot;There was a problem deleting rebel, invalid data&quot;);
                    result.Message = &quot;Invalid rebel information.&quot;;
                    result.IsError = true;
                    response = BadRequest(result);
                }
                else
                {
                    if (id &gt; 0)
                    {
                        var filteredRebel = _rebelRepository.GetRebelById(id);

                        if (filteredRebel == null)
                        {
                            _logger.LogWarning($&quot;The rebel {id} was not found&quot;);
                            result.Message = $&quot;The rebel with id {id} has not been found&quot;;
                            result.IsError = true;

                            response = BadRequest(result);

                        }
                        else
                        {
                            _rebelRepository.DeleteRebel(filteredRebel);
                            result.Message = &quot;Rebel deleted correctly&quot;;
                            _logger.LogDebug($&quot;Rebel {id} sucessfully deleted&quot;);

                            response = Ok(result);
                        }
                    }
                }

            }catch(Exception ex)
            {
                _logger.LogError(&quot;An error occurred while Deleted method was running, error :&quot; + ex.Message);
                result.Message = &quot;Error on Delete&quot;;
                result.IsError = true;
                response = BadRequest(result);
            }

            _logger.LogInformation(&quot;End of RebelsController.Delete()&quot;);
            return response;
        }
</code></pre>
<p>How can i make unit testing in APIs?</p>
",https://stackoverflow.com/questions/66790791/unit-testing-in-api-asp-net-core,"['c#', 'api', 'asp.net-core']",200,True,0,1
I am unable to call the SonarQube API from Java to search for issues get 410 error,"<p>Hi there I am writing an OpenSource Springboot microservice to get issues from SonarQube
I use SonarQube is installed in a Docker container
From the browser I call successfully after logging in :
<code>http://localhost:9001/api/issues/search?componentKeys=za.co.nico:RabbitMqPoc</code></p>
<p>I am unit testing a Java class that I can call the same URL and getting a 401
failing Authentication where I need it to work</p>
<pre><code>package za.co.nico.poc.services;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.HttpConnector;
import org.sonarqube.ws.client.WsClient;
import org.sonarqube.ws.client.WsClientFactories;
import org.sonarqube.ws.client.WsResponse;
import org.springframework.stereotype.Service;

/**
 * 
 * https://www.baeldung.com/java-http-request
 * 
 */
@Service
public class SonarServiceImpl implements SonarService {
    private static final Logger log = LoggerFactory.getLogger(SonarServiceImpl.class);
    
    private final String TOKEN=&quot;2ce06b3585c34141beeeb4005235337ba2bd135d&quot;; 
    
    /**
     * https://programtalk.com/java-api-usage-examples/org.sonarqube.ws.client.WsClient/
     */
    @Override
    public String getData(String restUrl,String sonarEndPoint) {

        log.debug(&quot; restUrl : &quot;+restUrl+&quot; sonarEndPoint : &quot;+sonarEndPoint); // restUrl : http://localhost:9001/ sonarEndPoint : api/components/search_projects

        String login=&quot;admin&quot;;
        String password=&quot;admin&quot;;
        
        WsClient wsClient = WsClientFactories.getDefault().newClient(HttpConnector.newBuilder().url(restUrl).credentials(login, password).build());
        WsResponse response = wsClient.wsConnector().call(new GetRequest(&quot;api/authentication/validate&quot;));
        String content = response.content();
        log.debug(&quot;&quot;+response.isSuccessful());
        log.debug(&quot;&quot;+response.code()); //200

        response = wsClient.wsConnector().call(new GetRequest(&quot;api/components/search_projects&quot;));
        log.debug(&quot;&quot;+response.isSuccessful());
        content = response.content();
        log.debug(&quot;&quot;+response.code()); //401
        
        
        wsClient = WsClientFactories.getDefault().newClient(HttpConnector.newBuilder().url(restUrl).credentials(&quot;admin&quot;, &quot;admin&quot;).build());
        response = wsClient.wsConnector().call(new GetRequest(&quot;local_ws_call/require_permission&quot;));
        log.debug(&quot;&quot;+response.isSuccessful());
        log.debug(&quot;&quot;+response.code()); // 200

        wsClient = WsClientFactories.getDefault().newClient(HttpConnector.newBuilder().url(restUrl).credentials(login, password).build());
        response = wsClient.wsConnector().call(new GetRequest(&quot;api/rules/search&quot;));
        log.debug(&quot;&quot;+response.isSuccessful());
        log.debug(&quot;&quot;+response.code()); // 401
        
        return &quot;&quot;;
    }

}
</code></pre>
<p>Please advise how to fix this</p>
",https://stackoverflow.com/questions/68334452/i-am-unable-to-call-the-sonarqube-api-from-java-to-search-for-issues-get-410-err,"['java', 'api', 'sonarqube']",115,False,0,1
How to write the Junit Mockito code for this Aspect class for maximum code coverage,"<p>Could someone please help me out in writing Junit for this piece of code and provide resources to learn the same. I have been trying to figure out from multiple resources but couldn't find anything. I need to mock the pointcuts and methods which are invoked within the pointcut. Is unit testing possible for this using Mockito</p>
<pre class=""lang-java prettyprint-override""><code>import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.sample.api.rest.account.AccountResource;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.CustomLog;
import lombok.extern.slf4j.slf4j;

@Aspect
@CustomLog
public class sample {
    ObjectMapper mapper = new ObjectMapper();
    long startTimeController = 0L;
    long endTimeController = 0L;

    @Pointcut(&quot;within(com.sample.api.rest.account. .) || &quot;
    + &quot;within(com.sample.api.rest.metadata..') &quot;)
    public void entryController() {}

    @Pointcut(&quot;within(com. sample.api.rest.user..*)&quot;)
    public void entryControllerUser() {}

    @Pointcut(&quot;within(com.sample.api.service. .*)&quot;)
    public void entryService() {}

    @Pointcut(&quot;within(com. sample.cmo.repositories..*)&quot;)
    public void entryDAO() {}

    @Before(&quot;entryController()&quot;)
    public void beforeOtherControllerCall(JoinPoint jp) throws JsonProcessingException {
        String methodName = jp.getSignature().getName();
        String className = jp.getTarget().getClass().toString();
        Object[] arguments = jp.getArgs();
        log.info(className + &quot; Method : &quot; + methodName + &quot; Arguments passed : &quot; + 
        mapper.writeValueAsString(arguments));
        startTimeController = System.currentTimeMillis();
    }

    @Before(&quot;entryControllerUser()&quot;)
    public void beforeUserControllerCall(JoinPoint jp) throws JsonProcessingException {
        String methodName = jp.getSignature().getName();
        String className = jp.getTarget().getClass().toString();
        log.info(className + &quot; Method : &quot; + methodName);
        startTimeController = System.currentTimeMillis();
    }

    @After(&quot;entryController() || entryControlleruser()&quot;)
    public void afterControllerCall(JoinPoint jp) throws JsonProcessingException {
        endTimeController = System.currentTimeMillis();
        String methodName = jp.getSignature().getName();
        String className = jp.getTarget().getClass().toString();
        log.info(className + &quot; Method : &quot; + methodName + &quot; Values returned :&quot;);
        if (endTimeController != 0) {
            log.info(&quot;Time consumed in &quot; + className + &quot; &quot; + methodName + &quot; call is &quot;
                    + (endTimeController - startTimeController) + &quot;ms&quot;);
        }
    }

    @Around(&quot;entryService()&quot;)
    public Object executionTimeService(ProceedingJoinPoint pjp) throws Throwable {
        String methodName = pjp.getSignature().getName();
        String className = pjp.getTarget().getClass().toString();
        Object[] arguments = pjp.getArgs();
        log.info(className + &quot; Method: &quot; + methodName + &quot; Arguments passed :&quot; + 
          mapper.writeValueAsString(arguments));
        long startTime = System.currentTimeMillis();
        Object obj = pip.proceed();
        long endTime = System.currentTimeMillis();
        log.info(className + &quot; Method : &quot; + methodName + &quot; Execution time: &quot; + (endTime - 
          startTime) + &quot;ms&quot;);
        log.info(className + &quot; Method : &quot; + methodName + &quot; Response received : &quot; + 
         mapper.writeValueAsString(obj));
        return obj;
    }

    @Around(&quot;entryDAO()&quot;) 
    public Object executionTimeDAO(ProceedingJoinPoint pjp ) throws Throwable {
    String methodName pjp.getSignature().getName();
    String className pjp.getTarget().getClass().toString();
    Object[] arguments = pjp.getArgs();
    log.info(className+&quot; Method : &quot;+methodName+&quot; Arguments passed :&quot; 
      +mapper.writeValueAsString(arguments) );
    long startTime = System.currentTimeMillis();
    Object obj = pip.proceed();
    long endTime = System.currentTimeMillis();
    log.info(className+&quot; method : &quot; + methodName+&quot; Execution time: &quot;
           +(endTime-start Time)+&quot;ms&quot; );
    log.info(className+&quot; Method: &quot;+methodName+&quot; Response received : &quot;+ 
     mapper.writeValueAsString(obj));
    return obj;
    }
}
</code></pre>
<p>Here is the sample of what I have tried with</p>
<pre class=""lang-java prettyprint-override""><code>@Test 
public void testBeforeOtherControllerCall() throws Throwable{
    JoinPoint joinPoint = mock(JoinPoint.class);
    AspectLogging logging = mock(AspectLogging.class);
    String[] args = {&quot;arg1&quot;, &quot;arg2&quot;}; 
    Object[] obj args)
    Signature signature = mock (Signature.class);
    when(joinPoint.getSignature().thenReturn(signature);
    when(signature.getName().thenReturn(&quot;MethodName&quot;);
    Object object = mock(Object.class);
    when(joinPoint.getTarget().thenReturn(object);
    when(object.getClass().thenReturn(objectClass);
    when(joinPoint.getArgs().thenReturn(obj); 
    logging.beforeOtherControllerCali(joinPoint); 
    verify(joinPoint, times (1)).getSignature().getName().equals(&quot;MethodName&quot;);
}
</code></pre>
",https://stackoverflow.com/questions/68204815/how-to-write-the-junit-mockito-code-for-this-aspect-class-for-maximum-code-cover,"['spring-boot', 'junit', 'mockito', 'spring-aop']",1790,True,0,1
Testing form submit when enter key is pressed?,"<p>I am trying to do some unit testing in PHP and based on the Symfony documentation, you test and submit based on the snippet below (Symfony v5.3 documentation)</p>
<pre><code>$client = static::createClient();
$crawler = $client-&gt;request('GET', '/post/hello-world');

// select the button
$buttonCrawlerNode = $crawler-&gt;selectButton('submit');

// retrieve the Form object for the form belonging to this button
$form = $buttonCrawlerNode-&gt;form();

// set values on a form object
$form['my_form[name]'] = 'Fabien';
$form['my_form[subject]'] = 'Symfony rocks!';

// submit the Form object
$client-&gt;submit($form);
</code></pre>
<p>Any suggestions on how to mock the submission for a search bar that submits the when you press the enter or tab (for autocomplete) key?</p>
<p>EDIT:
Sample of what I currently have in the test case</p>
<pre><code>//Test case for search bar

$client = static::createClient();

// path where the search bar is located
$crawler = $client-&gt;request('GET', '/user/search'); 

//Since there is no button, I used the hint text in the search bar
$buttonCrawlerNode = $crawler-&gt;selectButton('Search...');   

//When test is ran, this line gives a InvalidArgumentException: The current node list is empty.
$form = $buttonCrawlerNode-&gt;form(); 

$form['form_group[userSearchText]'] = &quot;Fall Class schedule&quot;;
$client-&gt;submit($form);
$client-&gt;followRedirects();

//returns false -- Error 500
self::assertResponseIsSuccessful(); 
</code></pre>
",https://stackoverflow.com/questions/69355782/testing-form-submit-when-enter-key-is-pressed,"['php', 'symfony', 'phpunit']",126,False,0,0
Failure in make fails to halt shell script,"<p>I am automating the building and unit testing of a <a href=""https://github.com/pacmaninbw/VMWithEditor/tree/master/VMWithEditor/UnitTests"" rel=""nofollow noreferrer"">personal project</a> using bash scripts (parts of the unit testing have been <a href=""https://codereview.stackexchange.com/questions/248559/hand-coded-state-driven-lexical-analyzer-in-c-with-unit-test-part-a"">reviewed on Code Review</a>), cmake and make on the latest version of Fedora Linux. The postive test passes on on the build system, however, when I force an LD failure in one of the unit tests the build still passes at the higher levels. It needs to fail at all levels.</p>
<p>Here is the error message from the make generated by a cmake command:</p>
<pre><code>/home/pacman/Documents/projects/VMWithEditor/VMWithEditor/human_readable_program_format.c:179: multiple definition of `HRF_delete_linked_list_of_program_steps'; CMakeFiles/Run_All_Unit_Tests.exe.dir/home/pacman/Documents/projects/VMWithEditor/VMWithEditor/UnitTests/HRF_UnitTest/HRF_UnitTest/unit_test_human_readable_program_format.c.o:/home/pacman/Documents/projects/VMWithEditor/VMWithEditor/UnitTests/RunAllUnitTests/RunAllUnitTests/../../../human_readable_program_format.c:179: first defined here  
collect2: error: ld returned 1 exit status  
make[2]: *** [CMakeFiles/Run_All_Unit_Tests.exe.dir/build.make:433: Run_All_Unit_Tests.exe] Error 1  
make[2]: Leaving directory '/home/pacman/Documents/projects/VMWithEditor/VMWithEditor/UnitTests/RunAllUnitTests/RunAllUnitTests/Debug'  
make[1]: *** [CMakeFiles/Makefile2:95: CMakeFiles/Run_All_Unit_Tests.exe.dir/all] Error 2  
make[1]: Leaving directory '/home/pacman/Documents/projects/VMWithEditor/VMWithEditor/UnitTests/RunAllUnitTests/RunAllUnitTests/Debug'  
make: *** [Makefile:103: all] Error 2  
</code></pre>
<p>This is the output of the top level shell script, the last 2 builds should not execute:</p>
<pre><code>Building CommandLine_UnitTest/CommandLine_UnitTest  
Building ControlConsole_UnitTest/ControlConsole_UnitTest  
Building Editor_UnitTest/Editor_UnitTest  
Building HRF_UnitTest/HRF_UnitTest  
Building Parser_Unit_Test/Parser_Unit_Test  
Building RunAllUnitTests/RunAllUnitTests  
Building State_Machine_Unit_Test/State_Machine_Unit_Test  
Building VirtualMachine_UnitTest/VirtualMachine_UnitTest  
</code></pre>
<p>This is the shell script that doesn't fail when it should:</p>
<h2>buildDebug.sh</h2>
<pre><code>#! /bin/sh

# Create a Debug build directory and then build the target within the Debug directory
# Stop on any build errors and stop the parent process.

mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug ..
retVal=$?
if [ $retVal -ne 0 ]; then
    echo &quot;\n\ncmake failed $retval!\n\n&quot;
    exit $retVal
fi
make VERBOSE=1
if [ $retVal -ne 0 ]; then
    echo &quot;\n\nmake failed! $retval\n\n&quot;
    exit $retVal
fi
</code></pre>
<p>The previous shell script is called by this shell script, there are 8 instances of the previous shell script in subdirectories.</p>
<h2>buildAllDebug.sh</h2>
<pre><code>#! /bin/sh

# Build the debug version of all the unit tests
# Stop on any build errors.

for i in *
do
    if [ -d $i ] ; then
        TESTDIRECTORY=&quot;$i/$i&quot;
        SHELLFILE=&quot;$TESTDIRECTORY/buildDebug.sh&quot;;
        if [ -f $SHELLFILE ] ; then
            echo &quot;Building $TESTDIRECTORY&quot;;
            cd &quot;$TESTDIRECTORY&quot;
            ./buildDebug.sh &gt;&amp; buildDebuglog.txt
            retVal=$?
            if [ $retVal -ne 0 ]; then
                exit $retVal
            fi
            cd ../..
        fi
    fi
done;
</code></pre>
<p>This generates the make file that is reporting the error:</p>
<h2>CMakeLists.txt</h2>
<pre><code>cmake_minimum_required(VERSION 3.18.4)

set(EXECUTABLE_NAME &quot;Run_All_Unit_Tests.exe&quot;)

project(${EXECUTABLE_NAME} LANGUAGES C VERSION 1.0)

if(&quot;${CMAKE_BUILD_TYPE}&quot; STREQUAL &quot;Debug&quot;)
    set(GCC_WARN_COMPILE_FLAGS  &quot; -Wall &quot;)
    set(CMAKE_C_FLAGS  &quot;${CMAKE_CXX_FLAGS} ${GCC_WARN_COMPILE_FLAGS}&quot;)
endif()

set(VM_SRC_DIR &quot;../../..&quot;)
set(COMMON_TEST_DIR &quot;../../Common_UnitTest_Code&quot;)
set(LEXICAL_TEST_DIR &quot;../../State_Machine_Unit_Test/State_Machine_Unit_Test&quot;)
set(PARSER_TEST_DIR &quot;../../Parser_Unit_Test/Parser_Unit_Test&quot;)
set(CMD_LINE_TEST_DIR &quot;../../CommandLine_UnitTest/CommandLine_UnitTest&quot;)
set(HRF_TEST_DIR &quot;../../HRF_UnitTest/HRF_UnitTest&quot;)


add_executable(${EXECUTABLE_NAME}
run_all_unit_tests_main.c
${HRF_TEST_DIR}/hrf_unit_test_main.c
${HRF_TEST_DIR}/unit_test_human_readable_program_format.c
${LEXICAL_TEST_DIR}/lexical_analyzer_unit_test_main.c 
${LEXICAL_TEST_DIR}/internal_character_transition_unit_tests.c
${LEXICAL_TEST_DIR}/internal_sytax_state_tests.c
${LEXICAL_TEST_DIR}/lexical_analyzer_test_data.c
${LEXICAL_TEST_DIR}/lexical_analyzer_unit_test_utilities.c
${VM_SRC_DIR}/error_reporting.c  
${VM_SRC_DIR}/safe_string_functions.c
${VM_SRC_DIR}/arg_flags.c
${VM_SRC_DIR}/file_io_vm.c
${VM_SRC_DIR}/opcode.c
${VM_SRC_DIR}/parser.c 
${VM_SRC_DIR}/default_program.c
${VM_SRC_DIR}/human_readable_program_format.c
${VM_SRC_DIR}/lexical_analyzer.c 
${VM_SRC_DIR}/virtual_machine.c 
${PARSER_TEST_DIR}/parser_unit_test_main.c
${PARSER_TEST_DIR}/internal_parser_tests.c
${PARSER_TEST_DIR}/parser_unit_test.c
${CMD_LINE_TEST_DIR}/command_line_unit_test_main.c
${VM_SRC_DIR}/error_reporting.c
${VM_SRC_DIR}/arg_flags.c
${VM_SRC_DIR}/safe_string_functions.c
${COMMON_TEST_DIR}/unit_test_logging.c
)

set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED True)

configure_file(VMWithEditorConfig.h.in VMWithEditorConfig.h)

target_compile_definitions(${EXECUTABLE_NAME} PUBLIC UNIT_TESTING)
target_compile_definitions(${EXECUTABLE_NAME} PUBLIC ALL_UNIT_TESTING)
target_include_directories(${EXECUTABLE_NAME} PUBLIC &quot;${PROJECT_BINARY_DIR}&quot;)
target_include_directories(${EXECUTABLE_NAME} PRIVATE &quot;${VM_SRC_DIR}&quot;)
target_include_directories(${EXECUTABLE_NAME} PRIVATE &quot;${COMMON_TEST_DIR}&quot;)
target_include_directories(${EXECUTABLE_NAME} PRIVATE &quot;${LEXICAL_TEST_DIR}&quot;)
target_include_directories(${EXECUTABLE_NAME} PRIVATE &quot;${CMD_LINE_TEST_DIR}&quot;)
target_include_directories(${EXECUTABLE_NAME} PRIVATE &quot;${PARSER_TEST_DIR}&quot;)
target_include_directories(${EXECUTABLE_NAME} PRIVATE &quot;${HRF_TEST_DIR}&quot;)
</code></pre>
<h2>The Directory Stucture for the builds:</h2>
<p>This was generated by ls -R and then edited to remove what isn't necessary for this question.</p>
<pre><code>/UnitTests/:
    buildAllDebug.sh  
    buildAll.log  
    buildDebug.sh  
    buildRelease.sh  
    CommandLine_UnitTest  
    Common_UnitTest_Code  
    ControlConsole_UnitTest
    DirStructure.txt
    Editor_UnitTest
    HRF_UnitTest
    Parser_Unit_Test
    RunAllUnitTests
    State_Machine_Unit_Test
    UnitTests
    VirtualMachine_UnitTest

    /UnitTests/CommandLine_UnitTest:
    /UnitTests/CommandLine_UnitTest/CommandLine_UnitTest:
    buildDebuglog.txt
    buildDebug.sh
    buildRelease.sh
    CMakeLists.txt

    /UnitTests/Common_UnitTest_Code:

    /UnitTests/ControlConsole_UnitTest:
    /UnitTests/ControlConsole_UnitTest/ControlConsole_UnitTest:
        buildDebug.sh
        buildRelease.sh
        CMakeLists.txt

    /UnitTests/Editor_UnitTest:
    /UnitTests/Editor_UnitTest/Editor_UnitTest:
        buildDebug.sh
        buildRelease.sh
        CMakeLists.txt

    /UnitTests/HRF_UnitTest:
    /UnitTests/HRF_UnitTest/HRF_UnitTest:
        buildDebug.sh
        buildRelease.sh
        CMakeLists.txt

    /UnitTests/Parser_Unit_Test:
    /UnitTests/Parser_Unit_Test/Parser_Unit_Test:
        buildDebug.sh
        buildRelease.sh
        CMakeLists.txt

    /UnitTests/RunAllUnitTests:
    /UnitTests/RunAllUnitTests/RunAllUnitTests:
        buildDebug.sh
        buildRelease.sh
        CMakeLists.txt

    /UnitTests/State_Machine_Unit_Test:
    /UnitTests/State_Machine_Unit_Test/State_Machine_Unit_Test:
        buildDebug.sh
        buildRelease.sh
        CMakeLists.txt

    /UnitTests/UnitTests:

    /UnitTests/VirtualMachine_UnitTest:
    /UnitTests/VirtualMachine_UnitTest/VirtualMachine_UnitTest:
        buildDebug.sh
        buildRelease.sh
        CMakeLists.txt
</code></pre>
",https://stackoverflow.com/questions/65602398/failure-in-make-fails-to-halt-shell-script,"['shell', 'makefile', 'cmake', 'sh']",240,True,1,1
Swift UI: Unit testing @Published var in an ObservableObject ViewModel,"<p>So I'm trying to write a unit test to test a view model function however it is an Async function and in the test I'm trying to write it will run synchronously. I've seen a few examples online e.g</p>
<pre><code>listViewModel.$list.sink { _ in
    XCTAssertEqual(listViewModel.list?.items.count , 1)
    actionExpectation.fulfill()
}
wait(for: [actionExpectation], timeout: 1)
</code></pre>
<p>and also trying the solution given here <a href=""https://stackoverflow.com/questions/62154604/unit-testing-an-observableobject-in-swift-test-driven-development"">Unit testing an @ObservableObject in Swift Test Driven Development</a></p>
<p>I've not had any luck trying to test it, any ideas?</p>
<p>ViewModel</p>
<pre><code>class ListViewModel: ObservableObject {
    @Published var list: List?
    
    let services: Services

    init(services: Services) {
        self.services = services
        getList()
    }

    func getList() {
        if let listService = self.services.resolve(ListService.self) {
            ListService().getList() { [weak self] result in
                switch result {
                    case .success(let dataRecieved):
                        DispatchQueue.main.async {
                            self?.list = dataRecieved
                        }
                    case .failure(let error):
                        print(error)
                }
            }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/67443559/swift-ui-unit-testing-published-var-in-an-observableobject-viewmodel,"['ios', 'swift', 'swiftui', 'xctest']",1055,False,0,1
Failed: Template parse errors: Can&#39;t bind to &#39;ngModel&#39; since it isn&#39;t a known property of &#39;input&#39;. (&quot; &lt;div class=&quot;input-group&quot;&gt;*,"<p>After updating to angular 12 , i am getting below error.</p>
<p>project is building and running , but whenever i am trying <strong>ng test</strong> for unit testing , i am getting below errors</p>
<p><em>Failed: Template parse errors:
Can't bind to 'ngModel' since it isn't a known property of 'input'. (&quot; </em></p>
<p>i tried importing
<strong>import { FormsModule, ReactiveFormsModule } from '@angular/forms';</strong> but
still same error . please help me on this.</p>
",https://stackoverflow.com/questions/68906581/failed-template-parse-errors-cant-bind-to-ngmodel-since-it-isnt-a-known-pr,['angular'],385,False,0,1
Simple Unit Testing of firebase rules in emulator always fails,"<p>I am trying to setup unit testing for my firestore rules and I followed the <a href=""https://firebase.google.com/docs/rules/unit-tests"" rel=""nofollow noreferrer"">video tutorial</a> but for some reason <code>firebase.assertSucceeds.(testDoc.get())</code> always passes even though I am not allowing it by the security rule.</p>
<p>Security rule:</p>
<pre><code>rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}
</code></pre>
<p>Unit test:</p>
<pre><code>process.env.FIRESTORE_EMULATOR_HOST = 'localhost:8090';
const assert = require('assert');
const firebase = require('@firebase/testing');

const PROJECT_ID = 'my-proj-id';

describe(&quot;Security Rules&quot;,()=&gt;{

    it(&quot;monkeytest&quot;, async()=&gt;{
        const db = firebase.initializeTestApp({projectId:PROJECT_ID}).firestore();
        const testDoc = db.collection(&quot;foo&quot;).doc('bar');
        await firebase.assertSucceeds(testDoc.get());
    })
});
</code></pre>
<p>No matter what I change in the security rule this unit test always passes. When I use <code>firebase.assertFails(testDoc.get())</code> instead the test always fails no matter what I change.</p>
",https://stackoverflow.com/questions/66696292/simple-unit-testing-of-firebase-rules-in-emulator-always-fails,"['unit-testing', 'google-cloud-firestore', 'firebase-security']",373,True,0,1
Confused by the use of $(Build.ArtifactStagingDirectory) in separate stage from published Artifact,"<h2>Problem:</h2>
<p><code>$(Build.ArtifactStagingDirectory)</code> is empty, despite being able to view the published Artifacts in the Azure DevOps Pipeline UI, which causes the pipeline to fail.</p>
<h2>What I'm trying to do:</h2>
<ol>
<li>Build microservice (e.g., <code>/api</code>).</li>
<li>Run unit tests.</li>
<li>If unit tests are passing, publish the build as an Artifact.</li>
<li>Dockerize the build Artifact using <code>buildContext</code>.</li>
</ol>
<p>This is based on advice <a href=""https://softwareengineering.stackexchange.com/questions/425232/clarifying-the-steps-in-a-ci-cd-but-namely-if-if-unit-testing-should-be-done-bu"">here</a>, <a href=""https://stackoverflow.com/questions/67012723/building-application-for-unit-testing-and-then-adding-to-docker-image"">here</a>, and <a href=""https://stackoverflow.com/questions/57590336/how-to-copy-azure-pipeline-artifacts-to-a-docker-image-which-is-microsoft-dotnet/59450867#59450867"">here</a>.</p>
<h2>Publish Stage Config</h2>
<p>My config for publishing after unit tests have passed is the following:</p>
<pre><code>- publish: $(System.DefaultWorkingDirectory)/${{ parameters.pathName }} 
  artifact: ${{ parameters.pathName }}
  condition: succeeded()
</code></pre>
<ul>
<li><code>$(System.DefaultWorkingDirectory)</code> should be <code>/home/vsts/work/1/s/</code> from what I gather.</li>
<li><code>${{ parameters.pathName }}</code> is just <code>api</code>.</li>
<li>I can see correct artifacts are generated in the Azure DevOps Pipelines UI.</li>
</ul>
<h2>Docker <code>buildAndPush</code> Stage Config</h2>
<p>My config for grabbing the artifact and using it in a Docker <code>buildAndPush</code> config is the following:</p>
<pre><code>- task: Docker@2
  condition: contains(variables['servicesChanged'], '${{ parameters.serviceName }}')
  displayName: Build and Push ${{ parameters.pathName }} Docker image
  inputs:
    command: buildAndPush
    repository: $(imageRepository)-${{ parameters.pathName }}
    dockerfile: $(dockerfilePath)/${{ parameters.pathName }}/Dockerfile
    buildContext: $(Build.ArtifactStagingDirectory)
    containerRegistry: $(dockerRegistryServiceConnection)
    tags: |
      ${{ parameters.tag }}-${{ parameters.tagVersion }}
</code></pre>
<ul>
<li>From what I gather, <code>$(Build.ArtifactStagingDirectory)</code> should be <code>/home/vsts/work/1/a/</code>.</li>
<li><em><strong>However, it is empty and this stage fails.</strong></em></li>
<li><code>$(dockerfilePath)</code> is equal to <code>$(Build.SourcesDirectory)</code>.</li>
</ul>
<h2><code>Dockerfile</code> Config</h2>
<p>Informational, but this is what the <code>Dockerfile</code> contains:</p>
<pre><code>FROM python:3.8-slim

WORKDIR /app
EXPOSE 5000
COPY . .
RUN pip install -r requirements.txt
CMD [&quot;gunicorn&quot;, &quot;-b&quot;, &quot;:5000&quot;, &quot;--log-level&quot;, &quot;info&quot;, &quot;config.wsgi:application&quot;, &quot;-t&quot;, &quot;150&quot;]
</code></pre>
<h2>Project Structure</h2>
<pre><code>/project-root
  /admin
    package.json
    Dockerfile
  /api
    requirements.txt
    Dockerfile
  /client
    package.json
    Dockerfile
</code></pre>
<h2>What I've Tried</h2>
<pre><code>dockerfile: $(dockerfilePath)/${{ parameters.pathName }}/Dockerfile
buildContext: $(Build.ArtifactStagingDirectory)


Step 5/17 : RUN pip install -r requirements.txt
 ---&gt; Running in 277ce44b61cf
ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'
The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1
##[error]The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 1
##[error]The process '/usr/bin/docker' failed with exit code 1

</code></pre>
<pre><code>dockerfile: $(dockerfilePath)/${{ parameters.pathName }}/Dockerfile
buildContext: $(Build.ArtifactStagingDirectory)/${{ parameters.pathName }}


unable to prepare context: path &quot;/home/vsts/work/1/a/api&quot; not found
##[error]unable to prepare context: path &quot;/home/vsts/work/1/a/api&quot; not found
##[error]The process '/usr/bin/docker' failed with exit code 1
</code></pre>
<pre><code>dockerfile: $(Build.ArtifactStagingDirectory)/${{ parameters.pathName }}/Dockerfile
buildContext: $(Build.ArtifactStagingDirectory)


##[error]Unhandled: No Dockerfile matching  /home/vsts/work/1/a/api/Dockerfile  was found.

</code></pre>
<pre><code>dockerfile: $(Build.ArtifactStagingDirectory)/Dockerfile
buildContext: $(Build.ArtifactStagingDirectory)

##[error]Unhandled: No Dockerfile matching  /home/vsts/work/1/a/Dockerfile  was found.
</code></pre>
<h2>What Has Worked</h2>
<pre><code>dockerfile: $(System.DefaultWorkingDirectory)/${{ parameters.pathName }}/Dockerfile
buildContext: $(System.DefaultWorkingDirectory)/${{ parameters.pathName }}
</code></pre>
<p>But doing this seems to negate the need to <code>publish</code> as an Artifact. Maybe this is the &quot;correct&quot; way, I don't know. It seems like it is doing what I want to accomplish by <code>COPY</code> what was built for unit testing into the Docker image instead of using a different version.</p>
<p>I'm pretty sure this isn't what I'm after since it looks like it is just cloning the repo again to <code>/home/vsts/work/1/a/</code> at the beginning of this stage.</p>
<h2>Question(s)</h2>
<ul>
<li>Why is <code>$(Build.ArtifactStagingDirectory)</code> empty?</li>
<li>Is it a deprecated env var?</li>
<li>Is using what I have in &quot;What Has Worked&quot; supposed to be the correct way of how to handle this? <em><strong>(I don't think that it is)</strong></em>.</li>
<li>So how should I be persisting the tested build between the unit testing stage and the Docker stage so I can use the exact build from the unit testing stage?</li>
</ul>
",https://stackoverflow.com/questions/68308817/confused-by-the-use-of-build-artifactstagingdirectory-in-separate-stage-from,"['azure-devops', 'azure-pipelines', 'azure-pipelines-build-task', 'azure-pipelines-yaml']",4395,True,3,1
Unit testing AWS Lambda CDK,"<p>I'm having issues unit testing a lambda function module that is dependent on a package inside the referenced lambda layer.</p>
<p>My module looks like so</p>
<pre><code>/lambda/function/orderIdGenerator.ts
</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-js lang-js prettyprint-override""><code>import { Order } from './structs';
import { generateHashedId } from '/opt/nodejs/node_modules/package_name/common';

export const orderIdGenerator = (order: Order): string =&gt; {
  const orderValues = Object.values(order);
  return generateHashedId(orderValues);
};</code></pre>
</div>
</div>
</p>
<p>To then test this function I want to mock the module being imported.
My attempt...</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>jest.mock('package_name/common');
import { Order } from 'lambda/function/structs';
import { orderIdGenerator } from '../../../lambda/function/orderIdGenerator';
import { generateHashedId } from '/opt/nodejs/node_modules/package_name/common';

describe('orderIdGenerator', () =&gt; {
  it('should call generateHashedId', () =&gt; {
    // GIVEN
    const fn = orderIdGenerator;
    // WHEN
    fn(({ foo: 'bar' } as unknown) as Order);
    // THEN
    expect(generateHashedId).toHaveBeenCalled();
  });

  it('should call generateHashedId with Order', () =&gt; {
    // GIVEN
    const fn = orderIdGenerator;
    // WHEN
    fn({} as Order);
    // THEN
    expect(generateHashedId).toHaveBeenCalledWith({});
  });
});</code></pre>
</div>
</div>
</p>
<p>But of course Jest is not able to mock a module it cannot find.</p>
<p>My tsconfig.json</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>{
  ""compilerOptions"": {
    ""target"": ""ES2018"",
    ""module"": ""commonjs"",
    ""lib"": [""es2018""],
    ""declaration"": true,
    ""strict"": true,
    ""noImplicitAny"": true,
    ""strictNullChecks"": true,
    ""noImplicitThis"": true,
    ""alwaysStrict"": true,
    ""noUnusedLocals"": false,
    ""noUnusedParameters"": false,
    ""noImplicitReturns"": true,
    ""noFallthroughCasesInSwitch"": false,
    ""inlineSourceMap"": true,
    ""inlineSources"": true,
    ""experimentalDecorators"": true,
    ""strictPropertyInitialization"": false,
    ""typeRoots"": [
      ""./node_modules/@types"",
      ""./layer/nodejs/node_modules/@types""
    ],
    ""baseUrl"": ""."",
    ""paths"": {
      ""/opt/nodejs/*"": [""layer/nodejs/*""]
    }
  },
  ""exclude"": [""cdk.out""]
}</code></pre>
</div>
</div>
</p>
<p>I even through this is my package.json</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>  ""jest"": {
    ""modulePaths"": [
      ""&lt;rootDir&gt;/node_modules/"",
      ""&lt;rootDir&gt;/layers/nodejs/node_modules/""
    ]
  }</code></pre>
</div>
</div>
</p>
<p>Any ideas would be appreciated.</p>
<p>Thanks !</p>
",https://stackoverflow.com/questions/66337969/unit-testing-aws-lambda-cdk,"['typescript', 'unit-testing', 'aws-lambda', 'jestjs', 'aws-cdk']",1102,False,2,0
what is the idiomatic way to raise an exception within the exception handler in Python?,"<p>What is the correct way in Python of catching an exception, and raising another exception?  I.e, I want to catch an exception of type 1, manipulate the Exception object and unconditionally raise a second exception of type 2, so that the calling function doesn't see the Exception of type 1 but absolutely sees the exception of type 2 whose construction depends on data accessed from the type-1 Exception.</p>
<p>Here is the code I've tried which doesn't work.</p>
<pre class=""lang-py prettyprint-override""><code>            def d(wrt):
                try:
                    return rt.derivative(wrt).canonicalize()
                except CannotComputeDerivative as e:
                    msg = &quot;\n&quot;.join([f&quot;When generating derivatives from {self}&quot;,
                                     f&quot;  when computing edges of {rt}&quot;,
                                     f&quot;  which canonicalizes to {self.canonicalize()}&quot;,
                                     f&quot;  computing derivative of {e.rte}&quot;,
                                     f&quot;  wrt={e.wrt}&quot;,
                                     f&quot;  derivatives() reported: {e.msg}&quot;])
                    raise CannotComputeDerivatives(msg=msg,
                                                   rte=rt,
                                                   wrt=wrt,
                                                   first_types=fts,
                                                   mdtd=wrts)
</code></pre>
<p>The reason I think it doesn't work is because I get the following message as output:</p>
<pre><code>Error
Traceback (most recent call last):
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 95, in d
    return rt.derivative(wrt).canonicalize()
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_singleton.py&quot;, line 68, in derivative
    return super().derivative(wrt)
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 72, in derivative
    return self.derivative_down(wrt)
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_singleton.py&quot;, line 91, in derivative_down
    raise CannotComputeDerivative(
rte.r_rte.CannotComputeDerivative

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/tests/rte_tests.py&quot;, line 615, in test_derivatives
    self.assertTrue(rt.derivatives())
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 111, in derivatives
    return trace_graph(self, edges)
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/genus/utils.py&quot;, line 199, in trace_graph
    es = edges(v0)  # List[(L,V)]
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 109, in edges
    return [(td, d(td)) for td in wrts]
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 109, in &lt;listcomp&gt;
    return [(td, d(td)) for td in wrts]
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 103, in d
    raise CannotComputeDerivatives(msg=msg,
rte.r_rte.CannotComputeDerivatives
</code></pre>
<p>Following the suggestion of <a href=""https://stackoverflow.com/users/5349916/mistermiyagi"">MisterMiyagi </a> I added <code>from None</code> after the <code>raise CannotComputeDerivatives(...)</code>.   This makes progress, but it seems the <code>unittest</code> environment doesn't really like it.  The displayed message during unit testing is shown below.  It looks like <code>unittest</code> sadly truncates the message.</p>
<pre><code>Error
Traceback (most recent call last):
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/tests/rte_tests.py&quot;, line 615, in test_derivatives
    rt.derivatives()
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 111, in derivatives
    return trace_graph(self, edges)
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/genus/utils.py&quot;, line 199, in trace_graph
    es = edges(v0)  # List[(L,V)]
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 109, in edges
    return [(td, d(td)) for td in wrts]
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 109, in &lt;listcomp&gt;
    return [(td, d(td)) for td in wrts]
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 103, in d
    raise CannotComputeDerivatives(msg=msg,
rte.r_rte.CannotComputeDerivatives
</code></pre>
<p>=============
To follow up on the solution:
The original problem was that the <code>__init__</code> function for the <code>CannotComputeDerivatives</code> class was calling <code>super().__init__()</code> without passing the message string.   I've updated the class definition as follows.</p>
<pre class=""lang-py prettyprint-override""><code>class CannotComputeDerivatives(Exception):
    def __init__(self, msg, rte, wrt, first_types, mdtd):
        self.msg = msg
        self.rte = rte
        self.wrt = wrt
        self.first_types = first_types
        self.mdtd = mdtd
        super().__init__(msg)
</code></pre>
<p>The result is that I get beautiful error messages during unit testing:</p>
<pre><code>Error
Traceback (most recent call last):
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/tests/rte_tests.py&quot;, line 615, in test_derivatives
    self.assertTrue(rt.derivatives())
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 111, in derivatives
    return trace_graph(self, edges)
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/genus/utils.py&quot;, line 199, in trace_graph
    es = edges(v0)  # List[(L,V)]
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 109, in edges
    return [(td, d(td)) for td in wrts]
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 109, in &lt;listcomp&gt;
    return [(td, d(td)) for td in wrts]
  File &quot;/Users/jnewton/Repos/python-rte/pyrte/rte/r_rte.py&quot;, line 103, in d
    raise CannotComputeDerivatives(msg=msg,
rte.r_rte.CannotComputeDerivatives: When generating derivatives from Singleton(SOr(odd?, SAtomic(Test2)))
  when computing edges of Singleton(SOr(odd?, SAtomic(Test2)))
  which canonicalizes to Singleton(SOr(odd?, SAtomic(Test2)))
  computing derivative of Singleton(SOr(odd?, SAtomic(Test2)))
  wrt=SOr(SAtomic(Test2), odd?)
  derivatives() reported: Singleton.derivative_down cannot compute derivative of Singleton(SOr(odd?, SAtomic(Test2)))
  wrt=SOr(SAtomic(Test2), odd?)
  disjoint=False
  subtypep=None
</code></pre>
",https://stackoverflow.com/questions/68271145/what-is-the-idiomatic-way-to-raise-an-exception-within-the-exception-handler-in,"['python', 'python-3.x', 'exception', 'raise']",152,True,-2,1
expect(jest.fn()).toHaveBeenCalled() fails even though the function has been called,"<p>I'm trying to unit test a function that returns a promise. I'm having challenges verifying if
the mocked functions are called. Here's what I've done.,</p>
<pre class=""lang-js prettyprint-override""><code>// codetotest.js
const { SomeModule, isSomething, isSomethingElse } = require(&quot;some-module&quot;);

exports.somefunction = (param1, param2)=&gt; {
    const someModule = new SomeModule();

    someModule.someMethod(&quot;aaa&quot;, isSomething);
    someModule.someMethod(&quot;bbb&quot;, isSomethingElse);

    return (someModule.someOtherMethod(param1)
    .then(()=&gt;{someModule.run(param2)}));
}
</code></pre>
<p>And this is the test file, the test says the mocked functions are not called, but I do see the console statement in the mock function is being displayed.</p>
<pre class=""lang-js prettyprint-override""><code>// codetotest.test.js
const { somefunction} = require(&quot;./codetotest.js&quot;);
const { SomeModule } = require(&quot;some-module&quot;);

jest.mock(&quot;some-module&quot;, () =&gt; {
    return {
        SomeModule: jest.fn().mockImplementation(() =&gt; {
            return {
                someMethod: jest.fn((param, fn) =&gt; { console.log(&quot;This prints!&quot;); }),
                someOtherMethod: jest.fn((param) =&gt; { return Promise.resolve(() =&gt; { }) }),
                run: jest.fn((param) =&gt; { return Promise.resolve(() =&gt; { return []; }) })
            }
        })
    };
});

afterEach(() =&gt; {
    jest.resetAllMocks();
    jest.restoreAllMocks();
});

describe(&quot;Test codetotest.js&quot;, () =&gt; {
    it(&quot;somefunction() - success&quot;, async () =&gt; {
        const someModule = new SomeModule();

        let output = await somefunction(&quot;param1&quot;, &quot;param2&quot;);

        expect(SomeModule).toHaveBeenCalled();
        expect(someModule.someMethod).toHaveBeenCalled(); // This fails

        await expect(someModule.someOtherMethod.mock.results[0]).resolves;
        expect(someModule.someOtherMethod).toHaveBeenCalled(); // This fails

        await expect(someModule.run.mocks.results[0]).resolves;
        expect(someModule.run).toHaveBeenCalled(); // This fails
    });
});
</code></pre>
<p>Appreciate any help/pointers.</p>
<p>Thank you.</p>
<p>P.S: I'm still a beginner when it comes to nodeJs development and unit testing.</p>
",https://stackoverflow.com/questions/67538405/expectjest-fn-tohavebeencalled-fails-even-though-the-function-has-been-cal,"['javascript', 'node.js', 'unit-testing', 'jestjs']",18420,True,5,1
Javascript nested array check value exist or not,"<p>I am using React for my app. I am trying make one food delivery app. In my app there is multiple restaurants. Some of the restaurants have delivery time and some of them don't have. All the restaurants have next 7 days date.</p>
<p>Some of the restaurant does not have first two days delivery time but after that the restaurant has delivery time for rest of the week. Some restaurant does not have delivery times at all for next seven days.</p>
<p>I want to create an helper function which will check if in the restaurant data have delivery time or not.</p>
<blockquote>
<p>PS: I am trying to learn UNIT testing. It would be awesome if you show
me how to do unit testing of my helper function.</p>
</blockquote>
<p>This is my sample data where there is dates and have delivery time:</p>
<pre><code> {
  deliveryMethod: &quot;PICKUP&quot;,
  deliverySlots: [
    {
      date: &quot;2021-08-04&quot;,
      deliveryTimes: [],
    },
    {
      date: &quot;2021-08-05&quot;,
      deliveryTimes: [],
    },
    {
      date: &quot;2021-08-06&quot;,
      deliveryTimes: [],
    },
    {
      date: &quot;2021-08-07&quot;,
      deliveryTimes: [
        {
          time: &quot;16:30-17:00&quot;,
          validFrom: &quot;2020-08-07&quot;,
          validUntil: &quot;2023-08-07&quot;,
        },
        { 
          time: &quot;18:00-19:00&quot;,
          validFrom: &quot;2020-08-07&quot;,
          validUntil: &quot;2023-08-07&quot;,
        },
      ],
    },
  ],
}
</code></pre>
<p>This is my sample data where there is dates and no delivery time:</p>
<pre><code> {
  deliveryMethod: &quot;PICKUP&quot;,
  deliverySlots: [
    {
      date: &quot;2021-08-04&quot;,
      deliveryTimes: [],
    },
    {
      date: &quot;2021-08-05&quot;,
      deliveryTimes: [],
    },
    {
      date: &quot;2021-08-06&quot;,
      deliveryTimes: [],
    },
    {
      date: &quot;2021-08-07&quot;,
      deliveryTimes: [],
    },
  ],
}
</code></pre>
<p>After passing the value to function, then I stuck how check is there any delivery times exist or not.</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>const deliveryArea = {
  deliveryMethod: ""PICKUP"",
  deliverySlots: [
    {
      date: ""2021-08-04"",
      deliveryTimes: [],
    },
    {
      date: ""2021-08-05"",
      deliveryTimes: [],
    },
    {
      date: ""2021-08-06"",
      deliveryTimes: [],
    },
    {
      date: ""2021-08-07"",
      deliveryTimes: [
        {
         
          time: ""16:30-17:00"",
          validFrom: ""2020-08-07"",
          validUntil: ""2023-08-07"",
        },
        {
         
          time: ""18:00-19:00"",
          validFrom: ""2020-08-07"",
          validUntil: ""2023-08-07"",
        },
      ],
    },
    {
      date: ""2021-08-08"",
      deliveryTimes: [
        {
         
          time: ""16:30-17:00"",
          validFrom: ""2020-08-08"",
          validUntil: ""2023-08-08"",
        },
        {
        
          time: ""18:00-19:00"",
          validFrom: ""2020-08-07"",
          validUntil: ""2023-08-07"",
        },
      ],
    },
    {
      date: ""2021-08-09"",
      deliveryTimes: [],
    },
    {
      date: ""2021-08-10"",
      deliveryTimes: [
        {
         
          time: ""16:30-17:00"",
          validFrom: ""2020-08-10"",
          validUntil: ""2023-08-10"",
        },
        {
         
          time: ""18:00-19:00"",
          validFrom: ""2020-08-10"",
          validUntil: ""2023-08-10"",
        },
      ],
    },
  ],
};

const helperFunction = (deliveryArea) =&gt; {
  console.log(deliveryArea); // in here i stuck
};

helperFunction(deliveryArea);</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/68663185/javascript-nested-array-check-value-exist-or-not,"['javascript', 'arrays', 'function']",86,True,0,1
Integration testing DRF,"<p>I'm using Django with DRF as just an API--it doesn't serve any FE assets of any kind. I know the Django testing suite is built on the Python native <code>unittest</code> library and plan on using it for unit testing.</p>
<ul>
<li>When it comes to integration testing, is it sufficient or should something like Behave be used?</li>
<li>If <code>unittest</code> is sufficient, should it be used in conjunction with some kind of faker?</li>
</ul>
",https://stackoverflow.com/questions/66676964/integration-testing-drf,"['django', 'testing', 'django-rest-framework', 'integration-testing']",835,True,2,1
Java Swing MVP unit testing with Mockito,"<p><strong>Description</strong></p>
<p>I have a simple Java Swing application implementing the Model-View-Presenter pattern. My aim is to be able to test the logic behind &quot;rendering&quot; the view.</p>
<p><a href=""https://i.stack.imgur.com/VgFCD.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VgFCD.png"" alt=""enter image description here"" /></a></p>
<p>Here is the presenter and associated interface:</p>
<pre><code>public class MainPresenter implements IViewListener
{
    private final IMainWindow _view;
    private final ITaxCalculator _model;

    public MainPresenter(IMainWindow view, ITaxCalculator model)
    {
        this._view = view;
        this._model = model;
    }

    @Override
    public void onCalculateButtonClicked(double amount)
    {
        // perform calculations
        this._model.setTotalSales(salesAmount);
        double countySalesTax = this._model.getCountySalesTax();
        double stateSalesTax = this._model.getStateSalesTax();
        double totalSalesTax = this._model.getTotalSalesTax();

        // update the view
        this._view.setCountySalesTaxField(countySalesTax);
        this._view.setStateSalesTaxField(stateSalesTax);
        this._view.setTotalSalesTaxField(totalSalesTax);
    }
}

public interface IViewListener
{
    public void onCalculateButtonClicked(double amount);
}
</code></pre>
<p>Here is the model and its associated interface:</p>
<pre><code>public interface ITaxCalculator
{
    public double getCountySalesTax();
    public double getStateSalesTax();
    public double getTotalSalesTax();
    public void setTotalSales(double totalSales);
}

public class TaxCalculator implements ITaxCalculator
{
    protected double _totalSales;
    
    public TaxCalculator()
    {
        
    }
    
    public TaxCalculator(double totalSales)
    {
        this._totalSales = totalSales;
    }
    
    public void setTotalSales(double totalSales)
    {
        this._totalSales = totalSales;
    }
    
    public double getCountySalesTax()
    {
        return 0.02 * this._totalSales;
    }
    
    public double getStateSalesTax()
    {
        return 0.04 * this._totalSales;
    }
    
    public double getTotalSalesTax()
    {
        return this.getCountySalesTax() + this.getStateSalesTax();
    }//getTotalSalesTax
}//class
</code></pre>
<p>Here is the interface which the view implements (I've omitted the actual view which extends JFrame, as that is quite a lot of code):</p>
<pre><code>public interface IMainWindow
{
    public void addListener(IViewListener listener);
    
    public double getSalesAmountEntered();
    public void setSalesAmountEntered(double amount);
    
    public double getCountySalesTaxField();
    public void setCountySalesTaxField(double amount);
    
    public double getStateSalesTaxField();
    public void setStateSalesTaxField(double amount);
    
    public double getTotalSalesTaxField();
    public void setTotalSalesTaxField(double amount);
    
    public void clear();
}
</code></pre>
<p><strong>Unit testing problems</strong></p>
<p>I'm using JUnit 4 and Mockito (here is an extract from my <code>pom.xml</code> file):</p>
<pre><code>&lt;dependency&gt;
        &lt;groupId&gt;junit&lt;/groupId&gt;
        &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;version&gt;4.13.2&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    
    &lt;dependency&gt;
        &lt;groupId&gt;org.mockito&lt;/groupId&gt;
        &lt;artifactId&gt;mockito-inline&lt;/artifactId&gt;
        &lt;version&gt;3.7.7&lt;/version&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;3.7.7&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
</code></pre>
<p>Now, I am trying to unit-test the presenter class. I normally work with C#, and only just started with Java. I've implemented a similar MVP pattern with WinForms before, using FakeItEasy for unit testing. In that situation, I might do something like the following, and it yields the expected results:</p>
<pre><code>// arrange
var fakeView = A.Fake&lt;IMainWindow&gt;();
A.CallTo(() =&gt; fakeView.GetAmount()).Returns(100);
var fakeModel = A.Fake&lt;ITaxCalculator&gt;();
var presenter = new MainPresenter(fakeView, fakeModel);

</code></pre>
<p>In this particular example, I am trying to achieve something similar with the following JUnit test.</p>
<pre><code>public class MainPresenter_Test
{
    @Mock
    IMainWindow mockView;
    
    @Mock
    ITaxCalculator mockModel;
    
    @Before
    public void setUp()
    {
        MockitoAnnotations.initMocks(this);
    }
    
    @Test
    public void onCalculateButtonClicked_Test()
    {
        // arrange
        double amount = 100;
        when(mockView.getSalesAmountEntered()).thenReturn(amount);
        when(mockModel.getCountySalesTax()).thenReturn(2.00);
        when(mockModel.getStateSalesTax()).thenReturn(4.00);
        when(mockModel.getTotalSalesTax()).thenReturn(6.00);
        MainPresenter presenter = new MainPresenter(mockView, mockModel);
        
        // act
        presenter.onCalculateButtonClicked(mockView.getSalesAmountEntered());
        double actualCountySalesTax = mockView.getCountySalesTaxField();
        double actualStateSalesTax = mockView.getStateSalesTaxField();
        double actualTotalSalesTax = mockView.getTotalSalesTaxField();
        
        // assert
        assertEquals(2.00, actualCountySalesTax, 0);
    }
</code></pre>
<p>However, the assert fails, because the actual value is always 0. Am I doing something wrong in the setup of the unit test?</p>
",https://stackoverflow.com/questions/68773316/java-swing-mvp-unit-testing-with-mockito,"['java', 'swing', 'unit-testing', 'user-interface', 'mockito']",98,False,0,0
Unit test custom InputFormatter,"<p>I have added a custom InputFormatter from <a href=""https://stackoverflow.com/a/47807117/1093406"">https://stackoverflow.com/a/47807117/1093406</a> but want to add unit testing for the class.</p>
<p>Is there an easy way to do this?
I'm looking at the <code>InputFormatterContext</code> parameter to <code>ReadRequestBodyAsync</code> and it seems to be complex with lots of other objects required to construct it and it looks difficult to mock.
Has anyone been able to do this?</p>
<p>I'm using xUnit and Moq on .Net5</p>
<p>Code</p>
<pre><code>public class RawJsonBodyInputFormatter : InputFormatter
{
    public RawJsonBodyInputFormatter()
    {
        this.SupportedMediaTypes.Add(&quot;application/json&quot;);
    }

    public override async Task&lt;InputFormatterResult&gt; ReadRequestBodyAsync(InputFormatterContext context)
    {
        var request = context.HttpContext.Request;
        using (var reader = new StreamReader(request.Body))
        {
            var content = await reader.ReadToEndAsync();
            return await InputFormatterResult.SuccessAsync(content);
        }
    }

    protected override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }
}
</code></pre>
",https://stackoverflow.com/questions/69252633/unit-test-custom-inputformatter,"['c#', 'unit-testing', 'asp.net-core', 'inputformatter']",343,True,1,2
How to use Chai and Mocha for Google Cloud functions unit testing,"<p>Having issue in writing simple unit test for Google Cloud Function using Chai, Mocha and Sinon although I am referring <a href=""https://cloud.google.com/functions/docs/testing/test-http"" rel=""nofollow noreferrer"">Google unit testing reference doc</a> but unable to understand it.</p>
<p><strong>Problems</strong></p>
<ul>
<li>I'm getting below error message while running unit test.</li>
</ul>
<pre><code>TypeError: response.status is not a function
</code></pre>
<ul>
<li>Why do I need to typecast Request and Response object while call function? In Google docs example (<a href=""https://github.com/GoogleCloudPlatform/nodejs-docs-samples/blob/e0ae58139eca50a578785624cc46dbc2e91e95c6/functions/helloworld/test/sample.unit.http.test.js#L35"" rel=""nofollow noreferrer"">Github</a>), they are not doing typecasting.</li>
</ul>
<pre><code>onCalculate(req as Request, res as unknown as Response);
</code></pre>
<p><strong>Objective:</strong>
Test should pass</p>
<p><strong>onCalculate.ts</strong></p>
<pre><code>import * as functions from &quot;firebase-functions&quot;;

export const onCalculate = functions.https.onRequest((request, response) =&gt; {
  const param1 = request.body.param1;
  const param2 = request.body.param2;
  response.status(200).send(calculate(param1 as number, param2 as number));
});

/**
 * Function to calculate two numbers
 * @param {number} param1
 * @param {number} param2
 * @return {number}
 */
function calculate(param1: number, param2: number): number {
  return param1 + param2;
}

</code></pre>
<p><strong>onCalculate.spec.ts</strong></p>
<pre><code>import firebase from &quot;firebase-functions-test&quot;;
import { Request, Response } from &quot;firebase-functions&quot;;
import { stub } from &quot;sinon&quot;;
import { assert } from &quot;chai&quot;;
import { onCalculate } from &quot;./onCalculate&quot;;

const test = firebase();

describe(&quot;Calculate&quot;, () =&gt; {
  after(() =&gt; {
    test.cleanup();
  });

  it(&quot;should return 3&quot;, () =&gt; {
    const req = {
      query: {},
      body: {
        param1: 1,
        param2: 2,
      },
    };

    const res = { send: stub() };

    onCalculate(req as Request, res as unknown as Response);

    assert.ok(res.send.calledOnce);
  });
});

</code></pre>
",https://stackoverflow.com/questions/70521083/how-to-use-chai-and-mocha-for-google-cloud-functions-unit-testing,"['node.js', 'unit-testing', 'google-cloud-functions', 'mocha.js', 'chai']",634,True,1,1
Read logs from Application Insights Using C#,"<p>I am trying to read logs from Application Insights in Azure Portal. I know how to create them but I am trying to figure out a way that I can read them so that I can confirm that a process is running correctly in unit testing.</p>
<p>Would any one know how to do this or have any articles they can point me to?</p>
<p>Your help would be greatly appreciated.</p>
",https://stackoverflow.com/questions/69020069/read-logs-from-application-insights-using-c,"['c#', 'azure-application-insights', 'azureportal']",857,False,1,1
How to unit test in C#,"<p>Hello I trying to do Testing in my Sort</p>
<pre><code> public class Sort
        {
    public string MergeSort(string Word)
    {
       
        var tempLetter=&quot;&quot;;
        string arrangedSort = &quot;&quot;;
        List&lt;string&gt; ListLetters = new List&lt;string&gt;();
        arrangedSort = &quot;&quot;;
        for (int i = 0; i &lt; Word.Length; i++)
        {
            ListLetters.Add(Word.Substring(i, 1));
        }
        for (int i = 0; i &lt; Word.Length; i++)
        {
            for (int j = i; j &lt; Word.Length; j++)
            {
                if (char.Parse(ListLetters[i]) &gt; char.Parse(ListLetters[j]))
                {
                    tempLetter = ListLetters[i];
                    ListLetters[i] = ListLetters[j];
                    ListLetters[j] = tempLetter;
                }
            }
        }
        foreach (var listLetter in ListLetters)
        {
            arrangedSort += listLetter;
        }
        return arrangedSort;
    }
    }
</code></pre>
<p>This is my Unit Test</p>
<pre><code> namespace Sort_Test
{
    [TestClass]
    public class Sort
    {
        [TestMethod]
          
            public void MergeSortTesting()
            {
                Sort sort = new Sort();
                string input = &quot;dcba&quot;;
                string output = sort.MergeSort(input);

                Assert.AreEqual(&quot;abcd&quot;, output);
            }

        private string MergeSort(string input)
        {
            return input;
        }
    }
}
</code></pre>
<p>But it didn't work may I know what is the cause why it didn't work. Sorry Beginner in c#. Kindly help me what is wrong with the code? I also tried searching the solution how to unit testing work but I can't get the solution
the expected result is abcd but in the testing dcba.</p>
<p><a href=""https://i.stack.imgur.com/7W4df.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7W4df.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/69784007/how-to-unit-test-in-c,"['c#', 'visual-studio', 'unit-testing', 'mstest']",603,True,1,3
How to recursively compare two objects with different field names but same values with AssertJ,"<p>I want to compare two objects (DTO and an Entity) using AssertJ's recursive comparison, for purpose of unit-testing DTO-&gt;Entity mapper.
Both of these objects have fields with pretty much the same values, but some of the fields have different names between these two objects. That results in following error:</p>
<pre><code>DTO can't be compared to Entity as Entity does not declare all DTO fields, it lacks these: [dtoFieldA, dtoFieldB, dtoFieldC]
</code></pre>
<p>I've tried following configuration, but without luck:</p>
<pre><code> assertThat(DTO)
    .usingRecursiveComparison(RecursiveComparisonConfiguration.builder()
    .withEqualsForFields(fieldAPRedicate, &quot;dtoFieldA&quot;)
    .withEqualsForFields(fieldBPRedicate, &quot;dtoFieldB&quot;)
    .withEqualsForFields(fieldCPRedicate, &quot;dtoFieldC&quot;)
    .build())
.isEqualTo(Entity)

BiPredicate&lt;DTO, Entity&gt; fieldAPRedicate = (d, e) -&gt; d.dtoFieldA().equals(e.entityFieldA());
BiPredicate&lt;DTO, Entity&gt; fieldBPRedicate = (d, e) -&gt; d.dtoFieldB().equals(e.entityFieldB());
BiPredicate&lt;DTO, Entity&gt; fieldCPRedicate = (d, e) -&gt; d.dtoFieldC().equals(e.entityFieldC());
</code></pre>
<p>Compared classess:</p>
<p>DTO:</p>
<pre><code>public class DTO {
   protected String sameNameField1;
   protected String sameNameField2;
   protected String dtoFieldA;
   protected String dtoFieldB;
   protected String dtoFieldC;
}
</code></pre>
<p>Entity:</p>
<pre><code>public class Entity {
   protected String sameNameField1;
   protected String sameNameField2;
   protected String entityFieldA;
   protected String entityFieldB;
   protected String entityFieldC;
}
</code></pre>
<p>How to configure assertJ for such case?</p>
",https://stackoverflow.com/questions/69287040/how-to-recursively-compare-two-objects-with-different-field-names-but-same-value,"['java', 'junit5', 'assertj']",1869,True,1,1
Mock NgControl in unit-test to access validators,"<p>I'm having trouble unit-testing a directive that sets validators via <code>NgControl</code>.</p>
<p>Here's what I'm doing inside my directive:</p>
<pre class=""lang-js prettyprint-override""><code>constructor(private control: NgControl) {
}

ngOnInit() {
    const ctrl = this.control.control;
    if (ctrl) {
        // this condition never passes here when run inside the test

        ctrl.setValidators([/* my validators*/]);
    }
}
</code></pre>
<p>In my test, I tried a number of ways to inject that <code>NgControl</code>, like this one:</p>
<pre class=""lang-js prettyprint-override""><code>{ provide: NgControl, useValue: new FormControl() }
</code></pre>
<p>But nothing works. Inside the test, <code>ctrl</code> within the directive is always <code>null</code>. In the meantime, normally the directive works perfectly.</p>
<p>I no longer know where to look. Any help is much appreciated!</p>
<hr />
<p>I'm using Angular v12.02</p>
",https://stackoverflow.com/questions/67827771/mock-ngcontrol-in-unit-test-to-access-validators,"['angular', 'unit-testing']",556,True,1,1
Unit Test failing with Redisson,"<p>I'm new to Redis and my team are using Redisson as Redis client for our Spring Boot Application. Below is the full console log of 1 of our Unit Testing. I use @Cacheable, @CacheEvict as well as @CachePut to first have the fundamental use case of Caching first. Seems like it's facing the Codec issue.</p>
<pre><code>Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
    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:244)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:350)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:355)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$7(ClassBasedTestDescriptor.java:350)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:312)
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:735)
    at java.base/java.util.stream.Streams$ConcatSpliterator.forEachRemaining(Streams.java:734)
    at java.base/java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:658)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:349)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$4(ClassBasedTestDescriptor.java:270)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:269)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$2(ClassBasedTestDescriptor.java:259)
    at java.base/java.util.Optional.orElseGet(Optional.java:369)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$3(ClassBasedTestDescriptor.java:258)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:101)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:100)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:65)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$1(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:111)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:79)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:75)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
    at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
    at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
    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.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
    at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
    at com.sun.proxy.$Proxy5.stop(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:135)
    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.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
    at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
    at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
    at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration.propertySourcesPlaceholderConfigurer
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:60)
    at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:108)
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:193)
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:153)
    at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:129)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:343)
    at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:247)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:311)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:112)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:746)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:564)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:338)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:123)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 92 more
Caused by: java.lang.IllegalStateException: Failed to introspect Class [com.ptc.swat.springmvc.common.cache.redis.RedissonConfig] from ClassLoader [jdk.internal.loader.ClassLoaders$AppClassLoader@2aae9190]
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:481)
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:358)
    at org.springframework.util.ReflectionUtils.getUniqueDeclaredMethods(ReflectionUtils.java:414)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.lambda$getTypeForFactoryMethod$2(AbstractAutowireCapableBeanFactory.java:747)
    at java.base/java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1705)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:746)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:685)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:656)
    at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1670)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:570)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:542)
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition.collectBeanNamesForType(OnBeanCondition.java:238)
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getBeanNamesForType(OnBeanCondition.java:231)
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getBeanNamesForType(OnBeanCondition.java:221)
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchingBeans(OnBeanCondition.java:169)
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:144)
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47)
    ... 108 more
Caused by: java.lang.NoClassDefFoundError: org/redisson/client/codec/Codec
    at java.base/java.lang.Class.getDeclaredMethods0(Native Method)
    at java.base/java.lang.Class.privateGetDeclaredMethods(Class.java:3166)
    at java.base/java.lang.Class.getDeclaredMethods(Class.java:2309)
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:463)
    ... 124 more
Caused by: java.lang.ClassNotFoundException: org.redisson.client.codec.Codec
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 128 more
</code></pre>
<p>Here is my dependencies related to Redis and Redisson inside build.gradle:</p>
<pre><code>implementation 'org.springframework.boot:spring-boot-starter-data-redis'
compileOnly &quot;org.redisson:redisson:3.16.0&quot;
compileOnly &quot;org.redisson:redisson-spring-boot-starter:3.16.0&quot;
compileOnly &quot;org.redisson:redisson-spring-data-21:3.16.0&quot;
</code></pre>
<p>My RedisConfiguration</p>
<pre><code>@Configuration
public class RedissonConfig {

    @Bean
    public RedissonConnectionFactory redissonConnectionFactory(RedissonClient redisson) {
        return new RedissonConnectionFactory(redisson);
    }

    @Bean
    public RedisTemplate&lt;Object, Object&gt; redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate&lt;Object, Object&gt; template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean(destroyMethod = &quot;shutdown&quot;)
    public RedissonClient redisson(@Value(&quot;classpath:/redisson.yml&quot;) Resource configFile)
            throws IOException {
        var config = Config.fromYAML(configFile.getInputStream());
        var objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        config.setCodec(new JsonJacksonCodec(objectMapper));
        return Redisson.create(config);
    }

    @Bean
    CacheManager cacheManager(RedissonClient redissonClient) {
        var config = new HashMap&lt;String, CacheConfig&gt;();
        // create &quot;testMap&quot; cache with ttl = 24 minutes and maxIdleTime = 12 minutes
        config.put(&quot;testMap&quot;, new CacheConfig(24*60*1000, 12*60*1000));
        return new RedissonSpringCacheManager(redissonClient, config);
    }
</code></pre>
<p>And my redisson.yml :</p>
<pre><code>singleServerConfig:
  idleConnectionTimeout: 10000
  connectTimeout: 10000
  timeout: 3000
  retryAttempts: 3
  retryInterval: 1500
  password: null
  subscriptionsPerConnection: 5
  clientName: null
  address: &quot;redis://127.0.0.1:6379&quot;
  subscriptionConnectionMinimumIdleSize: 1
  subscriptionConnectionPoolSize: 50
  connectionMinimumIdleSize: 10
  connectionPoolSize: 64
  database: 0
  dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: !&lt;org.redisson.codec.JsonJacksonCodec&gt; {}
</code></pre>
",https://stackoverflow.com/questions/68516438/unit-test-failing-with-redisson,"['spring-boot', 'redis', 'redisson']",1266,False,1,0
XUnit Tests No Longer Working After Upgrade From .NET 5 To .NET 6 (Q &amp; A),"<p>I have an xUnit unit testing project. All was working fine in .NET 5.</p>
<p>In Visual Studio 2022, I changed the .NET Version in the csproj to .NET 6 as shown below.</p>
<p><a href=""https://i.stack.imgur.com/8Berw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/8Berw.png"" alt=""enter image description here"" /></a></p>
<p>Following this, the tests build but no longer run.</p>
<p>There is no info in the output window. The Test Explorer just says it wont run the tests, with 'unexpected error detected'.</p>
<p><a href=""https://i.stack.imgur.com/sG3tV.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/sG3tV.png"" alt=""enter image description here"" /></a></p>
<p>What should I do to fix this?</p>
",https://stackoverflow.com/questions/69972184/xunit-tests-no-longer-working-after-upgrade-from-net-5-to-net-6-q-a,"['xunit', '.net-6.0']",3576,True,1,2
"Why is JSON.parse causing problems in an async unit test, but not in the console?","<p><strong>Context</strong></p>
<p>I'm trying to test as I work through the serverless-stack examples, and am currently unit testing the create.js file given <a href=""https://serverless-stack.com/chapters/add-a-create-note-api.html"" rel=""nofollow noreferrer"">here</a>.</p>
<p><strong>Problem</strong></p>
<p>It's currently a simple test without assertions, but when it hits <code>JSON.parse(event.body)</code> it throws <code>Unexpected token u in JSON at position 0</code>.</p>
<p><strong>create.test.js</strong></p>
<pre><code>import * as create from '../create.js';

test('create', async () =&gt; {
  const event = JSON.stringify({'body': 'event'}); // alternatively '{ &quot;body&quot;: &quot;test&quot; }';
  const context = 'context';
  const callback = (error, response) =&gt; {
    expect(response.statusCode).toEqual(200);
  };

  await create.main(event, context, callback);
});
</code></pre>
<p><strong>create.js</strong></p>
<pre><code>import * as uuid from &quot;uuid&quot;;
import AWS from &quot;aws-sdk&quot;;

const dynamoDb = new AWS.DynamoDB.DocumentClient();

export async function main(event, context) {
  // Request body is passed in as a JSON encoded string in 'event.body'
  const data = JSON.parse(event.body);

  const params = {
    TableName: process.env.tableName,
    Item: {
      // The attributes of the item to be created
      userId: &quot;123&quot;, // The id of the author
      noteId: uuid.v1(), // A unique uuid
      content: data.content, // Parsed from request body
      attachment: data.attachment, // Parsed from request body
      createdAt: Date.now(), // Current Unix timestamp
    },
  };

  try {
    await dynamoDb.put(params).promise();

    return {
      statusCode: 200,
      body: JSON.stringify(params.Item),
    };
  } catch (e) {
    return {
      statusCode: 500,
      body: JSON.stringify({ error: e.message }),
    };
  }
}
</code></pre>
<p>I have tried removing JSON.parse, which works, and I've tried running <code>JSON.parse(JSON.stringify({'body': 'event'}))</code> in the console, which also works.</p>
<p><strong>Question</strong></p>
<p>How can I fix my test so that <code>JSON.parse(event.body)</code> will not throw an error?</p>
",https://stackoverflow.com/questions/66692975/why-is-json-parse-causing-problems-in-an-async-unit-test-but-not-in-the-console,"['javascript', 'json', 'unit-testing', 'async-await']",227,True,-1,1
getting TypeError: expect(...).toBeInTheDocument is not a function,"<p>I am trying to do unit testing with my sidebar component, to check if the text rendered is in the document flow or not, well it is in the document flow but the test case gets failed saying &quot;<em><strong>TypeError: expect(...).toBeInTheDocument is not a function</strong></em>&quot;.
I don't know why it is so, I also imported the jest library in the file still getting same error, please help me.</p>
<p>sidebar.spec.js file</p>
<pre><code>import React from 'react';
import { shallow } from 'enzyme';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
import configureStore from 'redux-mock-store';
import toJson from 'enzyme-to-json';
import { Provider } from 'react-redux';

import Sidebar from './sidebar';

describe('Testing Sidebar component', () =&gt; {
    let wrapper, store;
    const mockStore = configureStore();
    const initialProp = {
        auth: {
            userAuth: {
                firstName: &quot;savitha&quot;,
                lastName: &quot;goel&quot;
            }
        },
        meta: {
            productsMeta: [
                { label: &quot;CX Admin Application&quot; },
                { label: &quot;Application Configuration Management&quot; }
            ]
        }
    };

    beforeEach(() =&gt; {
        store = mockStore(initialProp);
        wrapper = shallow(&lt;Sidebar store={store} /&gt;);
    });

    it('should be defined', () =&gt; {
        expect(wrapper).toBeDefined();
    });

    it('renders correctly', () =&gt; {
        expect(toJson(wrapper)).toMatchSnapshot();
    });

    it('render sidebar options as a text', () =&gt; {
        store = mockStore(initialProp);
        wrapper = shallow(
            &lt;Provider store={store}&gt;
                &lt;Sidebar /&gt;
            &lt;/Provider&gt;
        );

        console.log(store);

        console.log(screen.debug(null, Infinity))
        // const sidebarElement = screen.getByText('Application Manager');
        // expect(sidebarElement).toBeInTheDocument();
    });
});

</code></pre>
<p>my sidebar.js file</p>
<pre><code>import React, { Component } from 'react'
import { connect } from 'react-redux';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faAngleDown, faWrench, faUserCircle, faHome, faDigitalTachograph, faMicrophone, faRecordVinyl } from '@fortawesome/free-solid-svg-icons';
import './_sidebar.scss';

class Sidebar extends Component {
    handleProductSelection(product) {
        this.props.props.history.push(product.path);
    }

    renderProducts = () =&gt; {
    if(this.props.products) {
      return this.props.products.map((product) =&gt; {
        return (&lt;li onClick={() =&gt; this.handleProductSelection(product)}&gt;{product.label}&lt;/li&gt;);
      });
    }
    }

    render() {
        return(
      &lt;div className=&quot;sidebar&quot;&gt;
        &lt;div className=&quot;profileWrap&quot;&gt;
          &lt;div&gt;
            &lt;div className=&quot;userNameWrap&quot;&gt;
              &lt;FontAwesomeIcon icon={faUserCircle} /&gt;
              &lt;span className=&quot;userName&quot;&gt;{this.props.firstName} {this.props.lastName}&lt;/span&gt;
              &lt;span className=&quot;angleIcon&quot;&gt;&lt;FontAwesomeIcon icon={faAngleDown} /&gt;&lt;/span&gt;
            &lt;/div&gt;
            &lt;div className=&quot;userInfoWrap&quot;&gt;
              &lt;ul&gt;
                &lt;li&gt;My profile&lt;/li&gt;
                &lt;li&gt;Help with Console&lt;/li&gt;
                &lt;li&gt;Contact us&lt;/li&gt;
                &lt;li&gt;Log out&lt;/li&gt;
              &lt;/ul&gt;
            &lt;/div&gt;
            &lt;div className=&quot;divisionWrap&quot;&gt;
              Division:
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div className=&quot;sidebarNavigation&quot;&gt;
          &lt;ul&gt;
            &lt;li&gt;
              &lt;div className=&quot;mainMenu&quot;&gt;
                &lt;FontAwesomeIcon icon={faHome} /&gt;
                &lt;span className=&quot;menuName&quot;&gt;Home&lt;/span&gt;
              &lt;/div&gt;
            &lt;/li&gt;
            &lt;li&gt;
              &lt;div className=&quot;mainMenu&quot;&gt;
                &lt;FontAwesomeIcon icon={faDigitalTachograph} /&gt;
                &lt;span className=&quot;menuName&quot;&gt;Mosaic Insights&lt;/span&gt;
                &lt;span className=&quot;angleIcon&quot;&gt;&lt;FontAwesomeIcon icon={faAngleDown} /&gt;&lt;/span&gt;
              &lt;/div&gt;
              &lt;div className=&quot;subMenu&quot;&gt;
                &lt;ul&gt;
                  {this.renderProducts()}
                &lt;/ul&gt;
              &lt;/div&gt;
            &lt;/li&gt;
            &lt;li&gt;
              &lt;div className=&quot;mainMenu&quot;&gt;
                &lt;FontAwesomeIcon icon={faWrench} /&gt;
                &lt;span className=&quot;menuName&quot;&gt;Application Manager&lt;/span&gt;
                &lt;span className=&quot;angleIcon&quot;&gt;&lt;FontAwesomeIcon icon={faAngleDown} /&gt;&lt;/span&gt;
              &lt;/div&gt;
              &lt;div className=&quot;subMenu&quot;&gt;
                &lt;ul&gt;
                  {this.renderProducts()}
                &lt;/ul&gt;
              &lt;/div&gt;
            &lt;/li&gt;
            &lt;li&gt;
              &lt;div className=&quot;mainMenu&quot;&gt;
                &lt;FontAwesomeIcon icon={faMicrophone} /&gt;
                &lt;span className=&quot;menuName&quot;&gt;Call Recording&lt;/span&gt;
                &lt;span className=&quot;angleIcon&quot;&gt;&lt;FontAwesomeIcon icon={faAngleDown} /&gt;&lt;/span&gt;
              &lt;/div&gt;
              &lt;div className=&quot;subMenu&quot;&gt;
                &lt;ul&gt;
                  {this.renderProducts()}
                &lt;/ul&gt;
              &lt;/div&gt;
            &lt;/li&gt;
            &lt;li&gt;
              &lt;div className=&quot;mainMenu&quot;&gt;
                &lt;FontAwesomeIcon icon={faWrench} /&gt;
                &lt;span className=&quot;menuName&quot;&gt;Console Administration&lt;/span&gt;
                &lt;span className=&quot;angleIcon&quot;&gt;&lt;FontAwesomeIcon icon={faAngleDown} /&gt;&lt;/span&gt;
              &lt;/div&gt;
              &lt;div className=&quot;subMenu&quot;&gt;
                &lt;ul&gt;
                  {this.renderProducts()}
                &lt;/ul&gt;
              &lt;/div&gt;
            &lt;/li&gt;
          &lt;/ul&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
    }
}


const mapStateToProps = (state) =&gt; {
  return{
    firstName: state.auth.userAuth.firstName,
    lastName: state.auth.userAuth.lastName,
    products: state.meta.productsMeta
  };
};

export default connect(mapStateToProps)(Sidebar);

</code></pre>
",https://stackoverflow.com/questions/67817951/getting-typeerror-expect-tobeinthedocument-is-not-a-function,"['javascript', 'reactjs', 'jestjs']",2798,False,3,1
How to set up Camunda for unit testing in Spring Boot,"<p>I am able to run a Spring Boot application with Camunda for workflow management. My pom.xml with Camunda related dependencies are shown below.</p>
<pre><code>&lt;dependencyManagement&gt;
        ...
        &lt;dependency&gt;
            &lt;groupId&gt;org.camunda.bpm&lt;/groupId&gt;
            &lt;artifactId&gt;camunda-bom&lt;/artifactId&gt;
            &lt;version&gt;7.15.0&lt;/version&gt;
            &lt;scope&gt;import&lt;/scope&gt;
            &lt;type&gt;pom&lt;/type&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
&lt;/dependencyManagement&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm.springboot&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-bpm-spring-boot-starter&lt;/artifactId&gt;
        &lt;version&gt;7.15.0&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!-- REST API --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm.springboot&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-bpm-spring-boot-starter-rest&lt;/artifactId&gt;
        &lt;version&gt;7.15.0&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!-- dashboard --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm.springboot&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-bpm-spring-boot-starter-webapp&lt;/artifactId&gt;
        &lt;version&gt;7.15.0&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.bpm&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-engine-plugin-spin&lt;/artifactId&gt;
    &lt;/dependency&gt;

    &lt;dependency&gt;
        &lt;groupId&gt;org.camunda.spin&lt;/groupId&gt;
        &lt;artifactId&gt;camunda-spin-dataformat-all&lt;/artifactId&gt;
    &lt;/dependency&gt;
</code></pre>
<p>I have just one .BPMN file. My application.yml file looks like this:</p>
<pre><code>spring.main.banner-mode: console
server.port: 9090

springdoc:
  model-and-view-allowed: true
  swagger-ui:
    operationsSorter: alpha

spring.jpa:
  hibernate:
    ddl-auto: none
  show-sql: true
  properties:
    hibernate:
      format_sql: true
spring.datasource:
  initialization-mode: always
  platform: postgres
  url: jdbc:postgresql://xxxx
  username: xxxx
  password: xxxx

spring.flyway.enabled: false

camunda.bpm:
  admin-user:
    id: demo
    password: demo
  generic-properties:
    properties:
      generalResourceWhitelistPattern: &quot;[a-zA-Z0-9,'_\\$\\-\\.\\+\\!\\*\\(\\)]+|camunda-admin&quot;
</code></pre>
<p>In the codes, all I have to do are just to declare the Camunda objects and I can used them without further setups:</p>
<pre><code>@AutoWired
protected final RuntimeService runtimeService;

@AutoWired
protected final TaskService taskService;

@AutoWired
protected final IdentityService identityService;
</code></pre>
<p>Now I am trying to write unit tests. It seems that there are more than one way to set up Camunda for unit testing, but I am not able to get any of the examples I found working. By some trial and error, I managed to get the following codes to set up Camunda for unit test.</p>
<pre><code>@ActiveProfiles(&quot;test&quot;)
public class EntitlementServiceTest {

    private RuntimeService runtimeService;
    private TaskService taskService;
    private IdentityService identityService;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        ProcessEngine processEngine = ProcessEngineConfiguration.createStandaloneInMemProcessEngineConfiguration()
            .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE)
            .setJdbcUrl(&quot;jdbc:h2:mem:database_user;DB_CLOSE_ON_EXIT=FALSE&quot;)
            .setJobExecutorActivate(true)
            .buildProcessEngine();
        runtimeService = processEngine.getRuntimeService();
        taskService = processEngine.getTaskService();
        identityService = processEngine.getIdentityService();
    }

    ...
}
</code></pre>
<p>But I am not sure if this is the correct way to do so, so it would be better if someone points this out. The codes don't seem to have loaded anything from the application file for unit testing, application-test.yml. Replacing the hardcoded JDBC URL with ${spring.datasource.url} does not work at all. And even though I have set the camunda.bpm.generic-properties.properties.generalResourceWhitelistPattern, application-test.yml, it is obvious that it is not being read.</p>
",https://stackoverflow.com/questions/69345064/how-to-set-up-camunda-for-unit-testing-in-spring-boot,"['java', 'spring-boot', 'unit-testing', 'camunda']",3357,True,4,1
How can I mock an imported dependency with express?,"<p>I am unit-testing an express function. The express function uses an import which I want to mock (stripe). How can I mock an import while using express function? The issue is that it is a global import, if I could somehow make this an argument of the express function my problem would be solved.</p>
<p><strong>express code (exported to the test file as firebase_functions.subscribe)</strong></p>
<pre><code>const functions = require('firebase-functions');
const stripe = require('stripe')(functions.config().stripe.client_id);

module.exports = async function( request, response ) {
  if( !request.query.id_token ) {
    response.status(400).json({message: 'id_token has not been provided'});
    return;
  }

  await admin.auth()
  .verifyIdToken( request.query.id_token )
  .then( id_token =&gt; {
    // pseudo-code: something is done with e.g. 
    const message = await stripe.xxx( id_token ); // returns 'some result I got using the stripe Mock in the process'
    response.status(200).json({message});
    return;
  })
  .catch( error =&gt; {
    return response.status(401).json({message: 'You are currently not logged in as an authorised user'});
  })
}
</code></pre>
<p><strong>excerpt from the test-code</strong></p>
<pre><code>describe('subscribe( request, response)', () =&gt; {
  it( 'should redirect an user to an url for stripe subscriptions', async() =&gt; {
    // arrange
    const response = new ResponseSpy();
    const id_token = await get_id_token();
    const request = { query: { id_token }};
    // act
    await firebase_functions.subscribe( request, response );
    // assert
    assert.deepStrictEqual( result.json, {message: 'some result I got using the stripe Mock in the process'} );
  });
});
</code></pre>
",https://stackoverflow.com/questions/66157457/how-can-i-mock-an-imported-dependency-with-express,"['node.js', 'firebase', 'unit-testing', 'express', 'stripe-payments']",127,False,0,1
How to get PropertyMock for assertions without original PropertyMock object?,"<p>I have a <code>unittest.mock.PropertyMock</code> (<a href=""https://docs.python.org/3/library/unittest.mock.html#unittest.mock.PropertyMock"" rel=""nofollow noreferrer"">docs</a>) object created for unit testing purposes, on an attribute within an object.</p>
<p>I no longer have the reference to the <code>PropertyMock</code> made, as the <code>PropertyMock</code> was monkeypatched in during test setup.</p>
<p>How can I get access to the <code>PropertyMock</code> for assertions, given I have the object with the given <code>property</code>?</p>
<pre class=""lang-py prettyprint-override""><code>from typing import Any
from unittest.mock import PropertyMock

class Foo:
    @property
    def property_1(self) -&gt; int:
        return 1

def make_obj() -&gt; Any:
    &quot;&quot;&quot;Make some object, not returning a reference to the PropertyMock made inside.&quot;&quot;&quot;
    my_obj = Foo()
    type(my_obj).property_1 = PropertyMock(return_value=100)
    # NOTE: function doesn't return the PropertyMock, only the object
    return my_obj

def test_make_obj() -&gt; None:
    made_obj = make_obj()

    # We can see the PropertyMock is in place and works
    assert made_obj.property_1 == 100

    # How can I assert the property was set with 9001?  NOTE: I don't have access
    # to the PropertyMock made above
    made_obj.property_1 = 9001
    type(made_obj).property_1.assert_called_once_with(9001)  # This fails
    # AttributeError: 'int' object has no attribute 'assert_called_once_with'
</code></pre>
<p>In other words:</p>
<ol>
<li>After monkeypatching in the <code>PropertyMock</code></li>
<li>Calling <code>type(my_obj).property_1</code> returns <code>100</code></li>
<li>I want it to return the <code>PropertyMock</code> used (for assertions)</li>
</ol>
",https://stackoverflow.com/questions/68402262/how-to-get-propertymock-for-assertions-without-original-propertymock-object,"['python', 'unit-testing', 'python-unittest.mock']",496,True,0,1
How [call] method works with class components in Vue JS?,"<p>I’m a newbie in Vuejs, I was studying the unit testing handbook today and saw the call method.</p>
<p>So if I don’t want to mount the component to test some complex computed property I can use call passing a different context to the method.</p>
<p>But I’m using Typescript and class components.</p>
<p>So my question is:
Does Call method works with class components?
If so, how does it work?</p>
",https://stackoverflow.com/questions/66310025/how-call-method-works-with-class-components-in-vue-js,"['javascript', 'typescript', 'vuejs2', 'jestjs']",51,False,0,0
Mocking a return value for a Subject - Unit Testing with Jasmine,"<p>I'm unit testing and part of the testing has a Subject. I'm new to Subjects and get the general gist of how they work but am struggling to mock a return value on one. I've tried various ways in the hopes of stumbling on the correct way like using a spy and returnvalue to return the number 3.</p>
<p>In the component:</p>
<pre><code>.... 
private searchEvent: Subject&lt;string&gt; = new Subject&lt;string&gt;();

....
      this.searchEvent.pipe(debounceTime(500)).subscribe(value =&gt; {
        if (value.length &gt;= 3) {
          this.retrieveAssets(value);
        }
      })
....
</code></pre>
<p>In my spec file I basically have:</p>
<pre><code>        component['searchStockEvent'].subscribe(x=&gt; of(3));

        fixture.whenStable().then(() =&gt; {
          expect(component['retrieveAssets']).toHaveBeenCalled();
        });
</code></pre>
",https://stackoverflow.com/questions/68682463/mocking-a-return-value-for-a-subject-unit-testing-with-jasmine,"['testing', 'mocking', 'jasmine', 'subject']",765,True,0,1
How to handle Enums in C# with Data Annotations and testing it with XUnit,"<p>I would like to limit the value for my DTO.</p>
<p>I have an enum of months:</p>
<pre><code>public enum Month
{
    January,
    February,
    March,
    May,
    June,
    July,
    August,
    September,
    October,
    November,
    December
}
</code></pre>
<p>Now in my DTO I have:</p>
<pre><code>public class MyDTO {
    public Month Month{ get; set; }
}
</code></pre>
<p>I need to use a Data Annotation in order to accept only From <code>March</code> to <code>October</code>, and test it. with <code>Xunit</code> as <a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-dotnet-test"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-with-dotnet-test</a></p>
<pre><code>[Fact]
public void valid DTO_Months_ok()
{
    var dto = MyDTO()
    {
        Month = Month.March
    }
    var result = dto.validate();
    Assert.Equal(0, result.Count);
}
</code></pre>
<p>And check with Error</p>
<pre><code>[Fact]
public void valid DTO_Months_Error()
{
    var dto = MyDTO()
    {
        Month = Month.February
    }
    var result = dto.validate();
    Assert.Equal(1, result.Count);
}
</code></pre>
<p>My problem, is with the DataAnnotation.</p>
<p><strong>How to use DataAnnotation with Enum?</strong></p>
",https://stackoverflow.com/questions/69722777/how-to-handle-enums-in-c-with-data-annotations-and-testing-it-with-xunit,"['c#', 'enums', 'data-annotations', 'xunit']",1432,True,0,1
Not able to start embedded server for Kafka for Junit testing,"<p>I am trying to workout already implemented example from github for understanding of Springboot Kafka unit testing through Junit.
I am new to testing.
I am using this code <a href=""https://github.com/yildirimabdullah/spring-kafka-test/tree/master/src/main"" rel=""nofollow noreferrer"">Github </a>
When i try to run it as Junit then it gives me error mentioned below:</p>
<pre><code>2021-06-16 18:14:15.907  INFO 9864 --- [           main] o.a.k.clients.producer.KafkaProducer     : [Producer clientId=producer-1] Closing the Kafka producer with timeoutMillis = 0 ms.
2021-06-16 18:14:15.918  INFO 9864 --- [           -C-1] o.a.k.c.c.internals.ConsumerCoordinator  : [Consumer clientId=consumer-sender-1, groupId=sender] Revoke previously assigned partitions UpdatedBrandEvent-0, UpdatedBrandEvent-1
2021-06-16 18:14:15.918  INFO 9864 --- [           -C-1] o.s.k.l.KafkaMessageListenerContainer    : sender: partitions revoked: [UpdatedBrandEvent-0, UpdatedBrandEvent-1]
2021-06-16 18:14:15.918  INFO 9864 --- [           -C-1] o.a.k.c.c.internals.AbstractCoordinator  : [Consumer clientId=consumer-sender-1, groupId=sender] Member consumer-sender-1-95af1165-2ad8-4ea4-896b-28fbd9cef316 sending LeaveGroup request to coordinator localhost:60727 (id: 2147483647 rack: null) due to the consumer unsubscribed from all topics
2021-06-16 18:14:15.920  INFO 9864 --- [           -C-1] o.a.k.clients.consumer.KafkaConsumer     : [Consumer clientId=consumer-sender-1, groupId=sender] Unsubscribed all topics or patterns and assigned partitions
2021-06-16 18:14:15.920  INFO 9864 --- [           -C-1] o.s.s.c.ThreadPoolTaskScheduler          : Shutting down ExecutorService
2021-06-16 18:14:15.924  INFO 9864 --- [quest-handler-0] k.coordinator.group.GroupCoordinator     : [GroupCoordinator 0]: Member[group.instance.id None, member.id consumer-sender-1-95af1165-2ad8-4ea4-896b-28fbd9cef316] in group sender has left, removing it from the group
2021-06-16 18:14:15.924  INFO 9864 --- [quest-handler-0] k.coordinator.group.GroupCoordinator     : [GroupCoordinator 0]: Preparing to rebalance group sender in state PreparingRebalance with old generation 1 (__consumer_offsets-0) (reason: removing member consumer-sender-1-95af1165-2ad8-4ea4-896b-28fbd9cef316 on LeaveGroup)
2021-06-16 18:14:15.926  INFO 9864 --- [quest-handler-0] k.coordinator.group.GroupCoordinator     : [GroupCoordinator 0]: Group sender with generation 2 is now empty (__consumer_offsets-0)
2021-06-16 18:14:15.936  INFO 9864 --- [           -C-1] essageListenerContainer$ListenerConsumer : sender: Consumer stopped
2021-06-16 18:14:15.964  INFO 9864 --- [           main] kafka.server.KafkaServer                 : [KafkaServer id=0] shutting down
2021-06-16 18:14:15.965  INFO 9864 --- [           main] kafka.server.KafkaServer                 : [KafkaServer id=0] Starting controlled shutdown
2021-06-16 18:14:15.982  INFO 9864 --- [er-event-thread] kafka.controller.KafkaController         : [Controller id=0] Shutting down broker 0
2021-06-16 18:14:15.988  INFO 9864 --- [er-event-thread] state.change.logger                      : [Controller id=0 epoch=1] Sending UpdateMetadata request to brokers HashSet() for 0 partitions
2021-06-16 18:14:15.993  INFO 9864 --- [           main] kafka.server.KafkaServer                 : [KafkaServer id=0] Controlled shutdown succeeded
2021-06-16 18:14:16.002  INFO 9864 --- [           main] icationListener$ChangeEventProcessThread : [/config/changes-event-process-thread]: Shutting down
2021-06-16 18:14:16.003  INFO 9864 --- [-process-thread] icationListener$ChangeEventProcessThread : [/config/changes-event-process-thread]: Stopped
2021-06-16 18:14:16.003  INFO 9864 --- [           main] icationListener$ChangeEventProcessThread : [/config/changes-event-process-thread]: Shutdown completed
2021-06-16 18:14:16.003  INFO 9864 --- [           main] kafka.network.SocketServer               : [SocketServer brokerId=0] Stopping socket server request processors
2021-06-16 18:14:16.012  INFO 9864 --- [           main] kafka.network.SocketServer               : [SocketServer brokerId=0] Stopped socket server request processors
2021-06-16 18:14:16.013  INFO 9864 --- [           main] kafka.server.KafkaRequestHandlerPool     : [data-plane Kafka Request Handler on Broker 0], shutting down
2021-06-16 18:14:16.016  INFO 9864 --- [           main] kafka.server.KafkaRequestHandlerPool     : [data-plane Kafka Request Handler on Broker 0], shut down completely
2021-06-16 18:14:16.020  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-AlterAcls]: Shutting down
2021-06-16 18:14:16.220  INFO 9864 --- [per-0-AlterAcls] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-AlterAcls]: Stopped
2021-06-16 18:14:16.220  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-AlterAcls]: Shutdown completed
2021-06-16 18:14:16.221  INFO 9864 --- [           main] kafka.server.KafkaApis                   : [KafkaApi-0] Shutdown complete.
2021-06-16 18:14:16.222  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-topic]: Shutting down
2021-06-16 18:14:16.309  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-topic]: Shutdown completed
2021-06-16 18:14:16.309  INFO 9864 --- [nReaper-0-topic] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-topic]: Stopped
2021-06-16 18:14:16.312  INFO 9864 --- [           main] k.c.transaction.TransactionCoordinator   : [TransactionCoordinator id=0] Shutting down.
2021-06-16 18:14:16.313  INFO 9864 --- [           main] k.c.transaction.ProducerIdManager        : [ProducerId Manager 0]: Shutdown complete: last producerId assigned 0
2021-06-16 18:14:16.314  INFO 9864 --- [           main] k.c.transaction.TransactionStateManager  : [Transaction State Manager 0]: Shutdown complete
2021-06-16 18:14:16.314  INFO 9864 --- [           main] k.c.t.TransactionMarkerChannelManager    : [Transaction Marker Channel Manager 0]: Shutting down
2021-06-16 18:14:16.318  INFO 9864 --- [rSenderThread-0] k.c.t.TransactionMarkerChannelManager    : [Transaction Marker Channel Manager 0]: Stopped
2021-06-16 18:14:16.318  INFO 9864 --- [           main] k.c.t.TransactionMarkerChannelManager    : [Transaction Marker Channel Manager 0]: Shutdown completed
2021-06-16 18:14:16.319  INFO 9864 --- [           main] k.c.transaction.TransactionCoordinator   : [TransactionCoordinator id=0] Shutdown complete.
2021-06-16 18:14:16.320  INFO 9864 --- [           main] k.coordinator.group.GroupCoordinator     : [GroupCoordinator 0]: Shutting down.
2021-06-16 18:14:16.321  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Heartbeat]: Shutting down
2021-06-16 18:14:16.510  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Heartbeat]: Shutdown completed
2021-06-16 18:14:16.510  INFO 9864 --- [per-0-Heartbeat] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Heartbeat]: Stopped
2021-06-16 18:14:16.511  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Rebalance]: Shutting down
2021-06-16 18:14:16.544  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Rebalance]: Shutdown completed
2021-06-16 18:14:16.544  INFO 9864 --- [per-0-Rebalance] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Rebalance]: Stopped
2021-06-16 18:14:16.545  INFO 9864 --- [           main] k.coordinator.group.GroupCoordinator     : [GroupCoordinator 0]: Shutdown complete.
2021-06-16 18:14:16.545  INFO 9864 --- [           main] kafka.server.ReplicaManager              : [ReplicaManager broker=0] Shutting down
2021-06-16 18:14:16.546  INFO 9864 --- [           main] k.s.ReplicaManager$LogDirFailureHandler  : [LogDirFailureHandler]: Shutting down
2021-06-16 18:14:16.546  INFO 9864 --- [rFailureHandler] k.s.ReplicaManager$LogDirFailureHandler  : [LogDirFailureHandler]: Stopped
2021-06-16 18:14:16.546  INFO 9864 --- [           main] k.s.ReplicaManager$LogDirFailureHandler  : [LogDirFailureHandler]: Shutdown completed
2021-06-16 18:14:16.546  INFO 9864 --- [           main] kafka.server.ReplicaFetcherManager       : [ReplicaFetcherManager on broker 0] shutting down
2021-06-16 18:14:16.548  INFO 9864 --- [           main] kafka.server.ReplicaFetcherManager       : [ReplicaFetcherManager on broker 0] shutdown completed
2021-06-16 18:14:16.548  INFO 9864 --- [           main] kafka.server.ReplicaAlterLogDirsManager  : [ReplicaAlterLogDirsManager on broker 0] shutting down
2021-06-16 18:14:16.548  INFO 9864 --- [           main] kafka.server.ReplicaAlterLogDirsManager  : [ReplicaAlterLogDirsManager on broker 0] shutdown completed
2021-06-16 18:14:16.548  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Fetch]: Shutting down
2021-06-16 18:14:16.618  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Fetch]: Shutdown completed
2021-06-16 18:14:16.618  INFO 9864 --- [nReaper-0-Fetch] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Fetch]: Stopped
2021-06-16 18:14:16.618  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Produce]: Shutting down
2021-06-16 18:14:16.726  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Produce]: Shutdown completed
2021-06-16 18:14:16.726  INFO 9864 --- [eaper-0-Produce] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-Produce]: Stopped
2021-06-16 18:14:16.726  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-DeleteRecords]: Shutting down
2021-06-16 18:14:16.744  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-DeleteRecords]: Shutdown completed
2021-06-16 18:14:16.744  INFO 9864 --- [0-DeleteRecords] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-DeleteRecords]: Stopped
2021-06-16 18:14:16.744  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-ElectLeader]: Shutting down
2021-06-16 18:14:16.945  INFO 9864 --- [r-0-ElectLeader] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-ElectLeader]: Stopped
2021-06-16 18:14:16.945  INFO 9864 --- [           main] perationPurgatory$ExpiredOperationReaper : [ExpirationReaper-0-ElectLeader]: Shutdown completed
2021-06-16 18:14:16.956  INFO 9864 --- [           main] kafka.server.ReplicaManager              : [ReplicaManager broker=0] Shut down completely
2021-06-16 18:14:16.957  INFO 9864 --- [           main] kafka.log.LogManager                     : Shutting down.
2021-06-16 18:14:16.959  INFO 9864 --- [           main] kafka.log.LogCleaner                     : Shutting down the log cleaner.
2021-06-16 18:14:16.960  INFO 9864 --- [           main] kafka.log.LogCleaner                     : [kafka-log-cleaner-thread-0]: Shutting down
2021-06-16 18:14:16.961  INFO 9864 --- [leaner-thread-0] kafka.log.LogCleaner                     : [kafka-log-cleaner-thread-0]: Stopped
2021-06-16 18:14:16.961  INFO 9864 --- [           main] kafka.log.LogCleaner                     : [kafka-log-cleaner-thread-0]: Shutdown completed
2021-06-16 18:14:17.129  INFO 9864 --- [pool-8-thread-1] kafka.log.ProducerStateManager           : [ProducerStateManager partition=__consumer_offsets-0] Writing producer snapshot at offset 2
2021-06-16 18:14:17.280  INFO 9864 --- [           main] kafka.log.LogManager                     : Shutdown complete.
2021-06-16 18:14:17.280  INFO 9864 --- [           main] rollerEventManager$ControllerEventThread : [ControllerEventThread controllerId=0] Shutting down
2021-06-16 18:14:17.281  INFO 9864 --- [           main] rollerEventManager$ControllerEventThread : [ControllerEventThread controllerId=0] Shutdown completed
2021-06-16 18:14:17.281  INFO 9864 --- [er-event-thread] rollerEventManager$ControllerEventThread : [ControllerEventThread controllerId=0] Stopped
2021-06-16 18:14:17.285  INFO 9864 --- [           main] k.controller.ZkPartitionStateMachine     : [PartitionStateMachine controllerId=0] Stopped partition state machine
2021-06-16 18:14:17.286  INFO 9864 --- [           main] kafka.controller.ZkReplicaStateMachine   : [ReplicaStateMachine controllerId=0] Stopped replica state machine
2021-06-16 18:14:17.287  INFO 9864 --- [           main] kafka.controller.RequestSendThread       : [RequestSendThread controllerId=0] Shutting down
2021-06-16 18:14:17.287  INFO 9864 --- [r-0-send-thread] kafka.controller.RequestSendThread       : [RequestSendThread controllerId=0] Stopped
2021-06-16 18:14:17.287  INFO 9864 --- [           main] kafka.controller.RequestSendThread       : [RequestSendThread controllerId=0] Shutdown completed
2021-06-16 18:14:17.288  INFO 9864 --- [           main] kafka.controller.KafkaController         : [Controller id=0] Resigned
2021-06-16 18:14:17.289  INFO 9864 --- [           main] kafka.zookeeper.ZooKeeperClient          : [ZooKeeperClient Kafka server] Closing.
2021-06-16 18:14:17.395  INFO 9864 --- [ain-EventThread] org.apache.zookeeper.ClientCnxn          : EventThread shut down for session: 0x1000683bf6a0000
2021-06-16 18:14:17.395  INFO 9864 --- [           main] org.apache.zookeeper.ZooKeeper           : Session: 0x1000683bf6a0000 closed
2021-06-16 18:14:17.396  INFO 9864 --- [           main] kafka.zookeeper.ZooKeeperClient          : [ZooKeeperClient Kafka server] Closed.
2021-06-16 18:14:17.396  INFO 9864 --- [           main] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Fetch]: Shutting down
2021-06-16 18:14:17.447  INFO 9864 --- [           main] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Fetch]: Shutdown completed
2021-06-16 18:14:17.447  INFO 9864 --- [nelReaper-Fetch] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Fetch]: Stopped
2021-06-16 18:14:17.447  INFO 9864 --- [           main] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Produce]: Shutting down
2021-06-16 18:14:18.447  INFO 9864 --- [lReaper-Produce] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Produce]: Stopped
2021-06-16 18:14:18.447  INFO 9864 --- [           main] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Produce]: Shutdown completed
2021-06-16 18:14:18.447  INFO 9864 --- [           main] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Request]: Shutting down
2021-06-16 18:14:18.453  INFO 9864 --- [           main] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Request]: Shutdown completed
2021-06-16 18:14:18.453  INFO 9864 --- [lReaper-Request] lientQuotaManager$ThrottledChannelReaper : [ThrottledChannelReaper-Request]: Stopped
2021-06-16 18:14:18.454  INFO 9864 --- [           main] kafka.network.SocketServer               : [SocketServer brokerId=0] Shutting down socket server
2021-06-16 18:14:18.482  INFO 9864 --- [           main] kafka.network.SocketServer               : [SocketServer brokerId=0] Shutdown completed
2021-06-16 18:14:18.485  INFO 9864 --- [           main] kafka.server.KafkaServer                 : [KafkaServer id=0] shut down completed
2021-06-16 18:14:18.509  INFO 9864 --- [nnectionExpirer] o.a.z.server.NIOServerCnxnFactory        : ConnnectionExpirerThread interrupted
2021-06-16 18:14:18.509  INFO 9864 --- [electorThread-1] o.a.z.server.NIOServerCnxnFactory        : selector thread exitted run method
2021-06-16 18:14:18.509  INFO 9864 --- [ad:/127.0.0.1:0] o.a.z.server.NIOServerCnxnFactory        : accept thread exitted run method
2021-06-16 18:14:18.510  INFO 9864 --- [electorThread-0] o.a.z.server.NIOServerCnxnFactory        : selector thread exitted run method
2021-06-16 18:14:18.510  INFO 9864 --- [           main] o.a.zookeeper.server.ZooKeeperServer     : shutting down
2021-06-16 18:14:18.511  INFO 9864 --- [           main] o.a.zookeeper.server.SessionTrackerImpl  : Shutting down
2021-06-16 18:14:18.511  INFO 9864 --- [           main] o.a.z.server.PrepRequestProcessor        : Shutting down
2021-06-16 18:14:18.511  INFO 9864 --- [           main] o.a.z.server.SyncRequestProcessor        : Shutting down
2021-06-16 18:14:18.511  INFO 9864 --- [0 cport:60719):] o.a.z.server.PrepRequestProcessor        : PrepRequestProcessor exited loop!
2021-06-16 18:14:18.511  INFO 9864 --- [   SyncThread:0] o.a.z.server.SyncRequestProcessor        : SyncRequestProcessor exited!
2021-06-16 18:14:18.511  INFO 9864 --- [           main] o.a.z.server.FinalRequestProcessor       : shutdown of request processor complete
2021-06-16 18:14:19.207  INFO 9864 --- [ SessionTracker] o.a.zookeeper.server.SessionTrackerImpl  : SessionTrackerImpl exited loop!
</code></pre>
<p>Please help me here as i am running this on my local.Do i need to modify any other configuration files in bin for that.</p>
",https://stackoverflow.com/questions/68003004/not-able-to-start-embedded-server-for-kafka-for-junit-testing,"['junit', 'junit4', 'spring-kafka', 'spring-test']",520,True,0,1
Unit testing: how to stub a wrapper function,"<p>I'm new to unit testing and trying to figure out how to stub a wrapper function. I'm using Sinon/Mocha.</p>
<p>If I have a function like:</p>
<pre><code>const user = await User.findOne({ email: email });
</code></pre>
<p>I've been able to stub it like so:</p>
<pre><code>const userFindOneStub = sandbox.stub(User, 'findOne')
  .returns({
    _id: 'userId1234',
    companies: [
    {
      _id: 'companyId1234'
    }
  ]
});
</code></pre>
<p>But I've had to create a wrapper for my function to reorder the params for a specific function, using Lodash:</p>
<pre><code>const userWrapper = _.rearg(UserFunction, [0, 1, 2, 3, 5, 4]);
const res = await userWrapper(someargs);
</code></pre>
<p>I can stub the <code>UserFunction</code> call, but how would I stub the <code>userWrapper</code> call in a unit test?</p>
",https://stackoverflow.com/questions/67394142/unit-testing-how-to-stub-a-wrapper-function,"['javascript', 'node.js', 'mocha.js', 'sinon']",504,True,0,1
How to mock rest template and response entity,"<p>I m new to JUnit and Mockito concepts and trying to figure out how it's done in a rest template call.
Consider the below rough implementation,</p>
<pre><code>Class TheWrapper{

  @Autowired
  RestTemplate template;

}

Class Abc extends TheWrapper{

  boolean validation(){

      // .....
     //carries out different validation operations
     //  .....

     try{
       
        ResponseEntity&lt;Object&gt; response= template.postForEntity(&quot;localhost:8080...&quot;,obj,Object.class);

        if(response.getStatusCodeValue()==200) // Problem: throwing MyCustomException here, 
                                               // when test is runned
          return true;
        else
          return false;
     
     }catch(Exception e){
        throws new MyCustomException(...);
     }

}
</code></pre>
<p>Now I need to write unit testing in such a way that, I have to mock the rest template call and<br />
check whether the status code is 200 or not.</p>
<pre><code>Class Testing{

  @InjectMock
  Abc obj;

  @Mock
  RestTemplate template;

  @BeforeEach
  void setup(){
    obj=new Abc();
    MockitoAnnotations.initMocks(this);
   }

  @Test
  void testingIt(){
    
   ResponseEntity&lt;Object&gt; response=new ResponseEntity&lt;Object&gt;(HttpStatus.OK);
  
   when(template.postForEntity(&quot;local...&quot;,any(),any())).then(response)

   Assertion.assertEquals(obj.validation(),true);

  }
}
</code></pre>
<p>If this is not the way to implement, please do correct me.</p>
",https://stackoverflow.com/questions/66844295/how-to-mock-rest-template-and-response-entity,"['java', 'spring-boot', 'unit-testing', 'junit', 'mockito']",460,True,0,2
Mock mongoose aggregate function in jest,"<p>I have a middleware as below, for which I am trying to do unit testing using jest,</p>
<p><strong>Middleware:</strong></p>
<pre><code>import Ph from './Ph.model';
fAP = (req, res, next) =&gt; {
        const pN = req.body.pN;
        
        if (pN != null) {

            Ph.aggregate([
                { $match: { 'polNum': { $eq: pN } } },
                {
                    $match: {
                        $expr:
                        {
                            $and: [
                                { $eq: ['$pCS', 'A'] }
                            ]
                        }
                    }
                }
            ]).exec((err, data) =&gt; {

                if (data.length &gt; 0) {
                    req.p = data[0];
                    req.body.pN = data[0].pN;
                    return next();
                } else {
                    return res.json({ message: 'Not found'});
                }

            });
        } else {
            return res.json({ message: 'Cannot be null.'});
        }
    }
</code></pre>
<p><strong>Test code:</strong></p>
<pre><code>import { Request, Response, NextFunction } from 'express';

import PhCtrl from 'Ph.controller';
const PhController = new PhCtrl();

import Ph from './Ph.model';

describe('PhController', () =&gt; {
  let mockRequest: any;
  let mockResponse: any;
  let mockNext: NextFunction = jest.fn();

  beforeEach(() =&gt; {
    mockRequest = {
      body: {
        polNum: ''
      }
    };
    mockResponse = {
      json: jest.fn()
    };
  });

  // fAP middleware
  describe('fAP middleware', () =&gt; {
    // pN is not null and matches
    describe('when pn is not null', () =&gt; {
      // found
      test('should call next when matches', async () =&gt; {
        const mockRequest: any = {
          body: {
            pN: '3028'
          }
        };
        const mockResponse: any = {
          json: jest.fn()
        };
        const mockNext: NextFunction = jest.fn();

        const responseData = require('../../../mock-data/p.json');
        
        Ph.aggregate = jest.fn().mockImplementationOnce(() =&gt; ({
          exec: jest.fn().mockResolvedValueOnce(responseData)
        }));

        await PhController.fAP(
          mockRequest,
          mockResponse,
          mockNext
        );
        expect(mockNext).toHaveBeenCalled();
      });
    });
  });
});

</code></pre>
<p><strong>Error:</strong>
But I am receiving the following error, when I try to mock aggregate function.
In case of findOne, the similar process works, but fail in aggregation method of mongoose. Any help will be appreciated.</p>
<blockquote>
<p>● PhController › fAP middleware › when
pn is not null › should call next when matches</p>
<pre><code>expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: &gt;= 1
Received number of calls:    0

  54 |           mockNext
  55 |         );
&gt; 56 |         expect(mockNext).toHaveBeenCalled();
     |                          ^
  57 |       });
  58 | 
  59 |       // active ph is not found

  at tests/server/api/ph/ph.controller.test.ts:56:26
</code></pre>
</blockquote>
",https://stackoverflow.com/questions/66434808/mock-mongoose-aggregate-function-in-jest,"['node.js', 'typescript', 'unit-testing', 'mongoose', 'jestjs']",1912,True,0,1
Is there any way to unit test a Mapstruct with nested Mapper?,"<p>I'm trying to unit test a Mapstruct nested mapper as follows:</p>
<pre><code>@Mapper(componentModel = &quot;spring&quot;, uses = EventCategoryMapper.class, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface EventMapper {

    
    Event fromEventMO(EventMO eventMO);

    EventMO toEventMO(Event event);

    default Optional&lt;Event&gt; fromOptionalEventMO(Optional&lt;EventMO&gt; optionalEventMO) {
        
        return (optionalEventMO.isEmpty()) ? Optional.empty() : Optional.of(fromEventMO(optionalEventMO.get()));
        
    }
    
}
</code></pre>
<pre><code>@Mapper(componentModel = &quot;spring&quot;, injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface EventCategoryMapper {

    
    EventCategory fromEventCategoryMO(EventCategoryMO eventCategoryMO);

    EventCategoryMO toEventCategoryMO(EventCategory eventCategory);

    default String fromPriorityMO(PriorityMO priority) {
        return (priority.getPriority()==null) ? null : priority.getPriority();
    }

</code></pre>
<p>I'm trying to test the EventMapper:</p>
<pre><code>@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {EventMapper.class, EventCategoryMapper.class, EventMapperImpl.class, EventCategoryMapperImpl.class})
public class EventMapperTest {

    private Mocks mocks; //This object contains the mocked objects that should be mapped.

    @Autowired
    private EventMapper eventMapper;

    @Test
    @DisplayName(&quot;Should return an Event from an EventMO&quot;)
    void shouldReturnEventfromEventMO() {
        
        var event = eventMapper.fromEventMO(mocks.getEventMO());

        assertEquals(event.getId(), 123L);


    }
</code></pre>
<p>But it keeps failing with:</p>
<blockquote>
<p>Error creating bean with name 'eventMapper': Instantiation of bean
failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate
[com.mycompany.cna.projects.fishmarket.back.events.repositories.mappers.event.EventMapper]:
Specified class is an interface</p>
</blockquote>
<p>I've already tried instantiating the mapper with Mapper.getMapper(EventMapper.class) and it returned a NullPointerException.</p>
<p>What should I do to achieve unit testing on those kind of mappers?</p>
",https://stackoverflow.com/questions/70461891/is-there-any-way-to-unit-test-a-mapstruct-with-nested-mapper,"['java', 'spring', 'spring-boot', 'unit-testing', 'mapstruct']",871,True,2,1
How to use ThrowTheSwitch&#39;s Unity C unit testing library?,"<p>How to use ThrowTheSwitch's Unity C unit testing library?</p>
<p>I'm trying to use <a href=""https://github.com/ThrowTheSwitch/Unity/"" rel=""nofollow noreferrer"">ThrowTheSwitch's Unity library</a> to create my unit test in C, but I got some strange errors, but I'm newbie, so this is maybe something basic.</p>
<p>Here is My code:
this is <code>mytest.c</code></p>
<pre><code>int testValue = 45;

int testThisPass(int idx)
{
    if idx == 42
        return 1;
    
    return 0;
}

int testThisNotPass(int idx)
{
    return 42;
} 
</code></pre>
<p>this is <code>mytest.h</code></p>
<pre><code>int testThisPass(int idx);
int testThisNotPass(int idx);
</code></pre>
<p>this is <code>mytestMain.c</code></p>
<pre><code>#include &quot;unity.h&quot;
#include &quot;unity_internals.h&quot;
#include &quot;mytest.h&quot;
#include &lt;stdio.h&gt;

void setUp(void) {
    //testValue = 40;
}

void tearDown(void) {
    // clean stuff up here
}

void test_function_should_doBlahAndBlah(void) {
    TEST_ASSERT_EQUAL(1,testThisPass(42));
}

void test_function_should_doAlsoDoBlah(void) {
    TEST_ASSERT_EQUAL(42, testThisNotPass(5));
}

// not needed when using generate_test_runner.rb
int main(void) {
    UNITY_BEGIN();
    RUN_TEST(test_function_should_doBlahAndBlah);
    RUN_TEST(test_function_should_doAlsoDoBlah);
    return UNITY_END();
}
</code></pre>
<p>And this is the error what I got when I tried to compile <code>mytestMain.c</code>:</p>
<pre><code>/usr/bin/ld: /tmp/ccOOjz1w.o: in function `test_function_should_doBlahAndBlah':
mytestMain.c:(.text+0x24): undefined reference to `testThisPass'
/usr/bin/ld: mytestMain.c:(.text+0x43): undefined reference to `UnityAssertEqualNumber'
/usr/bin/ld: /tmp/ccOOjz1w.o: in function `test_function_should_doAlsoDoBlah':
mytestMain.c:(.text+0x58): undefined reference to `testThisNotPass'
/usr/bin/ld: mytestMain.c:(.text+0x77): undefined reference to `UnityAssertEqualNumber'
/usr/bin/ld: /tmp/ccOOjz1w.o: in function `main':
mytestMain.c:(.text+0x8e): undefined reference to `UnityBegin'
/usr/bin/ld: mytestMain.c:(.text+0xa6): undefined reference to `UnityDefaultTestRun'
/usr/bin/ld: mytestMain.c:(.text+0xbe): undefined reference to `UnityDefaultTestRun'
/usr/bin/ld: mytestMain.c:(.text+0xc3): undefined reference to `UnityEnd'
collect2: error: ld returned 1 exit status
</code></pre>
<p>What Should I do to work? What did I missed here?</p>
",https://stackoverflow.com/questions/69418872/how-to-use-throwtheswitchs-unity-c-unit-testing-library,"['c', 'unit-testing', 'gcc', 'unity-test-framework']",1086,True,2,2
No bean named &#39;entityManagerFactory&#39; available in RestController unsit test with Junit 5,"<p>I am getting 'No bean named 'entityManagerFactory' available' in my junit5 test class even when i am mocking the service layer class.
My understanding is if service layer is mocked, it should not look for actual jpa implementation. I am not understanding what i am missing. My application runs fine with JPA, only problem i am facing in the unit testing with @WebMvcTest</p>
<p><strong>spring boot application class</strong></p>
<pre><code>@SpringBootApplication(
    scanBasePackages = {&quot;com.testapp.rest.auth&quot;})
@EnableJpaRepositories
public class SampleAuthorizationServiceApplication {

  public static void main(String[] args) {
    SpringApplication.run(SampleAuthorizationServiceApplication.class, args);
  }
}
</code></pre>
<p><strong>Controller</strong></p>
<pre><code>@PostMapping(
      value = &quot;/testRest/auth&quot;,
      consumes = MediaType.APPLICATION_JSON_VALUE,
      produces = MediaType.APPLICATION_JSON_VALUE)
  public ResponseEntity&lt;ResObj&gt; testValid(
      @RequestBody ReqObj reqObj, @RequestHeader HttpHeaders headerSet)
      throws SampleTechnicalException {

    ResObj response = authServ.authorize(reqObj);

    if (response.isSuccess()) {
      log.info(&quot;Request processed successfully. response : {}&quot;, response.isSuccess());
      return ResponseEntity.ok(response);
    } else {
      log.error(
          &quot;Request couldn't be processed successfully. response : {}&quot;,
          response.isSuccess());
      return new ResponseEntity&lt;ResObj&gt;(response, HttpStatus.UNAUTHORIZED);
    }
  }
</code></pre>
<p><strong>service</strong></p>
<pre><code>@Service
@AllArgsConstructor
@Slf4j
public class AuthSerive {

  private SampleRepository1 sampleRepository1;

  private SampleRepository2 sampleRepository2;

  public ResObj authorize(ReqObj reqObj) throws SampleTechnicalException {


    if (reqObj == null) {
      throw new SampleTechnicalException(&quot;throw exception&quot;);
    }
    ..
    
}
</code></pre>
<p><strong>Controller Test class</strong></p>
<pre><code>@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = AuthController.class)
class AuthControllerTest {

  @MockBean AuthSerive authServ;

  @Autowired private MockMvc mockMvc;

  

  @Test
  void testAuthSample() throws Exception {
    String jsonreq =
        &quot;{ \&quot;field1\&quot;:\&quot;\&quot;, \&quot;field2\&quot;:\&quot;x\&quot;, \&quot;field3\&quot;:\&quot;\&quot;, \&quot;field4\&quot;:\&quot;\&quot;, \&quot;field5\&quot;:&quot;y&quot;, \&quot;field6\&quot;:\&quot;z\&quot;, \&quot;field7\&quot;:\&quot;x\&quot; }&quot;;
    ResObj mockResponse =
        ResObj.builder().authSuccess(true).errorMessage(null).build();

    ReqObj mockTestObj=
        ReqObj.builder().field2(&quot;x&quot;).field5(&quot;y&quot;).field6(&quot;z&quot;).field7(&quot;x&quot;).build();

    Mockito.when(authServ.authorize(mockTestObj)).thenReturn(mockResponse);

    mockMvc
        .perform(post(&quot;/api/testRest/auth&quot;).contentType(&quot;application/json&quot;).content(jsonreq))
        .andExpect(status().isOk());

     
  }
</code></pre>
<p><strong>build.gradle</strong></p>
<pre><code>dependencies {

    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-web'

    developmentOnly 'org.springframework.boot:spring-boot-devtools'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa'
    implementation 'com.oracle.database.jdbc:ojdbc8:18.3.0.0'
    compileOnly 'org.projectlombok:lombok:1.18.4'
    annotationProcessor 'org.projectlombok:lombok'
    implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.5.8'

    implementation group: 'org.springframework', name: 'spring-context'

    testCompile (&quot;org.springframework.boot:spring-boot-starter-test&quot;) {
        exclude group: &quot;org.mockito&quot;, module: &quot;mockito-all&quot;
    }

    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}
</code></pre>
<p><strong>error</strong></p>
<pre><code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SampleRepository1' defined in com.testapp.rest.auth.repository.SampleRepository1 defined in @EnableJpaRepositories declared on SampleAuthorizationServiceApplication: Cannot create inner bean '(inner bean)#47a7c93e' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#47a7c93e': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:389)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:134)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1689)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1434)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:601)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:925)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:782)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:774)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:439)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:339)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:123)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 68 common frames omitted
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#47a7c93e': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:342)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:113)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:693)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:374)
    ... 87 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
</code></pre>
",https://stackoverflow.com/questions/67835094/no-bean-named-entitymanagerfactory-available-in-restcontroller-unsit-test-with,"['java', 'spring-boot', 'junit', 'mockito', 'junit5']",3832,True,2,2
Check whether a variable has a type at compile time?,"<p>For the purpose of unit testing a new library with complicated types, I want to be able to check whether a provided variable has a given type. This needs to happen at compile time, since the types are erased.</p>
<p>Here's what I have so far:</p>
<pre><code>function hasType&lt;T&gt;(v: T): void{}
</code></pre>
<p>This is only half of the solution: it will compile if <code>v</code> is assignable to <code>T</code>, but it proves nothing about <code>T</code> being assignable to the actual type of <code>v</code>. (e.g. <code>hasType&lt;string|bool&gt;('somestring')</code> will pass.)</p>
",https://stackoverflow.com/questions/69258198/check-whether-a-variable-has-a-type-at-compile-time,['typescript'],85,False,1,0
How to mock a user for unit testing a Spring Security based application?,"<p>My application uses the Spring security configuration shown below, which requires a user to be authenticated. How can I mock a user for unit testing? It looks like I am being authenticated based on the content of <code>MockHttpServletRequest</code>; however, my test fails because I am denied access to the <code>/portfolio</code> endpoint and am instead redirected to the <code>/login</code> endpoint. I have followed the tutorial here: <a href=""https://rieckpil.de/guide-to-testing-spring-boot-applications-with-mockmvc/"" rel=""nofollow noreferrer"">https://rieckpil.de/guide-to-testing-spring-boot-applications-with-mockmvc/</a></p>
<pre><code>MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /portfolio
       Parameters = {}
          Headers = [Content-Type:&quot;multipart/form-data;charset=UTF-8&quot;]
             Body = null
    Session Attrs = {org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN=org.springframework.security.web.csrf.DefaultCsrfToken@3ce7394f, SPRING_SECURITY_CONTEXT=SecurityContextImpl [Authentication=UsernamePasswordAuthenticationToken [Principal=org.springframework.security.core.userdetails.User [Username=user, Password=[PROTECTED], Enabled=true, AccountNonExpired=true, credentialsNonExpired=true, AccountNonLocked=true, Granted Authorities=[ROLE_USER]], Credentials=[PROTECTED], Authenticated=true, Details=null, Granted Authorities=[ROLE_USER]]]}

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 = 302
    Error message = null
          Headers = [X-Content-Type-Options:&quot;nosniff&quot;, X-XSS-Protection:&quot;1; mode=block&quot;, Cache-Control:&quot;no-cache, no-store, max-age=0, must-revalidate&quot;, Pragma:&quot;no-cache&quot;, Expires:&quot;0&quot;, X-Frame-Options:&quot;DENY&quot;, Location:&quot;/login&quot;]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = /login
          Cookies = []

java.lang.AssertionError: Response header 'Location'
Expected: a string containing &quot;/portfolio&quot;
     but: was &quot;/login&quot;
Expected :a string containing &quot;/portfolio&quot;
Actual   :&quot;/login&quot;
&lt;Click to see difference&gt;


    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
    at org.springframework.test.web.servlet.result.HeaderResultMatchers.lambda$string$0(HeaderResultMatchers.java:60)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:196)
    at edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest.uploadPortfolioWithValidFile(PortfolioControllerTest.java:80)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:688)
    at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
    at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
    at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
    at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$6(TestMethodTestDescriptor.java:212)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:208)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:137)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:71)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1507)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:38)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:143)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:129)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:127)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:126)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:84)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:108)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:96)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:84)
    at org.junit.platform.runner.JUnitPlatform.run(JUnitPlatform.java:139)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)

16:35:57.243 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
16:35:57.277 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
16:35:57.400 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest] from class [org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper]
16:35:57.433 [main] INFO org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest], using SpringBootContextLoader
16:35:57.446 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]: class path resource [edu/bu/cs673/stockportfolio/unittests/api/PortfolioControllerTest-context.xml] does not exist
16:35:57.448 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]: class path resource [edu/bu/cs673/stockportfolio/unittests/api/PortfolioControllerTestContext.groovy] does not exist
16:35:57.449 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
16:35:57.450 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]: PortfolioControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
16:35:57.714 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]
16:35:57.818 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [/Users/mlewis/IntelliJProjects/CS673/StockPortfolio/target/classes/edu/bu/cs673/stockportfolio/StockportfolioApplication.class]
16:35:57.820 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration edu.bu.cs673.stockportfolio.StockportfolioApplication for test class edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest
16:35:57.831 [main] DEBUG org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper - @TestExecutionListeners is not present for class [edu.bu.cs673.stockportfolio.unittests.api.PortfolioControllerTest]: using defaults.
16:35:57.834 [main] INFO org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.event.ApplicationEventsTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener, org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener, org.springframework.security.test.context.support.ReactorContextTestExecutionListener]
16:35:57.883 [main] INFO org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@135606db, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@518caac3, org.springframework.test.context.event.ApplicationEventsTestExecutionListener@68034211, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@4f74980d, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@6c372fe6, org.springframework.test.context.support.DirtiesContextTestExecutionListener@58594a11, org.springframework.test.context.transaction.TransactionalTestExecutionListener@2a3888c1, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@4167d97b, org.springframework.test.context.event.EventPublishingTestExecutionListener@14fa86ae, org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener@6e15fe2, org.springframework.security.test.context.support.ReactorContextTestExecutionListener@68f1b17f, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@1722011b, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@57ad2aa7, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@5b3f61ff, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@3e2059ae, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@398dada8, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@7cb502c]
16:35:57.892 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@31920ade testClass = PortfolioControllerTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@1d483de4 testClass = PortfolioControllerTest, locations = '{}', classes = '{class edu.bu.cs673.stockportfolio.StockportfolioApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@4032d386 key = [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration, org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration, org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration, org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration, org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration, org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration, org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration, org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration, org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration, org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration, org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration, org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration, org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration, org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration, org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration, org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration, org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityConfiguration]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@793f29ff, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@543295b0, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@fffa4b8f, org.springframework.boot.test.autoconfigure.OverrideAutoConfigurationContextCustomizerFactory$DisableAutoConfigurationContextCustomizer@7a35b0f5, org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@645aa696, org.springframework.boot.test.autoconfigure.filter.TypeExcludeFiltersContextCustomizer@f44380e2, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@ef800a42, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@480d3575, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@0], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null].
16:35:58.033 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper=true}

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.5.0)

2021-07-31 16:35:59.499  INFO 12834 --- [           main] e.b.c.s.u.api.PortfolioControllerTest    : Starting PortfolioControllerTest using Java 13.0.1 on Michaels-MacBook-Air.local with PID 12834 (started by mlewis in /Users/mlewis/IntelliJProjects/CS673/StockPortfolio)
2021-07-31 16:35:59.504  INFO 12834 --- [           main] e.b.c.s.u.api.PortfolioControllerTest    : No active profile set, falling back to default profiles: default
2021-07-31 16:35:59.582 DEBUG 12834 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@21ec5d87
2021-07-31 16:35:59.904  WARN 12834 --- [kground-preinit] o.s.h.c.j.Jackson2ObjectMapperBuilder    : For Jackson Kotlin classes support please add &quot;com.fasterxml.jackson.module:jackson-module-kotlin&quot; to the classpath
2021-07-31 16:36:02.405  INFO 12834 --- [           main] o.s.s.web.DefaultSecurityFilterChain     : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@fb5aeed, org.springframework.security.web.context.SecurityContextPersistenceFilter@626e0c86, org.springframework.security.web.header.HeaderWriterFilter@51cab489, org.springframework.security.web.csrf.CsrfFilter@528c8c1, org.springframework.security.web.authentication.logout.LogoutFilter@491cafec, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter@e91af20, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@6b8d54da, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@7cf63b9a, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@73893ec1, org.springframework.security.web.session.SessionManagementFilter@15e1f8fe, org.springframework.security.web.access.ExceptionTranslationFilter@7418d76e, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@14c99bf6]
2021-07-31 16:36:02.830 DEBUG 12834 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : ControllerAdvice beans: 0 @ModelAttribute, 0 @InitBinder, 1 RequestBodyAdvice, 1 ResponseBodyAdvice
2021-07-31 16:36:02.963 DEBUG 12834 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : 4 mappings in 'requestMappingHandlerMapping'
2021-07-31 16:36:03.082 DEBUG 12834 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Patterns [/webjars/**, /**] in 'resourceHandlerMapping'
2021-07-31 16:36:03.109 DEBUG 12834 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : ControllerAdvice beans: 0 @ExceptionHandler, 1 ResponseBodyAdvice
2021-07-31 16:36:03.502  INFO 12834 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2021-07-31 16:36:03.503  INFO 12834 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Initializing Servlet ''
2021-07-31 16:36:03.505  INFO 12834 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : Completed initialization in 2 ms
2021-07-31 16:36:03.580  INFO 12834 --- [           main] e.b.c.s.u.api.PortfolioControllerTest    : Started PortfolioControllerTest in 5.499 seconds (JVM running for 8.233)

</code></pre>
<pre><code>@Service
public class AuthenticationService implements AuthenticationProvider {
    private final UserRepository userRepository;
    private final HashService hashService;

    public AuthenticationService(UserRepository userRepository, HashService hashService) {
        this.userRepository = userRepository;
        this.hashService = hashService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();

        User user = userRepository.findAllByUsername(username);
        if (user != null) {
            String encodedSalt = user.getSalt();
            String hashedPassword = hashService.getHashedValue(password, encodedSalt);
            if (user.getPassword().equals(hashedPassword)) {
                return new UsernamePasswordAuthenticationToken(username, password, new ArrayList&lt;&gt;());
            }
        }

        return null;
    }

    @Override
    public boolean supports(Class&lt;?&gt; authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

</code></pre>
<pre><code>
@Component
public class HashService {
    private final FluentLogger log = FluentLoggerFactory.getLogger(HashService.class);

    public String getHashedValue(String data, String salt) {
        byte[] hashedValue = null;

        KeySpec keySpec = new PBEKeySpec(data.toCharArray(), salt.getBytes(), 5000, 128);

        try {
            SecretKeyFactory factory = SecretKeyFactory.getInstance(&quot;PBKDF2WithHmacSHA1&quot;);
            hashedValue = factory.generateSecret(keySpec).getEncoded();
        } catch (InvalidKeySpecException | NoSuchAlgorithmException e) {
            log.error().log(e.getMessage());
        }

        return Base64.getEncoder().encodeToString((hashedValue));
    }
}

</code></pre>
<pre><code>@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final AuthenticationService authenticationService;

    public SecurityConfig(AuthenticationService authenticationService) {
        this.authenticationService = authenticationService;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) {
        auth.authenticationProvider(this.authenticationService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(&quot;/signup&quot;, &quot;/css/*&quot;, &quot;/js/*&quot;, &quot;/images/*&quot;).permitAll()
                .anyRequest().authenticated() // -
                .and()
                .formLogin().loginPage(&quot;/login&quot;).permitAll()
                .and()
                .formLogin().defaultSuccessUrl(&quot;/home&quot;, true)
                .and()
                .logout().permitAll()
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).invalidSessionUrl(&quot;/login&quot;);
    }
}

</code></pre>
<pre><code>@Controller
@RequestMapping(&quot;/portfolio&quot;)
public class PortfolioController {
    private final UserService userService;
    private final PortfolioService portfolioService;
    private final ValidationService validationService;
    private final ResponseService responseService;
    private final FluentLogger log = FluentLoggerFactory.getLogger(PortfolioController.class);

    public PortfolioController(UserService userService, PortfolioService portfolioService,
                               ValidationService validationService, ResponseService responseService) {
        this.userService = userService;
        this.portfolioService = portfolioService;
        this.validationService = validationService;
        this.responseService = responseService;
    }

    @PostMapping
    public String uploadPortfolio(Authentication authentication,
                                  @RequestParam(&quot;csvUpload&quot;)MultipartFile multipartFile, Model model) {
        // Removing implementation details for brevity 
}

</code></pre>
<pre><code>@AutoConfigureMockMvc
@AutoConfigureJsonTesters
@WebMvcTest(PortfolioController.class)
public class PortfolioControllerTest {

    @Autowired
    private MockMvc mvc;

    private MockMultipartFile mockFile;

    @Before
    public void setup() {
        mockFile =
                new MockMultipartFile(
                        &quot;portfolio&quot;,
                        &quot;/Users/name/Downloads/TestPortfolio.csv&quot;,
                        &quot;text/csv&quot;,
                        &quot;portfolio&quot;.getBytes());
    }

    @Test
    @WithMockUser()
    public void uploadPortfolioWithValidFile() throws Exception {
        mvc.perform(
                multipart(&quot;/portfolio&quot;)
                        .file(mockFile))
                .andExpect(header().exists(&quot;Location&quot;))
                .andExpect(header().string(&quot;Location&quot;, Matchers.containsString(&quot;/portfolio&quot;)))
                .andExpect(status().is3xxRedirection());

    }
}

</code></pre>
",https://stackoverflow.com/questions/68598201/how-to-mock-a-user-for-unit-testing-a-spring-security-based-application,"['java', 'spring', 'unit-testing', 'mocking', 'mockito']",617,False,1,0
WebStorm Salesforce Commerce Cloud Testing Error - &#39;C:\Users\...&#39; is not recognized as an internal or external command,"<p>I'm using WebStorm for Salesforce Commerce Cloud development. I have the Salesforce B2C Commerce Cloud plugin installed and it's all working when using sgmf-scripts (<code>npm run compile:scss</code>, <code>npm run compile:js</code>) except for the unit testing script. When I type <code>npm run test</code> I get:</p>
<blockquote>
<p>'C:\Users...' is not recognized as an internal or external command.</p>
</blockquote>
<p>I can't get to the bottom of it, maybe someone here can help.</p>
<p>Here's my package.json:</p>
<pre class=""lang-json prettyprint-override""><code>{
 {
  &quot;name&quot;: &quot;app_custom_radup&quot;,
  &quot;version&quot;: &quot;0.0.1&quot;,
  &quot;description&quot;: &quot;New overlay cartridge&quot;,
  &quot;main&quot;: &quot;index.js&quot;,
  &quot;engines&quot;: {
    &quot;node&quot;: &quot;^12.0.0&quot;
  },
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;sgmf-scripts --test test/unit/**/*.js&quot;,
    &quot;cover&quot;: &quot;sgmf-scripts --cover 'test/unit'&quot;,
    &quot;test:integration&quot;: &quot;sgmf-scripts --integration 'test/integration/**/*.js'&quot;,
    &quot;test:acceptance:custom&quot;: &quot;npx codeceptjs run --plugins retryFailedStep --profile&quot;,
    &quot;test:acceptance:deep&quot;: &quot;npx codeceptjs run --plugins retryFailedStep --grep '(?=.*)^(?!.*@mobile)^(?!.*@tablet)^(?!.*@pageDesigner)' --profile&quot;,
    &quot;test:acceptance:smoke&quot;: &quot;npx codeceptjs run --plugins retryFailedStep --grep @happyPath --profile&quot;,
    &quot;test:acceptance:pagedesigner&quot;: &quot;npx codeceptjs run --plugins retryFailedStep --grep @pageDesigner --profile&quot;,
    &quot;test:acceptance:desktop&quot;: &quot;npx codeceptjs run --plugins retryFailedStep --grep '(?=.*)^(?!.*@mobile)^(?!.*@tablet)^(?!.*@pageDesigner)^(?!.*@deepTest)' --profile&quot;,
    &quot;test:acceptance:mobile&quot;: &quot;npx codeceptjs run --plugins retryFailedStep --profile sauce:phone --grep @mobile&quot;,
    &quot;test:acceptance:tablet&quot;: &quot;npx codeceptjs run --plugins retryFailedStep --profile sauce:tablet --grep @tablet&quot;,
    &quot;test:acceptance:parallel&quot;: &quot;npx codeceptjs run-multiple parallel --plugins retryFailedStep --profile&quot;,
    &quot;test:acceptance:multibrowsers&quot;: &quot;npx codeceptjs run-multiple multibrowsers --plugins retryFailedStep --profile&quot;,
    &quot;test:acceptance:report&quot;: &quot;./node_modules/.bin/allure serve test/acceptance/report&quot;,
    &quot;bdd:snippets&quot;: &quot;./node_modules/.bin/codeceptjs bdd:snippets --path&quot;,
    &quot;compile:scss&quot;: &quot;sgmf-scripts --compile css&quot;,
    &quot;compile:js&quot;: &quot;sgmf-scripts --compile js&quot;,
    &quot;compile:fonts&quot;: &quot;node bin/Makefile compileFonts&quot;,
    &quot;build&quot;: &quot;npm run compile:js &amp;&amp; npm run compile:fonts &amp;&amp; npm run compile:scss&quot;,
    &quot;lint&quot;: &quot;npm run lint:css &amp;&amp; npm run lint:js&quot;,
    &quot;lint:css&quot;: &quot;sgmf-scripts --lint css&quot;,
    &quot;lint:js&quot;: &quot;sgmf-scripts --lint js&quot;,
    &quot;init:isml&quot;: &quot;./node_modules/.bin/isml-linter --init&quot;,
    &quot;lint:isml&quot;: &quot;./node_modules/.bin/isml-linter&quot;,
    &quot;build:isml&quot;: &quot;./node_modules/.bin/isml-linter --build&quot;,
    &quot;fix:isml&quot;: &quot;./node_modules/.bin/isml-linter --autofix&quot;,
    &quot;upload&quot;: &quot;sgmf-scripts --upload&quot;,
    &quot;uploadCartridge&quot;: &quot;sgmf-scripts --uploadCartridge app_custom_radup&quot;,
    &quot;watch&quot;: &quot;sgmf-scripts --watch&quot;,
    &quot;watch:static&quot;: &quot;sgmf-scripts --watch static&quot;,
    &quot;release&quot;: &quot;node bin/Makefile release --&quot;
  },
  &quot;repository&quot;: {
    &quot;type&quot;: &quot;git&quot;,
    &quot;url&quot;: &quot;git+https://github.com/SalesforceCommerceCloud/storefront-reference-architecture.git&quot;
  },
  &quot;author&quot;: &quot;Ilya Volodin &lt;ivolodin@demandware.com&gt;&quot;,
  &quot;license&quot;: &quot;ISC&quot;,
  &quot;homepage&quot;: &quot;https://github.com/SalesforceCommerceCloud/storefront-reference-architecture&quot;,
  &quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;^7.14.6&quot;,
    &quot;@babel/plugin-proposal-object-rest-spread&quot;: &quot;^7.14.5&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.14.5&quot;,
    &quot;@tridnguyen/config&quot;: &quot;^2.3.1&quot;,
    &quot;@wdio/sauce-service&quot;: &quot;^5.14.0&quot;,
    &quot;@wdio/selenium-standalone-service&quot;: &quot;^5.13.2&quot;,
    &quot;allure-commandline&quot;: &quot;^2.13.0&quot;,
    &quot;appium&quot;: &quot;^1.21.0&quot;,
    &quot;babel-core&quot;: &quot;^6.26.3&quot;,
    &quot;babel-loader&quot;: &quot;^8.0.6&quot;,
    &quot;babel-preset-env&quot;: &quot;^1.7.0&quot;,
    &quot;browserslist&quot;: &quot;^4.16.6&quot;,
    &quot;chai&quot;: &quot;^4.3.4&quot;,
    &quot;chai-subset&quot;: &quot;^1.6.0&quot;,
    &quot;chalk&quot;: &quot;^1.1.3&quot;,
    &quot;cheerio&quot;: &quot;0.22.0&quot;,
    &quot;cldr-data&quot;: &quot;^32.0.1&quot;,
    &quot;codeceptjs&quot;: &quot;^2.3.2&quot;,
    &quot;codeceptjs-cucumber&quot;: &quot;^2.0.10&quot;,
    &quot;codeceptjs-saucehelper&quot;: &quot;^1.4.0&quot;,
    &quot;codeceptjs-saucelabs&quot;: &quot;^2.0.6&quot;,
    &quot;codeceptjs-shared&quot;: &quot;^2.0.6&quot;,
    &quot;cross-env&quot;: &quot;^7.0.3&quot;,
    &quot;css-loader&quot;: &quot;^0.28.11&quot;,
    &quot;debug&quot;: &quot;^4.1.1&quot;,
    &quot;deepmerge&quot;: &quot;^3.3.0&quot;,
    &quot;eslint&quot;: &quot;^3.19.0&quot;,
    &quot;eslint-config-airbnb-base&quot;: &quot;^5.0.3&quot;,
    &quot;eslint-plugin-import&quot;: &quot;^1.16.0&quot;,
    &quot;eslint-plugin-sitegenesis&quot;: &quot;~1.0.0&quot;,
    &quot;globalize&quot;: &quot;^1.4.2&quot;,
    &quot;husky&quot;: &quot;^4.2.5&quot;,
    &quot;isml-linter&quot;: &quot;^5.35.3&quot;,
    &quot;istanbul&quot;: &quot;^0.4.5&quot;,
    &quot;lodash&quot;: &quot;^4.17.15&quot;,
    &quot;minimist&quot;: &quot;^1.2.0&quot;,
    &quot;mocha&quot;: &quot;^9.0.1&quot;,
    &quot;mocha-junit-reporter&quot;: &quot;^1.23.1&quot;,
    &quot;moment-timezone&quot;: &quot;^0.5.26&quot;,
    &quot;node-sass&quot;: &quot;^4.12.0&quot;,
    &quot;postcss-loader&quot;: &quot;^2.1.6&quot;,
    &quot;properties-parser&quot;: &quot;^0.3.1&quot;,
    &quot;proxyquire&quot;: &quot;1.7.4&quot;,
    &quot;request-promise&quot;: &quot;^4.2.4&quot;,
    &quot;sass-loader&quot;: &quot;^7.3.1&quot;,
    &quot;selenium-standalone&quot;: &quot;^6.24.0&quot;,
    &quot;sgmf-scripts&quot;: &quot;^2.4.1&quot;,
    &quot;shelljs&quot;: &quot;^0.8.3&quot;,
    &quot;should&quot;: &quot;^13.2.3&quot;,
    &quot;sinon&quot;: &quot;^1.17.7&quot;,
    &quot;style-loader&quot;: &quot;^0.21.0&quot;,
    &quot;stylelint&quot;: &quot;^8.4.0&quot;,
    &quot;stylelint-config-standard&quot;: &quot;^17.0.0&quot;,
    &quot;stylelint-scss&quot;: &quot;^2.5.0&quot;,
    &quot;url&quot;: &quot;^0.11.0&quot;,
    &quot;wdio-sauce-service&quot;: &quot;^0.4.14&quot;,
    &quot;webdriverio&quot;: &quot;^5.14.5&quot;,
    &quot;xml2js&quot;: &quot;^0.4.22&quot;
  },
  &quot;dependencies&quot;: {
    &quot;babel&quot;: &quot;^6.23.0&quot;,
    &quot;bootstrap&quot;: &quot;^5.0.1&quot;,
    &quot;browserslist&quot;: &quot;^4.16.6&quot;,
    &quot;chai-http&quot;: &quot;^4.3.0&quot;,
    &quot;cleave.js&quot;: &quot;^1.5.3&quot;,
    &quot;extract-text-webpack-plugin&quot;: &quot;^3.0.2&quot;,
    &quot;flag-icon-css&quot;: &quot;^2.9.0&quot;,
    &quot;font-awesome&quot;: &quot;^4.7.0&quot;,
    &quot;jquery&quot;: &quot;^3.5.1&quot;,
    &quot;next&quot;: &quot;^11.0.0&quot;,
    &quot;nyc&quot;: &quot;^15.1.0&quot;
  },
  &quot;browserslist&quot;: [
  &quot;defaults&quot;,
  &quot;not IE 11&quot;,
  &quot;maintained node versions&quot;
  ],
  &quot;packageName&quot;: &quot;app_custom_radup&quot;,
  &quot;babel&quot;: {
    &quot;presets&quot;: [
      &quot;env&quot;
    ]
  },
  &quot;husky&quot;: {
    &quot;hooks&quot;: {
      &quot;pre-commit&quot;: &quot;npm run lint&quot;,
      &quot;pre-push&quot;: &quot;npm run test&quot;
    }
  },
  &quot;paths&quot;: {
    &quot;base&quot;: &quot;../storefront-reference-architecture/cartridges/app_storefront_base/&quot;
  }
 }
</code></pre>
<p>And the error when running <code>npm run test</code>:</p>
<pre><code>C:\Users\Radu Popescu\WebstormProjects\SFRA\radup\node_modules\.bin\_mocha &quot;test/unit/**/*.js&quot; --reporter spec
'C:\Users\Radu' is not recognized as an internal or external command, operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! app_custom_radup@0.0.1 test: `sgmf-scripts --test test/unit/**/*.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the app_custom_radup@0.0.1 test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Radu Popescu\AppData\Roaming\npm-cache\_logs\2021-06-18T11_58_20_148Z-debug.log
</code></pre>
<p>Any help would be great!</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/68034846/webstorm-salesforce-commerce-cloud-testing-error-c-users-is-not-recogni,"['node.js', 'unit-testing', 'webstorm', 'package.json', 'salesforce-commerce-cloud']",457,False,1,0
SImulate runtime object mock K8S,"<p>Im using the following function which works.
Now I need to add a unit tests to the below function and I didn't find a simple way how to mock the runtime object of k8s.</p>
<p><strong>This is the function</strong></p>
<pre><code>import(
&quot;k8s.io/apimachinery/pkg/runtime&quot;

)


func GetModified(obj runtime.Object, annotate bool, codec runtime.Encoder) ([]byte, error) {
    var modified []byte
    annotates, err := metadataAccessor.Annotations(obj)
    if err != nil {
        return nil, err
    }

    if annotates == nil {
        annotates = map[string]string{}
    }

    original := annotates[corev1.LastAppliedConfigAnnotation]
    delete(annotates, corev1.LastAppliedConfigAnnotation)
    if err := metadataAccessor.SetAnnotations(obj, annotates); err != nil {
        return nil, err
    }

    modified, err = runtime.Encode(codec, obj)
    if err != nil {
        return nil, err
    }

    if annotate {
        annotates[corev1.LastAppliedConfigAnnotation] = string(modified)
        if err := metadataAccessor.SetAnnotations(obj, annotates); err != nil {
            return nil, err
        }

        modified, err = runtime.Encode(codec, obj)
        if err != nil {
            return nil, err
        }
    }
    annotates[corev1.LastAppliedConfigAnnotation] = original
    if err := metadataAccessor.SetAnnotations(obj, annotates); err != nil {
        return nil, err
    }
    return modified, nil
}
</code></pre>
<p>I want to create a unit test to it but not sure how to simulate the runtime</p>
<p><code>obj runtime.Object</code>
<code>codec runtime.Encoder</code></p>
<p>Any idea how can I <strong>mock</strong> those two values for unit testing?</p>
<p><strong>This is the unit test</strong></p>
<pre><code>func TestGetModified(t *testing.T) {
    
    
    
    type args struct {
        obj      runtime.Object
        annotate bool
        codec    runtime.Encoder
    }
    // HERE I NEED TO PROVIDE THE RUNTIME OBJECT
    args{
        obj:      nil,
        annotate: false,
        codec:    nil,
    }

    tests := []struct {
        name    string
        args    args
        want    []byte
        wantErr bool
    }{{
        name: &quot;test&quot;,
        args: ,
        want:    nil,
        wantErr: false,
    },

    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got, err := GetModified(tt.args.obj, tt.args.annotate, tt.args.codec)
            if (err != nil) != tt.wantErr {
                t.Errorf(&quot;GetModified() error = %v, wantErr %v&quot;, err, tt.wantErr)
                return
            }
            if !reflect.DeepEqual(got, tt.want) {
                t.Errorf(&quot;GetModified() got = %v, want %v&quot;, got, tt.want)
            }
        })
    }
}
</code></pre>
",https://stackoverflow.com/questions/69807058/simulate-runtime-object-mock-k8s,"['go', 'kubernetes']",140,False,1,0
Angular testing ngOnInit with sevice calls,"<p>I am learning unit testing in Angular using jasmine. I have a component in which the <code>ngOnInit()</code> method has certain service calls. Below is my <code>ngOnInit()</code> method:</p>
<pre><code>ngOnInit() {
    this.componentInteractionService.resetCurrentMenu();
    this.router.paramMap.subscribe(params =&gt; {
      this.currentContentUrl = params.get(&quot;currentContentUrl&quot;);
      let tmp = params.get(&quot;contentTitle&quot;);
      this.contentSubstitle = params.get(&quot;contentSubtitle&quot;);
      if (tmp == undefined) {
        let url = this.currentContentUrl;
        this.contentTitle = url.substring(url.lastIndexOf(&quot;/&quot;) + 1, url.length);
      } 
      else {
        this.contentTitle = tmp;
      }
    });
  }
</code></pre>
<p>So how should I test so that all the lines of the <code>ngOnInit()</code> method are covered? I mean I need full code coverage.
In my <code>spec.ts</code>:</p>
<pre><code>it('should call all methods in ngOnInit', () =&gt; {
    component.ngOnInit();
    .......
    .......
  });
</code></pre>
<p>What should I write after <code>component.ngOnInit();</code>? Please help. I can test the first line which is:
<code>this.componentInteractionService.resetCurrentMenu();</code>
But how to test the rest of the lines?</p>
",https://stackoverflow.com/questions/66763095/angular-testing-ngoninit-with-sevice-calls,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",932,False,1,1
Problems to use python unittest mock properly,"<p>I have difficulties to implement unit tests for my python project. I've done unit testing without mocking but this time it's not possible because of SSH.</p>
<p>Here's one of my scripts what I'm currently trying to unit test:</p>
<pre><code>import os
from helpers.ssh_connection import SshConnection


class Certificates:
    def get_certificates(self, env_name):
        try:
            stdin, stdout, stderr = SshConnection().execute_cmd(&quot;get certificate_1&quot;)
            certificate_1 = stdout.read().decode(&quot;utf-8&quot;).strip()
            stdin, stdout, stderr = SshConnection().execute_cmd(f&quot;get certificate_2 by using {env_name}&quot;)
            certificate_2 = stdout.read().decode(&quot;utf-8&quot;).strip()
            print(certificate_1, end=&quot;\n\n&quot;)
            print(certificate_2)
            return True

        except RuntimeError:
            msg = &quot;Unable to run script for certificate list&quot;
            print(msg)
            return False

    def main(self):
        environment = os.environ['IP_ADDRESS']
        ssh_key = os.environ['SSH_KEY_PATH']
        env_name = os.environ['ENV_NAME']

        SshConnection().open_connection(environment, ssh_key)

        print(&quot;Certificates&quot;)
        print(&quot;============&quot;)
        Certificates().get_certificates(env_name)
        SshConnection().close_connection()


if __name__ == &quot;__main__&quot;:
    Certificates().main()
</code></pre>
<p>And here's what I have tried but my coverage is less than 20% and I can't figure out how to increase it:</p>
<pre><code>import os
import unittest
from unittest import mock

@mock.patch('certificates.Certificates')
@mock.patch('helpers.ssh_connection.SshConnection')
class TestCertificates(unittest.TestCase):

    def test_certificates(self, MockCertificates, MockSsh):
        certs = MockCertificates()
        env_name = &quot;env&quot;

        certs.get_certificates(env_name)
        certs.get_certificates.assert_called_once_with(env_name)
        certs.get_certificates.return_value = True

        result = certs.get_certificates(env_name)
        expected = True
        self.assertEqual(expected, result)

    def test_main(self, MockCertificates, MockSsh):
        certs = MockCertificates()
        ssh = MockSsh()

        mock_env_vars = mock.patch.dict(os.environ, {&quot;IP_ADDRESS&quot;: &quot;123.123.123&quot;,
                                                    &quot;SSH_KEY_PATH&quot;: &quot;ssh_keys/ssh&quot;,
                                                    &quot;ENV_NAME&quot;: &quot;env&quot;)

        mock_env_vars.start()

        ssh.open_connection(os.environ[&quot;IP_ADDRESS&quot;], os.environ[&quot;SSH_KEY_PATH&quot;])
        ssh.open_connection.assert_called_once_with(os.environ[&quot;IP_ADDRESS&quot;], os.environ[&quot;SSH_KEY_PATH&quot;])
        certs.get_certificates(os.environ[&quot;ENV_NAME&quot;])
        certs.get_certificates.assert_called_once_with(os.environ[&quot;ENV_NAME&quot;])
        certs.get_certificates.return_value = True

        result = certs.get_certificates(os.environ[&quot;ENV_NAME&quot;])
        expected = True
        self.assertEqual(expected, result)

        ssh.close_connection()
        mock_env_vars.stop()


if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>Please help me to understand how to use mock properly. Thank you very much!</p>
",https://stackoverflow.com/questions/67870861/problems-to-use-python-unittest-mock-properly,"['python', 'python-3.x', 'unit-testing', 'mocking', 'python-unittest']",201,False,1,0
Could not autowire. No beans of &#39;JobRepositoryTestUtils&#39; type found. With SpringBatchTest Annotation added,"<p>I am working on a Spring Batch unit testing using the <code>@SpringBatchTest</code> annotation which is supposed to automatically add the beans for <code>JobLauncherTestUtils</code> and <code>JobRepositoryTestUtils</code>.</p>
<p>Here's the Job configuration class:</p>
<pre><code>@Configuration
@EnableBatchProcessing
public class JobConfiguration {

    @Bean
    public Job getJob(JobBuilderFactory jobBuilderFactory,
                      @Qualifier(&quot;flow_master&quot;) Flow flowMaster) {

        return jobBuilderFactory.get(&quot;job&quot;)
                .incrementer(new RunIdIncrementer())
                .start(flowMaster)
                .build().build();
    }
}
</code></pre>
<p>Here's the Test Class:</p>
<pre><code>@ExtendWith(SpringExtension.class)
@SpringBatchTest
@ContextConfiguration(classes = JobConfiguration.class)
public class SpringBatchTest {

    @Autowired
    private JobLauncherTestUtils jobLauncherTestUtils;

    @Before
    public void clearJobExecutions() {
        this.jobRepositoryTestUtils.removeJobExecutions();
    }

    @Test
    public void testMyJob() throws Exception {

        JobParameters jobParameters = this.jobLauncherTestUtils.getUniqueJobParameters();

        JobExecution jobExecution = this.jobLauncherTestUtils.launchJob(jobParameters);

        Assert.assertEquals(ExitStatus.COMPLETED, jobExecution.getExitStatus());
    }

}
</code></pre>
<p>Problem:</p>
<p>I am getting the error messages:</p>
<ul>
<li><em>Could not autowire. No beans of 'JobLauncherTestUtils' type found.</em></li>
</ul>
<p>I have cloned some repo examples which are supposed to work but I am getting the same error for all of them.</p>
<p>Am I missing something?</p>
",https://stackoverflow.com/questions/67767525/could-not-autowire-no-beans-of-jobrepositorytestutils-type-found-with-spring,"['java', 'spring', 'unit-testing', 'testing', 'spring-batch']",2074,True,1,1
A problem with looping while selecting longest and shortest words using a regex,"<p>I need to select all words of the maximum length and all of the minimum length.</p>
<p>For example:</p>
<pre class=""lang-none prettyprint-override""><code>When I was younger, so much younger than today 
I never needed anybody's help in any way 
But now these days are gone, I'm not so self-assured 
Now I find I've changed my mind 
I've opened up the doors
</code></pre>
<p>Example of the Output:</p>
<pre class=""lang-none prettyprint-override""><code>Min: I, s, m
Max: younger, anybody, assured, changed
</code></pre>
<p>I already figured out the algorithm, but it simply terminates after the sorting loop (with an int k), and I can't why, because the debugger says nothing because of my unit testing. It simply stops.
Could you help me to figure out why it doesn't work pls?
P.S. I can't use container classes</p>
<pre class=""lang-java prettyprint-override""><code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Part2 {

    public static void main(String[] args) {
        String input = Util.getInput(&quot;part2.txt&quot;);
        System.out.print(convert(input));
    }

    public static String convert(String input) {
        Pattern p = Pattern.compile(&quot;[A-zА-я]+&quot;);
        Matcher m = p.matcher(input);
        int i = 0;
        String[] arr = new String[100];
        while (m.find()){
            arr[i] = m.group(0);
            i++;
        }
        StringBuilder longestResult = new StringBuilder();
        longestResult.append(&quot;Max: &quot;);
        StringBuilder shortestResult = new StringBuilder();
        shortestResult.append(&quot;Min: &quot;);
        int longest = 0;
        int shortest = arr[0].length();
        for (int k = 0; k &lt; arr.length; k++){
            if (arr[k].length() &gt; longest){
                longest = arr[k].length();
            }
            if (arr[k].length() &lt; shortest){
                shortest = arr[k].length();
            }
        }
        for ( String word : arr) {
            if (word.length() == longest) {
                longestResult.append(word + &quot;, &quot;);
            }
            if (word.length() == shortest) {
                shortestResult.append(word + &quot;, &quot;);
            }
        }
        return shortestResult.substring(1, shortestResult.length() - 2) +
                longestResult.substring(1, longestResult.length() - 2);
    }
}
</code></pre>
",https://stackoverflow.com/questions/68405684/a-problem-with-looping-while-selecting-longest-and-shortest-words-using-a-regex,"['java', 'regex', 'loops', 'sorting']",47,False,1,1
Unit Testing Stops In Middle When I use Console.Readline(),"<p>I want to mock <code>Console.ReadLine()</code> using MOQ but I do not know how to do that. I tried to search on the internet but I couldn't find an appropriate answer.
I have tried various things but none had worked so far. This is just a demo file. I am working on a console app where I have to use <code>Console.ReadLine()</code>. But I do not know how to mock the function that is using <code>Console.ReadLine()</code>.</p>
<pre><code>using System;

namespace _Calci
{
    public class Operands
    {
        public int num1;
        public int num2;
    }

    public class ret
    {
        public virtual int _ret()
        { 
            return (Int32.Parse(Console.ReadLine()));
        }
    }

    public class Calci : ret
    {
        ret retObj = new ret();

        public int Multiply()
        {
            int result;
            int num1 = 4;
            result = retObj._ret() * num1;

            return result;
        }
    }
}
</code></pre>
<p>Unit Testing File:</p>
<pre><code>using Xunit;
using _Calci;
using Moq;

namespace Testings
{
    public class Testing
    {
        [Fact]
        public void MultiplyTesting()
        {
            Mock&lt;ret&gt; mockingVar = new Mock&lt;ret&gt;();
            mockingVar.Setup(x=&gt; x._ret()).Returns(()=&gt;5);
            Calci calciObj = new Calci();
            int expected = 20;
            int actual = calciObj.Multiply();
        
            Assert.Equal(expected, actual);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/67157278/unit-testing-stops-in-middle-when-i-use-console-readline,"['c#', 'unit-testing', 'mocking', 'moq']",67,True,0,1
Create HTTPCookieStorage for testing,"<p>I'm attempting to Unit test some of my network code. I'm trying to write a test that verifies that <code>HTTPCookie</code>s from a given <code>HTTPCookieStorage</code> is actually added to <code>URLRequest</code> headers.</p>
<p>So, I need a <code>HTTPCookieStorage</code> with a <code>HTTPCookie</code> inside. I attempt to create it like this:</p>
<pre><code>let cookie = HTTPCookie(properties: [
    .name: &quot;name&quot;,
    .value: &quot;value&quot;,
    .domain: &quot;.example.com&quot;,
    .path: &quot;/&quot;,
    .expires: Date(timeIntervalSinceNow: 10),
    .comment: &quot;Test cookie&quot;
])!

let url = URL(string: &quot;www.example.com&quot;)!

let cookieStorage = HTTPCookieStorage()
cookieStorage.cookieAcceptPolicy = .always
cookieStorage.setCookies([someCookie], for: url, mainDocumentURL: nil)
</code></pre>
<p>But at this point <code>cookieStorage</code> is still empty.. I've also tried with:</p>
<pre><code>cookieStorage.setCookie(cookie)
</code></pre>
<p>which also ignore the cookie..</p>
<p><strong>Why is the cookie ignored, and how can I create a <code>HTTPCookieStorage</code> with predictable cookies for unit testing?</strong></p>
",https://stackoverflow.com/questions/69390077/create-httpcookiestorage-for-testing,"['ios', 'swift', 'unit-testing', 'cookies']",1174,True,0,2
What ThreadX uses to do its testing?,"<p>I am a student developing a microcontroller application that uses the Azure RTOS ThreadX, and I never used tests and want to start doing unit testing, integration testing, and automatic tests. I found out the Ceedling and Google Test frameworks, but I would like to know what the community and the ThreadX team uses or recommends to proceed with the tests.</p>
<p>My programming language is C, and I'm using a Cortex M0+.</p>
",https://stackoverflow.com/questions/68845339/what-threadx-uses-to-do-its-testing,"['unit-testing', 'testing', 'threadx', 'azure-rtos']",263,False,0,1
Should I use both Cypress and Jest together?,"<p>I'm learning both Jest and Cypress at same time. I know that they are not direct competitors because Cypress is focused on E2E and Jest on unit testing. For now I have implemented in my project both Jest and Cypress with few tests.</p>
<p>But actually most things I can test in both Cypress and Jest, and often I have hard time to decide with what write my test. Also it is harder to maintain compared to single test library.</p>
<p>I'm wondering - how often is Cypress (or alternative) and Jest (or alternative) used together? Is it really standard and good practice to use both? Or most developers/teams sticks with single one solution and it is fine?</p>
<p><strong>Update edit</strong>: It was a long time since this question was asked. I got compromise that was also suggested in comment. Instead using only Cypress or Cypress + Jest, I'm using Cypress + new Cypress Component Testing (so no Jest). Thanks to that I'm having same library and assertions (easier to manage) but can test both e2e and components.</p>
",https://stackoverflow.com/questions/66217682/should-i-use-both-cypress-and-jest-together,"['vue.js', 'jestjs', 'cypress']",40871,True,65,3
Undefined error when mocking globals with Jest and Create React App,"<p>I'm new to unit testing with JS so apologies if I'm missing something obvious.</p>
<p>I need to mock the <code>navigator.mediaDevices.getUserMedia</code> method for some tests, so have defined the following in <code>setupTests.js</code>:</p>
<pre class=""lang-js prettyprint-override""><code>const mockMedia = {
    getUserMedia: jest.fn().mockImplementation(() =&gt;
        Promise.resolve(
            &quot;stream&quot;
        ))
}
global.navigator.mediaDevices = mockMedia
</code></pre>
<p>This works as expected when testing in the same file:</p>
<pre class=""lang-js prettyprint-override""><code>navigator.mediaDevices.getUserMedia({video:true})
    .then((stream =&gt; console.log(stream)))
</code></pre>
<p>But when testing in my component I get <code>TypeError: Cannot read property 'then' of undefined</code> with the same code.</p>
<p>If I don't try and call the mocked function it appears to exist:</p>
<pre><code>console.log(navigator.mediaDevices)

    {
      getUserMedia: [Function: mockConstructor] { ... }
    }

</code></pre>
<p>But calling results in <code>undefined</code></p>
<p>What am I missing here and thanks in advance</p>
",https://stackoverflow.com/questions/66154949/undefined-error-when-mocking-globals-with-jest-and-create-react-app,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'create-react-app']",548,False,3,1
Entity Framework Core 3: Interface on DBContext good practice?,"<p>Is creating an Interface on DBContext good practice in Entity Framework Core 3.1? Does Microsoft have any documentation on this?</p>
<p>We know that Mocking DBContext in Unit testing is bad practice, however how about creating an Interface over it?</p>
<p><a href=""https://learn.microsoft.com/en-us/ef/core/testing/"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/ef/core/testing/</a></p>
<blockquote>
<p>&quot;However, we never try to mock DbContext or IQueryable. Doing so is
difficult, cumbersome, and fragile. Don't do it.&quot;</p>
</blockquote>
<p><strong>Resources:</strong> <a href=""https://stackoverflow.com/questions/12263514/why-dbcontext-doesnt-implement-idbcontext-interface"">Why DbContext doesn&#39;t implement IDbContext interface?</a></p>
",https://stackoverflow.com/questions/66015128/entity-framework-core-3-interface-on-dbcontext-good-practice,"['c#', '.net', 'entity-framework', '.net-core', 'ef-core-3.0']",841,True,0,1
"Angular Unit Testing using Jasmine and Karma, for a switch case","<p>I am new to angular unit testing</p>
<p>I have implemented a method to convert the data type of the column values(which is of type text) of a particular array, into integer or float. And I used a switch case for this in my product component.</p>
<p>Here is my switch method</p>
<pre class=""lang-js prettyprint-override""><code>
     export() {
       
        this.getProducts().then(() =&gt; {
          let products: Array&lt;Array&lt;any&gt;&gt; = [];
        
        this.productContent = this.productContent.map(product =&gt; {
            ProductConfig.forEach(item =&gt; {
              let columnValue = product[item.column];
              let valueIsString = isNaN(parseFloat(columnValue));
              if (!valueIsString) {
                switch (item.dataType) {
                  case item.dataType = &quot;Integer&quot;: {
                    product[item.column] = parseInt(columnValue);
                    break;
                  }
                  case item.dataType = &quot;Float&quot;: {
                    product[item.column] = parseFloat(columnValue);
                    break;
                  }
                  default: {
                    product[item.column] = columnValue;
                    break;
                  }
                }
              }
            });
            return product;
          });
        
    }

</code></pre>
<p>The productConfig is implemented as below.</p>
<pre class=""lang-js prettyprint-override""><code>export const ProductConfig
  = [
    { column:&quot;Product Code&quot;, dataType: &quot;Integer&quot; },
    { column:&quot;Total Price&quot;, dataType: &quot;Float&quot; },
    { column:&quot;Discounted Price&quot;, dataType: &quot;Float&quot; },
    { column:&quot;Tax&quot;, dataType: &quot;Float&quot; },
  ]
</code></pre>
<p>How can I write a unit test case for the above method using jasmine and karma?</p>
",https://stackoverflow.com/questions/68411211/angular-unit-testing-using-jasmine-and-karma-for-a-switch-case,"['angular', 'unit-testing', 'switch-statement', 'karma-jasmine']",353,False,0,0
How to unit test flink timers using mockito,"<p>I have a process funtion, im using mockito for unit testing.</p>
<pre><code>class SampleProcessFunction : KeyedProcessFunction&lt;String, String, String&gt;() {{
        override fun processElement(dm: String, ctx: Context, out: Collector&lt;String&gt;) {
            var retrieveState = state.value()
            // schedule the next timer  from the current event time
            ctx.timerService().registerEventTimeTimer(ctx.timestamp() + 3000)
        } 
    
     override fun onTimer(scheduledTimer: Long, ctx: OnTimerContext?, out: Collector&lt;String&gt;) {
            val retrieveState = state.value()
    
            if(scheduledTimer == (ctx.timestamp()+3000)) {
                         out.collect(presenceEvent)
            }
        }
}
</code></pre>
<p>I wanted to unit test the process function using mockito</p>
<pre><code> internal class PresenceDetectionProcessFunctionTest {
    
        private lateinit var out: Collector&lt;String&gt;
        private lateinit var mockPresenceState: ValueState&lt;Presence&gt;
    
    
        @BeforeEach
        fun setUp() {
            SampleProcessFunction = SampleProcessFunction()
            out = mock(Collector::class.java) as Collector&lt;PresenceEvent&gt;
            val mockRunTimeContext = mock(RuntimeContext::class.java)
            mockSampleState = mock(ValueState::class.java) as ValueState&lt;SampleState&gt;
           
    
            whenever(mockRunTimeContext.getState(ValueStateDescriptor(&quot;sample-state&quot;, 
             Sample::class.java))).thenReturn(mockSampleState)      
            
             sampleProcessFunction.runtimeContext = mockRunTimeContext
            sampleProcessFunction.open(Configuration())
        }
    
    @Test
    fun `test sample process function`() {
       
        sampleProcessFunction.processElement(&quot;Hellp, context, out)
        Mockito.verify(mockPresenceState, times(1)).update(result.capture())
       }
</code></pre>
<p>How do we test the timer here, in my process fun i have register the event timer, but when I debug throws NPE at <code>ctx.timerService().registerEventTimeTimer(ctx.timestamp() + 3000)</code> in sample  process function as I did not setup any test configuration for timers in my test. How do we test the flink timer functionality here? Any suggestions?</p>
",https://stackoverflow.com/questions/66192493/how-to-unit-test-flink-timers-using-mockito,"['unit-testing', 'timer', 'mockito', 'apache-flink']",1034,True,0,1
Mocking functions in python called from a dictionary,"<p>I have a problem with the code below. I would like to mock the functions in different file for unit testing in the FUNCTION_MAPPING part.</p>
<pre><code>import module.module2 as module_name

FUNCTION_MAPPING = {
1: module_name.foo,
2: module_name.foo2,
3: module_name.foo3
}

def my_func(number):
    function_call = FUNCTION_MAPPING[number]
    result = function_call()
    return result
</code></pre>
<p>For some reason I can not mock those functions. I have tried every possible way that i had knowledge about. If possible i would like not to change the code above.</p>
<p>foo, foo2 and foo3 inner code can be anything print(1), print(2) etc</p>
<p>Code of the unit test:</p>
<pre><code>@patch(&quot;module_of_the_code_above.module_name.foo&quot;,return_value=&quot;Test&quot;)
def test_my_func(self,mocked_foo):
    result = my_func(1)
    nose_tools.assert_equal(result,&quot;Test&quot;)
</code></pre>
",https://stackoverflow.com/questions/68817513/mocking-functions-in-python-called-from-a-dictionary,"['python', 'unit-testing', 'mocking']",94,True,0,2
How to &#39;Ignore&#39; a Method using Python-Mockito?,"<p>I am new to unit testing and the mockito library, and am trying to figure out how to 'skip' or 'ignore' a class instantiation within a method call. I have some code that looks like this:</p>
<pre><code>def main(args):
  ...
  ...
  notify = Notify(some_variables)
  ...
  try:
    ...
    ...
  except Exceptions as err:
    notify.alert(some_variables)
</code></pre>
<p>I tried mocking this method like:</p>
<pre><code>notice_mock = mock()
when(notify).Notify(some_variables).thenReturn(notice_mock)
</code></pre>
<p>However, it still instantiated the class and is throwing errors because of other method calls in that class. Am I misunderstanding the function of mock()? Is there a way to ignore this method?</p>
",https://stackoverflow.com/questions/69441018/how-to-ignore-a-method-using-python-mockito,"['python', 'unit-testing', 'mockito']",77,False,0,1
Unit testing practical scenarios,"<p>Hopefully this question is allowed as it is subjective.
But I'm struggling to discover a real world example as to why you need to do unit testing in Angular? All the example videos I see are basic in the nature of what they're testing for. Most are testing to see if a button is on the page or whatever. But that seems to be a pretty pointless test. Could someone please give me an example?</p>
",https://stackoverflow.com/questions/70156711/unit-testing-practical-scenarios,['angular'],27,True,0,1
Unit testing app using node.js and azure functions with SQL,"<p>How can I start unit testing my application?
First of I wanna test that I can access my SQL database.
Second i wanna test how i can test the creation of a new User</p>
<p>I can't seem to find any documentation on this subject</p>
<p>Which kind of test framework can i use, mocha &amp; chai?</p>
<p>This is my azure function for register</p>
<pre><code>    module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.')
    try {
        await db.startDb(); //start db connection
    } catch (error) {
        console.log(&quot;Error connecting to the database&quot;, error.message)
    }
    
    switch (req.method) {
        case 'GET':
            await get(context, req);
            break;
        case 'POST':
            await post(context, req);
            break
        default:
            context.res = {
                body: &quot;Please get or post&quot;
            };
            break
    }
}

async function get(context, req){
    try{
        let name = req.query.name;
        let user = await db.select(name)
        context.res = {
            body: user
        };
    } catch(error){
        context.res = {
            status: 400,
            body: `No user - ${error.message}`
        }
    }
}

async function post(context, req){
    try{
        let payload = req.body;
        await db.insert(payload)
        console.log(payload)
        
        context.res = {
            body: [&quot;succes&quot;]
        }
    } catch(error){
        context.res = {
            status: 400,
            body: error.message
        }
    }
}
</code></pre>
<p><strong>This is my DB file</strong></p>
<pre><code>const { Connection, Request, TYPES } = require('tedious');
const config = require('./config.json');
const jwt = require(&quot;jsonwebtoken&quot;);
const safeJWT = require(&quot;../middleware/Jwt&quot;)
const bcrypt = require(&quot;bcryptjs&quot;);

var connection = new Connection(config);

function startDb() {
    return new Promise((resolve, reject) =&gt; {
        connection.on('connect', (err) =&gt; {
            if (err) {
                console.log('Connection failed')
                reject(err)
                throw (err);
            } else {
                console.log('Connected')
                resolve();
            }
        })
        connection.connect();
    })
}
module.exports.sqlConnection = connection
module.exports.startDb = startDb
</code></pre>
<p><strong>This is some of my register.js file</strong></p>
<pre><code>    fetch(&quot;http://localhost:7071/api/register&quot;, {
        method: 'POST',
        body: JSON.stringify({
            username: username,
            email: email,
            password: password
        }),
        headers: {
            &quot;Content-Type&quot;: &quot;application/json; charset-UTF-8&quot;
        }
    }).then((response) =&gt;
        response.json()).then((data) =&gt; {
            if(data[0] = &quot;succes&quot;){
            location.href = &quot;login.html&quot;
            } else {
                alert(&quot;failed&quot;)
            }
        }).catch((err) =&gt; {
            console.log(err)
        })
})
</code></pre>
",https://stackoverflow.com/questions/67473484/unit-testing-app-using-node-js-and-azure-functions-with-sql,"['javascript', 'sql', 'node.js', 'azure', 'unit-testing']",229,True,0,1
Laravel mocking route parameters,"<p>I am currently unit testing some of my form validation and need to mock a route parameter so that it can pass the tests. I've set up what I thought was the right expectation for the request but I've not done something correctly.</p>
<pre><code>Rule::unique('users')-&gt;ignore($this-&gt;route('user')-&gt;id)
</code></pre>
<p>This is the test mock that I'm attempting to get to pass. Everything I&quot;m attempting to do turns up as that the user property on the route is null.</p>
<pre><code>$userMock = $this-&gt;mock(User::class)-&gt;expects()-&gt;set('id', 1);

$requestMock = $this-&gt;mock(Request::class)
        -&gt;makePartial()
        -&gt;shouldReceive('route')
        -&gt;set('user', $user)
        -&gt;once()
        -&gt;andReturn(\Mockery::self());

$this-&gt;mock(Rule::class, function ($mock) use ($userMock, $requestMock) {
    $mock-&gt;expects()-&gt;unique('user')-&gt;andReturns(\Mockery::self());
    $mock-&gt;expects()-&gt;ignore($requestMock)-&gt;andReturns(\Mockery::self());
});
</code></pre>
",https://stackoverflow.com/questions/69058674/laravel-mocking-route-parameters,"['php', 'laravel', 'testing', 'phpunit', 'mockery']",610,True,0,1
How to unit test a function inside a Higher Order Function in JavaScript?,"<p>How to adapt unit tests for an existing function that needs to be wrapped in a Higher Order Function?</p>
<p>I have two functions. <code>getServerProps()</code> fetching data and <code>isAuthenticated()</code> checking user authentication. Both in separate modules with their own unit tests.</p>
<pre><code>export function isAuthenticated(getServerProps) {
  return async function (param1, param2, param3) {

    const isLoggedIn = await authService()

    if (!isLoggedIn) {
      return { shouldRedirect: true };
    }
    
    const serverProps = await getServerProps(param1, param2, param3);
    return { shouldRedirect: false, ...serverProps };
  };
}
</code></pre>
<p>.</p>
<pre><code>export async function getServerProps(param1, param2, param3) {
  const data = new DataService(param1, param2, param3);
  return { ...data };
}
</code></pre>
<p>Changing the export of the second function to <code>isAuthenticated(getServerProps)</code> mixes two functions in one unit. How to isolate the initial <code>getServerProps()</code> for the purpose of unit testing?</p>
<p>What's the best way to write tests in such a situation?</p>
",https://stackoverflow.com/questions/70317492/how-to-unit-test-a-function-inside-a-higher-order-function-in-javascript,"['javascript', 'unit-testing', 'jestjs']",89,False,0,0
How to test Observable with subscribe function in Angular?,"<p>I have the following function in component.</p>
<pre><code>@Output() data: EventEmitter&lt;any&gt; = new EventEmitter();

testData() {
    observableRef.subscribe(() =&gt; {
      this.data.emit();
    }, () =&gt; {
      this.data.emit();
    });
  }
</code></pre>
<p>I would like to write the unit test cases for the above function, I have tried like the below:</p>
<pre><code>it('should call testData method', fakeAsync(() =&gt; {
    fixture.detectChanges();
    spyOn(observableRef, 'emit’);
    component.testData(component.data);
    expect(component.data.emit).toHaveBeenCalled();
    tick();
    discardPeriodicTasks();
}));
</code></pre>
<p>But, after running this test case, the code coverage is not going inside of subscribe function. I am not sure why, actually I am new to this unit testing, can anyone please help me on this to go inside subscribe and make it test case looks good.</p>
",https://stackoverflow.com/questions/68032826/how-to-test-observable-with-subscribe-function-in-angular,"['angular', 'typescript', 'unit-testing', 'jasmine', 'observable']",285,False,0,1
Writing better fixtures for unit tests in .Net Core,"<p>I'm fairly new to unit testing in the .Net Core. I'm writing unit tests for an <code>Interactor</code> class, whose responsibility is to get<code>Client</code>s either by email or name using the <code>IClientGateway</code> dependency. I've used <code>XUnit</code>, <code>Moq.AutoMock</code> and <code>FluentAssertions</code>.</p>
<h3><code>GetClientsInteractorTest.cs</code></h3>
<pre class=""lang-cs prettyprint-override""><code>[Trait(&quot;Clients&quot;, &quot;GetClientsInteractor&quot;)]
[Collection(nameof(GetClientsInteractorTestsCollectionFixture))]
public class GetClientsInteractorTests
{
    private readonly GetClientsInteractorTestsFixture fixture;

    public GetClientsInteractorTests(GetClientsInteractorTestsFixture fixture) =&gt;
        this.fixture = fixture;

    [Theory(DisplayName = &quot;should return clients in clientsGateway&quot;)]
    [MemberData(nameof(GetClientsInteractorTestsFixture.Params), MemberType = typeof(GetClientsInteractorTestsFixture))]
    public async Task ShouldReturnClients(IEnumerable&lt;Client&gt; mockedClients, CancellationTokenSource cancellationTokenSource,
                                            GetClientsRequest request, GetClientsResponse expectedResponse)
    {
        // Arrange
        fixture.Mocker.GetMock&lt;IClientGateway&gt;()
            .Setup(ClientGateway =&gt; ClientGateway.GetByNameAsync(request.Name, cancellationTokenSource.Token))
            .ReturnsAsync(mockedClients.Where(client =&gt; client.Name.Equals(request.Name)))
            .Verifiable();
        fixture.Mocker.GetMock&lt;IClientGateway&gt;()
            .Setup(ClientGateway =&gt; ClientGateway.GetByEmailAsync(request.Email, cancellationTokenSource.Token))
            .ReturnsAsync(mockedClients.Where(client =&gt; client.Email.Equals(request.Email)))
            .Verifiable();
        // Act
        GetClientsResponse actualResponse =
            await fixture.Mocker.CreateInstance&lt;GetClientsInteractor&gt;()
            .Handle(request, cancellationTokenSource.Token);
        // Assert
        if(request.Name != null)
            fixture.Mocker.GetMock&lt;IClientGateway&gt;()
                .Verify(mock =&gt; mock.GetByNameAsync(request.Name, cancellationTokenSource.Token), Times.Once(), &quot;GetByNameAsync was not called&quot;);
        else if (request.Email != null)
            fixture.Mocker.GetMock&lt;IClientGateway&gt;()
                .Verify(mock =&gt; mock.GetByEmailAsync(request.Email, cancellationTokenSource.Token), Times.Once(), &quot;GetByEmailAsync was not called&quot;);
        actualResponse.Should()
            .Be(expectedResponse);
    }
}
</code></pre>
<h3><code>GetClientsInteractorTestsFixture.cs</code></h3>
<pre class=""lang-cs prettyprint-override""><code>public class GetClientsInteractorTestsFixture
{
    public AutoMocker Mocker = new AutoMocker(MockBehavior.Strict);

    public static IEnumerable&lt;Client&gt; mockedClients = new Client[] {
            new Client()
            {
                ClientId = 1,
                Name = &quot;Victor&quot;,
                Email = &quot;someEmail@someProvider.com&quot;
            },
        };

    public static CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

    public static IEnumerable&lt;object[]&gt; Params = new[]
    {
        new object[]
        {
            mockedClients,
            cancellationTokenSource,
            new GetClientsRequest(),
            new GetClientsResponse()
        },

        new object[]
        {
            mockedClients,
            cancellationTokenSource,
            new GetClientsRequest(){ Name = &quot;Victor&quot; },
            new GetClientsResponse(){ Clients = new List&lt;ClientDto&gt;()
                {
                    new ClientDto()
                    {
                        Id = 1,
                        Name = &quot;Victor&quot;,
                        Email = &quot;someEmail@someProvider.com&quot;
                    }
                }
            }
        },

        new object[]
        {
            mockedClients,
            cancellationTokenSource,
            new GetClientsRequest(){ Email = &quot;someEmail@someProvider.com&quot;},
            new GetClientsResponse(){ Clients = new List&lt;ClientDto&gt;()
                {
                    new ClientDto()
                    {
                        Id = 1,
                        Name = &quot;Victor&quot;,
                        Email = &quot;someEmail@someProvider.com&quot;
                    }
                }
            }
        },
    };
}
</code></pre>
<p>The unit test itself (<code>ShouldReturnClients</code>) its quite simple at first, but it requires 4 parameters (plus <code>AutoMocker</code>) as a test fixture, found in <code>GetClientsInteractorTestsFixture</code>. Is there a better way to make this test fixture by making it less repetitive? perhaps using something like <code>AutoFixture</code>?</p>
",https://stackoverflow.com/questions/66545620/writing-better-fixtures-for-unit-tests-in-net-core,"['c#', 'unit-testing', 'moq', 'xunit', 'autofixture']",2206,True,-1,1
Writing unit test for a flask application using unittest,"<p>I am new to unit testing and I am trying to write a test for the coed I wrote which is a commenting system that saves comments and some extra information to a database. here is the code:</p>
<pre><code>@app.route(&quot;/&quot;, methods=[&quot;GET&quot;, &quot;POST&quot;])
def home():

    if request.method == &quot;POST&quot;:
        ip_address = request.remote_addr
        entry_content = request.form.get(&quot;content&quot;)
        formatted_date = datetime.datetime.today().strftime(&quot;%Y-%m-%d/%H:%M&quot;)
        app.db.entries.insert({&quot;content&quot;: entry_content, &quot;date&quot;: formatted_date, &quot;IP&quot;: ip_address})

    return &quot;GET method called&quot;

</code></pre>
<p>I want to write a test to check the post part of it but I don't know how to pass content in post method and make sure everything is ok.</p>
<p>Can you please help me with this?</p>
",https://stackoverflow.com/questions/69853072/writing-unit-test-for-a-flask-application-using-unittest,"['python-3.x', 'unit-testing', 'flask', 'python-unittest']",6540,True,0,1
GitLab CI Cypress E2E Hangs on &quot;Verifying Cypress&quot;,"<p>I am learning how to use GitLab CI / CD. My example project is a boilerplate VueJS App.</p>
<p>I have unit testing, docker builds and push to registry working, but I am struggling with Cypress e2e testing.</p>
<p>The e2e tests hang when verifying cypress and the test never ends. Here is the output of log.</p>
<pre><code>Running with gitlab-runner 13.8.0 (775dd39d)
  on Cypress/base:14.15.4 GGTzNUZr
Preparing the &quot;docker&quot; executor
00:12
Using Docker executor with image cypress/base:14.15.4 ...
Pulling docker image cypress/base:14.15.4 ...
Using docker image sha256:7bdb668124f5113a85870e35e904cda83549e6d2953493b1a3f566f63b242161 for cypress/base:14.15.4 with digest cypress/base@sha256:dad8727e107f61f48a3c6ef22cb651069cfd29fd377addcfbd7986c0a2659903 ...
Preparing environment
00:01
Running on runner-ggtznuzr-project-5-concurrent-0 via a467d812c00c...
Getting source from Git repository
00:01
Fetching changes with git depth set to 50...
Initialized empty Git repository in /builds/learning/gitlab/vuejs_devops/.git/
Created fresh repository.
Checking out 127f8b87 as master...
Skipping Git submodules setup
Executing &quot;step_script&quot; stage of the job script
59:46
$ npm install
&gt; nodent-runtime@3.2.1 install /builds/learning/gitlab/vuejs_devops/node_modules/nodent-runtime
&gt; node build.js
## Built /builds/learning/gitlab/vuejs_devops/node_modules/nodent-runtime/dist/index.js
&gt; yorkie@2.0.0 install /builds/learning/gitlab/vuejs_devops/node_modules/yorkie
&gt; node bin/install.js
CI detected, skipping Git hooks installation
&gt; node-sass@4.14.1 install /builds/learning/gitlab/vuejs_devops/node_modules/node-sass
&gt; node scripts/install.js
Downloading binary from https://github.com/sass/node-sass/releases/download/v4.14.1/linux-x64-83_binding.node
Download complete
Binary saved to /builds/learning/gitlab/vuejs_devops/node_modules/node-sass/vendor/linux-x64-83/binding.node
Caching binary to /root/.npm/node-sass/4.14.1/linux-x64-83_binding.node
&gt; core-js@2.6.12 postinstall /builds/learning/gitlab/vuejs_devops/node_modules/@babel/runtime-corejs2/node_modules/core-js
&gt; node -e &quot;try{require('./postinstall')}catch(e){}&quot;
&gt; core-js@3.8.3 postinstall /builds/learning/gitlab/vuejs_devops/node_modules/core-js
&gt; node -e &quot;try{require('./postinstall')}catch(e){}&quot;
&gt; ejs@2.7.4 postinstall /builds/learning/gitlab/vuejs_devops/node_modules/ejs
&gt; node ./postinstall.js
&gt; cypress@3.8.3 postinstall /builds/learning/gitlab/vuejs_devops/node_modules/cypress
&gt; node index.js --exec install
[08:07:00]  Downloading Cypress     [started]
[08:07:03]  Downloading Cypress     [completed]
[08:07:03]  Unzipping Cypress       [started]
[08:07:08]  Unzipping Cypress       [completed]
[08:07:08]  Finishing Installation  [started]
[08:07:08]  Finishing Installation  [completed]
&gt; node-sass@4.14.1 postinstall /builds/learning/gitlab/vuejs_devops/node_modules/node-sass
&gt; node scripts/build.js
Binary found at /builds/learning/gitlab/vuejs_devops/node_modules/node-sass/vendor/linux-x64-83/binding.node
Testing binary
Binary is fine
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules/webpack-dev-server/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {&quot;os&quot;:&quot;darwin&quot;,&quot;arch&quot;:&quot;any&quot;} (current: {&quot;os&quot;:&quot;linux&quot;,&quot;arch&quot;:&quot;x64&quot;})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules/watchpack-chokidar2/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {&quot;os&quot;:&quot;darwin&quot;,&quot;arch&quot;:&quot;any&quot;} (current: {&quot;os&quot;:&quot;linux&quot;,&quot;arch&quot;:&quot;x64&quot;})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules/mochapack/node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {&quot;os&quot;:&quot;darwin&quot;,&quot;arch&quot;:&quot;any&quot;} (current: {&quot;os&quot;:&quot;linux&quot;,&quot;arch&quot;:&quot;x64&quot;})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.1 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.1: wanted {&quot;os&quot;:&quot;darwin&quot;,&quot;arch&quot;:&quot;any&quot;} (current: {&quot;os&quot;:&quot;linux&quot;,&quot;arch&quot;:&quot;x64&quot;})
added 1610 packages from 1535 contributors and audited 1617 packages in 30.945s
72 packages are looking for funding
  run `npm fund` for details
found 3 low severity vulnerabilities
  run `npm audit fix` to fix them, or `npm audit` for details
$ npm run test:unit
&gt; cicd_test@0.1.0 test:unit /builds/learning/gitlab/vuejs_devops
&gt; vue-cli-service test:unit
Download the Vue Devtools extension for a better development experience:
https://github.com/vuejs/vue-devtools
You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
 WEBPACK  Compiling...
 DONE  Compiled successfully in 2532ms
 WEBPACK  Compiled successfully in 2532ms
 MOCHA  Testing...
  HelloWorld.vue
    ✓ renders props.msg when passed
  1 passing (24ms)
 MOCHA  Tests completed successfully
$ npm run test:e2e
&gt; cicd_test@0.1.0 test:e2e /builds/learning/gitlab/vuejs_devops
&gt; vue-cli-service test:e2e
 INFO  Starting e2e tests...
 INFO  Starting development server...
 DONE  Compiled successfully in 5366ms8:07:24 AM
  App running at:
  - Local:   http://localhost:8080/ 
  It seems you are running Vue CLI inside a container.
  Access the dev server via http://localhost:&lt;your container's external mapped port&gt;/
  App is served in production mode.
  Note this is for preview or E2E testing only.
[08:07:24]  Verifying Cypress can run /root/.cache/Cypress/3.8.3/Cypress [started]
[08:07:26]  Verifying Cypress can run /root/.cache/Cypress/3.8.3/Cypress [completed]
ERROR: Job failed: execution took longer than 1h0m0s seconds
</code></pre>
<p>Here is my <code>.gitlab-ci.yml</code> file</p>
<pre><code>stages:
  - test
  - build

test:
  stage: test
  tags:
    - e2e-test
  script:
    - npm install
    - npm run test:unit
    - npm run test:e2e


docker-build:
  tags:
    - DOCKER
  image: docker:latest
  stage: build
  services:
    - docker:dind
  before_script:
    - echo $CI_BUILD_TOKEN | docker login -u &quot;$CI_REGISTRY_USER&quot; --password-stdin $CI_REGISTRY
  script:
    - docker build --pull -t &quot;$CI_REGISTRY_IMAGE&quot; .
    - docker push &quot;$CI_REGISTRY_IMAGE&quot;
</code></pre>
<p>My GitLab runner is using a docker image version <code>cypress/base:14.15.4</code> although I have also tried <code>cypress/base:10</code></p>
",https://stackoverflow.com/questions/66006177/gitlab-ci-cypress-e2e-hangs-on-verifying-cypress,"['docker', 'testing', 'continuous-integration', 'gitlab', 'cypress']",873,True,0,1
Autofac.Extras.Moq - response from mocked Login does not contain expected value,"<p>I want to make unit tests in my app. I use NUNIT, and the following libraries :</p>
<ul>
<li>Autofac.Extras.Moq</li>
<li>AutoFixture</li>
</ul>
<p>I followed this samples but it doesn't work :</p>
<ul>
<li><a href=""http://makanda.io/unit-testing-xamarin-forms-view-model/"" rel=""nofollow noreferrer"">http://makanda.io/unit-testing-xamarin-forms-view-model/</a></li>
<li><a href=""https://stackoverflow.com/questions/68665858/mock-a-method-of-class-under-test-with-moq-automock"">Mock a method of class under test with Moq &amp; AutoMock</a></li>
</ul>
<p>Here is my test :</p>
<pre class=""lang-cs prettyprint-override""><code>private Fixture _fixture;

[SetUp]
public void Setup()
{
   _fixture = new Fixture();
}

[Test]
public void Login_Success()
{
   using (var mock = AutoMock.GetLoose())
   {
      var infosLogin = _fixture.Create&lt;LoginRequest&gt;();
      var loginResponse = _fixture.Create&lt;LoginResponse&gt;();

      var userService = mock.Mock&lt;IUserService&gt;();
      userService
         .Setup(user =&gt; user.Login(infosLogin))
         .Returns(Task.FromResult(loginResponse));

      var viewModel = new MainPageViewModel(new ContentPage(), userService.Object);

      viewModel.Login = infosLogin.Username;
      viewModel.Password = infosLogin.Password;
      viewModel.LoginCommand.Execute(null);
   }
}
</code></pre>
<p>My view</p>
<pre class=""lang-cs prettyprint-override""><code>public MainPage()
{
   InitializeComponent();
   BindingContext = new MainPageViewModel(this, new UserServiceImpl());
}
</code></pre>
<p>My ViewModel</p>
<pre class=""lang-cs prettyprint-override""><code>public MainPageViewModel(Page page, IUserService userService)
{
   _page = page;
   _userService = userService;

   Login = &quot;&quot;;
   Password = &quot;&quot;;
}

public Command LoginCommand
{
   get
   {
      return new Command(async () =&gt;
      {
         Console.WriteLine(&quot;step 1...&quot;);

         if (!string.IsNullOrEmpty(Login) &amp;&amp; !string.IsNullOrEmpty(Password))
         {
            Console.WriteLine(&quot;step 2...&quot;);
            var infos = new LoginRequest() { Username = &quot;Wyllis&quot;, Password = &quot;test&quot; };
            LoginResponse response = await _userService.Login(infos);
            Console.WriteLine(&quot;step 3...&quot;);
            Console.WriteLine(response);
            Age = response.Age; // Got error : Object reference not set to an instance of an object
         }
      });
   }
}
</code></pre>
<p>LoginResponse model</p>
<pre class=""lang-cs prettyprint-override""><code>public class LoginResponse
{
   public string Username { get; set; }
   public string Age { get; set; }
}
</code></pre>
<p><code>Age = response.Age;</code>, I Got error : Object reference not set to an instance of an object, can you explain what is wrong ?</p>
",https://stackoverflow.com/questions/70509232/autofac-extras-moq-response-from-mocked-login-does-not-contain-expected-value,"['c#', 'unit-testing', 'xamarin.forms', 'mocking', 'autofac']",210,True,0,1
How to pass parameter using laravel&#39;s Request?,"<p>Currently we're doing unit testing in Laravel, and I just noticed my colleague this line below (its working fine though). I look for a <a href=""https://laravel.com/docs/8.x/requests"" rel=""nofollow noreferrer"">documentation</a> in Laravel about this but I can't find it. It seems all we're just focusing on getting the request input values in the <a href=""https://laravel.com/docs/8.x/requests"" rel=""nofollow noreferrer"">documentation</a>.</p>
<pre><code>use Illuminate\Http\Request;
// ...more code here
$request = Request::create('/users/all', 'GET');
</code></pre>
<p>I just wanna ask how to pass a parameter using the above code line? And someone can give me a documentation about that.</p>
",https://stackoverflow.com/questions/66301702/how-to-pass-parameter-using-laravels-request,"['php', 'laravel', 'laravel-request']",1517,True,0,2
How to make Unit Test for Koin Component class in Kotlin?,"<p>I am new with Unit testing. I am doing Unit test with kotlin in a project. I should test <code>WelcomeFragment</code>. I just tried to use Mockito library and tried to mock this class. That failed with error</p>
<blockquote>
<p>Mockito cannot mock this class:</p>
</blockquote>
<p>If I use PhoneHelper.isValid method without mocking then getting error</p>
<blockquote>
<p>Koin has not started.</p>
</blockquote>
<p>This class use <code>PhoneHelper class</code> How can I test successfully .isValid method of PhoneHelper in my test?</p>
<p>WelcomeFragment.kt</p>
<pre><code> private fun checkEditText() {
        drawableChanges(
            PhoneHelper.isValid(
                mBinding.inputLogin.lifEdittext.text.toString(),
                mViewModel.mFormState.countryCode
            )
        )
    }
</code></pre>
<p>PhoneHelper.kt</p>
<pre><code>import io.michaelrocks.libphonenumber.android.PhoneNumberUtil
import io.michaelrocks.libphonenumber.android.Phonenumber
import org.koin.core.KoinComponent
import org.koin.core.inject


object PhoneHelper : KoinComponent {
    private val mPhoneNumberUtil: PhoneNumberUtil by inject()

    fun isValid(gsmNo: String?, countryCode: String?): Boolean {
        val phoneModel = Phonenumber.PhoneNumber()
        phoneModel.nationalNumber = gsmNo?.toLongOrNull() ?: 0
        phoneModel.countryCode = if (countryCode?.contains(&quot;+&quot;)==true) countryCode?.removePrefix(&quot;+&quot;).toString()
            .toIntOrNull() ?: 90
        else 90
        return mPhoneNumberUtil.isValidNumber(phoneModel)
    }
}
</code></pre>
<p>WelcomeFragmentTest.kt</p>
<pre><code>class WelcomeFragmentTest{

    val phonehelper = Mockito.mock(PhoneHelper::class.java)

    @Test
    fun `checkEditText Test`(){
        val phoneNo= &quot;558887888&quot;
        val bool = phonehelper.isValid(phoneNo,null)
        assertEquals(
            &quot;false&quot;,
            bool
        )
    }
</code></pre>
",https://stackoverflow.com/questions/69672988/how-to-make-unit-test-for-koin-component-class-in-kotlin,"['android', 'unit-testing', 'kotlin', 'mockito', 'koin']",579,True,0,1
How can I test/mock external code or external dependencies using moq?,"<p>I'm using Moq for mocking of my code in unit testing. It's ok to mock the code without external dependencies. Below code is my last dependencies which I mocked</p>
<pre class=""lang-cs prettyprint-override""><code>/// &lt;summary&gt;
/// Executes the request.
/// &lt;/summary&gt;
/// &lt;param name=&quot;booking&quot;&gt;The booking.&lt;/param&gt;
protected override void ExecuteRequest(BookingModel.Booking booking)
{
    var request = this.CreateRequest(this.TravelContext, booking);
    using (var proxy = this.TravelContext.CreateProxy&lt;IMonitorBookingServiceProxy&gt;())
    {
        var response = proxy.AutoCancelBooking(request);
        this.AddResponseInfos(response.ResponseInfos);
    }
}
</code></pre>
<p>I mock the above code like this</p>
<pre class=""lang-cs prettyprint-override""><code>// mock the IMonitorBookingServiceProxy
Mock&lt;IMonitorBookingServiceProxy&gt; mockedMonitorBookingContext = new Mock&lt;IMonitorBookingServiceProxy&gt;() { DefaultValue = DefaultValue.Mock };
mockedMonitorBookingContext.Setup(x =&gt; x.AutoCancelBooking(It.IsAny&lt;AutoCancelBookingRequest&gt;())).Returns(autoCancelBookingResponse).Verifiable();
ProxyFactory.Configure&lt;IMonitorBookingServiceProxy&gt;(mockedMonitorBookingContext.Object);
</code></pre>
<p>it's return the response to me correctly.
but my problem is that there's a lot of scenarios and classes to be test inside <code>proxy.AutoCancelBooking(request);</code> function.</p>
<p>How How i can test or mocked that that classes and dependencies .</p>
",https://stackoverflow.com/questions/65596532/how-can-i-test-mock-external-code-or-external-dependencies-using-moq,"['c#', 'asp.net-mvc', 'unit-testing', 'mocking', 'moq']",826,True,0,2
Unit testing function ehich return observable of observables,"<p>I've got a problem with unit testing function like this:</p>
<pre><code>loadData({prop1, prop2, prop3}: Props): Observable&lt;unknown&gt; {
    return this.dataService.clearData().pipe(
         concanMap(() =&gt; this.personalDataService.getData(prop1)),
         concanMap(() =&gt; this.extendedDataService.getData(prop2)),
         concanMap(() =&gt; this.weatherDataService.getData(prop3))
    );
}
</code></pre>
<p>I want to do this based on spyOn's. Something like this:</p>
<pre><code>it('should correctly load data', () =&gt; {
    spyOn(dataService, 'clearData');
    spyOn(personalDataService, 'getData');
    spyOn(extendedDataService, 'getData');
    spyOn(weatherDataService, 'getData');

    spectator.service.loadData({
          prop1: '',
          prop2: '',
          prop3: ''
    })

    expect(dataService.clearData).toHaveBeenCalled();
    expect(personalDataService.getData).toHaveBeenCalled();
    expect(extendedDataService.getData).toHaveBeenCalled();
    expect(weatherDataService.getData).toHaveBeenCalled();
});
</code></pre>
<p>I've got an error:</p>
<blockquote>
<p>TypeError: Cannot read properties of undefined (reading 'pipe')</p>
</blockquote>
<p>It's quite obvious because dataService.clearData is a mock, so I need to return some value from this method:</p>
<pre><code>spyOn(dataService, 'clearData').and.returnValue(of());
</code></pre>
<p>This solution is bad because the other services calls can't be triggerred.</p>
<p>Do you have any idea how to test this function?</p>
",https://stackoverflow.com/questions/70470757/unit-testing-function-ehich-return-observable-of-observables,"['angular', 'unit-testing', 'jestjs', 'angular-spectator']",98,False,-1,1
Why does a unit test with sinon createStubInstance is successful but hangs?,"<p>I'm unit testing a method in fileA.js that requires a new class instance from fileB.js with success.</p>
<p>The problem is that I get success, as expected but this specific test hangs and I don't get results from istanbul.
Yes, I have already added --exit flag. This only happens if I run this test... Why does it hang?</p>
<p>This is the method in fileA.js:</p>
<pre><code>global.mapperObj = {};
const opts = config.opts
(...)

async function startServices() {
    const data = await getData();

    Object.keys(data).forEach(function(key) {
        mapperObj[key] = new ClassInFileB(key, data[key], opts);
        mapperArray.push(key);
    });
}
</code></pre>
<p>The class in fileB.js:</p>
<pre><code>const npmPool = require('npmPackage');

class ClassInFileB{
    
    constructor(ip, port, opts) {
        this.classPool = npmPool.createPool(ip, port, opts);
    }
    
    (...)
    // other class methods

}
</code></pre>
<p>And the test for that method:</p>
<pre><code>const rewire = require('rewire');
const fileA = rewire(`path/to/fileA`);
const ClassInFileB = require(`path/to/fileB`);

describe('Testing startServices() function', function () {
    it('It should not throw errors', async function () {
        let result;
        let error = false;
        global.mapperArray = [];
        
        try {
            function getDataMock() {
                return { '0.0.0.1': 'thisIsSomething'};
            }
            fileA.__set__('getData', getDataMock);

            // Create a stub instance to ClassInFileB class avoiding the constructor
            sinon.createStubInstance(ClassInFileB);

            result = await fileA.startServices();
        } catch (err) {
            error = err;
        }
        expect(error).to.be.false;
    });
</code></pre>
",https://stackoverflow.com/questions/65615212/why-does-a-unit-test-with-sinon-createstubinstance-is-successful-but-hangs,"['javascript', 'unit-testing', 'mocha.js', 'chai', 'sinon']",420,False,0,0
Flutter secure storage unit test,"<p>Hey as a part of project I would like to test my classes like the one below but I have a little problem. Impossible for me to test, I always encounter the same errors &quot;type 'Null' is not a subtype of type 'Future&lt;OAuthToken?&gt;'&quot; or &quot;Null check operator used on a null value&quot;. For example  :</p>
<pre><code>class Authentication {
  final FlutterSecureStorage _secureStorage = const FlutterSecureStorage();

  static const String BEARER_TOKEN = 'BEARER_TOKEN';

 Future&lt;OAuthToken&gt; setToken(OAuthTokenResponse token) async {
  assert(token.accessToken != null, 'A non null token is required');
  final String jsonToken = json.encode(token.toJson());
  await _secureStorage.write(key: BEARER_TOKEN, value: jsonToken);
  return token;
 }

 Future&lt; OAuthToken?&gt; getToken() async {
  final String? jsonToken = await _secureStorage.read(key: BEARER_TOKEN);
  if (jsonToken == null) {
   return null;
  }
  return OAuthToken(json.decode(jsonToken));
 }

 Future&lt;void&gt; deleteToken() async {
  await _secureStorage.delete(key: BEARER_TOKEN);
 }
}
</code></pre>
<p>My Unit testing :</p>
<pre><code>void main() {
 final Authentication dataSource = Authentication();
 final MockFlutterSecureStorage mockSecureStorage = MockFlutterSecureStorage();

 final token = OAuthToken.fromJson(json.decode(fixture('oauth_token_response.json')));

group('getToken', () {
 test('should return OAuthToken from FlutterSecureStorage when there is one the saved', () async {
   // arrange
   when(() =&gt; mockSecureStorage.read(key: BEARER_TOKEN)).thenAnswer((_) async =&gt; fixture('oauth_token_response.json'));

   // act
   final result = await dataSource.getToken();

   //assert
   verify(() =&gt; mockSecureStorage.read(key: BEARER_TOKEN));
   expect(result, equals(token));
 });

 test('should return null when is not saved token', () async {
   // arrange
   when(() =&gt; mockSecureStorage.read(key: BEARER_TOKEN)).thenAnswer((_) async =&gt; null);

   // act
   final result = await dataSource.getToken();

   //assert
   expect(result, equals(null));
 });
});

group('saveToken', () {
 test('should call FlutterSecureStorage to save token', () async {
   // arrange
   when(() =&gt; mockSecureStorage.write(key: BEARER_TOKEN, value: json.encode(token))).thenAnswer((invocation) =&gt; Future&lt;void&gt;.value());

   //act
   await dataSource.setToken(token);

   // assert
   final expectedJsonString = json.encode(token.toJson());
   verify(() =&gt; mockSecureStorage.write(key: BEARER_TOKEN, value: expectedJsonString));
 });
});
}
</code></pre>
<p>I tried Cocktail and Mockito and I have the same error... A problem with mock maybe ?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/70098232/flutter-secure-storage-unit-test,"['flutter', 'unit-testing', 'mockito', 'flutter-test', 'flutter-mockito']",615,False,0,1
Getting unexpected error while executing queries for unit testing with sqlmock,"<p>I have the following function that takes a slice of type <code>SchoolDbEntry</code> and bulk inserts it into a DB.</p>
<pre><code>type SchoolRegistry struct {
    Conn         *sqlx.DB
}

insertStudentEntry = `insert into StudentEntries (registerId, studentId, fee, admissionDate) values (:registerId, :studentId, :fee, :admissionDate)`

func (s *SchoolRegistry) AddStudentEntries(ctx context.Context, entry []StudentDbEntry) error {
    requestHeaders := helper.FetchHeaders(ctx)

    query, args, err := sqlx.Named(insertStudentEntry, entry)
    if err != nil {
        return exception.DBInternalError
    }

    _, err = s.Conn.Exec(query, args...)
    if err != nil {
        return cutomModels.NewError(err.Error()
    }

    return nil
}
</code></pre>
<p>I am trying to test this using sqlmock using the following functions</p>
<pre><code>var repo *SchoolRegistry


func TestAddStudentEntriesSuccess(t *testing.T) {

     db, mock, err := sqlmock.New()
     if err != nil {
            t.Fatalf(&quot;an error '%s' was not expected when opening a stub database connection&quot;, err)
     }

     sqlxDb := sqlx.NewDb(db, &quot;sqlmock&quot;)

     defer sqlxDb.Close()

     repo = &amp;SchoolRegistry{sqlxDb}
     if err := logger.Init(logLevel, logTimeFormat); err != nil {
         fmt.Printf(&quot;failed to initialize logger: %v&quot;, err)
     }

    query := `insert into StudentEntries (registerId, studentId, fee, admissionDate) values (:registerId, :studentId, :fee, :admissionDate)`

    args := []models.StudentDbEntry{
        {
            RegisterID:     1,
            StudentID:      1,
            Fee:            &quot;100&quot;,
            AdmissionDate:  &quot;10-20-2015&quot;,
        },
    }

    prep := mock.ExpectPrepare(query)
    prep.ExpectExec().WithArgs(1,1,&quot;100&quot;,&quot;10-20-2015&quot;).WillReturnResult(sqlmock.NewResult(0, 0))

    err := repo.AddStudentEntries(helper.FetchTestContext(), args)
    assert.NoError(t, err)

}
</code></pre>
<p>However, the tests are failing. I am getting</p>
<pre><code>call to ExecQuery 'insert into StudentEntries (registerId, studentId, fee, admissionDate) values (?, ?, ?, ?)' with args [{Name: Ordinal:1 Value:1} {Name: Ordinal:2 Value:1} {Name: Ordinal:3 Value:&quot;100&quot;} {Name: Ordinal:4 Value:&quot;10-20-2015&quot;}], was not expected, next expectation is: ExpectedPrepare =&gt; expecting Prepare statement which:
                              - matches sql: 'insert into StudentEntries (registerId, studentId, fee, admissionDate) values (:registerId, :studentId, :fee, :admissionDate)' 
</code></pre>
<p>error when no errors are expected ( that is, after this line : <code>_, err = s.Conn.Exec(query, args...)</code> ). The function works fine when I tested it as a part of the actual code. The issue is just with the unit testing.</p>
",https://stackoverflow.com/questions/69456040/getting-unexpected-error-while-executing-queries-for-unit-testing-with-sqlmock,"['unit-testing', 'go', 'sqlx', 'go-sqlmock']",348,False,0,0
Unit Test api CRUD operation with Moq,"<p>I am completely new to unit testing and I tried to write unit testing for crud operation. I could write unit tests for <strong>get by id</strong> and <strong>get all</strong>. But the problem arises when writing the unit test for <strong>create</strong> and <strong>update</strong>.</p>
<p><strong>This is my controller code for the create method</strong></p>
<pre><code>public async Task&lt;IActionResult&gt; Create([FromBody] Message message)
    {
        var duplicatemessage = await _messageService.DuplicateMessage(message.Text);
        if (duplicatemessage == null)
        {
            _messageService.Create(message);
            return CreatedAtRoute(&quot;Api&quot;, new { id = message.Id.ToString() }, message);
        }
        else
        {
            return BadRequest(new { message = &quot;Text Already Exist&quot; });
        }
    }
</code></pre>
<p><strong>This is the unit test I wrote for the create method</strong></p>
<pre><code>[TestCase(&quot;Hello&quot;)]
    public async Task Create_StateUnderTest_ExpectedBehavior(Message message)
    {
        // Arrange
        // mockMessageService.Setup(t =&gt; t.GetId(id)).ReturnsAsync(new Message());
        mockMessageService.Setup(t =&gt; t.DuplicateMessage(message.Text)).ReturnsAsync(new Message());
        mockMessageService.Setup(t =&gt; t.Create(message)).Returns(new Message());
        var apiController = this.CreateApiController();
        //var message1 = new Message() { Text = &quot;Hello&quot; };

        // Act
        var result = await apiController.Create(message);

        // Assert
        Assert.IsInstanceOf&lt;CreatedAtRouteResult&gt;(result);
        this.mockRepository.VerifyAll();
    }
</code></pre>
<p><strong>When I run the test I am getting this error</strong></p>
<p>Message:
System.ArgumentException : Object of type 'System.String' cannot be converted to type 'HelloApi.Models.Message'.</p>
<p>Stack Trace:
RuntimeType.TryChangeType(Object value, Binder binder, CultureInfo culture, Boolean needsSpecialCast)
RuntimeType.CheckValue(Object value, Binder binder, CultureInfo culture, BindingFlags invokeAttr)
MethodBase.CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig)
RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
MethodBase.Invoke(Object obj, Object[] parameters)
Reflect.InvokeMethod(MethodInfo method, Object fixture, Object[] args)</p>
<p>I tried to debug but debug point did not hit.
and I tried,
<a href=""https://stackoverflow.com/questions/51926925/test-api-crud-operation-with-moq"">Test api CRUD operation with Moq</a>
and
<a href=""https://stackoverflow.com/questions/16060745/how-can-i-convert-an-class-object-into-string"">How can I convert an Class Object into String?</a>
this but I don't think it is related to my problem. can anyone help me, please?</p>
",https://stackoverflow.com/questions/66303292/unit-test-api-crud-operation-with-moq,"['c#', 'asp.net', 'unit-testing', 'asp.net-core', 'asp.net-web-api']",765,True,0,3
Cannot create dynamic type in .NET Core,"<p>I want to add <code>Child</code> as a dynamic type to a dynamic assembly:</p>
<pre class=""lang-cs prettyprint-override""><code>public abstract class Parent { }       // I want to define this statically

public class Child : Parent {          // I want to define this dynamically
  private Child() : base() { }
}
</code></pre>
<p>I followed <a href=""https://stackoverflow.com/a/41785168/9971404"">this</a> example.</p>
<p>I added the nuget package <a href=""https://www.nuget.org/packages/System.Reflection.Emit"" rel=""nofollow noreferrer"">System.Reflection.Emit</a> (v 4.7.0).</p>
<p>Then wrote this:</p>
<pre class=""lang-cs prettyprint-override""><code>using System;
using System.Reflection;
using System.Reflection.Emit;

public abstract class Base { }

public class Program {

  public static void Main() {

    // define dynamic assembly
    var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(Guid.NewGuid().ToString()), AssemblyBuilderAccess.Run);
    var moduleBuilder = assemblyBuilder.DefineDynamicModule(Guid.NewGuid().ToString());

    // define dynamic type
    var typeName = &quot;Child&quot;;
    var typeBuilder = moduleBuilder.DefineType(
      typeName,
      TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoLayout,
      typeof(Base));
    typeBuilder.DefineDefaultConstructor(MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName);
    //typeBuilder.CreateType();   // this was missing - see accepted answer below

    // test it
    try {
      typeBuilder.Assembly.GetTypes();                 // &lt;--- throws
    }
    catch (ReflectionTypeLoadException exception) {
      Console.WriteLine(exception.Message);
    }
  }

}
</code></pre>
<p>It throws this:</p>
<blockquote>
<p>Unable to load one or more of the requested types.
Could not load type 'Child' from assembly '28266a72-fc60-44ac-8e3c-3ba7461c6be4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.</p>
</blockquote>
<p>This failed for me in a unit testing project. It also failed on <a href=""https://dotnetfiddle.net/IvuEKK"" rel=""nofollow noreferrer"">dotnetfiddle</a>.</p>
<p>What have I done wrong?</p>
",https://stackoverflow.com/questions/69602204/cannot-create-dynamic-type-in-net-core,"['c#', '.net-core', 'reflection', '.net-5', 'reflection.emit']",491,True,2,1
Angular and Jasmine Test firebase auth with google provider cannot read property,"<p>I'm starting with unit testing and it's hard to test a method that login using firebase auth. I've tried it in many ways and tested it in several means as you can see in the code comments and in most cases it always returns:</p>
<p><code>TypeError: Cannot read property 'GoogleAuthProvider' of undefined</code></p>
<p>I used the <strong>ng-mocks</strong> library to mock <strong>AngularFireAuth</strong>.</p>
<p>the project can be seen in this branch of the project on <strong><a href=""https://github.com/miguelsmuller/angular-11-crud/tree/feature/unit-teste"" rel=""nofollow noreferrer"">github branch</a></strong></p>
<p>this is the <strong>method</strong> i want to test:</p>
<pre><code>login(): Observable&lt;IUser&gt; {
    const provider = new firebase.auth.GoogleAuthProvider();
    const responseAuth = from(this.fireAuthService.signInWithPopup(provider)).pipe(
      map((fireUser) =&gt; {
        const objUser: IUser = {
          uid: fireUser.user?.uid!,
          name: fireUser.user?.displayName!,
          email: fireUser.user?.email!,
          emailVerified: fireUser.user?.emailVerified!,
          photoURL: fireUser.user?.photoURL!,
          provider: fireUser.user?.providerId!,
        };
        return objUser;
      }),
      catchError(() =&gt; {
        throw new Error('error in the logout process');
      })
    );

    return responseAuth;
  }
</code></pre>
<p>this is the <strong>test</strong>.</p>
<pre><code>it('should executed login method with success', fakeAsync(() =&gt; {
    const googleSignInMethod = spyOn(fireAuthService, 'signInWithPopup');

    service.login().subscribe((data) =&gt; {
      expect(googleSignInMethod).toHaveBeenCalled();
    });

    // const googleSignInMethod = spyOn(fireAuthService, 'signInWithPopup').and.callThrough();
    // service.login().subscribe((data) =&gt; {});
    // expect(googleSignInMethod).toHaveBeenCalled();

    // service.login().subscribe((data) =&gt; {
    //   let spy = spyOn(fireAuthService, 'signInWithPopup');
    // expect(spy).toHaveBeenCalledWith(provider);
    //   expect(spyOn(fireAuthService, 'signInWithPopup')).toBeTruthy();
    // });
    // spy = spyOn(service, 'isAuthenticated').and.returnValue(false); (3)
    // expect(component.needsLogin()).toBeTruthy();
    // expect(service.isAuthenticated).toHaveBeenCalled(); (4)
  }));
</code></pre>
",https://stackoverflow.com/questions/68433229/angular-and-jasmine-test-firebase-auth-with-google-provider-cannot-read-property,"['angular', 'unit-testing', 'firebase-authentication', 'jasmine', 'ng-mocks']",634,True,2,1
How to unit test with redux selectors,"<p>I am currently unit testing this file but I have no idea on how to unit test the two constants I have in redux (grid and list).</p>
<p><strong>file</strong></p>
<pre><code>const Projects = () =&gt; {
  const dispatch = useDispatch();
  const view = useSelector(selectView);

  useMount(() =&gt; {
    dispatch(projectsActions.viewRestore());
    dispatch(projectsActions.filterRestore());
  });

  return (
    &lt;Wrapper&gt;
      &lt;div className=&quot;projects-toolbar&quot; data-testid=&quot;projects-toolbar-container&quot;&gt;
        &lt;Toolbar /&gt;
      &lt;/div&gt;

      {view === VIEW_TYPES.grid &amp;&amp; &lt;ProjectsGridView /&gt;}
      {view === VIEW_TYPES.list &amp;&amp; &lt;ProjectsListView /&gt;}
    &lt;/Wrapper&gt;
  );
};
</code></pre>
<p><strong>test file</strong></p>
<pre><code>    test('renders properly', () =&gt; {
    const { getByTestId,  } = setup();

    expect(getByTestId('projects-toolbar-container')).toBeInTheDocument();
  });
</code></pre>
<p>As you guys see the only test I could do is adding a ID to the Toolbar components outer div to see if it is there but besides that I have no idea on how to check if the constants match to render the other 2 components</p>
",https://stackoverflow.com/questions/67744527/how-to-unit-test-with-redux-selectors,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",759,False,1,1
Is there a standard practice for storing flat data files that are used for testing in a Django project?,"<p>I'm unit testing the way that my Django application loads and processes various flat files and I'm having trouble deciding where to store the files that contain the data for these tests. Is there a standard practice or location for this?</p>
<p>Would it make more sense to store these files in one of the <code>STATICFILES_DIRS</code> or in a subdirectory of <code>MEDIA_ROOT</code>, or some other directory? If some other directory, how might that be configured in the settings module?</p>
<p>For example:</p>
<pre><code>from pathlib import Path 
from django.core.files.uploadedfile import SimpleUploadedFile
from django.test import TestCase

def simulate_uploaded_file(data_path: Path, filename: str)
    content_type = get_content_type(filename)
    filepath = data_path / filename
    content = open(filepath, 'rb').read()
    data_file = SimpleUploadedFile(data_file_path, content, content_type)

class TestFileHandler(TestCase):
    @classmethod
    def setUpTestData(cls):
        test_data_path: Path = settings.TEST_DATA_DIR # &lt;- IS THERE A STANDARD LOCATION FOR THIS?
        cls.valid_csv: SimpleUploadedFile = simulate_uploaded_data(test_data_path, 'filename.csv')
</code></pre>
",https://stackoverflow.com/questions/70193974/is-there-a-standard-practice-for-storing-flat-data-files-that-are-used-for-testi,"['python', 'django', 'unit-testing']",49,False,1,0
Can not access child nodes inside a DIV with Angular Unit Test,"<p>I have an Angular (<em>using Angular 1</em>0) component with a HTML snippet like below:</p>
<pre><code>&lt;div *ngIf=&quot;someCondition()&quot; id=&quot;myID&quot;&gt;
     &lt;p&gt;Line 1&lt;/p&gt;
     &lt;p&gt;Line 2&lt;/p&gt;
     &lt;p&gt;Line 3&lt;/p&gt;
     &lt;p&gt;Line 4&lt;/p&gt;
     &lt;p&gt;Line 5&lt;/p&gt;
     &lt;p&gt;Line 6&lt;/p&gt;
     &lt;p&gt;Line 7&lt;/p&gt;
&lt;/div&gt;
</code></pre>
<p>Now, while unit testing, I would like to figure out if <code>*ngIf</code> satisfies, the corresponding <code>&lt;div&gt;</code> will have 7 child elements.</p>
<p>In the spec file, I have the following :</p>
<pre><code>it('should check for 7 elements', async () =&gt; {    
    spyOn(component, 'someCondition()').and.returnValue(true);
    fixture.detectChanges();
    await fixture.whenRenderingDone();

    const elements = fixture.debugElement.queryAllNodes(By.css('#myID'));
    // const elements = fixture.debugElement.queryAll(By.css('#myID'));    

    console.log('check elements.... ', elements);
  })
</code></pre>
<p>With the above, I can not get access to the child <code>&lt;p&gt;</code> tags or the number of the children! Also, it would be good, if I could test a specific <code>&lt;p&gt;</code> tag with expected value.</p>
<p><strong>How can I achieve this?</strong></p>
",https://stackoverflow.com/questions/69373039/can-not-access-child-nodes-inside-a-div-with-angular-unit-test,"['angular', 'karma-jasmine', 'angular-components', 'angular10', 'angular-unit-test']",1831,True,1,2
How to mock multiple query.filter_by in Flaks-SqlAlchemy,"<h2>In brief</h2>
<p>When testing in Flask-SqlAlchemy how can I mock multiple differents query.filter_by().first ?</p>
<h2>More in detail</h2>
<p>I followed <a href=""https://stackoverflow.com/questions/42482021/how-to-mock-modelclass-query-filter-by-in-flask-sqlalchemy"">this link</a> to do some unit testing and it works very well when I have only one query.filter_by.</p>
<p>The problem is in one function I have:</p>
<pre><code>user = User.query.filter_by(username=user[&quot;username&quot;]).first()
organization = Organization.query.filter_by(organization_name=user.get(&quot;organization&quot;)).first()
</code></pre>
<p>If I follow the previous link when I do:</p>
<pre><code>@mock.patch('flask_sqlalchemy._QueryProperty.__get__')
def test(self, queryMOCK):
    queryMOCK \
        .return_value.filter_by \
        .return_value.first \
        .return_value = user
</code></pre>
<p>I mock all the query.filter_by() and not only one of the two.</p>
<p>They say to do:</p>
<pre><code>@patch('app.model.some_model.SomeModel')
def test_some_case(self, some_model_mock):
    filter_by_mock = some_model_mock.query.filter_by
</code></pre>
<p>but I didn't manage to do it.</p>
",https://stackoverflow.com/questions/67818023/how-to-mock-multiple-query-filter-by-in-flaks-sqlalchemy,"['python', 'unit-testing', 'flask', 'sqlalchemy']",777,False,1,2
django.db.utils.IntegrityError: NOT NULL constraint failed: rango_category.super_cat_id,"<pre><code>/*tests.py*/
def create_user(username, password):
user = get_user_model().objects.create_user(username=username, password=password)
return user

#helper function to populat database 
def create_category(name, super, user):
category = Category.objects.get_or_create(name=name)[0]
category.super = super
category.user = user
category.save()
return category

# The following test is for the save and deleting of
# a page from the favorites list
class TestFavoritesFeature(TestCase):
def setUp(self):
    self.user = create_user(&quot;testUser&quot;, &quot;testPassword&quot;)
    self.cat = create_category('python', self.super, self.user)
</code></pre>
<p>Both the object.create and object.get_or_create give an error for NOT NULL field. Above is the code , 2 models and both throw an error on only the id field that we do not even populate. It is the function's job to assign a unique id to it. The above is code from tests.py file. I am trying to populate DB for unit testing . In the actual code, these objects.get_or_create or objects.create do not give errors but are rather successful</p>
",https://stackoverflow.com/questions/68672156/django-db-utils-integrityerror-not-null-constraint-failed-rango-category-super,"['django', 'unit-testing', 'django-models']",433,True,1,1
Assert.Inconclusive analogue for MS C++ unit testing framework or how to skip test on the run?,"<p>I want to be able to skip a current test from its body. Of course, I could simply do this:</p>
<pre><code>if (condition) return;
</code></pre>
<p>But this will show the test as &quot;passed&quot;. I want to keep the user informed that the test is neither passed nor failed if <code>(condition)</code> happens.</p>
<p>In C# we have <code>Assert.Inconclusive()</code>, so some C++ analogue of this function would be the best. Is there anything like this in <em>Microsoft Cpp Unit Testing Framework</em> or can it be implemented?</p>
",https://stackoverflow.com/questions/68815485/assert-inconclusive-analogue-for-ms-c-unit-testing-framework-or-how-to-skip-te,"['c++', 'unit-testing', 'microsoft-cpp-unit-test']",95,False,1,0
How to use tSQLt to test if a integer value is within a specific range?,"<p>I'm using the <a href=""https://tsqlt.org/"" rel=""nofollow noreferrer"">tSQLt unit testing tool</a>. I want to test if an actual row count is within .1% of an expected value.  Seems like I could use a <code>EXEC tSQLt.AssertIntValueInRange</code> procedure, but I couldn't find anything like this. I would settle for writing the logic myself and conditionally calling <code>EXEC tSQLt.FailAssertion</code>, but apparently this doesn't exist either.</p>
<p>Would somebody please advise on how to use tSQLt for checking if an integer value is within x percent of an expected value?</p>
",https://stackoverflow.com/questions/69668599/how-to-use-tsqlt-to-test-if-a-integer-value-is-within-a-specific-range,"['sql-server', 'tsqlt']",147,True,1,2
Unit testing client-go function that auths and returns a k8s clientset,"<p>I am writing the simplest fxn possible using <code>client-go</code> that justs performs in-cluster authentication and returns a pointer to the <code>kubernetes.Clientset</code> object</p>
<pre class=""lang-golang prettyprint-override""><code>// getInClusterAuth performs in cluster authentication and returns the clientset
func getInClusterAuth() (*kubernetes.Clientset, error) {
    // creates the in-cluster config
    config, err := rest.InClusterConfig()
    if err != nil {
        return nil, err
    }
    // create the clientset
    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        return nil, err
    }

    return clientset, nil
}
</code></pre>
<p>Since this is sth that not only does it run against an external system (a <code>k8s</code> api server) but it is also supposed to be running from within a <code>Pod</code> once deployed, what is the appropriate way of unit-testing it?</p>
<p>Could it be that it is an acceptable practice to cover the case in e2e or integration tests?</p>
",https://stackoverflow.com/questions/68705402/unit-testing-client-go-function-that-auths-and-returns-a-k8s-clientset,"['unit-testing', 'go', 'testing', 'kubernetes', 'client-go']",1108,True,1,1
How to test ViewModel with LiveData and Room Android using Kotlin?,"<p>I am following this <a href=""https://medium.com/@iamanbansal/testing-viewmodel-livedata-4a62f34e7c26"" rel=""nofollow noreferrer"">article</a> and finding it hard to get my head around it.
I am diving deeper into testing and need your help to understand it more.</p>
<p>How to test my viewmodel?</p>
<pre><code>class SongViewModel (application: Application) : AndroidViewModel(application) {

    private val repository: SongRepository
    val allSongs: LiveData&lt;List&lt;LocalSong&gt;&gt;

    init {
        val songsDao = SongRoomDatabase.getDatabase(application, viewModelScope).localSongDao()
        repository = SongRepository(songsDao)
        allSongs = repository.allSongs
    }

    /**
     * Launching a new coroutine to insert the data in a non-blocking way
     */
    fun insert(song: LocalSong) = viewModelScope.launch(Dispatchers.IO) {
        repository.insert(song)
    }

    fun delete(id: Int) = viewModelScope.launch(Dispatchers.IO) {
        repository.delete(id)
    }

    fun getCount(): Int {
        return repository.getCount()
    }
}
</code></pre>
<p>What I have tried?</p>
<pre><code>@RunWith(MockitoJUnitRunner::class)
class SongViewModelTest : TestCase() {
    private lateinit var viewModel: SongViewModel
    @Mock
    private lateinit var songRepo: SongRepository
    @Mock
    private lateinit var observer: io.reactivex.Observer&lt;SharedResourceHolder.Resource&lt;List&lt;LocalSong&gt;&gt;&gt;
    @Captor
    private lateinit var argumentCaptor: ArgumentCaptor&lt;SharedResourceHolder.Resource&lt;List&lt;LocalSong&gt;&gt;&gt;

    @get:Rule
    public val instantExecutorRule = InstantTaskExecutorRule()

    @Before
    fun setupSongViewModel() {
        RxJavaPlugins.setIoSchedulerHandler{io.reactivex.schedulers.Schedulers.trampoline()}
    }

    @Test
    fun loadSongItemTriggersLoadingState(){

    }
}
</code></pre>
<p>I have read up on unit testing and mockito but still can't get my head around it and get a lot of errors. Any links would be nice too so I can fully understand testing on Android. Happy coding everyone!</p>
",https://stackoverflow.com/questions/67084354/how-to-test-viewmodel-with-livedata-and-room-android-using-kotlin,"['android', 'unit-testing', 'mvvm', 'mockito', 'android-testing']",192,False,1,0
Vue 3 Unit Testing - Cannot find module,"<p>I'm pretty new to Unit Testing but have just started writing some in my Vue 3 application.</p>
<p>In the component I am testing I import some interface types from a models sub-folder like this:</p>
<pre><code>import { ITEM } from &quot;../models/product.models&quot;;
</code></pre>
<p>This all works fine when in the component but in my Unit Test I get this error:</p>
<pre><code>Cannot find module '../models/product.models' from 'Product.vue'


 &gt; 88 | import { ITEM } from &quot;../models/product.models&quot;;
         | ^

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
</code></pre>
<p>What do I need to do to get the test to evaluate that import correctly?</p>
<p>this is the config I have for jest:</p>
<pre><code>&quot;jest&quot;: {
    &quot;globals&quot;: {
      &quot;vue-jest&quot;: {
        &quot;hideStyleWarn&quot;: true
      }
    },
    &quot;preset&quot;: &quot;@vue/cli-plugin-unit-jest&quot;,
    &quot;testMatch&quot;: [
      &quot;**/src/**/*.spec.[jt]s?(x)&quot;
    ],
    &quot;transform&quot;: {
      &quot;^.+\\.vue$&quot;: &quot;vue-jest&quot;
    },
    &quot;transformIgnorePatterns&quot;: [
      &quot;&lt;rootDir&gt;/node_modules/(?!primevue/.*)&quot;
    ]
  }
</code></pre>
<p>tsconfig.js</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;esnext&quot;,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;strict&quot;: true,
    &quot;jsx&quot;: &quot;preserve&quot;,
    &quot;importHelpers&quot;: true,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;experimentalDecorators&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;noImplicitAny&quot;: false,
    &quot;esModuleInterop&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;sourceMap&quot;: true,
    &quot;baseUrl&quot;: &quot;.&quot;,
    &quot;types&quot;: [
      &quot;webpack-env&quot;,
      &quot;jest&quot;
    ],
    &quot;paths&quot;: {
      &quot;@/*&quot;: [
        &quot;src/*&quot;
      ]
    },
    &quot;lib&quot;: [
      &quot;esnext&quot;,
      &quot;dom&quot;,
      &quot;dom.iterable&quot;,
      &quot;scripthost&quot;
    ]
  },
  &quot;include&quot;: [
    &quot;src/**/*.ts&quot;,
    &quot;src/**/*.tsx&quot;,
    &quot;src/**/*.vue&quot;,
    &quot;tests/**/*.ts&quot;,
    &quot;tests/**/*.tsx&quot;],
  &quot;exclude&quot;: [
    &quot;node_modules&quot;
  ]
}
</code></pre>
",https://stackoverflow.com/questions/69925671/vue-3-unit-testing-cannot-find-module,"['vue.js', 'unit-testing']",1450,False,1,1
Mocikto how to correctly verify mock calls,"<p>I am new to kotlin unit testing and trying to use Mockito for the same</p>
<pre><code>private val mockClient: MongoClient = Mockito.mock(MongoClient::class.java)
private val mockDatabase: MongoDatabase = Mockito.mock(MongoDatabase::class.java)
private val mockCollection: MongoCollection&lt;Document&gt; =
        Mockito.mock(MongoCollection::class.java, RETURNS_DEEP_STUBS) as MongoCollection&lt;Document&gt;

private val dao = MyDao(mockClient)
</code></pre>
<p>Testing the get method of dao that fetches data from mongo works fine using <strong>when</strong> and <strong>thenReturn</strong></p>
<pre><code>val query = BasicDBObject(&quot;_id&quot;, someId)
Mockito.`when`(mockClient.getDatabase(DB_NAME)).thenReturn(mockDatabase)
Mockito.`when`(mockDatabase.getCollection(COLLECTION_NAME))
    .thenReturn(mockCollection)
Mockito.`when`(mockCollection.find(query)).thenReturn(iterable)
Mockito.`when`(iterable.iterator()).thenReturn(cursor)
Mockito.`when`(cursor.hasNext()).thenReturn(true).thenReturn(false)
Mockito.`when`(cursor.next()).thenReturn(validDocument)
assertEquals(expectedData, dao.get(someId))
</code></pre>
<p>The problem arises when verifying the mock for calls during insertion</p>
<pre><code>Mockito.verify(mockCollection, Mockito.times(1)).insertOne(dataDocument)
dao.create(data)
</code></pre>
<p>The error is</p>
<pre><code>Wanted but not invoked:
mongoCollection.insertOne({//documents goes here})
</code></pre>
<p>I tried directly using the API and its inserting data in the correctly, the issue lies in the testing not sure if I am correctly using the verify?
Any helps suggestion appreciated.</p>
",https://stackoverflow.com/questions/65580291/mocikto-how-to-correctly-verify-mock-calls,"['java', 'unit-testing', 'kotlin', 'mocking', 'mockito']",193,True,1,1
.NET&#39;s &quot;InternalsVisibleTo&quot; equivalent in Haskell,"<p>In .NET I can decorate my assembly with the following attribute:</p>
<pre class=""lang-ml prettyprint-override""><code>[&lt;assembly: InternalsVisibleTo(&quot;MyProject.Test&quot;)&gt;]
</code></pre>
<p>Thanks to this, all the modules marked as &quot;internal&quot; are accessible from &quot;MyProject.Test&quot;. I can use it e.g. for unit testing the functionality I don't want to expose in my library.</p>
<p>I'm wondering if there's something similar in the Haskell's world. Let's say I have a library with the following .cabal file:</p>
<pre><code>library
  exposed-modules:  MyLibrary.API
  other-modules:    MyLibrary.Utils
  -- ...

test-suite mylib-test
  -- ...
  build-depends:  base,
                  hspec,
                  my-library
</code></pre>
<p>Is there a way to refer to &quot;MyLibrary.Utils&quot; from mylib-test test-suite?</p>
",https://stackoverflow.com/questions/65983989/nets-internalsvisibleto-equivalent-in-haskell,"['unit-testing', 'haskell', 'internalsvisibleto']",64,True,1,1
Unit test fail with not being able to find global module,"<p>From the root of my project I am running the standard python unit-testing command.</p>
<pre><code>python3 -m unittest
</code></pre>
<p>I end up with</p>
<pre><code>doc = yaml.safe_load(f)
NameError: name 'yaml' is not defined
</code></pre>
<p>Here's a blueprint of the test code:</p>
<pre><code>import unittest
import yaml
from validators.utils import get_settings_key
# from validators.validators import validate_assumed_role


class TestValidators(unittest.TestCase):
    
    def setUp(self):
        with open(&quot;boilerplate_aws.yaml&quot;) as f:
            self.doc = yaml.safe_load(f)
            self.infrastructure = self.doc[&quot;parameters&quot;][&quot;infrastructure&quot;]
            self.inventory_role = self.infrastructure[&quot;assumed_role_arn&quot;]
 
    def test_role_validator(self):
        settings_role = get_settings_key(&quot;assumed_role_arn&quot;)
        # self.assertTrue(validate_assumed_role(self.inventory_role, settings_role))
# 

if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>I  consider the yaml module as a global one coming by default in Python. Just wondering if I am missing something or it's some project messed up structure ? Just for safety check, I looked up the package and it's here locally. This is under Ubuntu. No venvs, or anything like that.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/65684756/unit-test-fail-with-not-being-able-to-find-global-module,"['python', 'python-3.x', 'unit-testing', 'module', 'yaml']",64,False,0,1
INotifyPropertyChanged PropertyChanged event is null when called during unit tests,"<p>I am trying to unit test my View Model in a WPF MVVM application. This application currently runs correctly when run</p>
<p>My ViewModel implements INotifyPropertyChanged and raises the correct PropertyChanged events
When unit testing, the PropertyChanged event is null and therefore throws exceptions</p>
<p>I have gone down a rabbit hole about the Application.Current, but have confirmed it is set while running the unit tests</p>
<p>What do I need to set/mock to prevent this from happening?</p>
",https://stackoverflow.com/questions/66646435/inotifypropertychanged-propertychanged-event-is-null-when-called-during-unit-tes,"['c#', 'wpf', 'unit-testing', 'mvvm']",98,False,-2,1
How to set current route in Angular unit test,"<p>When unit testing a component that depends on being on a certain route, how do I set the current URL?</p>
<p><strong>component.html</strong></p>
<pre class=""lang-html prettyprint-override""><code>&lt;button class=&quot;menu-button&quot; *ngIf=&quot;router.url === '/home'&quot;&gt;
</code></pre>
<p><strong>component.spec.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>it('menu button should toggle side navs', () =&gt; {
  const buttonEl = toolbarElement.querySelector('.menu-button');

  (buttonEl as HTMLElement).click();
  expect(navigationServiceSpy.sideNavLeftToggle).toHaveBeenCalled();
});
</code></pre>
<p><code>buttonEl</code> is <strong>undefined</strong> because I cannot set the current route of the component.
I have tried the following without luck:</p>
<ul>
<li>navigating to the URL in the unit test using router.navigate(['/home']) on the 'real' router</li>
<li>spying on the router and navigating to the URL</li>
</ul>
<p>In both cases <code>router.url</code> remains undefined and I cannot get my conditional element to render :(</p>
",https://stackoverflow.com/questions/69391561/how-to-set-current-route-in-angular-unit-test,"['angular', 'jasmine', 'karma-jasmine', 'angular-router']",980,False,0,0
How can i mock a return type of a factory method of a 3rd party library?,"<p>I am working on a tool that loads assemblies using Mono.Cecil. I have the following Factory that returns an object named binary and depends on interface responsible for loading assemblies with <code>AssemblyDefinintion.ReadAssembly</code> method.</p>
<p>I am completely new to unit testing and I need to unit test the <code>GetBinary</code> method.</p>
<pre class=""lang-cs prettyprint-override""><code>internal sealed class DotNetBinaryFactory : IBinaryFactory
{
    private readonly IBinaryLoader binaryLoader;
    public DotNetBinaryFactory(IBinaryLoader binaryLoader)
    {
        this.binaryLoader = binaryLoader;
    }

    [NotNull] public Binary GetBinary([NotNull] FilePath path)
    {
        var assembly = binaryLoader.LoadBinary(path);
        return BinaryUtils.GetBinary(assembly);
    }
}
</code></pre>
<p>Here is the <code>IBinaryLoader</code> dependency implementation</p>
<pre class=""lang-cs prettyprint-override""><code>internal interface IBinaryLoader
{
    AssemblyDefinition LoadBinary(FilePath path);
}

internal sealed class DotnetBinaryLoader : IBinaryLoader
{
    public AssemblyDefinition LoadBinary([NotNull] FilePath path)
    {
        try
        {
            return AssemblyDefinition.ReadAssembly(path.Path);
        }                
        catch (Exception)
        {
            Console.WriteLine(&quot;Exception in loading Assembly From : &quot; + path.Path);
            throw;
        }
    }
}
</code></pre>
<p>So to unit test <code>GetBinary</code> method I need to mock <code>IBinaryLoader</code> and setup <code>LoadBinary</code> method to return a dummy <code>AssemblyDefinition</code> object, but I can't create one.</p>
<p>Here is what I tried</p>
<pre class=""lang-cs prettyprint-override""><code>[Test]
public void GetDotnetBinary_AssemblyDefinitionInput_ReturnCorrectDotnetFrameworkBianry()
{
    var path = FilePath.GetRandom();
    var mockedAssemblyDef = new Mock&lt;AssemblyDefinition&gt;();
    var binaryLoader = new Mock&lt;IBinaryLoader&gt;();
    binaryLoader.Setup(m =&gt; m.LoadBinary(path)).Returns(mockedAssemblyDef.Object);
}
</code></pre>
",https://stackoverflow.com/questions/67325603/how-can-i-mock-a-return-type-of-a-factory-method-of-a-3rd-party-library,"['.net', 'unit-testing', 'moq', 'assemblies', 'mono.cecil']",123,True,0,1
Mock different answers and exceptions after several calls with Mocktail,"<p>I was using <a href=""https://pub.dev/packages/mocktail"" rel=""nofollow noreferrer"">mocktail</a> for my unit testing and I could not find a way to <strong>throw</strong> an Exception on the <strong>first call</strong> but later, on the <strong>second call</strong>, <strong>answer</strong> with the right output.</p>
<p>I could find <a href=""https://stackoverflow.com/a/53897351/14559140"">this solution</a> for two different answers but this was not enough for testing exceptions thrown. So I needed to come up with a modified solution.</p>
<p>This is what I wanted to achieve. By the way, I was testing a connection retry with http get.</p>
<pre class=""lang-dart prettyprint-override""><code>import 'package:http/http.dart' as http;
import 'package:mocktail/mocktail.dart';

class MockClient extends Mock implements http.Client {}

final mockClient = MockClient();

//First time fails, second one retrieves a result. This doesn't work on Mocktail
when(() =&gt; mockClient.get(Uri.parse(url)))
  .thenThrow(SocketException()) // Call 1
  .thenAnswer((_) =&gt; Future.value(http.Response(&quot;page content&quot;, 200)) // Call 2
);
</code></pre>
",https://stackoverflow.com/questions/69687714/mock-different-answers-and-exceptions-after-several-calls-with-mocktail,"['flutter', 'unit-testing', 'dart', 'mockito']",1472,True,3,1
Unit Testing with Router.events Angular 9,"<p>I am new to Angular and to unit testing in general and now I can't find a way to test the code in this service below. This is responsable for the creation of a breadcrumb menu. In the Routing Module I have added for every route --&gt; data:{breadcrumb:'custom name'}.</p>
<p>Here is the service code:</p>
<pre><code>import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {IBreadcrumbs} from '../breadcrumb/ibreadcrumbs';
import {ActivatedRouteSnapshot, Data, NavigationEnd, Router} from '@angular/router';
import {filter} from 'rxjs/operators';


@Injectable({
  providedIn: 'root'
})
export class BreadcrumbService {

  /// Subject emitting the breadcrumb hierarchy
  private readonly breadcrumbsSub$ = new BehaviorSubject&lt;IBreadcrumbs[]&gt;([]);

  // Observable exposing the breadcrumb hierarchy
  readonly breadcrumbs$ = this.breadcrumbsSub$.asObservable();

  constructor(private router: Router) {
    this.router.events
      .pipe(
        // Filter the NavigationEnd events as the breadcrumb is updated only when the route reaches its end
        filter((event) =&gt; event instanceof NavigationEnd)
      )
      .subscribe((event) =&gt; {
        // Construct the breadcrumb hierarchy
        const root = this.router.routerState.snapshot.root;
        const breadcrumbs: IBreadcrumbs[] = [];


        this.addBreadcrumb(root, breadcrumbs);
        // Emit the new hierarchy
        this.breadcrumbsSub$.next(breadcrumbs);
      });
  }


  private addBreadcrumb(
    route: ActivatedRouteSnapshot | null,
    breadcrumbs: IBreadcrumbs[]
  ) {
    if (route) {
      // Add an element for the current route part
      if (route.data.breadcrumb) {
        const breadcrumb = {
          label: this.getLabel(route.data),
          url: route.url.toString()
        };
        breadcrumbs.push(breadcrumb);
      }
      // Add another element for the next route part
      this.addBreadcrumb(route.firstChild, breadcrumbs);
    }
  }

  private getLabel(data: Data) {
    // The breadcrumb can be defined as a static string or as a function to construct the breadcrumb element out of the route data
    return typeof data.breadcrumb === 'function'
      ? data.breadcrumb(data)
      : data.breadcrumb;
  }


}

</code></pre>
<p>And here is my spec.ts file</p>
<pre><code>import {TestBed} from '@angular/core/testing';

import {BreadcrumbService} from './breadcrumb.service';
import {RouterTestingModule} from '@angular/router/testing';
import {Router, RouterEvent} from '@angular/router';
import {ReplaySubject} from 'rxjs';


fdescribe('BreadcrumbService', () =&gt; {
  let service: BreadcrumbService;
  let routerEventRelaySubject: ReplaySubject&lt;RouterEvent&gt;;
  let routerMock;
  let router: Router;


  beforeEach(() =&gt; {
    routerEventRelaySubject = new ReplaySubject&lt;RouterEvent&gt;(1);
    routerMock = {
      events: routerEventRelaySubject.asObservable()
    };
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      providers: [{provide: Router, useValue: routerMock}]
    });
    service = TestBed.inject(BreadcrumbService);
  });

  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });

});
</code></pre>
<p>I need a coverage of 80% minimum, please help me achieve this.
Thank you in advance.</p>
",https://stackoverflow.com/questions/67670433/unit-testing-with-router-events-angular-9,"['angular', 'typescript', 'unit-testing']",267,False,0,2
Custom #define macro for unit testing,"<p>I have a function that is returning the condition of a macro, and for unit testing I want to be able to determine what this macros value is.</p>
<p>Currently I have,</p>
<pre class=""lang-c prettyprint-override""><code>#define READ_PORT ReadingPortStatus(SOME_OTHER_CONDITION)

#ifdef UNIT_TEST
bool READ_PORT_flag_UT;
#endif

void ReturnPortCondition()
{
#ifdef UNIT_TEST
#undef READ_PORT
    if (READ_PORT_flag_UT)
    {
        #define READ_PORT 1
    }
    else
    {
        #define READ_PORT 0
    }
#endif

    if (READ_PORT)
    {
        return(GOOD_READ);
    }
    else
    {
        return(BAD_READ);
    }
}
</code></pre>
<p>And in my unit test file I would use it as follows,</p>
<pre class=""lang-c prettyprint-override""><code>extern READ_PORT_flag_UT;

READ_PORT_flag_UT = true // Because I want ReturnPortCondition() to return true
bool result = ReturnPortCondition();
</code></pre>
<p>However, it is not working as I expect, it is only returning the last define of the port, which in this case is 0. the if else statements are not working in this context.</p>
",https://stackoverflow.com/questions/67940936/custom-define-macro-for-unit-testing,"['c', 'unit-testing']",688,True,0,1
How to test rest endpoint which accepts java object which contain multipart formadata,"<p>I'm stuck with unit testing of rest controller which has post method
which is accepting a RequestBody of java object which contains the multipart file.</p>
<p>various options I search for shows how to send a single file along with request or making them as part.</p>
<p>is there a way to test the whole object as single entity.</p>
<p><strong>Model class</strong></p>
<pre><code>@Data
public class Person{
  private String name;
  private String age;
  private List&lt;MultipartFile&gt; images;
}
</code></pre>
<p>and the rest controller to handle the request is</p>
<p><strong>Rest Controller</strong></p>
<pre><code>@RestController
@RequestMapping(&quot;/v1)
public class PersonRestController{

  @Autowired
  private IPersonService personService;

  @PostMapping(&quot;/save&quot;)
  public ResponseEntity&lt;String&gt; savePerson(@ModelAttribute Person person){
    String name = personService.savePerson(person);
    return new ResponseEntity&lt;String&gt;(name,HttpStatus.CREATED);
  }

}
</code></pre>
<p>will be really helpful if anyone could help.</p>
",https://stackoverflow.com/questions/69715357/how-to-test-rest-endpoint-which-accepts-java-object-which-contain-multipart-form,"['java', 'spring-boot', 'unit-testing', 'spring-boot-test']",87,False,0,0
Spring WebFlux: Unit testing of Mono,"<p>I have the following service</p>
<pre class=""lang-java prettyprint-override""><code>@Service
public class TestService {
    @Autowired
    TestService1 testService1;
    
    @Autowired
    TestService2 testService2;
    
    @Autowired
    TestService3 testService3;
    
    @Autowired
    TestService4 testService4;

    public Mono&lt;DataResponse&gt; getData() {
        Mono&lt;String&gt; ts1 = testService1.getMono();
        Mono&lt;String&gt; ts2 = testService2.getMono();
        Mono&lt;String&gt; ts3 = testService3.getMono();
        Mono&lt;String&gt; ts4 = testService4.getMono();
        
        return Mono.zip(ts1, ts2, ts3, ts4)
        .flatmap(resp -&gt; {
             // line XX
             return(Mono.just(new DataResponse(ts1, ts2, ts3, ts4)));
        });
    }
}
</code></pre>

<p>I'm trying to perform unit testing using Mockito and JUnit.</p>
<pre class=""lang-java prettyprint-override""><code>@SpringBootTest()
public class TestService {
    @InjectMocks
    TestService testService;

    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    TestService1 testService1;
    
    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    TestService2 testService2;
    
    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    TestService3 testService3;
    
    @Mock(answer = Answers.RETURNS_DEEP_STUBS)
    TestService4 testService4;
    
    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public Mono&lt;DataResponse&gt; getData() {
        when(testService1.getMono()).thenReturn(Mono.just(new String()));
        when(testService2.getMono()).thenReturn(Mono.just(new String()));
        when(testService3.getMono()).thenReturn(Mono.just(new String()));
        when(testService4.getMono()).thenReturn(Mono.just(new String()));
                
        Mono&lt;DataResponse&gt; res = testService.getData();
        
        Predicate&lt;DataResponse&gt; p = response -&gt; response != null;
        StepVerifier.create(res.log(), 1).expectNextMatches(p).verifyComplete();
    }
}
</code></pre>

<p>StepVerifier never executes expectNextMatches if I return Mono.zip(...) from the getData method and never executes code inside flatmap (line XX), the publisher is getting initialized but not able to subscribe to it. But if I return Mono.just() it is working fine.</p>
<p>Following are the logs</p>
<pre class=""lang-html prettyprint-override""><code>12:47:18.576 [main] INFO reactor.Mono.FlatMap.2 - | onSubscribe([Fuseable] MonoFlatMap.FlatMapMain)
12:47:18.587 [main] INFO reactor.Mono.FlatMap.2 - | request(1)
</code></pre>

<p>What would be the best approach to write unit test cases for this use case with 100% coverage?</p>
",https://stackoverflow.com/questions/69342710/spring-webflux-unit-testing-of-mono,"['unit-testing', 'junit', 'mockito', 'project-reactor']",1378,False,0,0
How to run my code each and everytime on event based triggering,"<p>I've a code in vs-2019, for unit testing with c# and Nunit framework. What I need to do is  to trigger this code using a queue message, everytime when the queue got a new message. How can I do that?? There are suggestions like azure Monitor and azure functions. If thats the case how can I incorporate anyone of them with my code. And I can't post my project here and really sorry for that. Thanks in advance</p>
",https://stackoverflow.com/questions/70358331/how-to-run-my-code-each-and-everytime-on-event-based-triggering,"['c#', 'api', 'unit-testing', 'visual-studio-2019', 'web-api-testing']",63,False,0,1
Unit Test for Auth0 FIle in Angular,"<p>Following is the auth0 service file which is getting used for authentication for the application.
<strong>import * as auth0 from 'auth0-js';</strong>
Using auth0 module I created stub file for testing auth0 service file.Unit testing is getting done in Jasmine Karma.
Test is getting passed but  without any coverage. Hence of no use.
Please help to find out errors in the unit testing code.</p>
<p><strong>Auth0 Service File</strong></p>
<pre><code>@Injectable()
export class AuthService {
  private _Auth0 = new auth0.WebAuth({
    clientID: AUTH_CONFIG.CLIENT_ID,
    domain: AUTH_CONFIG.CLIENT_DOMAIN,
    responseType: 'token id_token',
    redirectUri: AUTH_CONFIG.REDIRECT,
    audience: AUTH_CONFIG.AUDIENCE,
    scope: AUTH_CONFIG.SCOPE
  });

  userProfile: UserProfile;
  accessToken: string;
  expiresAt: number;
  loggedIn: boolean;
  loggedIn$ = new BehaviorSubject&lt;boolean&gt;(this.loggedIn);

  constructor(public router: Router) {
  }

  login() {
    this._Auth0.authorize({ connection: 'value ....' });
  }

  handleLoginCallback() {
    this._Auth0.parseHash((err, authResult) =&gt; {
      if (authResult &amp;&amp; authResult.accessToken) {
        window.location.hash = '';
        this.accessToken = authResult.accessToken;
        this.getUserInfo(authResult);
        this.router.navigate(['/home']);
      } else if (err) {
        console.error(`Error: ${err.error}`);
      } else {
        console.log('Authentication not successful');
      }
    });
  }

  getUserInfo(authResult) {
    this._Auth0.client.userInfo(authResult.accessToken, (err,  profile)  =&gt;  {
      this._setSession(authResult,  profile);
    });
    if  (authResult.idTokenPayload.user_metadata) {   
      let decodedToken = jwt_decode(authResult.accessToken);
      decodedToken[&quot;https://api.test.net/roles&quot;].forEach(role =&gt; {
        if (role == &quot;COMMON_EXCEPTIONHANDLER_UPDATER&quot;) {
          localStorage.setItem(&quot;perm&quot;, 'write');
        }
      }); 
      localStorage.setItem('loggedInUser',
     `${authResult.idTokenPayload.user_metadata.username}@${authResult.idTokenPayload.name}`);
    }
  }

  private _setSession(authResult, profile) {
    this.expiresAt = authResult.expiresIn * 1000 + Date.now();
    this.accessToken = authResult.accessToken;
    this.userProfile = profile;
    this._setLoggedIn(true);
  }

  logout() {
    this._Auth0.logout({
      returnTo: environment.returnTo,
      clientID: AUTH_CONFIG.CLIENT_ID
    });
    localStorage.removeItem('loggedInUser');
  }

  private _setLoggedIn(value: boolean) {
    this.loggedIn$.next(value);
    this.loggedIn = value;
  }

  get authenticated(): boolean {
    return (Date.now() &lt; this.expiresAt) &amp;&amp; this.loggedIn;
  }
}

**Following is the stub file created**

import { Observable, of } from 'rxjs';
export class Auth0SecurityServiceStub {
    authorize() {}

    parseHash() {
        return { user: 'bob', idToken: 'token' };
    }

    logout() { return of(true);}

    authenticated() {
        return true;
    }

    accessToken = &quot;eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVC&quot;;

    userProfile: {
        &quot;sub&quot;: &quot;waad|nwr1ZvxhR3Bdpn4Xapd9i9F_x48y0cdrqQ5mTQeNjjI&quot;,
        &quot;given_name&quot;: &quot;test1&quot;,
        &quot;family_name&quot;: &quot;test3&quot;,
        &quot;nickname&quot;: &quot;M@test.com&quot;,
        &quot;name&quot;: &quot;test&quot;,
        &quot;picture&quot;: &quot;https://s.gravatar.com/avatar/0cd89133dd90b50a34e97da7d146cc45?s=480&amp;r=pg&amp;d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fmm.png&quot;,
        &quot;updated_at&quot;: &quot;2021-08-03T15&quot;,
        &quot;email&quot;: &quot;test@test.com&quot;,
        &quot;email_verified&quot;: true
    };
    expiresAt = '1628012228162';
    loggedIn = true;
}
</code></pre>
<p>Please help how to get code covered with proper testing.</p>
",https://stackoverflow.com/questions/68639846/unit-test-for-auth0-file-in-angular,"['angular', 'unit-testing', 'karma-jasmine', 'auth0', 'karma-coverage']",371,False,0,1
NSubstitute : Can not return value of type Task`1 for IMapperBase.Map (expected type List`1),"<p>I write a unit test, in the test I want to test my <code>CashCapitalService</code>.</p>
<p>in my service, I used <code>AutoMapper</code> for mapping my model to dto and reverse.</p>
<p>My Service is:</p>
<pre class=""lang-cs prettyprint-override""><code>public class CashCapitalService : ICashCapitalService
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IMapper _mapper;
    public CashCapitalService(IUnitOfWork unitOfWork, IMapper mapper)
    {
        _unitOfWork = unitOfWork;
        _mapper = mapper;
    }

    public async Task&lt;List&lt;CashCapitalInsertAndUpdateDto&gt;&gt; GetAllAsync()
    {
        var allAsync = await _unitOfWork.CashCapitalRepository.GetAllAsync();

        List&lt;CashCapitalInsertAndUpdateDto&gt; cashCapitalInsertAndUpdateDtos = _mapper.Map&lt;List&lt;CashCapitalInsertAndUpdateDto&gt;&gt;(source:allAsync);
        return cashCapitalInsertAndUpdateDtos;
    }
}
    
public class CashCapitalService : ICashCapitalService
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IMapper _mapper;
    public CashCapitalService(IUnitOfWork unitOfWork, IMapper mapper)
    {
        _unitOfWork = unitOfWork;
        _mapper = mapper;
    }

    public async Task&lt;List&lt;CashCapitalInsertAndUpdateDto&gt;&gt; GetAllAsync()
    {
        var allAsync = await _unitOfWork.CashCapitalRepository.GetAllAsync();

        List&lt;CashCapitalInsertAndUpdateDto&gt; cashCapitalInsertAndUpdateDtos = _mapper.Map&lt;List&lt;CashCapitalInsertAndUpdateDto&gt;&gt;(source:allAsync);
        return cashCapitalInsertAndUpdateDtos;
    }
}
</code></pre>
<p>as you can see Automapper profile is:</p>
<pre class=""lang-cs prettyprint-override""><code>public class CashCapitalInsertDtoProfile : Profile
{
    public CashCapitalInsertDtoProfile()
    {
        CreateMap&lt;CashCapitalInsertAndUpdateDto, CashCapital&gt;().ReverseMap();
    }
}
</code></pre>
<p>and in my unit test:</p>
<pre class=""lang-cs prettyprint-override""><code>public class CashCapitalServiceTest
{
    private readonly CashCapitalService _cashCapitalService;
    private readonly IUnitOfWork _unitOfWork;
    private readonly IMapper _mapper;

    public CashCapitalServiceTest()
    {
        _unitOfWork = Substitute.For&lt;IUnitOfWork&gt;();
        _mapper = Substitute.For&lt;IMapper&gt;();
        _cashCapitalService = new CashCapitalService(_unitOfWork, _mapper);
    }

    [Fact]
    public async Task GetAllAsync_Should_GetAllCashCapital()
    {
        //Arrange
        _unitOfWork.CashCapitalRepository.GetAllAsync().Returns(new List&lt;CashCapital&gt;());

        var cashCapitals = new List&lt;CashCapital&gt;()
        {
            new CashCapital()
            {
                InsertDateTime = DateTime.Now,
                AmountRial = 250000000, 
                Description = &quot;tv,a lj,v&quot;
            }
        };

        var cashCapitalInsertAndUpdateDtos = new List&lt;CashCapitalInsertAndUpdateDto&gt;()
        {
            new CashCapitalInsertAndUpdateDto()
            {
                AmountRial = 250000000, Description = &quot;tv,a lj,v&quot;
            }
        };

        //var returnValue = _mapper.Map(Arg.Any&lt;List&lt;CashCapital&gt;&gt;(), Arg.Any&lt;List&lt;CashCapitalInsertAndUpdateDto&gt;&gt;());
        //_cashCapitalService.GetAllAsync().Returns(returnValue);
        _mapper.Map(cashCapitals, cashCapitalInsertAndUpdateDtos).Returns(new List&lt;CashCapitalInsertAndUpdateDto&gt;()
        {
            new CashCapitalInsertAndUpdateDto()
            {
                AmountRial = 250000000, Description = &quot;tv,a lj,v&quot;
            }
        });
        var resultValue = _mapper.Map(cashCapitals, cashCapitalInsertAndUpdateDtos);

        _cashCapitalService.GetAllAsync().ReturnsForAnyArgs(resultValue);
        //Act
        var all = await _cashCapitalService.GetAllAsync();

        //Assert
        all.Should().BeOfType&lt;List&lt;CashCapitalInsertAndUpdateDto&gt;&gt;();
        await _unitOfWork.CashCapitalRepository.Received(1).GetAllAsync();
    }
}
</code></pre>
<p>When I run this test, failed and give me an error:</p>
<blockquote>
<p>Message:
NSubstitute.Exceptions.CouldNotSetReturnDueToTypeMismatchException : Can not return value of type Task<code>1 for IMapperBase.Map (expected type List</code>1).</p>
</blockquote>
<p>I'm new in unit testing and the NSubstitute library, I don't know how to mock the AutoMapper.</p>
",https://stackoverflow.com/questions/66396916/nsubstitute-can-not-return-value-of-type-task1-for-imapperbase-map-expected,"['unit-testing', 'automapper', 'xunit.net', 'nsubstitute']",699,False,0,0
E.g. thenReturn() may be missing. Examples of correct stubbing: unit test in springboot,"<p>I am trying to unit test BookService class and I am very new to unit testing.
In project, I am using DTO's, and I am converting them back and forward as needed.</p>
<p>My test class looks like this:</p>
<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration
class BookServiceTest {


    @InjectMocks
    BookService bookService;

    @Mock
    BookRepository bookRepository;

    @Mock
    private ModelMapper modelMapper;
    private BookDto bookDto = new BookDto();
    private Book book = new Book();


    @Test
    void addNewBook() {
        bookDto.setId(1L);
        bookDto.setTitle(&quot;Harry Potter&quot;);
        bookDto.setAuthor(&quot;J. K. Rowling&quot;);
        bookDto.setPublisher(&quot;Bloomsbury Publishing&quot;);
        bookDto.setCategory(Category.NEW);
        bookDto.setTotalCount(10);
        bookDto.setRented(0);

        book = modelMapper.map(bookDto, Book.class);

        Mockito.when(bookRepository.save(book)).thenReturn(book);
        assertEquals(bookService.addNewBook(bookDto), book);

    }
</code></pre>
<p>And when I run the test I get this error:</p>
<pre><code>E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed
</code></pre>
<p>What am I missing?</p>
<p><strong>UPDATE</strong></p>
<pre><code>    @Test
    void findBookById() {
        bookDto.setId(2L);
        bookDto.setTitle(&quot;Harry Potter&quot;);
        bookDto.setAuthor(&quot;J. K. Rowling&quot;);
        bookDto.setPublisher(&quot;Bloomsbury Publishing&quot;);
        bookDto.setCategory(Category.CLASSIC);
        bookDto.setTotalCount(10);
        bookDto.setRented(0);

        book = modelMapper.map(bookDto, Book.class);

        Mockito.when(bookRepository.findById(2L)).thenReturn(Optional.ofNullable(book));
        assertEquals(book, bookService.findBookById(2L));
    }
</code></pre>
<p>And this part of code returns like id = 2 doesn't exist which is not true. It exists.</p>
<p>Same is for this code test</p>
<pre><code>    @Test
    void allBooks() {

        BookDto bookDto = new BookDto();
        bookDto.setId(2L);
        bookDto.setTitle(&quot;Harry Potter&quot;);
        bookDto.setAuthor(&quot;J. K. Rowling&quot;);
        bookDto.setPublisher(&quot;Bloomsbury Publishing&quot;);
        bookDto.setCategory(Category.NEW);
        bookDto.setTotalCount(10);
        bookDto.setRented(0);

        BookDto bookDto1 = new BookDto();
        bookDto1.setId(3L);
        bookDto1.setTitle(&quot;1984&quot;);
        bookDto1.setAuthor(&quot;George Orwell&quot;);
        bookDto1.setPublisher(&quot;George Orwell Publishing&quot;);
        bookDto1.setCategory(Category.CLASSIC);
        bookDto1.setTotalCount(10);
        bookDto.setRented(2);

        List&lt;BookDto&gt; books = new ArrayList&lt;&gt;();
        books.add(bookDto);
        books.add(bookDto1);

        List&lt;Book&gt; bookList = Arrays.asList(modelMapper.map(bookDto, Book.class));

        Mockito.when(bookRepository.findAll()).thenReturn(bookList);
        assertEquals(bookDto, bookService.allBooks());


    }
</code></pre>
<p>it says <code>java.lang.IllegalArgumentException: source cannot be null</code></p>
",https://stackoverflow.com/questions/66772827/e-g-thenreturn-may-be-missing-examples-of-correct-stubbing-unit-test-in-spr,"['java', 'spring-boot', 'unit-testing', 'junit']",601,False,0,1
Unable to test a service method in angular using jasmine,"<p>I am doing unit testing in angular. In the <code>component.ts</code>, inside the <code>ngOnInit</code>, I have a service method call which I have shown below:</p>
<pre><code>ngOnInit(){
   this.DomainManagementService.getVerifiedDomains().then(res =&gt; {
      this.claimedDomains = res.filter(domain =&gt; {
        return domain.status === 'claimed';
      });
    });
}
</code></pre>
<p>I am getting the data from the <code>getVerifiedDomains()</code> method and then applying filter method to filter out only the claimed domains. Finally I am storing the filtered domains in <code>this.claimedDomains</code>.
Now I need to test whether the length of <code>this.claimedDomains</code> is greater than 0 or not. How to do this? Please help me to write the test case.</p>
",https://stackoverflow.com/questions/67524053/unable-to-test-a-service-method-in-angular-using-jasmine,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",114,True,0,2
"Facing issue with vertx junit configuratoin , error in vertx.deployVerticle , How to setup spring verticalfactory in deployment test","<p>I want to test particular REST APIs written in vertx with spring boot.</p>
<p>below is test class</p>
<pre><code>@RunWith(VertxUnitRunner.class)
public class sampleTest {
    private Vertx vertx;
    private Integer port;

    @Before
    public void setUp(TestContext context) throws IOException {
        vertx = Vertx.vertx();

        ServerSocket socket = new ServerSocket(0);
        port = socket.getLocalPort();
        socket.close();

        DeploymentOptions options = new DeploymentOptions()
                .setConfig(new JsonObject().put(&quot;http.port&quot;, port)
                );
        vertx.deployVerticle(sampleVerticle.class.getName(), options, context.asyncAssertSuccess());
    }

    @After
    public void tearDown(TestContext context) {
        vertx.close(context.asyncAssertSuccess());
    }

    @Test
    public void givenId_whenReceivedArticle_thenSuccess(TestContext testContext) {
        final Async async = testContext.async();

        vertx.createHttpClient()
                .getNow(port, &quot;localhost&quot;, &quot;/tracking/id/12345/12345/12345&quot;, response -&gt; {
                    response.handler(responseBody -&gt; {
                        testContext.assertTrue(responseBody.toString()
                                .contains(&quot;\&quot;articalId\&quot; : \&quot;12345\&quot;&quot;));
                        testContext.assertTrue(responseBody.toString()
                                .contains(&quot;\&quot;pageId\&quot; : \&quot;12345\&quot;&quot;));
                        testContext.assertTrue(responseBody.toString()
                                .contains(&quot;\&quot;eventId\&quot; : \&quot;12345\&quot;&quot;));
                        async.complete();
                    });
                });
    }

}
</code></pre>
<p>here im just checking url parameter.
Now when i run above test class it throws error</p>
<blockquote>
<p>java.lang.InstantiationException:
com.articals.sampleVerticle</p>
</blockquote>
<p>Below is sampleVerticle class where multiple routers are handled,</p>
<pre><code>@Component
@Slf4j
@Scope(SCOPE_PROTOTYPE)
class sampleVerticle extends AbstractVerticle {

    private final Router router
    private final ArticalHandler articalHandler
    private final FailureHandler failureHandler
    private final MetricsHandler metricsHandler

    ClickVerticle(
            Router router,
            ArticalHandler articalHandler,
            FailureHandler failureHandler,
            MetricsHandler metricsHandler
    )
    {
        this.articalHandler= articalHandler
        this.router = router
        this.failureHandler = failureHandler
        this.metricsHandler = metricsHandler
    }


    @Override
    void start() throws Exception {

        router.get('/tracking/id/:articalId/:pageId/:eventId')
              .handler(articalHandler)
              .failureHandler(failureHandler)


        router.get('/metrics')
              .handler(metricsHandler)
              .failureHandler(failureHandler)

    }
}
</code></pre>
<p>If i include default constructor then i error</p>
<blockquote>
<p>Cannot invoke method get() on null object</p>
</blockquote>
<p>I am following this example for unit testing
<a href=""https://www.baeldung.com/vertx"" rel=""nofollow noreferrer"">https://www.baeldung.com/vertx</a></p>
<p>Please help me with above issue.</p>
<p>Thanks &amp; Regards</p>
",https://stackoverflow.com/questions/66190042/facing-issue-with-vertx-junit-configuratoin-error-in-vertx-deployverticle-ho,"['java', 'spring-boot', 'rest', 'junit', 'vert.x']",131,False,-1,1
"How do I use Jest to test the output in one element, from an input from another element?","<p>My test is trying to mock a user typing &quot;abcdef&quot; in the textarea as an input, and then verify if the same string (&quot;abcdef&quot;) is written in the output:</p>
<pre><code>it(&quot;should write in input and correspond in output&quot;, async () =&gt; {
    render(App);

    const input = document.getElementById(&quot;input&quot;);
    fireEvent.change(input, { target: { value: 'abcdef' }})
    
    let output = document.getElementById(&quot;output&quot;);
    expect(output).toHaveTextContent(&quot;abcdef&quot;); // undefined
});
</code></pre>
<p>This is the output element:</p>
<pre><code>    &lt;h1 id=&quot;output&quot;&gt;{output}&lt;/h1&gt;
</code></pre>
<p>If I hardcode 'abcdef' next to the {output} tag, then my test passes, but the <em>fireEvent.change</em> doesn't seem to work properly. Maybe I misunderstand the capabilities of Jest - maybe it only does unit testing, and not user-tests /end-to-end testing?</p>
",https://stackoverflow.com/questions/69241760/how-do-i-use-jest-to-test-the-output-in-one-element-from-an-input-from-another,"['jestjs', 'svelte']",380,True,0,1
I am getting this error &quot;TypeError: this.reCaptchaApi.render is not a function&quot; when I try to access elements of reactive form for unit testing,"<p>I am trying to write unit test cases for registration component in my project, but when I try to access a input ele by ID to test it's placeholder which is in the same form with ngx-recaptcha2, I this error <strong>TypeError: this.reCaptchaApi.render is not a function</strong></p>
<p>HTML</p>
<pre><code>&lt;ngx-recaptcha2
            #captchaElem
            [siteKey]=&quot;siteKey&quot;
            (success)=&quot;handleSuccess($event)&quot;
            [useGlobalDomain]=&quot;false&quot;
            size=&quot;100&quot;
            formControlName=&quot;recaptcha&quot;
          &gt;
          &lt;/ngx-recaptcha2&gt;
</code></pre>
<p>SPEC.TS(unit testing file)</p>
<pre><code>import { async, ComponentFixture, TestBed } from &quot;@angular/core/testing&quot;;
    import { FormBuilder, FormsModule, ReactiveFormsModule } from &quot;@angular/forms&quot;;
    import { SpinnerVisibilityService } from &quot;ng-http-loader&quot;;
    import {
      HttpClientTestingModule,
      HttpTestingController,
    } from &quot;@angular/common/http/testing&quot;;
    import { AuthService } from &quot;src/app/shared/services/auth.service&quot;;
    import { CookieService } from &quot;src/app/shared/services/cookie.service&quot;;
    import { SharedService } from &quot;src/app/shared/services/shared.service&quot;;
    import { RouterTestingModule } from &quot;@angular/router/testing&quot;;
    import { RegistrationComponent } from &quot;./registration.component&quot;;
    import { NgxCaptchaModule } from &quot;ngx-captcha&quot;;
    import { DebugElement } from &quot;@angular/core&quot;;
    import { By } from &quot;@angular/platform-browser&quot;;
    
    fdescribe(&quot;RegistrationComponent&quot;, () =&gt; {
      let component: RegistrationComponent;
      let fixture: ComponentFixture&lt;RegistrationComponent&gt;;
      let el: DebugElement;
      beforeEach(async(() =&gt; {
        TestBed.configureTestingModule({
          imports: [
            FormsModule,
            ReactiveFormsModule,
            RouterTestingModule,
            HttpClientTestingModule,
            NgxCaptchaModule,
          ],
          declarations: [RegistrationComponent],
          providers: [
            AuthService,
            SharedService,
            CookieService,
            SpinnerVisibilityService,
          ],
        }).compileComponents();
      }));
    
      beforeEach(() =&gt; {
        fixture = TestBed.createComponent(RegistrationComponent);
        component = fixture.componentInstance;
        el = fixture.debugElement;
        fixture.detectChanges();
      });
    
      it(&quot;should create&quot;, () =&gt; {
        expect(component).toBeTruthy();
      });
    
      it(&quot;checking card heading&quot;, () =&gt; {
        const title = el.queryAll(By.css(&quot;#card-heading&quot;));
        expect(title).toBeTruthy();
        expect(title[0].nativeElement.textContent).toBe(&quot;Create a new account&quot;);
      });
    
      it(&quot;fisrt name&quot;, () =&gt; {
        const title = el.queryAll(By.css(&quot;#firstName&quot;));
        expect(title).toBeTruthy();
        expect(title[0].nativeElement.placeholder).toBe(&quot;First Name&quot;);
      });
    
    });
</code></pre>
<p>TS(typescipt file)</p>
<pre><code>ngOnInit(): void {
this.siteKey = &quot;6Lc0E2caAAAAAOMswzmbCRbYEYtH_rtFFMlc9SDE&quot;;
this.formInIt();
this.getCountryCode();
this.Form.valueChanges.subscribe(
  (value) =&gt; {
    if (value) {
      this.errorMessage = null;
    }
  },
  (error: any) =&gt; {
    this.catchServerError(error, this.Form);
  }
);

this.country.valueChanges.subscribe((value) =&gt; {
  const selectedCountry = this.totalCountryCode.find(
    (obj) =&gt; obj.name === value
  );
  this.selectedCountryCode = selectedCountry.dial_code;
  if (selectedCountry.regEx) {
    this.Form.get(&quot;phone&quot;).clearValidators();
    this.Form.get(&quot;phone&quot;).setValue(&quot;&quot;);
    this.Form.get(&quot;phone&quot;).setValidators(
      Validators.compose([
        Validators.required,
        Validators.pattern(selectedCountry.regEx),
      ])
    );
    this.Form.get(&quot;phone&quot;).updateValueAndValidity();
  }
});
  

}

  
  

formInIt() {
    this.Form = this.fb.group({
      firstName: [
        &quot;&quot;,
        [Validators.required, Validators.pattern(AppSettings.FIRST_NAME)],
      ],
      lastName: [
        &quot;&quot;,
        [Validators.required, Validators.pattern(AppSettings.LAST_NAME)],
      ],
      email: [&quot;&quot;, [Validators.required, Validators.pattern(AppSettings.EMAIL)]],
      country: [&quot;India&quot;, Validators.required],
      phone: [
        &quot;&quot;,
        [Validators.required, Validators.pattern(AppSettings.PHONE_NUMBER)],
      ],
      websiteUrl: [&quot;&quot;, [Validators.pattern(AppSettings.WEBSITE_URL)]],
      password: [
        &quot;&quot;,
        [Validators.required, Validators.pattern(AppSettings.PASSWORD)],
      ],
      confirmPassword: [&quot;&quot;, Validators.required],
      role: [&quot;&quot;, Validators.required],
      recaptcha: [&quot;&quot;,Validators.required],
      instructionsDeclarationAccepted: [&quot;&quot;, Validators.required],
    });

    this.confirmPassword.valueChanges.subscribe(
      (value) =&gt; {
        if (this.password.value !== this.confirmPassword.value) {
          this.confirmPassword.setErrors({ MatchPassword: true });
        } else {
          return null;
        }
      },
      (error: any) =&gt; {
        this.catchServerError(error, this.Form);
      }
    );

    this.password.valueChanges.subscribe(
      (value) =&gt; {
        if (this.password.value !== this.confirmPassword.value) {
          this.confirmPassword.setErrors({ MatchPassword: true });
        } else {
          this.confirmPassword.setErrors({ MatchPassword: false });
          this.confirmPassword.updateValueAndValidity();
        }
        
      },
      (error: any) =&gt; {
        this.catchServerError(error, this.Form);
      }
    );
  }
</code></pre>
<p>Can anyone please help me out, how to approach this problem, should I mock it or is there any other way, please guide me.</p>
",https://stackoverflow.com/questions/69879357/i-am-getting-this-error-typeerror-this-recaptchaapi-render-is-not-a-function,"['angular', 'unit-testing', 'recaptcha']",299,True,0,2
How to fetch and parse all the generated coverage.cobertura files in CI pipelines?,"<p>Given a .Net 5 solution with multiple xUnit test projects I can run <code>dotnet test</code> from the root of the solution and it will run all the tests.</p>
<p>I would like to generate reports so based on <a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#integrate-with-net-test"" rel=""noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#integrate-with-net-test</a> I run <code>dotnet test --collect:&quot;XPlat Code Coverage&quot;</code> which generates a coverage.cobertura file per test project.</p>
<p>Based on <a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports"" rel=""noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports</a> I know that I can install the <code>dotnet-reportgenerator-globaltool</code> tool and get a visual HTML report based on each coverage.cobertura file.</p>
<p>But I want to add a CI pipeline where I want to make the pipeline fail when the line coverage is below x %.</p>
<p>Given the following sample Gitlab CI configuration</p>
<pre><code>image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - tests

tests:
  stage: tests
  script:
    - dotnet test --collect:&quot;XPlat Code Coverage&quot;
</code></pre>
<p>how can I gather all the generated <code>coverage.cobertura.xml</code> files, read the line coverage and let the pipeline fail if the value is below e.g. 80%?</p>
<p>Example:</p>
<pre><code>tests:
  stage: tests
  script:
    - dotnet test --collect:&quot;XPlat Code Coverage&quot;
    # for each coverage.cobertura file found in the test projects
    # parse the file
    # read the line coverage
    # fail if the value is less than 80 percent
</code></pre>
<p>It would be nice if I don't have to reinvent the wheel if tools like xUnit already provide such functionality!</p>
<hr />
<p>Edit:</p>
<p>I know that I could also use the <a href=""https://docs.gitlab.com/ce/ci/yaml/index.html#allow_failure"" rel=""noreferrer"">allow_failure</a> keyword to leave this stage in a warning state. This would be fine for me, I just want to know how to read the required information from the generated reports and validate them to decide if that stage should pass, fail or be unstable.</p>
",https://stackoverflow.com/questions/68348031/how-to-fetch-and-parse-all-the-generated-coverage-cobertura-files-in-ci-pipeline,"['c#', 'gitlab-ci', 'code-coverage', 'xunit']",2502,True,9,2
how to define function within an object you make in typescript,"<p>I have written the following object in typescript, which I need for a stub in unit testing (I know the values/function definitions make no sense but it's just a stub):</p>
<pre><code>    const obj = {
      isEmpty: true,
      testName: 'unitTest',
      getTime: () =&gt; 5,
      success: () =&gt; {},
      fail: () =&gt; {},
      wait: () =&gt; {},
    };
</code></pre>
<p><code>getTime</code>,<code>success</code>,<code>fail</code> and <code>wait</code> are supposed to be functions, but when I hover over them in VSCode, they are given as properties (like <code>isEmpty</code> and <code>testName</code>). Is there any way I can make it so they are strictly recognised as functions? (this is important later on in the unit test)</p>
",https://stackoverflow.com/questions/69392329/how-to-define-function-within-an-object-you-make-in-typescript,"['typescript', 'object']",32,True,0,1
unable to catch2 hello test on mac running Apple LLVM version 10.0.1,"<p>Im only trying my tutorial to try catch2 unit testing lib. Im using mac with 10.14.
I dont have full XCode, only cmd tools and macports runs perfect in my setup (no brew).
Im using the amalgamated single header and source file as suggested.</p>
<p>Yet, a simple tutorial:</p>
<pre><code>#define CATCH_CONFIG_MAIN  // This tells Catch to provide a main() - only do this in one cpp file
#include &quot;catch.hpp&quot;

unsigned int Factorial( unsigned int number ) {
    return number &lt;= 1 ? number : Factorial(number-1)*number;
}


TEST_CASE( &quot;Factorials are computed&quot;, &quot;[factorial]&quot; ) {
    REQUIRE( Factorial(1) == 1 );
    REQUIRE( Factorial(2) == 2 );
    REQUIRE( Factorial(3) == 6 );
    REQUIRE( Factorial(10) == 3628800 );
}
</code></pre>
<p>gives many compile errors - snip:</p>
<pre><code>In file included from test1.cpp:2:
./catch.hpp:75:49: warning: deleted function definitions are a C++11 extension [-Wc++11-extensions]
            NonCopyable( NonCopyable const&amp; ) = delete;
                                                ^
./catch.hpp:76:37: warning: rvalue references are a C++11 extension [-Wc++11-extensions]
            NonCopyable( NonCopyable&amp;&amp; ) = delete;
                                    ^
./catch.hpp:76:44: warning: deleted function definitions are a C++11 extension [-Wc++11-extensions]
            NonCopyable( NonCopyable&amp;&amp; ) = delete;
                                           ^
./catch.hpp:77:60: warning: deleted function definitions are a C++11 extension [-Wc++11-extensions]
            NonCopyable&amp; operator=( NonCopyable const&amp; ) = delete;
                                                           ^
./catch.hpp:78:48: warning: rvalue references are a C++11 extension [-Wc++11-extensions]
            NonCopyable&amp; operator=( NonCopyable&amp;&amp; ) = delete;
                                               ^
./catch.hpp:78:55: warning: deleted function definitions are a C++11 extension [-Wc++11-extensions]
            NonCopyable&amp; operator=( NonCopyable&amp;&amp; ) = delete;
                                                      ^
./catch.hpp:81:26: error: expected ';' at end of declaration list
            NonCopyable() noexcept = default;
                         ^
                         ;
</code></pre>
<p>Please suggest, Thanks.</p>
<p>Edit:</p>
<p>After @Tiib suggested to try with <code>g++ -std=c++17</code> the code got compiled and build. <code>g++ -std=c++11</code> also did not work. Not understood why.</p>
",https://stackoverflow.com/questions/67521108/unable-to-catch2-hello-test-on-mac-running-apple-llvm-version-10-0-1,"['c++', 'unit-testing', 'tdd', 'catch2']",299,False,0,0
Why I always get &quot;No tests were found&quot; &quot;Class not found: xxx&quot; when running the defualt local unit ExampleUnitTest class on Android?,"<p>I'm trying to use Unit testing using JUnit in my android project, so I tried to run the ExampleUnitTest class in the (test) folder with this statement:</p>
<pre><code>Assert.assertEquals(4,5)
</code></pre>
<p>and it passed I don't know why then I created another class in the same folder and now I get the error even on the ExampleUnitTest class</p>
<blockquote>
<p>No tests where found
with a message
Class not found: &quot;{{packageName}}.ExampleUnitTest&quot;</p>
</blockquote>
<p>This is the ExampleUnitTest class
<a href=""https://i.stack.imgur.com/dA5gd.png"" rel=""nofollow noreferrer"">ExampleUnitTest class</a></p>
<p>This is the configuration
<a href=""https://i.stack.imgur.com/CpwdR.png"" rel=""nofollow noreferrer"">ExampleUnitTest configuration</a></p>
<p>Using this dependency:</p>
<pre><code>testImplementation 'junit:junit:4.13.2'
</code></pre>
",https://stackoverflow.com/questions/69173670/why-i-always-get-no-tests-were-found-class-not-found-xxx-when-running-the-d,"['android', 'android-studio', 'unit-testing', 'testing', 'junit']",56,False,2,0
Jest Fetch API call unit test - unhandledpromiserejection error,"<p>I have a fetch call and unit test for that fetch all. It was working, suddenly i see that unit test cases failed for API unit testing. Below is my code</p>
<p>React fetch call</p>
<pre><code>export const getUser = async () =&gt; {
  try {
    const resp = await fetch(url);
    return resp.json();
  } catch (err) {
    throw new Error(err);
  }
};
</code></pre>
<p>Unit test case</p>
<pre><code>const mockResp = {};
const mockJsonPromise = Promise.resolve(mockResp);
const mockFetchPromise = Promise.resolve({
  json: () =&gt; mockJsonPromise,
});

jest.spyOn(global, &quot;fetch&quot;).mockImplementation(() =&gt; mockFetchPromise);

test(&quot;test getUser&quot;, (done) =&gt; {
  expect(getUser()).toEqual(mockFetchPromise);
  global.fetch.mockClear();
  done();
});
</code></pre>
<p>Error  - UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with reason &quot;Error: TypeError: Cannot read properties of undefined (reading 'json')&quot;</p>
",https://stackoverflow.com/questions/70219173/jest-fetch-api-call-unit-test-unhandledpromiserejection-error,"['reactjs', 'unit-testing', 'jestjs', 'fetch-api', 'unhandled-promise-rejection']",241,False,2,0
JUnit5 Assert List of similar Object are equal,"<p>I need to test a layer of a method that maps a list of objects into a list of another, e.g. transforming from a list of objects we don't control to a list of objects we do. I can't compare by using equals() since the objects are of different types, but I need to test that the list and object values are being mapped correctly.</p>
<p>My current implementation is:</p>
<pre><code>    public void test {
        // GIVEN
        List&lt;T1&gt; l1 = api.getData();
    
        // WHEN
        List&lt;T2&gt; l2 = getList();
    
        // THEN
        assertEquals(l1.size(), l1.size());

        for(int i = 0; i &lt; l1.size(); i++) {
            assertEquals(l1.get(i).getVal1(), l2.get(i).getVal1());
            assertEquals(l1.get(i).getVal2(), l2.get(i).getVal2());
            assertEquals(l1.get(i).getVal3(), l2.get(i).getVal3());
            ...
            
        }

    
    }
</code></pre>
<p>I'm new to unit testing. Is there a better way to structure this test?</p>
",https://stackoverflow.com/questions/65877682/junit5-assert-list-of-similar-object-are-equal,"['java', 'junit5']",305,True,2,1
Flutter BLoC Test failures,"<p>Currently trying to implement Unit testing for my cubit and am feeling there is a severe lack in documentation for BLoC test online or useful examples. Can anyone explain what I'm doing wrong with setting up this test. I can't seem to figure out what the problem is. If anyone could shed just a little bit of light on what I can do to fix this, it would be greatly appreciated.</p>
<p>SettingsState File:</p>
<pre><code>class SettingsState extends Equatable {
  late final bool expandNavigation;
  late final bool gpsEnabled;
  late final bool celsiusEnabled;
  late final bool notificationsEnabled;
  late final bool breakingNewsNotifications;
  late final bool trendingNotifications;
  late final bool liveRemindersNotifications;
  late final bool sportsNotifications;
  SettingsState({
    required this.notificationsEnabled,
    required this.gpsEnabled,
    required this.celsiusEnabled,
    required this.expandNavigation,
    required this.breakingNewsNotifications,
    required this.trendingNotifications,
    required this.liveRemindersNotifications,
    required this.sportsNotifications,
  });
  SettingsState copyWith({
    bool? gpsEnabled,
    bool? celsiusEnabled,
    bool? expandNavigation,
    bool? notificationsEnabled,
    bool? breakingNewsNotifications,
    bool? trendingNotifications,
    bool? liveRemindersNotifications,
    bool? sportsNotifications,
  }) {
    return SettingsState(
      expandNavigation: expandNavigation ?? this.expandNavigation,
      gpsEnabled: gpsEnabled ?? this.gpsEnabled,
      celsiusEnabled: celsiusEnabled ?? this.celsiusEnabled,
      notificationsEnabled: notificationsEnabled ?? this.notificationsEnabled,
      breakingNewsNotifications:
          breakingNewsNotifications ?? this.breakingNewsNotifications,
      trendingNotifications:
          trendingNotifications ?? this.trendingNotifications,
      liveRemindersNotifications:
          liveRemindersNotifications ?? this.liveRemindersNotifications,
      sportsNotifications: sportsNotifications ?? this.sportsNotifications,
    );
  }
  // mapping user settings
  Map&lt;String, dynamic&gt; toMap() {
    return {
      'expandNavigation': expandNavigation,
      'gpsEnabled': gpsEnabled,
      'celsiusEnabled': celsiusEnabled,
      'notificationsEnabled': notificationsEnabled,
      'breakingNewsNotifications': breakingNewsNotifications,
      'trendingNotifications': trendingNotifications,
      'liveRemindersNotifications': liveRemindersNotifications,
      'sportsNotifications': sportsNotifications,
    };
  }
  //  grabbing settings state from map
  factory SettingsState.fromMap(Map&lt;String, dynamic&gt; map) {
    if (map == map['']) {
      return SettingsState(
        expandNavigation: map[''],
        gpsEnabled: map[''],
        celsiusEnabled: map[''],
        notificationsEnabled: map[''],
        breakingNewsNotifications: map[''],
        trendingNotifications: map[''],
        liveRemindersNotifications: map[''],
        sportsNotifications: map[''],
      );
    } else {
      return SettingsState(
        expandNavigation: map['expandNavigation'],
        gpsEnabled: map['gpsEnabled'],
        celsiusEnabled: map['celsiusEnabled'],
        notificationsEnabled: map['notificationsEnabled'],
        breakingNewsNotifications: map['breakingNewsNotifications'],
        trendingNotifications: map['trendingNotifications'],
        liveRemindersNotifications: map['liveRemindersNotifications'],
        sportsNotifications: map['sportsNotifications'],
      );
    }
  }
  // encode to a json
  String toJson() =&gt; json.encode(toMap());
  // decode the json
  factory SettingsState.fromJson(String source) =&gt;
      SettingsState.fromMap(json.decode(source));
  //! Helps for equatable and unit testing
  @override
  List&lt;Object?&gt; get props =&gt; [
        expandNavigation,
        gpsEnabled,
        celsiusEnabled,
        notificationsEnabled,
        breakingNewsNotifications,
        trendingNotifications,
        liveRemindersNotifications,
        sportsNotifications,
      ];
  //! Shows changes in State for Bloc Observers
  @override
  String toString() =&gt; 'SettingsState(expandNavigation: $expandNavigation, '
      'gpsEnabled: $gpsEnabled, celsiusEnabled: $celsiusEnabled, notificationsEnabled: $notificationsEnabled,'
      'breakingNewsNotifications: $breakingNewsNotifications, trendingNotifications: $trendingNotifications,'
      ' liveRemindersNotifications: $liveRemindersNotifications, sportsNotifications: $sportsNotifications)';
}
</code></pre>
<p>SettingsCubit File:</p>
<pre><code>import 'dart:convert';
import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
part 'settings_state.dart';
//bloc/cubit for the settings screen
class SettingsCubit extends Cubit&lt;SettingsState&gt; with HydratedMixin {
  SettingsCubit()
      : super(SettingsState(
          expandNavigation: false,
          gpsEnabled: false,
          celsiusEnabled: false,
          notificationsEnabled: false,
          breakingNewsNotifications: false,
          trendingNotifications: false,
          liveRemindersNotifications: false,
          sportsNotifications: false,
        ));
  // Toggle for Expanding Navigation
  void toggleExpandNavigation(bool newValue) =&gt;
      emit(state.copyWith(expandNavigation: newValue));
  // Toggle for GPS
  void toggleGpsEnabled(bool newValue) =&gt;
      emit(state.copyWith(gpsEnabled: newValue));
  // Toggle for Celsius or Fahrenheit
  void toggleCelsiusEnabled(bool newValue) =&gt;
      emit(state.copyWith(celsiusEnabled: newValue));
  // Toggle for All Notifications
  void toggleNotificationsEnabled(bool newValue) {
    emit(state.copyWith(notificationsEnabled: newValue));
  }
  // Toggle for Breaking News Notifications
  void toggleBreakingNewsNotifications(bool newValue) {
    emit(state.copyWith(breakingNewsNotifications: newValue));
  }
  // Toggle for Trending Notifications
  void toggleTrendingNotifications(bool newValue) {
    emit(state.copyWith(trendingNotifications: newValue));
  }
  // Toggle for Live Reminders Notifications
  void toggleLiveRemindersNotifications(bool newValue) {
    emit(state.copyWith(liveRemindersNotifications: newValue));
  }
  // Toggle for Sports Notifications
  void toggleSportsNotifications(bool newValue) {
    emit(state.copyWith(sportsNotifications: newValue));
  }
  // retrieving from phone storage - json
  @override
  SettingsState? fromJson(Map&lt;String, dynamic&gt; json) {
    return SettingsState.fromMap(json);
  }
  // writing to phone storage - json
  @override
  Map&lt;String, dynamic&gt;? toJson(SettingsState state) {
    return state.toMap();
  }
}
</code></pre>
<p>BLoC Test file:</p>
<pre><code>import 'package:bloc_test/bloc_test.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/services.dart';
import 'package:hydrated_bloc/hydrated_bloc.dart';
import 'package:news_test_app/logic/cubit/settings_cubit.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:path_provider/path_provider.dart';
import 'package:mocktail/mocktail.dart';
class MockCubit extends Mock implements SettingsCubit {}
class MockStorage extends Mock implements Storage {}
void main() {
  TestWidgetsFlutterBinding.ensureInitialized();
  group('SettingsCubit', () {
    SettingsCubit settingsCubit = SettingsCubit();
    Storage storage;
    setUp(() {
      storage = MockStorage();
      HydratedBloc.storage = storage;
      settingsCubit = SettingsCubit();
    });
    tearDown(() {
      settingsCubit.close();
    });
    blocTest&lt;SettingsCubit, SettingsState&gt;(
        'the cubit should emit a SettingsState(expandNavigation: true, gpsEnabled: false, celsiusEnabled: false, notificationsEnabled: false, '
        'breakingNewsNotifications: false, trendingNotifications: false, liveRemindersNotifications: false, sportsNotifications: false) '
        'when cubit.toggleExpandNavigation is called',
        build: () =&gt; settingsCubit,
        act: (cubit) =&gt; settingsCubit.toggleExpandNavigation(true),
        expect: () =&gt; [
              settingsCubit.state,
              //settingsCubit.state,
              // SettingsState(
              //   expandNavigation: false,
              //   gpsEnabled: false,
              //   celsiusEnabled: false,
              //   notificationsEnabled: false,
              //   breakingNewsNotifications: false,
              //   trendingNotifications: false,
              //   liveRemindersNotifications: false,
              //   sportsNotifications: false,
              // ),
            ]);
  });
}
</code></pre>
<p>The console output is:</p>
<pre><code>package:test_api                             expect
package:bloc_test/src/bloc_test.dart 193:9   testBloc.&lt;fn&gt;
===== asynchronous gap ===========================
dart:async                                   _asyncThenWrapperHelper
package:bloc_test/src/bloc_test.dart         testBloc.&lt;fn&gt;
dart:async                                   runZonedGuarded
package:bloc_test/src/bloc_test.dart 172:9   testBloc
package:bloc_test/src/bloc_test.dart 140:11  blocTest.&lt;fn&gt;
package:bloc_test/src/bloc_test.dart 139:26  blocTest.&lt;fn&gt;
Expected: [
            SettingsState:SettingsState(expandNavigation: false, gpsEnabled: false, celsiusEnabled: false, notificationsEnabled: false,breakingNewsNotifications: false, trendingNotifications: false, liveRemindersNotifications: false, sportsNotifications: false)
          ]
  Actual: []
   Which: at location [0] is [] which shorter than expected
</code></pre>
",https://stackoverflow.com/questions/68582768/flutter-bloc-test-failures,"['flutter', 'unit-testing', 'flutter-test', 'bloc', 'bloc-test']",1221,False,2,0
Factory relationship returning null laravel testing,"<p>I'm trying to unit testing a service that handles the registration of a user in Laravel.</p>
<p>This is the service:</p>
<pre><code>public function completeRegistration(Collection $data)
    {
        $code = $data-&gt;get('code');
        $registerToken = $this-&gt;fetchRegisterToken($code);

        DB::beginTransaction();

        $registerToken-&gt;update(['used_at' =&gt; Carbon::now()]);
        $user = $this-&gt;userRepository-&gt;update($data, $registerToken-&gt;user);
        $token = $user-&gt;createToken(self::DEFAULT_TOKEN_NAME);

        DB::commit();

        return [
            'user' =&gt; $user,
            'token' =&gt; $token-&gt;plainTextToken,
        ];
    }
</code></pre>
<p>Where the <code>update</code> method has the following signature:</p>
<pre><code>&lt;?php

namespace App\Repositories\User;

use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

interface UserRepositoryInterface
{
    public function create(Collection $data): User;
    public function update(Collection $data, User $user): User;
}
</code></pre>
<p>With my test being:</p>
<pre><code>/**
     * Test a user can register
     *
     * @return void
     */
    public function test_user_can_complete_registration()
    {
        $userRepositoryMock = Mockery::mock(UserRepositoryInterface::class);
        $registerTokenRepositoryMock = Mockery::mock(RegisterTokenRepository::class);
        $userFactory = User::factory()-&gt;make();
        $registerTokenFactory = RegisterToken::factory()
            -&gt;for($userFactory)
            -&gt;timestamped()
            -&gt;make(['user_id' =&gt; $userFactory-&gt;id]);

        dd($registerTokenFactory-&gt;user);

        $userRepositoryMock
            -&gt;expects($this-&gt;any())
            -&gt;once()
            -&gt;andReturn($userFactory);

        ....

    }
</code></pre>
<p>When I run <code>phpunit --filter=test_user_can_complete_registration</code> I get the following error:</p>
<pre><code>1) Tests\Unit\Services\Auth\AuthServiceTest::test_user_can_complete_registration
TypeError: Argument 2 passed to Mockery_0_App_Repositories_User_UserRepositoryInterface::update() must be an instance of App\Models\User, null given, called in /var/www/app/Services/Auth/AuthService.php on line 64

/var/www/app/Services/Auth/AuthService.php:64
/var/www/tests/Unit/Services/Auth/AuthServiceTest.php:88

</code></pre>
<p>This tells me that the <code>user</code> relationship on <code>$registerTokenFactory</code> is null. When I do:</p>
<pre><code>public function test_user_can_complete_registration()
{
   ...
   dd($registerTokenFactory-&gt;user);
}

</code></pre>
<p>I get the output <code>null</code>. I'm trying to test the service without hitting the database. How can I attach the <code>user</code> relationship to the <code>$registerTokenFactory</code> object? I have tried using <code>for</code> and trying to attach directly:</p>
<pre><code>$registerTokenFactory = RegisterToken::factory()
            -&gt;for($userFactory)
            -&gt;timestamped()
            -&gt;make(['user_id' =&gt; $userFactory-&gt;id, 'user' =&gt; $userFactory]);
</code></pre>
",https://stackoverflow.com/questions/67081820/factory-relationship-returning-null-laravel-testing,"['php', 'laravel', 'unit-testing', 'phpunit']",920,True,2,1
How to say &quot;both arguments must have the same type&quot; in Java?,"<p>In unit testing, you sometimes want a method like this one:</p>
<pre class=""lang-java prettyprint-override""><code>&lt;V&gt; void checkEq(V expectation, V value) {
  if (!expectation.equals(value))
    throw new IllegalArgumentException(&quot;not equal&quot;);
}
</code></pre>
<p>(assume for a second that we can't use junit for some reason) The idea is that the compiler should ensure both arguments have <em>the</em> <em>same</em> <em>type</em>.
However the compiler doesn't complain about this invocation, where the types obviously differ:</p>
<pre class=""lang-java prettyprint-override""><code>checkEq(1, &quot;&quot;);
</code></pre>
<p>I've tried some variations of this, like <code>checkEq(V expectation, Supplier&lt;V&gt; value)</code> and <code>checkEq(1, () -&gt; &quot;&quot;)</code>. It seems like the compiler is always happy to insert <code>Object</code> for <code>V</code>. Is there some way to tell the compiler not to use the trivial <code>Object</code> solution?</p>
",https://stackoverflow.com/questions/68159529/how-to-say-both-arguments-must-have-the-same-type-in-java,"['java', 'generics', 'type-inference']",213,True,2,3
Testing Dark Mode using snapshot testing,"<p>Any leads how can we use Snapshot testing to test darkmode implementation? Or any other testing strategy for dark mode on iOS.</p>
<p>When XCUITest is one of the options along with XCTest (unit-test). The problem with UITest in dark mode means for every app flow it needs to be run twice.</p>
<p>Will Unittest cases be enough to suffice testing needs for dark mode? Can you think of any use case which won't be covered using only unit testing for dark mode?</p>
",https://stackoverflow.com/questions/67167854/testing-dark-mode-using-snapshot-testing,"['xcuitest', 'ios-darkmode', 'xctestcase', 'darkmode', 'snapshot-testing']",995,True,2,1
Android: unit testing of LiveData and Flow,"<p>I'm trying to write unit testing for my ViewModel but I don't know how to deal with LiveData functions.</p>
<p>Specifically I'm not able to validate all the values that receive the LiveData <code>Observer</code>.</p>
<p>Regarding I have a Flow Use case that emit values and then is pased as a LiveData, what is the best approach to test <code>operation</code> function?</p>
<p>In the code below you can find that I'm only able to read the value <code>&quot;endLoading&quot;</code>, but I want to check all the values: <code>&quot;startLoading&quot;</code>, <code>&quot;Hello Dummy $input&quot;</code>, <code>&quot;endLoading&quot;</code></p>
<p>MainViewModel.kt</p>
<pre><code>class MainViewModel(val useCase: DummyUseCase = DummyUseCase()): ViewModel() {
    fun operation(value: Int): LiveData&lt;String&gt; = useCase.invoke(value)
        .transform { response -&gt;
            emit(response)
        }.onStart {
            emit(&quot;startLoading&quot;)
        }.catch {
            emit(&quot;ERROR&quot;)
        }.onCompletion {
            emit(&quot;endLoading&quot;)
        }.asLiveData(viewModelScope.coroutineContext)
}
</code></pre>
<p>MainViewModelTest.kt</p>
<pre><code>import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.Observer
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test

@ExperimentalCoroutinesApi
class MainViewModelTest {
    //region Setup
    @get:Rule
    val rule = InstantTaskExecutorRule()
    private val testDispatcher = TestCoroutineDispatcher()

    @MockK private lateinit var stateObserver: Observer&lt;String&gt;
    @MockK private lateinit var useCase: DummyUseCase
    private lateinit var viewModel: MainViewModel

    @Before
    fun setup() {
        MockKAnnotations.init(this, relaxUnitFun = true)
        Dispatchers.setMain(testDispatcher)
        viewModel = MainViewModel(useCase)
    }

    @After
    fun teardown() {
        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }
    //endregion

    @Test // AAA testing
    fun `when my flow succeeds, return a state String`() {
        runBlocking {
            //Arrange
            val input = 10
            coEvery { useCase.invoke(input) }.returns(flow {
                emit(&quot;Hello Dummy $input&quot;)
            })

            //Act
            val actual = viewModel.operation(input).apply {
                observeForever(stateObserver)
            }

            //Assert
            // I want to assert here every value received in the observer of the &quot;actual&quot; LiveData
            // How? :(
            assertNotNull(actual.value) // is always &quot;endLoading&quot;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/67169360/android-unit-testing-of-livedata-and-flow,"['kotlin', 'android-livedata', 'android-viewmodel', 'kotlin-coroutines']",1699,True,2,1
Kotlin - TypeReference&lt;T&gt; Cannot obtain Class&lt;*&gt; For Type Arguments,"<p>I've created a Kotlin equivalent of <code>TypeReference&lt;T&gt;</code> like so:</p>
<pre class=""lang-kotlin prettyprint-override""><code>abstract class TypeReference&lt;T&gt; : Comparable&lt;T&gt; {

    val type: Type get() = getGenericType()
    val arguments: List&lt;Type&gt; get() = getTypeArguments()

    final override fun compareTo(other: T): Int {
        return 0
    }

    private fun getGenericType(): Type {
        val superClass = javaClass.genericSuperclass

        check(superClass !is Class&lt;*&gt;) {
            &quot;TypeReference constructed without actual type information.&quot;
        }

        return (superClass as ParameterizedType).actualTypeArguments[0]
    }

    private fun getTypeArguments(): List&lt;Type&gt; {
        val type = getGenericType()
        return if (type is ParameterizedType) {
            type.actualTypeArguments.toList()
        } else emptyList()
    }
}
</code></pre>
<p>In order to obtain <code>Class&lt;*&gt;</code> of the generic type and its arguments, I've also created the following extension function (and this is where I believe the problem lies, since this is where the stack trace fails).</p>
<pre class=""lang-kotlin prettyprint-override""><code>fun Type.toClass(): Class&lt;*&gt; = when (this) {
    is ParameterizedType -&gt; rawType.toClass()
    is Class&lt;*&gt; -&gt; this
    else -&gt; Class.forName(typeName)
}
</code></pre>
<p>I'm unit testing this like so:</p>
<pre class=""lang-kotlin prettyprint-override""><code>@Test
fun `TypeReference should correctly identify the List of BigDecimal type`() {

    // Arrange
    val expected = List::class.java
    val expectedParameter1 = BigDecimal::class.java
    val typeReference = object : TypeReference&lt;List&lt;BigDecimal&gt;&gt;() {}

    // Act
    val actual = typeReference.type.toClass()
    val actualParameter1 = typeReference.arguments[0].toClass()

    // Assert
    assertEquals(expected, actual)
    assertEquals(expectedParameter1, actualParameter1)
}
</code></pre>
<p>The problem I think, lies in the extension function <code>else -&gt; Class.forName(typeName)</code> as it throws:</p>
<blockquote>
<p>java.lang.ClassNotFoundException: ? extends java.math.BigDecimal</p>
</blockquote>
<p>Is there a better way to obtain the <code>Class&lt;*&gt;</code> of a <code>Type</code>, even when they're generic type parameters?</p>
",https://stackoverflow.com/questions/66505467/kotlin-typereferencet-cannot-obtain-class-for-type-arguments,['kotlin'],491,True,2,2
GetManifestResourceStream doesn&#39;t work in azure pipeline,"<p>In the process of unit testing,I tried to read a SQL file which I marked as embedded resource. It works fine in local. But when the unit test runs in the DevOps pipeline, I am getting ArgumentNullexpetion for the stream reader which uses the output of 'GetManifestResourceStream'
I tried write in console the list of 'GetManifestResourceNames' it lists all SQL files correctly.</p>
<pre><code>var assembly=Assembly.GetExecutingAssembly();
var filename=MethodBase.GetCurrentMethod().Declaring type.Namesapce+folder name+filename;
var stream= assembly.GetManifestResourceStream(filename);//returns null in pipeline but works perfectly in local.
var reader=new StreamReader(stream)
reader.ReadToEnd()// exception thrown
</code></pre>
<p>The code is placed in MSTest project and called in the ClassInitialize method. How to fix this pipeline exception</p>
",https://stackoverflow.com/questions/66482292/getmanifestresourcestream-doesnt-work-in-azure-pipeline,"['c#', '.net-core', 'azure-devops', 'mstest', 'embedded-resource']",263,False,2,0
&quot;Missing region in config&quot; after attempting to mock SecretsManager with Jest,"<p>I'm currently attempting to mock AWS SecretsManager for my unit testing with Jest, and everytime I'm hit with the <code>ConfigError</code>
My code is somewhat like this</p>
<pre><code>//index.ts
import SM from &quot;aws-sdk/clients/secretsmanager&quot;
const secretManagerClient = new SM()
...
export const randomMethod = async (a: string, b: string) =&gt; {
  let secret
  const personalToken = {
    SecretId: process.env.secretId,
  }
  secretManagerClient
    .getSecretValue(personalToken, (err, data) =&gt; {
      if (err) {
        console.error(`[SECRETS MANAGER] Error fetching personal token : ${err}`)
      } else if (data &amp;&amp; data.SecretString) {
        secret = data.SecretString
      }
    })
}
</code></pre>
<p>My mock goes like this :</p>
<pre class=""lang-js prettyprint-override""><code>//index.test.js
const mockGetSecretValue = jest.fn((SecretId) =&gt; {
  switch (SecretId) {
    case process.env.GITHUB_PERSONAL_TOKEN:
      return {
        SecretString: process.env.GITHUB_PERSONAL_TOKEN_VALUE,
      }
    default:
      throw Error(&quot;secret not found&quot;)
  }
})

jest.mock(&quot;aws-sdk/clients/secretsmanager&quot;, () =&gt; {
  return jest.fn(() =&gt; {
    return {
      getSecretValue: jest.fn(({ SecretId }) =&gt; {
        return mockGetSecretValue(SecretId)
      }),
      promise: jest.fn(),
    }
  })
})
</code></pre>
<p>However, I get this error thrown at me : <code>ConfigError: Missing region in config</code>, which I understand to some extent, however I don't understand why it occurs here in the mocking part...</p>
<p>Thanks in advance!</p>
<p>EDIT: Thanks to the 1st answer, I've managed to stop having this error. However, the <code>getSecretValue()</code> method is not returning the Secret value I want.</p>
",https://stackoverflow.com/questions/69977310/missing-region-in-config-after-attempting-to-mock-secretsmanager-with-jest,"['node.js', 'unit-testing', 'jestjs', 'mocking', 'aws-sdk']",3596,False,1,2
How to write a unit test case for below scenario in Angular Jasmine?,"<p>main.service.ts</p>
<pre><code>    public validateUser (serviceCall : any, data: object, callback: Function ){
      this.httpclient.post&lt;any&gt;(serviceCall , data).toPromise().then((res) =&gt; {
      callback(res, null);
    }).catch((err)=&gt;{
      callback(null,res);
    });

</code></pre>
<p>main.component.ts</p>
<pre><code>    ngOnInit() {
      this.userDetails = new UserDetails();
      this.userDetails.userName = &quot;&lt;userName&gt;&quot;;
      this.userDetails.userPwd= &quot;&lt;userPwd&gt;&quot;;

      this.mainService.vaidateUser(this.serviceUtil.REST_API_URL, this.userDetails, 
      this._processResponse.bind(this));

    }

    _processResponse(res: any, err: null ) {
    if (err == null &amp;&amp; res != null ) {
       this.isLoginSuccessFull = res.response;
    } else {
      this.isLoginSuccessFull = false;
    }
</code></pre>
<p>main.component.spec.ts</p>
<p>What I am trying to do is as below :</p>
<pre><code>    it(&quot;should hit API and get success response &quot;, () =&gt; {
     this.userDetailsMock.userName = &quot;&lt;userName&gt;&quot;;
     this.userDetailsMock.userPwd  = &quot;&lt;userPwd&gt;&quot;;

     let bindedFunction = spyOn(component_processResponse as CallbackFunction, &quot;bind&quot;);
     this.mainService.validateUser(this.serviceUtil.REST_API_URL, this.userDetailsMock, bindedFunction);
      let res = this.httpMock.expectOne({
        'url' : this.serviceUtil.REST_API_URL,
         'method' : &quot;POST&quot;
      });
     res.flush(result);
      expect(component.isLoginSuccessFull).toBeEqual(result);
     }
    });
</code></pre>
<p>But this does not seems to working and I'm thinking I'm way away from solutions. I'm pretty new in unit testing module in jasmine - angular. Gow can I write a unit test case for this scenario?</p>
<p>In my component while making service call via main.service file, I'm passing <code>_processResponse</code> function with current component context. I service after getting response from backend API, I'm checking calling this function (callBack(res, err)).</p>
",https://stackoverflow.com/questions/66471682/how-to-write-a-unit-test-case-for-below-scenario-in-angular-jasmine,"['angular', 'typescript', 'unit-testing', 'jasmine']",84,False,1,0
bazel test lacking SEGFAULT information,"<p>We are currently migrating from a CMake-based build to bazel. For unit-testing, we are using our own implemented framework.</p>
<p>When dealing with a <code>SEGFAULT</code>, <code>ctest</code> gives the following output:</p>
<pre><code>The following tests FAILED:
    19 - SomeTest (SEGFAULT)
Errors while running CTest
</code></pre>
<p>However, when executing the exact same test with the exact same build-options and sources, the <code>bazel</code> output looks like:</p>
<pre><code>//services/SomeTest:test                                                FAILED in 0.2s
  /root/.cache/bazel/_bazel_root/b343aed36e4de4757a8e698762574e37/execroot/repo/bazel-out/k8-fastbuild/testlogs/SomeTest/test/test.log
</code></pre>
<p>The other output is just the regular printout from the test, nothing regarding the <code>SEGFAULT</code>. Same goes for the contents of <code>SomeTest/test/test.log</code>.</p>
<p>I tried the following options to <code>bazel test</code>: <code>--test_output=all</code>, <code>--test_output=errors</code>, <code>--verbose_test_summary</code>, and <code>--verbose_failures</code>.</p>
<p>What am I missing here?</p>
",https://stackoverflow.com/questions/70184514/bazel-test-lacking-segfault-information,"['unit-testing', 'bazel']",430,True,1,1
Unable to add resources using a Flask Application Factory and Flask-Restful,"<p>I'm writing in a bit of desperation. I have an application that uses Flask, Flask Restful, JWT, Flask SQLAlchemy.</p>
<p>It's a personal project which is quite large and is suffering from lack of unit testing - so I've been adding unit testing using pytest and tox.</p>
<p>I realized that to do this properly, I needed to move from the</p>
<pre><code>from flask import Flask
app = Flask(__name__)
</code></pre>
<p>to using an application factory so I can setup different environments easily. I am completely stuck and feeling more than a little stupid. To get help and show the issue, I have stripped things down to this:</p>
<p>The 'old' way:</p>
<pre><code>resources/talk.py:

from flask_restful import Resource

class Talk(Resource):
    def get(self):
        return { 'msg' : 'Talking' }

app.py:

from flask import Flask
from flask_restful import Api
from resources.talk import Talk

app = Flask(__name__)
api = Api(app)

api.add_resource(Talk, '/talk')

if __name__ == &quot;__main__&quot;:
    app.run(debug=True)

</code></pre>
<p>If I run this and go to http://localhost:5000/talk I get the  { 'msg' : 'Talking' } response.</p>
<p>However, I cannot get it to work using an application factory.</p>
<p>I have looked at the docs from Flask, which are here: <a href=""https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/#"" rel=""nofollow noreferrer"">https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/#</a></p>
<p>And it makes sense. However, I can't get the url to work.</p>
<pre><code>app_factory.py:

from flask import Flask
from flask_restful import Api

api = Api()

def create_app():
    app = Flask(__name__)    
    api.init_app(app)
    
    from resources.talk import Talk

    api.add_resource(Talk, '/talk')

    return app

run.py:

from app_factory import create_app
app = create_app()

</code></pre>
<p><strong>127.0.0.1 - - [09/Jan/2021 22:07:09] &quot;GET /talk HTTP/1.1&quot; 404</strong></p>
<p>I also tried using</p>
<pre><code>
def create_app():
    app = Flask(__name__)    
    api.init_app(app)
    
    from resources.talk import Talk
    with app.app_context():
        api.add_resource(Talk, '/talk')

    return app
</code></pre>
<p>but realized I'm just guessing and not understanding.</p>
<p>Does anyone have any pointers on how to set this up correctly? If I can' get this working then the JWT, database and other things stand no chance!</p>
<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/65647670/unable-to-add-resources-using-a-flask-application-factory-and-flask-restful,"['python', 'flask', 'flask-restful']",334,True,2,1
Writing a unit test for an if else statement,"<p>I am new to unit testing and fairly new to c# and would really appreciate some help with how to write a unit test to ensure the logic in the AddGrade method is working. So basically if the grade is &gt;=0 and &lt;=100 then the grade is valid and it will be added, anything else isn't and it should display an error in the console.</p>
<p>I have seen another post about unit testing an if-else statement in c# and tried working this out from that but It confused me if I am honest. I have looked around online etc and tried a lot of different things to try and figure this out but I find it hard sometimes to apply peoples example to my code so I thought it best just to post my code and get some help, any help would be greatly appreciated :)</p>
<p>I am using Xunit for the unit tests. This project runs in the console.</p>
<p>This is the program class with the main method</p>
<pre><code>    using System;
using System.Collections.Generic;

namespace GradeBook
{
    class Program
    {
        static void Main(string[] args)
        {
            var book = new Book(&quot;Dave's&quot;);

            //add grade to the book
            book.AddGrade(90.5);
            book.AddGrade(80.5);
            book.AddGrade(70.5);
            book.AddGrade(60.5);

            var stats = book.GetStatistics();
            Console.WriteLine($&quot;This Gradebooks name is {book.Name}&quot;);
            Console.WriteLine($&quot;The highest grade is {stats.High:N1}&quot;);
            Console.WriteLine($&quot;The lowest grade is {stats.Low:N1}&quot;);
            Console.WriteLine($&quot;The average grade is {stats.Average:N1}&quot;);//N1,N2 etc. is number of decimal places
        }
    }
}
</code></pre>
<p>This is the book class where the AddGrade method is I want to write the unit test for</p>
<pre><code>    using System;
using System.Collections.Generic;

namespace GradeBook
{
    public class Book
    {
        public Book(string name)
        {
            grades = new List&lt;double&gt;();
            Name = name;
        }

        public void AddGrade(double grade)
        {
            if (grade &gt;= 0 &amp;&amp; grade &lt;= 100)
            {
                grades.Add(grade);               
            }
            else
            {
                Console.WriteLine(&quot;Please enter a value between 0 and 100&quot;);
            }
        }

        public Statistics GetStatistics()
        {
            var result = new Statistics();
            result.Average = 0.0;
            result.High = double.MinValue;
            result.Low = double.MaxValue;
            

            foreach (var grade in grades)
            {
                Console.WriteLine($&quot;{Name} grade is: {grade}&quot;);
                result.Low = Math.Min(grade, result.Low);
                result.High = Math.Max(grade, result.High);
                result.Average += grade;
                
                
            }
            result.Average /= grades.Count;
            return result;           
        }

        private List&lt;double&gt; grades = new List&lt;double&gt;() { };
        public string Name;
    }
}
</code></pre>
<p>This is the Statistics class</p>
<pre><code>    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GradeBook
{
    public class Statistics
    {
        public double Average;
        public double High;
        public double Low;
    }
}
</code></pre>
<p>This is where I am writing the unit test for this</p>
<pre><code>    using System;
    using System.Collections.Generic;
    using Xunit;
    
    namespace GradeBook.Tests
    {
        public class BookTests
        {
            [Fact]
            public void BookGradeIsValid()
            {
                var book = new Book(&quot;&quot;);           
                book.AddGrade(105);
            }
        }
    }
</code></pre>
",https://stackoverflow.com/questions/66545245/writing-a-unit-test-for-an-if-else-statement,"['c#', 'unit-testing', 'if-statement', 'xunit.net']",2192,True,2,1
Why my PhpStorm does not have needed interface for PHPUnit tests?,"<p>I'm watching a video about Unit-testing. An author of that video uses very convenient interface of PhpStorm that shows details of testing.</p>
<p><a href=""https://i.stack.imgur.com/PcXtO.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/PcXtO.jpg"" alt=""enter image description here"" /></a></p>
<p>But I don't have this. I have a simple, not pleasant interface))</p>
<p><a href=""https://i.stack.imgur.com/wJxfU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wJxfU.png"" alt=""enter image description here"" /></a></p>
<p>The year of the video is 2015. My version of PhpStorm - 2018.3 (I think it's much newer)</p>
<p>Why should I do to make interface of my PhpStorm like on the first picture? Do I need to install some plugin?</p>
<p>If it helps: I use it with Yii2.</p>
",https://stackoverflow.com/questions/67369981/why-my-phpstorm-does-not-have-needed-interface-for-phpunit-tests,"['php', 'phpunit', 'phpstorm']",97,True,1,1
Unit testing Flask application API endpoints,"<p>I have a Flask application and my routes are divided into Blueprints. I want to test my endpoints.</p>
<p>Is unit testing a single method enough for testing an endpoint? I guess not. Because my endpoints perform operations inside LXC container and then update DB and finally return JSON response. If I want to test if the functionality executed as expected, would it be called e2e test for an endpoint? If yes, should I only test the returned response in unit tests of methods?</p>
",https://stackoverflow.com/questions/66581352/unit-testing-flask-application-api-endpoints,"['python-3.x', 'unit-testing', 'flask', 'testing', 'pytest']",63,False,1,0
How to unit test - zipping a file,"<p>I wrote a simple method that takes in a path to a folder, zips all the content inside that folder, and saves it to a specified destination path.</p>
<pre><code>void zipFiles(string sourcePath, string destinationPath, string nameToZipAs)
    {
        try
        {
            // This is where the zip file will be saved.
            string fullDestinationPath = $&quot;{destinationPath}\\{nameToZipAs}&quot;;
            ZipFile.CreateFromDirectory(sourcePath, fullDestinationPath);
        }

        catch (Exception e)
        {
            // ...
        }
}        
</code></pre>
<p>I was wondering how I would go about unit testing this. I read that a unit test shouldn't touch the file system. Is that correct good practice? If so, then I can't create a folder (programmatically) in the unit test in order to zip that folder with my method to verify it works.</p>
",https://stackoverflow.com/questions/68231240/how-to-unit-test-zipping-a-file,"['c#', 'unit-testing']",1234,True,1,1
nodejs: How to store multiple events of same name for unit test,"<p>For unit testing (with mocha) I would like to setup some sort of asynchronous queue for events.</p>
<p>Until now I have setup a once() Promise to wait for events:</p>
<pre><code>import EventEmitter from 'events'
import { once } from 'events'
import { strict as assert } from 'assert'

describe('tests', function () {
    const emitter = new EventEmitter()

    it('testcase-1', async function () {
        const ecmConfigurationPromise1 = once(emitter, 'event')
        setTimeout(() =&gt; {
            emitter.emit('event', { a: 1 })
        })
        assert.equal((await ecmConfigurationPromise1)[0].a, 1)
    })
})
</code></pre>
<p>(<code>setTimeout(...)</code> represent triggering my application)</p>
<p>However now I need to be able to capture multiple events with the same name, and would like to follow the same pattern of awaiting for them. My idea was to store the events on some async queue (XXX below), but I cannot find any such thing.</p>
<pre><code>import EventEmitter from 'events'
import { strict as assert } from 'assert'

describe('tests', function () {
    const emitter = new EventEmitter()

    it('testcase-2', async function () {
        emitter.on('event', (msg) =&gt; XXX.push(msg))
        setTimeout(() =&gt; {
            emitter.emit('event', { a: 1 })
            emitter.emit('event', { a: 2 })
        })
        assert.equal((await XXX)[0].a, 1)
        assert.equal((await XXX)[0].a, 2)
        // nice to have:
        assert.equal(XXX.length(), 0)
    })
})
</code></pre>
<p>Any ideas?</p>
",https://stackoverflow.com/questions/67369494/nodejs-how-to-store-multiple-events-of-same-name-for-unit-test,"['javascript', 'node.js', 'typescript', 'mocha.js']",132,False,0,1
Spring Boot unit testing assertion error JSON object got a JSON array,"<p>I am unit testing in a spring boot application. But as the getProductById() method returns Optional of the object, I am not sure how to test it.</p>
<p><strong>ProductController.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>@GetMapping(&quot;/products/{id}&quot;)
@Transactional(readOnly=true)
@Cacheable(&quot;product-cache&quot;)
public Product getProduct(@PathVariable(&quot;id&quot;) int id) {
        LOGGER.info(&quot;Finding product by id : &quot;+id);
        return productRepository.findById(id).get();
}
</code></pre>
<p><strong>MockTest.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>private static final String PRODUCTS_URL = &quot;/productsapi/products&quot;;
private static final int PRODUCT_ID = 1;
private static final String CONTEXT_URL = &quot;/productsapi&quot;;
private static final int PRODUCT_PRICE = 1000;
private static final String PRODUCT_DESCRIPTION = &quot;Its awesome&quot;;
private static final String PRODUCT_NAME = &quot;Macbook&quot;;

@Test
public void testGetProductById() throws JsonProcessingException, Exception {
        Product product = buildProduct();
        when(productRepository.findById(PRODUCT_ID)).thenReturn(Optional.of(product));
        
        ObjectWriter objectWriter = new ObjectMapper().writer().withDefaultPrettyPrinter();
        mockMvc.perform(get(PRODUCTS_URL).contextPath(CONTEXT_URL))
           .andExpect(status().isOk())
           .andExpect(content().json(objectWriter.writeValueAsString(Optional.of(product))));
}

private Product buildProduct() {
        Product product = new Product();
        product.setId(PRODUCT_ID);
        product.setName(PRODUCT_NAME);
        product.setDescription(PRODUCT_DESCRIPTION);
        product.setPrice(PRODUCT_PRICE);
        return product;
}
</code></pre>
<p>When I run the test, it fails with below error.</p>
<p><strong>Error:</strong>
java.lang.AssertionError:
Expected: a JSON object
got: a JSON array</p>
<p>It doesn't show any compilation error. But test case fails. I think it's the problem with conversion of product object into json.</p>
<p>So, little help in resolving this will be helpful!!</p>
",https://stackoverflow.com/questions/67405278/spring-boot-unit-testing-assertion-error-json-object-got-a-json-array,"['java', 'spring-boot', 'unit-testing', 'junit', 'option-type']",1220,True,0,1
How to unit test a component to check a particular component is rendered or not,"<p>I've a very simple custom component. I call it <code>NavbarComponent</code> and the selector is <code>app-navbar</code>. It is a very basic static navbar. I'm rendering it on <code>app.component.html</code>:</p>
<p><strong>app.component.html</strong></p>
<pre><code>&lt;app-navbar&gt;&lt;/app-navbar&gt;
&lt;router-outlet&gt;&lt;/router-outlet&gt;
</code></pre>
<p>I'm writing a unit test case like this:
<strong>app.component.spec.ts</strong></p>
<pre><code>import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';

fdescribe('AppComponent', () =&gt; {
  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent,
        NavbarComponent
      ],
    }).compileComponents();
  }));

  it('should create the app', () =&gt; {
    ...
  });

  it(`should have as title 'my-app'`, () =&gt; {
    ...
  });

  fit('should display navbar', () =&gt; {
    const fixture=TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled=fixture.debugElement.nativeElement;
    expect(compiled.querySelector('app-navbar')).toBeDefined();
  })
});
</code></pre>
<p>It's not working properly. The test is passed eve If i remove <code>&lt;app-navbar&gt;&lt;/app-navbar&gt;</code> from the template. I've just started with Unit testing few days ago. Please correct my mistake.</p>
<p>2 things I would like to mention:</p>
<ol>
<li>I don't have any css (as of now).</li>
<li>No *ngIf condition so <code>NavbarComponent</code> should be rendered all the time.</li>
</ol>
",https://stackoverflow.com/questions/65551246/how-to-unit-test-a-component-to-check-a-particular-component-is-rendered-or-not,"['angular', 'jasmine', 'karma-jasmine']",1500,True,3,1
Missing c/c++ unit testing support in eclipse?,"<p>I am using the <em>Eclipse IDE for C/C++ Developers</em> (2021-03) package and cannot find the entry &quot;C/C++
Unit Testing Support&quot; under &quot;Help &gt; Install New Software&quot;.</p>
<p>I need it for using gtest with a C++ project but the installation entry in the software menu (within Programming Languages) does not exist anymore. Previous versions appeared to have it available. I followed this guide: <a href=""https://www.pbma.de/docpt/content/951f7999aa405c4c016c1cda35f564d08ae7c71bf867722ad896d11c21e3be51"" rel=""nofollow noreferrer"">https://www.pbma.de/docpt/content/951f7999aa405c4c016c1cda35f564d08ae7c71bf867722ad896d11c21e3be51</a></p>
<p>Is it removed from there or how can I install it?</p>
",https://stackoverflow.com/questions/66903457/missing-c-c-unit-testing-support-in-eclipse,"['eclipse', 'unit-testing']",136,True,0,1
How can i write UnitTest for my Flask API,"<p>I'm fairly new to unit testing, and im required to write some unit test for my flask api. Any idea how I can write unit tests for this code below? Any examples and help will be appreciated.
I tried to create a seperate file to start unittesting but im not able to import the flask app into the file as it gives me module errors. And ontop of that im not sure how to test each function in this application.</p>
<pre><code>from flask import Flask, request, Response, send_file
import machine_learning_model.Object_detection.yoloModel as yoloModel
import jsonpickle
import numpy as np
import cv2
import base64
import json
import ast
import requests
app = Flask(__name__)


url_base = 'http://192.168.1.6:5000'
predict_image_api = '/v1/api/predict'
bounding_box_API = '/v1/resoures/predict_images/'


# Load YOLO model
labels, colors = yoloModel.load_label(&quot;coco.names&quot;)
net, ln = yoloModel.load_model()


# route http posts to this method
@app.route(predict_image_api, methods=['GET', 'POST'])
def predict():
    loaded_body = parse_json_from_request(request)
    
    # Conversion of base64 image back to its binary
    img_original = base64.b64decode(loaded_body['image'])

    # Conversion of image data to unit8
    jpg_as_np = np.frombuffer(img_original, dtype=np.uint8)
    
    # Decoding the image
    image = cv2.imdecode(jpg_as_np, cv2.IMREAD_COLOR)

    idxs, boxes, confiences, centers, classIDs = yoloModel.detectObjectFromImage(image, net, ln)

    objectProperty = yoloModel.bouding_box(idxs, image, boxes, colors, labels, classIDs, confiences)

    response = {
        'objectProperty':''
    }
    response['objectProperty'] = objectProperty
    print(response)
    # encode response using jsonpickle
    response_pickled = jsonpickle.encode(response)



    return Response(response=response_pickled, status=200, mimetype=&quot;application/json&quot;)

@app.route(bounding_box_API+'&lt;name&gt;', methods=['GET'])
def get_image(name):
    filename = 'predict_images/output_resize_%s.jpg' % name
    print(filename)
    return send_file(filename, mimetype='image/gif')


def parse_json_from_request(request):
    body_dict = request.json
    body_str = json.dumps(body_dict)
    loaded_body = ast.literal_eval(body_str)
    return loaded_body

if __name__ == &quot;__main__&quot;:
    # start flask app
    app.run()
</code></pre>
",https://stackoverflow.com/questions/67438113/how-can-i-write-unittest-for-my-flask-api,"['python', 'unit-testing', 'flask']",800,True,-1,1
Unit test for post sling servlet aem 6.5,"<p>I have the following POST servlet that adds new node under certain resource with parameters(name and last nam) from the request:</p>
<pre><code>@Component(
        service = Servlet.class,
        property = {
                &quot;sling.servlet.paths=/bin/createuser&quot;,
                &quot;sling.servlet.methods=&quot; + HttpConstants.METHOD_POST
        })
public class CreateNodeServlet extends SlingAllMethodsServlet {

    /**
     * Logger
     */
    private static final Logger log = LoggerFactory.getLogger(CreateNodeServlet.class);

    @Override
    protected void doPost(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws IOException {
        log.info(&quot;Inside CreateNodeServlet&quot;);
        ResourceResolver resourceResolver = req.getResourceResolver();
        final Resource resource = resourceResolver.getResource(&quot;/content/test/us/en&quot;);
        String name = req.getParameter(&quot;name&quot;);
        String lastname = req.getParameter(&quot;lastname&quot;);
        log.info(&quot;name :{}&quot;,name);
        log.info(&quot;lastname :{}&quot;,lastname);

        Node node = resource.adaptTo(Node.class);
        try {
            log.info(&quot;Node {}&quot;, node.getName() );

            Node newNode = node.addNode(name+lastname, &quot;nt:unstructured&quot;);
            newNode.setProperty(&quot;name&quot;, name);
            newNode.setProperty(&quot;lastname&quot;, lastname);

            resourceResolver.commit();
        } catch (RepositoryException e) {
            e.printStackTrace();
        } catch (PersistenceException e) {
            e.printStackTrace();
        }
        resp.setStatus(200);
        resp.getWriter().write(&quot;Simple Post Test&quot;);
    }
}
</code></pre>
<p>I tried creating unit test for this I got this so far:</p>
<pre><code>@ExtendWith(AemContextExtension.class)
class CreateNodeServletTest {

    private final AemContext context = new AemContext();

    private CreateNodeServlet createNodeServlet = new CreateNodeServlet();

    @Test
    void doPost() throws IOException, JSONException {

        context.currentPage(context.pageManager().getPage(&quot;/bin/createuser&quot;));
        context.currentResource(context.resourceResolver().getResource(&quot;/bin/createuser&quot;));
        context.requestPathInfo().setResourcePath(&quot;/bin/createuser&quot;);

        MockSlingHttpServletRequest request = context.request();
        MockSlingHttpServletResponse response = context.response();

        createNodeServlet.doPost(request, response);
        JSONArray output = new JSONArray(context.response().getOutputAsString());

        assertEquals(&quot;Simple Post Test&quot;, output);
    }
}
</code></pre>
<p>however this is not working I am getting null pointer on this line</p>
<pre><code> Node node = resource.adaptTo(Node.class);
</code></pre>
<p>can some one help what I am missing and some tips will be of great help as I am new to AEM, and there is not much resources about unit testing sling servlets ?</p>
",https://stackoverflow.com/questions/67093125/unit-test-for-post-sling-servlet-aem-6-5,"['servlets', 'aem', 'sling', 'sling-models']",585,False,0,1
"in the github enterprise UI, is there a way to see commit statuses outside of the PR context?","<p>As part of our CI plans, dev branch commits will have statuses applied to them based on build/unit testing/etc.  Once a PR is opened to merge the dev branch to the product branch, those statuses will be visible and can be used as part of branch protection for the product branch.  However, is there anywhere in the UI where you can look at a particular commit directly, and view the statuses, or is it only through the lens of the PR?</p>
",https://stackoverflow.com/questions/66441875/in-the-github-enterprise-ui-is-there-a-way-to-see-commit-statuses-outside-of-th,['github-enterprise'],120,True,0,1
"Node.js axios unit testing using Mocha, sinon and chai","<p>I have node.js component name controller.js which have a function that calls api service using axios with options and it also have catch function for error handling. I am not able to stub axios function so as to cover it by unit testing.</p>
<p>Below is controller.js component.</p>
<pre><code>const axios = require('axios');
export.getData = function(req, res, next) {
  try {
     const options = {
            method: 'GET',
            headers: headers,
            url,
            params: queryParams
     };  
     axios(options).then(function (response) {
            res.json(response.data);
        })
            .catch(function (error) {
                if (error &amp;&amp; error.response) {
                    if (error.response.status === 401) {
                        res.status(500).send({ error: true, message: 'There seems to be an issue, please try after sometime' });                   
                    }
                 }
             });
  }
}
</code></pre>
<p>below is my controller.test.js</p>
<pre><code>const chai = require('chai');
const assert = chai.assert;
const axios = require('axios');
const sinon = require('sinon');
const controller = require('../controllersr');

describe(&quot;controller API testing&quot;, () =&gt; {

it(&quot;should call getMarketId function and return status 200 on success&quot;, function (done) {
        const req = { };
        const res =  { json: {greet: &quot;hello&quot;}, status: 200};
        var mockStub = sinon.stub(axios, 'get').resolves(res);
        controller.getData(req, res);
        assert.equal(res.status, 200);
        mockStub.restore();
        done();
    });

});
</code></pre>
<p>Here, I am not able to stub axios funtion and catch function for error handling.
And thus unable to cover the code for axios success and catch function in NYC.
Please help..</p>
",https://stackoverflow.com/questions/68451221/node-js-axios-unit-testing-using-mocha-sinon-and-chai,"['node.js', 'unit-testing', 'axios', 'mocha.js', 'sinon']",3164,True,0,1
Unity Moq not found,"<p>My Unity project contains the Moq dll, which we use for unit testing. I'm upgrading the project from Unity 2018 to 2019, and when I performed the upgrade it randomly decided Moq doesn't exist anymore. Moq is still inside the Assets folder (specifically in Assets/Plugins/dlls) and the version is defined in packages.config.</p>
<p>I've deleted and re-added, re-imported, and reloaded Unity multiple times to no avail. Does anyone have insight on why Unity just decided Moq doesn't exist anymore?</p>
",https://stackoverflow.com/questions/66432091/unity-moq-not-found,"['c#', 'unity-game-engine', 'dll', 'moq']",275,False,0,1
Angular: TestCase For Custom Pipe,"<p>I am new in Unit testing and i need help in writing TestCase for Sort Pipe in karma. My Custom Sorting Pipe is calling Methods Based on DirectionValue,In which the logic for sorting are.</p>
<pre><code>@Pipe({
  name: 'sortBy'
})
export class SortByPipe implements PipeTransform {
transform(value[], direction:string){

    if (direction === 'desc'){
      this.descendingSort(value);
    }
    else if(direction === 'asc'){
      this.ascendingSort(value);
    }
    return value;
  }      
</code></pre>
<p>First Case: want to check If it's Calling right Method based on direction value or not.</p>
<p>Second Case: check the result of sort.</p>
<p>I tried to write for something like this for second case.</p>
<pre><code>    const direction = 'asc';
    const pipe = new SortByPipe();
    const result = pipe.transform([4,3,2,1], direction);
    expect(result).toBe([1,2,3,4]);
</code></pre>
<p>Please Help me understand How i can Solve it.
Thanks in Advance</p>
",https://stackoverflow.com/questions/67092201/angular-testcase-for-custom-pipe,"['angular', 'karma-jasmine', 'angular-unit-test']",945,True,0,2
Spyon with returnValue() execute original function but no desired value,"<p>Hello devs i have been doing some tutorials for unit testing but i have a problem trying to do UT to a http call example when i do the test to the function inside my component it returns the original value of the function but no the value that i want it to return doing spyOn(x,x).and.returnValue(X) somebody could help me?</p>
<p>this is my component</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { environment } from '../../../environments/environment';

@Component({
 selector: 'app-root',
 templateUrl: './entrega.component.html',
 styleUrls: ['./entrega.component.css']
})
export class EntregaComponent implements OnInit {
 idEntrega:any='';
 foto:any='';
 urlCasillero='';
 constructor(private route: ActivatedRoute) { }

 ngOnInit() {
  
   this.urlCasillero=environment.URLCASILLERO;
   this.idEntrega = this.route.snapshot.params.id;
 }


 peticionFoto(data:string):string{
   let foto:string='';
   
     fetch(this.urlCasillero+this.idEntrega).then(res =&gt; res.text()).then((text:string) =&gt; {
       this.foto=text;
   })
   
 return foto;
 }


}

</code></pre>
<p>this is my .specs file</p>
<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing'; 


import { EntregaComponent } from './entrega.component';

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


  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [ EntregaComponent ],
      imports: [ RouterTestingModule  ],
    })
    .compileComponents();
  });

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

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


  it('debe obtener una foto', () =&gt; {
    spyOn(component,&quot;peticionFoto&quot;).and.returnValue(
      &quot;foto&quot;
    );
      expect(component.foto).toBe('foto');
    });

    
 
});

</code></pre>
<p>and this is my jasmine result for ng Test</p>
<pre><code>
EntregaComponent &gt; debe obtener una foto

Expected '' to be 'foto'.

Error: Expected '' to be 'foto'.
    at &lt;Jasmine&gt;
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/webpack:/src/app/pages/entrega/entrega.component.spec.ts:36:30)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone.js:372:1)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/fesm2015/zone-testing.js:287:1)
</code></pre>
",https://stackoverflow.com/questions/70490652/spyon-with-returnvalue-execute-original-function-but-no-desired-value,"['angular', 'unit-testing', 'jasmine', 'karma-runner']",997,False,0,1
How to set a private variable value without a setter?,"<p>I am currently doing a unit testing assignment.
Within the project I have a Bank Account Class and a UnitTesting class.
Within the BankAccount class we have a variable
<code>private double balance { get; }</code></p>
<p>With a variable of private  type and only get, how do I update the balance once I've done through a class function of withdrawing cash for example.</p>
<pre><code>public double Debit (double amount)
        /*Ensuring Debit Amount is Valid and Balance Available for Transaction*/
        {
            IsAmountVerified(amount);     
            if (IsAmountVerified(amount) is false) { throw new ArgumentOutOfRangeException(&quot;&quot;,WRONG_AMOUNT); }
            if (balance &lt; amount) { throw new ArgumentOutOfRangeException(&quot;&quot;,INSUFFICIENT_BALANCE); }
            else **balance -= amount**;
        /*Return Value*/
            return amount;
        }
</code></pre>
<p>How do I update the balance? Also making this variable private I cannot access it within the UnitTesting Class.</p>
<pre><code> [TestMethod]
        public void DepositTest1()
        {
            BankAccount Account = new BankAccount(100, &quot;Baldip Singh&quot;);
            Account.Deposit(1);
            Assert.AreEqual(101, Account.balance);
        }
</code></pre>
<p>Thanks for any insight, cheers.</p>
",https://stackoverflow.com/questions/68960520/how-to-set-a-private-variable-value-without-a-setter,"['c#', 'visual-studio', 'unit-testing', 'access-modifiers']",478,True,0,3
Unit test of Vue Formulate not seeing errors,"<p>I am getting started with unit testing components in Vue using Jest and Vue-Test-Utils.  I am using <a href=""https://vueformulate.com/"" rel=""nofollow noreferrer"">Vue Formulate</a> to manage form fields, which works as expected in the browser.  I am importing the plugin in a 'local Vue' testing instance as per the documentation.</p>
<p>However, the following assertion fails as text not found in testing, whilst it works in the browser.  What am I doing wrong?  I have tried a variety of selectors including <code>wrapper.text()</code> without success</p>
<p><strong>Component:</strong></p>
<pre><code>&lt;template&gt;
&lt;div class=&quot;card&quot;&gt;
    &lt;FormulateForm v-model=&quot;formValues&quot;&gt;
        &lt;FormulateInput type=&quot;text&quot; label=&quot;Full Name&quot; name=&quot;name&quot; validation=&quot;required&quot;/&gt;
    &lt;/FormulateForm&gt;
&lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
name: &quot;RegistrationFormComponent&quot;,

data: function(){
    return {
        'formValues' : {},
    }
}
&lt;/script&gt;
</code></pre>
<p><strong>Test</strong></p>
<pre><code>import { mount, createLocalVue } from '@vue/test-utils';
import VueFormulate from '@braid/vue-formulate';
import registrationForm from '../../resources/js/components/RegistrationFormComponent'

test('name field is required', async () =&gt; {
    const localVue = createLocalVue();
    localVue.use(VueFormulate);
    let wrapper = mount(registrationForm,{localVue});

    let form = wrapper.find('form');
    let field = form.find('input[name=name]');

    await field.setValue('');
    expect(wrapper.find('.formulate-input-error').text()).toContain('Name is required');
})
</code></pre>
<p><strong>Jest Output:</strong></p>
<pre><code> FAIL  tests/Vue/registrationForm.test.js
  ● email must be a valid email address

    [vue-test-utils]: find did not return .formulate-input-error, cannot call text() on empty Wrapper

      12 | 
      13 |     await field.setValue('Dog');
    &gt; 14 |     expect(wrapper.find('.formulate-input-error').text()).toContain('a valid email');
         |                                                   ^
      15 | })
</code></pre>
",https://stackoverflow.com/questions/65652838/unit-test-of-vue-formulate-not-seeing-errors,"['vue.js', 'vue-test-utils', 'vue-formulate']",694,True,0,1
Event not changing the state of the label react-testing-library,"<p>Sorry i'm new to unit testing and i'm stuck on this.</p>
<p>I'm just testing the onClick of a &quot;Show more&quot; button.</p>
<blockquote>
<p>Total size = 16 items, Page size = 15 items</p>
</blockquote>
<p>so if I clicked the button, it should add 1 item to the currentResult</p>
<pre><code>test('Show more button click works successfully', () =&gt; {
const state = {
search: {
  ...initialState.search,
  mainResult: SearchData.test.large,
  currentResult: SearchData.test.large.slice(0, 15),
  currentCount: 15,
  currentTotal: 16,
},
};

store = mockStore(state);
const { getByTestId } = render(
&lt;Provider store={store}&gt;
  &lt;SearchListing {...props} /&gt;
 &lt;/Provider&gt;
);
const showMoreBtn = getByTestId('search-listing-result-footer-btn');

expect(getByTestId('search-listing-result-footer-label')).toHaveTextContent('Showing 15 of 16 results');

userEvent.click(showMoreBtn);

expect(getByTestId('search-listing-result-footer-label')).toHaveTextContent('Showing 16 of 16 results');
});
</code></pre>
<p>Show more function, I'm chunking the mainResult so if I click the show more, I'll just add the next chunk to currentResult.</p>
<pre><code> const showMore = () =&gt; {
const newPageCount = pageCount + 1;
const newResult = [...currentResult, ...resultsChunk[newPageCount]];
dispatch(searchActions.showMore({ currentResult: newResult, currentCount: newResult.length }));
setPageCount(newPageCount);
};
</code></pre>
<p>Error message:</p>
<pre><code>Expected element to have text content:
  Showing 16 of 16 results
Received:
  Showing 15 of 16 results
</code></pre>
<p>How can I update the mockStore after onClick? or is there any other way.</p>
",https://stackoverflow.com/questions/69735639/event-not-changing-the-state-of-the-label-react-testing-library,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",176,False,0,0
TypeError: &#39;module&#39; object is not callable with unittest,"<p>I am trying to simulate a QDialogButtonBox button click in a QDialog, as part of unit testing.</p>
<ol>
<li><p>I have not found the solution to reach the QDialogButtonBox object in the QDialog instance. The only solution I found is to do an QDialog().accept() directly. Maybe there is a better way to do it?</p>
</li>
<li><p>The test does not work because I have an exception TypeError: 'module' object is not callable that I do not understand. What do I not understand?</p>
</li>
</ol>
<p>This is the code:</p>
<pre><code>import sys
import unittest
import threading
from PyQt5.QtWidgets import (
    QApplication,
    QDialog,
    QDialogButtonBox,
    QGridLayout,
    QGroupBox,
    QLabel,
    QMainWindow,
    QScrollArea,
    QVBoxLayout,
    QWidget,
)

app = QApplication(sys.argv)

class Fortest:
    def dial(self):
        dialog = QDialog()
        buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        layout = QVBoxLayout(dialog)
        param_box = QGroupBox(&quot;Iterate over parameters:&quot;)
        pblayout = QVBoxLayout()
        pblayout.setContentsMargins(0, 0, 0, 0)
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setFrameStyle(scroll.NoFrame)
        scroll.setViewportMargins(0, 0, 0, 0)
        pblayout.addWidget(scroll)
        param_lay = QGridLayout()
        wid = QWidget()
        scroll.setWidget(wid)
        wid.setLayout(param_lay)
        param_box.setLayout(pblayout)
        layout.addWidget(param_box)
        layout.addWidget(buttonbox)
        buttonbox.accepted.connect(dialog.accept)
        buttonbox.rejected.connect(dialog.reject)
        param_lay.addWidget(QLabel(&quot;iter. / database:&quot;), 0, 0, 1, 3)
        param_lay.addWidget(QLabel(&quot;iter.:&quot;), 0, 3, 1, 2)
        param_lay.setColumnStretch(2, 1)
        param_lay.setColumnStretch(4, 1)
        param_lay.setRowStretch(0, 0)
        res = dialog.exec_()
        if res != dialog.Accepted:
            print(&quot;dialog not accepted&quot;)
            self.a = False
        else:
            print(&quot;dialog accepted&quot;)
            self.a = True

class Test(unittest.TestCase):
    def test(self):
        b = Fortest()
        threading.Timer(1, self.execute_click).start()
        b.dial()
        self.assertEqual(b.a, True)
    def execute_click(self):
        w = QApplication.activeWindow()
        if isinstance(w, QDialog):
            w.accept()
 

if __name__ == &quot;__main__&quot;:
    unittest(Test().test())
</code></pre>
",https://stackoverflow.com/questions/69058227/typeerror-module-object-is-not-callable-with-unittest,"['python', 'pyqt5', 'python-unittest']",162,True,0,1
Is there a way to use Assert or Moq.Verify on a Mocked Logger?,"<p>I'm unit testing my OnAuthorization class and i need to test the error cases. Here's an example:</p>
<pre><code>Mock&lt;ILogger&gt; mockLog = new Mock&lt;ILogger&gt;();
ILogger log = mockLog.Object;

public override void OnAuthorization(HttpActionContext actionContext)
{
   try 
   {
       //some code
       if (condition)
       {
          //some more code
       }
       else
       {
          throw new Exception(&quot;MyMessage&quot;);
       }
   }
   catch(Exception ex)
   {
       log.LogError(ex);
   }
}
</code></pre>
<p>Now, assuming that <code>condition = false</code> how can i check that the right exception was thrown in an UnitTest method?</p>
<p>I thought about using <code>log.Verify</code> or <code>Assert.That</code> but i don't see how i should use them to achieve my goal
Any Ideas?</p>
<p>p.s. I'm working on a huge project, and I'm not the only one working on it, so i should avoid modifying the code unless it's really unavoidable.</p>
",https://stackoverflow.com/questions/66261945/is-there-a-way-to-use-assert-or-moq-verify-on-a-mocked-logger,"['c#', 'unit-testing', 'moq']",30,False,0,0
angular test not checking the actual value emitted by observable,"<p>I am unit testing an observable and checking if it contains a ? element. The source data is as follows.</p>
<p>Though both the expects run without error I am not convinced with the expect that checks for ? mark.</p>
<p>Wouldn't I need to check for the complete element { name: '?', isAlive: false },</p>
<p>When i console.log the result it looks like this</p>
<p>[Object{name: 'Test', isAlive: true}, Object{name: 'Test2', isAlive: false}, Object{name: 'Test3', isAlive: false}, Object{name: 'Test4', isAlive: false}, Object{name: 'Test5', isAlive: false}]</p>
<pre><code>export const TestModelObjectMock: any[] = [
    { name: 'Test', isAlive: false },
    { name: 'Test2', isAlive: false },
    { name: 'Test3', isAlive: false },
    { name: '?', isAlive: false },
    { name: 'Test4', isAlive: true },
    { name: 'Test5', isAlive: false }
]; 

const testModelObject = TestModelObjectMock;

   it('should call the title service and filter questionmark', fakeAsync(() =&gt; {
        mockTestService.extend({ getTitles: () =&gt; of(testModelObject ) });
        setupComponent();
       
        flush();

        expect(component.titleService.getNames().subscribe(result =&gt; expect(result).not.toContain('?')));

        
        expect(component.titleNames$.subscribe(result =&gt; {expect(result.length).toEqual(5),
        console.log(result)})); 
</code></pre>
",https://stackoverflow.com/questions/70225801/angular-test-not-checking-the-actual-value-emitted-by-observable,"['angular', 'jasmine']",46,False,0,1
Unit testing explicitly dispatching WebhookReceived event is not working,"<p>I am building a Laravel application. I am using Laravel Cashier to handle subscription in my application. I am writing unit test for the Stripe Webhook creating a custom event listener for that.</p>
<p>I have an event listener like this:</p>
<pre><code>class StripeEventListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(WebhookReceived $event)
    {
        if ($event-&gt;payload['type'] === 'invoice.payment_succeeded') {
            // Handle the incoming event...
        }
        // TODO: write unit test for this event.
        if ($event-&gt;payload['type'] === 'customer.subscription.updated') {
            // Handle the incoming event...
            // handleCustomerSubscriptionUpdated
            if ($user = $this-&gt;getUserByStripeId($event-&gt;payload['data']['object']['customer'])) {
                $data = $event-&gt;payload['data']['object'];
                if (
                    isset($data['status']) &amp;&amp;
                    ($data['status'] === StripeSubscription::STATUS_INCOMPLETE_EXPIRED ||
                    $data['status'] == StripeSubscription::STATUS_INCOMPLETE)
                ) {
                    if (! $user-&gt;payment_method_needs_updating) {
                        $user-&gt;payment_method_needs_updating = true;
                        $user-&gt;save();
                    }
                }
            }
        }
    }

    protected function getUserByStripeId($stripeId)
    {
        return Cashier::findBillable($stripeId);
    }
}
</code></pre>
<p>Then I bind that to WebhookReceived event in the EventServiceProvider like this:</p>
<pre><code>protected $listen = [
        WebhookReceived::class =&gt; [
            StripeEventListener::class
        ],
        Registered::class =&gt; [
            SendEmailVerificationNotification::class,
        ],
    ];
</code></pre>
<p>I am unit testing the listener dispatching the WebhookReceived event like this:</p>
<pre><code>WebhookReceived::dispatch([
            .... mock data
        ]);
</code></pre>
<p>But I am getting this error:</p>
<pre><code>   Illuminate\Contracts\Container\BindingResolutionException 

  Target class [events] does not exist.

  at vendor/laravel/framework/src/Illuminate/Container/Container.php:879
    875▕ 
    876▕         try {
    877▕             $reflector = new ReflectionClass($concrete);
    878▕         } catch (ReflectionException $e) {
  ➜ 879▕             throw new BindingResolutionException(&quot;Target class [$concrete] does not exist.&quot;, 0, $e);
    880▕         }
</code></pre>
<p>How can I fix it or how can I unit test it?</p>
",https://stackoverflow.com/questions/70509116/unit-testing-explicitly-dispatching-webhookreceived-event-is-not-working,"['laravel', 'laravel-cashier']",293,False,0,0
"TYPED_TEST for a class template &lt;typename T, size_t size&gt;","<p>I am trying to write a unit tests for a templated class named Client. Couldn't succeed in compiling the unitTests code. Not sure how to pass both the <code>class / typename T</code> and the <code>size_t size</code> parameters in unit Testing. I have made a git repo <code>git clone https://github.com/BhanuKiranChaluvadi/gtest-minimal-example.git</code> in case if you wish to compile on local machine and look into the issue.</p>
<pre><code>#pragma once

#include &lt;array&gt;

namespace inputs
{
    template &lt;typename T, size_t size&gt;
    class IClient
    {
    public:
        using ClientType = std::array&lt;T, size&gt;;
        virtual const ClientType &amp;getID() const = 0;
        virtual bool isID(const ClientType &amp;anotherID) const = 0;
    };

    template &lt;typename T, size_t size&gt;
    class Client : public IClient&lt;T, size&gt;
    {
    public:
        using ClientT = std::array&lt;T, size&gt;;

        Client(const ClientT &amp;ID) : ID(ID) {}
        Client(const ClientT &amp;&amp;ID) : ID(std::move(ID)) {}

        inline const ClientT &amp;getID() const override { return ID; }
        inline bool isID(const ClientT &amp;anotherID) const override { return ID == anotherID; }

        inline bool operator==(const Client &amp;anotherClient) { return ID == anotherClient.getID(); }

    private:
        ClientT ID;
    };

} // namespace inputs
</code></pre>
<p>And this is how my google tests looks like</p>
<pre><code>#include &quot;gtest/gtest.h&quot;
#include &lt;type_traits&gt;
#include &quot;client.hpp&quot;
#include &lt;memory&gt;
#include &lt;utility&gt;
#include &lt;tuple&gt;

using namespace inputs;

namespace inputs_test
{

    template &lt;class T, size_t size&gt;
    class ClientTest : public testing::Test
    {
    };

    using testing::Types;

    // The list of types we want to test.
    typedef Types&lt;std::pair&lt;int8_t, std::integral_constant&lt;std::size_t, 16&gt;&gt;,
                                std::pair&lt;uint8_t, std::integral_constant&lt;std::size_t, 24&gt;&gt;&gt;
            Implementations;

    TYPED_TEST_CASE(ClientTest, Implementations);

    TYPED_TEST(ClientTest, shouldReturnSetID)
    {
        typename TypeParam::first_type data_type;
        typename TypeParam::second_type size;
        // static constexpr std::size_t n = TypeParam::value;
        EXPECT_TRUE(true);
    }

} // namespace inputs_test
</code></pre>
<p>The templated Client class expected either <code>&lt;int8_t, 16&gt;</code> or <code>&lt;uint8_t, 24&gt;</code>. I am not sure how to pass <code>size_t</code> templated argument.</p>
<pre><code>test/googletest-src/googletest/include/gtest/gtest-typed-test.h:174:38: error: wrong number of template arguments (1, should be 2)
  174 |     typedef CaseName&lt;gtest_TypeParam_&gt; TestFixture; \
</code></pre>
",https://stackoverflow.com/questions/68251554/typed-test-for-a-class-template-typename-t-size-t-size,"['c++', 'unit-testing', 'templates', 'c++14', 'googletest']",339,True,0,1
How to create a function that will add new elements into an empty array(JS)?,"<p>I'm trying to get some unit testing to work and I'm running into problems when writing a function that will add a new ingredient to my empty array.</p>
<p>The test says:</p>
<pre><code>it(&quot;should be able to add ingredients to an array&quot;, function() {
      var ingredients = [];

      addIngredients(&quot;cheese&quot;, ingredients);

      assert.equal(ingredients.length, 1);
      assert.deepEqual(ingredients, [&quot;cheese&quot;]);
    });
</code></pre>
<p>My code is not working... it says that the array is still empty when it should return 1. Any advice on how to get this function to add to the empty array?</p>
<p>My code:</p>
<pre><code>
function addIngredients(ingredients) {
  var ingredients = [];
  ingredients.push();
  return ingredients;
}

addIngredients(&quot;cheese&quot;);
</code></pre>
<p>Still very green, any advice that can lead me in the right direction would be great!</p>
",https://stackoverflow.com/questions/68946043/how-to-create-a-function-that-will-add-new-elements-into-an-empty-arrayjs,"['javascript', 'arrays']",148,True,0,3
How to raise an error with decorator for unit testing?,"<p>I would like to do something in my unit testing before it fails and using decorator to do so</p>
<p>Here is my code :</p>
<pre><code>import requests
import unittest
import test


class ExceptionHandler(object):
    def __init__(self, f):
        self.f = f

    def __call__(self, *args, **kwargs):
        try:
            self.f(*args, **kwargs)
        except Exception as err:
            print('do smth')
            raise err


class Testing(unittest.TestCase):
    @ExceptionHandler
    def test_connection_200(self):
        r = requests.get(&quot;http://www.google.com&quot;)
        self.assertEqual(r.status_code, 400)


if __name__ == '__main__':
    unittest.main(verbosity=2)
</code></pre>
<p>But it throws me an :</p>
<pre><code>TypeError: test_connection_200() missing 1 required positional argument: 'self'
</code></pre>
<p>How can I do something when my test fail, then having the normal failing behavior of unitest?</p>
<p>Edit :
I would like to do something before my test fail like write a  log and then continue the normal process of failing.</p>
<p>If possible with a decorator.</p>
<p>Edit bis the solution thanks to @Thymen :</p>
<pre><code>import requests
import unittest
import test


class ExceptionHandler(object):
    def __init__(self, f):
        self.f = f

    def __call__(self, *args, **kwargs):
        try:
            self.f(*args, **kwargs)
        except Exception as err:
            print('do smth')
            raise err


class Testing(unittest.TestCase):
    def test_connection_200(self):
        @ExceptionHandler
        def test_connection_bis(self):
            r = requests.get(&quot;https://www.google.com&quot;)
            print(r.status_code)
            self.assertEqual(r.status_code, 400)
        test_connection_bis(self)


if __name__ == '__main__':
    unittest.main(verbosity=2)
</code></pre>
",https://stackoverflow.com/questions/67032032/how-to-raise-an-error-with-decorator-for-unit-testing,"['python-3.x', 'unit-testing']",427,True,0,1
Angular testing - TypeError: Cannot read property of underfined,"<p>I'm not much familiar with Angular Unit testing. I have been working on this issue for almost a day. Please tell me why this coming and how to solve this issue? There are more issues similar to this one.</p>
<p>I already referred to this one, which is not helped.
<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>
<blockquote>
<p>I found that the error is occurring inside the <code>addRole</code> function in <code>add-role.component.ts</code>.</p>
</blockquote>
<p><strong>Error</strong></p>
<pre><code>TypeError: Cannot read property 'roleName' of undefined
    at AddRoleComponent_Template (ng:///AddRoleComponent.js:59:52)
    at executeTemplate (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9545:1)
    at refreshView (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9414:1)
    at refreshComponent (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10580:1)
    at refreshChildComponents (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9211:1)
    at refreshView (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9464:1)
    at renderComponentOrTemplate (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:9528:1)
    at tickRootContext (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10754:1)
    at detectChangesInRootView (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10779:1)
    at RootViewRef.detectChanges (node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:22792:1)
TypeError: Cannot read property 'roleName' of undefined
    at AddRoleComponent.addRole (src/app/components/admin/add-role/add-role.component.ts:53:29)
    at &lt;Jasmine&gt;
    at UserContext.&lt;anonymous&gt; (src/app/components/admin/add-role/add-role.component.spec.ts:60:17)
    at ZoneDelegate.invoke (node_modules/zone.js/dist/zone-evergreen.js:364:1)
    at ProxyZoneSpec.push.QpwO.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/zone-testing.js:292:1)
    at ZoneDelegate.invoke (node_modules/zone.js/dist/zone-evergreen.js:363:1)
</code></pre>
<p><strong>Here are the lines that the errors are coming,</strong></p>
<pre><code>add-role.component.ts:53 -&gt; const claimValue = role.roleName;
add-role.component.spec.ts:60 -&gt; component.addRole();
</code></pre>
<p><strong>add-role.component.ts</strong></p>
<pre><code>import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {IRole} from 'src/app/models/role.model';
import {AlertService} from 'src/app/services/alert-service/alert-service.service';
import {AuthService} from 'src/app/services/auth/auth.service';
import {ClaimsService} from 'src/app/services/claims/claims.service';

@Component({
  selector: 'app-add-role',
  templateUrl: './add-role.component.html',
  styleUrls: ['./add-role.component.scss']
})
export class AddRoleComponent implements OnInit {
  addRoleForm: FormGroup;
  roleName?: string;
  role?: IRole;

  constructor(
    private activatedRoute: ActivatedRoute,
    private authService: AuthService,
    private router: Router,
    private formBuilder: FormBuilder,
    private claimService: ClaimsService,
    private alertService: AlertService
  ) {
    this.buildForm();
  }

  get formControls() {
    return this.addRoleForm.controls;
  }

  onDataLoadFailed(errors: any): void {
  }

  onDataLoadSuccessful(results: any): void {
    this.role = results;
  }

  ngOnInit(): void {
  }

  addRole() {
    const role = this.addRoleForm.value;
    const claimValue = role.roleName;
    this.claimService.addRole(claimValue).subscribe(
      data =&gt; this.onSuccess(data),
      error =&gt; this.handleError(error),
      () =&gt; this.onComplete()
    );
  }

  onSuccess(data): void {
    this.alertService.success(data.key, data.message);
  }

  handleError(errors): void {
    this.alertService.errors(errors);
  }

  onComplete(): void {
  }

  private buildForm() {
    this.addRoleForm = this.formBuilder.group({
      roleName: ['', [Validators.required]],
    });
  }

}


</code></pre>
<p><strong>add-role.component.spec.ts</strong></p>
<pre><code>import {ComponentFixture, TestBed} from '@angular/core/testing';
import {NO_ERRORS_SCHEMA} from '@angular/core';
import {FormBuilder} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {AlertService} from 'src/app/services/alert-service/alert-service.service';
import {AuthService} from 'src/app/services/auth/auth.service';
import {ClaimsService} from 'src/app/services/claims/claims.service';
import {AddRoleComponent} from './add-role.component';

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

  beforeEach(() =&gt; {
    const formBuilderStub = () =&gt; ({group: object =&gt; ({})});
    const activatedRouteStub = () =&gt; ({});
    const routerStub = () =&gt; ({});
    const alertServiceStub = () =&gt; ({
      success: (key, message) =&gt; ({}),
      errors: errors =&gt; ({})
    });
    const authServiceStub = () =&gt; ({});
    const claimsServiceStub = () =&gt; ({
      addRole: claimValue =&gt; ({subscribe: f =&gt; f({})})
    });
    TestBed.configureTestingModule({
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [AddRoleComponent],
      providers: [
        {provide: FormBuilder, useFactory: formBuilderStub},
        {provide: ActivatedRoute, useFactory: activatedRouteStub},
        {provide: Router, useFactory: routerStub},
        {provide: AlertService, useFactory: alertServiceStub},
        {provide: AuthService, useFactory: authServiceStub},
        {provide: ClaimsService, useFactory: claimsServiceStub}
      ]
    });
    fixture = TestBed.createComponent(AddRoleComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  afterEach(() =&gt; {
    fixture.destroy();
  });

  it('can load instance', () =&gt; {
    expect(component).toBeTruthy();
  });

  describe('addRole', () =&gt; {
    it('makes expected calls', () =&gt; {
      const claimsServiceStub: ClaimsService = fixture.debugElement.injector.get(
        ClaimsService
      );
      spyOn(component, 'onSuccess').and.callThrough();
      spyOn(component, 'handleError').and.callThrough();
      spyOn(component, 'onComplete').and.callThrough();
      spyOn(component, 'addRole').and.callThrough();
      component.addRole();
      expect(component.onSuccess).toHaveBeenCalled();
      expect(component.handleError).toHaveBeenCalled();
      expect(component.onComplete).toHaveBeenCalled();
      expect(component.addRole).toHaveBeenCalled();
    });
  });
});
</code></pre>
",https://stackoverflow.com/questions/66677597/angular-testing-typeerror-cannot-read-property-of-underfined,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",2338,True,0,2
Mocking html-pdf using Jest,"<p>I am using the <a href=""https://www.npmjs.com/package/html-pdf"" rel=""nofollow noreferrer"">html-pdf</a> package in my nodejs code (not in Typescript). Now, this package has a <code>create()</code> function which is chained with the <code>toBuffer()</code> function. I am unit testing my code using Jest and want to mock this call <code>pdf.create(html).toBuffer()</code>.</p>
<pre><code>var pdf = require('html-pdf');
pdf.create(html).toBuffer(function(htmlToPdfError, buffer){
  if (htmlToPdfError) {
    reject(htmlToPdfError);
  }
  resolve(buffer.toString('base64'));
});
</code></pre>
<p>EDIT:
I am trying to use the following code in my spec file to make the module:</p>
<pre><code>jest.mock('html-pdf', () =&gt; ({
    create: jest.fn(() =&gt; {
        return Promise.resolve();
    })
}));
</code></pre>
<p>This is helping me mock the <code>create()</code> function but I do not know how to return a object in Promise.resolve which would have a <code>toBuffer</code> function</p>
",https://stackoverflow.com/questions/69838559/mocking-html-pdf-using-jest,"['javascript', 'node.js', 'html-pdf', 'node-html-pdf']",1670,True,0,2
How test a functional component and get full coverage report with jest and enzyme,"<p>I tried to get a full coverage report and tried to cover all unit testing of my React project,
i know this is just to get a 100% full report and i can do it without it, but i want to know if there are something way to cover all test on a SFC to get 100% coverage report.</p>
<p>This is my component:</p>
<pre><code>import React, { useEffect } from &quot;react&quot;;
import { connect } from &quot;react-redux&quot;;
import { createStructuredSelector } from &quot;reselect&quot;;

///Components
import UserForm from &quot;../../components/user-form/user-form.component&quot;;

//Actions
import { getUserStartActionable, updateUserStart  } from &quot;../../redux/admin-user/admin-user.actions&quot;;

//Selector
import { selectGetUser } from &quot;../../redux/admin-user/admin-user.select&quot;;

import { SpinnerLoading } from &quot;../../utils/styles.utils&quot;;

import {
  WrapContainer,
  UserBody,
  UserHeader,
  UserFooter,
} from &quot;./update-user.styles&quot;;

/***
 * Componente que renderiza la página para realizar
 * el registro de usuarios pacientes
 * @param {Object} state
 * @param {Function} createUser
 * @return {Component} RegisterUsersPage
 */
export const UpdateUser = ({ match, getUser, patientState }) =&gt; {

  const fetchStart = () =&gt; {getUser(match.params.patientId)};
      

  useEffect(fetchStart, []);

  return (
    &lt;WrapContainer&gt;
      &lt;UserHeader&gt;
        &lt;h3&gt;Actualizar Usuario&lt;/h3&gt;
      &lt;/UserHeader&gt;
      &lt;UserBody&gt;
        {patientState.user ? (
          &lt;UserForm user={patientState.user} type=&quot;UPDATE&quot; /&gt;
        ) : (
          &lt;SpinnerLoading text=&quot;Cargando información&quot; /&gt;
        )}
      &lt;/UserBody&gt;
      &lt;UserFooter&gt;&lt;/UserFooter&gt;
    &lt;/WrapContainer&gt;
  );
};

//Selector de estados
const mapStateToProps = createStructuredSelector({
  patientState: selectGetUser,
});

//Despachador de acciones
const mapDispatchToProps = (dispatch) =&gt; ({
  getUser: (user) =&gt; dispatch(getUserStartActionable(user)),
});

export default connect(mapStateToProps, mapDispatchToProps)(UpdateUser);

</code></pre>
<p>So when run &quot;yarn test --coverage&quot;</p>
<pre><code>update-user.component.jsx          |    66.67 |        0 |       25 |    85.71 |                73 |
</code></pre>
<p>My test:</p>
<pre><code>describe(&quot;&lt;UpdateUser /&gt;&quot;, () =&gt; {
  let wrapper;

  beforeEach(() =&gt; {
    
    wrapper = shallow(&lt;UpdateUser /&gt;);
  });

  it(&quot;should render the RegisterUsers Page&quot;, () =&gt; {
    expect(wrapper).toMatchSnapshot();
  });

  
});
</code></pre>
<p>So how i cover the dispatch getUser?</p>
<p>Thanks a lot</p>
",https://stackoverflow.com/questions/65801980/how-test-a-functional-component-and-get-full-coverage-report-with-jest-and-enzym,"['javascript', 'jestjs', 'enzyme']",485,False,-1,1
How to cover outside function in Jest test case React Native,"<p>I am using Jest for unit testing for my React Native project. I have created the test file and it's running successfully, but when I am checking the coverage some functions which are getting called inside the render() method are not covered. I have attached the image for that. How can I cover all these functions in my Jest file so my coverage will increase?</p>
<p>Below is test case:</p>
<pre><code>import React from 'react';
import renderer from 'react-test-renderer';
import App from '../app/components/Home';
import DashboardContainer from '../app/components/container/DashboardContainer';
import MenuContainer from '../app/components/container/MenuContainer';
import DigitalFooter from '../app/components/ui/digitalFooter';
import OffersContainer from '../app/components/container/OffersContainer';
import DigitalSearchContainer from '../app/components/container/DigitalSearchContainer';
import BMobileDashboardContainer from '../app/components/container/BMobileDashboardContainer';
import { MockedProvider } from '@apollo/client/testing';
import gql from 'graphql-tag';
import { ApolloProvider } from 'react-apollo';
import { InMemoryCache } from 'apollo-cache-inmemory';
import ApolloClient from 'apollo-client';


const defaultOptions = {
    watchQuery: {
      fetchPolicy: 'no-cache',
      errorPolicy: 'ignore',
    },
    query: {
      fetchPolicy: 'no-cache',
      errorPolicy: 'all',
    },
  };
  
  const client = new ApolloClient({
    link: 'http://localhost:4000',
    cache: new InMemoryCache(),
    defaultOptions
  })
  

  jest.useFakeTimers();

  
  test('Notification renders correctly', () =&gt; {
    const tree = renderer.create(
        &lt;ApolloProvider client={client}&gt;
          &lt;MenuContainer /&gt;
          &lt;/ApolloProvider&gt;
      ).toJSON();
    //console.log(tree);
    expect(tree).toMatchSnapshot();
  });

  test('Homescreen Component renders correctly', () =&gt; {
    const tree = renderer.create(
        &lt;ApolloProvider client={client}&gt;
          &lt;DashboardContainer/&gt;
          &lt;/ApolloProvider&gt;
      ).toJSON();
    //console.log(tree);
    expect(tree).toMatchSnapshot();
  });

  test('Homescreen Component renders correctly', () =&gt; {
    const tree = renderer.create(
        &lt;ApolloProvider client={client}&gt;
          &lt;BMobileDashboardContainer/&gt;
          &lt;/ApolloProvider&gt;
      ).toJSON();
    //console.log(tree);
    expect(tree).toMatchSnapshot();
  });
  test('Homescreen Component renders correctly', () =&gt; {
    const tree = renderer.create(
        &lt;ApolloProvider client={client}&gt;
          &lt;DigitalSearchContainer/&gt;
          &lt;/ApolloProvider&gt;
      ).toJSON();
    //console.log(tree);
    expect(tree).toMatchSnapshot();
  });

//   test('Login renders correctly', () =&gt; {
//     const tree = renderer.create(&lt;DigitalFooter /&gt;).toJSON();
//     console.log(tree);
//     expect(tree).toMatchSnapshot();
//   });

it('renders without error', () =&gt; {
    renderer.create(
        &lt;ApolloProvider client={client}&gt;
        &lt;MockedProvider  addTypename={false}&gt;
            &lt;App/&gt;
          &lt;/MockedProvider&gt;
      &lt;/ApolloProvider&gt;
    );
  });
</code></pre>
<p>// Below is component</p>
<pre><code>import React from 'react';
import { View } from 'react-native';
import { getData, hasPermission } from './services/services';
import _ from 'lodash';
import { withApollo } from 'react-apollo';
import DigitalFooter from './ui/digitalFooter';
import OffersContainer from '../components/container/OffersContainer';
import MenuContainer from '../components/container/MenuContainer';
import DashboardContainer from './container/DashboardContainer';
import DigitalSearchContainer from './container/DigitalSearchContainer';
import BMobileDashboardContainer from './container/BMobileDashboardContainer';
import parentStyle from '../themes/parent.style';
const APPLICATION_THEME = 'applicationTheme';
const APPLICATION_MODE = 'applicationMode';
const OPCO = 'opco';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeCount: 0,
      updateResponse: {},
      actionList: [],
      selectedTab: 'home',
      appliedTheme: '',
      appliedMode: '',
      showSearchScreen: false,
      opco: '',
      globalsearch: false,
      offers: false,
      tabs: []
    };
  }

  async componentDidMount() {
    this.setState({
      appliedTheme: await getData(APPLICATION_THEME),
      appliedMode: await getData(APPLICATION_MODE),
      opco: await getData(OPCO),
      globalsearch: await hasPermission('dclm.fe.footer.globalsearch.allow'),
      offers: await hasPermission('dclm.fe.footer.offers.allow')
    });
    await this.prepareFooterTabs();
  }
  updateFooterColor = async() =&gt; {
    this.setState({
      appliedTheme: await getData(APPLICATION_THEME),
      appliedMode: await getData(APPLICATION_MODE),
    });
  }
  prepareFooterTabs = async () =&gt; {
    let tabs = [];
    const { globalsearch, offers } = this.state;
    const home = {
      page: 'home',
      iconText: 'Home',
      icon: 'ios-home',
      iconType: 'Ionicons',
    };
    const menu = {
      page: 'menu',
      iconText: 'Menu',
      icon: 'md-menu',
      iconType: 'Ionicons',
    };
    tabs.push(home);
   
    tabs.push(menu);
    this.setState({
      tabs: tabs
    })
  }

  selectFooterTab = (tab) =&gt; {
    this.setState({
      selectedTab: tab
    })
  }
  showSearchScreen = async (e) =&gt; {
    this.setState({
      showSearchScreen: e
    })
  }

  render() {
    const { selectedTab, opco, tabs, appliedTheme, appliedMode } = this.state;
    const signatureHeadingColor = parentStyle[appliedTheme] ? parentStyle[appliedTheme][appliedMode].signatureHeadingColor : null;
    return (
      &lt;View style={{ width: '100%', height: '100%' }}&gt;
        {selectedTab === 'home' &amp;&amp; opco === 'opco1_rose' &amp;&amp; &lt;BMobileDashboardContainer navigation={this.props.navigation} showSearchScreen={(e) =&gt; this.showSearchScreen(e)} /&gt;}
        {selectedTab === 'home' &amp;&amp; opco === 'mauritius_telecom' &amp;&amp; &lt;BMobileDashboardContainer navigation={this.props.navigation} showSearchScreen={(e) =&gt; this.showSearchScreen(e)} /&gt;}
        {selectedTab === 'home' &amp;&amp; opco === 'default' &amp;&amp; &lt;DashboardContainer navigation={this.props.navigation} showSearchScreen={(e) =&gt; this.showSearchScreen(e)} /&gt;}
        {selectedTab === 'search' &amp;&amp; &lt;DigitalSearchContainer navigation={this.props.navigation} showSearchScreen={(e) =&gt; this.showSearchScreen(e)} /&gt;}
        {selectedTab === 'offers' &amp;&amp; &lt;OffersContainer navigation={this.props.navigation} showSearchScreen={(e) =&gt; this.showSearchScreen(e)} /&gt;}
        {selectedTab === 'menu' &amp;&amp; &lt;MenuContainer navigation={this.props.navigation} selectedTab={selectedTab} updateFooterColor={()=&gt; this.updateFooterColor()}/&gt;}

        {this.state.tabs.length !== 0 &amp;&amp; &lt;View style={{ position: 'absolute', bottom: 0 }}&gt;
          &lt;DigitalFooter
            signatureHeadingColor={signatureHeadingColor}
            tabs={tabs}
            screen={selectedTab}
            navigation={this.props.navigation}
            selectFooterTab={(tab) =&gt; this.selectFooterTab(tab)} /&gt;
        &lt;/View&gt;}
      &lt;/View&gt;
    );
  }
}
export default withApollo(App);
</code></pre>
<p>Here red highlight is not covered in the test file:</p>
<p><a href=""https://i.stack.imgur.com/KoBew.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/KoBew.png"" alt="""" /></a></p>
",https://stackoverflow.com/questions/70107027/how-to-cover-outside-function-in-jest-test-case-react-native,"['javascript', 'reactjs', 'react-native', 'jestjs', 'ts-jest']",538,False,0,0
Angular Testing Circular Dependency Error on Service in Component,"<p>I recently started to get myself into Angular Unit Testing and started to provide mock tests on a project of mine. At the moment, I can't figure out why I get the following error on one of my component tests:</p>
<p><em>Error: NG0200: Circular dependency in DI detected for KeycloakService</em></p>
<pre><code>error properties: Object({ code: '200' })
Error: NG0200: Circular dependency in DI detected for KeycloakService
    at throwCyclicDependencyError (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:1352:1)
    at R3Injector.hydrate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11154:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10979:1)
    at NgModuleRef$1.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:25053:1)
    at Object.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:24767:1)
    at lookupTokenUsingModuleInjector (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:3296:1)
    at getOrCreateInjectable (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:3408:1)
    at ɵɵdirectiveInject (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:14428:1)
    at NodeInjectorFactory.DashboardComponent_Factory [as factory] (ng:///DashboardComponent/ɵfac.js:6:7)
    at getNodeInjectable (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:3503:1)
</code></pre>
<p><em>NullInjectorError: R3InjectorError(DynamicTestModule)[KeycloakService -&gt; HttpClient -&gt; HttpClient]:
NullInjectorError: No provider for HttpClient!</em></p>
<pre><code>error properties: Object({ ngTempTokenPath: null, ngTokenPath: [ 'KeycloakService', 'HttpClient', 'HttpClient' ] })
NullInjectorError: R3InjectorError(DynamicTestModule)[KeycloakService -&gt; HttpClient -&gt; HttpClient]: 
  NullInjectorError: No provider for HttpClient!
    at NullInjector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10823:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10990:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10990:1)
    at injectInjectorOnly (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:4907:1)
    at ɵɵinject (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:4911:1)
    at Object.KeycloakService_Factory [as factory] (ng:///KeycloakService/ɵfac.js:5:43)
    at R3Injector.hydrate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:11158:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:10979:1)
    at NgModuleRef$1.get (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/core.js:25053:1)
    at TestBedRender3.inject (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/__ivy_ngcc__/fesm2015/testing.js:1686:1)
</code></pre>
<p><em>DashboardComponent</em></p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { TimeModule } from 'src/app/time/time.module';
import { KeycloakService } from 'src/app/services/keycloak.service';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.scss']
})
export class DashboardComponent implements OnInit {

  public tacticalTimestamp = '';

  constructor(
    private router: Router,
    private keycloak: KeycloakService) {}
</code></pre>
<p><em>DashboardComponentSpec</em></p>
<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';

import { DashboardComponent } from './dashboard.component';

import { Router } from '@angular/router';
import { KeycloakService} from 'src/app/services/keycloak.service';
import { of } from 'rxjs';

class MockRouter {
}

class MockKeycloakService {
}

describe('DashboardComponent', () =&gt; {
  let component: DashboardComponent;
  let fixture: ComponentFixture&lt;DashboardComponent&gt;;
  let router: Router;
  let keycloak: KeycloakService;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [ DashboardComponent ],
      providers: [
        { provide: Router, useClass: MockRouter },
        { provide: KeycloakService, useclass: MockKeycloakService },
      ]
    })
    .compileComponents();

    router = TestBed.inject(Router);
    keycloak = TestBed.inject(KeycloakService);
  });

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

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
<p><em>KeycloakService</em></p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http'
import { environment } from 'src/environments/environment';
import { IKeycloakToken, IKeycloakTokenConvert } from 'src/app/interfaces/keycloak-token';

import jwt_decode from 'jwt-decode';
import { UserDataService } from './user-data.service';
import { MedicalQualification } from './user-data.service';

export enum ELoginResult {
  Success,
  Fail
}

@Injectable({
  providedIn: 'root'
})
export class KeycloakService {

  private token: IKeycloakToken = {} as IKeycloakToken;

  username = '';
  private intervalId: any;
  private intervalDelta = 60000;

  constructor(private http: HttpClient, private userData: UserDataService) { }
</code></pre>
<p><em>KeycloakServiceSpec</em></p>
<pre><code>import { TestBed } from '@angular/core/testing';

import { KeycloakService } from './keycloak.service';
import { HttpClient } from '@angular/common/http';
import { UserDataService } from './user-data.service';

class MockHttpClient {
}

class MockUserDataService {
}

describe('KeycloakService', () =&gt; {
  let service: KeycloakService;
  let httpClient: HttpClient;
  let userData: UserDataService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        { provide: HttpClient, useClass: MockHttpClient },
        { provide: UserDataService, useClass: MockUserDataService }
      ]
    });

    service = TestBed.inject(KeycloakService);
    httpClient = TestBed.inject(HttpClient);
    userData = TestBed.inject(UserDataService);
  });

  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });
});
</code></pre>
<p>The error gets especially weird, because in some components the KeycloakService works just fine...</p>
<p>Hope to find an answer.</p>
",https://stackoverflow.com/questions/70323737/angular-testing-circular-dependency-error-on-service-in-component,"['angular', 'testing']",1121,False,0,1
Getting type &#39;Null&#39; is not a subtype of type &#39;Future&lt;Info&gt;&#39; in type cast in flutter unit testing using mockito,"<p>I have generated mock class for my store and repository class using @GenerateMocks as below::</p>
<pre><code>@GenerateMocks([],customMocks: [

  MockSpec&lt;MyStore&gt;(as: #MockMyStore, returnNullOnMissingStub: true),

  MockSpec&lt;MyRepository&gt;(as: #MockMyRepository, returnNullOnMissingStub: true),

])
</code></pre>
<p>this has automatically created a test.mocks file for both store and repository class but while writing unit testing I am getting error: <strong>'Null' is not a subtype of type 'Future' in type cast.</strong></p>
<p>The test cases I have written as below:</p>
<pre><code>test('call api successfully', () async {

      when(mockStore.calApi()).thenAnswer((realInvocation) =&gt; Future.value());
      expect(await store.calApi(), true);
    });
</code></pre>
<p>//MyStore class</p>
<pre><code>class MyStore = _MyStore with _$MyStore;

abstract class _MyStore with Store {
  late MyRepository _repository;

  _MyStore(MyStore repository)
      : this._repository = repository;
Future&lt;bool&gt; callApi() async {
    
        final isInternet = await Util.checkInternetAndShowDialog(context);
    
        if (isInternet) {
    
          final future = _repository.callApi();
    
          var res = await future;
    
          return true;
    
        }
    
    return false;
    
        }
}
</code></pre>
<p>Can any one help me to resolve this issue, why I am receiving 'Null' subtype error and pass the test cases in flutter. I shall be thankful for this.</p>
",https://stackoverflow.com/questions/68660779/getting-type-null-is-not-a-subtype-of-type-futureinfo-in-type-cast-in-flut,"['flutter', 'mockito', 'flutter-test']",217,False,2,0
How can you mock the methods from a class if you have no control over the class?,"<p>I'm using Xunit and Moq for unit testing. So far I was able to succesfully mock and test methods from interfaces.
But how am I supposed to mock and test the methods of a class that I have no control over. The class has no interface and the methods are not virtual.</p>
<p>I looked into Type Mock Isolator, but I could not make that work, and also that is not a feasible solution because it's paid and only has a 14 day trial, and I need to do this long term.</p>
<p>What are my options?</p>
",https://stackoverflow.com/questions/65832779/how-can-you-mock-the-methods-from-a-class-if-you-have-no-control-over-the-class,"['c#', 'unit-testing', 'moq', 'xunit']",995,True,5,1
NullPointerException when powermockito testing method invocation,"<p>I'm new to unit testing with powermockito and currently i'm trying to test a method that calls <code>java.util.Timer.scheduleAtFixedRate</code>. I've tried to run the test but it failed and showed <code>NullPointerException</code> at the line where an object invoke a method that i suppose my object here is not null. Here is my code, i've summarized the part that may cause the problem.</p>
<p><strong>DailyReminderTest.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>@RunWith(PowerMockRunner.class)
@PrepareForTest(DailyReminder.class)
public class DailyReminderTest {

    @InjectMocks
    DailyReminder dailyReminder;

    @Mock
    User user;

    @Mock
    Timer mockTimer;

    @Mock
    TimerTask mockTask;
    
    @BeforeEach
    public void setUp() {
        TimerTask task = new MyTask(user);
        mockTask = mock(task.getClass());

        dailyReminder = new DailyReminder() {
            @Override
            public Timer createTimer() {
                return mockTimer;
            }

            @Override
            public TimerTask createTask() {
                return mockTask;
            }
        };
    }

    @Test
    void testRemind() throws Exception {
        dailyReminder.remind();  // here is the line where NullPointerException occured
        verify(mockTimer).scheduleAtFixedRate(eq(mockTask), any(Date.class), anyLong());
    }
}
</code></pre>
<p><strong>DailyReminder.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>public class DailyReminder {

    private Timer timer;
    private TimerTask task;
    private User user;
    private Date dateStart;
    private final Duration fixedDuration = Duration.of(1, ChronoUnit.DAYS);
    
    // some constructor here...
    
    public void remind() {
        timer = createTimer();
        task = createTask();
        timer.scheduleAtFixedRate(task, dateStart, fixedDuration.toMillis());
    }

    public Timer createTimer() {
        return new Timer();
    }

    public TimerTask createTask() {
        return new MyTask(user);
    }
}
</code></pre>
<p>I also have tried <code>assertNull(dailyReminder)</code> however the stack trace shows</p>
<pre><code>org.opentest4j.AssertionFailedError: expected: &lt;null&gt; but was: &lt;Daily Reminder&gt;
</code></pre>
<p>which is weird that dailyReminder there wasn't null. Is there any explanation for this?</p>
",https://stackoverflow.com/questions/67855222/nullpointerexception-when-powermockito-testing-method-invocation,"['java', 'unit-testing', 'mockito', 'junit4', 'powermockito']",439,True,2,1
NullPointerException when powermockito testing method invocation,"<p>I'm new to unit testing with powermockito and currently i'm trying to test a method that calls <code>java.util.Timer.scheduleAtFixedRate</code>. I've tried to run the test but it failed and showed <code>NullPointerException</code> at the line where an object invoke a method that i suppose my object here is not null. Here is my code, i've summarized the part that may cause the problem.</p>
<p><strong>DailyReminderTest.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>@RunWith(PowerMockRunner.class)
@PrepareForTest(DailyReminder.class)
public class DailyReminderTest {

    @InjectMocks
    DailyReminder dailyReminder;

    @Mock
    User user;

    @Mock
    Timer mockTimer;

    @Mock
    TimerTask mockTask;
    
    @BeforeEach
    public void setUp() {
        TimerTask task = new MyTask(user);
        mockTask = mock(task.getClass());

        dailyReminder = new DailyReminder() {
            @Override
            public Timer createTimer() {
                return mockTimer;
            }

            @Override
            public TimerTask createTask() {
                return mockTask;
            }
        };
    }

    @Test
    void testRemind() throws Exception {
        dailyReminder.remind();  // here is the line where NullPointerException occured
        verify(mockTimer).scheduleAtFixedRate(eq(mockTask), any(Date.class), anyLong());
    }
}
</code></pre>
<p><strong>DailyReminder.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>public class DailyReminder {

    private Timer timer;
    private TimerTask task;
    private User user;
    private Date dateStart;
    private final Duration fixedDuration = Duration.of(1, ChronoUnit.DAYS);
    
    // some constructor here...
    
    public void remind() {
        timer = createTimer();
        task = createTask();
        timer.scheduleAtFixedRate(task, dateStart, fixedDuration.toMillis());
    }

    public Timer createTimer() {
        return new Timer();
    }

    public TimerTask createTask() {
        return new MyTask(user);
    }
}
</code></pre>
<p>I also have tried <code>assertNull(dailyReminder)</code> however the stack trace shows</p>
<pre><code>org.opentest4j.AssertionFailedError: expected: &lt;null&gt; but was: &lt;Daily Reminder&gt;
</code></pre>
<p>which is weird that dailyReminder there wasn't null. Is there any explanation for this?</p>
",https://stackoverflow.com/questions/67855222/nullpointerexception-when-powermockito-testing-method-invocation,"['java', 'unit-testing', 'mockito', 'junit4', 'powermockito']",439,True,2,1
Testing VuexOrm with vue test utils and jest,"<p>this is my first question here. And my english is not to good. please forgive me for that. ;)</p>
<p>i need help for use vuexOrm with unit testing.
I will test an new model create with jest testing.</p>
<p>e.g. const user = new User - with a trigger</p>
<p>my mock is only return data.</p>
<p>My question. Is it possible to use the models in my mock or what is best practice?
Is it possible to use any mocks with VuexOrm and maybe someone has examples or tutorials somewhere?</p>
<p>Thank you</p>
",https://stackoverflow.com/questions/69265874/testing-vuexorm-with-vue-test-utils-and-jest,"['vue.js', 'unit-testing', 'jestjs', 'vuex-orm']",140,False,2,0
How to mock a function called in the constructor of a RAII class,"<p>Is there a way to correctly mock a function call which is used inside a constructor using Google Mock / Google Test? This is for unit testing my RAII class.</p>
<p>What I tried is creating a Mock class which inherits from the implementation and have the <code>MOCK_METHODx</code> functions in place. Then in my test suite I want to put the <code>EXPECT_CALL</code> before the creation of the object, however, for the <code>EXPECT_CALL</code> the object already needs to be created.</p>
<pre class=""lang-cpp prettyprint-override""><code>// DeviceImpl.h
class DeviceImpl : public IDevice {
public: 
    explicit DeviceImpl(uint32_t deviceAddress);
    ~DeviceImpl() override;

    uint32_t read();
    void write(uint32_t data);

protected:
    /* Virtual forwarding functions to make gmock happy */
    virtual int _open_device(uint32_t deviceAddress) {
      return open_device(deviceAddress); // this is a C function
    }
    virtual int _close_device(int fd) {
      return close_device(fd); // this is a C function
    }
}

// DeviceImplMock.h
class DeviceImplMock : public DeviceImpl {
public:
    DeviceImplMock() : DeviceImpl(1) {};
    ~DeviceImplMock() override = default;

    MOCK_METHOD1(_open_device, int(uint32_t deviceAddress));
    MOCK_METHOD1(_close_device, int(int));
}

// DeviceTest.cc
class DeviceTestSuite : public ::testing::Test {
public:
    std::shared_ptr&lt;DeviceImplMock&gt; device_{nullptr};

    DeviceTestSuite() {
        // Determine how to fix the order problem.
        // For the EXPECT_CALL, and thus the mock, the objects already needs to be created.
        // However, creating the object (with std::make_shared) already calls the non-mocked function
        // What to do here?
        EXPECT_CALL(*device_.get(), _open_device(::testing::_)).WillOnce(Return(1));
        device_ = std::make_shared&lt;DeviceImplMock&gt;();
    }

    ~DeviceTestSuite() override {
        EXPECT_CALL(*device_.get(), _close_device(1)).WillOnce(Return(0));
    }
};

TEST_F(DeviceTestSuite, read) {
  // Test for device-&gt;read() here, etc...
}
</code></pre>
<p>Examples on how to unit test RAII classes using GMock are extremely welcome.</p>
",https://stackoverflow.com/questions/67349159/how-to-mock-a-function-called-in-the-constructor-of-a-raii-class,"['c++', 'c++11', 'googletest', 'googlemock']",600,False,2,0
How to mock an async redux action in jest?,"<p>I'm using jest in my expo project for unit testing. I am new to jest I don't know how to use mock functions to test my redux actions.Following is my action for <code>SignIn</code>.</p>
<p><strong>authActions.ts</strong></p>
<pre><code>..
import Api, {
  SubscriptionPreference,
} from &quot;@myPackage/api&quot;;
...
    export const signIn =
      ({ email, phoneNumber, password }) =&gt;
      async (dispatch) =&gt; {
        console.log(&quot;DATA&quot;)
        dispatch({ type: types.STATE_LOADING });
      try {
           const result = (
            await Api.accounts.accountsLogin({
              email,
              phoneNumber,
              password,
            })
          ).data;    
     
          if (!result.success) {
            throw new Error(i18n.t(&quot;signin_incorrectUsername&quot;));
          }
    
          await SecureStore.setItemAsync(&quot;authtoken&quot;, result.token);
          dispatch(loadAuth());
        } catch (e) {
          const errorMessage = e.error?.message || e.message;
          Alert.alert(errorMessage);
          dispatch({
            type: types.AUTH_ERROR,
            payload: errorMessage,
          });
        }
      };

</code></pre>
<p>The Api is being called from my custom package.So I am not sure how to write a test suite for my <code>signIn</code> action. I have gone through several documentation but couldn't find a proper one for my case. If anybody knows the answer please help. Any help would be really appreciable. Thank you</p>
",https://stackoverflow.com/questions/69448930/how-to-mock-an-async-redux-action-in-jest,"['javascript', 'react-native', 'expo', 'redux-thunk', 'jest-expo']",84,False,1,0
How to mock the router.navigate method in jest,"<p>I am a beginner in unit testing using Jest in Angular. In my component, I have the <code>this.router.navigate()</code> method. Earlier I was using Jasmine to test it. For that I had done the following:</p>
<pre><code>import { Router } from '@angular/router';
</code></pre>
<p>Then,</p>
<pre><code>let router:Router;
</code></pre>
<p>Then, in the <code>beforeEach</code>,</p>
<pre><code>router = TestBed.get(Router);
</code></pre>
<p>Then, in the testcase,</p>
<pre><code>it('should show news intially ', () =&gt; {
   const navigateSpy = spyOn(router,'navigate');
   component.showNews();
   expect(navigateSpy).toHaveBeenCalledWith(['/news']);
 });
</code></pre>
<p>This test was passed. But how do I do the same using Jest? Please Help.</p>
<p>I have an <code>ngOnInit()</code> method which calls another method <code>getDynamicMenus()</code>. Below is the <code>ngOnInit()</code> method:</p>
<pre><code> ngOnInit() {
    this.getDynamicMenus();
  }


  getDynamicMenus() {
    this.menuService.getAllMenus().subscribe(menus =&gt; {
      this.menus = menus._embedded.menu;
    });
  }
</code></pre>
<p>Please let me know how to mock this method. In jasmine, I mocked the <code>getDynamicMenus()</code> and called <code>component.ngOnInit()</code>. But this doesn't work in Jest. Please help.</p>
",https://stackoverflow.com/questions/66872744/how-to-mock-the-router-navigate-method-in-jest,"['angular', 'typescript', 'unit-testing', 'jestjs', 'jasmine']",12326,True,4,1
Mocking errors with client-go fake client,"<p>I'm using client-go (the k8s client for go) to programmatically retrieve and update some secrets from my cluster. While doing this, I'm facing the need of unit-testing my code, and after some investigation I stumbled upon client-go's <code>fake</code> client. However, I haven't been able to mock errors yet. I've followed the instructions from <a href=""https://github.com/kubernetes/client-go/issues/742#issuecomment-633676780"" rel=""nofollow noreferrer"">this issue</a>, but without any success.</p>
<p>Here you have my business logic:</p>
<pre class=""lang-golang prettyprint-override""><code>func (g goClientRefresher) RefreshNamespace(ctx context.Context, namespace string) (err error, warnings bool) {
    client := g.kubeClient.CoreV1().Secrets(namespace)
    secrets, err := client.List(ctx, metav1.ListOptions{LabelSelector: &quot;mutated-by=confidant&quot;})
    if err != nil {
        return fmt.Errorf(&quot;unable to fetch secrets from cluster: %w&quot;, err), false
    }

    for _, secret := range secrets.Items {
        // business logic here
    }
    return nil, warnings
}

</code></pre>
<p>And the test:</p>
<pre class=""lang-golang prettyprint-override""><code>func TestWhenItsNotPossibleToFetchTheSecrets_ThenAnErrorIsReturned(t *testing.T) {
    kubeClient := getKubeClient()
    kubeClient.CoreV1().(*fakecorev1.FakeCoreV1).
        PrependReactor(&quot;list&quot;, &quot;secret&quot;, func(action testingk8s.Action) (handled bool, ret runtime.Object, err error) {
            return true, &amp;v1.SecretList{}, errors.New(&quot;error listing secrets&quot;)
        })
    r := getRefresher(kubeClient)


    err, warnings := r.RefreshNamespace(context.Background(), &quot;target-ns&quot;)


    require.Error(t, err, &quot;an error should have been raised&quot;)
}
</code></pre>
<p>However, when I run the test I'm getting a <code>nil</code> error. Am I doing something wrong?</p>
",https://stackoverflow.com/questions/69740891/mocking-errors-with-client-go-fake-client,"['unit-testing', 'go', 'testing', 'kubernetes', 'client-go']",1150,True,1,1
Does Python unittest reset the setUp function in each call?,"<p>I am currently doing unit testing on a class</p>
<pre><code>class Employee:
    &quot;&quot;&quot;Class to define an employee&quot;&quot;&quot;

    def __init__(self, fname, lname, salary):
        self.fname = fname
        self.lname = lname 
        self.salary = salary 

    def give_raise(self, number=5000):
        self.salary += number
</code></pre>
<p>I am writing tests that will test the methods I have defined in my class. The first will increase the employees salary by the default function parameter and the second a custom</p>
<pre><code>from employee import Employee
import unittest

class TestEmployee(unittest.TestCase):
    &quot;&quot;&quot;Test the employee class&quot;&quot;&quot;

    def setUp(self):
        &quot;&quot;&quot;
        Create employees and test the results
        &quot;&quot;&quot;
        self.dave = Employee(&quot;dave&quot;, &quot;stanton&quot;, 20000)

    def test_default_raise(self):
        self.dave.give_raise()
        self.assertEqual(25000, self.dave.salary)
        print(self.dave.salary)
        

    def test_custom_raise(self):
        self.dave.give_raise(10000)
        self.assertEqual(30000, self.dave.salary)
        print(self.dave.salary)


if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>I am using a SetUp function to instantiate an instance of the employee class.</p>
<p>My question is does the value of self.dave.salary get reset to the base value on each method call?</p>
<pre><code>30000
.25000
.
----------------------------------------------------------------------
Ran 2 tests in 0.000s
</code></pre>
<p>I would expect the value of the second test to be 35000</p>
",https://stackoverflow.com/questions/70103466/does-python-unittest-reset-the-setup-function-in-each-call,"['python', 'unit-testing', 'python-unittest']",538,True,1,1
Dependency injection with service layer,"<p>I have implemented a service layer in my MVC application that handles all the CRUD business logic. My question is, does this way of injecting dependency of context and other instances into the service class is a good approach or there is an alternative way of doing it ?</p>
<pre><code>public class Admin: Controller
{
  private readonly AdminServices _adminServices;
  
  public Admin(ApplicationDbContext context, UserManager&lt;IdentityUser&gt; userManager, RoleManager&lt;IdentityRole&gt; roleManager)
    _adminServices = new AdminServices(context, userManager, roleManager);
  }
}

public class AdminServices{ 
  public AdminServices(ApplicationDbContext context, UserManager&lt;IdentityUser&gt; userManager, RoleManager&lt;IdentityRole&gt; roleManager)
  {
    // code
  }
}
</code></pre>
<p>PS: I don't use interfaces for the service layer due to the overhead it brings to maintain but also because I won't be using unit testing or do other fancy stuff with the application in the long term.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/69990226/dependency-injection-with-service-layer,"['c#', 'asp.net-core-mvc', 'asp.net-core-3.1']",509,False,0,0
Validate ElasticSearch data with the mapping,"<p>For unit testing purpose, I would like to reuse the ElasticSearch mapping in order to validate a sample of data and make sure the structure remains consistent.</p>
<p>Is there a solution like what <a href=""https://github.com/justinrainbow/json-schema"" rel=""nofollow noreferrer"">we could have to validate a json schema</a> ?</p>
<p>I don't want to use a real elasticsearch, make an insert request and check the integrity of the data after.
And I don't want to be too decorrelated from my source code and create a json schema from the ES mapping just for my tests.</p>
<p>Any ideas ?</p>
",https://stackoverflow.com/questions/67333895/validate-elasticsearch-data-with-the-mapping,"['php', 'validation', 'elasticsearch', 'testing', 'foselasticabundle']",187,False,3,0
Returning anonymous object from function and infering type in Kotlin,"<p>I'm coming from Java and am new to Kotlin. I am trying to create declarative DSL for unit testing purposes. Here is my attempt to create generic builder method to construct any model object with declarative syntax.</p>
<pre><code>fun &lt;T&gt; having(t: Class&lt;T&gt;) = object {
    infix fun with(fn: T.() -&gt; Unit) = t.newInstance().apply(fn)
}

fun test() {

    having(Pizza::class.java) with {
        size = Size.NORMAL
        cheese = Cheese.MOZARELLA
    }
}
</code></pre>
<p>However, the <code>having</code> function returns <code>Any</code> type with unresolved reference to <code>with</code> function. I could extract the anonymous object to it's own class to make it compile, but it would feel redundant. Is it possible to resort on the type inference with functions returning an <code>object</code> instances?</p>
<p>Also, I'm not sure if I'm using generics the idiomatic way here.</p>
",https://stackoverflow.com/questions/70196349/returning-anonymous-object-from-function-and-infering-type-in-kotlin,"['unit-testing', 'kotlin', 'generics', 'dsl']",769,True,3,2
Jest Enzyme - Code Coverage for a callback function from third party Library,"<p>I have a React application, and I am using Jest and Enzyme for unit testing the application. I am using a third-party library that returns a callback function. I am struggling to complete code coverage for the code inside the callback function. I tried mocking and spyOn but couldn’t use it to my use case. Can I get any suggestions on how to approach this?</p>
<p>I have created a sample code for reference</p>
<p><a href=""https://codesandbox.io/s/xenodochial-kilby-obnmt"" rel=""nofollow noreferrer"">https://codesandbox.io/s/xenodochial-kilby-obnmt</a></p>
<p>someLibrary.js</p>
<pre><code>export function getUserContext(callback) {
  var context = {
    userName: &quot;TestUser&quot;,
    locale: &quot;en-us&quot;
  };
  callback(context);
}

</code></pre>
<p>MyApp.js</p>
<pre><code>
componentDidMount() {
    someLib.getUserContext((context) =&gt; {
      //want to cover these below lines
      //and some other codes inside this callback function
      this.setState({
        userName: context.userName,
        locale: context.locale
      });
      //some other code to cover
    });
  }

</code></pre>
<p>App.test.js - as of now</p>
<pre><code>describe(&quot;App Component&quot;, () =&gt; {
  const wrapper = shallow(&lt;App /&gt;);
  //const layout = wrapper.instance();
  it(&quot;renders the component&quot;, () =&gt; {
    expect(wrapper.exists()).toBe(true);
  });
  it(&quot;sets the user context&quot;, () =&gt; {
    //not sure what to write here inorder to cover
  });
});
</code></pre>
",https://stackoverflow.com/questions/68102090/jest-enzyme-code-coverage-for-a-callback-function-from-third-party-library,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",1354,True,0,1
How to work with a nested function in redux action unit test,"<p>I'm trying to learn unit testing for testing our react application. I'm starting with actions.</p>
<p>I have a function, the object that returned also has a nested function.</p>
<p>hello.actions.js</p>
<pre><code>export function loadData(request){
    return {
        type: types.TEST_API,
        coreApi: {
            body: request,
            success: (response) =&gt; [receiveData(response), update(response)]
        }
    }
}

export function receiveData(request){...}
export function update(request){...}
</code></pre>
<p>What I tried to do on returning success, it'll be <code>() =&gt; jest.fn()</code></p>
<p>helloActions.test.js</p>
<pre><code>describe(&quot;Action: hello&quot;, () =&gt; {

       const payload = {
           request: &quot;request&quot;
       }

       const expectedAction = {
           type: types.TEST_API,
           coreApi: {
               body: request,
               success: () =&gt; jest.fn()
           } 
       }


       expect(actions.loadData(payload.request)).toEqual(expectedAction);
    });
});
</code></pre>
<p>If I remove the success line from both test and action, it works. So I've pin pointed it to be something wrong with the success line. Any insight would be greatly appreciated. I even tried to push <code>success: (response) =&gt; [receiveData(response), update(response)]</code> in the unit test but that fails as well.</p>
",https://stackoverflow.com/questions/67236356/how-to-work-with-a-nested-function-in-redux-action-unit-test,"['javascript', 'reactjs', 'unit-testing', 'redux', 'jestjs']",102,True,-1,1
Angular unit testing click event which executes only navigateByUrl using Jasmin &amp; Karma,"<p>How to write unit test case for below click event in angular using Jasmin &amp; Karma</p>
<pre><code>     onClickCancel(): any {
        this.router.navigateByUrl('login');
      }
</code></pre>
<p>How to write unit test case for below click event which open material dialog in angular using Jasmin &amp; Karma. I am new to Angular.</p>
<pre><code>  addNewRole(): any {
    const dialogRef = this.dialog.open(AddNewRoleComponent, {
      width: '450px', disableClose: true
    });
    dialogRef.afterClosed().subscribe(() =&gt; {
      this.getRoles();
    });
  }

  editRole(roleData): any {
    const dialogRef = this.dialog.open(AddNewRoleComponent, {
      width: '450px', disableClose: true, data: roleData
    });
    dialogRef.afterClosed().subscribe(() =&gt; {
      this.getRoles();
    });
  }
</code></pre>
<p>This is my approach for unit testing of opening dialog</p>
<pre><code>  it('should open the add role component on click of addNewRole', () =&gt; {
    component.addNewRole();
    expect(dialog.open.calls.count()).toBe(1);
  });
</code></pre>
<p>My approach of opening dialog works properly for other test cases. But here - <strong>TypeError: Cannot read property 'count' of undefined</strong> error is thrown.</p>
<p>It would be a great pleasure if someone suggested me. Thank you !!!</p>
",https://stackoverflow.com/questions/68919030/angular-unit-testing-click-event-which-executes-only-navigatebyurl-using-jasmin,"['angular', 'typescript', 'jasmine', 'karma-jasmine']",393,False,0,1
How can I fake mutex context in C/C++?,"<p>I've been reading through and attempting to apply <a href=""https://interrupt.memfault.com/blog/unit-testing-basics"" rel=""nofollow noreferrer"">Tyler Hoffman's C/C++ unit testing strategies</a>.</p>
<p>He offers the following as a way to fake a mutex:</p>
<pre><code>#define NUM_MUTEXES 256

typedef struct Mutex {
  uint8_t lock_count;
} Mutex;

static Mutex s_mutexes[NUM_MUTEXES];
static uint32_t s_mutex_index;

// Fake Helpers

void fake_mutex_init(void) {
  memset(s_mutexes, 0, sizeof(s_mutexes));
}

bool fake_mutex_all_unlocked(void) {
  for (int i = 0; i &lt; NUM_MUTEXES; i++) {
    if (s_mutexes[i].lock_count &gt; 0) {
      return false;
    }
  }
  return true;
}

// Implementation

Mutex *mutex_create(void) {
  assert(s_mutex_index &lt; NUM_MUTEXES);
  return &amp;s_mutexes[s_mutex_index++];
}

void mutex_lock(Mutex *mutex) {
  mutex-&gt;lock_count++;
}

void mutex_unlock(Mutex *mutex) {
  mutex-&gt;lock_count--;
}
</code></pre>
<p>For a module that has functions like:</p>
<pre class=""lang-c prettyprint-override""><code>#include &quot;mutex/mutex.h&quot;

static Mutex *s_mutex;

void kv_store_init(lfs_t *lfs) {
  ...
  s_mutex = mutex_create();
}

bool kv_store_write(const char *key, const void *val, uint32_t len) {
  mutex_lock(s_mutex); // New
  ...
  mutex_unlock(s_mutex); // New
  analytics_inc(kSettingsFileWrite);
  return (rv == len);
}
</code></pre>
<p>After being setup in a test like:</p>
<pre><code>TEST_GROUP(TestKvStore) {
  void setup() {
    fake_mutex_init();
    ...
  }
  ...
}
</code></pre>
<p>I'm confused about a couple things:</p>
<ol>
<li>How does <code>fake_mutex_init()</code> cause methods using <code>mutex_lock</code> and <code>mutex_unlock</code> to use the fake lock and unlock?</li>
<li>How does this actually fake mutex locking? Can I produce deadlocks with these fakes? Or, should I just be checking the lock count in my tests?</li>
</ol>
",https://stackoverflow.com/questions/70499727/how-can-i-fake-mutex-context-in-c-c,"['c', 'unit-testing', 'mutex']",232,True,0,1
Jest testing Vue lifecycle or async method doesn&#39;t await for result in unit-testing,"<p>I'm trying to implement unit testing with Jest for a Vue component which on created() lifecycle calls a function which has axios who runs async.
The thing is, the created is being triggered, but the value of the object that sits in the component data section won't show it's new value. (remains undefined, tested also when initialized with some other value then undefined)</p>
<p>I've used many solutions that was offered around here but nothing was 100% accurate to the situation I'm dealing with.</p>
<p>Products component:</p>
<pre><code>   data() {
      return {
        products: undefined,
        countries: undefined,
        fields: undefined,
        selectedItem: undefined,
        alert: undefined,
     };
  },
  methods: {
    async getProducts() {
      try {
        let res = await axios.get(&quot;http://localhost:5000&quot;);
        this.products = res.data.products;
        this.countries = res.data.countries;
        this.fields = Object.keys(this.products[0]).splice(1);
        this.fields.push({ key: &quot;Edit&quot;, label: &quot;Click &amp; Edit&quot; });
        } 
        catch (error) {
        this.toggleAlert(true, &quot;Failed to retrieve data from server&quot;);
        console.log(error);
        }
    },
  }
  created() {
    this.getProducts();
  }
</code></pre>
<p>testfile:</p>
<pre><code>// create an extended `Vue` constructor
   const localVue = createLocalVue();
// install plugins as normal 
   localVue.use(BootstrapVue);
   describe(&quot;Testing Products component:&quot;, () =&gt; {
       test(&quot;checks the incoming data from api&quot;, async () =&gt; {
          const wrapper = shallowMount(Products, { localVue });
          await flushPromises();
          console.log(wrapper.vm.$data.products, &quot;products&quot;); //prints undefined instead of an array
          expect(wrapper.vm.$data.products).not.toBe(undefined);
  });
});

</code></pre>
",https://stackoverflow.com/questions/68517663/jest-testing-vue-lifecycle-or-async-method-doesnt-await-for-result-in-unit-test,"['vue.js', 'unit-testing', 'jestjs']",307,False,0,0
Is it possible to do nested spying with Mockito?,"<p>Let's assume I have an object like this:</p>
<pre><code>public ClassA() {
   public void start() {
      ...
      ClassB something = getSomeStuff();
      ...
   }
  
   protected ClassB getSomeStuff() {
      return new ClassB(render, response);
   }
}
</code></pre>
<p>Then I'm trying to do some unit-testing like this where I do a spy on a method-call on a spied object:</p>
<pre><code>@Spy private ClassA classA;
@Mock private ClassC classC;
...
@Test 
void test1() {
    ClassB classB = spy(classA.getSomeStuff());
    doReturn(classC).when(classB).getResults();

    classA.start();
}
</code></pre>
<p>When I run this test and it comes down to this last line, I can see in my debugger that it is not returning classC.</p>
<p>Is this because it is not possible to do nested spying? Or is somehting wrong in my setup? Or should I approach this differently?</p>
<hr />
<p>Details:</p>
<ul>
<li>junit: 5.7.0</li>
<li>mockito: 3.12.4</li>
</ul>
",https://stackoverflow.com/questions/70047132/is-it-possible-to-do-nested-spying-with-mockito,"['java', 'mocking', 'mockito']",308,False,0,1
Xamarin UI Testing on Visual Studio Community 2019,"<p>I've been trying for hours trying to get the Xamarin UI Testing project type to show up by installing various visual studio packages, as well as attempting to add the Xamarin.UITesting nuget package to my existing unit testing project. I've consulted dozens of guides on the subject and read bug reports and stack overflow questions.</p>
<p>I can't find it definitively stated anywhere, but I think I've finally decided that I need the enterprise version of Visual Studio. Can anyone just confirm that for me?</p>
",https://stackoverflow.com/questions/66844734/xamarin-ui-testing-on-visual-studio-community-2019,"['visual-studio', 'unit-testing', 'xamarin', 'testing', 'automated-tests']",41,True,0,1
How do you cover correctly branch statements?,"<p>Recently, I've come across a problem multiple times about unit testing in a front-end environment (Vue.JS v2, jest) but I think it's more related to general use cases. This problem concerns the branch coverage of a function.</p>
<p>Let's say you've got the following snippet (I did not add more nested if/else statements for clarity sake).</p>
<pre><code>function doSomeNormalStuff(p: Person) {
    const isAdult = p.age &gt; 17;
    
    if (isAdult) {
      walkWithTheDog();
      getWage();
    } else {
       playWithToys();
       driveSmallCar();
    }
}

</code></pre>
<p>And the following unit test snippet:</p>
<pre><code>describe('doSomeNormalStuff', () =&gt; {
  describe('isAdult', () =&gt; {
    const p: Person = { name: 'Michael', age: 18 };
    beforeEach(() =&gt; {
      doSomeNormalStuff(p);
    });

    it('Should call the walkWithTheDog function', () =&gt; {
      expect(walkWithTheDog).toHaveBeenCalledTimes(1);
    });

    it('Should call the getWage function', () =&gt; {
      expect(getWage).toHaveBeenCalledTimes(1);
    });

    it('Should not call the playWithToys function', () =&gt; {
      expect(playWithToys).not.toHaveBeenCalled();
    });

    it('Should not call the driveSmallCar function', () =&gt; {
      expect(driveSmallCar).not.toHaveBeenCalled();
    });
  });

  describe('isChild', () =&gt; {
    const p: Person = { name: 'John', age: 5 };
    beforeEach(() =&gt; {
      doSomeNormalStuff(p);
    });

    it('Should call the playWithToys function', () =&gt; {
      expect(playWithToys).toHaveBeenCalledTimes(1);
    });

    it('Should call the driveSmallCar function', () =&gt; {
      expect(driveSmallCard).toHaveBeenCalledTimes(1);
    });

    it('Should not call the walkWithTheDog function', () =&gt; {
      expect(walkWithTheDog).not.toHaveBeenCalled();
    });

    it('Should not call the getWage function', () =&gt; {
      expect(getWage).not.toHaveBeenCalled();
    });
  }); 
})

</code></pre>
<p>Do you consider the &quot;not.toHaveBeenCalled()&quot; calls necessary ? Or is it considered as  too much testing (or bad practice) ?</p>
<p>Thanks for your answers.</p>
",https://stackoverflow.com/questions/70079277/how-do-you-cover-correctly-branch-statements,"['typescript', 'unit-testing', 'jestjs', 'conditional-statements', 'test-coverage']",110,False,0,0
Using gMock for function call within function,"<p>I am unit testing a bit of code for coverage and am curious how I should handle this given situation.</p>
<p>I can't write the exact code here, so i'm using some placeholders.</p>
<pre><code>TEST_F(testing, testingFunctionCall)
{
   bool result = FunctionCall();
   EXPECT_EQ(true, result);
}
</code></pre>
<p>Now the function call is in another file, and it requires another function to return a number for <code>FunctionCall()</code> to return true.</p>
<pre><code>// In a seperate file
bool FunctionCall()
{
   int number = GettingNumberFromSystemState();
   if(number &gt; A_CERTAIN_VALUE)
   {
      return  true;
   }else{
      return false;
   }
}
}

</code></pre>
<p>The function <code>GettingNumberFromSystemState()</code> will always return a false number because the firmware is not running on the hardware, so how would I create a mock function for <code>GettingNumberFromSystemState()</code> to always return the number I want?</p>
",https://stackoverflow.com/questions/67875184/using-gmock-for-function-call-within-function,"['c++', 'c', 'googletest', 'googlemock']",260,False,0,0
MockMvc fails when request body is empty for Put and Post requests,"<p>I'm pretty new to unit testing with Spring and can't figure out why I can't MockMvc doesn't work with post when the request body is empty. The error I'm getting: <code>java.lang.AssertionError:Response status expected:&lt;200&gt; but was &lt;404&gt;</code>. I've gotten the get endpoint to work correctly so I think the rest controller is wired correctly. I'm just wondering how to write a unit test when a POST or PUT request lacks a body, but has params. I've tried different variations of the below such as chaining <code>.contentType(MediaType.ALL).content(&quot;&quot;)</code>, but I always get the same error.</p>
<p>UnitTest.java</p>
<pre><code>@Test
public void shouldCreateSomething() throws Exception{
    mockMvc.perform(post(somethingUri).param(idParameter, fieldParameter))
    .andExpect(status().is(200));
}
</code></pre>
<p>RestAPI.java</p>
<pre><code>@Operation(summary = &quot;Updates something&quot;, responses = {
        @ApiResponse(responseCode = &quot;200&quot;, description = &quot;Something was updated&quot;),
        @ApiResponse(responseCode = &quot;406&quot;, description = &quot;Something was invalid&quot;) })
@PutMapping(value = somethingUri)
public void updateSomething(
        @Parameter(description = &quot;Something's id&quot;, required = true) @RequestParam String id,
        @Parameter(description = &quot;Something's name to be updated&quot;, required = true) @RequestParam String name)
{
        System.out.println(&quot;please work&quot;);
}  
</code></pre>
",https://stackoverflow.com/questions/68137983/mockmvc-fails-when-request-body-is-empty-for-put-and-post-requests,"['spring', 'unit-testing', 'mockmvc']",468,False,0,1
How to send @Autowired field in @InjectMocks,"<p>I am unit testing a class AuthController, which has this constructor</p>
<pre><code>@Autowired
public AuthController(DynamicBeanFactory beanService) {
   Sysout(beanService); //here null is coming - Point-1
}
</code></pre>
<p>In Test Class, I have done:</p>
<pre><code>@Mock
DynamicBeanFactory beanService;

@InjectMocks
AuthController authController(beanService);

- Below @Test are there -
</code></pre>
<p>Now when I am running this :</p>
<p>the value of beanService inside constructor above at <code>point-1</code> is coming <strong>null</strong>.</p>
<hr />
<p>Also, when I am doing @Autowired at place of @InjectMocks it works.</p>
<blockquote>
<p>Below I have shared some questions people asked.</p>
</blockquote>
<p><strong>Q) What is AuthController?</strong></p>
<p>A) It's just a class having that constructor I have shared above.</p>
<p><strong>Q) What is Dynamic Bean Factory ?</strong></p>
<p>A) It's a Service class something like this below :</p>
<pre><code>@Service
public class DynamicBeanFactory

   @Autowired
   public DynamicBeanFactory(BeanFactory beanFactory) {
        this.beanFactory = beanFactory)
   }
}
</code></pre>
",https://stackoverflow.com/questions/66366150/how-to-send-autowired-field-in-injectmocks,"['java', 'unit-testing', 'mocking', 'mockito', 'junit5']",87,False,-1,2
NativeScript Angular + Karma - ReferenceError: window is not defined,"<p>So I decided to add unit testing to my NS7/NG11 app, followed instructions from NS website and got to the point where the app would start but the screen is blank (all white).</p>
<p>Initialized tests with <code>ns test init</code>, manually updated <code>karma-webpack</code> in <code>package.json</code> to v <code>5.0.0-alpha.5</code> as the default one had a bug that was fixed and should be released soon.</p>
<p>Command used to start testing is: <code>ns test run --emulator</code></p>
<p>Testing in <code>Tabs</code> template with Angular. When running <code>ns run ios --emulator</code> the runs just fine and is usable.</p>
<p>Below is my <code>package.json</code>:</p>
<pre><code>{
  &quot;name&quot;: &quot;@nativescript/template-tab-navigation-ng&quot;,
  &quot;main&quot;: &quot;main.js&quot;,
  &quot;displayName&quot;: &quot;Tabs&quot;,
  &quot;templateType&quot;: &quot;App template&quot;,
  &quot;version&quot;: &quot;7.0.6&quot;,
  &quot;description&quot;: &quot;NativeScript Application&quot;,
  &quot;author&quot;: &quot;NativeScript Team &lt;oss@nativescript.org&gt;&quot;,
  &quot;license&quot;: &quot;SEE LICENSE IN &lt;your-license-filename&gt;&quot;,
  &quot;publishConfig&quot;: {
    &quot;access&quot;: &quot;public&quot;
  },
  &quot;keywords&quot;: [
    &quot;nstudio&quot;,
    &quot;nativescript&quot;,
    &quot;mobile&quot;,
    &quot;angular&quot;,
    &quot;{N}&quot;,
    &quot;tns&quot;,
    &quot;template&quot;,
    &quot;tab&quot;,
    &quot;navigation&quot;,
    &quot;category-general&quot;
  ],
  &quot;repository&quot;: &quot;&lt;fill-your-repository-here&gt;&quot;,
  &quot;homepage&quot;: &quot;https://github.com/NativeScript/nativescript-app-templates&quot;,
  &quot;bugs&quot;: {
    &quot;url&quot;: &quot;https://github.com/NativeScript/NativeScript/issues&quot;
  },
  &quot;scripts&quot;: {
    &quot;lint&quot;: &quot;tslint \&quot;src/**/*.ts\&quot;&quot;
  },
  &quot;dependencies&quot;: {
    &quot;@angular/animations&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/common&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/compiler&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/core&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/forms&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/platform-browser&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/platform-browser-dynamic&quot;: &quot;~11.0.0&quot;,
    &quot;@angular/router&quot;: &quot;~11.0.0&quot;,
    &quot;@nativescript/angular&quot;: &quot;~11.0.0&quot;,
    &quot;@nativescript/core&quot;: &quot;~7.1.0&quot;,
    &quot;@nativescript/theme&quot;: &quot;~2.3.0&quot;,
    &quot;@nativescript/unit-test-runner&quot;: &quot;^1.0.2&quot;,
    &quot;reflect-metadata&quot;: &quot;~0.1.12&quot;,
    &quot;rxjs&quot;: &quot;^6.6.0&quot;,
    &quot;zone.js&quot;: &quot;~0.11.1&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@angular/compiler-cli&quot;: &quot;~11.0.0&quot;,
    &quot;@nativescript/ios&quot;: &quot;7.1.0&quot;,
    &quot;@nativescript/webpack&quot;: &quot;~4.0.0&quot;,
    &quot;@ngtools/webpack&quot;: &quot;~11.0.0&quot;,
    &quot;@types/jasmine&quot;: &quot;3.6.2&quot;,
    &quot;codelyzer&quot;: &quot;~6.0.0&quot;,
    &quot;karma&quot;: &quot;6.0.0&quot;,
    &quot;karma-jasmine&quot;: &quot;4.0.1&quot;,
    &quot;karma-nativescript-launcher&quot;: &quot;0.4.0&quot;,
    &quot;karma-webpack&quot;: &quot;5.0.0-alpha.5&quot;,
    &quot;node-sass&quot;: &quot;^4.14.1&quot;,
    &quot;tslint&quot;: &quot;~6.1.3&quot;,
    &quot;typescript&quot;: &quot;~4.0.0&quot;
  },
  &quot;private&quot;: &quot;true&quot;,
  &quot;readme&quot;: &quot;NativeScript Application&quot;
}

</code></pre>
<p>and here's the console output when I run <code>ns test ios --emulator</code>:</p>
<pre><code>Webpack compilation complete. Watching for file changes.
Webpack build done!
Updating runtime package.json with configuration values...
Project successfully prepared (ios)
Successfully transferred all files on device DF60258A-B86C-4E93-BCEF-4E2ED154E007.
Restarting application on device DF60258A-B86C-4E93-BCEF-4E2ED154E007...
Successfully synced application org.nativescript.karmans7 on device DF60258A-B86C-4E93-BCEF-4E2ED154E007.
(RunningBoardServices) [com.apple.runningboard:connection] Identity resolved as application&lt;org.nativescript.karmans7&gt;
CONSOLE LOG: NSUTR: fetching http://127.0.0.1:9877/context.json
CONSOLE LOG: NSUTR: fetching http://172.16.1.6:9877/context.json
CONSOLE LOG: NSUTR: fetching http://172.16.1.4:9877/context.json
CONSOLE LOG: NSUTR: found karma at 127.0.0.1
CONSOLE LOG: NSUTR: found karma at 172.16.1.4
CONSOLE LOG: NSUTR: found karma at 172.16.1.6
CONSOLE LOG: NSUTR: connecting to karma at http://127.0.0.1:9877
CONSOLE LOG: ReferenceError: window is not defined
</code></pre>
",https://stackoverflow.com/questions/65791937/nativescript-angular-karma-referenceerror-window-is-not-defined,"['angular', 'nativescript', 'karma-runner', 'nativescript-angular', 'karma-webpack']",848,True,2,2
How should I correctly construct my unit test in Laravel,"<p>I am quite new to unit testing and could do with a bit of guidance. I am trying to write a simple unit test using the Factory pattern in Laravel and phpunit for an application that allows you to add Companies to a database.</p>
<p>I have a Company Model <code>Company.php</code>, a Factory class which uses it <code>CompanyFactory.php</code>, and finally the unit test itself <code>CompaniesTest.php</code>.</p>
<p><code>Models/Company.php</code></p>
<pre><code>namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    use HasFactory;
    protected $table = 'companies';
    protected $fillable = [
        'name',
        'email'
    ];
}
</code></pre>
<p><code>Database/Factories/CompanyFactory.php</code></p>
<pre><code>namespace Database\Factories;

use App\Models\Company;
use Illuminate\Database\Eloquent\Factories\Factory;

class CompanyFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Company::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' =&gt; $this-&gt;faker-&gt;name,
            'email' =&gt; $this-&gt;faker-&gt;email,
            'created_at' =&gt; now(),
            'updated_at' =&gt; now(),
        ];
    }
}
</code></pre>
<p><code>Tests/Feature/CompaniesTest.php</code></p>
<pre><code>namespace Tests\Unit;
        
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Models\Company;
use Tests\TestCase;
use Illuminate\Support\Str;
use Illuminate\Foundation\Testing\WithFaker;

class CompanyTest extends TestCase
{
    use WithFaker, DatabaseTransactions;

    public function createCompany($name = NULL)
    {
        if ($name == NULL) $name = Str::random(6);

        $company = Company::factory()-&gt;create([
            'name' =&gt; 'TestName_'.$name
        ]);

        return $company-&gt;id;
    }


    /** @test */
    public function company_can_be_created()
    {
        $name = Str::random(6);

        //Create a company
        $company_id = $this-&gt;createCompany($name);

        //Check whether the company name exists in the database
        $this-&gt;assertDatabaseHas('companies', [
            'name' =&gt; 'TestName_'.$name
        ]);
    }
}
</code></pre>
<p>The test seems to work, but it feels like I might have over-complicated it and probably not followed the correct conventions.</p>
<p>What would be a better way to structure it?</p>
",https://stackoverflow.com/questions/68271050/how-should-i-correctly-construct-my-unit-test-in-laravel,"['php', 'unit-testing', 'phpunit', 'laravel-8', 'factory-pattern']",1797,True,2,1
Mock Internal dependencies of unit while Unit testing?,"<p>I'm writing unit tests for a NestJs application (Node.js). Consider the classes below</p>
<pre><code>class CatService {

  constructor(private walkService:WalkService){
    //....
  }

  public function doSomething(){
    this.walkService.walk();
    this.doThis();
    this.doThat();
  }

  public function doThis(){
    //....
  }

  private function doThat(){
    //....
  }

}
</code></pre>
<p>Now the question is if I want to write test for this <code>CatService</code> Class, Which dependencies would be need to mock? Also would we be testing the <code>doThat</code> method <em>keeping in mind it is private function</em>?</p>
<p>while testing <code>doSomething</code></p>
<p><code>WalkService</code> dependency would be mocked for sure.</p>
<p>but what about <code>doThis</code> &amp; <code>doThat</code>?</p>
<p><em>Summary</em></p>
<p>Should we mock methods of the same class used by the method which is being tested?</p>
<p>If No then would it be unit testing? since a unit is a function here.</p>
",https://stackoverflow.com/questions/69017044/mock-internal-dependencies-of-unit-while-unit-testing,"['javascript', 'unit-testing', 'jestjs', 'nestjs']",146,False,1,0
How do I test event trigger cloud function?,"<p>I want to do unit testing on cloud functions, however, the function itself is an event trigger function that contains some helper functions. I want to test those helper functions as well. Here is the code sample</p>
<pre><code>import os
from google.cloud import vision
from google.cloud import storage


def face_detection(uri):
    &quot;&quot;&quot;
    This function detects the faces in the file
    located in Google Cloud Storage or the web
    Args:
        uri: the file located in Google Cloud Storage or the web
    returns:
        None: Prints the likelihood of the face expressions
        or returns an errors resonse in string format
    &quot;&quot;&quot;

def trigger_event(event, context):
    &quot;&quot;&quot;
    Background Cloud Function to be triggered by Cloud Storage.
    This generic function logs relevant data when a file is changed.
    Args:
        event (dict):  The dictionary with data specific to this type of event.
                        The `data` field contains a description of the event in
                        the Cloud Storage `object` format described here:
                        https://cloud.google.com/storage/docs/json_api/v1/objects#resource
        context (google.cloud.functions.Context): Metadata of triggering event.
    Returns:
        None; the output is written to Stackdriver Logging
    &quot;&quot;&quot;

    bucket_name = event[&quot;bucket&quot;]
    source_img = event[&quot;name&quot;]
    tmp_download_path = f&quot;/tmp/{source_img}&quot;

    try:
        download_image(bucket_name, source_img, tmp_download_path)
        print(f&quot;Image {source_img} downloaded to {tmp_download_path}&quot;)
        # currenlty this makes sure there's one person
        # in the frame and prints a few other details
        face_detection(tmp_download_path)
    except Exception:
        pass
    finally:
        if os.path.isfile(tmp_download_path):
            os.remove(tmp_download_path)
        else:
            print(&quot;Error: %s file not found&quot; % tmp_download_path)


def download_image(bucket_name, source_blob_name, destination_file_name):
    &quot;&quot;&quot;Downloads the specified image from cloud storage
    Args:
        bucket_name = &quot;your-bucket-name&quot;
        source_blob_name = &quot;image-name&quot;
        destination_file_name = &quot;local/path/to/file&quot;
    Returns:
        Local path to downloaded image
    &quot;&quot;&quot;

def upload_processed_images(bucket_name, source_file_folder):
    &quot;&quot;&quot;Uploads images to the bucket.
    Args:
        bucket_name = &quot;your-bucket-name&quot;
        source_file_folder = Path to the folder that contains
                                all the processed images
    Returns:
        None;
    &quot;&quot;&quot;

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    for file_name in os.listdir(source_file_folder):
        blob = bucket.blob(file_name)
        blob.upload_from_filename(os.path.join(source_file_folder, file_name))

        print(&quot;File {} uploaded to {}.&quot;.format(file_name, bucket_name))
</code></pre>
<p>For example, if I want to test if the function upload_processed_images is actually working. I want it to be an unit test. Should I test locally? If the function is tested locally, will it connect to GCP with correct storage.Client()? Or I need to test it on the GCP platform?</p>
<p>Thanks for any help.</p>
",https://stackoverflow.com/questions/66297468/how-do-i-test-event-trigger-cloud-function,"['python', 'google-cloud-platform', 'google-cloud-functions']",1018,True,1,1
Unit testing in laravel using filesystems,"<p>I'm doing unit testing using the filesystems config. I want to map my file system disk to a testing directory where I will put my files(JSON, Excel, txt) to be used by the application for testing purposes. I don't want to use fake directories as I need to put the file in the 'import' location.</p>
<p>filesystems.php:</p>
<pre><code>'disks' =&gt; [
    'import' =&gt; [
        'driver' =&gt; 'local',
        'root' =&gt; '/import/clientname',
        'visibility' =&gt; 'private'
    ],
];
</code></pre>
<p>In the application, here is the function which i want to test:</p>
<pre><code>public function importFile(){
    $filesystem = Storage::disk('import');
    
    ...
}
</code></pre>
<p>The solution I was thinking is to use this location for my testing:</p>
<p><a href=""https://i.stack.imgur.com/JT5lt.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JT5lt.png"" alt=""enter image description here"" /></a></p>
<p>Is there a way to implement this solution?</p>
",https://stackoverflow.com/questions/66865458/unit-testing-in-laravel-using-filesystems,"['laravel', 'unit-testing', 'phpunit', 'filesystems']",702,True,1,1
Android Unit Test Mockito returns null,"<p>I'm using Mockito for unit testing.</p>
<p>I want to test my usecase and with mock repository but there's some problem.</p>
<p>I had my repository's function returns arraylist by using mockito. (here's code below)</p>
<pre><code>`when`(mockRepository.searchByKeyword(request.auth, request.keyword)).thenReturn(myArrayList)
</code></pre>
<p>And created usecase with the mock repository. (here's code below too)</p>
<pre><code> val useCase = SearchProjectUseCase(
    mockRepository, coroutineRule.testDispatcher
 )
</code></pre>
<p>SearchUseCase's code below.</p>
<pre><code>class SearchProjectsUseCase(
    private val projectRepository: ProjectRepository,
    coroutineDispatcher: CoroutineDispatcher,
) : CoroutineUseCase&lt;SearchRequest, ArrayList&lt;Project&gt;&gt;(coroutineDispatcher) {

    override suspend fun execute(parameter: SearchRequest): Result&lt;ArrayList&lt;Project&gt;&gt; {
        return projectRepository.searchByKeyword(parameter.auth, parameter.keyword)
    }
}
</code></pre>
<p>Next, use this usecase like this.</p>
<pre><code>useCase.invoke(request)
</code></pre>
<p>And I want to check my mock repository worked. So I use mock verify and this failed.</p>
<pre><code>verify(mockRepository).searchByKeyword(request.auth, request.keyword)
</code></pre>
<p>But another test below succeeded</p>
<pre><code>mockRepository.searchByKeyword(request.auth, request.keyword)

verify(mockRepository).searchByKeyword(request.auth, request.keyword)
</code></pre>
<p>Should I call mock function directly?</p>
<p>Thank you for answer. and sorry for my English</p>
<p>All codes below</p>
<pre><code>@ExperimentalCoroutinesApi
@Test
fun `check SearchProjectUseCase returns correct data`() = coroutineRule.runBlockingTest {

    val mockRepository = mock(ProjectRepository::class.java)

    val request = SearchRequest(
        &quot;auth&quot;, &quot;keyword&quot;
    )

    `when`(mockRepository.searchByKeyword(request.auth, request.keyword)).thenReturn(projects)

    val useCase = SearchProjectsUseCase(
        mockRepository, coroutineRule.testDispatcher
    )

    //useCase.invoke(request) //failed

    mockRepository.searchByKeyword(request.auth, request.keyword) //succeeded

    verify(mockRepository).searchByKeyword(request.auth, request.keyword)
}
</code></pre>
",https://stackoverflow.com/questions/65933661/android-unit-test-mockito-returns-null,"['android', 'mockito', 'android-testing', 'mockito-kotlin', 'android-unit-testing']",624,False,1,0
Testing react-lazyload in React testing library,"<p>I am unit testing a component that makes use of <code>react-lazyload</code> to lazyload stuff. While rendering in my unit test, I noticed that the <code>Lazyload</code> is not rendering the content and its placeholder is being shown. I tried using waitFor with async/await to wait for lazily loaded content to render in next tick cycle but it still fails and <code>screen.debug()</code> still shows the placeholder in the dom.</p>
<p>Is there any way I can test such a component? Here is what I tried:</p>
<pre><code>render(&lt;WrapperComponent /&gt;)
await waitFor(() =&gt; { 
  expect(screen.getByText('Lazily loaded text!')).toBeInTheDocument()
});

// source code
import LazyLoad from 'react-lazyload';
const WrapperComponent = () =&gt; {
  return (
    &lt;div&gt;
      &lt;LazyLoad placeholder=&quot;Loading...&quot; &gt;
        &lt;div&gt;Lazily loaded text!&lt;/div&gt;
      &lt;/LazyLoad&gt;
    &lt;/div&gt;
  );
}
</code></pre>
<p>Lazily loaded content has a div with the text being expected above.</p>
",https://stackoverflow.com/questions/69172825/testing-react-lazyload-in-react-testing-library,"['reactjs', 'jestjs', 'react-testing-library', 'react-lazy-load']",834,True,1,3
Capture QEMU Semihosted I/O,"<p>For unit testing purposes, I want to be able to run a bare-metal binary with qemu and capture it's output.</p>
<p>Sample file:</p>
<pre><code>#include &lt;stdio.h&gt;
#include &lt;stdint.h&gt;

static void qemu_exit() {
  register uint32_t r0 __asm__(&quot;r0&quot;);
  r0 = 0x18;
  register uint32_t r1 __asm__(&quot;r1&quot;);
  r1 = 0x20026;
  __asm__ volatile(&quot;bkpt #0xAB&quot;);
}

int main(void) {
  puts(&quot;This is some example text that I want to capture&quot;);

  qemu_exit();

  return 0;
}
</code></pre>
<p>Running with:</p>
<pre><code>qemu-system-gnuarmeclipse --nographic --no-reboot \
  --board STM32F4-Discovery --mcu STM32F429ZI \
  --semihosting-config enable=on,target=native \
  --image &lt;binary&gt;
</code></pre>
<p>Displayed to the console is:</p>
<pre><code>QEMU 2.8.0-13 monitor - type 'help' for more information
(qemu) This is some example text that I want to capture
</code></pre>
<p>This 'example text' is generated within QEMU and so redirecting stdout to a file does not capture it (only: <em>QEMU 2.8.0-13 monitor - type 'help' for more information
(qemu)</em>). Looking at the available qemu logging options <code>-d help</code> does not offer anything as far as I can see.</p>
<p><strong>EDIT</strong></p>
<p>A hacky solution is to use <a href=""http://manpages.ubuntu.com/manpages/trusty/en/man1/script.1.html"" rel=""nofollow noreferrer"">script</a> to capture terminal session:
<code>script --quiet --command &lt;qemu-shell-script-wrapper&gt;</code></p>
",https://stackoverflow.com/questions/70357970/capture-qemu-semihosted-i-o,"['arm', 'stm32', 'qemu', 'semihosting']",426,True,1,1
CameraX unit testing Android,"<p>I`m begginer in unit testing. The more I read, the less I understand what to do.
I'm trying to write unit tests for the cameraX, but I'm having trouble figuring it out. Here is my code now</p>
<p>My method:</p>
<pre><code>  fun startCamera() {
    val cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())
    cameraProviderFuture.addListener(
        {
            cameraProvider = cameraProviderFuture.get()

            val cameraSelector = CameraSelector.Builder()
                .requireLensFacing(cameraSelectorOption)
                .build()

            setCameraConfig(cameraProvider, cameraSelector)

        }, ContextCompat.getMainExecutor(requireContext())
    )
}
</code></pre>
<p>My unit test:</p>
<pre><code>@RunWith(MockitoJUnitRunner::class)
</code></pre>
<p>class CameraFragmentTest {</p>
<pre><code>@get:Rule
val permissionRule = GrantPermissionRule.grant(
    Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
    Manifest.permission.READ_EXTERNAL_STORAGE
)

@get:Rule
val activityRule: ActivityTestRule&lt;MainActivity&gt; = ActivityTestRule(MainActivity::class.java)

@Mock
lateinit var cameraProviderFuture: ProcessCameraProvider
lateinit var processCameraProvider: ProcessCameraProvider
private lateinit var mockContext: Context

@Test
fun useAppContext() {
    val context = ApplicationProvider.getApplicationContext() as Context
    assertEquals(&quot;com.android.example.studyprojectrnc&quot;, context.packageName)
}

@Test
fun testStartCamera() {

    //init
    val cameraFragment : CameraFragment = mock()

    //work
    val result = cameraFragment.startCamera()

    //assert
    Assert.assertEquals(result)
}
</code></pre>
<p>}</p>
<p>I would be very grateful for an example of test writing</p>
<p>Also maybe you can recommend what else I can read or any courses on testing (although a lot of information in my head is already making me crazy)</p>
<p>So... Please help me understand this т_т</p>
",https://stackoverflow.com/questions/70123690/camerax-unit-testing-android,"['android', 'unit-testing', 'testing', 'camera', 'android-camerax']",540,False,1,1
Why Jest unit test debugging doesn&#39;t stop at breakpoints in Chrome inspector?,"<p>Unit testing is very helpful and usually makes debugging easier, but only if your debugging tools work properly. I have worked in few <code>React</code> project and most of the time the Chrome debugger works well, but sometimes it refuses to stop on a particular breakpoint. Then I manually write <code>debugger;</code> instruction in the source code where I like the execution to stop and it usually works. Sometimes even this solution doesn't work and I'm forced to use old fasioned debugging methods like <code>console.log()</code>. Currently I have all these issues in a <code>React</code> project written in <code>Typescript</code> within <code>Ubuntu 16.04</code> development environment. They makes debugging very difficult. I start the unit test with <code>yarn test:debug</code> command, where <code>test:debug</code> calls the following line inside <code>package.json</code>:</p>
<pre><code>&quot;scripts&quot;: {
  &quot;test:debug&quot;: &quot;react-scripts --inspect test --runInBand --no-cache&quot;
}
</code></pre>
<p>I'm new to <code>Typescript</code> and am working on a legacy project which is not very well maintained. Could it be a matter of wrong configuration. Maybe something to deal with <code>webpack</code>? The debugger's console indicates that a mapping file is missing:</p>
<pre><code>DevTools failed to load source map: Could not load content for 
file:///path/to/project/node_modules/typescript/lib/typescript.js.map: System error: 
net::ERR_FILE_NOT_FOUND
</code></pre>
<p>Could it be that missing file the reason for the issues I experience? How to provice debugger with that missing file?</p>
<p><code>package.json</code> dependencies:</p>
<pre><code>&quot;@babel/preset-env&quot;: &quot;^7.14.4&quot;,
&quot;@babel/preset-react&quot;: &quot;^7.14.5&quot;,
&quot;@capacitor/app&quot;: &quot;^1.0.2&quot;,
&quot;@types/fs-extra&quot;: &quot;^9.0.3&quot;,
&quot;@types/jest&quot;: &quot;24.0.18&quot;,
&quot;@types/node&quot;: &quot;12.7.12&quot;,
&quot;@types/node-cron&quot;: &quot;^2.0.3&quot;,
&quot;@types/react&quot;: &quot;16.9.5&quot;,
&quot;@types/react-dom&quot;: &quot;16.9.1&quot;,
&quot;@types/styled-components&quot;: &quot;^5.1.7&quot;,
&quot;@webcomponents/webcomponentsjs&quot;: &quot;^2.5.0&quot;,
&quot;global&quot;: &quot;^4.4.0&quot;,
&quot;import&quot;: &quot;^0.0.6&quot;,
&quot;jetifier&quot;: &quot;^1.6.6&quot;,
&quot;react&quot;: &quot;^16.10.2&quot;,
&quot;react-clock&quot;: &quot;^3.0.0&quot;,
&quot;react-dom&quot;: &quot;^16.10.2&quot;,
&quot;react-player&quot;: &quot;^2.7.2&quot;,
&quot;react-qr-code&quot;: &quot;^2.0.2&quot;,
&quot;react-rating&quot;: &quot;^2.0.5&quot;,
&quot;react-router-dom&quot;: &quot;^5.1.2&quot;,
&quot;react-scripts&quot;: &quot;^2.1.8&quot;,
&quot;react-simple-keyboard&quot;: &quot;^2.0.15&quot;,
&quot;react-toast-notifications&quot;: &quot;^2.2.5&quot;,
&quot;ts-node&quot;: &quot;^9.0.0&quot;,
&quot;typescript&quot;: &quot;^4.3.5&quot;
</code></pre>
<p><code>node</code> version</p>
<pre><code>v14.15.0
</code></pre>
<p>I wonder if any of you has experiend similar issues in unit testing with <code>Jest</code> and Chrome inspector and if so could you give me any advise how to resolve it? Could it be some sort of libraries incompatibility or any particular configuration in <code>React</code> project?</p>
",https://stackoverflow.com/questions/69252664/why-jest-unit-test-debugging-doesnt-stop-at-breakpoints-in-chrome-inspector,"['reactjs', 'typescript', 'unit-testing', 'jestjs', 'google-chrome-devtools']",628,False,2,1
PHP Unit / Mockery - Mock static function not working,"<p>Hey so I have the below method and when trying to mock the Manager::getConfiguration call, I cannot get it to work. I have tried using a namedMock as well as the unit test decorators to have it run in another thread. It either gives me a class already exists error or actually pulls the manager configuration which I do not want.</p>
<pre><code>public function getBaseTypeManagerConfig() {
        $baseTypeManagerConfig = array();

        if (!empty($this-&gt;dataConfig)
                &amp;&amp; !empty($baseType = $this-&gt;dataConfig-&gt;getBaseType())) {
            $baseTypeManagerConfig = Manager::getConfiguration($baseType);
        }

        return $baseTypeManagerConfig;
}

/**
 * @runTestsInSeparateProcesses
 * @preserveGlobalState disabled
 */
public function testBaseTypeManagerConfig() {
         $managerMock = Mockery::namedMock('Manager', 'ManagerStub');
         $managerMock-&gt;shouldReceive('getConfiguration')-&gt;andReturn(self::MOCKED_MANAGER_DECODED_JSON);

         $listModule = Mockery::mock('GenericListModule')-&gt;makePartial();
         $listModule-&gt;shouldReceive([
                 'getBaseType' =&gt; 'events',
         ]);

         $config = \SWL\Lib\Generic\ConfigFactory::getConfig('Events_Event');
         $listModule-&gt;shouldReceive('setDataConfig')-&gt;andSet('dataConfig', $config);

         $baseTypeManagerConfig = $listModule-&gt;getBaseTypeManagerConfig();
         $this-&gt;assertEquals(array(), $baseTypeManagerConfig);
}

// Attempt at using named mock to replace 'Manager' class with mock
class ManagerStub {
    public static function getConfiguration($configType) {
        return array();
    }
}
</code></pre>
<p>Any thoughts on why I can't use this named mock to replace the Manager call? New to unit testing and phpunit/mockery so any other pointers welcome. Thank you! :)</p>
",https://stackoverflow.com/questions/68046271/php-unit-mockery-mock-static-function-not-working,"['php', 'unit-testing', 'phpunit']",961,True,1,1
Identical expressions in SymPy are not ==,"<p>I have two structurally identical expressions in SymPy, created in different ways:</p>
<pre><code>import sympy as sp

f = sp.Symbol('f')
x = sp.Symbol('x')

by_hand = sp.Function(f)(x)
from_string = sp.sympify('f(x)')
</code></pre>
<p>Despite being identical expressions by construction, the two are not <code>==</code>:</p>
<pre><code>by_hand == from_string
# False
</code></pre>
<p>Indeed, SymPy doesn't even know that they're equal <strong>symbolically</strong>:</p>
<pre><code>sp.simplify(by_hand - from_string)
# 𝑓(𝑥)−𝑓(𝑥) 
</code></pre>
<p>The two have identical <code>srepr</code>s:</p>
<pre><code>(sp.srepr(by_hand), sp.srepr(from_string))
# (&quot;Function('f')(Symbol('x'))&quot;, &quot;Function('f')(Symbol('x'))&quot;)

sp.srepr(by_hand) == sp.srepr(from_string)
# True
</code></pre>
<p>I know that <a href=""https://stackoverflow.com/q/50694693/85467"">round-tripping through strings isn't necessary reliable</a> for maintaining identity in SymPy, but even using the <code>locals</code> argument as a fix doesn't resolve this issue:</p>
<pre><code>by_hand == sp.sympify('f(x)', locals={'f': f}) == by_hand
# False
</code></pre>
<p>Having to use <code>locals</code> is already somewhat painful, because I am trying to do unit testing of a routine that constructs a bunch of symbolic expressions by constructing them independently.</p>
",https://stackoverflow.com/questions/69305664/identical-expressions-in-sympy-are-not,"['python', 'sympy']",59,True,1,1
How can I use RateLimiter&#39;s HttpClient DelegatingHandler with dependency injection?,"<p>I've been using <a href=""https://www.nuget.org/packages/RateLimiter/"" rel=""nofollow noreferrer"">RateLimiter</a> (<a href=""https://github.com/David-Desmaisons/RateLimiter"" rel=""nofollow noreferrer"">github</a>) successfully with my project for a while now. I've recently discovered dependency injection and am attempting to migrate my code as-is to use this but I'm stuck on RateLimiter.</p>
<p>Normal usage from the docs is</p>
<pre><code>var handler = TimeLimiter
        .GetFromMaxCountByInterval(25, TimeSpan.FromMinutes(1))
        .AsDelegatingHandler();
var Client = new HttpClient(handler)
</code></pre>
<p>However if I try to replicate that during dependency injection</p>
<pre><code>    public override void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddHttpClient&lt;IMyApiClient, MyApiClient&gt;(client =&gt; client.BaseAddress = new Uri(&quot;https://api.myapi.com/&quot;))
               .AddPolicyHandler(GetRetryPolicy())
               .AddHttpMessageHandler(() =&gt; TimeLimiter.GetFromMaxCountByInterval(25, TimeSpan.FromMinutes(1)).AsDelegatingHandler());
     }
</code></pre>
<p>I receive the error:</p>
<pre><code>[2021-05-17T21:58:00.116Z] Microsoft.Extensions.Http: The 'InnerHandler' property must be null. 'DelegatingHandler' instances provided to 'HttpMessageHandlerBuilder' must not be reused or cached.
[2021-05-17T21:58:00.117Z] Handler: 'ComposableAsync.DispatcherDelegatingHandler'.
[2021-05-17T21:58:00.122Z] An unhandled host error has occurred.
</code></pre>
<p>My class client structure (mostly for the sake of unit testing) looks like this:</p>
<pre><code>using System.Net.Http;
using System.Threading.Tasks;

public class MyApiClient : HumbleHttpClient, IMyApiClient
{
    public MyApiClient(HttpClient client)
        : base(client)
    {
    }
}

public class HumbleHttpClient : IHttpClient
{
    public HumbleHttpClient(HttpClient httpClient)
    {
        this.Client = httpClient;
    }

    public HttpClient Client { get; }

    public Task&lt;HttpResponseMessage&gt; GetAsync(string requestUri)
    {
        return this.Client.GetAsync(requestUri);
    }

    public Task&lt;HttpResponseMessage&gt; PostAsync(string requestUri, HttpContent content)
    {
        return this.Client.PostAsync(requestUri, content);
    }
}

public interface IHttpClient
{
    Task&lt;HttpResponseMessage&gt; GetAsync(string requestUri);
    Task&lt;HttpResponseMessage&gt; PostAsync(string requestUri, HttpContent content);
    HttpClient Client { get; }
}
</code></pre>
<p>These are the docs I've been trying to follow:
<a href=""https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests</a></p>
",https://stackoverflow.com/questions/67577658/how-can-i-use-ratelimiters-httpclient-delegatinghandler-with-dependency-injecti,"['c#', '.net-core', 'dependency-injection', 'dotnet-httpclient']",1015,True,1,1
Getting null when using MockClient,"<p>For my unit testing, I am using <a href=""https://pub.dev/packages/mockito"" rel=""nofollow noreferrer"">mockito 4.1.4</a> like this:</p>
<p><strong>I am having a test that is passing if I am using this code:</strong></p>
<pre><code>    test('Adding data manually', () async {
      final GhibliFilms ghibliMock = GhibliFilms();

      ghibliMock.addFilm(FilmModel(
          director: 'test director',
          description: 'test',
          releaseDate: 'test',
          producer: 'test'
      ));

      expect(ghibliMock.films.length, 1);

    });

</code></pre>
<p>GhibliFilms addFilm method:</p>
<pre><code>  List&lt;FilmModel&gt; _films = [];

  void addFilm(FilmModel film){
    _films.add(film);
  }
</code></pre>
<hr />
<h2>A problem</h2>
<p>I want to use <code>MockClient</code> to control some data manually, but when I am using it my test will fail:</p>
<p>This is my MockClient:</p>
<pre><code>class MockClient extends Mock implements GhibliFilms {
  @override
  Future&lt;List&lt;FilmModel&gt;&gt; getFilms() async{
    return null;
  }
}
</code></pre>
<p>And when I change <code>final GhibliFilms ghibliMock = GhibliFilms();</code> to <code>final MockClient ghibliMock = MockClient();</code> (the rest of the code remained the same) my test will fail with this message:</p>
<pre><code>NoSuchMethodError: The getter 'length' was called on null.
Receiver: null
Tried calling: length
</code></pre>
<p><strong>What is wrong with my approach? and how can I use MockClient for my case?</strong></p>
",https://stackoverflow.com/questions/65927643/getting-null-when-using-mockclient,"['flutter', 'unit-testing', 'dart', 'mocking', 'mockito']",319,True,1,1
Mocking an interface with nested static class,"<p>I have an interface and its implementation which I can't change.
Interface looks like this:</p>
<pre><code>public Interface IHello{
// ... some method declarations
     public static class IoH{
          static IHello hello = new IHello.IoH.HelloImpl();
          public IoH(){}
          
          public static IHello getHello(){
              return hello;
          }

          private static class HelloImpl implements IHello{ 
              // .... constructor and methods....
          }
     }
}
</code></pre>
<p>I am also given an implementation of IHello interface, Hello (which is <strong>final class</strong>), which is just overriding the functions of IHello Interface and not doing anything else. That means it is not using any nested part of interface.</p>
<p>It is now used somewhere in the code as :</p>
<pre><code>String string = IHello.IoH.getHello().getInfo(); // getInfo()  is method of interface
</code></pre>
<p>I'm unit testing and I want to mock this <strong>IHello.IoH.getHello()</strong> or <strong>IHello.IoH.getHello().getInfo()</strong> with either MockImplementation of <strong>IHello</strong> interface  and injecting some bean <strong>or</strong> using Mockito...</p>
<p>How can I do this?</p>
",https://stackoverflow.com/questions/65664712/mocking-an-interface-with-nested-static-class,"['java', 'spring', 'spring-boot', 'unit-testing', 'mockito']",638,True,1,1
How are application classes/methods made available to java tests,"<p>In my recent role, I transitioned from C to Java. Our project has a standard java project structure as laid out by Apache Maven. I am able to run Junit tests from Intellij with no problems.</p>
<p>But I am curious about how the application logic spread across  /src/main/ is made available to the test logic in /src/test.</p>
<p>Is Unit testing framework responsible for this? or build tool creates a temporary jar which includes test classes along with application classes as governed by their respective package structures?</p>
<p>Thanks for your responses!</p>
",https://stackoverflow.com/questions/67592600/how-are-application-classes-methods-made-available-to-java-tests,"['java', 'maven', 'junit']",62,True,1,1
Dapper is crashing when load is increased,"<p>I am using dapper in a payment processing application built on .net 5.0. In unit testing, everything was working fine, but when I used JMeter to put the load of 100 users, after processing few transactions, the dapper started crashing with the below error:</p>
<blockquote>
<p>Exception[System.InvalidOperationException: Connection must be open
for this operation    at
Oracle.ManagedDataAccess.Client.OracleCommand.ValidateStatePriorToExecution()
at Oracle.ManagedDataAccess.Client.OracleCommand.ExecuteNonQuery()<br />
at Dapper.SqlMapper.ExecuteCommand(IDbConnection cnn,
CommandDefinition&amp; command, Action<code>2 paramReader) in /_/Dapper/SqlMapper.cs:line 2822    at Dapper.SqlMapper.ExecuteImpl(IDbConnection cnn, CommandDefinition&amp; command) in /_/Dapper/SqlMapper.cs:line 572    at Dapper.SqlMapper.Execute(IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Nullable</code>1 commandTimeout, Nullable`1
commandType) in /_/Dapper/SqlMapper.cs:line 443</p>
</blockquote>
<p>The code for SP execution is below:</p>
<pre><code>public static int ExecuteSP(string spName, object parameters)
{
    IDbConnection connection = ConnectionManager.GetConnection(_ConnectionString);

    int result = connection.Execute(spName, parameters, null, null, CommandType.StoredProcedure);

    ConnectionManager.CloseConnection();
    return result;
}

public static IDbConnection GetConnection(string connectionString)
{
     DefaultTypeMap.MatchNamesWithUnderscores = true;

     if (_oracleConnection == null)
     {
         _oracleConnection = new OracleConnection(GetConnectionString(connectionString));
     }

     if (_oracleConnection.State == ConnectionState.Closed)
     {
         _oracleConnection.Open();
     }
     return _oracleConnection;
}
</code></pre>
<p>Is there anything I am missing in configuration or use of Dapper?</p>
",https://stackoverflow.com/questions/69268474/dapper-is-crashing-when-load-is-increased,"['dapper', 'stress-testing']",496,True,1,1
Offline Jest unit test implementation in firebase functions in Nodejs,"<p>I am trying to implement jest unit testing for firebase functions in my application. I was purely looking at implementing an offline test. I have mocked the request and response objects and am still trying to access some other firebase resources on execution. I am not sure whether I missed any sort of mocking. I intend to not use any firebase-related configuration URLs.</p>
<p>Here is my function and test samples,</p>
<p><strong>randomgenerator.ts</strong></p>
<pre><code>import { https } from &quot;firebase-functions&quot;;

export const generateTrickyNumber = https.onRequest(async (req, res) =&gt; {
    corsHandler(req, res, async () =&gt; {
            try {
                let num =0;
                switch (req.body.type) {
                    case &quot;palindrome&quot;:
                       num= await generatePalindrome(req.body.startnumber,req.body.endnumber);
                        break;
                    case &quot;prime&quot;:
                       num= await generatePrime(req.body.startnumber,req.body.endnumber);
                        break;
                    default:
                        break;
                }
                return res.status(200).send(num);
            } catch (err) {
                console.log({ err });
                return;
            }
    });
});
</code></pre>
<p><strong>randomgenerator.test.ts</strong></p>
<pre><code>import 'jest';
import * as httpMock from 'node-mocks-http';
import * as TestFunctions from 'firebase-functions-test';
const testEnv = TestFunctions();
import { generateTrickyNumber } from &quot;../src/randomgenrator.ts&quot;;

describe('generateTrickyNumber ', () =&gt; {
    test('it returns a successful response with a valid card', async () =&gt; {
        const req = { method: &quot;POST&quot;, body: {type:&quot;palindrome&quot;, startnumber:1,endnumber:200} };
        const res = {
            send: (payload) =&gt; {
                expect(payload).toBe(153)
            },
        };

        await generateTrickyNumber (req as any, res as any);
    });


    test('it returns an error if the method is not passed', async () =&gt; {
        const req = { body: { type: &quot;palindrome&quot; } };
        const res = {
            send: (payload) =&gt; {
                expect(payload).toBe('Missing value!')
            },
        };

        await generateTrickyNumber (req as any, res as any);
    });
});
</code></pre>
<p>Do we need to handle any more mocking for making this successful? Please feel free to suggest.</p>
",https://stackoverflow.com/questions/68824850/offline-jest-unit-test-implementation-in-firebase-functions-in-nodejs,"['node.js', 'jestjs', 'google-cloud-functions', 'ts-jest']",178,False,1,0
What is the proper way to say that a unit test failed but only because the test script is broken?,"<p>I'm looking for help with terminology to explain that a unit test failed because the test script itself has errors. The statement &quot;this unit test failed because...&quot; usually implies that the test script is correct and it's the function under test that is incorrect. I'm looking for the other way around.</p>
<p>Context: I'm grading a bunch of assignments in Python 3.x where students had to define some classes and subclasses while also providing the unit testing in Pytest. I would like to give succinct but correct feedback.</p>
",https://stackoverflow.com/questions/69598892/what-is-the-proper-way-to-say-that-a-unit-test-failed-but-only-because-the-test,"['python', 'unit-testing', 'pytest', 'terminology']",361,False,0,1
Flutter: Unit Testing a Cubit issues,"<p>I have been trying to set up unit testing for my cubit but bloc test seems to be having issues. Just trying to check the initial state of the values works just fine with regular test but as soon as I try to the same thing with bloc test it spits out fail with the actual being an empty list at [0] and I'm not sure what I'm doing wrong. Nothing on the internet is helpful with this error.</p>
<pre><code>//passes
test('initial state of SettingsCubit', () {
  expect(
      settingsCubit.state,
      SettingsState(
          notificationsEnabled: false,
          gpsEnabled: false,
          celsiusEnabled: false,
          expandNavigation: false,
          breakingNewsNotifications: false,
          trendingNotifications: false,
          liveRemindersNotifications: false,
          sportsNotifications: false));
});

//fails
blocTest(
  'initial state of SettingsCubit',
  build: () =&gt; SettingsCubit(),
  expect: () =&gt; [
    SettingsState(
      expandNavigation: false,
      gpsEnabled: false,
      celsiusEnabled: false,
      notificationsEnabled: false,
      breakingNewsNotifications: false,
      trendingNotifications: false,
      liveRemindersNotifications: false,
      sportsNotifications: false,
    )
  ],
);
</code></pre>
<p>Error:</p>
<pre><code>package:bloc_test/src/bloc_test.dart 193:9   testBloc.&lt;fn&gt;
===== asynchronous gap ===========================
dart:async                                   _asyncThenWrapperHelper
package:bloc_test/src/bloc_test.dart         testBloc.&lt;fn&gt;
dart:async                                   runZonedGuarded
package:bloc_test/src/bloc_test.dart 172:9   testBloc
package:bloc_test/src/bloc_test.dart 140:11  blocTest.&lt;fn&gt;
package:bloc_test/src/bloc_test.dart 139:26  blocTest.&lt;fn&gt;
Expected: [
            SettingsState:SettingsState(expandNavigation: false, gpsEnabled: false, celsiusEnabled: false, notificationsEnabled: false,breakingNewsNotifications: false, trendingNotifications: false, liveRemindersNotifications: false, sportsNotifications: false)
          ]
  Actual: []
   Which: at location [0] is [] which shorter than expected
</code></pre>
<p>SettingsCubit and SettingsState code is at:
<a href=""https://stackoverflow.com/questions/68582768/flutter-bloc-test-failures"">Flutter BLoC Test failures</a></p>
",https://stackoverflow.com/questions/68667461/flutter-unit-testing-a-cubit-issues,"['flutter', 'unit-testing', 'bloc', 'bloc-test', 'flutter-cubit']",1484,True,0,1
Testing form reset on Vue with Jest,"<p>Testing a form built with Vue using Jest for unit tests. Among the elements I have a reset button (type=reset), which works fine and once clicked it removes all the values already introduced.</p>
<p>However, when unit testing, the button click doesn't seem to clear the values. I don't have a handler for the click, just using the default reset function of the form.</p>
<p>I've also tried using <code>wrapper.emmited('reset');</code> to no avail, and <code>wrapper.emmitedByOrder();</code> returns an empty array.</p>
<p>How do I test that the reset button is generated correctly and works as expected?</p>
<pre><code>test('Assert Form Components', async () =&gt; {
 const wrapper = mount(FormElement, {
            propsData: {
                message: sampleJSON.formJSON
            }
        })

let resetBtn = wrapper.find('.form-reset');
let requiredInput = wrapper.find('.required-input');
....
requiredInput.setValue('test');
expect(requiredInput.element).toHaveValue('test'); //This passes

await resetBtn.trigger('click');
expect(requiredInput.element).not.toHaveValue('test') //This fails
....
</code></pre>
",https://stackoverflow.com/questions/68546062/testing-form-reset-on-vue-with-jest,"['javascript', 'vue.js', 'unit-testing', 'jestjs', 'vue-test-utils']",949,True,0,1
Vue: Mixin in Unit Test causes weird test failure,"<p>I am attempting to add some unit tests to a component that has a mixin.</p>
<p>Here is roughly what the mixin is doing:</p>
<pre><code>import test from '@/assets/file.txt'

export default {
  data() {
    return {
      title: '',
      body: ''
    }
  },
  methods: {
    initData() {
      // Read data from the file and update data() above.
    }
  }
}
</code></pre>
<p>The only seemingly relevant line in this mixin causing the error is the import. It is throwing a SyntaxError as follows:</p>
<pre><code>SyntaxError: Invalid left-hand side expression in prefix operation

&gt; 1 | import alertTuning from '@/assets/AlertTuning.md'
    | ^
  2 |
  3 | export default {
  4 |   data() {

  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; (src/assets/js/mixins/alertTuningTemplateMixin.js:1:1)
</code></pre>
<p>This strikes me as weird because I know this is syntactically correct JavaScript, why would this import be throwing such an error only when unit testing it?</p>
<p>The mixin works perfectly outside of testing scenarios, i.e. in our local, prod, and stage website it works perfectly without any errors.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/70248280/vue-mixin-in-unit-test-causes-weird-test-failure,"['javascript', 'vue.js', 'vuejs2', 'jestjs']",127,False,0,0
Powermock&#39;s Mock Static is not working as expected,"<p>For my project, I am working on power mock framework for unit testing.
I am facing an issue, I have mocked a static method, but still, it is calling the real method. I have set up the problem with simple classes. Please help to resolve the issue.</p>
<p>This is the Test that is being tested and it has a static method.</p>
<pre><code>package in.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionClass {
    public static boolean getValue() throws SQLException {
        Connection connection = DriverManager.getConnection(&quot;&quot;, &quot;&quot;, &quot;&quot;);
        return connection == null;
    }
}
</code></pre>
<p>This is the test class.</p>
<pre><code>package in.service;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest({DriverManager.class})
public class ConnectionClassTest {
    @Mock
    private Connection connection;
    @Before
    public void setUp() {
        PowerMockito.mockStatic(DriverManager.class);
    }

    @Test
    public void check_Value_WhenConnectionIsNotPresent() throws SQLException {
        when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(connection);
        ConnectionClass.getValue();
    }

    @Test
    public void check_Value_WhenConnectionIsPresent() throws SQLException {
        when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(null);
        ConnectionClass.getValue();
    }
}
</code></pre>
<p>When I try to run these tests, DriverManager's actual connection method is called. Ideally, this method shouldn't be called.</p>
<p>Please help here if I am doing anything wrong here.</p>
",https://stackoverflow.com/questions/68695431/powermocks-mock-static-is-not-working-as-expected,"['java', 'unit-testing', 'junit', 'powermockito']",204,False,0,0
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-cli) on project UnitTestCourse: No tests were executed,"<p>I'm currently learning Unit Testing and until an hour ago I had no problems running the tests on my files but now for some reason I started getting this error. I already checked similar questions on this website but their solutions were no use to me.</p>
<p>Like this : <a href=""https://stackoverflow.com/questions/32069324/failed-to-execute-unit-tests-using-maven-no-tests-executed"">Failed to execute unit tests using maven : No tests executed</a></p>
<p>Here are my pom.xml and codes:</p>
<pre><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;com.junitdemo&lt;/groupId&gt;
    &lt;artifactId&gt;UnitTestCourse&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
    &lt;packaging&gt;jar&lt;/packaging&gt;
    &lt;properties&gt;
        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
        &lt;maven.compiler.source&gt;1.8&lt;/maven.compiler.source&gt;
        &lt;maven.compiler.target&gt;1.8&lt;/maven.compiler.target&gt;
        &lt;junit.jupiter.api&gt;5.1.1&lt;/junit.jupiter.api&gt;
   
    &lt;/properties&gt;
    
    &lt;build&gt;
        &lt;plugins&gt;
        &lt;plugin&gt;
    &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
    &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
    &lt;version&gt;2.19.1&lt;/version&gt;
    &lt;configuration&gt;
        &lt;testFailureIgnore&gt;true&lt;/testFailureIgnore&gt;
    &lt;/configuration&gt;
&lt;/plugin&gt;
&lt;/plugins&gt;
    &lt;/build&gt;
    
    &lt;dependencies&gt;
        
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;
            &lt;version&gt;${junit.jupiter.api}&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;junit&lt;/groupId&gt;
            &lt;artifactId&gt;junit&lt;/artifactId&gt;
            &lt;version&gt;4.12&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hamcrest&lt;/groupId&gt;
            &lt;artifactId&gt;hamcrest-core&lt;/artifactId&gt;
            &lt;version&gt;1.3&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
&lt;/project&gt;

</code></pre>
<p>Test Code (package name seems same but this is in Test Packages, not Source Packages.)</p>
<pre><code>package test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;


public class HelloWorldTest {
    
    @Test
    void sayHelloToWorld(){
        
        HelloWorld helloWorld = new HelloWorld();
        
        assertEquals(&quot;Hello World!&quot;, helloWorld.sayHello(), &quot;Say Hello to World&quot;);
    }
    
}
</code></pre>
<p>and source class</p>
<pre><code>
package test;


public class HelloWorld {
    
    public String sayHello(){
        
        return &quot;Hello World&quot;;
    }
    
}
</code></pre>
<p>Here is the full error I'm getting</p>
<pre><code>
BUILD FAILURE
------------------------------------------------------------------------
Total time: 1.701s
Finished at: Sun Aug 15 18:17:36 EDT 2021
Final Memory: 7M/245M
------------------------------------------------------------------------
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.19.1:test (default-cli) on project UnitTestCourse: No tests were executed!  (Set -DfailIfNoTests=false to ignore this error.) -&gt; [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

</code></pre>
",https://stackoverflow.com/questions/68795705/failed-to-execute-goal-org-apache-maven-pluginsmaven-surefire-plugin2-19-1tes,"['java', 'maven', 'testing']",262,False,0,0
How to karma/jasmine test property in Angular service,"<p>I have an angular component (Purchases) that has the following code in the constructor</p>
<pre><code>this.userAuthService.loggedInUser.subscribe(user =&gt; {
  this.taxName = user.TaxName || 'GST';
});
</code></pre>
<p>The UserAuthService has the following defined in it's constructor</p>
<pre><code>private loggedInUserSubject = new BehaviorSubject&lt;User&gt;({} as User);
public loggedInUser = this.loggedInUserSubject.asObservable().pipe(distinctUntilChanged());
</code></pre>
<p>I'm trying to write a unit test to ensure the Purchases component is created, but I'm getting the error</p>
<blockquote>
<p>&quot;Failed:  : could not find an object to spy upon for loggedInUser()&quot;.</p>
</blockquote>
<p>I'm fairly new to unit testing Angular, so I'm not sure if I have it set up properly, to begin with. Can anyone help with how I can test the constructor of the <code>PurchasesComponent</code>?</p>
<p>Here's the test for it:</p>
<pre><code>describe('PurchasesComponent', () =&gt; {
    let component: PurchasesComponent;
    let fixture: ComponentFixture&lt;PurchasesComponent&gt;;
    let service: UserAuthService;
    let mockData = {TaxName: 'GST'};

    beforeEach(waitForAsync(() =&gt; {
        spyOn(service, 'loggedInUser').and.callFake(() =&gt; of(mockData));
        TestBed.configureTestingModule({
            declarations: [PurchaseMadeComponent],
            providers: [
                { provide: UserAuthService, useValue: {} }
            ]
        }).compileComponents();
    }));

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

        service = TestBed.inject(UserAuthService);
    });

    it('should create', () =&gt; {
        expect(component).toBeTruthy();
    });
});
</code></pre>
",https://stackoverflow.com/questions/67595723/how-to-karma-jasmine-test-property-in-angular-service,"['angular', 'karma-jasmine']",461,True,0,1
"NUnit Test Error: Could not load type &#39;System.Web.HttpApplication&#39; from assembly &#39;System.Web, Version=4.0.0.0","<p>I have tried to search for this but solutions provided don't seem to work for me.
I have an existing C# Class Library project targeting .Net Framework 4.5.1 that is currently live. I would like to introduce Unit testing using NUnit. I therefore added NUnit Test Project(.Net Core 3.1) to the solution. I have added a reference to the .Net Framework 4.5.1 in the NUnit project, after building it looks fine.
However, I have created a simple test below, when I run I get the error</p>
<pre><code>Test
   Duration: 208 ms

  Message: 
    System.TypeLoadException : Could not load type 'System.Web.HttpApplication' from assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
  Stack Trace: 
    RuntimeAssembly.GetExportedTypes()
    Assembly.get_ExportedTypes()
    ExtensionsForAssembly.GetNinjectModules(Assembly assembly)
    &lt;&gt;c.&lt;Load&gt;b__25_0(Assembly asm)
    SelectManySingleSelectorIterator`2.ToList()
    Enumerable.ToList[TSource](IEnumerable`1 source)
    KernelBase.Load(IEnumerable`1 m)
    KernelBase.Load(IEnumerable`1 assemblies)
    ModuleLoadExtensions.Load(IKernel kernel, Assembly[] assemblies)
    DirectRewardsController.ctor() line 24
    DirectRewardsTests.Test() line 18
</code></pre>
<p>NUnit Test</p>
<pre><code>public class DirectRewardsTests
    {
        [SetUp]
        public void SetUp()
        {

        }

        [Test]
        public void Test()
        {
            //Arrange
            DirectRewardsController directRewards = new DirectRewardsController(); 
            //Act

            //Assert
            Assert.Pass();
        }
    }
</code></pre>
<p>DirectRewardsController</p>
<pre><code>public class DirectRewardsController : ApiController
    {
        StandardKernel DependencyKernel;
        
        private IDirectRewards justRewards;
        public DirectRewardsController()
        {
            DependencyKernel = new StandardKernel();
            DependencyKernel.Load(Assembly.GetExecutingAssembly());
            justRewards = DependencyKernel.Get&lt;IDirectRewards&gt;();
        }
        
         public HttpResponseMessage AddMember(MemberRequest model)
        {
            try
            {
                //Add Member record
            }
            catch (Exception ex)
            {
                return new HttpResponseMessage { StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(ex.Message) };
            }
        }
    }
</code></pre>
",https://stackoverflow.com/questions/67406569/nunit-test-error-could-not-load-type-system-web-httpapplication-from-assembly,"['c#', '.net', 'nunit']",469,True,0,1
class attribute default value doesn&#39;t receive the mock,"<p>I'm unit testing a module I wrote and encountering a problem with default class object provided to a function that has a mock for it.
This is how it looks in high level:</p>
<p>main_file.py</p>
<pre><code>class MainClass(object):
    def main_func(self):
        sub_class_obj = SubClass()
        sub_class_obj.sub_func()
</code></pre>
<p>sub_file.py</p>
<pre><code>class SubClass(object):
    def sub_func(self, my_att=Helper(2)):
        self.my_att = my_att
</code></pre>
<p>helpers.py</p>
<pre><code>class Helper():
    def __init__(self, my_val):
        self.my_val = my_val
</code></pre>
<p>test.py</p>
<pre><code>class TestClass(object):
    @patch('sub_file.Helper', MockHelper)
    def my_test(self):
        main_class_obj = MainClass()
        main_class_obj.main_func()
</code></pre>
<p>When I do that in a way that my_att is provided - all works well and the Mock is called, but when I don't and the default value is set - I get the original Helper class object.</p>
<p>Any idea how to make the default value for this attribute to receive the mock as well?</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/68662689/class-attribute-default-value-doesnt-receive-the-mock,"['python', 'python-2.7', 'python-unittest']",212,True,0,2
.NET Core Benchmarking without database,"<p>I'm looking for an effective way to benchmark my server endpoints &amp; business logic.
The problem I encounter is when I want to avoid accessing the database in terms of reading and writing to it when i benchmark my methods. I have recently been using the <code>NSubstitute</code> library for unit testing to mock database\storage methods. I was wondering if I could use something similar in my benchmarking classes - something like this:</p>
<p><strong>Main program</strong></p>
<pre><code>public static async Task Benchmark()
 {
   BenchmarkRunner.Run&lt;Logins&gt;();          
 }
</code></pre>
<p><strong>Logins Class</strong></p>
<pre><code>[MemoryDiagnoser]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
public class Logins
{
    private const string UserId = &quot;60c9d&quot;;
    private const string Email = &quot;example@main.club&quot;;

    [Benchmark]
    public async Task LoginWithEmail()
    {
       // This is my login method 
        await UserLoginManager.Instance.LoginWithEmail(Email, Password);
    }
}
</code></pre>
<p>LoginWithEmail method contains a call for db which i would like to ignore or substitute/Mock. Hopefully this makes sense.</p>
",https://stackoverflow.com/questions/68055601/net-core-benchmarking-without-database,"['c#', 'unit-testing', '.net-core', 'benchmarking']",196,False,0,0
Unit test - Karma - Jasmine - BsModalService code coverage is not working,"<p>I am trying to write the unit testing for 1 of the method, it was expecting the parameter of <strong>template: TemplateRef</strong> and inside method. I am showing and hiding the modal by using
<strong>this.modalService.show(template, CommonConst.CONFIGFORSMALLMODAL)</strong>. There is no error but code coverage is not covered.</p>
<p>HTML</p>
<pre><code>&lt;button type=&quot;button&quot; id=&quot;add_btn_point&quot; class=&quot;btn btn-primary&quot; (click)=&quot;add(validateTemplate)&quot;&gt;
 Add &lt;/button&gt;
&lt;ng-template #validateTemplate&gt;
    &lt;div class=&quot;alert-box&quot;&gt;
      &lt;div class=&quot;modal-header&quot;&gt;
        &lt;h4 class=&quot;modal-title&quot;&gt;
          Add
        &lt;/h4&gt;
        &lt;button type=&quot;button&quot; class=&quot;close&quot; aria-label=&quot;Close&quot; &gt;
          &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;
        &lt;/button&gt;
      &lt;/div&gt;
      &lt;div class=&quot;modal-body&quot;&gt;
        &lt;div class=&quot;messageText text-center&quot;&gt;
          &lt;p&gt;
            {{errorMessaage}}
          &lt;/p&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      &lt;div class=&quot;modal-footer&quot;&gt;
        &lt;button type=&quot;button&quot; data-dismiss=&quot;modal&quot; class=&quot;btn btn-primary&quot; &gt;
          Save
        &lt;/button&gt;
        &lt;button type=&quot;button&quot; data-dismiss=&quot;modal&quot; class=&quot;btn btn-primary&quot;&gt;
          Close
        &lt;/button&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/ng-template&gt; 
</code></pre>
<p>Component:</p>
<pre><code>addFileQueryDataPool(template: TemplateRef&lt;any&gt;) {
if(true) {
        this.valModalRef = this.modalService.show(template, CommonConst.CONFIGFORSMALLMODAL);
      } else {
this.valModalRef.hide();
}
  }
</code></pre>
<p>Unit Test:</p>
<pre><code>it('should call the addFileQueryDataPoint() method when clicking on the links', () =&gt; {
    const obj = spyOn(component, 'addFileQueryDataPoint');
    
    //let el = fixture.debugElement.query(By.css('#add_btn_point'))
    //el.triggerEventHandler('click', null)

    let buttonDebugElems: DebugElement[] = fixture.debugElement.queryAll(By.css('#add_btn_point'));
    buttonDebugElems[0].triggerEventHandler('click', null);
    const button: HTMLButtonElement = fixture.debugElement.nativeElement.querySelector('#add_btn_point');
    button.dispatchEvent(new Event('click'));
    fixture.detectChanges()
    
    fixture.whenStable().then(() =&gt; {
      expect(component.addFileQueryDataPoint).toHaveBeenCalled();
    });
  });
</code></pre>
<p>Is it any way to skip this method. I was tried adding x in front of it() method. Method skipped but coverage is not increasing.</p>
<p>Please advice, how to write unit test case for above code. Advance thanks</p>
",https://stackoverflow.com/questions/68421006/unit-test-karma-jasmine-bsmodalservice-code-coverage-is-not-working,"['angular', 'unit-testing', 'karma-jasmine']",252,False,0,0
How can I use globally installed AVA for unit tests?,"<p>I am trying to implement unit testing with AVA for my javascript app.</p>
<p>I have installed AVA globally.</p>
<p>I have created a basic ava.config.cjs file:</p>
<pre><code>module.exports = {
    files: ['tests/**', '!tests/**/{fixtures,helpers}/**']
};
</code></pre>
<p>And I have a test file:</p>
<pre><code>import test from 'ava';
// const { test } = require('ava');

test('foo', t =&gt; {
    t.pass();
});

test('bar', async t =&gt; {
    const bar = Promise.resolve('bar');
    t.is(await bar, 'bar');
});
</code></pre>
<p>I have tried both 'import', and 'require' but neither work.</p>
<p>When I run ava from the command line I get an error that the module 'ava' can't be found.</p>
<blockquote>
<p>Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'ava'</p>
</blockquote>
<p>Or</p>
<blockquote>
<p>Error: Cannot find module 'ava'</p>
</blockquote>
<p>Depending on which method I try to include AVA...</p>
<p>What would I need to do to get this working?</p>
",https://stackoverflow.com/questions/67207390/how-can-i-use-globally-installed-ava-for-unit-tests,"['javascript', 'ava']",216,True,0,1
How to test setState after getting response from an api,"<p>I am doing unit testing using jest and enzyme on my reactjs code,where I have main functional component &quot;TrashDisplayFiles&quot; inside which there is a method &quot;getDeletedData&quot;,where I have called the api which is setting TrashFileState by getting response from an api.</p>
<pre><code>function TrashDisplayFiles(props){
      const[TrashFileState,setTrashFileState]=useState([]);
 //API CALL
  useEffect(()=&gt;{
    getDeletedData();
  },[]);
const getDeletedData=()=&gt;{ 
 trackPromise(
  Axios.get(getUrl(),
    {headers:{
    Authorization: `Basic ${btoa(getToken())}`
     }}).then((response) =&gt; {
      let FileData=response.data;
      setPaginationDefault(response.data.list.pagination)
      setTrashFileState(response.data.list.entries.map(d=&gt;{
        return {
          select:false,
          id:d.entry.id,
          name:d.entry.name
        }})) 
      }).catch(err=&gt;alert(err))
  )
};
</code></pre>
<p>how can i unit test this setTrashFileState(response.data.list.entries.map(d=&gt;{return{  and error alert,so that it get covers in  my coverage report</p>
<p>also, this function is not getting simulated in my jsx through onsubmit or onclick,when the Trash page gets load ,this api gets triggered automatically.</p>
",https://stackoverflow.com/questions/65770368/how-to-test-setstate-after-getting-response-from-an-api,"['reactjs', 'jestjs', 'enzyme', 'moxios']",146,False,0,1
Unit-Test for a switch statement on Angular,"<p>I'm new to angular unit testing and I don't know how to test this switch:</p>
<pre><code>  displayBadge(text: any) {
    switch (text) {
      case 'blabla':
        return 'badge badge-pill badge-success';
      case 'lalala':
        return 'badge badge-pill badge-secondary';
      case 'uuuu':
        return 'badge badge-pill badge-warning';
      case 'ooooo':
        return 'badge badge-pill badge-warning';
      case 'eeee':
        return 'badge badge-pill badge-warning';
      case 'zzzzz':
        return 'badge badge-pill badge-dark';
      case 'aaaaa':
        return 'badge badge-pill badge-dark';
      case 'qqqqq':
        return 'badge badge-pill badge-success';
      case 'ccccc':
        return 'badge badge-pill badge-warning';
      case 'rrrrr':
        return 'badge badge-pill badge-success';
      case 'ttttt':
        return 'badge badge-pill badge-warning';
      case 'fffff':
        return 'badge badge-pill badge-success';
      default:
        return '';
</code></pre>
<p>I'm using Simontest plugin on VSCODE and the code coverage always tells me I'm missing like 80% of the coverage, which is this switch.</p>
<p>I've tried this way on my spec.ts file:</p>
<pre><code>it('text aaaaa', () =&gt; {
    component.text ='aaaaa'
    component.displayBadge(component.text);
    expect('badge badge-pill badge-secondary');
  });
</code></pre>
<p>but it doesn't work.</p>
<p>text is defined like this in my ts:</p>
<pre><code>@Input()
  text!: any;
</code></pre>
<p>I've seen there are others posts about testing a switch, I've tried everything I've seen here on stack and in general on Google, but SimonTest always tells me this function is not tested.</p>
",https://stackoverflow.com/questions/70155600/unit-test-for-a-switch-statement-on-angular,"['angular', 'typescript', 'testing', 'switch-statement', 'angular-unit-test']",2655,True,0,1
How can I test the full setup of an iOS app?,"<p>My iOS app (Swift 5.3) has the structure below for the API and unit testing via mocking.</p>
<p>This does allow to test <em>some</em> aspects with a mocked-up API, but it's not a complete test: When running the tests, I will still run <code>setupInitialStateForApp</code> against the real API (not mocked out). Is there some way in the test that I can say: Don't initialize the app until I have mocked out the API? Or would there be a better way of writing this to avoid this problem?</p>
<p><strong>MyApp.swift:</strong></p>
<pre><code>@main
struct MyApp: App {
  var apiServer: ApiServer?
  var dataHandler: DataHandler? // Stores the app state as an observable object

  init() {
    self.apiServer = apiServer()
    self.dataHandler = setupInitialStateForApp(apiServer: apiServer)
  }
</code></pre>
<p><strong>MyAppTest.swift:</strong></p>
<pre><code>testApi() {
  let apiServer = APIServer()
  apiServer.session = getMockSession()
  // Now testing some stuff, and everything is mocked. Good!
  // But `setupInitialStateForApp` already ran, 
  // so I made real API calls which I want to avoid.
}

</code></pre>
",https://stackoverflow.com/questions/65762839/how-can-i-test-the-full-setup-of-an-ios-app,"['swiftui', 'xctest']",66,False,0,0
JUnit tests for Generic Links in tapestry,"<p>I have developed UI page which has href to external link. Now this external link is built (with db based key values for http request parameters) in a class which extends <code>GenericLink</code> of Tapestry. I am overriding <code>public ILink getLink(IRequestCycle cycle)</code> and <code>public String getHref()</code> methods for that. The developed task is working as expected.<br />
Now I want to write JUnit tests for this class, but I read there is other <a href=""https://tapestry.apache.org/unit-testing-pages-or-components.html"" rel=""nofollow noreferrer"">mechanism for Unit testing</a> in Tapestry but this is again not clear to me w.r.t. GenericLinks.<br />
Any leads to any artical will really help in order to test GenericLink class.</p>
",https://stackoverflow.com/questions/66815511/junit-tests-for-generic-links-in-tapestry,"['java', 'junit', 'junit4', 'tapestry']",80,False,0,0
How do I make a Spring ApplicationContext available for another class&#39;s unit test?,"<p>I have a <code>SpringContext</code> class which implements <code>ApplicationContextAware</code> so that I can access Spring beans from a regular Java class that isn't managed by Spring:</p>
<pre><code>@Component
public class SpringContext implements ApplicationContextAware {

    private static ApplicationContext context;

    /**
     * Returns the Spring managed bean instance of the given class type if it exists.
     * Returns null otherwise.
     * @param beanClass
     * @return
     */
    public static &lt;T extends Object&gt; T getBean(Class&lt;T&gt; beanClass) {
        return context.getBean(beanClass);
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {

        // store ApplicationContext reference to access required beans later on
        SpringContext.context = context;
    }

}
</code></pre>
<p>This works well when running the actual application, but during unit testing the <code>context</code> object is null, so <code>getBean()</code> returns a NPE.</p>
<p>The <code>getBean()</code> method is being called by a spy in the test class, but not directly, i.e. the spy has a mocked dependency which then calls this method.</p>
<p>I've tried making the test class <code>ApplicationContextAware</code> but that doesn't help, and neither does <code>@Inject</code>ing the <code>ApplicationContext</code>. How can I make sure that the <code>context</code> object is initialized?</p>
",https://stackoverflow.com/questions/67540967/how-do-i-make-a-spring-applicationcontext-available-for-another-classs-unit-tes,"['java', 'spring', 'unit-testing', 'testing']",94,False,0,0
Is there a way to unit test for multiple prints on terminal?,"<p>I'm currently having trouble unit testing a function that has multiple prints on multiple rows:</p>
<pre><code>def state_game(grid, score):

    print(grid[0])
    print(grid[1])
    print(grid[2])
    print(grid[3])
    print(f&quot;Your score is {score}&quot;)
    return('------------')
</code></pre>
<p>What I'm trying to do is test for each row of print whether the line printed on python terminal is correct. So far I've tried this to capture what's printed on terminal :</p>
<pre><code>import unittest
from unittest.mock import patch
&quot;defining grid&quot;
&quot;defining score&quot;
def test_state_game(self, mock_print):
         state_game(grid, score)
         mock_print.assert_called_with(grid[0])
         mock_print.assert_called_with(grid[1])
         mock_print.assert_called_with(grid[2])
         mock_print.assert_called_with(grid[3])
         mock_print.assert_called_with(f&quot;Your score is {score}&quot;)
</code></pre>
<p>The problem is it seems that when it first tests whether grid[0] is printed on terminal, the test fails showing that expected is grid[0] when &quot;Your score is {score}&quot; has been printed (i.e. the last print of the state_game function). Any idea ?</p>
",https://stackoverflow.com/questions/67178052/is-there-a-way-to-unit-test-for-multiple-prints-on-terminal,"['python', 'unit-testing', 'testing', 'pytest']",250,True,0,1
MSTest v2 won&#39;t run with net5.0-windows,"<p>I am trying to create a MSTest project for unit testing of our WinUI 3 development. I am able to run tests through the test explorer when targeting .NET 5.0.</p>
<p>Project Reunion requires net5.0-windows10.0.19041 as the target framework. When I try to run tests targeting net5.0-windows10.0.19041 the project builds but the tests do not run. The output of the Test log below says the WinUI3-UnitTests.dll file is not found but WinUI3-UnitTests.dll does exist in the specified location.</p>
<pre><code>[2021-10-05 9:38:57.350 AM] [MSTest][Discovery][WinUI3-Demo\WinUI3-UnitTests\bin\Debug\net5.0-windows10.0.19041\WinUI3-UnitTests.dll] Failed to discover tests from assembly WinUI3-Demo\WinUI3-UnitTests\bin\Debug\net5.0-windows10.0.19041\WinUI3-UnitTests.dll. Reason:File does not exist: WinUI3-Demo\WinUI3-UnitTests\bin\Debug\net5.0-windows10.0.19041\WinUI3-UnitTests.dll
</code></pre>
<p>In the MSTest output log it throws a System.InvalidOperation exception</p>
<pre><code>TpTrace Information: 0 : 4580, 4, 2021/10/01, 16:05:24.725, 12341249999384, testhost.x86.dll, AssemblyResolver.OnResolve: Resolved assembly: Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices, from path: \WinUI3-Demo\WinUI3-UnitTests\bin\Debug\net5.0-windows10.0.19041\Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.dll
TpTrace Information: 0 : 4580, 4, 2021/10/01, 16:05:24.725, 12341250002103, testhost.x86.dll, MSTestExecutor.RunTests: Running tests from sources.
TpTrace Information: 0 : 4580, 4, 2021/10/01, 16:05:24.728, 12341250024421, testhost.x86.dll, CollectSourceInformation value Found : False 
TpTrace Error: 0 : 4580, 4, 2021/10/01, 16:05:24.773, 12341250480636, testhost.x86.dll, Exception of type 'System.InvalidOperationException' was thrown.
TpTrace Information: 0 : 4580, 4, 2021/10/01, 16:05:24.774, 12341250491724, testhost.x86.dll, AssemblyResolver.OnResolve: Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.resources: Resolving assembly.
TpTrace Information: 0 : 4580, 4, 2021/10/01, 16:05:24.774, 12341250492593, testhost.x86.dll, AssemblyResolver.OnResolve: Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.resources: Searching in: 'WinUI3-Demo\WinUI3-UnitTests\bin\Debug\net5.0-windows10.0.19041'.
TpTrace Information: 0 : 4580, 4, 2021/10/01, 16:05:24.774, 12341250493693, testhost.x86.dll, AssemblyResolver.OnResolve: Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.resources: Assembly path does not exist: 'WinUI3-Demo\WinUI3-UnitTests\bin\Debug\net5.0-windows10.0.19041\Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.resources.dll', returning.
TpTrace Information: 0 : 4580, 4, 2021/10/01, 16:05:24.775, 12341250494624, testhost.x86.dll, AssemblyResolver.OnResolve: Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.resources: Assembly path does not exist: 'WinUI3-Demo\WinUI3-UnitTests\bin\Debug\net5.0-windows10.0.19041\Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.resources.exe', returning.
TpTrace Information: 0 : 4580, 4, 2021/10/01, 16:05:24.775, 12341250495194, testhost.x86.dll, AssemblyResolver.OnResolve: Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.resources: Failed to load assembly.
</code></pre>
<p>My Nuget packages for reference</p>
<pre><code>    &lt;PackageReference Include=&quot;Microsoft.Graphics.Win2D&quot; Version=&quot;1.0.0.26-experimental1&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.ProjectReunion&quot; Version=&quot;0.8.4&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.ProjectReunion.Foundation&quot; Version=&quot;0.8.4&quot; /&gt;
    &lt;PackageReference Include=&quot;Vortice.WinUI&quot; Version=&quot;2.0.20-beta&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;16.11.0&quot; /&gt;
    &lt;PackageReference Include=&quot;MSTest.TestAdapter&quot; Version=&quot;2.2.7&quot; /&gt;
    &lt;PackageReference Include=&quot;MSTest.TestFramework&quot; Version=&quot;2.2.7&quot; /&gt;
</code></pre>
",https://stackoverflow.com/questions/69450999/mstest-v2-wont-run-with-net5-0-windows,"['c#', 'visual-studio', 'mstest', '.net-5', 'winui-3']",559,True,5,2
How to compare file paths from JsonConfigurationSources and Directory.GetFiles properly?,"<p>I created an extension method to add all JSON configuration files to the <code>IConfigurationBuilder</code></p>
<pre><code>public static class IConfigurationBuilderExtensions
{
    public static IConfigurationBuilder AddJsonFilesFromDirectory(
        this IConfigurationBuilder configurationBuilder,
        IFileSystem fileSystem,
        string pathToDirectory,
        bool fileIsOptional,
        bool reloadConfigurationOnFileChange,
        string searchPattern = &quot;*.json&quot;,
        SearchOption directorySearchOption = SearchOption.AllDirectories)
    {
        var jsonFilePaths = fileSystem.Directory.EnumerateFiles(pathToDirectory, searchPattern, directorySearchOption);

        foreach (var jsonFilePath in jsonFilePaths)
        {
            configurationBuilder.AddJsonFile(jsonFilePath, fileIsOptional, reloadConfigurationOnFileChange);
        }

        return configurationBuilder;
    }
}
</code></pre>
<p>and want to create tests for it using xUnit. Based on</p>
<p><a href=""https://stackoverflow.com/questions/1087351/how-do-you-mock-out-the-file-system-in-c-sharp-for-unit-testing"">How do you mock out the file system in C# for unit testing?</a></p>
<p>I installed the packages <strong>System.IO.Abstractions</strong> and <strong>System.IO.Abstractions.TestingHelpers</strong> and started to test that JSON files from directories have been added</p>
<pre><code>public sealed class IConfigurationBuilderExtensionsTests
{
    private const string DirectoryRootPath = &quot;./&quot;;
    
    private readonly MockFileSystem _fileSystem;

    public IConfigurationBuilderExtensionsTests()
    {
        _fileSystem = new MockFileSystem(new[]
            {
                &quot;text.txt&quot;, 
                &quot;config.json&quot;, 
                &quot;dir/foo.json&quot;, 
                &quot;dir/bar.xml&quot;, 
                &quot;dir/sub/deeper/config.json&quot;
            }
            .Select(filePath =&gt; Path.Combine(DirectoryRootPath, filePath))
            .ToDictionary(
            filePath =&gt; filePath, 
            _ =&gt; new MockFileData(string.Empty)));
    }
    
    [Theory]
    [InlineData(&quot;*.json&quot;, SearchOption.AllDirectories)]
    [InlineData(&quot;*.json&quot;, SearchOption.TopDirectoryOnly)]
    // ... more theories go here ...
    public void ItShouldAddJsonFilesFromDirectory(string searchPattern, SearchOption searchOption)
    {
        var addedJsonFilePaths = new ConfigurationBuilder()
            .AddJsonFilesFromDirectory(_fileSystem, DirectoryRootPath, true, true, searchPattern, searchOption)
            .Sources
            .OfType&lt;JsonConfigurationSource&gt;()
            .Select(jsonConfigurationSource =&gt; jsonConfigurationSource.Path)
            .ToArray();
        
        var jsonFilePathsFromTopDirectory = _fileSystem.Directory.GetFiles(DirectoryRootPath, searchPattern, searchOption);
        
        Assert.True(addedJsonFilePaths.Length == jsonFilePathsFromTopDirectory.Length);
    
        for (int i = 0; i &lt; addedJsonFilePaths.Length; i++)
        {
            Assert.Equal(
                jsonFilePathsFromTopDirectory[i],
                Path.DirectorySeparatorChar + addedJsonFilePaths[i]);
        }
    }
}
</code></pre>
<p>The tests are passing but I would like to know if I could get in trouble when prepending <code>Path.DirectorySeparatorChar</code> to <code>addedJsonFilePaths[i]</code>.</p>
<p>The problem is that</p>
<ul>
<li><code>jsonFilePathsFromTopDirectory[i]</code> returns &quot;/config.json&quot;</li>
<li><code>addedJsonFilePaths[i]</code> returns &quot;config.json&quot;</li>
</ul>
<p>so I have to prepend a slash at the beginning. Do you have any suggestions how to improve this / avoid later problems?</p>
",https://stackoverflow.com/questions/70378711/how-to-compare-file-paths-from-jsonconfigurationsources-and-directory-getfiles-p,['c#'],366,True,10,3
Azure Functions (AF) 3.0/.NET 5.0/XUnit Unit Testing - Compilation Errors (C#),"<p>I am trying to adapt the Microsoft example for AF 3.0/.NET Core 3.1/xUnit (see <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/functions-test-a-function"" rel=""nofollow noreferrer"">Strategies for testing your code in Azure Functions</a>) to work with AF 3.0/.NET 5.0/xUnit.  However, I am running into compilation issues.</p>
<p>The Azure Function is a simple HTTP Trigger (GET only), ExportFuncApp.csproj file is as follows:</p>
<pre><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;
  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net5.0&lt;/TargetFramework&gt;
    &lt;AzureFunctionsVersion&gt;v3&lt;/AzureFunctionsVersion&gt;
    &lt;OutputType&gt;Exe&lt;/OutputType&gt;
  &lt;/PropertyGroup&gt;
  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.Functions.Worker.Extensions.Http&quot; Version=&quot;3.0.12&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.Functions.Worker.Sdk&quot; Version=&quot;1.2.0&quot; OutputItemType=&quot;Analyzer&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.Azure.Functions.Worker&quot; Version=&quot;1.5.2&quot; /&gt;
  &lt;/ItemGroup&gt;
  &lt;ItemGroup&gt;
    &lt;None Update=&quot;host.json&quot;&gt;
      &lt;CopyToOutputDirectory&gt;PreserveNewest&lt;/CopyToOutputDirectory&gt;
    &lt;/None&gt;
    &lt;None Update=&quot;local.settings.json&quot;&gt;
      &lt;CopyToOutputDirectory&gt;PreserveNewest&lt;/CopyToOutputDirectory&gt;
      &lt;CopyToPublishDirectory&gt;Never&lt;/CopyToPublishDirectory&gt;
    &lt;/None&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;
</code></pre>
<p>The ExportFunc.cs file is as follows:</p>
<pre><code>using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;

namespace ExportFuncApp
{
    public class ExportFunc
    {
        [Function(nameof(ExportFunc))]
        public static HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;)] HttpRequestData req,
            FunctionContext executionContext)
        {
            var logger = executionContext.GetLogger(&quot;ExportFunc&quot;);
            logger.LogInformation(&quot;C# HTTP trigger function processed a request.&quot;);

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add(&quot;Content-Type&quot;, &quot;text/plain; charset=utf-8&quot;);

            response.WriteString(&quot;Welcome to Azure Functions!&quot;);

            return response;
        }
    }
}
</code></pre>
<p>Nothing special there.  However, XUnit tests provided by Microsoft (.NET Core 3.1) are not really applicable to .NET 5.0.  There was a StackOverflow article on the subject: <a href=""https://stackoverflow.com/questions/67937686/testing-an-azure-function-in-net-5"">Testing an Azure Function in .NET 5</a>.  4 solutions were given in the article and all of them have compile issues.  The first solution given was (ExportFuncUnitTests2.cs):</p>
<pre><code>using Xunit;
using ExportFuncApp;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using Moq;
using Microsoft.Azure.Functions.Worker;
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Azure.Functions.Worker.Http;

namespace ExportFuncAppUnitTestsXunit
{
    public class ExportFuncUnitTests2
    {
        [Fact]
        public async Task Http_trigger_should_return_known_string()
        {
            var serviceCollection = new ServiceCollection();
            serviceCollection.AddScoped&lt;ILoggerFactory, LoggerFactory&gt;();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var context = new Mock&lt;FunctionContext&gt;();
            context.SetupProperty(c =&gt; c.InstanceServices, serviceProvider);

            var byteArray = Encoding.ASCII.GetBytes(&quot;test&quot;);
            var bodyStream = new MemoryStream(byteArray);

            var request = new Mock&lt;HttpRequestData&gt;(context.Object);
            request.Setup(r =&gt; r.Body).Returns(bodyStream);
            request.Setup(r =&gt; r.CreateResponse()).Returns(() =&gt;
            {
                var response = new Mock&lt;HttpResponseData&gt;(context.Object);
                response.SetupProperty(r =&gt; r.Headers, new HttpHeadersCollection());
                response.SetupProperty(r =&gt; r.StatusCode);
                response.SetupProperty(r =&gt; r.Body, new MemoryStream());
                return response.Object;
            });

            var result = await ExportFunc.Run(request.Object, context.Object);
            result.HttpResponse.Body.Seek(0, SeekOrigin.Begin);

            // Assert
            var reader = new StreamReader(result.HttpResponse.Body);
            var responseBody = await reader.ReadToEndAsync();
            Assert.NotNull(result);
            Assert.Equal(HttpStatusCode.OK, result.HttpResponse.StatusCode);
            Assert.Equal(&quot;Hello test&quot;, responseBody);
        }
    }
}
</code></pre>
<p>This results in a compilation error in ExportFuncUnitTests2.cs:</p>
<pre><code>CS1061  'HttpResponseData' does not contain a definition for 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'HttpResponseData' could be found (are you missing a using directive or an assembly reference?)
for:
var result = await ExportFunc.Run(request.Object, context.Object);
</code></pre>
<p>The second solution given in the article involves FakeHttpRequestData.cs:</p>
<pre><code>using System;
using System.Collections.Generic;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.Functions.Worker;
using System.IO;
using System.Security.Claims;

namespace ExportFuncAppUnitTestsXunit
{
    class FakeHttpRequestData : HttpRequestData
    {
        public FakeHttpRequestData(FunctionContext functionContext, Uri url, Stream body = null) : base(functionContext)
        {
            Url = url;
            Body = body ?? new MemoryStream();
        }

        public override Stream Body { get; } = new MemoryStream();

        public override HttpHeadersCollection Headers { get; } = new HttpHeadersCollection();

        public override IReadOnlyCollection&lt;IHttpCookie&gt; Cookies { get; }

        public override Uri Url { get; }

        public override IEnumerable&lt;ClaimsIdentity&gt; Identities { get; }

        public override string Method { get; }

        public override HttpResponseData CreateResponse()
        {
            return new FakeHttpResponseData(FunctionContext);
        }
    }
}
</code></pre>
<p>and, FakeHttpResponseData.cs:</p>
<pre><code>using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Azure.Functions.Worker;
using System.Net;
using System.IO;

namespace ExportFuncAppUnitTestsXunit
{
    class FakeHttpResponseData : HttpResponseData
    {
        public FakeHttpResponseData(FunctionContext functionContext) : base(functionContext)
        {
        }

        public override HttpStatusCode StatusCode { get; set; }
        public override HttpHeadersCollection Headers { get; set; } = new HttpHeadersCollection();
        public override Stream Body { get; set; } = new MemoryStream();
        public override HttpCookies Cookies { get; }
    }
}
</code></pre>
<p>And the test is (ExportFuncUnitTests2.cs):</p>
<pre><code>using Xunit;
using ExportFuncApp;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using Moq;
using Microsoft.Azure.Functions.Worker;
using System;
using System.Net;
using Microsoft.Extensions.Logging.Abstractions;

namespace ExportFuncAppUnitTestsXunit
{
    public class ExportFuncUnitTests2
    {
        [Fact]
        public async Task Http_trigger_should_return_known_string()
        {
            // Arrange
            var body = new MemoryStream(Encoding.ASCII.GetBytes(&quot;{ \&quot;test\&quot;: true }&quot;));
            var context = new Mock&lt;FunctionContext&gt;();
            var request = new FakeHttpRequestData(
                           context.Object,
                           new Uri(&quot;https://stackoverflow.com&quot;),
                          body);

            // Act
            var function = new ExportFunc(new NullLogger&lt;ExportFunc&gt;());
            var result = await function.Run(request, context);
            result.HttpResponse.Body.Position = 0;

            // Assert
            var reader = new StreamReader(result.HttpResponse.Body);
            var responseBody = await reader.ReadToEndAsync();
            Assert.NotNull(result);
            Assert.Equal(HttpStatusCode.OK, result.HttpResponse.StatusCode);
            Assert.Equal(&quot;Hello test&quot;, responseBody);
        }
    }
}
</code></pre>
<p>The ExportFuncUnitTests2.cs has the following compilation errors:</p>
<pre><code>CS1729  'ExportFunc' does not contain a constructor that takes 1 arguments
for:
var function = new ExportFunc(new NullLogger&lt;ExportFunc&gt;());
</code></pre>
<p>and</p>
<pre><code>CS1503  Argument 2: cannot convert from 'Moq.Mock&lt;Microsoft.Azure.Functions.Worker.FunctionContext&gt;' to 'Microsoft.Azure.Functions.Worker.FunctionContext'
for:
var result = await function.Run(request, context);
</code></pre>
<p>I the article <a href=""https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide"" rel=""nofollow noreferrer"">Guide for running C# Azure Functions in an isolated process</a> was somewhat useful but no help in terms of unit testing.  Maybe I am missing the point.  Since there is no examples/documentation on how to do unit testing for AF 3.0 with .NET 5.0 from Microsoft then I should not be trying to do that?</p>
<p>Any pointers will be greatly appreciated.  Thanks!</p>
",https://stackoverflow.com/questions/70119693/azure-functions-af-3-0-net-5-0-xunit-unit-testing-compilation-errors-c,"['unit-testing', 'azure-functions', 'visual-studio-2019', '.net-5', 'xunit']",191,False,0,1
Install luarocks-3.8.0 on windows-latest github workflow runner with custom lua intepreter luajit-2.0.4,"<p>I am trying to install luarocks-3.8.0 on githubs workflow runner using windows-stable, but unfortunatelly I am not able to set any <a href=""https://github.com/luarocks/luarocks/wiki/Installation-instructions-for-Windows"" rel=""nofollow noreferrer"">arguments</a> with success.</p>
<p>I tried the following:</p>
<ul>
<li>without any argument</li>
<li>with and without /P</li>
<li>with and without /LUA</li>
<li>with and without /INC</li>
<li>with and without /LIB</li>
<li>with and without /BIN</li>
</ul>
<p>One of the Powershell commands I used, see below:</p>
<pre><code>Start-Process -FilePath &quot;${{ github.workspace }}\luarocks-3.8.0-win32\luarocks-3.8.0-win32\install.bat&quot; -ArgumentList &quot;/FORCECONFIG&quot; -Wait -NoNewWindow
</code></pre>
<p>As you can see I also tried to provide a config.lua by using /FORCECONFIG and copying the config file from ${{ github.workspace }}\luarocks-3.8.0\config-windows.5.1.lua to C:\luarocks\config.lua,</p>
<p>but I always get this error:</p>
<blockquote>
<p>The system cannot find the path specified.</p>
</blockquote>
<p>I tried --verbose without success.</p>
<p>Additional info:</p>
<ul>
<li>I am using luaJIT-2.0.4 and installed it on the workflow runner</li>
<li>I need luarocks to install luaunit for unit testing</li>
<li>inside of directory <a href=""https://github.com/Ismoh/NoitaMP/tree/unit-tests/.building"" rel=""nofollow noreferrer"">.building</a> you can see all provided files</li>
<li>Workflow action can be found <a href=""https://github.com/Ismoh/NoitaMP/actions/workflows/windows-latest-lua-unit-testing.yml"" rel=""nofollow noreferrer"">here</a></li>
<li>and the workflow action yml <a href=""https://github.com/Ismoh/NoitaMP/actions/runs/1607206290/workflow#L46"" rel=""nofollow noreferrer"">file</a> &quot;Windows Lua Unit Testing&quot; - see step &quot;Install luarocks 3.8.0&quot;</li>
</ul>
<p>If you need any additional information, please let me know!
I am getting out of ideas how to solve this!</p>
<p>A verbose output with install.bat would really help me out, but it doesn't seems to be working and I am unable to find anything about verbose output on windows with install.bat!</p>
",https://stackoverflow.com/questions/70437121/install-luarocks-3-8-0-on-windows-latest-github-workflow-runner-with-custom-lua,"['lua', 'github-actions', 'luarocks', 'github-actions-runners']",141,True,0,1
Github actions workflow for an R package using reticulate and python dependencies,"<p>I'm trying to install <code>python</code> dependencies for automating unit testing within a <code>github</code> repository of an <code>R</code> package that uses <a href=""https://rstudio.github.io/reticulate/"" rel=""nofollow noreferrer""><code>reticulate</code></a> (specifically converting <a href=""https://networkx.org/"" rel=""nofollow noreferrer""><code>networkx</code></a> objects to <a href=""https://igraph.org/r/"" rel=""nofollow noreferrer""><code>iGraph</code></a> <code>R</code> objects <a href=""https://networkx.org/documentation/stable//reference/readwrite/json_graph.html"" rel=""nofollow noreferrer"">via json</a>). I'm working from <a href=""https://github.com/rstudio/reticulate/blob/master/.github/workflows/R-CMD-check.yaml"" rel=""nofollow noreferrer""><code>reticulate</code>'s <code>github-action</code></a> and get stuck building within <code>linux</code> (<code>ubuntu</code> specifically), where it seems <code>conda</code> may be the safest way to install python dependencies.</p>
<pre><code>Preparing transaction: ...working... done
Verifying transaction: ...working... done
Executing transaction: ...working... done
#
# To activate this environment, use
#
#     $ conda activate r-reticulate
#
# To deactivate an active environment, use
#
#     $ conda deactivate

Error: Error: package or namespace load failed for ‘py2Rgraphs’:
 .onLoad failed in loadNamespace() for 'py2Rgraphs', details:
  call: NULL
  error: could not find a Python environment for /usr/bin/python3
Error: Error: loading failed
Execution halted
ERROR: loading failed
* removing ‘/home/runner/work/py2Rgraphs/py2Rgraphs/check/py2Rgraphs.Rcheck/py2Rgraphs’

1 error ✖ | 0 warnings ✔ | 1 note ✖
</code></pre>
<p>I'm also having issues with <code>macOS</code> and <code>windows</code> but wanted to start by fixing the <code>linux</code> builds.
As I understand it, it will be particularly difficult to enable tests that require <code>python</code> on <code>CRAN</code>, so at least automating that within the <code>git</code> repository seems a crucial prerequisite. I can at least confirm the tests pass fine locally and on some colleagues' computers.</p>
",https://stackoverflow.com/questions/67021631/github-actions-workflow-for-an-r-package-using-reticulate-and-python-dependencie,"['python', 'r', 'github-actions', 'reticulate', 'testthat']",169,False,4,0
bash variable only retaining last line of grep,"<p>I'm trying to write a git hook which would allow me to collect unit testing reports post commit.</p>
<p>I'm on a windows machine but using bash for the hook itself. It seems to run fine. Here's what I have so far:</p>
<pre><code>#!/bin/sh
test_summary=$(pytest -v | grep -E &quot;.+\.py::.+[A-Z]+&quot;)
commit_id=$(git rev-parse HEAD)
</code></pre>
<p>The issue is that the variable <code>test_summary</code> retains only the last line from the <code>grep</code> match. I know my piped <code>pytest</code>/<code>grep</code> is fine since running it on an interactive msys terminal gives the correct output with all the matches:</p>
<pre><code>$ pytest -v | grep -E &quot;.+.py::.+[A-Z]+&quot;
test_main.py::test_main PASSED                                           [ 33%]
test_main.py::test2 FAILED                                               [ 66%]
test_main.py::test3 PASSED                                               [100%]
</code></pre>
<p><code>test_summary</code> contains the following:</p>
<pre><code>$ echo $test_summary
 test_main.py::test3 PASSED [100%]3%]
</code></pre>
<p>Why does it only retain the last line plus some mumbo jumbo from the first line?</p>
<p>I don't get it....</p>
",https://stackoverflow.com/questions/69699969/bash-variable-only-retaining-last-line-of-grep,"['windows', 'bash']",120,True,3,2
How should I write my unit tests for a child class?,"<p>Say I have a class</p>
<pre><code>public class Foo extends Bar
{
   public Response post()
   {
      return authorize();
   }

   // override some additional methods from Bar class
}
</code></pre>
<p>and another class</p>
<pre><code>public class Bar
{
  public Response get()
  {
    return authorize();
  }

  public Response post()
  {
    return authorize();
  }

  public Response authorize()
  {
    // let's assume this method is &quot;complicated&quot; and has 200+ lines of code... lots of diff code paths etc
  }

}
</code></pre>
<p>So I was thinking of a few different approaches in terms of unit testing</p>
<ol>
<li><p>I directly call <code>authorize</code> and test every single possible code path. Then I write 1 happy path unit test for the <code>get</code> and <code>post</code> methods for <code>Foo</code> and <code>Bar</code> for completeness.</p>
</li>
<li><p>I directly call <code>get</code> and <code>post</code> methods of both classes, and decide to only write tests for all combinations against one method only.</p>
</li>
<li><p>I completely ignore my <code>get</code> and <code>post</code> methods and assume that as long as I fully test my <code>authorize</code> method I'm good.</p>
</li>
</ol>
<p>Am I complicating this? What's the best practice here.</p>
",https://stackoverflow.com/questions/67429032/how-should-i-write-my-unit-tests-for-a-child-class,"['java', 'junit']",787,True,2,2
Why are my firebase emulator get-call promises not resolving in jest unit tests,"<ul>
<li>Using react with firestore as my database running as a local emulator.</li>
<li>Testing with react-script test which uses jest.</li>
</ul>
<p>Now when calling firestore set() and get() functions from my react app in the browser everything works.
But when unit testing those same calls only the set() promise resolves. The get() promise never resolves (&quot;Exceeded timeout of 5000 ms for a test.[I tested with timeouts &gt; 100000000])
The emulator receives the get() request without any problem.(It gets logged in the Request tab of the emulator)</p>
<p>This is a simple test which isolates my problem.</p>
<pre><code>import { firestore } from '../firebase';

it('Gets from Firestore', async () =&gt; {
  try {
    await firestore.collection(&quot;users&quot;).doc(&quot;testUser&quot;).set({ name: &quot;Frank&quot; })
    await firestore.collection(&quot;users&quot;).doc(&quot;testUser&quot;).get()
    expect(1).toBe(1);
  } catch (err) {
    console.log(err)
  }
})
</code></pre>
<p>Firestore initialization (creds not included):</p>
<pre><code>import firebase from &quot;firebase/app&quot;;

import 'firebase/firestore';
import 'firebase/auth';

const firebaseConfig = {
    apiKey: &quot;&quot;,
    authDomain: &quot;&quot;,
    projectId: &quot;&quot;,
    storageBucket: &quot;&quot;,
    messagingSenderId: &quot;&quot;,
    appId: &quot;&quot;,
    measurementId: &quot;&quot;
  };
  
firebase.initializeApp(firebaseConfig);
const firestore = firebase.firestore();
if (window.location.hostname === &quot;localhost&quot;) {
  firestore.useEmulator(&quot;localhost&quot;, 8080);
}
export {firestore}
export default firebase;
</code></pre>
",https://stackoverflow.com/questions/68376016/why-are-my-firebase-emulator-get-call-promises-not-resolving-in-jest-unit-tests,"['reactjs', 'firebase', 'unit-testing', 'google-cloud-firestore', 'promise']",168,False,2,1
How to mock a ZipFile object in S3?,"<p>I'd like to test uploading an archive to S3 bucket. This archive is unzipped so I'd like to test the extracted JSON files as well.
Here is what I want to test:</p>
<pre class=""lang-py prettyprint-override""><code>def get_files_from_s3(bucket_name, s3_prefix):
    files = []
    s3_resource = boto3.resource(&quot;s3&quot;)
    bucket = s3_resource.Bucket(bucket_name)
    response = bucket.objects.filter(Prefix=s3_prefix)
    for obj in response:
        if obj.key.endswidth('.zip'):
            buffer = BytesIO(obj.get()[&quot;Body&quot;].read())
            print(&quot;Before unzipping the file&quot;)
            z = ZipFile(buffer)
            for filename in z.namelist():
                print(&quot;After unzipping the file&quot;)
                if filename == &quot;files/file1.json&quot;:
                    for dict in self.parse_json(z, filename):
                    # store some data from the json
            data.append(...)
    return data

def parse_json(obj, file):
    with obj.open(file, &quot;r&quot;) as f:
        data = json.loads(f.read())
    return data[&quot;some_key&quot;]
</code></pre>
<p>and here is what I've tried in unit testing after getting an answer to <a href=""https://stackoverflow.com/questions/70233225/how-to-mock-list-of-response-objects-from-boto3"">my previous question here</a>:</p>
<pre class=""lang-py prettyprint-override""><code>from moto import mock_s3

@pytest.fixture(scope='function')
def aws_credentials():
    &quot;&quot;&quot;Mocked AWS Credentials, to ensure we're not touching AWS directly&quot;&quot;&quot;
    os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
    os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
    os.environ['AWS_SECURITY_TOKEN'] = 'testing'
    os.environ['AWS_SESSION_TOKEN'] = 'testing'


@mock_s3
def test_get_files_from_s3(self, aws_credentials):
    s3 = boto3.resource('s3')
    bucket = s3.Bucket(self.bucket_name)
    # Create the bucket first, as we're interacting with an empty mocked 'AWS account'
    bucket.create()

    # Create some example files that are representative of what the S3 bucket would look like in production
    client = boto3.client('s3')
    client.put_object(Bucket=self.bucket_name, Key=s3_prefix + &quot;file.zip&quot;, Body=open('local_file.zip', 'r'))
    client.put_object(Bucket=self.bucket_name, Key=s3_prefix + &quot;file.nonzip&quot;, Body=&quot;...&quot;)

    # Retrieve the files again using whatever logic
    files = module.get_files_from_s3(BUCKET_NAME, S3_PREFIX)
    self.assertEqual(['file.zip'], files)
</code></pre>
<p>So my concern here is how to mock a ZipFile object when passing to moto? because when I passed the <code>Body</code> argument with the actual zip file that I wanted to send to the S3 client, I found this error: <code>E UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9b in position 10: invalid start byte</code></p>
<p>Another concern is how to pass that object to another function like <code>parse_json()</code>?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/70243296/how-to-mock-a-zipfile-object-in-s3,"['python', 'unit-testing', 'amazon-s3', 'mocking', 'boto3']",537,True,2,1
Correctly testing that a method does nothing under certain cicrumstances,"<p>I am running into a little trouble with my unit testing code and SonarQube.</p>
<p>I have the following simple test:</p>
<pre><code>    [TestMethod]
    public void TestFormat_Null()
    {
        _sut.Format(null);
    }

    public void Format(IPhone phoneNumber)
    {
        if (phoneNumber == null) return;
        FormatNumber(phoneNumber);
        FormatAreaCode(phoneNumber);
        FormatCountryCode(phoneNumber);
    }
</code></pre>
<p>The requirement here is, that if null is passed in, the method will simply do nothing, since there is nothing to format and also not crash with an exception.</p>
<p>Now the problem we are getting is that our SonarQube complains, that this is a test without any Assertions.</p>
<p>Is there any better way to declare a test that tests for a method not doing anything or is this a case where the SonarQube warning should simply be ignored?</p>
",https://stackoverflow.com/questions/67583943/correctly-testing-that-a-method-does-nothing-under-certain-cicrumstances,"['c#', 'unit-testing', 'sonarqube', 'mstest']",299,True,2,2
NSubstitute test failing only in build server,"<p>Using the NSubstite framework for mocking in c# unit testing project and recently we created version2 API controller and business and repositories. But when created the tests for the controller the very first case is failing in Azure build pipeline. The same test case running without error with status as pass. I have tried all the ways from blogs but no luck. here is the error and code.</p>
<p>ERROR:</p>
<pre><code>Test method XXX threw exception:
NSubstitute.Exceptions.RedundantArgumentMatcherException: Some argument specifications (e.g. Arg.Is, Arg.Any) were left over after the last call.

This is often caused by using an argument spec with a call to a member NSubstitute does not handle (such as a non-virtual member or a call to an instance which is not a substitute), or for a purpose other than specifying a call (such as using an arg spec as a return value). For example:

var sub = Substitute.For&lt;SomeClass&gt;();
var realType = new MyRealType(sub);
// INCORRECT, arg spec used on realType, not a substitute:
realType.SomeMethod(Arg.Any&lt;int&gt;()).Returns(2);
// INCORRECT, arg spec used as a return value, not to specify a call:
sub.VirtualMethod(2).Returns(Arg.Any&lt;int&gt;());
// INCORRECT, arg spec used with a non-virtual method:
sub.NonVirtualMethod(Arg.Any&lt;int&gt;()).Returns(2);
// CORRECT, arg spec used to specify virtual call on a substitute:
sub.VirtualMethod(Arg.Any&lt;int&gt;()).Returns(2);
To fix this make sure you only use argument specifications with calls to substitutes. If your substitute is a class, make sure the member is virtual.

Another possible cause is that the argument spec type does not match the actual argument type, but code compiles due to an implicit cast. For example, Arg.Any&lt;int&gt;() was used, but Arg.Any&lt;double&gt;() was required.

NOTE: the cause of this exception can be in a previously executed test. Use the diagnostics below to see the types of any redundant arg specs, then work out where they are being created.

Diagnostic information:

Remaining (non-bound) argument specifications:
any Int64
any Int64

All argument specifications:
any Int64
any Int64
any Int64
any Int64


Stack trace
at NSubstitute.Core.Arguments.ArgumentSpecificationsFactory.Create(IList`1 argumentSpecs, Object[] arguments, IParameterInfo[] parameterInfos, MethodInfo methodInfo, MatchArgs matchArgs)
at NSubstitute.Core.CallSpecificationFactory.CreateFrom(ICall call, MatchArgs matchArgs)
at NSubstitute.Routing.Handlers.RecordCallSpecificationHandler.Handle(ICall call)
at NSubstitute.Routing.Route.Handle(ICall call)
at NSubstitute.Core.CallRouter.Route(ICall call)
at NSubstitute.Proxies.CastleDynamicProxy.CastleForwardingInterceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at NSubstitute.Proxies.CastleDynamicProxy.ProxyIdInterceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Castle.Proxies.ObjectProxy_4.GetTemplateByApplicationIdTemplateId(Int64 applicationId, Int64 templateId)
at XXX() in YYY.cs:line 61

public Interface XXX
{
long Process(long x, string y, out string z);
}

[TestMethod]
public void XXX()
{
XXX _business = Substitute.For&lt;XXX&gt;();
Object model = GetFakeModel();
_business.Process(Arg.Any&lt;long&gt;(), Arg.Any&lt;string&gt;(), out Arg.Any&lt;string&gt;())
.Returns(x =&gt; { x[2] = &quot;Success&quot;; return 1; });
var _controller = new YYY(_business);
var result = _controller.Post(1, model) as ObjectResult;
Assert.IsNotNull(result);
}
</code></pre>
<p>How can we solve this problem. even i cant debug as its passing in the local machine. Tried running tests in sequential by adding a annotation [DoNotParallelize] but no luck.</p>
",https://stackoverflow.com/questions/66892982/nsubstitute-test-failing-only-in-build-server,"['c#-3.0', 'nsubstitute', 'vs-unit-testing-framework']",378,False,2,0
java.lang.ExceptionInInitializerError on sparkContext.parallelize() caused by JsonMappingException: Incompatible Jackson version,"<p>I am trying to write some unit testing for my Apache Spark code. Below are my first simple try</p>
<pre><code>public class SparkHelperTest {

    private JavaSparkContext sparkCtx;

    @Before
    public void setUp() throws IllegalArgumentException, IOException {
        SparkConf conf = new SparkConf();
        conf.setMaster(&quot;local[2]&quot;);
        conf.setAppName(&quot;sparkHelperTest&quot;);
        sparkCtx = new JavaSparkContext(conf);
    }

    @Test
    public void test() {
        final List&lt;Integer&gt; nums = new ArrayList&lt;Integer&gt;();
        nums.add(3);
        nums.add(4);
        nums.add(2);
        JavaRDD&lt;Integer&gt; rdd = sparkCtx.parallelize(nums,1);
        assertEquals(3, rdd.count());
    }
}
</code></pre>
<p>However, I got the following error:</p>
<pre><code>java.lang.ExceptionInInitializerError
    at org.apache.spark.SparkContext.withScope(SparkContext.scala:714)
    at org.apache.spark.SparkContext.parallelize(SparkContext.scala:728)
    at org.apache.spark.api.java.JavaSparkContext.parallelize(JavaSparkContext.scala:143)
    at com.firsttry.SparkHelperTest.test(SparkHelperTest.java:39)
    ......
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Incompatible Jackson version: 2.9.7
    at com.fasterxml.jackson.module.scala.JacksonModule$class.setupModule(JacksonModule.scala:64)
    at com.fasterxml.jackson.module.scala.DefaultScalaModule.setupModule(DefaultScalaModule.scala:18)
    at com.fasterxml.jackson.databind.ObjectMapper.registerModule(ObjectMapper.java:751)
    at org.apache.spark.rdd.RDDOperationScope$.&lt;init&gt;(RDDOperationScope.scala:81)
    at org.apache.spark.rdd.RDDOperationScope$.&lt;clinit&gt;(RDDOperationScope.scala)
    ... 29 more
</code></pre>
<p>As you can see from the error, it was caused by some depenencies conflicts. Below are some of my dependencies in the build.gradle:</p>
<pre><code>compile (
            'io.dropwizard:dropwizard-core:' + dropwizardVersion,
            ......
)

testCompileOnly (
            'com.sun.jersey:jersey-server:1.17.1',
            'com.sun.jersey:jersey-core:1.17.1',
            'com.sun.jersey:jersey-servlet:1.17.1',
            'com.sun.jersey:jersey-bundle:1.17.1'
    ) 
</code></pre>
<p>I ran the dependencies check, and find the jackson 2.9.7 is coming from the dropWizard core as shown below</p>
<p><a href=""https://i.stack.imgur.com/Nif4A.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Nif4A.png"" alt=""enter image description here"" /></a></p>
<p>I tried the exclude thing and enforcing as below. It seems not working. Am I doing something wrong here?</p>
<pre><code>compile (
                'io.dropwizard:dropwizard-core:' + dropwizardVersion,
                ......
    )
    
testCompileOnly (
                'com.sun.jersey:jersey-server:1.17.1',
                'com.sun.jersey:jersey-core:1.17.1',
                'com.sun.jersey:jersey-servlet:1.17.1',
                'com.sun.jersey:jersey-bundle:1.17.1'
) {
      exclude 'com.fasterxml.jackson.core:*:2.9.7'
      // also tried 
      // force = true 
}
</code></pre>
<p>Is there anyway I EXCLUDE this 2.9.7 version jackson for the unit test only?</p>
",https://stackoverflow.com/questions/69817160/java-lang-exceptionininitializererror-on-sparkcontext-parallelize-caused-by-js,"['java', 'unit-testing', 'apache-spark', 'gradle', 'build.gradle']",261,False,1,0
Why inject the entire DbContext instead of just the necessary DbSets?,"<p>I've seen a lot of projects whether the entire DbContext is injected in a class:</p>
<pre><code>public class MyClass
{
    public MyClass(MyDbContext context)
    {
        ...
    }
    
    public void DoStuff()
    {
         dbContext.MyTable.Select(x =&gt; x...)
    }
}
</code></pre>
<p>Why not do this:</p>
<pre><code>public class MyClass
{
    public MyClass(DbSet&lt;MyType&gt; myTypes)
    {
        ...
    }
    
    public void DoStuff()
    {
         myTypes.Select(x =&gt; x...)
    }
}
</code></pre>
<p>I find #2 makes it more clear as to what data exactly the object needs to operate. It makes unit testing especially more clear as the dependencies are obvious from the constructor. Otherwise, you have to inspect the implementation of the method to find out what data it needs exactly so you can setup your test properly.</p>
<p>So why is #1 the norm?</p>
<p>(P.S. sorry for bad tags but it seems the tag system is broken atm)</p>
",https://stackoverflow.com/questions/68709529/why-inject-the-entire-dbcontext-instead-of-just-the-necessary-dbsets,"['c#', 'entity-framework', 'dependency-injection', 'anti-patterns']",353,True,1,2
How do I mock the settings attribute of an Office object using the office-addin-mock library?,"<p>In order to test this function...</p>
<pre><code>export async function blueBlackToggle() {
  try {
    await Excel.run(async context =&gt; {
      const range = context.workbook.getSelectedRange();
      let blueBlackToggleNum = Office.context.document.settings.get(&quot;blueBlackToggle&quot;);
      console.log(blueBlackToggleNum);
      if (blueBlackToggleNum === 0) {
        const propertiesToGet = range.getCellProperties({
          format: {
            font: {
              color: true
            }
          }
        });
        await context.sync();
        Office.context.document.settings.set(
          &quot;blueBlackToggle&quot;,
          propertiesToGet.value[0][0].format.font.color === &quot;#0000FF&quot; ? 1 : 2
        );
        Office.context.document.settings.saveAsync();
      }
      Office.context.document.settings.set(&quot;blueBlackToggle&quot;, blueBlackToggleNum + 1);
      Office.context.document.settings.saveAsync();
      range.format.font.color = blueBlackToggleNum % 2 === 0 ? &quot;blue&quot; : &quot;black&quot;;
      await context.sync();
    });
  } catch (error) {
    console.error(error);
  }
}
</code></pre>
<p>I made this testing suite...</p>
<pre><code>import 'regenerator-runtime/runtime';
//import add in feature
import * as format from &quot;../format&quot;;
//import mock library
import { OfficeMockObject } from &quot;office-addin-mock&quot;;



const excelHostMockData = {
  context: {
    workbook: {
      range: {
        format:{
            font:{
                color:&quot;#000000&quot;
            }
        },
        address:&quot;C2:G3&quot;,
        value:[[
            {
                format:{
                    font:{
                        color:&quot;#000000&quot;
                    }
                }
            }
        ]],
        getCellProperties: function(obj){
            return this;
        }
      },
      // Mock getSelectedRange method.
      getSelectedRange: function () {
        return this.range;
      },
    },
  },
  // Mock the Excel.run method.
  run: async function(callback) {
    await callback(this.context);
  },
};

const officeMockData = {
    context:{
        document:{
            settings:{
                blueBlackToggle:0,
                get: function(setting){
                    if(setting===&quot;blueBlackToggle&quot;){
                        return this.blueBlackToggle;
                    }
                },
                set: function(setting, value){
                    if(setting===&quot;blueBlackToggle&quot;){
                        this.blueBlackToggle=value;
                    }
                },
                saveAsync: function(){

                }
            }
        }
    }
}

// Create the final mock object from the seed object.
const excelMock = new OfficeMockObject(excelHostMockData);
const officeMock = new OfficeMockObject(officeMockData);

// Define and initialize the Excel object that is called in the changeCellColorYellow function.
global.Excel = excelMock;
global.Office = officeMock;


// Jest test set
describe(&quot;format.blueBlackToggle&quot;, () =&gt; {

    it(&quot;should change color to blue or black&quot;, async () =&gt; {
        await format.blueBlackToggle();        
        expect(excelMock.context.workbook.range.format.font.color).toBe(&quot;black&quot;);
        
    })

})
</code></pre>
<p>I get the error</p>
<p>Error, property was not loaded</p>
<p>at _callee29$ (src/format-updated/functions/format.ts:17:15)</p>
<p>The function doesn't seem to read the blueBlackToggleSetting when using Office.context.document.settings.get(&quot;blueBlackToggle&quot;), although I think I recreated the structure of the Office object correctly. How do I structure my Office mock object to access the settings by the function being tested? There are very few examples of mocking an office object for unit testing in the office js documentation, and none of the examples have settings properties.</p>
",https://stackoverflow.com/questions/70365357/how-do-i-mock-the-settings-attribute-of-an-office-object-using-the-office-addin,"['excel', 'unit-testing', 'office-js', 'excel-web-addins', 'office-web-app']",278,True,1,1
Unit testing IHttpActionResult with OkNegotiatedContentResult having anonymous types,"<p>I am using MS Test for Unit Testing my Web API Controller.</p>
<p>Below is my Web API Controller method with the return type:</p>
<pre><code>public IHttpActionResult MethodName(){ //Code logic 
    return Ok(new { Data = result, Total = (result.Count() &gt; 0 ? result.First().TotalCount : 0) });
}
</code></pre>
<p>In above code snippet:</p>
<ol>
<li>Data is of Type IEnumerable&lt;ViewModelName'&gt;</li>
<li>Total Count is of Type Int</li>
</ol>
<p>Now for testing above API method return type below is what I have tried :</p>
<pre><code>[TestMethod]
public void TestMethodName(){
var result = controller.MethodName();
//Below line is having issue and thus the contentResult is null 
var contentResult = result as OkNegotiatedContentResult&lt;List&lt;ViewModelName&gt;&gt;;
}
</code></pre>
<p>Adding Int to OkNegotiatedContentResult throws error as it only excepts single parameter &lt;T'&gt;</p>
<p>Below is the actual return type from the API:</p>
<p>{System.Web.Http.Results.OkNegotiatedContentResult&lt;&lt;&gt;f__AnonymousType0&lt;System.Collections.Generic.List&lt;ViewModel'&gt;, int&gt;&gt;}</p>
<p>How should I convert result so that I can use its content into Assert ?</p>
<p>Thank you in advance.
Code sample is appreciated.</p>
",https://stackoverflow.com/questions/69359128/unit-testing-ihttpactionresult-with-oknegotiatedcontentresult-having-anonymous-t,"['c#', 'unit-testing', 'asp.net-web-api', 'mstest']",897,True,1,2
Unit Test Observables and check count of subscribers in Angular,"<p>I have subject and observable -</p>
<pre><code>export class WebSocket{
    private _WebSocketSubject: Subject&lt;any&gt;;
    public OWebSockConn$: Observable&lt;any&gt;;

    constructor(){
          this._WebSocketSubject = new Subject&lt;JSON&gt;();
          this.OWebSockConn$ = this._WebSocketSubject.asObservable();
    }

    public receiveData = () =&gt; {
          this._WebSocketSubject$.next(&quot;hi&quot;);
    });
}
</code></pre>
<p>ReceiveData is called to push data. In Unit test i want to know the count of subscribers for this subject and i want to check whether data i receive is correct or not.  So this is my unit test case -</p>
<p>Approach 1:</p>
<pre><code>it('Find_Observanles_AndData_IsCorrect', async ((done) =&gt; {
   myWebSocket.receiveData();
   expect((myWebSocket as any).OWebSockConn$.observers.length).toBe(1);

   myWebSocket.invokeFromWebSockConn$.subscribe((data) =&gt; {
       console.log(&quot;Data reached&quot;);
       expect(data).not.tobe(null);
       done();
  });
}));
</code></pre>
<p>Approach 2:</p>
<pre><code>it('Find_Observanles_AndData_IsCorrect', async(inject( [WebSocket], ( websocket ) =&gt; {
     myWebSocket.receiveData();
     expect((myWebSocket as any).OWebSockConn$.observers.length).toBe(1);
     websocket.OWebSockConn.subscribe(result =&gt;  expect(data).not.tobe(null)); 
}));
</code></pre>
<p>It is not going inside subscribe and console is also not printing, and my subscriber count is 0 although it is subscribed in another service, i tried two approaches i don't know where is the issue, please help a noobie.</p>
<p>Tried approach mentioned here as well -
<a href=""https://stackoverflow.com/questions/34607990/unit-testing-an-observable-in-angular-2/55546267#55546267"">Unit testing an observable in Angular 2</a></p>
",https://stackoverflow.com/questions/66885184/unit-test-observables-and-check-count-of-subscribers-in-angular,"['unit-testing', 'angular8']",163,False,1,0
Mocking a Subject property of mocked service to be subscribed in the Angular unit test,"<p>In my Angular unit testing my mocked service has two properties:</p>
<pre><code>  public messageChange: Subject&lt;ChatMessage&gt; = new Subject&lt;ChatMessage&gt;();
  public gameChange: Subject&lt;GameState&gt; = new Subject&lt;GameState&gt;();
</code></pre>
<p>And in my SUT I use them in my constructor:</p>
<pre><code>this._subChat = this.hub.messageChange.subscribe((message: ChatMessage) =&gt; {
      this.message = message;
      this.messageChange.next(this.message);
    });
    this._subGame = this.hub.gameChange.subscribe((game: GameState) =&gt; {
      this.game.setGame(game);
    });
</code></pre>
<p>Right now I am trying to use these 2 approaches to mock properties from mocked service:</p>
<ul>
<li><a href=""https://stackoverflow.com/a/55279477"">Angular Unit Test Mock Replay Subject</a></li>
<li><a href=""https://stackoverflow.com/a/43793575/12603542"">How to spyOn a value property (rather than a method) with Jasmine</a></li>
</ul>
<p>Riht now my testing looks like this:</p>
<pre><code>describe('SignalRService', () =&gt; {
  let signalrService: SignalRService;
  const hubServiceMock = jasmine.createSpyObj('HubConnectionService', [
    'isConnectionStarted',
  ]);
  const messageChange = new Subject();
  const gameChange = new Subject();

  beforeEach(() =&gt; {
    signalrService = new SignalRService(
      hubServiceMock
    );
    let msg = {} as ChatMessage;
    let gam = {} as GameState;
    messageChange.next(msg);
    gameChange.next(gam);
  });

  it('Service_ShouldBeCreated', () =&gt; {
    spyOnProperty(hubServiceMock, 'messageChange', 'get').and.returnValue(
      messageChange
    );
    spyOnProperty(hubServiceMock, 'gameChange', 'get').and.returnValue(
      gameChange
    );
    expect(signalrService).toBeTruthy();
  });
}
</code></pre>
<p>So in the test I create:</p>
<ul>
<li><p>service mock <code>hubServiceMock</code>,</p>
</li>
<li><p>fake <code>messageChange = new Subject();</code>,</p>
</li>
<li><p>fake <code>gameChange = new Subject();</code>,</p>
</li>
<li><p>i run for both <code>.next</code>,</p>
</li>
<li><p>and I setup spy for properties:</p>
<p><code>spyOnProperty(hubServiceMock, 'messageChange', 'get').and.returnValue( messageChange );</code></p>
<p><code>spyOnProperty(hubServiceMock, 'gameChange', 'get').and.returnValue( gameChange );</code></p>
</li>
</ul>
<p>Why it does not work to me? I receive an error:</p>
<blockquote>
<p>Cannot read property 'subscribe' of undefined</p>
</blockquote>
",https://stackoverflow.com/questions/65780831/mocking-a-subject-property-of-mocked-service-to-be-subscribed-in-the-angular-uni,"['angular', 'unit-testing', 'properties', 'jasmine', 'subject']",2514,True,1,2
Vis-js Timeline error when unit testing click events with test-library,"<p>I'm having some issues with unit testing a react component that uses the vis-js timeline control. The error I'm getting is &quot;Cannot read property 'scale' of undefined&quot;, debugging the code the error happens because the timeaxis object is supposed to have a step property but that property only gets set when the timeaxis's redraw method is ran. I suspect that the issue is that the testing library generates the DOM with no height or width. I would have expected setting the timeaxis option to resolve this issue but that does not seem to be the case. Here is my test method.</p>
<pre><code>const defaultProps: GanttProps = {
    rowData: [],
    data: [],
    expanded: false,
    availabilityItems: [],
    dragLocked: false,
    isVisualizerForPrint: false,
    showNestedOverride: false,
    textItemsForDisplay: [&quot;Name&quot;],
    options: {
        start: moment(0).toDate(),
        end: moment(0).add(1, &quot;year&quot;).toDate(),
        timeAxis: {scale: 'day', step: 30}
    }
};

it(&quot;Should call handleClick&quot;, async () =&gt; {
        const handleClick = jest.fn();
        const props = {
            ...defaultProps,
            click: handleClick,
            data: mockData,
            rowData: mockRowData
        };
        
        render(&lt;Gantt { ...props } /&gt;);

        userEvent.click(screen.getByText(/Test Item/i));

        expect(handleClick).toHaveBeenCalledTimes(1);
    });
</code></pre>
<pre><code>import * as React from &quot;react&quot;;
import ReactDOM from &quot;react-dom&quot;;
import * as visTimeline from &quot;vis-timeline&quot;;
import * as typeDefs from &quot;./../common/typeDefs&quot;;
import moment from &quot;moment&quot;;
import &quot;vis-timeline/styles/vis-timeline-graph2d.min.css&quot;;

export type SchedTemplateFunc = (item: typeDefs.TaskItem, element: any) =&gt; any;

export type SubgroupStackingLookupBuilder = (items: typeDefs.GanttSubgroupData[]) 
    =&gt; { [subgroupId: string]: boolean };

const DefaultTimeZone = &quot;America/Edmonton&quot;;
const _timelineItemTypes = [&quot;background&quot;, &quot;box&quot;, &quot;point&quot;, &quot;range&quot;];
const MonthDragScale: visTimeline.TimelineOptions = 
    { timeAxis: { scale: &quot;month&quot; } };
const YearDragScale: visTimeline.TimelineOptions = 
    { timeAxis: { scale: &quot;year&quot; } };
const defaultOptions: visTimeline.TimelineOptions = {
    stack: false,
    stackSubgroups: true,
    minHeight: 200,
    editable: false,
    verticalScroll: true,
    zoomable: true,
    zoomMax: 253206145314,
    zoomMin: 80927257,
    zoomKey: &quot;ctrlKey&quot;,
    moveable: true,
    orientation: &quot;top&quot;,
    margin: {
        item: { horizontal: 0, vertical: 0 }
    },
    timeAxis: { scale: &quot;day&quot; }
};

type GanttProps = {
    data?: typeDefs.TaskItem[] | null;
    rowData?: typeDefs.GanttRowData[] | null;
    subGroups?: typeDefs.GanttSubgroupData[] | null;
    availabilityItems?: typeDefs.AvailabilityItem[] | null;
    parentSelector?: string;
    dragDirection?: string;
    dragLocked?: boolean;
    expanded?: boolean;
    isVisualizerForPrint?: boolean;
    showNestedOverride?: boolean;
    timescaleSelector?: string | null;
    textItemsForDisplay?: string[];
    timezone?: string | undefined;
    options?: visTimeline.TimelineOptions | undefined;
    timelineRange?: typeDefs.Range | undefined;
    click?: (event: string, properties: any) =&gt; void;
    doubleClick?: (event: React.MouseEvent&lt;HTMLElement&gt;) =&gt; void;
    changed?: () =&gt; void;
    select?: (items: visTimeline.IdType[], event?: any) =&gt; void;
    rangeChange?: (properties?: typeDefs.RangeProperties) =&gt; void;
    rangeChanged?: (properties?: typeDefs.RangeProperties) =&gt; void;
    subgroupStackingLookup?: SubgroupStackingLookupBuilder;
    focusedItem? : string;
};

const Gantt = (props: GanttProps) =&gt; {
    const [loaded, setLoaded] = React.useState(false);
    const [items, setItems] = React.useState&lt;visTimeline.DataItemCollectionType&gt;([]);
    const [groups, setGroups] = React.useState&lt;visTimeline.DataGroupCollectionType&gt;([]);
    const [range, setRange] = React.useState&lt;typeDefs.Range&gt;()

    let timeline: visTimeline.Timeline | undefined = undefined;
    let timelineNode: HTMLDivElement | null = null;
    let invisibleInput: HTMLInputElement | null = null;
    let hideColumnsTimer: number = 0;

    const timelineRef = React.useRef&lt;visTimeline.Timeline | undefined&gt;(timeline);

    const deferredLoad = _.debounce(() =&gt; setLoaded(true), 200);

    const createTimeline = (): void =&gt; {
        if (timelineNode &amp;&amp; !timelineRef.current) {
            let tlOptions = {
                ...defaultOptions,
                ...props.options,
                autoResize: true,
                moveable: !props.dragLocked
            };

            if (tlOptions.height === undefined) {
                delete tlOptions.height;
            }

            if (tlOptions.maxHeight === undefined) {
                delete tlOptions.maxHeight;
            }

            timeline = new visTimeline.Timeline(
                timelineNode,
                items ?? [],
                groups,
                tlOptions
            );

            timelineRef.current = timeline;

            timelineRef.current.on(&quot;doubleClick&quot;, doubleClickHandler);
            timelineRef.current.on(&quot;changed&quot;, changedHandler);
            timelineRef.current.on(&quot;select&quot;, selectHandler);
            timelineRef.current.on(&quot;rangechanged&quot;, rangeChangedHandler);
            timelineRef.current.on(&quot;rangechange&quot;, rangeChangeHandler);

            timelineRef.current.on(&quot;mouseDown&quot;, mouseDownHandler);
            timelineRef.current.on(&quot;mouseUp&quot;, mouseUpHandler);
            timelineRef.current.on(&quot;click&quot;, (properties) =&gt; {
                clickHandler(&quot;click&quot;, properties);
            });
        } else if (!loaded) {
            deferredLoad();
        }
    }

    /* Start Event Handlers */
    const doubleClickHandler = (event: React.MouseEvent&lt;HTMLElement&gt;): void =&gt; {
        ...
    }

    const clickHandler = (event: string, properties: any): void =&gt; {
        ...
    }

    const changedHandler = (): void =&gt; {
        ...
    };

    const rangeChangedHandler = (properties?: typeDefs.RangeProperties): void =&gt; {
        ...
    };

    const rangeChangeHandler = (properties?: typeDefs.RangeProperties): void =&gt; {
        ...
    }

    // vanishes the columns on drag so that they don't make dragging choppy
    const mouseDownHandler = (event: visTimeline.TimelineEventPropertiesResult )
        : boolean =&gt; 
    {
        ...
    }

    const mouseUpHandler = () : boolean =&gt; {
        ...
    }

    const selectHandler = (params: typeDefs.SelectionEventInfo): void =&gt; {
        ...
    }

    /* End Event Handlers */

    /**
     * Update the timeline scale options based on current scale.
     * Timeline scale is being switched to auto when the zoom reaches a level where days labels can fit and will revert back to day when zoomed out above that scale level.
     * @returns Void
     */
    const updateOptions = (prevOptions?: visTimeline.TimelineOptions): void =&gt; {
        if (!timelineRef.current) {
            return;
        }

        let options: visTimeline.TimelineOptions | null = null;

        if (calcScale &gt; 0) {
            options = {
                showMinorLabels: true
                
            };
        }

        if (prevOptions &amp;&amp; prevOptions!.multiselect !== props.options!.multiselect) {
            options = { ...options, multiselect: props.options!.multiselect };
        }

        if (options) {
            timelineRef.current.setOptions(options);
        }
    }

    // ---------- start effect hooks
    React.useEffect(() =&gt; {
        createTimeline();

        if(props.timescaleSelector) {
            createTimescale();
        }

        // find the nearest focusable grid target in the parent element
        if (timelineNode) {
            const parent = timelineNode.parentElement;
            if (parent !== null) {
                const grandparent = parent.parentElement;
                if (grandparent !== null) {
                    invisibleInput = grandparent.querySelector(
                        `.form-control[type=&quot;text&quot;]`
                    );
                }
            }
        }

        return () =&gt; {
            if (timelineRef.current) {
                timelineRef.current.destroy();
            }
        }
    }, []);

    React.useEffect(() =&gt; {
        setItems(() =&gt; [...]);
   }, [props.data]);

    React.useEffect(() =&gt; {
        setGroups([...]);
    }, [props.rowData]);

    React.useEffect(() =&gt; {
        removeResizeLeftDiv();

        if(timelineRef.current)
            timelineRef.current.setItems(items);
    }, [items]);

    React.useEffect(() =&gt; {
        removeResizeLeftDiv();
        
        if(timelineRef.current)
            timelineRef.current.setData({
                groups: groups,
                items: items
            });
    }, [groups]);

    React.useEffect(() =&gt; {
        if(!range) {
            return;
        }

        if (
            timelineRef.current &amp;&amp; props.options &amp;&amp;
            props.options.maxHeight
        ) {
            timelineRef.current.setOptions({
                maxHeight: props.options!.maxHeight
            });
        }
        updateOptions();

        if(range?.start &amp;&amp; range?.end)
        {
            if(timelineRef.current)
                timelineRef.current.setWindow(
                    range.start, 
                    range.end,
                    {
                        animation: true
                    });
        }

    }, [range]);

    React.useEffect(() =&gt; {
        if(props?.timelineRange)
        {
            setRange(props.timelineRange);
        }
    },[props.timelineRange])

    React.useEffect(() =&gt; {

        if(props.focusedItem &amp;&amp; timelineRef.current)
        {
            timelineRef.current.focus(props.focusedItem,{animation: false, zoom: false});
        }
    }, [props.focusedItem])

    // ---------- end effect hooks

    return (
        &lt;div ref={el =&gt; (timelineNode = el)} /&gt;
    );
}

export default Gantt; export type { GanttProps };
</code></pre>
",https://stackoverflow.com/questions/67112988/vis-js-timeline-error-when-unit-testing-click-events-with-test-library,"['javascript', 'react-testing-library', 'vis.js']",422,False,1,0
"fetch-mock-jest .post resolves to {&quot;size&quot;:0,&quot;timeout&quot;:0}","<p>I am trying to unit test a function which sends a post request then the API returns a json object. I am trying to do this using jest and <a href=""http://www.wheresrhys.co.uk/fetch-mock/"" rel=""nofollow noreferrer"">fetch-mock-jest</a>.</p>
<p>Now instead of the expected payload the tested function receives <code> {&quot;size&quot;:0,&quot;timeout&quot;:0}</code>
and throws error <code>invalid json response body at  reason: Unexpected end of JSON input</code>. Pretty sure there is something basic I don't see. I spent way more time on this without any progress than I'd like to admit.</p>
<p>Edit: I am pretty new to jest and unit testing in general, so if someone has a better suggestion to go about mocking fetch, please tell me.</p>
<p><strong>Test File</strong>
<div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import fetchMock from 'fetch-mock-jest'

import {
  refreshAccessToken, isTokenExpired
} from '../../../lib/access/AccessToken'

describe('AccessToken Component...', () =&gt; {
it('...Refreshes AccessToken', async () =&gt; {
    const responseBody = { accessToken: taiDeveloperTokenValid } // The payload I want the AccessToken.refreshAccessTokento get
    setAccessToken(taiDeveloperTokenExpired)

    process.env.NEXT_PUBLIC_AUTH_API_HTTPS_URL = 'http://new-api.com'
    fetchMock.post(
      `${process.env.NEXT_PUBLIC_AUTH_API_HTTPS_URL}/refreshToken`,
      new Promise((res) =&gt;
        setTimeout(
          () =&gt;
            res({
              status: 200,
              body: JSON.stringify(responseBody),
              statusText: 'OK',
              headers: { 'Content-Type': 'application/json' },
            }),
          50,
        ),
      ),
    )
    const refreshAccessTokenResponse = await refreshAccessToken()
    expect(refreshAccessTokenResponse).toBe(true)
    expect(isTokenExpired()).toBe(false)
  })
  }</code></pre>
</div>
</div>
</p>
<p><strong>Function I am testing</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import fetch from 'isomorphic-unfetch'

export const refreshAccessToken = async (): Promise&lt;boolean&gt; =&gt; {
  try {
    const response = await fetch(
      `${process.env.NEXT_PUBLIC_AUTH_API_HTTPS_URL}/refreshToken`,
      {
        method: 'POST',
        credentials: 'include',
      },
    )
    console.log(JSON.stringify(await response)) // this prints {""size"":0,""timeout"":0}
    const data = await response.json()
    accessToken = data.accessToken
    return true
  } catch (error) {
    console.log(error) // this prints  FetchError { message: 'invalid json response body at  reason: Unexpected end of JSON input', type: 'invalid-json'
    return false
  }
}</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/66009798/fetch-mock-jest-post-resolves-to-size0-timeout0,"['javascript', 'typescript', 'unit-testing', 'jestjs', 'fetch-mock']",2019,True,1,1
Unit testing getting error class could not be found,"<p>I have a class for <code>dynamoDB</code> in location</p>
<pre><code>src/Dynamo/shop.php 
</code></pre>
<p>My class looks like below</p>
<pre><code>&lt;?php
    
    namespace App\Dynamo;
    
    
    class Shop
    {
        -----
    }
    
?&gt;
</code></pre>
<p>I am trying to implement unit test for this class, So I have created a folder class dynamo in below location.</p>
<pre><code>app/cake/tests/TestCase/Dynamo
</code></pre>
<p>In Dynamo folder I have created a class with file name <code>ShopTest.php</code></p>
<p>For create a unit testing I have written this class like below</p>
<pre><code>&lt;?php
declare(strict_types=1);

namespace App\Test\TestCase\Dynamo;

use App\Dynamo\Shop;
use Cake\TestSuite\TestCase;

class ShopTest{
    
    public function setUp()
    {
        $this-&gt;shop = new Shop;
    }

    public function testconnectDynamoDB()
    {
        debug($this-&gt;shop-&gt;connectDynamoDB());

        $this-&gt;assertNotEmpty($this-&gt;shop-&gt;connectDynamoDB());

    }
}
</code></pre>
<p>Now after run phpunit command</p>
<pre><code>vendor/bin/phpunit tests/TestCase/Dynamo/ShopTest.php 
</code></pre>
<p>I am getting</p>
<pre><code>Class 'App\Test\TestCase\Dynamo\ShopTest' could not be found in '/var/www/html/tests/TestCase/Dynamo/ShopTest.php'.
</code></pre>
<p>Class is present in this location , Why I am getting Class could not be found ?</p>
<pre><code>root@0ceda1df4444:/var/www/html# cd /var/www/html/tests/TestCase/Dynamo/
    root@0ceda1df4444:/var/www/html/tests/TestCase/Dynamo# ls
    ShopTest.php

root@0ceda1df4444:/var/www/html/tests/TestCase/Dynamo# cat ShopTest.php 
&lt;?php
declare(strict_types=1);

namespace App\Test\TestCase\Dynamo;

use App\Dynamo\Shop;
use Cake\TestSuite\TestCase;

class ShopTest{

</code></pre>
<p>Also I am trying to run all test case by below command , I am getting a warning.</p>
<pre><code>root@0ceda1df4444:/var/www/html# vendor/bin/phpunit                
PHPUnit 9.5.9 by Sebastian Bergmann and contributors.

Warning:       Your XML configuration validates against a deprecated schema.
Suggestion:    Migrate your XML configuration using &quot;--migrate-configuration&quot;!

No tests executed!
</code></pre>
",https://stackoverflow.com/questions/69123049/unit-testing-getting-error-class-could-not-be-found,"['cakephp', 'cakephp-4.x']",406,True,1,1
Why am I getting Error: Timeout in my Jasmine unit test of http interceptor?,"<p>I am struggling with unit testing my interceptor since yesterday noon. After following several tutorial and SO answers, I have a code that so far looks the best. BUT, because of some reason I am getting an error:</p>
<blockquote>
<p>Error: Timeout - Async function did not complete within 5000ms (set by
jasmine.DEFAULT_TIMEOUT_INTERVAL) Error: Timeout - Async function did
not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)
at Jasmine</p>
</blockquote>
<p><strong>EDIT</strong>: I just added <a href=""https://stackblitz.com/edit/jasmine-in-angular-7c5hpm?file=src%2Fapp%2Fsut%2Ferror.interceptor.spec.ts"" rel=""nofollow noreferrer"">Stackblitz example</a>.</p>
<p>my test:</p>
<pre><code>it('should display an error message if the request is unauthorized', (done) =&gt; {
    service.getGameState('1').subscribe(
      (data) =&gt; {
        console.log(data);
        expect(data).toBeNull();
        expect(errorsMock.handleAuthError).toHaveBeenCalledWith('dupa');
        done();
      },
      (error: HttpErrorResponse) =&gt; {
        console.log(error);
        done();
      }
    );

    const testRequest = httpMock.expectOne(
      'http://localhost:50962/api/game/join?id=1'
    );
    expect(testRequest.request.method).toBe('GET');
    testRequest.flush(null, {
      status: 401,
      statusText: 'Unauthorized request',
    });
  });
</code></pre>
<p><strong>NOTE</strong>: <code>console.log</code> in the test are not called;</p>
<p>test preparation:</p>
<pre><code>describe('ErrorInterceptor', () =&gt; {
  let httpMock: HttpTestingController;
  let injector: TestBed;
  let service: HttpService;
  const errorsMock = jasmine.createSpyObj('ErrorService', [
    'handleBackendError',
    'handleAuthError',
    'handleBotError',
    'handleOtherError',
  ]);

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule.withRoutes([])],
      providers: [
        HttpService,
        {
          provide: HTTP_INTERCEPTORS,
          useClass: ErrorInterceptor,
          multi: true,
        },
        { provide: ErrorService, useValue: errorsMock },
      ],
    });

    injector = getTestBed();
    httpMock = injector.inject(HttpTestingController);
    service = TestBed.inject(HttpService);
  });

  afterEach(() =&gt; {
    httpMock.verify();
  });

  it('Injector_ShouldBeCreated', () =&gt; {
    expect(injector).toBeTruthy();
    expect(service).toBeTruthy();
  });
</code></pre>
<p><strong>NOTE</strong>: when using <code>.and.callThrough();</code> on <code>errorsMock</code> it throws an error:</p>
<blockquote>
<p>Cannot read property 'callThrough' of undefined</p>
</blockquote>
<p>Why <code>errorsMock</code> is undefined?</p>
<p>Interceptor by himself:</p>
<pre><code>@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(private error: ErrorService) {}

  public intercept(
    request: HttpRequest&lt;any&gt;,
    next: HttpHandler
  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    return new Observable((observer) =&gt; {
      next.handle(request).subscribe(
        (res: HttpResponse&lt;any&gt;) =&gt; {
          if (res instanceof HttpResponse) {
            observer.next(res);
          }
        },
        (err: HttpErrorResponse) =&gt; {
          this.handleResponseError(err, request, next);
        }
      );
    });
  }

  private handleResponseError(
    error: HttpErrorResponse,
    request: HttpRequest&lt;any&gt;,
    next: HttpHandler
  ): any {
    if (request.url.indexOf('refresh') !== -1) {
      return next.handle(request);
    }

    if (error.status === 0) {
      this.error.handleBackendError(error);
    } else if (error.status === 401 || error.status === 403) {
      this.error.handleAuthError(error, next, request);
    } else if (error.status === 429) {
      this.error.handleBotError(error);
    } else {
      this.error.handleOtherError(error);
    }
  }
}
</code></pre>
<p>And <code>http.service</code> method:</p>
<pre><code>public getGameState(id: string): Observable&lt;any&gt; {
    const url: string = environment.apiUrl + 'api/game/join?id=' + id;
    return this.http.get(url);
  }
</code></pre>
",https://stackoverflow.com/questions/65683562/why-am-i-getting-error-timeout-in-my-jasmine-unit-test-of-http-interceptor,"['angular', 'unit-testing', 'jasmine', 'angular-http-interceptors', 'stackblitz']",811,True,0,1
How to test void methods?,"<p>In my most recent homework, we were provided a class library and told to complete unit testing to ensure the changes we made to comply with SOLID didn't break the code.</p>
<p>The problem I have is that all the methods are void. I may just be ignorant but I don't know how you're supposed to Unit Test Void methods.</p>
<p>Should I just refactor the methods to return something instead of leaving it void?
I'll provide one of the methods from the code.
I would appreciate some ideas to move me in the right direction. Thank you!</p>
<pre><code>
 public class Cart : ICart
    {
        public decimal TotalAmount { get; set; }
        public IEnumerable&lt;OrderItem&gt; Items { get; set; }
        public string CustomerEmail { get; set; }
    }


 public class OrderNotifyCustomer
    {

        public static void NotifyCustomer(Cart cart)
        {
            string customerEmail = cart.CustomerEmail;
            if (!String.IsNullOrEmpty(customerEmail))
            {
                using (var message = new MailMessage(&quot;orders@somewhere.com&quot;, customerEmail))
                using (var client = new SmtpClient(&quot;localhost&quot;))
                {
                    message.Subject = &quot;Your order placed on &quot; + DateTime.Now.ToString();
                    message.Body = &quot;Your order details: \n &quot; + cart.ToString();

                    try
                    {
                        client.Send(message);
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(&quot;Problem sending notification email&quot;, ex);
                    }
                }
            }
        }
    }
</code></pre>
",https://stackoverflow.com/questions/66404435/how-to-test-void-methods,"['c#', 'unit-testing', 'class-library']",322,True,-1,3
"Vue 2 Testing with Mocha, wrapper data is not changing or updating","<p>I'm trying to integrate tests in a vue 2-cli project,the test framework Mocha and Chai is used. There is a very helpful guide I'm relying on:</p>
<p><a href=""https://www.dotnetcurry.com/vuejs/1441/vuejs-unit-testing"" rel=""nofollow noreferrer"">https://www.dotnetcurry.com/vuejs/1441/vuejs-unit-testing</a></p>
<p>Most of the tests are working, but every time I'm changing the data on the fly and expecting the changes on the wrapper, the wrapper is not updated at all. For example:</p>
<pre><code>describe('the onIncrease method', () =&gt; {
    let wrapper;
    let componentInstance;
    beforeEach(() =&gt; {
        wrapper = shallowMount(Counter, {
            propsData: {initialValue: 42},
        });
        componentInstance = wrapper.vm;
    });

    it('the counter value is increased by one', () =&gt; {
        componentInstance.onIncrease();
        expect(componentInstance.value).to.be.equal(43);
    });
    // this test passes and returns the correct 43
    it('the rendered output contains the value increased by one', () =&gt; {
        componentInstance.onIncrease();
        expect(wrapper.text()).to.include('Counter value: 43');
    });
    // this test fails with:
    // expected 'Counter value: 42' to include 'Counter value: 43'
});
</code></pre>
<p>I'm working on this for days and hopefully anyone can give a hint on how to get the updated data. There is a picture of the error-page, maybe it's useful.</p>
<p><a href=""https://i.stack.imgur.com/t8xoA.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/t8xoA.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/68335670/vue-2-testing-with-mocha-wrapper-data-is-not-changing-or-updating,"['vue.js', 'unit-testing', 'mocha.js', 'chai']",148,True,0,2
Jest import common plugins like Vee Validate before each test,"<p>I'm new to Jest and am testing my Nuxt JS application with unit testing. I have many test files set up and need to import various logic into each test file, such as my Vee Validate config.</p>
<p>I've tried adding it to a <code>setup.js</code> file and included this in <code>setupFilesAfterEnv</code> but it's not getting included.</p>
<p>What am I doing wrong?</p>
<p><strong>tests/unit/setup.js</strong></p>
<pre class=""lang-js prettyprint-override""><code>import Vue from 'vue'
import { ValidationProvider, ValidationObserver, extend, configure, localize } from 'vee-validate'
import * as rules from 'vee-validate/dist/rules';
import en from 'vee-validate/dist/locale/en.json'

const config = {
  mode: 'lazy',
  classes: {
    valid: '',
    invalid: 'tw-border-red-500 dark:tw-border-white'
  }
}

Object.keys(rules).forEach(rule =&gt; {
  extend(rule, rules[rule]);
});

configure(config)

// Register it globally
Vue.component('ValidationObserver', ValidationObserver)
Vue.component('ValidationProvider', ValidationProvider)

// // activate the locales
localize({
  en
});
</code></pre>
<p>My <code>jest.config.js</code> file:</p>
<pre class=""lang-js prettyprint-override""><code>module.exports = {
  silent: true,
  testEnvironment: 'jsdom',
  moduleNameMapper: {
    '^@/(.*)$': '&lt;rootDir&gt;/$1',
    '^~/(.*)$': '&lt;rootDir&gt;/$1',
    '^vue$': 'vue/dist/vue.common.js',
  },
  moduleFileExtensions: ['js', 'vue', 'json'],
  transform: {
    '^.+\\.js$': 'babel-jest',
    '.*\\.(vue)$': 'vue-jest',
    'vee-validate/dist/rules': 'babel-jest'
  },
  collectCoverage: true,
  collectCoverageFrom: [
    '&lt;rootDir&gt;/components/**/*.vue',
    '&lt;rootDir&gt;/pages/**/*.vue',
  ],
  transformIgnorePatterns: [
    '&lt;rootDir&gt;/node_modules/(?!vee-validate/dist/rules)',
  ],
  setupFilesAfterEnv: [
    '&lt;rootDir&gt;/tests/unit/setup.js'
  ]
}
</code></pre>
<p>And one of my test files called <code>LoanAmount</code> is:</p>
<pre class=""lang-js prettyprint-override""><code>import { mount } from '@vue/test-utils'
import flushPromises from 'flush-promises';
import LoanAmount from '@/components/Form/Steps/Loan/LoanAmount'

describe('LoanAmount', () =&gt; {
  test('is a Vue instance', () =&gt; {
    const wrapper = mount(LoanAmount)
    expect(wrapper.vm).toBeTruthy()
  })

  test('amount is available for value', async () =&gt; {
    const wrapper = mount(LoanAmount)
    await flushPromises()

    const amount = wrapper.findAll('.jest__amount-input')
    expect(amount.exists()).toBe(true)
  })
})
</code></pre>
<p>If I include all of the contents from <code>tests/unit/setup.js</code> and include above my <code>describe</code> block then it works, but I can't be repeating this in each test file.</p>
",https://stackoverflow.com/questions/69881192/jest-import-common-plugins-like-vee-validate-before-each-test,"['vue.js', 'unit-testing', 'jestjs']",231,False,0,1
Is there a way to macro unit test in kdb+?,"<p>I have seen a few different unit testing approaches online using qunit and k4unit but I can only get them testing on single functions. I was hoping that I could run a unit test that check the daily checks I execute each day such as, &quot;has the nightjobs ran correctly?&quot;, &quot;are the dashboards on the WebUI up?&quot;, &quot;did the deploy script run with no errors?&quot;. Is there built in kdb+ functionality for these kind of tests or a clean way to adapt the qunit or k4unit unit tests? Or will it require a script written from scratch?
Thanks</p>
",https://stackoverflow.com/questions/66238760/is-there-a-way-to-macro-unit-test-in-kdb,"['unit-testing', 'kdb']",124,True,0,1
Go unit testing Bcrypt,"<p>I am performing unit tests for a service where request dto's are validated and user passwords are hashed using Go's <a href=""https://pkg.go.dev/golang.org/x/crypto/bcrypt"" rel=""nofollow noreferrer"">Bcrypt package</a> before being passed to a repository for insertion into the DB.</p>
<p>I don't know how my mock functions should return a dummy response which should match with the service's hashing.</p>
<pre class=""lang-golang prettyprint-override""><code>func Test_should_create_new_account(t *testing.T) {
    // Arrange
    teardown := setup(t)
    defer teardown()

    // ** Focus here **
    hashedpassword, err := AppCrypto.HashAndSalt([]byte(&quot;securepassword&quot;))

    request := dto.RegisterRequest{
        Email:    &quot;test@test.com&quot;,
        Password: &quot;securepassword&quot;,
        RoleID:   1,
    }

    account := realDomain.Account{
        Email:    request.Email,
        Password: hashedpassword,
        RoleID:   request.RoleID,
    }

    accountWithID := account
    accountWithID.AccountID = 1

    mockRepo.EXPECT().Create(account).Return(&amp;accountWithID, nil)
    // Act
    res, err := service.RegisterAccount(request)

    // Assert
    if err != nil {
        t.Error(&quot;Failed while creating account&quot;)
    }
    if !res.Created {
        t.Error(&quot;Failed while creating account&quot;)
    }
}
</code></pre>
<p><code>HashAndSalt</code> simply hashed a given string.</p>
<pre class=""lang-golang prettyprint-override""><code>// HashAndSalt Hashes a given string
func HashAndSalt(pwd []byte) (string, *errs.AppError) {

    // Use GenerateFromPassword to hash &amp; salt pwd.
    // MinCost is just an integer constant provided by the bcrypt
    // package along with DefaultCost &amp; MaxCost.
    // The cost can be any value you want provided it isn't lower
    // than the MinCost (4)
    hash, err := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)
    if err != nil {
        return &quot;&quot;, errs.NewUnexpectedError(&quot;An unexpected error ocurred while hashing the password&quot; + err.Error())
    } // GenerateFromPassword returns a byte slice so we need to
    // convert the bytes to a string and return it
    return string(hash), nil
}
</code></pre>
<p>This is the service's <code>RegisterAccount</code></p>
<pre class=""lang-golang prettyprint-override""><code>func (d DefaultAccountService) RegisterAccount(request dto.RegisterRequest) (*dto.RegisterResponse, *errs.AppError) {
    err := request.Validate()
    if err != nil {
        return nil, err
    }
    // Hash the request's password
    hashedpassword, err := AppCrypto.HashAndSalt([]byte(request.Password))

    if err != nil {
        return nil, err
    }
    // Assign the hashed password to the request obj
    request.Password = hashedpassword
    a := request.ToDomainObject()

    _, err = d.repo.Create(a)
    if err != nil {
        return nil, err
    }
    response := dto.RegisterResponse{
        Created: true,
    }
    return &amp;response, nil
}
</code></pre>
<p>This is the thrown error, notice the <code>want</code> and <code>got</code> blocks where the mock request does not match with the given request.</p>
<pre><code>accountService.go:34: Unexpected call to *domain.MockAccountRepository.Create([{0 test@test.com 1 $2a$04$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}]) at /home/dio/Documents/Code/go-beex-backend/auth-server/mocks/domain/accountRepositoryDB.go:40 because: 
        expected call at /home/dio/Documents/Code/go-beex-backend/auth-server/service/accountService_test.go:52 doesn't match the argument at index 0.
        Got: {0 test@test.com 1 $2a$04$.ORGMDZNk3.ySMpKwJYYcONdpAbgMJh79UDApzwRnzkCe.qeiECUG false}
        Want: is equal to {0 test@test.com 1 $2a$04$Bah8tCOzf7Z9Suw55DfyHOvnsBbXLyJEWV8QZ.owCBUOxxomAuEM2 false}
</code></pre>
<p>Hope my explanation makes sense, unit testing was not discussed in <a href=""https://medium.com/@jcox250/password-hash-salt-using-golang-b041dc94cb72"" rel=""nofollow noreferrer"">the article</a> I am basing my code from.</p>
",https://stackoverflow.com/questions/66093942/go-unit-testing-bcrypt,"['unit-testing', 'go', 'bcrypt', 'go-testing']",1741,True,0,1
Attempting to run Jest/Supertest in my nodejs api but keep getting a TypeError : &quot;app.address is not a function&quot;,"<p>I'm trying to begin integration/unit testing for my nodejs api but I'm unable to properly connect to my app.js file via supertest.</p>
<p>The below code is written in my main.test.js file</p>
<pre><code>const app = require('../app')
const supertest = require('supertest');
const request = supertest(app)

it('posts color', async () =&gt; {
    await request.post('/postColor')
    .send({
        &quot;Color&quot;: &quot;Green&quot;,
}).expect(201)
})
</code></pre>
<p>Below is my app.js file</p>
<pre><code>import express from 'express';
const app = express();

export default app;
</code></pre>
<p>I broke apart my index.js file into an app.js and index.js file.</p>
<p>My index.js imports app from app.js and sets it up to listen to whichever port I need it to.
My main.test.js file imports app from app.js and uses it as shown above in accordance with supertest.</p>
<p>I keep getting the following error</p>
<p>TypeError: app.address is not a function</p>
<pre><code>  4 |
  5 | it('posts color', async () =&gt; {
&gt; 6 |     await request.post('/postColor')
    |                   ^
</code></pre>
",https://stackoverflow.com/questions/67696044/attempting-to-run-jest-supertest-in-my-nodejs-api-but-keep-getting-a-typeerror,"['javascript', 'node.js', 'jestjs', 'supertest']",950,True,-1,1
Using @Mock in Java for Unit Tests,"<p>Hello I am new to unit testing and want to test a method within a class that will generate a document to an external folder via an API. However, as this is just a test I don't want the document to actually show up in the external folder every time I test. I simply want to see if the document was created the right way. If I use @Mock and bring in the class that way will this prevent the document from showing up in the folder or is there another way to go about it. I am using Java and Mockito.</p>
",https://stackoverflow.com/questions/69034540/using-mock-in-java-for-unit-tests,"['java', 'unit-testing', 'mockito']",57,False,0,1
adding java spark code unit testing in the build fat jar fails the spark run later,"<p>I try to add unit test code for some java spark method. However, I found the spark job run failed after I add them. Here are the things I found</p>
<p>a) After I added the unit test code, they will be run when I build the java fat jar.</p>
<p>b) Then, after build, if I ran the spark submit job, it will failed with the exception below</p>
<pre><code> Error in trying to obtain a connection. Retrying in 7000ms
java.sql.SQLException: A read-only user or a user in a read-only database is not permitted to disable read-only mode on a connection.
        at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
......
</code></pre>
<p>c) To fix this issue, I have to remove the metastore_db folder under the code root directory.</p>
<p>d) If I don't build the jar again, but directly run the spark job (after fix the issue in step c), then, it will run fine.</p>
<p>Based on what I see above, my guessing is that the unit test during the building jar process started a spark session (something like that). And this session is not being closed. Therefore, when the actual code run later, the job will failed to have a new session connection.</p>
<p>Again, this is my guessing. Below is my unit testing code.</p>
<pre><code>@Before
public void setUp() throws IllegalArgumentException, IOException {
    SparkConf conf = new SparkConf();
    conf.setMaster(&quot;local[2]&quot;);
    conf.setAppName(&quot;sparkHelperTest&quot;);
    sparkContext = new JavaSparkContext(conf);
    sqlContext = new org.apache.spark.sql.hive.HiveContext(sparkContext);
    sparkHelper = new DSERunEnvironmentSparkHelper(sparkContext, sqlContext, aktanaServiceConfiguration);
}
                                                       
@Test
public void testAccountDF() {
    ArrayList&lt;Account&gt; mockList = new ArrayList&lt;&gt;();
    Account account = new Account();
    account.setId(1);
    account.setName(&quot;name&quot;);

    List&lt;StructField&gt; listOfStructField= new ArrayList&lt;&gt;();
    listOfStructField.add(DataTypes.createStructField(&quot;id&quot;, DataTypes.IntegerType, false));
    listOfStructField.add(DataTypes.createStructField(&quot;name&quot;, DataTypes.StringType, true));

    StructType structType=DataTypes.createStructType(listOfStructField);


    JavaRDD&lt;Row&gt; rowRDD = sparkContext.parallelize(mockList).map(
            account -&gt; RowFactory.create(repAccount.getId(), account.getName());

    DataFrame df1 = sqlContext.createDataFrame(rowRDD, structType);
    df1.show();
}

@After
public void postProcess () {
    sparkContext.stop();
    sparkContext.close();
}
</code></pre>
<p>Another notice is that let's see if I fix the metastore_db issue by c). If I build the fat jar and run the job again, it still fail. However, if I run the unit testing directly (NOT re-build the jar) and run the job again, the job is running OK. So the testing run in the build failed the spark job, while the directly running unit test through IntelliJ is OK.</p>
<p>Please help!! Thanks in advance.</p>
",https://stackoverflow.com/questions/69862352/adding-java-spark-code-unit-testing-in-the-build-fat-jar-fails-the-spark-run-lat,"['java', 'unit-testing', 'apache-spark']",96,False,1,1
Junit5 jpa repository null pointer exception,"<p>I am trying to test the repositories. Alas, when I am trying to test I keep getting the same error. The error is as follows:</p>
<pre><code>java.lang.NullPointerException
    at com.changing.springboot.repository.TemplateRepositoryTest.should_return_templateName_when_call_findByTemplateName(TemplateRepositoryTest.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.Iterator.forEachRemaining(Iterator.java:116)
    at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
    at java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:485)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:137)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
</code></pre>
<p>Here is my TemplateRepositoryTest.class:</p>
<pre><code>package com.changing.springboot.repository;

import java.util.List;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import com.changing.springboot.model.TemplateModel;

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.AUTO_CONFIGURED)
public class TemplateRepositoryTest {
     
     @Autowired
     TemplateRepository templateRepository;
     
     @Test
     public void should_return_templateName_when_call_findByTemplateName() {
         
         List&lt;TemplateModel&gt; list = templateRepository.findAll();
     }
}
</code></pre>
<p>Here is my TemplateRepository.class:</p>
<pre><code>package com.changing.springboot.repository;

import java.util.Date;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import com.changing.springboot.model.TemplateModel;

@Repository
public interface TemplateRepository extends JpaRepository&lt;TemplateModel, Integer&gt; {
    List&lt;TemplateModel&gt; findAll();

    TemplateModel findByTemplateName(String templateName);

    TemplateModel findByTemplateCusUid(String templateCusUid);

    Page&lt;TemplateModel&gt; findAllByTemplateCreateTimeBetween(Date begin, Date after, Pageable pageable);

    Page&lt;TemplateModel&gt; findAllByTemplateNameAndTemplateCreateTimeBetween(String templateName, Date begin, Date after,
            Pageable pageable);

    Page&lt;TemplateModel&gt; findAllByTemplateCusUidAndTemplateCreateTimeBetween(String templateCusUid, Date begin,
            Date after, Pageable pageable);

    Page&lt;TemplateModel&gt; findAllByTemplateNameAndTemplateCusUidAndTemplateCreateTimeBetween(String templateName,
            String templateCusUid, Date begin, Date after, Pageable pageable);
}
</code></pre>
<p>Here is my TemplateModel.class:</p>
<pre><code>package com.changing.springboot.model;

import lombok.*;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = &quot;cg_template&quot;)
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TemplateModel{
    
    @Id
    @GeneratedValue(generator = &quot;id_Sequence&quot;)
    @GenericGenerator(name = &quot;id_Sequence&quot;, strategy = &quot;native&quot;)
    @Column(name = &quot;template_id&quot;)
    private Integer templateId;

    @ManyToOne
    @JoinColumn(name = &quot;template_creator_account_id&quot;)
    private AccountModel accountModel;

    @ManyToOne
    @JoinColumn(name = &quot;template_group_id&quot;)
    private FormGroupModel formGroupModel;

    @OneToMany(mappedBy = &quot;template&quot;, orphanRemoval = false, fetch = FetchType.LAZY)
    @Cascade(value = CascadeType.SAVE_UPDATE)
    @OrderBy(&quot;docId ASC&quot;)
    private List&lt;DocModel&gt; cgDoc = new ArrayList&lt;DocModel&gt;();

    @Column(name = &quot;template_name&quot;)
    private String templateName;

    @Column(name = &quot;template_desc&quot;)
    private String templateDesc;

    @Column(name = &quot;template_create_time&quot;)
    private Date templateCreateTime;

    @Column(name = &quot;template_uid&quot;)
    private String templateUid;

    @Column(name = &quot;template_cus_uid&quot;)
    private String templateCusUid;

    @Column(name = &quot;template_status&quot;)
    private Integer templateStatus;

    @Column(name = &quot;template_expire_days&quot;)
    private Integer templateExpireDays;

    @Column(name = &quot;template_sign_video_flag&quot;)
    private Integer signVideoFlag;

    @Column(name = &quot;template_check_require_item&quot;)
    private Integer checkRequiredBeforeSign;
    
    @Column(name = &quot;template_check_required_before_upload&quot;)
    private Integer checkRequiredBeforeUpload;

    
    public TemplateModel(AccountModel accountModel, FormGroupModel formGroupModel, String templateName, String templateDesc,
            Date templateCreateTime, String templateUid, String templateCusUid, Integer templateStatus,
            Integer templateExpireDays,Integer signVideoFlag, Integer checkRequiredBeforeSign, Integer checkRequiredBeforeUpload) {
        super();
        this.accountModel = accountModel;
        this.formGroupModel = formGroupModel;
        this.templateName = templateName;
        this.templateDesc = templateDesc;
        this.templateCreateTime = templateCreateTime;
        this.templateUid = templateUid;
        this.templateCusUid = templateCusUid;
        this.templateStatus = templateStatus;
        this.templateExpireDays = templateExpireDays;
        this.signVideoFlag=signVideoFlag;
        this.checkRequiredBeforeSign = checkRequiredBeforeSign;
        this.checkRequiredBeforeUpload = checkRequiredBeforeUpload;
    }
}
</code></pre>
<p>This problem is occure at List list = templateRepository.findAll();</p>
<p>My database connection string in application.yml.
I don't know this problem is about connect db or repository error.
If problem is database,how can I connect to the database with unit testing?
I want connect real database, not H2.</p>
<p>If you could help or point me in the right direction I would be very grateful. Thank you</p>
",https://stackoverflow.com/questions/67957487/junit5-jpa-repository-null-pointer-exception,"['java', 'spring-boot', 'junit5']",1881,False,0,2
flutter: unit testing dao in moor,"<p>I've started unit testing the first time. I'm following tutorials of <a href=""https://github.com/ResoCoder/flutter-tdd-clean-architecture-course"" rel=""nofollow noreferrer"">resoCoder</a></p>
<p>here is my test code where I'm mocking my dbManager class but I could not mock DAO's as they are auto-generated in moor and there is no setter method for them.</p>
<pre><code>class MockDbManager extends Mock implements DbManager{}

void main() {
  RecipeLocalDataSource dataSource;
  MockDbManager _dbManager;
  setUp(() {
    _dbManager = MockDbManager();
    dataSource = RecipeLocalDataSource(_dbManager);
  });

  group('Search Food Table', (){
    List&lt;FoodTableData&gt; getFoodTable(){
      var list = [];
      for(var i =1; i &lt;=5 ; i++){
        list.add(FoodTableData(id: i, name: 'item $i'));
      }
      return list;
    }
    var searchQuery = 'query';

    test('Should return foodTableData when query is successful', (){
      //arrange
      when(_dbManager.foodTableDao.searchFoods(searchQuery)).thenAnswer((realInvocation) async =&gt; getFoodTable());
      //act
      var result = dataSource.searchFoodTable('test');
      //assert
      verify(_dbManager.foodTableDao.searchFoods(searchQuery));
      expect(getFoodTable(), result);
    });
  });
}
</code></pre>
<p>I'm getting the following error</p>
<pre><code>NoSuchMethodError: The method 'searchFoods' was called on null.
Receiver: null
Tried calling: searchFoods(&quot;query&quot;)
</code></pre>
<p>I understood the error but don't know how to solve that.</p>
<p>Also, I'm getting a similar issue with preferenceManager class as well, where I'm having a getter for UserPrefs.</p>
<pre><code>UserPrefs get user =&gt; UserPrefs(_pref);
</code></pre>
<p>when I'm accessing <code>_prefManager.user.name</code> for the test, it throws the same error. How can I tackle that as well?</p>
",https://stackoverflow.com/questions/65561079/flutter-unit-testing-dao-in-moor,"['unit-testing', 'flutter', 'flutter-moor']",644,True,0,1
googlemock giving error while building a program with mock,"<p>I have some experience in C and C++. But I am new to googletest and googlemock.
I am trying unit testing for C++ Programs.
I did not get any error while I was working on googletest. But, when I started working on googlemock, I got problems.
I have a simple code for working with googlemock, and when I tried to build it with the command</p>
<pre class=""lang-sh prettyprint-override""><code>g++ mock.cpp -lgtest -lgtest_main -lgmock -pthread
</code></pre>
<p>I get this error which I am not able to understand. (I have attached both the program and the error which I got).</p>
<p>Please help me to understand it and overcome.
Thanks in advance.</p>
<p>mock.cpp</p>
<pre><code>#include&lt;iostream&gt;
#include&lt;vector&gt;
#include&lt;gtest/gtest.h&gt;
#include&lt;gmock/gmock.h&gt;

using namespace std;
using ::testing::AtLeast;
using ::testing::Return;
using ::testing::_;


class DataBaseConnect{
    public:
        virtual bool login(string username, string password){ return true; }
        virtual bool logout(string username){ return true; }
        virtual int fetchRecord(){ return -1; }
};


class MockDB : public DataBaseConnect{
    public:
        MOCK_METHOD0(fetchRecord, int());
        MOCK_METHOD1(logout, bool(string username));
        MOCK_METHOD2(login, bool(string username, string password));
};


class MyDatabase{
    DataBaseConnect &amp; dbC;
    public:
        MyDatabase(DataBaseConnect &amp; _dbC) : dbC(_dbC) {}

        int Init(string username, string password){
            if(dbC.login(username, password) != true){
                cout&lt;&lt;&quot;DB FAILURE\n&quot;;
                return -1;
            }
            else{
                cout&lt;&lt;&quot;DB SUCCESS\n&quot;;
                return 1;
            }
        }
};


TEST(MyDBTest, LoginTest){
    //Arrange
    MockDB mdb;
    MyDatabase db(mdb);

    EXPECT_CALL(mdb, login(_, _))
    .Times(1)
    .WillOnce(Return(true));

    //Act
    int retVal = db.Init(&quot;Terminator&quot;, &quot;I'm Back&quot;);

    //Assert
    EXPECT_EQ(retVal, 1);
}


int main(int argc, char **argv){
    testing::InitGoogleTest(&amp;argc, argv);

    return RUN_ALL_TESTS();
}
</code></pre>
<p>command:</p>
<pre><code>g++ mock.cpp -lgtest -lgmock -lgtest_main -pthread
</code></pre>
<p>error:</p>
<pre><code>g++ mock.cpp -lgtest -lgmock -lgtest_main -pthread
/usr/bin/ld: /tmp/ccFl5wbu.o: in function `testing::internal::linked_ptr_internal::join(testing::internal::linked_ptr_internal const*)':
mock.cpp:(.text._ZN7testing8internal19linked_ptr_internal4joinEPKS1_[_ZN7testing8internal19linked_ptr_internal4joinEPKS1_]+0x2a): undefined reference to `testing::internal::g_linked_ptr_mutex'
/usr/bin/ld: /tmp/ccFl5wbu.o: in function `testing::internal::linked_ptr_internal::depart()':
mock.cpp:(.text._ZN7testing8internal19linked_ptr_internal6departEv[_ZN7testing8internal19linked_ptr_internal6departEv]+0x27): undefined reference to `testing::internal::g_linked_ptr_mutex'
/usr/bin/ld: /tmp/ccFl5wbu.o: in function `testing::internal::FunctionMockerBase&lt;int ()&gt;::InvokeWith(std::tuple&lt;&gt; const&amp;)':
mock.cpp:(.text._ZN7testing8internal18FunctionMockerBaseIFivEE10InvokeWithERKSt5tupleIJEE[_ZN7testing8internal18FunctionMockerBaseIFivEE10InvokeWithERKSt5tupleIJEE]+0x33): undefined reference to `testing::internal::UntypedFunctionMockerBase::UntypedInvokeWith(void const*)'
/usr/bin/ld: /tmp/ccFl5wbu.o: in function `testing::internal::FunctionMockerBase&lt;bool (std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;)&gt;::InvokeWith(std::tuple&lt;std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt; const&amp;)':
mock.cpp:(.text._ZN7testing8internal18FunctionMockerBaseIFbNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEE10InvokeWithERKSt5tupleIJS7_EE[_ZN7testing8internal18FunctionMockerBaseIFbNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEEE10InvokeWithERKSt5tupleIJS7_EE]+0x33): undefined reference to `testing::internal::UntypedFunctionMockerBase::UntypedInvokeWith(void const*)'
/usr/bin/ld: /tmp/ccFl5wbu.o: in function `testing::internal::FunctionMockerBase&lt;bool (std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;, std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;)&gt;::InvokeWith(std::tuple&lt;std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;, std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt; const&amp;)':
mock.cpp:(.text._ZN7testing8internal18FunctionMockerBaseIFbNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES7_EE10InvokeWithERKSt5tupleIJS7_S7_EE[_ZN7testing8internal18FunctionMockerBaseIFbNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES7_EE10InvokeWithERKSt5tupleIJS7_S7_EE]+0x33): undefined reference to `testing::internal::UntypedFunctionMockerBase::UntypedInvokeWith(void const*)'
/usr/bin/ld: /tmp/ccFl5wbu.o: in function `testing::internal::FunctionMockerBase&lt;bool (std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;, std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt;)&gt;::AddNewExpectation(char const*, int, std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; const&amp;, std::tuple&lt;testing::Matcher&lt;std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt;, testing::Matcher&lt;std::__cxx11::basic_string&lt;char, std::char_traits&lt;char&gt;, std::allocator&lt;char&gt; &gt; &gt; &gt; const&amp;)':
mock.cpp:(.text._ZN7testing8internal18FunctionMockerBaseIFbNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES7_EE17AddNewExpectationEPKciRKS7_RKSt5tupleIJNS_7MatcherIS7_EESG_EE[_ZN7testing8internal18FunctionMockerBaseIFbNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEES7_EE17AddNewExpectationEPKciRKS7_RKSt5tupleIJNS_7MatcherIS7_EESG_EE]+0xda): undefined reference to `testing::Expectation::Expectation(testing::internal::linked_ptr&lt;testing::internal::ExpectationBase&gt; const&amp;)'
collect2: error: ld returned 1 exit status
</code></pre>
",https://stackoverflow.com/questions/67985529/googlemock-giving-error-while-building-a-program-with-mock,"['c++', 'unit-testing', 'googletest', 'googlemock']",862,True,0,1
How to test image upload on Django Rest Framework,"<p>i'm on a struggle. The problem is with the unit testing (&quot;test.py&quot;), and i figured out how to upload images with <strong>tempfile</strong> and <strong>PIL</strong>, but those temporary images never get deleted. I think about making a temporary dir and then, with <strong>os.remove</strong>, delete that temp_dir, but the images upload on different media directorys dependings on the model, so i really don't know how to post temp_images and then delete them.</p>
<p>This is my <strong>models.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>class Noticia(models.Model):
  ...
  img = models.ImageField(upload_to=&quot;noticias&quot;, storage=OverwriteStorage(), default=&quot;noticias/tanque_arma3.jpg&quot;)
  ...
</code></pre>
<p><strong>test.py</strong></p>
<pre class=""lang-py prettyprint-override""><code>def temporary_image():
    import tempfile
    from PIL import Image

    image = Image.new('RGB', (100, 100))
    tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg', prefix=&quot;test_img_&quot;)
    image.save(tmp_file, 'jpeg')
    tmp_file.seek(0)
    return tmp_file

class NoticiaTest(APITestCase):
    def setUp(self):
        ...
        url = reverse('api:noticia-create')
        data = {'usuario': usuario.pk, &quot;titulo&quot;:&quot;test&quot;, &quot;subtitulo&quot;:&quot;test&quot;, &quot;descripcion&quot;:&quot;test&quot;, &quot;img&quot;: temporary_image()}
        response = client.post(url, data,format=&quot;multipart&quot;)

        ...
</code></pre>
<p>So, to summarize, the question is, ¿How can i delete a temporary file from different directories, taking into account that those files strictly have to be upload on those directorys?</p>
",https://stackoverflow.com/questions/67605691/how-to-test-image-upload-on-django-rest-framework,"['python', 'django', 'django-rest-framework', 'temporary-files']",2504,True,5,3
Unit test HttpClient that uses credentials in .NET 5,"<p>I have this in the <code>ConfigureServices</code> method:</p>
<pre><code>services.AddHttpClient(&quot;ClientUsingCredentials&quot;)
        .ConfigurePrimaryHttpMessageHandler(() =&gt;
        {
            var credentials = new NetworkCredential(&quot;someUsername&quot;, &quot;somePassword&quot;);
            return new HttpClientHandler()
            {
                // UseDefaultCredentials = true,
                Credentials = credentials
            };
        });
</code></pre>
<p>Now, my service looks like this:</p>
<pre><code>public class WebAppService : IWebAppService
{
    private readonly ILogger&lt;WebAppService&gt; _logger;
    private readonly IHttpClientFactory _httpClientFactory;

    public WebAppService(ILogger&lt;WebAppService&gt; logger, IHttpClientFactory httpClientFactory)
    {
        _logger = logger;
        _httpClientFactory = httpClientFactory;
    }

    public async Task&lt;WebAppReport&gt; CheckWebSiteWithCredentialsAsync(string someUrlThatNeedsCredentials)
    {
        WebAppReport report = new();

        try
        {
            using (var client = _httpClientFactory.CreateClient(&quot;ClientUsingCredentials&quot;))
            {
                var result = await client.GetAsync(someUrlThatNeedsCredentials);

                if (result.IsSuccessStatusCode)
                {
                    // Do something with the result
                    report.IsCheckSuccessful = true;
                }
                else
                {
                    // Set report fields accordingly
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $&quot;Something went wrong while checking the website: '{someUrlThatNeedsCredentials}'.&quot;);
            // Set report fields accordingly
        }

        return report;
    }
}
</code></pre>
<p>The <code>WebAppReport</code> class:</p>
<pre><code>public class WebAppReport
{
    public bool IsCheckSuccessful { get; set; }
    //Some other fields here
}
</code></pre>
<p>Is there a way to write unit test for this service method that also checks that it passes correct credentials while sending out requests?</p>
<p><strong>Edit:</strong> I see @Nkosi's answer saying that Unit testing is not possible in this case. So, can you please show an example for doing <em>integration</em> test on it?
Should I be creating the service in my test method using <code>new ServiceCollection()</code>, add the service in the same way I did in <code>ConfigureServices</code> method, set correct <code>credentials</code> and so on? Would love to see your example on it.</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/68821329/unit-test-httpclient-that-uses-credentials-in-net-5,"['c#', 'unit-testing', 'moq', 'xunit', '.net-5']",264,True,0,1
Github testing can&#39;t find file,"<p>I have a &quot;models&quot; folder, inside which i have different models that are used for unit testing.
File hierarchy is as follows</p>
<pre><code>- test
  - models
    - nn_class.sav
    - nn_reg.sav
  - test_model
</code></pre>
<p>I run test_model, which has unit test inside. And when i read the file <code>nn_class.sav</code>, it works perfectly fine by giving path <code>&quot;./models&quot;</code>. Whereas when i try to run the same tests on Github, it throws the error of <strong>File not found</strong>.
I have to use this instead, so it can find files in both environments.</p>
<pre><code>model_name = 'nn_class.sav'
    if os.path.isdir('./models'):
        path = './models/'
    else:
        path = 'test/models/'
</code></pre>
<p>Is there a nice elegant way to deal with this issue. Someone suggested fixtures to me, i don't know if they'll be helpful.</p>
",https://stackoverflow.com/questions/68921370/github-testing-cant-find-file,"['python', 'github', 'pytest', 'filenotfoundexception', 'file-not-found']",400,False,0,1
PHPSpec and Behat,"<p>I just started to learn the concept of BDD.</p>
<p>I learn PHPSpec and Behat for that, but it is not clear to my why do I need to use both. I understand that behat is for the functional/acceptance testing and PHPSpec is mainly for unit testing, but the articles and videos I found on this is basicly testing the the code twice: once with behat (with scenarios) and once with with phpspec. Can someone explain to my with easy examples what is the difference and when do I need to use behat and whan phpspec?</p>
<p>Thanks the anwers in advance,
Br.</p>
",https://stackoverflow.com/questions/69152829/phpspec-and-behat,"['php', 'unit-testing', 'testing', 'behat', 'phpspec']",142,True,0,1
Jest test onClick for util function,"<p>Hey guys I am facing issue while trying to add test case for onClick in <strong>MetaDetails.tsx</strong> file</p>
<p><strong>utils.js</strong></p>
<pre><code>export const handlePrintLabelButtonClick = (
  e,
  rmaNumber,
  labelUrl,
  getReturnLabel
) =&gt; {
  const rmaList = [];

  e.preventDefault();
  if (!labelUrl) {
    // some logic
  } else {
    // some logic
  }
};
</code></pre>
<p><strong>PrintLabel.tsx</strong></p>
<pre><code>import { DefaultButton } from &quot;some path&quot;;
import { AnchorWrapper, ButtonWrapper } from &quot;./index.styles&quot;;

export const PrintLabelButton = ({
  target,
  url,
  type,
  text,
  onClickHandle
}: PrintLabelButtonProps) =&gt; {
  return (
    &lt;ButtonWrapper&gt;
      &lt;AnchorWrapper
        href={url}
        target={target}
        type={type}
      &gt;
        &lt;DefaultButton
          tabIndex=&quot;0&quot;
          onClick={onClickHandle}
          data-test=&quot;print-label-button&quot;
        &gt;
          {text}
        &lt;/DefaultButton&gt;
      &lt;/AnchorWrapper&gt;
    &lt;/ButtonWrapper&gt;
  );
};
</code></pre>
<p><strong>MetaDetails.tsx</strong></p>
<pre><code>// Some lines of code 
import { PrintLabelButton } from &quot;./printLabel&quot;;
import { handlePrintLabelButtonClick } from &quot;utils&quot;;
export const OrderMetaDetails = () =&gt; {
  // some logic 
  return(
    //Some React code 

    {showPrintLabelButton &amp;&amp; (
          &lt;PrintLabelButton
            onClickHandle={e =&gt;
              handlePrintLabelButtonClick(e, rmaNumber, labelUrl, getLabel)
            }
            url={labelUrl}
            target=&quot;_blank&quot;
            type=&quot;printLabel&quot;
            text={intl.formatMessage(messages.printLabelText)}
            
          /&gt;
        )}

      // Some React code 
  )
}
</code></pre>
<p>What I've tried</p>
<p><strong>MetaDetails.test.tsx</strong></p>
<pre><code> test(&quot;Order Meta Details Print Label Click&quot;, () =&gt; {
    const handlePrintLabelButtonClick = jest.fn();
    const wrapper = mountWithIntl(
      &lt;OrderMetaDetails
        getLabel={() =&gt; {}}
        info={/*some data*/}
        intl={/*intl*/ }
      /&gt;
    );
    const component = wrapper.find(`[data-test=&quot;print-label-button&quot;]`).hostNodes();
    component.simulate(&quot;click&quot;)
    expect(handlePrintLabelButtonClick).toHaveBeenCalled();
  });
</code></pre>
<p><strong>Jest throws the following error</strong></p>
<pre><code>Error: expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: &gt;= 1
Received number of calls:    0
</code></pre>
<p>When running the test coverage, in the function coverage I see that the &quot;handlePrintLabelButtonClick&quot; in <strong>MetaDetails.tsx</strong> is shown as uncovered. I have tried other approaches as well but none worked. I am new to unit testing. Can someone please guide as to what is the correct approach.</p>
<p><strong>Note 1:</strong>  I am using react/@emotion<br />
<strong>Note 2:</strong>  I have commented or written text such as &quot;some logic&quot; since there are lots of unwanted lines.</p>
",https://stackoverflow.com/questions/69078782/jest-test-onclick-for-util-function,"['javascript', 'reactjs', 'redux', 'react-redux', 'jestjs']",323,False,0,1
Testing stateful UDFs in Flink,"<p>I am trying to test some stateful UDFs in my Scala Flink application following the docs:</p>
<p><a href=""https://nightlies.apache.org/flink/flink-docs-release-1.13/docs/dev/datastream/testing/#unit-testing-stateful-or-timely-udfs--custom-operators"" rel=""nofollow noreferrer"">https://nightlies.apache.org/flink/flink-docs-release-1.13/docs/dev/datastream/testing/#unit-testing-stateful-or-timely-udfs--custom-operators</a></p>
<p>Based on that link, I've added the following dependencies to the <code>build.sbt</code> file:</p>
<pre><code>&quot;org.apache.flink&quot; %% &quot;flink-test-utils&quot; %  flinkVersion % Test,
&quot;org.apache.flink&quot; %% &quot;flink-runtime&quot; %  flinkVersion % Test,
&quot;org.apache.flink&quot; %% &quot;flink-streaming-java&quot; % flinkVersion % Test
</code></pre>
<p>But still, I cannot access the required utility classes such as <code>OneInputStreamOperatorTestHarness</code> (the class cannot be found).</p>
<p>FYI the scala version in my project is 2.12.11, whereas Flink is at v1.13.2. Am I doing something wrong? Any reasons why I cannot find those classes? Maybe the documentation is not correct?</p>
",https://stackoverflow.com/questions/69626681/testing-stateful-udfs-in-flink,"['scala', 'apache-flink']",161,True,0,1
Kotlin state flows not emitting in unit test with view model scope,"<p>I'm new to Kotlin Coroutines and Flows and unit testing them. I have a pretty simple test:</p>
<pre><code>@Test
fun debounce(): Unit = runBlocking {
    val state = MutableStateFlow(&quot;hello&quot;)
    val debouncedState = state.debounce(500).stateIn(this, SharingStarted.Eagerly, &quot;bla&quot;)

    assertThat(debouncedState.value).isEqualTo(&quot;bla&quot;)

    state.value = &quot;good bye&quot;

    // not yet...
    assertThat(debouncedState.value).isEqualTo(&quot;bla&quot;)

    delay(600)

    // now!
    assertThat(debouncedState.value).isEqualTo(&quot;good bye&quot;)

    // cannot close the state flows :(
    cancel(&quot;DONE&quot;)
}
</code></pre>
<p>It works just fine (except that I cannot stop it, but that's a different issue).</p>
<p>Next, I want to test my <code>ViewModel</code> which includes the exact same state flows. It's basically the same code above, but I thought it should run in the same scope as <code>viewModel.someMutableStateFlow</code> so I tried to run it on <code>viewModelScope</code>:</p>
<pre><code>@Test
fun debounce(): Unit = runBlocking {
    val viewModel = MyViewModel()

    // in view model the state and debouncedState are defined the same way as above
    val state = viewModel.someMutableStateFlow
    val debouncedState = state.debounce(500).stateIn(viewModel.viewModelScope, SharingStarted.Eagerly, &quot;bla&quot;)

    ///////////////////////////////////////////////////
    // Below is the same code as in previous example //
    ///////////////////////////////////////////////////

    assertThat(debouncedState.value).isEqualTo(&quot;bla&quot;)

    state.value = &quot;good bye&quot;

    // not yet...
    assertThat(debouncedState.value).isEqualTo(&quot;bla&quot;)

    delay(600)

    // now!
    assertThat(debouncedState.value).isEqualTo(&quot;good bye&quot;)

    // cannot close the state flows :(
    cancel(&quot;DONE&quot;)
}
</code></pre>
<p>But this time the <code>debouncedState.value</code> is never changed, it stays <code>bla</code> all the time! Nothing is emitted from those states.</p>
<p>Does this have something to do with the fact that I am using <code>viewModelScope</code> and maybe it is not running?</p>
<p>Some explanation about what's going on here would be great.</p>
",https://stackoverflow.com/questions/68673993/kotlin-state-flows-not-emitting-in-unit-test-with-view-model-scope,"['kotlin', 'kotlin-coroutines', 'kotlin-flow']",927,True,10,1
Writing Test cases for Spring Integration Application,"<p>I am new for Unit/Integration testing. Hence looking for best approach for given scenario.
I have legacy application (REST) which was written in Spring Integration. Same application I have migrated to Spring Boot. Now I am wondering, how to mock Gateway in Controller and how to test Gateways, Routers. Application structure as:</p>
<p><strong>Controller:</strong></p>
<pre><code>@RestController
@RequestMapping(value = &quot;/acct&quot;)
public class AcctOpenImpl implements AcctOpen {
    /**
     * AcctMgmt Gateway Interface.
     */
    @Autowired
    AcctOpenService acctopenmgmtServiceGateway;
    
    @Override
    @RequestMapping(value = &quot;/product/{product_id_num}&quot;, method = RequestMethod.GET)
    public ResponseEntity&lt;RetrieveAppProdAplnResponse&gt; rtrvAppProdAplnByQueryParam(
        @PathVariable(&quot;product_id_num&quot;) final Long productIdNum) throws BusinessException,
        TechnicalException {
        Map&lt;String, Object&gt; headers = getHeaders();
       
        RetrieveAppProdAplnResponse response = this.acctopenmgmtServiceGateway.rtrvAppProdApln(request, headers);

        ResponseEntity&lt;RetrieveAppProdAplnResponse&gt; retrieveAppProdResponse = new ResponseEntity&lt;RetrieveAppProdAplnResponse&gt;(
            response, HttpStatus.OK);

        return retrieveAppProdResponse;
    }
} 
</code></pre>
<p><strong>Service Interface:</strong></p>
<pre><code>public interface AcctOpenService {
    public RetrieveAppProdAplnResponse rtrvAppProdApln(RetrieveAppProdAplnRequest retrieveAppProdAplnRequest,
        @Headers Map&lt;String, Object&gt; customHeaderMap) throws BusinessException, TechnicalException;
}
</code></pre>
<p><strong>geteways.xml:</strong></p>
<pre><code>&lt;int:gateway id=&quot;acctopenmgmtServiceGateway&quot; service-interface=&quot;com.hsbc.group.depositproduct.svc.gateway.AcctOpenService&quot;
    default-reply-channel=&quot;acctopenmgmtReplyChannel&quot; error-channel=&quot;acctopenmgmtErrorChannel&quot;&gt;
    &lt;int:method name=&quot;rtrvAppProdApln&quot; request-channel=&quot;rtrvAppProdAplnRequestChannel&quot; /&gt;
&lt;/int:gateway&gt;
</code></pre>
<p><strong>si-channels.xml:</strong></p>
<pre><code>&lt;int:channel id=&quot;rtrvAppProdAplnRequestChannel&quot;/&gt;
</code></pre>
<p><strong>si-routers.xml:</strong></p>
<pre><code>&lt;int:router input-channel=&quot;rtrvAppProdAplnRequestChannel&quot; default-output-channel=&quot;acctopenmgmtReplyChannel&quot;     expression=&quot;headers.SERVICE_HEADER.consumerEntyId.ctryCde.toLowerCase()+headers.SERVICE_HEADER.consumerEntyId.groupMbr+'RtrvAppProdAplnRequestChannel'&quot; /&gt;
</code></pre>
<p><strong>si-chain.xml:</strong></p>
<pre><code>&lt;int:chain input-channel=&quot;usMMBIRtrvAppProdAplnRequestChannel&quot; output-channel=&quot;acctopenmgmtReplyChannel&quot;&gt;
    &lt;int:transformer method=&quot;formatRequest&quot; ref=&quot;usRtrvAppProdAplnTransformer&quot;/&gt;
    &lt;int:service-activator method=&quot;rtrvAppProdApln&quot; ref=&quot;rtrvAppProdAplnActivator&quot; /&gt;
    &lt;int:transformer method=&quot;parseResponse&quot; ref=&quot;usRtrvAppProdAplnTransformer&quot;/&gt;
&lt;/int:chain&gt;
</code></pre>
<p><strong>si-transformers.xml:</strong></p>
<pre><code>&lt;bean id=&quot;usRtrvAppProdAplnTransformer&quot; class=&quot;com.hsbc.group.depositproduct.us.svc.transformer.RetrieveAppProdAplnTransformer&quot;&gt;
&lt;/bean&gt;
</code></pre>
<p>Could you please suggest best approach (Unit testing or Integration testing) for given scenario. Also, if some one gives any example that how can I start that will be appreciated.
Thanks in advance.</p>
",https://stackoverflow.com/questions/66843582/writing-test-cases-for-spring-integration-application,"['spring-boot', 'unit-testing', 'spring-integration', 'integration-testing']",120,False,-1,1
How to do integration testing with spring and junit by scanning classpath instead of manually specifying classes to autowire?,"<p>I'm trying to do some sort of integration testing (not really full testing, only it's not  really unit testing either) on a service :</p>
<pre><code>package foo;


@Component
public class FooService {}
</code></pre>
<p>And the corresponding test :</p>
<pre><code>package foo;

@SpringBootTest
public FooTest {
   @Autowired FooService fooService;
}
</code></pre>
<p>Only when I try to test it says</p>
<pre><code>No qualifying bean of type 'foo.FooService' available
</code></pre>
<p>I could add the class to <code>@SpringBootTest</code> like this :</p>
<pre><code>@SpringBootTest(classes = {FooService.class})
</code></pre>
<p>But I don't want to manually select the classes I want to test. My application is much larger than the MWE, and I want to test without having to specify each class I am testing and their respective dependencies.</p>
<p>Is there anyway to tell spring to scan and autowire dependencies like it would outside of tests ?</p>
",https://stackoverflow.com/questions/69741747/how-to-do-integration-testing-with-spring-and-junit-by-scanning-classpath-instea,"['java', 'spring', 'testing']",98,True,0,1
fireEvent.click doesn&#39;t make any changes to the state while testing in react,"<p>I'm trying to build a simple calculator application using react, but facing some issues while doing some unit testing. Here I've attached the test case in which I'm facing some issues. Most of the references I found online are built using a single component. In my case I'm using <strong>useReducer</strong> for state management and <strong>useContext</strong> for passing the data to other components, but while firing <strong>click</strong> event it doesn't make any changes to the state, so the <code>result.textContent</code> always remains as an empty string(&quot;&quot;). Any kind of help or hint will be appriciated.</p>
<p><strong>App.test.js</strong></p>
<pre><code>import React from &quot;react&quot;;
import { render, fireEvent } from &quot;@testing-library/react&quot;;
import App from &quot;./App&quot;;
import &quot;@testing-library/jest-dom/extend-expect&quot;;

describe(&quot;Calculator test&quot;, () =&gt; {
  const { getByTestId } = render(&lt;App /&gt;);

  const btn7 = getByTestId(&quot;nm-btn-7&quot;);
  const btnSum = getByTestId(&quot;nm-btn-sum&quot;);
  const btn2 = getByTestId(&quot;nm-btn-2&quot;);
  const btnEql = getByTestId(&quot;eq-btn&quot;);
  const result = getByTestId(&quot;result&quot;);

  // expect(btn7.textContent).toBe(&quot;7&quot;);
  it(&quot;should return the correct sum value&quot;, () =&gt; {
    fireEvent.click(btn7);
    fireEvent.click(btnSum);
    fireEvent.click(btn2);
    fireEvent.click(btnEql);
    console.log(result.textContent);
    expect(result.textContent).toBe(&quot;9&quot;);
  });
});
</code></pre>
<p><strong>App.tsx</strong></p>
<pre><code>import React from &quot;react&quot;;
import styled from &quot;styled-components&quot;;

import Calculator from &quot;./components/Calculator&quot;;
import &quot;./_app.scss&quot;;

function App() {
  return (
    &lt;Main&gt;
      &lt;div&gt;
        &lt;Calculator /&gt;
      &lt;/div&gt;
    &lt;/Main&gt;
  );
}

const Main = styled.main`
  display: grid;
  place-items: center;
  min-height: 100vh;
  div {
    /* width: 25%; */
    /* height: 70vh; */
    background-color: #061017;
    border-radius: 0.5em;
  }
`;

export default App;

</code></pre>
<p><strong>Calculator.tsx</strong></p>
<pre><code>import React from &quot;react&quot;;
import styled from &quot;styled-components&quot;;

import { useGlobalContext } from &quot;../context/context&quot;;
import Buttons from &quot;./Buttons&quot;;
import &quot;./_calculator.scss&quot;;

const Calculator = () =&gt; {
  const { newState } = useGlobalContext();

  const { inputValue } = newState;

  return (
    &lt;Container&gt;
      &lt;section className=&quot;form-section&quot;&gt;
        &lt;div className=&quot;result&quot; data-testid=&quot;result&quot;&gt;
          {inputValue}
        &lt;/div&gt;
      &lt;/section&gt;
      &lt;section className=&quot;button-section&quot;&gt;
        &lt;Buttons /&gt;
      &lt;/section&gt;
    &lt;/Container&gt;
  );
};

const Container = styled.section`
  color: #f2f3f4;
  height: inherit;
  .form-section {
    .result {
      width: 100%;
      padding: 2em 1em;
      font-size: 2em;
      height: 5em;
      border: none;
      outline: none;
      border-radius: 0.5em;
      background-color: #061017;
      color: #f2f3f4;
      text-align: right;
    }
  }
  .button-section {
    padding: 0.5em;
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 0.5em;
  }
`;

export default Calculator;

</code></pre>
<p><strong>Buttons.tsx</strong></p>
<pre><code>import React, { Fragment } from &quot;react&quot;;

import { useGlobalContext } from &quot;../context/context&quot;;
import &quot;./_buttons.scss&quot;;

const Buttons = () =&gt; {
  const {
    handleNumberOpClick,
    handleEqualClick,
    handleClearClick,
    handleBackspaceClick,
  } = useGlobalContext();

  return (
    &lt;Fragment&gt;
      &lt;button className=&quot;button-span-2 sp-btn&quot; onClick={handleBackspaceClick}&gt;
        C
      &lt;/button&gt;
      &lt;button className=&quot;sp-btn&quot; onClick={handleClearClick}&gt;
        AC
      &lt;/button&gt;
      {/* &lt;button className=&quot;button-blue&quot;&gt;+/-&lt;/button&gt; */}
      &lt;button
        className=&quot;button-blue nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;/&quot;
      &gt;
        &amp;divide;
      &lt;/button&gt;
      &lt;button
        className=&quot;button-gray&quot;
        data-testid=&quot;nm-btn-7&quot;
        onClick={handleNumberOpClick}
        name=&quot;7&quot;
      &gt;
        7
      &lt;/button&gt;
      &lt;button
        className=&quot;button-gray nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;8&quot;
      &gt;
        8
      &lt;/button&gt;
      &lt;button
        className=&quot;button-gray nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;9&quot;
      &gt;
        9
      &lt;/button&gt;
      &lt;button
        className=&quot;button-blue nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;*&quot;
      &gt;
        &amp;times;
      &lt;/button&gt;
      &lt;button
        className=&quot;button-gray nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;4&quot;
      &gt;
        4
      &lt;/button&gt;
      &lt;button
        className=&quot;button-gray nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;5&quot;
      &gt;
        5
      &lt;/button&gt;
      &lt;button
        className=&quot;button-gray nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;6&quot;
      &gt;
        6
      &lt;/button&gt;
      &lt;button
        className=&quot;button-blue nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;-&quot;
      &gt;
        -
      &lt;/button&gt;
      &lt;button
        className=&quot;button-gray nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;1&quot;
      &gt;
        1
      &lt;/button&gt;
      &lt;button
        className=&quot;button-gray&quot;
        data-testid=&quot;nm-btn-2&quot;
        onClick={handleNumberOpClick}
        name=&quot;2&quot;
      &gt;
        2
      &lt;/button&gt;
      &lt;button
        className=&quot;button-gray nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;3&quot;
      &gt;
        3
      &lt;/button&gt;
      &lt;button
        className=&quot;button-blue&quot;
        data-testid=&quot;nm-btn-sum&quot;
        onClick={handleNumberOpClick}
        name=&quot;+&quot;
      &gt;
        +
      &lt;/button&gt;
      &lt;button
        className=&quot;button-span-2 button-gray nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;0&quot;
      &gt;
        0
      &lt;/button&gt;
      &lt;button
        className=&quot;button-gray nm-btn&quot;
        onClick={handleNumberOpClick}
        name=&quot;.&quot;
      &gt;
        .
      &lt;/button&gt;
      &lt;button
        className=&quot;nm-btn&quot;
        data-testid=&quot;eq-btn&quot;
        onClick={handleEqualClick}
      &gt;
        =
      &lt;/button&gt;
    &lt;/Fragment&gt;
  );
};

export default Buttons;

</code></pre>
<p><strong>context.tsx</strong></p>
<pre><code>import React, { useContext, useReducer } from &quot;react&quot;;

import { reducer } from &quot;../reducer/reducer&quot;;
import { IState, IValue } from &quot;../interfaces&quot;;

const initialState: IState = {
  inputValue: &quot;&quot;,
};

const initialContextState: IValue = {
  newState: initialState,
  handleNumberOpClick: function () {},
  handleEqualClick: function () {},
  handleClearClick: function () {},
  handleBackspaceClick: function () {},
};

const AppContext = React.createContext&lt;IValue&gt;(initialContextState);

const AppProvider = ({ children }: { children: any }) =&gt; {
  const [newState, dispatch] = useReducer(reducer, initialState);

  const handleNumberOpClick = (e: any) =&gt; {
    e.preventDefault();
    let newInputValue = newState.inputValue || &quot;&quot;;
    if (
      newState.inputValue === &quot;Invalid&quot; ||
      newState.inputValue === &quot;Infinity&quot;
    ) {
      dispatch({
        type: &quot;ON_NUMBER_OP_CLICK&quot;,
        payload: e.target.name,
      });
      return;
    }
    newInputValue = newInputValue.concat(e.target.name);
    dispatch({ type: &quot;ON_NUMBER_OP_CLICK&quot;, payload: newInputValue });
  };

  const handleEqualClick = () =&gt; {
    try {
      if (
        newState.inputValue === &quot;Invalid&quot; ||
        !newState.inputValue ||
        newState.inputValue === &quot;Infinity&quot;
      ) {
        dispatch({
          type: &quot;ON_EQUAL_CLICK&quot;,
          payload: &quot;&quot;,
        });
        return;
      }
      dispatch({
        type: &quot;ON_EQUAL_CLICK&quot;,
        payload: eval(newState.inputValue).toString(),
      });
    } catch (err) {
      dispatch({
        type: &quot;ON_EQUAL_CLICK&quot;,
        payload: &quot;Invalid&quot;,
      });
    }
  };

  const handleClearClick = () =&gt; {
    dispatch({ type: &quot;ON_CLEAR_CLICK&quot; });
  };

  const handleBackspaceClick = () =&gt; {
    const newInputValue = newState.inputValue.slice(0, -1) || &quot;&quot;;
    dispatch({ type: &quot;ON_BACKSPACE_CLICK&quot;, payload: newInputValue });
  };

  return (
    &lt;AppContext.Provider
      value={{
        newState,
        handleNumberOpClick,
        handleEqualClick,
        handleClearClick,
        handleBackspaceClick,
      }}
    &gt;
      {children}
    &lt;/AppContext.Provider&gt;
  );
};

export const useGlobalContext = () =&gt; {
  return useContext(AppContext);
};

export { AppContext, AppProvider };

</code></pre>
<p><strong>reducer.ts</strong></p>
<pre><code>import { IAction, IState } from &quot;../interfaces&quot;;

export const reducer = (currentState: IState, action: IAction): IState =&gt; {
  const { type, payload } = action;

  if (type === &quot;ON_NUMBER_OP_CLICK&quot;) {
    return { ...currentState, inputValue: payload };
  }

  if (type === &quot;ON_EQUAL_CLICK&quot;) {
    return { ...currentState, inputValue: payload };
  }

  if (type === &quot;ON_CLEAR_CLICK&quot;) {
    return { ...currentState, inputValue: &quot;&quot; };
  }

  if (type === &quot;ON_BACKSPACE_CLICK&quot;) {
    return { ...currentState, inputValue: payload };
  }

  return currentState;
};

</code></pre>
<p><strong>interfaces.ts</strong></p>
<pre><code>export type IType =
  | &quot;ON_NUMBER_OP_CLICK&quot;
  | &quot;ON_CLEAR_CLICK&quot;
  | &quot;ON_BACKSPACE_CLICK&quot;
  | &quot;ON_EQUAL_CLICK&quot;;

export interface IState {
  inputValue: string;
}

export interface IAction {
  type: IType;
  payload?: any;
}

export interface IValue {
  newState: IState;
  handleNumberOpClick: any;
  handleEqualClick: any;
  handleClearClick: any;
  handleBackspaceClick: any;
}

</code></pre>
",https://stackoverflow.com/questions/69098563/fireevent-click-doesnt-make-any-changes-to-the-state-while-testing-in-react,"['javascript', 'reactjs', 'unit-testing']",908,True,0,1
"Why does my method work in my API, but not in a test class?","<p>I have a problem with unit testing a functionality.</p>
<pre><code>public User[] fetchUserByStarsAscendingOrder(String username) throws IOException {
    User[] user = fetchUser(username);
    Arrays.sort(user,Collections.reverseOrder());
    return user;
}   

public User[] fetchUser(String username) throws IOException {
    URL url = new URL(&quot;https://api.github.com/users/&quot; + username + &quot;/repos&quot;);
    InputStreamReader reader = new InputStreamReader(url.openStream());

    User[] user = new Gson().fromJson(reader, User[].class);

    if (user == null) {
        logger.error(&quot;No input provided.&quot;);
        return null;
    } else {
        logger.info(&quot;The output returned.&quot;);
        return user;
    }
}
</code></pre>
<p>The above method works just fine in my API, no troubles whatsoever.</p>
<p>BUT when I try to use it in my test class, with the same parameter... it suddenly returns null:</p>
<pre><code>class UserServiceTest {
        UserService userService;
        User aUser;
        
        @Test
        void shouldReturnArray() throws IOException {
            //given
            String name = &quot;pjhyett&quot;;
            //when
            User[] resultArray = userService.fetchUserByStarsAscendingOrder(name);
            //then
            assertThat(resultArray[0]).isEqualTo(aUser);
        }

        @BeforeEach
        void setUp() {
            aUser = new User();
            aUser.setFull_name(&quot;pjhyett/github-services&quot;);
            aUser.setDescription(&quot;Moved to http://github.com/github/github-services&quot;);
            aUser.setClone_url(&quot;https://github.com/pjhyett/github-services.git&quot;);
            aUser.setStars(408);
            aUser.setCreatedAt(&quot;2008-04-28T23:41:21Z&quot;);
        }
</code></pre>
<p>All the above data is taken from GitHub API and are about public repos. I am reaching for the first element in the array because the method returns a couple of results for the array.</p>
<p>IDE tells me that the method that works perfectly in the API itself... returns a null in a test class.</p>
<p>Why is that?</p>
",https://stackoverflow.com/questions/66970226/why-does-my-method-work-in-my-api-but-not-in-a-test-class,"['java', 'testing', 'gson', 'inputstreamreader']",153,False,0,1
Node / Express / Mocha disable middleware?,"<p>I have a hello world app which looks like this:</p>
<pre><code>let clientAuthMiddleware = () =&gt; (req, res, next) =&gt; {
  if (!req.client.authorized) {
    return res.status(401).send('Invalid client certificate authentication.');
  }
  return next();
};

function app() {
    const fs = require('fs');
    const https = require('https');
    const express = require('express');

    const app = express();
    app.use(clientAuthMiddleware());

    app.get('/', (req, res) =&gt; {
      console.log(req.socket.getPeerCertificate());
      return res.send('Hello world!');
    });

    https
      .createServer(
        {
          cert: fs.readFileSync('cert/localhost.crt'),
          key: fs.readFileSync('cert/localhost.key'),        
          requestCert: true,
          rejectUnauthorized: false,
          ca: fs.readFileSync('cert/ca.crt'),
        },
        app
      )
      .listen(9443);
    
    return app;
}

if (require.main === module) instance = app()
module.exports.app = app
module.exports.authMiddleware = clientAuthMiddleware
</code></pre>
<p>And a test which looks like:</p>
<pre><code> describe('GET /', function() {
    it('should return Hello world!', function(done) {
          chai.request(app.app()).get('/')
             .end((err, res) =&gt; {
                 if (err)done(err);
                 res.should.have.status(200);
                 expect(res.body).to.equal('Hello world!');
                 done();
              });
    });
  });
</code></pre>
<p>How can I replace authMiddleware in the test, preferably without using some external stubbing library? Isn't there some way I can just rearrange my code so in the test I can just do app.authMiddleware = {my own stub function} ?</p>
<p>Edit: Also, is there a way I can just straightforwardly unit test these endpoints like app.get('/') without making a real HTTP request? I keep searching Google for unit testing Node/Express with Mocha and every resource I find seems to be functional testing making a real request....</p>
",https://stackoverflow.com/questions/66568989/node-express-mocha-disable-middleware,"['javascript', 'node.js', 'express', 'mocha.js', 'chai']",228,False,0,1
"Why does my method work in my API, but not in a test class?","<p>I have a problem with unit testing a functionality.</p>
<pre><code>public User[] fetchUserByStarsAscendingOrder(String username) throws IOException {
    User[] user = fetchUser(username);
    Arrays.sort(user,Collections.reverseOrder());
    return user;
}   

public User[] fetchUser(String username) throws IOException {
    URL url = new URL(&quot;https://api.github.com/users/&quot; + username + &quot;/repos&quot;);
    InputStreamReader reader = new InputStreamReader(url.openStream());

    User[] user = new Gson().fromJson(reader, User[].class);

    if (user == null) {
        logger.error(&quot;No input provided.&quot;);
        return null;
    } else {
        logger.info(&quot;The output returned.&quot;);
        return user;
    }
}
</code></pre>
<p>The above method works just fine in my API, no troubles whatsoever.</p>
<p>BUT when I try to use it in my test class, with the same parameter... it suddenly returns null:</p>
<pre><code>class UserServiceTest {
        UserService userService;
        User aUser;
        
        @Test
        void shouldReturnArray() throws IOException {
            //given
            String name = &quot;pjhyett&quot;;
            //when
            User[] resultArray = userService.fetchUserByStarsAscendingOrder(name);
            //then
            assertThat(resultArray[0]).isEqualTo(aUser);
        }

        @BeforeEach
        void setUp() {
            aUser = new User();
            aUser.setFull_name(&quot;pjhyett/github-services&quot;);
            aUser.setDescription(&quot;Moved to http://github.com/github/github-services&quot;);
            aUser.setClone_url(&quot;https://github.com/pjhyett/github-services.git&quot;);
            aUser.setStars(408);
            aUser.setCreatedAt(&quot;2008-04-28T23:41:21Z&quot;);
        }
</code></pre>
<p>All the above data is taken from GitHub API and are about public repos. I am reaching for the first element in the array because the method returns a couple of results for the array.</p>
<p>IDE tells me that the method that works perfectly in the API itself... returns a null in a test class.</p>
<p>Why is that?</p>
",https://stackoverflow.com/questions/66970226/why-does-my-method-work-in-my-api-but-not-in-a-test-class,"['java', 'testing', 'gson', 'inputstreamreader']",153,False,0,1
getBoundingClientRect() returns zero,"<p>What the below code does is it creates a span with specific dimensions and position (Offered by getBoundingClientRect) when the mouse is hovered over an <code>&lt;a&gt;</code> tag and this works fine</p>
<pre><code>
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
  &lt;meta charset=&quot;UTF-8&quot;&gt;
  &lt;title&gt;ollow Along Nav&lt;/title&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;style.css&quot;&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;nav&gt;
      &lt;ul class=&quot;menu&quot;&gt;
        &lt;li&gt;&lt;a href=&quot;&quot;&gt;Home&lt;/a&gt;&lt;/li&gt;
     
      &lt;/ul&gt;
    &lt;/nav&gt;

    &lt;div class=&quot;wrapper&quot;&gt;
      &lt;p&gt;Lorem ipsum dolor sit amet, &lt;a href=&quot;&quot;&gt;consectetur&lt;/a&gt; adipisicing elit. Est &lt;a href=&quot;&quot;&gt;explicabo&lt;/a&gt; unde natus necessitatibus esse obcaecati distinctio, aut itaque, qui vitae!&lt;/p&gt;
      &lt;p&gt;Aspernatur sapiente quae sint &lt;a href=&quot;&quot;&gt;soluta&lt;/a&gt; modi, atque praesentium laborum pariatur earum &lt;a href=&quot;&quot;&gt;quaerat&lt;/a&gt; cupiditate consequuntur facilis ullam dignissimos, aperiam quam veniam.&lt;/p&gt;
    &lt;/div&gt;

&lt;script&gt;
  const triggers = document.querySelectorAll('a');
  const highlight = document.createElement('span');
  highlight.classList.add('highlight');
  document.body.appendChild(highlight);

  function highlightLink(a) {
    const linkCoords = a.getBoundingClientRect();
    const coords = {
      width: linkCoords.width,
      height: linkCoords.height,
      top: linkCoords.top + window.scrollY,
      left: linkCoords.left + window.scrollX
    };

    highlight.style.width = `${coords.width}px`;
    highlight.style.height = `${coords.height}px`;
    highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;

  }

  triggers.forEach(a =&gt; highlightLink(a));

&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

</code></pre>
<p>I wanted to create a unit testing for the above code in the script tag So I came up with this NodeJS based script</p>
<pre><code>const index = require('./index.js');
//runs the html in express app


var jsdom = require('jsdom');
const { JSDOM } = jsdom;
const { document } = (new JSDOM('')).window;
global.document = document;

const test =async()=&gt;{

   const request = require('supertest');
  const response = await request(index).get(&quot;/&quot;);
 
  document.body.innerHTML = response.text;
  const triggers = document.querySelectorAll('a')
  var highlight = document.createElement('span');
highlight.classList.add('highlight');
document.body.appendChild(highlight);
  

  function checkThis(a) {
      
    const linkCoords = a.getBoundingClientRect();
 console.log(linkCoords.width)

    }
    triggers.forEach(a =&gt; checkThis(a));
} 

  
test()
</code></pre>
<p>For some reason, I am getting the width as zero for all the <code>&lt;a&gt;</code> tags. Even the other properties from <code>getBoundingClientRect</code> are zero. What could be the possible reasons for it?. And what will be the best way to test this code using Jest and Supertest?</p>
",https://stackoverflow.com/questions/70290905/getboundingclientrect-returns-zero,"['javascript', 'html']",1227,False,0,1
flutter: unit testing dao in moor,"<p>I've started unit testing the first time. I'm following tutorials of <a href=""https://github.com/ResoCoder/flutter-tdd-clean-architecture-course"" rel=""nofollow noreferrer"">resoCoder</a></p>
<p>here is my test code where I'm mocking my dbManager class but I could not mock DAO's as they are auto-generated in moor and there is no setter method for them.</p>
<pre><code>class MockDbManager extends Mock implements DbManager{}

void main() {
  RecipeLocalDataSource dataSource;
  MockDbManager _dbManager;
  setUp(() {
    _dbManager = MockDbManager();
    dataSource = RecipeLocalDataSource(_dbManager);
  });

  group('Search Food Table', (){
    List&lt;FoodTableData&gt; getFoodTable(){
      var list = [];
      for(var i =1; i &lt;=5 ; i++){
        list.add(FoodTableData(id: i, name: 'item $i'));
      }
      return list;
    }
    var searchQuery = 'query';

    test('Should return foodTableData when query is successful', (){
      //arrange
      when(_dbManager.foodTableDao.searchFoods(searchQuery)).thenAnswer((realInvocation) async =&gt; getFoodTable());
      //act
      var result = dataSource.searchFoodTable('test');
      //assert
      verify(_dbManager.foodTableDao.searchFoods(searchQuery));
      expect(getFoodTable(), result);
    });
  });
}
</code></pre>
<p>I'm getting the following error</p>
<pre><code>NoSuchMethodError: The method 'searchFoods' was called on null.
Receiver: null
Tried calling: searchFoods(&quot;query&quot;)
</code></pre>
<p>I understood the error but don't know how to solve that.</p>
<p>Also, I'm getting a similar issue with preferenceManager class as well, where I'm having a getter for UserPrefs.</p>
<pre><code>UserPrefs get user =&gt; UserPrefs(_pref);
</code></pre>
<p>when I'm accessing <code>_prefManager.user.name</code> for the test, it throws the same error. How can I tackle that as well?</p>
",https://stackoverflow.com/questions/65561079/flutter-unit-testing-dao-in-moor,"['unit-testing', 'flutter', 'flutter-moor']",644,True,0,1
C#: P/Invoke and Unit Testing,"<p>I have been following the guidelines from:</p>
<ul>
<li><a href=""https://www.meziantou.net/stop-using-intptr-for-dealing-with-system-handles.htm"" rel=""nofollow noreferrer"">https://www.meziantou.net/stop-using-intptr-for-dealing-with-system-handles.htm</a></li>
</ul>
<p>So basically I have now a wrapper class on top of my native code as follow:</p>
<pre><code>public sealed class MyFileWrapper : IDisposable
{
    private readonly MySafeHandle _handle;
    // implement cstor and Dispose() as recommended

    public int ReadFile(byte[] bytes, int numBytesToRead) {
      int ret = NativeMethods.ReadFile(_handle...);
      // ...
      return numBytesRead;
    }
}
</code></pre>
<p>with:</p>
<pre><code>internal static class NativeMethods
{
[...]
    // Take a SafeHandle in parameter instead of IntPtr
    [DllImport(&quot;kernel32&quot;, SetLastError = true)]
    internal extern static int ReadFile(MySafeHandle handle, byte[] bytes, int numBytesToRead, out int numBytesRead, IntPtr overlapped_MustBeZero);
[...]
}
</code></pre>
<p>What would be a good practice to unit test this <code>ReadFile</code> function (using Xunit) ? It seems like the static class <code>NativeMethods</code> is <a href=""https://stackoverflow.com/a/1823750/136285"">against good practice</a> for unit testing, so I was wondering what people do in this case. It seems that hiding the implementation detail of <code>MySafeHandle</code> is part of the solution, so I suspect turning <code>NativeMethods</code> into an interface would expose too much of the low level.</p>
",https://stackoverflow.com/questions/68257341/c-p-invoke-and-unit-testing,['.net-core'],100,False,0,0
Use unit-testing framework in matlab to test data,"<p>I would like to test datasets with a variable number of values. Each value should be tested and I would like to have a standardized output that I can read in afterward again. My used framework is Matlab.</p>
<p>Example:<br />
The use case would be a dataset which includes, e.g., 14 values that need to be testet. The comparison is already completely handled by my implementation. So I have 14 values, which I would like to compare against some tolerance or similar and get an output like</p>
<pre><code>1..14
ok value1
ok value2
not ok value3
...
ok value14
</code></pre>
<p>Current solution:<br />
I try to use the <a href=""https://de.mathworks.com/help/matlab/class-based-unit-tests.html?s_tid=CRUX_lftnav"" rel=""nofollow noreferrer"">unit-testing framework</a> and the according <a href=""https://de.mathworks.com/help/matlab/ref/matlab.unittest.plugins.tapplugin-class"" rel=""nofollow noreferrer"">TAPPlugin</a> that would produce exactly such an output (<a href=""https://testanything.org/"" rel=""nofollow noreferrer"">tap</a>), one for every unit-test. My main problem is that the unit-testing framework does not take any input parameters. I already read about parametrization, but I do not know how this helps me. I could put the values as a list into the parameter, but how to I pass them there? Afaik the unit-test class does not allow additional parameters during initialization, so I cannot include this in the program the way I want.</p>
<p>I would like to avoid to need to format the TAP output on my own, because it is already there, but only for unit-test objects. Unfortunately, I cannot see how to implement this wisely.</p>
<p>How can I implement the output of a test anything protocol where I have a variable amount of comparisons (values) in Matlab?</p>
",https://stackoverflow.com/questions/69191537/use-unit-testing-framework-in-matlab-to-test-data,"['matlab', 'testing']",82,False,0,1
Unit testing with user inputs - Python,"<p>im trying to create a unit test to check a function that includes user input.
Im very new to unit testing and this is one seems a little complex for me. Basically the function takes coordinates of user input and places a &quot;ship&quot; of &quot;o&quot; in a 2d array of points.</p>
<p>example:</p>
<pre><code>[[&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;],[&quot;.&quot;,&quot;O&quot;,&quot;O&quot;,&quot;O&quot;,&quot;.&quot;], [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;], [&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;,&quot;.&quot;]]
</code></pre>
<p>The test i wrote is not checking how the arrays match because id basically have to build another 2d array to check if my 2d array is built properly.... Is there a way to write this unit test to properly check the output?</p>
<p>What am i missing here?</p>
<p>Here is the code:</p>
<pre><code>def set_ship_coordinates():
        letterArray = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;, &quot;F&quot;, &quot;G&quot;, &quot;H&quot;]
        board = GameBoard().gameboard
        
        while True:
        
            while True:
                direction_input = input(&quot;Which direction? Horizontal 'H' or Vertical 'V': &quot;)
                upper_direction = direction_input.upper() #uppercase the input for the function check
                
                if upper_direction == &quot;H&quot; or upper_direction == &quot;V&quot;:
                    break
                else:
                    print(&quot;That is not a valid input, please enter H or V&quot;)
                    print(&quot; &quot;)
            
            while True: 
                row_input = input(&quot;Which row? (Between 1 and 8): &quot;)
                try:
                    int_row = int(row_input)
                    if int_row &gt;= 1 and int_row &lt;=8:
                        break
                    else:
                        print(&quot;That is not a valid input, please enter between 1 and 8&quot;)
                        print(&quot; &quot;)
                except ValueError:
                    print(&quot;This is not a valid response&quot;)
                    
            while True: 
                column_input = input(&quot;Which Column? (Between A and H): &quot;)
                upper_column = column_input.upper() #uppercase the input for loop check
                
                if upper_column in letterArray:
                    column_choice = letterArray.index(upper_column)
                    break
                else:
                    print(&quot;That is not a valid input, please enter letter between A and H&quot;)
                    print(&quot; &quot;)
            
            dir = upper_direction
            row = int_row - 1 #remove one here to account for 0 in list 
            column = column_choice #this is already an index value and does not need to -1
            
            if dir == &quot;H&quot;:
                #if horizontal, column cannot be 0 or 7 at center or ship is out of bounds
                if column != 0 and column != 7:
                    #center of ship
                    board[row][column] = &quot;O&quot;
                    #front and back of ship
                    board[row][column - 1] = &quot;O&quot;
                    board[row][column + 1] = &quot;O&quot;
                    return board
                else: 
                    print(&quot;Can't place ship here, try again&quot;)
            elif dir == &quot;V&quot;:
                #if vertical, row cannot be 0 or 7 at center or ship is out of bounds
                if row != 0 and row != 7:
                    #center of ship
                    board[row][column] = &quot;O&quot;
                    #front and back of ship
                    board[row - 1][column] = &quot;O&quot;
                    board[row + 1][column] = &quot;O&quot;
                    return board
                else: 
                    print(&quot;Can't place ship here, try again&quot;)
            else:
                print(&quot;Something went wrong&quot;)
</code></pre>
<p>Unit test:</p>
<pre><code>from unittest import mock
from unittest import TestCase
import unittest
from player import Player

class test_set_ship_coordinates(TestCase):
    @mock.patch(&quot;player.Player.set_ship_coordinates.input&quot;, create=True)
    def test_set_coordinates_correct(self, mocked_input):
        mocked_input.side_effect = [&quot;h&quot;, '2', 'c']
        result = Player.set_ship_coordinates()
        self.assertEqual(result, {'h', 1, 2})
        
if __name__ == &quot;__main__&quot;:
    unittest.main()
</code></pre>
",https://stackoverflow.com/questions/70431269/unit-testing-with-user-inputs-python,"['python', 'unit-testing']",171,False,3,0
How to mock RxJs BehaviorSubject or Observables for testing?,"<p>I've created a sample react hook which I want to test. The hooks imports an subject from another file and subscribe to it. On completion of that subject the internal state of the hook changes.</p>
<p>sampleBehaviourSubject.ts</p>
<pre><code>export const subject = new BehaviorSubject&lt;string&gt;(&quot;I'm just an example&quot;)
</code></pre>
<p>useSample.js</p>
<pre><code>const useSample(){

 const [state, setState] = useState(&quot;Nothing to show here&quot;)
 
 useEffect(()=&gt;{

    subject.subscribe({
      complete: () =&gt; setState(&quot;The subject is completed&quot;)
    }) 

 },[])

 return [state]
}
</code></pre>
<p>I'm new to unit testing but I know that external dependencies can be mocked/stubbed using sinon.js . But I'm not able to figure out how can I mock an Observable/Subject and test this <code>useSample</code> hook. It'll be great if someone shows an example with <strong>@testing-library/react-hooks</strong></p>
<p>Please note that this subject is subscribed at many other places hence I want to restore the mock/stub afterEach spec runs.</p>
",https://stackoverflow.com/questions/70343832/how-to-mock-rxjs-behaviorsubject-or-observables-for-testing,"['javascript', 'reactjs', 'typescript', 'rxjs', 'sinon']",622,False,3,0
react-i18next:: You will need to pass in an i18next instance by using initReactI18next warning thrown in Jest unit test,"<p>I am using <code>react-i18next</code> in my app to great effect but when I run the unit tests against my component:</p>
<pre><code>const OptionList = ({
  definition,
  name,
  status = EMutationStatus.IDLE,
  onChange = () =&gt; null,
  value = [],
}: IOptionListProps): React.ReactElement =&gt; {
  const { t } = useTranslation();
  const { options } = definition;
  return (
    &lt;Select
      name={name}
      data-testid=&quot;optionList&quot;
      id={name}
      placeholder={t('COMMON.PLEASE_SELECT')}
      onChange={e =&gt; onChange(e.currentTarget.value)}
      defaultValue={value[0]}
      disabled={status === EMutationStatus.LOADING}
    &gt;
      {options.map((option: string): React.ReactElement =&gt; {
        return (
          &lt;option key={option} value={option}&gt;
            {option}
          &lt;/option&gt;
        );
      })}
    &lt;/Select&gt;
  );
};
</code></pre>
<p>It throws the following <em><strong>warning</strong></em> when running the unit test suite:</p>
<p><code>react-i18next:: You will need to pass in an i18next instance by using initReactI18next</code></p>
<p>I am a bit lost as I have set up <code>react-i18next</code> for unit testing in a custom render function for <code>react-testing-library</code>.</p>
<p>My <code>i18n</code> instance for tests:</p>
<pre><code>import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

i18n.use(initReactI18next).init({
  lng: 'cimode', // setting lng to 'cimode' will cause the t function to always return the key.
  // ----- ^
  // have a common namespace used around the full app
  ns: ['translations'],
  defaultNS: 'translations',

  interpolation: {
    escapeValue: false, // not needed for react!!
  },

  resources: { en: { translations: {} }, zh: { translations: {} }, th: { translations: {} } },
});

export default i18n;
</code></pre>
<p>And my custom render function is as follows:</p>
<pre><code>export function render(
  ui: RenderUI,
  { wrapper, ...options }: RenderOptions = {}
): RenderResult {
  if (!wrapper) {
    // eslint-disable-next-line no-param-reassign
    wrapper = ({ children }) =&gt; (
      &lt;BrowserRouter&gt;
        &lt;ChakraProvider resetCSS theme={theme}&gt;
          &lt;QueryClientProvider client={testQueryClient}&gt;
            &lt;I18nextProvider i18n={i18n}&gt;{children}&lt;/I18nextProvider&gt;
          &lt;/QueryClientProvider&gt;
        &lt;/ChakraProvider&gt;
      &lt;/BrowserRouter&gt;
    );
  }

  return defaultRender(ui, { wrapper, ...options });
}
</code></pre>
<p>It is only a warning so not a big deal but am confused as to why this is throwing here as I believe I have set up the Provider as outlined in the docs here:</p>
<p><a href=""https://react.i18next.com/misc/testing"" rel=""noreferrer"">https://react.i18next.com/misc/testing</a></p>
<p>An anyone help me get rid of this warning?</p>
<h1>UPDATE</h1>
<p>I tried adding the suggested jest mock of the <code>useTranslation</code> hook from the same testing link:</p>
<pre><code>jest.mock('react-i18next', () =&gt; ({
  // this mock makes sure any components using the translate hook can use it without a warning being shown
  useTranslation: () =&gt; {
    return {
      t: (str: string): string =&gt; str,
    };
  },
}));
</code></pre>
<p>But still I get the same warning.</p>
",https://stackoverflow.com/questions/68770813/react-i18next-you-will-need-to-pass-in-an-i18next-instance-by-using-initreacti,"['reactjs', 'internationalization', 'i18next', 'react-i18next']",14670,True,17,6
Mock/stub data with Jest with models that have autoIncrement.MongooseAutoIncrementId.plugin business. Cannot read property &#39;Mongoose....&#39; of undefined,"<p>Hello I am trying to write some unit test and while I import some needed interface to implement the unit testing I keep run into this error &quot; Cannot read property 'MongoseAutoIncrementId' of undefined&quot;.
There is a model that its schema used the plugin</p>
<pre><code>Schema.plugin(autoIncrement.MongooseAutoIncrementID.plugin, { modelName: &quot;ModelName&quot;, field: &quot;UID&quot; });
</code></pre>
<p>I don't really need this model to implement the unit test, the model was from a package that was imported to my project so I cannot remove the auto increment business out either or change anything inside the model.</p>
<p>My question is how should I mock the data and model to be able to import, declare service or consumer object without getting the error?</p>
<p>Thank you</p>
",https://stackoverflow.com/questions/68434963/mock-stub-data-with-jest-with-models-that-have-autoincrement-mongooseautoincreme,"['javascript', 'unit-testing', 'jestjs', 'mongoose-schema', 'mongoose-auto-increment']",131,False,2,0
MS test does not improve code coverage in sonarqube,"<p>I am using .Net MVC with Web API project in Visual Studio 2015.</p>
<p>The project is configured with the SonarQube Version 8.7.</p>
<p>Currently the Code coverage percent is 0%.</p>
<p>Recently I have added a unit test project in my solution and added around 25+ test methods for my Web API Controllers.</p>
<p>All the test methods are passed. I am using MS Test for Unit testing.</p>
<p>On executing the SonarQube script I am not able to see any improvement in my Code coverage inspite of adding unit test cases.</p>
<p>Please guide me for what have been gone wrong resulting in 0 percent of Code coverage in SonarQube</p>
<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/69376722/ms-test-does-not-improve-code-coverage-in-sonarqube,"['asp.net-mvc', 'unit-testing', 'asp.net-web-api', 'sonarqube', 'mstest']",860,False,2,2
Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath &#39;./build/types&#39; is not defined by &quot;exports&quot; in .../node_modules/jest-circus/package.json,"<p>I'm trying to setup detox for e2e testing for my React Native app using jest and jest-circus. I am able to build my iOS app with detox by running <code>detox build --configuration ios</code> but have been unable to run the sample <code>firstTest.e2e.js</code> test with <code>detox run --configuration ios</code>. I get the following error:</p>
<pre><code>  ● Test suite failed to run

    Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './build/types' is not defined by &quot;exports&quot; in [project path]/node_modules/jest-circus/package.json

      at Object.&lt;anonymous&gt; (../node_modules/detox/runners/jest-circus/listeners/DetoxCoreListener.js:11:25)

detox[92379] ERROR: [cli.js] Command failed: jest --config e2e/config.json --testNamePattern '^((?!:android:).)*$' --maxWorkers 1 e2e
</code></pre>
<p>My package.json has the following libraries installed:</p>
<p><code>&quot;detox&quot;: &quot;^18.12.1&quot;,</code></p>
<p><code>&quot;jest&quot;: &quot;^24.9.0&quot;,</code></p>
<p><code>&quot;jest-circus&quot;: &quot;^27.1.0&quot;,</code></p>
<p>My .detoxrc.json file looks like this:</p>
<pre><code>{
  &quot;testRunner&quot;: &quot;jest&quot;,
  &quot;runnerConfig&quot;: &quot;e2e/config.json&quot;,
  &quot;apps&quot;: {
    &quot;ios&quot;: {
      &quot;type&quot;: &quot;ios.app&quot;,
      &quot;binaryPath&quot;: &quot;ios/build/Build/Products/Debug-iphonesimulator/appname.app&quot;,
      &quot;build&quot;: &quot;xcodebuild -workspace ios/appname.xcworkspace -scheme appname -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build EXCLUDED_ARCHS=arm64&quot;
    }
  },
  &quot;devices&quot;: {
    &quot;simulator&quot;: {
      &quot;type&quot;: &quot;ios.simulator&quot;,
      &quot;device&quot;: {
        &quot;type&quot;: &quot;iPhone 11&quot;
      }
    }
  },
  &quot;configurations&quot;: {
    &quot;ios&quot;: {
      &quot;device&quot;: &quot;simulator&quot;,
      &quot;app&quot;: &quot;ios&quot;
    }
  }
}
</code></pre>
<p>and my e2e/config.json file looks like this:</p>
<pre><code>{
    &quot;testEnvironment&quot;: &quot;./environment&quot;,
    &quot;testRunner&quot;: &quot;jest-circus/runner&quot;,
    &quot;testTimeout&quot;: 120000,
    &quot;testRegex&quot;: &quot;\\.e2e\\.js$&quot;,
    &quot;reporters&quot;: [&quot;detox/runners/jest/streamlineReporter&quot;],
    &quot;verbose&quot;: true
}
</code></pre>
<p>This is a fairly old project, and I am already using jest for unit testing. I wonder if there might be some other configuration file interfering with my e2e config but can't seem to figure it out just yet. Any help is welcome!</p>
",https://stackoverflow.com/questions/68991102/error-err-package-path-not-exported-package-subpath-build-types-is-not-de,"['react-native', 'jestjs', 'detox', 'jest-circus']",509,False,1,1
Is it possible to get code coverage with karate tests for java code?,"<p>I'm trying to get test code coverage for java code using the karate test cases. I know Junit is the best approach for unit testing and code coverage but I need to do this specifically because I want to test the java code and get coverage through karate test cases. I am able to run the karate test case and get the cucumber HTML report and coverage report(provided by jacoco plugin) but karate test case coverage is not shown. I need to know if this is possible or not and if it is possible then what changes/additions do I need to make.</p>
<p>Karate feature file code</p>
<pre><code>Feature: Test ElasticUtilsProperties
 
      Background:
        * def ElasticUtilsProperties = Java.type('com.staff.util.ElasticUtilsProperties')
        * def elasticProps = new ElasticUtilsProperties()
        
      Scenario: Get Host
          Given elasticProps.setHost(&quot;host-1&quot;)
           When def host = elasticProps.getHost()
           Then print 'host--&gt;', host
        
      Scenario: Get Port
          Given elasticProps.setPort(&quot;host-1&quot;)
           When def port = elasticProps.getPort()
           Then print 'port--&gt;', port
      
      Scenario: Get Scheme
          Given elasticProps.setScheme(&quot;scheme&quot;)
           When def scheme = elasticProps.getScheme()
           Then print 'scheme--&gt;', scheme
      
      Scenario: Get trustStorePath
          Given elasticProps.setTrustStorePath(&quot;trustStorePath&quot;)
           When def trustStorePath = elasticProps.getTrustStorePath()
           Then print 'trustStorePath--&gt;', trustStorePath
      
      Scenario: Get trustStorePass
          Given elasticProps.setTrustStorePass(&quot;trustStorePass&quot;)
           When def trustStorePass = elasticProps.getTrustStorePass()
           Then print 'trustStorePass--&gt;', trustStorePass
      
      Scenario: Get pathPrefix
          Given elasticProps.setPathPrefix(&quot;PathPrefix&quot;)
           When def pathPrefix = elasticProps.getPathPrefix()
           Then print 'pathPrefix--&gt;', pathPrefix
      
      Scenario: Get index
          Given elasticProps.setIndex(&quot;Index&quot;)
           When def index = elasticProps.getIndex()
           Then print 'Index--&gt;', index
      
      Scenario: Get RestHighLevelClient
          Given elasticProps.setHost(&quot;host-1&quot;)
           When def host = elasticProps.getHost()
           Then print 'host--&gt;', host
</code></pre>
<p>Java file code</p>
<pre><code>import org.elasticsearch.client.RestHighLevelClient;

public class ElasticUtilsProperties {
private String host;
private int port;
private String scheme;
private String trustStorePath;
private String trustStorePass;
private String pathPrefix;
private String index;
private RestHighLevelClient restHighLevelClient;

public String getHost() {
    return host;
}

public void setHost(String host) {
    this.host = host;
}

public int getPort() {
    return port;
}

public void setPort(int port) {
    this.port = port;
}

public String getScheme() {
    return scheme;
}

public void setScheme(String scheme) {
    this.scheme = scheme;
}

public String getTrustStorePath() {
    return trustStorePath;
}

public void setTrustStorePath(String trustStorePath) {
    this.trustStorePath = trustStorePath;
}

public String getTrustStorePass() {
    return trustStorePass;
}

public void setTrustStorePass(String trustStorePass) {
    this.trustStorePass = trustStorePass;
}

public String getPathPrefix() {
    return pathPrefix;
}

public void setPathPrefix(String pathPrefix) {
    this.pathPrefix = pathPrefix;
}

public String getIndex() {
    return index;
}

public void setIndex(String index) {
    this.index = index;
}

public RestHighLevelClient getRestHighLevelClient() {
    return restHighLevelClient;
}

public void setRestHighLevelClient(RestHighLevelClient restHighLevelClient) {
    this.restHighLevelClient = restHighLevelClient;
}
}
</code></pre>
",https://stackoverflow.com/questions/69297222/is-it-possible-to-get-code-coverage-with-karate-tests-for-java-code,"['java', 'unit-testing', 'code-coverage', 'karate']",1964,True,1,1
Building Qt-test with Cmake and Ctest,"<p>I recently started exploring unit-testing with QT library, so I just want to repeat simple code from its <a href=""https://doc.qt.io/qt-5/qtest-overview.html#building-with-cmake-and-ctest"" rel=""nofollow noreferrer"">documentation</a> and build it by Cmake (I have msvc compiler and use CLion IDE).</p>
<p>Cmake:</p>
<pre><code>cmake_minimum_required(VERSION 3.17)
project(unit_tests)
find_package(Qt5Test REQUIRED)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

set(CMAKE_AUTOMOC ON)

enable_testing(true)

add_executable(mytest tst_mytest.cpp)
add_test(mytest mytest)

target_link_libraries(mytest PRIVATE Qt5::Test)
</code></pre>
<p>tst_mytest.cpp:</p>
<pre><code>#include &lt;QObject&gt;
#include &lt;QtTest/QTest&gt;
class MyFirstTest: public QObject
{
    Q_OBJECT

private:
    bool myCondition()
    {
        return true;
    }

private slots:
    void initTestCase()
    {
        qDebug(&quot;Called before everything else.&quot;);
    }

    void myFirstTest()
    {
        QVERIFY(true);
        QCOMPARE(1, 1);
    }

    void mySecondTest()
    {
        QVERIFY(myCondition());
        QVERIFY(1 != 2);
    }

    void cleanupTestCase()
    {
        qDebug(&quot;Called after myFirstTest and mySecondTest.&quot;);
    }
};
QTEST_MAIN(MyFirstTest)
#include &quot;tst_mytest.moc&quot;
</code></pre>
<p>Then, I run All CTest and this test fails with error:</p>
<pre><code>&quot;F:\CLion 2020.3.1\bin\cmake\win\bin\ctest.exe&quot; --extra-verbose
Testing started at 16:07 ...
UpdateCTestConfiguration  from :C:/Users/nikolya/CLionProjects/untitled13/cmake-build-debug/DartConfiguration.tcl
UpdateCTestConfiguration  from :C:/Users/nikolya/CLionProjects/untitled13/cmake-build-debug/DartConfiguration.tcl
Test project C:/Users/nikolya/CLionProjects/untitled13/cmake-build-debug
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

1: Test command: C:\Users\nikolya\CLionProjects\untitled13\cmake-build-debug\foo.exe
1: Test timeout computed to be: 10000000

Terminated with exit code: 0xc0000135

Exception:


Errors while running CTest
0% tests passed, 1 tests failed out of 1

Total Test time (real) =   0.02 sec

The following tests FAILED:
      1 - foo (Exit code 0xc0000135
)
Process finished with exit code 8
</code></pre>
<p>For some reason the test is not appropriate for fixture requirements.
I had a look for some other <a href=""https://coderoad.ru/4753845/%D0%A1%D0%B1%D0%BE%D1%80%D0%BA%D0%B0-Qt-%D1%82%D0%B5%D1%81%D1%82%D0%BE%D0%B2-%D1%81-CMake"" rel=""nofollow noreferrer"">Qt-questions</a> and <a href=""https://stackoverflow.com/questions/4643179/running-qt-unit-tests"">here</a> about structure of unit-tests, but didn`t see a lot of differences with my code. <a href=""https://i.stack.imgur.com/q9Smx.png"" rel=""nofollow noreferrer"">Here are Cmake options</a>. After adding Qt directory to Path environment variable there is a linking error:</p>
<pre><code>CMake Error at CMakeLists.txt:2 (project):
  The CMAKE_C_COMPILER:

    cl

  is not a full path and was not found in the PATH.

  To use the NMake generator with Visual C++, cmake must be run from a shell
  that can use the compiler cl from the command line.  This environment is
  unable to invoke the cl compiler.  To fix this problem, run cmake from the
  Visual Studio Command Prompt (vcvarsall.bat).

  Tell CMake where to find the compiler by setting either the environment
  variable &quot;CC&quot; or the CMake cache entry CMAKE_C_COMPILER to the full path to
  the compiler, or to the compiler name if it is in the PATH.


CMake Error at CMakeLists.txt:2 (project):
  The CMAKE_CXX_COMPILER:

    cl

  is not a full path and was not found in the PATH.

  To use the NMake generator with Visual C++, cmake must be run from a shell
  that can use the compiler cl from the command line.  This environment is
  unable to invoke the cl compiler.  To fix this problem, run cmake from the
  Visual Studio Command Prompt (vcvarsall.bat).

  Tell CMake where to find the compiler by setting either the environment
  variable &quot;CXX&quot; or the CMake cache entry CMAKE_CXX_COMPILER to the full path
  to the compiler, or to the compiler name if it is in the PATH.
</code></pre>
<p>What is going wrong here?</p>
",https://stackoverflow.com/questions/67403649/building-qt-test-with-cmake-and-ctest,"['c++', 'qt', 'unit-testing', 'cmake', 'ctest']",909,False,1,0
How to test with jest &amp; enzyme and simulate option select?,"<p>I have wrote some react code and render a form, and the form doesn't have a dropdown, instead it displays all 3 options available for selecting with no default option.</p>
<p>I am wondering how can I test and simulate the change of option in jest using enzyme?</p>
<p>Below is a snippet of the code and the unit test that I have</p>
<pre><code>import { ReactDOM } from &quot;react&quot;;

enum SomeCategory {
  NONE = 0,
  A = 1,
  B = 2,
  C = 3
}

class ReportBase extends React.Component&lt;{}, {}}&gt; {
  constructor() {
    category = SomeCategory.NONE;
  }

  render() {
    return ReactDOM.div(
      {
        key: 'some-random-key', className: 'random-class-name',
      },
      [
        React.createElement(
        'select',
        {
          size: 3,
          className: 'category',
          onChange: (e: React.SyntheticEvent&lt;HTMLSelectElement&gt;) =&gt; {
            this.category = parseInt(e.currentTarget.value, 10);
          },
        },
        React.createElement(
          'option',
          {value: SomeCategory.A},
          'AAA'
        ),
        React.createElement(
          'option',
          {value: SomeCategory.B},
          'BBB'
        ),
        React.createElement(
          'option',
          {value: SomeCategory.C},
          'CCC'
        )
      )
      ]
    );

const ReportForm = requireCssWithComponent(ReportBase, [
  '/static/css/some.css',
]);

export {ReportForm};

</code></pre>
<p>Below is my jest unit testing code</p>
<pre><code>
describe('ReportForm', () =&gt; {
  it('can select selection category', () =&gt; {
    spyOn(Browser, 'get_href').and.returnValue(url);
    let form = enzyme.mount(&lt;ReportForm /&gt;);
    let react_form = form.instance().getWrappedComponent();

    form.find(`.category option[value=${SomeCategory.A}]`).simulate('click');
    expect(react_form.category).toBe(SomeCategory.A);
    form.find(`.category option[value=${SomeCategory.B}]`).simulate('click');
    expect(react_form.category).toBe(SomeCategory.B);
  });
});
</code></pre>
<p>But this failed as the expected value is different.</p>
<p>I believe the issue is due to the fact that onClick event doesn't work with select option, but how would I manually trigger an onChange event in jest?</p>
<p>Thanks for any help</p>
",https://stackoverflow.com/questions/68705529/how-to-test-with-jest-enzyme-and-simulate-option-select,"['reactjs', 'jestjs', 'enzyme']",652,False,1,0
Sinon.JS mocking confusion,"<p>I'm trying to learn how to do JS unit testing using Sinon, Mocha, and Chai. Right now, I want to confirm that one of my functions actually makes an api request (so I need to mock my function). I believe that I've found relevant mocking code in the Sinon docs (it's code for testing Ajax), however, I can't make any sense of what's going on (the documentation is very sparse). Can anyone explain each of the 3 lines of code in the it function (directly below)?</p>
<pre><code>it(&quot;makes a GET request for todo items&quot;, function () {
  sinon.replace(jQuery, &quot;ajax&quot;, sinon.fake());

  getTodos(42, sinon.fake());

  assert(jQuery.ajax.calledWithMatch({ url: &quot;/todo/42/items&quot; }));
</code></pre>
<p>For reference, the function being mocked is directly below:</p>
<pre><code>function getTodos(listId, callback) {
  jQuery.ajax({
    url: &quot;/todo/&quot; + listId + &quot;/items&quot;,
    success: function (data) {
      // Node-style CPS: callback(err, data)
      callback(null, data);
    },
  });
}
</code></pre>
<p>Also, here is a link to the documentation:
<a href=""https://sinonjs.org/"" rel=""nofollow noreferrer"">https://sinonjs.org/</a></p>
",https://stackoverflow.com/questions/66926144/sinon-js-mocking-confusion,"['jquery', 'mocking', 'mocha.js', 'chai', 'sinon']",229,True,1,1
verify react functional component to be there,"<p>I'm new to react unit testing, here I have react code which works fine but need to unit test it.
I want to verify the component to be there, I have tried in two different ways and both of them does not work:
I'm using <code>useSelector</code> and <code>useDispatch</code> thats why <code>connect(null,null)</code>.</p>
<p>my code:</p>
<p>M2SelectionCard.js:</p>
<pre><code>function ConnectedSelectionCard({ classes }) {
  

  return (
    &lt;Card data-testid=&quot;M2SelectionCardd&quot; className={classes.selectionCard}&gt;
      &lt;CardContent&gt;
        
      &lt;/CardContent&gt;
    &lt;/Card&gt;
  );
}

const M2SelectionCard = connect(null, null)(ConnectedSelectionCard);

export default M2SelectionCard;
</code></pre>
<p>first I did like this:</p>
<pre><code>import React from &quot;react&quot;;

import { expect } from &quot;@jest/globals&quot;;
import { render, screen, cleanup } from &quot;@testing-library/react&quot;;
import M2SelectionCard from &quot;../M2SelectionCard&quot;;

test(&quot;test&quot;, () =&gt; {
  render(&lt;M2SelectionCard /&gt;);
  const SelectionCardElement = screen.getByTestId(&quot;M2SelectionCardd&quot;);
  expect(SelectionCardElement).toBeInTheDocument();
  // expect(true).toBe(true);
});
</code></pre>
<p>and got error : <code>Could not find &quot;store&quot; in the context of &quot;Connect(ConnectedSelectionCard)&quot;</code>. Either wrap the root component in a <code>&lt;Provider&gt;</code>, or pass a custom React context provider to <code>&lt;Provider&gt;</code> and the corresponding React context consumer to <code>Connect(ConnectedSelectionCard)</code> in connect options.'</p>
<pre><code>import React from &quot;react&quot;;
import { expect } from &quot;@jest/globals&quot;;
import { render, screen, cleanup } from &quot;@testing-library/react&quot;;
import M2SelectionCard from &quot;../M2SelectionCard&quot;;
import { Provider } from &quot;react-redux&quot;;
import configureStore from &quot;../../redux/store&quot;;

const store = configureStore({});

it(&quot;test&quot;, () =&gt; {
  render(
    &lt;Provider store={store}&gt;
      &lt;M2SelectionCard /&gt;
    &lt;/Provider&gt;
  );
  const SelectionCardElement = screen.getByTestId(&quot;M2SelectionCardd&quot;);
  expect(SelectionCardElement).toBeInTheDocument();
});
</code></pre>
<p>after that I added store to it in test (don't know should I add it here ?):
error message:
<code>TypeError: Cannot read property 'selectionCard' of undefined</code>
it points to <code>className={classes.selectionCard}</code>
any idea ?</p>
",https://stackoverflow.com/questions/69094372/verify-react-functional-component-to-be-there,"['javascript', 'reactjs', 'unit-testing', 'testing', 'react-testing-library']",149,True,1,1
How to mock external dependency in typescript using jest,"<p>I am hopelessly trying to mock firebase admin dependency in typescript for unit testing.</p>
<p>My actual function is as below</p>
<pre><code>import {auth} from 'firebase-admin';

async validateUser(payload: string): Promise&lt;User&gt; {
  try {
    const resp = await auth().verifyIdToken(payload, true);

    return await this.userService.findByUsername(resp.email);
  } catch (e) {
    return null;
 }
}
</code></pre>
<p>I am trying to test the <code>admin.auth().verifyIdToken(payload, true)</code> by mocking the <code>admin</code> function. I attempted the test code like below</p>
<pre><code>import {auth} from 'firebase-admin';

jest.mock('firebase-admin');

const mockedAuth = auth as jest.Mock;

mockedAuth.mockReturnValue({
  verifyIdToken: jest.fn().mockResolvedValue(true),
});
</code></pre>
<p>but I get an error saying <code>TypeError: Cannot read property 'mockReturnValue' of undefined</code></p>
<p>if I am understanding correctly, I am mocking the entire <code>firebase-admin</code> package by calling <code>jest.mock('firebase-admin')</code>. So I would expect to be able to call <code>mockReturnValue</code> and again mock the <code>verifyIdToken</code> function within the auth function. However, I am not even able to call <code>mockReturnValue</code> because weirdly it doesn't seem to exist.</p>
<p>How do I need to write a code so that I can mock the resolved value from <code>auth().verifyIdToken()</code> ?</p>
",https://stackoverflow.com/questions/67748989/how-to-mock-external-dependency-in-typescript-using-jest,"['typescript', 'unit-testing', 'jestjs']",4385,True,1,2
"testEnv.firestore.makeDocumentSnapshot(data, path) is not creating a new document","<p>Setting up unit testing firebase functions (online mode).</p>
<p>I'm testing an onCreate() function, so I need to create a document in firestore to ensure the function is triggered and working properly. The problem I'm encountering is that <code>testEnv.firestore.makeDocumentSnapshot(data, path)</code> is not creating a new document. If the document already exists, I can write this data to it and trigger the onCreate() function, but if it doesn't exist I get an <code>Error: 5 NOT_FOUND: No document to update</code> when I run the test.</p>
<p>test.ts</p>
<pre><code>const functions = require(&quot;firebase-functions-test&quot;);

const testEnv = functions({
  databaseURL: &quot;https://***.firebaseio.com&quot;,
  storageBucket: &quot;***.appspot.com&quot;,
  projectId: &quot;***&quot;,
}, &quot;./test-service-account.json&quot;);

import &quot;jest&quot;;
import * as admin from &quot;firebase-admin&quot;;


import { makeLowerCase } from &quot;../src&quot;;

describe(&quot;makes bio lower case&quot;, () =&gt; {
  let wrapped: any;
  beforeAll(() =&gt; {
    wrapped = testEnv.wrap(makeLowerCase);
  });

  test(&quot;it converts the bio to lowercase&quot;, async () =&gt; {

    const path = &quot;/animals/giraffe&quot;;
    const data = {bio: &quot;GIRAFFE&quot;};

    const snap = testEnv.firestore.makeDocumentSnapshot(data, path);

    await wrapped(snap)

    const after = await admin.firestore().doc(path).get();

    expect(after?.data()?.bio).toBe(&quot;giraffe&quot;);

  });
});
</code></pre>
<p>makeLowerCase.ts</p>
<pre><code>import * as functions from &quot;firebase-functions&quot;;
import * as admin from &quot;firebase-admin&quot;;

export const makeLowerCase = functions.firestore
  .document(&quot;animals/{animalId}&quot;)
  .onCreate((snap, context) =&gt; {
    const data = snap.data();
    const bio = data.bio.toLowerCase();

    return admin.firestore().doc(`animals/${snap.id}`).update({bio});
  });
</code></pre>
<p>I can fix this in <code>makeLowerCase.ts</code> by returning:</p>
<pre><code>admin.firestore().doc(`animals/${snap.id}`).set({bio}, {merge: true});
</code></pre>
<p>Or by creating the doc with admin in the test:</p>
<pre><code>await admin.firestore().doc(path).set(data);
</code></pre>
<p>But the <code>testEnv.firestore.makeDocumentSnapshot(data, path);</code> should be creating a document I think, no?</p>
<p>Is this is bug or expected behaviour from <code>firebase-functions-test&quot;</code>?</p>
",https://stackoverflow.com/questions/69984257/testenv-firestore-makedocumentsnapshotdata-path-is-not-creating-a-new-documen,"['javascript', 'firebase', 'unit-testing', 'google-cloud-firestore', 'google-cloud-functions']",296,True,1,1
Angular - Long Polling with Observables - Unit Testing,"<p>I'm quite new to unit testing observables, so far I found out that there are two ways of testing them either by using the subscribe and assert pattern or by using marble testing.</p>
<p>I do now have a task at hand where I need some sort of long polling implementation. The implementation is working fine, but writing the according unit test is a pain.</p>
<p>Here is the code I have so far:</p>
<p>long-polling.service.ts</p>
<pre class=""lang-js prettyprint-override""><code>// ...
/**
* Starts polling a long polling endpoint. Pass in any kind of observable stream
* to the method and eg. from the httpClient.get(). You can also configure a maximum
* number of retries in case the server might fail and the retry interval in ms.
* @param observableToPoll$
* @param maxRetrys
* @param retryIntervalOnError
*/
startPolling&lt;T&gt;(
  observableToPoll$: Observable&lt;T&gt;,
  maxRetrys: number = Infinity,
  retryIntervalOnError = 5000
): Observable&lt;T&gt; {
  if (this.poll$) {
    return this.poll$;
  }

  this.poll$ = observableToPoll$.pipe(
    longPollUntil(this.stopPolling$, maxRetrys, retryIntervalOnError)
  );

  return this.poll$;
}
//...
</code></pre>
<p>util.ts</p>
<pre class=""lang-js prettyprint-override""><code>export function longPollUntil&lt;T&gt;(
  isPollingActive: IsActiveCallback | Observable&lt;any&gt;,
  maxRetrys = Infinity,
  retryInterval = 5000
): MonoTypeOperatorFunction&lt;T&gt; {
  return (source$) =&gt; {
    const poll$ = source$.pipe(
      repeat(),
      retryWhen((errors) =&gt;
        errors.pipe(
          concatMap((e, i) =&gt;
            iif(
              () =&gt; i &gt;= maxRetrys,
              throwError(e),
              of(e).pipe(delay(retryInterval))
            )
          )
        )
      ),
      share()
    );

    if (isObservable(isPollingActive)) {
      return poll$.pipe(takeUntil(isPollingActive));
    }

    return poll$.pipe(takeWhile(isPollingActive as (res: T) =&gt; boolean, true));
  };
}
</code></pre>
<p>long-polling.service.spec.ts</p>
<pre class=""lang-js prettyprint-override""><code>// ...
it('should start polling and repeat after stream ends', fakeAsync((done) =&gt; {
  const httpClient = TestBed.inject(HttpClient);


  const polling = service.startPolling(
    httpClient.get('/sometest/test.json').pipe(
      // observeOn(scheduler),
      tap(() =&gt; {
        console.log('request fired');
      })
    )
  );
  let callCount = 0;
  polling.subscribe((data: any) =&gt; {
    if (callCount === 0) {
      expect(data.someMessage).toBe('Test message');
    } else {
      expect(data.someMessage).toBe('Another message');
    }

    callCount++;

    if (callCount &gt; 2) {
      done();
    }
  }, done.fail);
  const req = httpMock.match('/sometest/test.json');
  expect(req[0].request.method).toBe('GET');

  scheduler.flush();

  req[0].flush({
    someMessage: 'Test message',
  });
  scheduler.flush();

  //tick(70000);
  req[1].flush({
    someMessage: 'Another message',
  });
}));
// ...
</code></pre>
<p>As you can see I tried several approaches already. But the request is only fired once and does not repeat like it should do.</p>
<p>Does anyone have a clue how to test this?</p>
",https://stackoverflow.com/questions/67583101/angular-long-polling-with-observables-unit-testing,"['angular', 'typescript', 'unit-testing', 'rxjs']",269,False,1,0
fake/mock nonvirtual C++ methods without changing the production code on Visual Studio platform,"<p>I am unit testing a c++ class and using Google Test and Google Mock frameworks.</p>
<p>For example,
I have a class which has non-virtual functions and I want to mock these two functions which have external dependencies.
I don't want to change my class <code>A</code> (using gmock template way solution and dependency injection). Below can be two solutions probably:</p>
<ol>
<li>Simply mock on fly or any other option like we have in Python where we create <code>MagicMock()</code> and patch.</li>
<li>derive non-virtual class from the test class and wrap the non-virtual
function by making it virtual in the test class, then call the prod non-virtual function.</li>
</ol>
<pre class=""lang-cpp prettyprint-override""><code>class A 
{
  public:
          bool DBConnect(string username);
  private:
          bool someWork(int);
};
</code></pre>
",https://stackoverflow.com/questions/66189297/fake-mock-nonvirtual-c-methods-without-changing-the-production-code-on-visual,"['c++', 'unit-testing', 'mocking', 'googletest', 'googlemock']",235,False,1,1
Vue Cypress code coverage report with python tests,"<p>I have Python tests with Selenium to test my Vue webpage. I would like to get code coverage results for those tests. I have installed babel-plugin-istanbul to instrument the application, and it works. I have <code>window.__coverage__</code> object, which contains the coverage information.</p>
<p>My question is, how can I get coverage reports if I run the tests using Python, not Cypress's testing framework. I have installed cypress/code-coverage, but I don't know how to generate the reports without using Cypress' unit testing framework.</p>
<p>Also, If there is another coverage report framework for Vue, which is more suitable for my use case, I am open to suggestions.</p>
",https://stackoverflow.com/questions/67331809/vue-cypress-code-coverage-report-with-python-tests,"['python', 'vue.js', 'testing', 'cypress', 'istanbul']",291,True,1,1
NullReferenceException when mock my handler database,"<p>I'm trying to do unit testing to my handler database but I got a nullReferenceException when I call my methods.</p>
<p>This is my handler constructor</p>
<pre class=""lang-cs prettyprint-override""><code>public SignalsHandler(IConfiguration configuration, IDbConnection connection)
{
    _dbConnection = connection;
    _settings = configuration.GetSection(&quot;SigSettings&quot;).Get&lt;SigSettings&gt;();
    if (_settings == null)
        _settings = new SigSettings();
}
</code></pre>
<p>And what I do is to Mock that with this on my testing class:</p>
<pre class=""lang-cs prettyprint-override""><code>private Mock&lt;IConfigurationSection&gt; _configSectionMock = new Mock&lt;IConfigurationSection&gt;();
private Mock&lt;IConfiguration&gt; _configMock = new Mock&lt;IConfiguration&gt;();
private Mock&lt;IDbConnection&gt; _connection = new Mock&lt;IDbConnection&gt;();
private readonly SignalsHandler _handler;

public SignalsTest()
{
    _configMock.Setup(x =&gt; x.GetSection(It.IsAny&lt;string&gt;())).Returns(_configSectionMock.Object);
    _handler = new SignalsHandler(_configMock.Object, _connection.Object);
}
</code></pre>
<p>So far so good but when I try to implement some testing it doesn't work. For example, a simple test:</p>
<pre class=""lang-cs prettyprint-override""><code>public void CanGetAllSignals()
{
    var result = _handler.GetSignals();
    Assert.IsNotNull(result);
}
</code></pre>
<p>I call my <code>.GetSignals()</code> method with my Mock handler. This is the code:</p>
<pre class=""lang-cs prettyprint-override""><code>public async Task&lt;List&lt;SignalsDTO&gt;&gt; GetSignals()
{
    var res = new List&lt;SignalsDTO&gt;();
    var sigList = await _dbConnection.QueryAsync&lt;SigSignal&gt;(_settings.Signals);
    foreach (var s in sigList)
        res.Add(new SignalsDTO()
        {
            IDTag = s.IDTag,
            Name = s.Name
        });
    return res;
}
</code></pre>
<p>But when I debug my testing method I got:<br />
<code>NullReferenceException:'Object reference not set to an instance of an object.'</code><br />
at this line:</p>
<pre class=""lang-cs prettyprint-override""><code>var sigList = await _dbConnection.QueryAsync&lt;SigSignal&gt;(_settings.Signals);
</code></pre>
<p>I suppose this is an error with my mock configuration at my test constructor but I'm not sure about how can I fix this.</p>
",https://stackoverflow.com/questions/69721801/nullreferenceexception-when-mock-my-handler-database,"['c#', 'unit-testing', 'mstest']",613,True,1,1
Adding GitLab hooks to catch Merge Requests that lack unit tests,"<p>I’ve been tasked with investigating whether something can be added to our MR approval process to highlight whether proposed Merge Requests (MRs) in GitLab, which are C++ based code, contain any new unit tests or modifications to existing tests. The overall aim is to remind developers and approvers that they need to consider unit testing.</p>
<p>Ideally a small script would run and detect the presence of additional tests or changes (this I can easily write, and I accept that there’s a limit to how much can be done here) and display a warning on the MR if they weren’t detected.</p>
<p>An addition step, if at all possible, would be to block the MR until either, further commits were pushed that meet the criteria, or an (extra/custom) GitLab MR field is completed explaining why unit testing is not appropriate for this change. This field would be held with the MR for audit purposes. I accept that this is not foolproof but am hoping to pilot this as part of a bigger push for more unit test coverage.</p>
<p>As mentioned, I can easily write a script in, say, Python to check for unit tests in the commit(s), but what I don’t know is whether/how I can hook this into the GitLab MR process (I looked at web-hooks but they seem to focus on notifying other systems rather than being transactional) and whether GitLab is extensible enough for us to achieve the additional step above. Any thoughts? Can this be done, and if so, how would I go about it?</p>
",https://stackoverflow.com/questions/68081610/adding-gitlab-hooks-to-catch-merge-requests-that-lack-unit-tests,"['gitlab', 'hook', 'gitlab-api', 'merge-request']",778,True,1,2
Using Jest.js to test Adobe ExtendScript,"<p>I want to do unit testing with my Adobe JSX files using Jest.</p>
<p>However, all Jest tutorials have some package.json which I don't use, and they use modules and requires which aren't in ES3 javascript, etc.</p>
<p>Plus 'JSX' has been appropriated by React, so it's also probably going to think I'm doing React files and not Adobe ES3 files.</p>
<p>Is there some way to use Jest and not bother with any modules and packages? I just want to test some ancient-style ES3 code that's just javascript.
If JSX extension is going to muddle things up, is there a way to do this with a single JS file?</p>
",https://stackoverflow.com/questions/65542383/using-jest-js-to-test-adobe-extendscript,['jestjs'],75,False,-1,1
Why does using importlib.util break type comparisons?,"<p>I have a module (<code>some_module</code>) with a file (<code>somefile</code>), containing an object I want to instantiate (<code>foo</code>).</p>
<pre><code>from collections import namedtuple

foo = namedtuple('Foo', ['a', 'b'])
</code></pre>
<p>In certain situations I only know the path to this file so have been importing <a href=""https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path"">like so</a>:</p>
<pre><code>import importlib.util as iu

spec = iu.spec_from_file_location(&quot;some_module.somefile&quot;, 'path/to/some_module/somefile.py')
mod = iu.module_from_spec(spec)
spec.loader.exec_module(mod)

var1 = mod.foo(1 ,2)
</code></pre>
<p>This worked fine at first but in my unit testing I discovered that <code>type(var)</code> was not equal to the type of the original ie:</p>
<pre><code>from some_module.somefile import foo

var2 = foo(1, 2)

print(type(var1) is type(var2))
print(isinstance(var1, var2.__class__)
</code></pre>
<p>Prints only <code>False</code>'s, despite the fact that it appears that both <code>var1</code> &amp; <code>var2</code> are functionally equivalent.</p>
<p>EDIT:
I'm using python 3.9.5 and in my test code, the construction functions for <code>var1</code> &amp; <code>var2</code> are in separate .py files, they get imported into a unit test which tries to check if both the objects are the same.</p>
",https://stackoverflow.com/questions/68471480/why-does-using-importlib-util-break-type-comparisons,['python'],28,False,0,0
AVPlayerItem Status Observer - Unit Test Status Changes,"<p>Does anyone have any references on unit testing key value observing logic in swift? I'd like to mock the AVPlayerItem's status changes in my unit tests to confirm that the expected logic is triggered. For simplicity this is what I have so far:</p>
<p>A function that observes the provided playerItem's status</p>
<pre><code>public func observePlayerItemStatus(playerItemToObserve: AVPlayerItem) -&gt; NSKeyValueObservation {
    let observerToken = playerItemToObserve.observe(\.status, options: [.new, .old], changeHandler: { (playerItemToObserve, _) in
        switch playerItemToObserve.status {
        case .failed:
            // failed logic
        case .readyToPlay:
            // ready to play logic
        default:
            // default logic
        }
    })

    return observerToken
}
</code></pre>
<p>I've created a mock class, MockAVPlayerItem</p>
<pre><code>class MockAVPlayerItem: AVPlayerItem {
    var mockStatus: AVPlayerItem.Status = .unknown
    public override var status: AVPlayerItem.Status {
        get { return mockStatus }
        set { self.mockStatus = newValue }
    }
}
</code></pre>
<p>My unit test attempting to trigger the status code change does the following:</p>
<pre><code>func test_readyToPlayIsTriggered() {
   let url = URL(string: &quot;https://www.rmp-streaming.com/media/big-buck-bunny-360p.mp4&quot;)!
   let mockPlayerItem = MockPlayerItem(url: url)
   let statusToken = observePlayerItemStatus(playerItemToObserve: mockPlayerItem)
   mockPlayerItem.status = .readyToPlay

... some assertion that ready to play was called ....
}
</code></pre>
<p>The logic itself works when I run the application however my unit tests are unable to trigger my observer. I've followed a similar approach to mock <code>AVPlayer.timeControlStatus</code> and it's worked great but for some reason <code>AVPlayerItem.status</code> isn't behaving the same.</p>
",https://stackoverflow.com/questions/67595300/avplayeritem-status-observer-unit-test-status-changes,"['swift', 'unit-testing']",267,True,0,1
Cypress Testing Library as open source,"<p>I should be starting testing react soon, I am more focused on integration and e2e testing as unit testing will be done by developers. However we would like to respect some homogeneity in our react testing tool-kit. I am only interested into open source tools. I know that cypress is a good candidate for e2e testing however it's not open source. My question is is it possible to use cypress as a testing library instead : <a href=""https://testing-library.com/docs/cypress-testing-library/intro"" rel=""nofollow noreferrer"">https://testing-library.com/docs/cypress-testing-library/intro</a> and will it have any limitation compared to using cypress? Which runner would you recommend and will i need to bundle any other tool with the library?</p>
",https://stackoverflow.com/questions/67466934/cypress-testing-library-as-open-source,"['reactjs', 'cypress', 'e2e-testing']",97,True,-2,1
Why does Android Studio compile my whole app to launch a primitive unit test?,"<p>Whenever I launch a unit test &quot;from the margin menu&quot; (see screenshot), that does not have any Android dependencies, Android Studio compiles my whole app only to run one primitive assert.</p>
<p>Is it the intended behaviour that my app needs to fully compile? I was expecting that unit tests are extremely fast and compile only those classes mentioned in the test and their dependent classes are to be compiled for unit testing.</p>
<p><a href=""https://i.stack.imgur.com/2OHSU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2OHSU.png"" alt=""run a test from margin menu"" /></a></p>
<p>Moreover, if I add any Android class, e.g. <code>Application</code> or <code>AppCompatActivity</code>, to the test it will still complete successfully. Every article about testing on Android says that it's impossible to run a unit test that depends on any Android library.</p>
",https://stackoverflow.com/questions/69556562/why-does-android-studio-compile-my-whole-app-to-launch-a-primitive-unit-test,"['android', 'android-studio', 'unit-testing', 'gradle', 'junit']",290,True,0,1
How can I require a generated file in my SConscript?,"<p>I'm working on adding googletest unit testing to a large project.</p>
<p>We have a top level SConstruct, which calls SConscripts for each of the git submodules, which may further call other SConstructs contained in each component.</p>
<p>One of these SConscripts will build the googletest framework, which will create the 'gtest.h' file among others. I need to include 'gtest.h' in my source file (test1.cpp) which is in a different repo that has it's own SConscript.</p>
<p>How can I require the gtest.h in test SConscript file before test1.cpp consumes it?</p>
<p>Imagine something like:</p>
<p>Top level SConstruct:</p>
<pre><code>env.SConscript('{path to Gtest}/SConscript')
env.SConscript('{path to my unit test}/SConscript')
</code></pre>
<p>SConscript for building Gtest:</p>
<pre><code>env2 = env.Clone()
def buildGtest(target, source, env):
  #Assuming I have a CMake file that does this in the directory...
  subprocess.run(['cmake', '../'], cwd='build/')
  subprocess.run(['make'], cwd='build/')
  
env2.Command(['gtest.h', 'build/libgtest.a', 'build/libgtest_main.a'], [], buildGtest)
</code></pre>
<p>SConscript for my unit test:</p>
<pre><code>env2 = env.Clone()
env2.Require('{path to gtest}/build/include/gtest.h') # This doesn't seem to work
env2.Append(CPPPATH='{path to gtest}/build/include')
env2.Object(target = 'test1.o', source = 'test1.cpp')
</code></pre>
",https://stackoverflow.com/questions/70203107/how-can-i-require-a-generated-file-in-my-sconscript,['scons'],72,False,0,1
Issues while Unit testing in c#,"<p>I have a class Library project which will be consumed by some legacy code and some modernized code. briefly I would like to show what issues I am facing with.</p>
<pre><code>class ClasslibraryService
{
    private Dependency1 _dependency1;
    private Dependency2 _dependency2
    public  ClasslibraryService(Dependency1 dependency)
    {
        _dependency1 = dependency;
         // this dependency2 could be something like logger or Bearer token service which I do not want to expose to consuming application
        _dependency2 = new Dependency2(new Dependency3());
    }
    public int DoSomeOperation()
    {
        var res = _dependency2.DoSomething();
        return _dependency1.DoSomeOperation(res);
    }
} 
</code></pre>
<p>So basically I had to new up within constructor without injecting dependency using constructor.</p>
<p>Now while unit test this class , I have created another constructor which takes all dependency through constructor. This is working fine.</p>
<p>But question here is</p>
<ol>
<li>I know I am violating main objective of unit testing by creating another constructor.Actual code will not be using this constructor. But I could not find any other way too!!</li>
<li>If 1 is not correct solution , please suggest me one solution</li>
</ol>
<p>TIA</p>
",https://stackoverflow.com/questions/68643396/issues-while-unit-testing-in-c,"['c#', '.net', 'unit-testing', 'moq']",85,True,0,1
"mockito wanted but not invoked, Actually there were zero interactions with this mock","<p>I apologize for making another post on this error, but I double checked the other post and ensured it is not the same cause.</p>
<p>I have a <code>ExploreRepository</code> class that use a <code>ExploreService</code>. The repository implement NetworkBoundResource. I am unit testing repository, use Mockito to mock Service.</p>
<pre class=""lang-kotlin prettyprint-override""><code>
class ExploreRepository(
    private val context: Context,
    private val exploreService: ExploreService
) {
    
    suspend fun getProperties(southwest: LatLng, northeast: LatLng, zoomLevel: Float): LiveResource&lt;List&lt;Property&gt;&gt; {
        return object : NetworkBoundResource&lt;List&lt;Property&gt;, SearchProperties&gt;() {


            override suspend fun makeApiCall(): SearchProperties {
                println(&quot;exploreService hashcode ${System.identityHashCode(exploreService)}&quot;)
                return exploreService.getProperties(context, geoHashList, precision)
            }

        }.asLiveResource()
    }

</code></pre>
<p>My testExploreRepository class</p>
<pre class=""lang-kotlin prettyprint-override""><code>
@Config(sdk = intArrayOf(Build.VERSION_CODES.O_MR1))
@RunWith(AndroidJUnit4::class)
class ExploreRepositoryTest {


    ...
    // Subject under test
    private lateinit var exploreRepository: ExploreRepository

    // Use a fake service to be injected into the repository
    private lateinit var mockExploreService: ExploreService

    private lateinit var mockSearchProperties: SearchProperties

    private val context: Application = ApplicationProvider.getApplicationContext()

    @Before
    fun setup(){
        mockExploreService = mock()
        exploreRepository = ExploreRepository(context, mockExploreService)
        mockSearchProperties = mock()
    }

    @Test
    fun `should make network service call`() = runBlocking&lt;Unit&gt; {

        // stubbing
        whenever(mockExploreService.getProperties(any(), any(), any())).thenReturn(mockSearchProperties)

        val northeast = LatLng( 37.799001, -122.422889)
        val southwest = LatLng( 37.782180, -122.451554)
        val zoomLevel = 10f

        exploreRepository.getProperties(southwest,northeast,zoomLevel)
        println(&quot;exploreService hashcode ${System.identityHashCode(mockExploreService)}&quot;) // debug line
        verify(mockExploreService, times(1)).getProperties(any(), any(), any())
    }
}

</code></pre>
<p>I have printed out the exploreService's hashCode.
The <code>println(&quot;exploreService hashcode ${System.identityHashCode(exploreService)}&quot;)</code> inside the makeApiCall() did run.
And I ensured that I am calling the  on the same instance of mock Service inside my repository.
But mockito still throw <code>Actually, there were zero interactions with this mock.</code></p>
<p>Edit: Actually in the test file, with the println() debug line enabled. The error is gone. Without it throw the error. Any clue?</p>
",https://stackoverflow.com/questions/68978280/mockito-wanted-but-not-invoked-actually-there-were-zero-interactions-with-this,"['android', 'unit-testing', 'mockito']",542,True,0,1
Verify if a web api controller require authorization programmatically,"<p>To simplify my life I've disabled the authorization policy for all the controllers in a .Net Core 3.1 Web API project when the environment is equal to development by adding some configuration in the startup file.</p>
<p>The controllers are secured by adding <code>[Authorize(AuthenticationSchemes = &quot;Bearer&quot;)]</code> on top of them.</p>
<p>Everything works fine, but there is also some piece of code inside all actions of the controllers that retrieve the username of the logged user to log the request.</p>
<p>Is there a way to check inside the method if the controller requires authorization (I'm in production) or not (I'm in development)?</p>
<p>This will be useful also for unit testing.</p>
",https://stackoverflow.com/questions/67338808/verify-if-a-web-api-controller-require-authorization-programmatically,"['c#', 'asp.net-core', 'asp.net-core-webapi']",333,False,0,1
Laravel 8 Unit Test,"<p>I am new to Unit Testing. The application has <code>helpers</code> (<code>App\Helpers\Helper</code>, <code>'Helper' =&gt; App\Helpers\Helper::class</code> added to the aliases in the <code>config</code>).</p>
<p>For tests, it is necessary to use the functionality of the helpers, since authorization goes through another service, and I send all requests there from the helpers.</p>
<p>Test code itself:</p>
<pre class=""lang-php prettyprint-override""><code>class ParticipantsTest extends TestCase
{
    use RefreshDatabase;

    public function test_createParticipants()
    {
        $participant = Helper::getRandParticipant();
        $type_participant = Helper::getType(2);
        $token = Helper::chooseToken($type_participant);

        $response = $this-&gt;post('/api/participants/create', [
            'token' =&gt; Helper::renewToken($participant, $token),
            'type_participant' =&gt; $type_participant,
            'callback' =&gt; $this-&gt;faker-&gt;sentence(20),
        ]);

        $response-&gt;assertStatus(200);

        $this-&gt;assertTrue(count(Task::all()) &gt; 1);
    }
}
</code></pre>
<p>When passing the test, I get an error:</p>
<blockquote>
<p>Attempt to read property &quot;participant&quot; on <code>null</code></p>
</blockquote>
<p>Although when I send a test request to the API using the <code>getRandParticipnat</code> method, I get a random participant, and in the tests it is <code>null</code>, how I can fix it?</p>
<p>Thanks</p>
<p><strong>UPD:</strong></p>
<pre class=""lang-xml prettyprint-override""><code>&lt;php&gt;
    &lt;server name=&quot;APP_ENV&quot; value=&quot;testing&quot;/&gt;
    &lt;server name=&quot;BCRYPT_ROUNDS&quot; value=&quot;4&quot;/&gt;
    &lt;server name=&quot;CACHE_DRIVER&quot; value=&quot;array&quot;/&gt;
    &lt;server name=&quot;DB_CONNECTION&quot; value=&quot;sqlite&quot;/&gt; 
    &lt;server name=&quot;DB_DATABASE&quot; value=&quot;:memory:&quot;/&gt; 
    &lt;server name=&quot;MAIL_MAILER&quot; value=&quot;array&quot;/&gt;
    &lt;server name=&quot;QUEUE_CONNECTION&quot; value=&quot;sync&quot;/&gt;
    &lt;server name=&quot;SESSION_DRIVER&quot; value=&quot;array&quot;/&gt;
    &lt;server name=&quot;TELESCOPE_ENABLED&quot; value=&quot;false&quot;/&gt;
&lt;/php&gt;
</code></pre>
<p>I think I'm need to reconfig for mysql connection? If I'm do that, can test clear DB with my real data?</p>
",https://stackoverflow.com/questions/69300980/laravel-8-unit-test,"['php', 'laravel', 'unit-testing', 'phpunit']",591,False,-1,1
How to test create model service?,"<p>I decided to create CreateClassroomService to separte logic in my controller method.</p>
<pre><code>class CreateClassroomService extends Service
{
    public function create(string $name, User $user): ?Classroom
    {
        $this-&gt;checkName($name);

        $classroom = new Classroom();
        $created = $classroom-&gt;setName($name)
            -&gt;associateUser($user)
            -&gt;save();

        return $created ? $classroom : null;
    }

    private function checkName(string $name): void
    {
        if (empty($name)) {
            throw new InvalidArgumentException();
        }
    }
}
</code></pre>
<p>I am trying to test this service as part of learning unit testing, but I don't know how. I don't know how to mock the classroom object to control what the method should return. Does this mean that creating this service was not a good idea because I am not able to test it? Should I build this service differently? Unless the service can be tested, but I don't know how... What should I check in assertion?</p>
<p>This is my test but it is not good because I am not able to force what should be returned.</p>
<pre><code>public function testGivenCreateCorrectDataClassroomWillBeCreated(): void
    {

        $name = 'Test classroom';
        $user = Mockery::mock(User::class);


        $result = $this-&gt;service-&gt;create($name, $user);

        $this-&gt;assertTrue($result);

    }
</code></pre>
",https://stackoverflow.com/questions/70237450/how-to-test-create-model-service,"['php', 'laravel', 'unit-testing', 'model', 'mocking']",416,True,-1,2
&#39;router-outlet&#39; is a Web Component then add &#39;CUSTOM_ELEMENTS_SCHEMA&#39; when ever i write unit testing,"<p>As you can see I am testing the application using unit testing in angular7, when ever I am running <code>ng test</code>.
I am getting issue like <code>router-outlet</code> is a Web Component then add <code>CUSTOM_ELEMENTS_SCHEMA</code> to the <code>@NgModule.schemas</code> of this component to suppress this message and the issue is related to app component and patient-group component no where they are getting called each other in testing application please have a look.</p>
<pre><code>patient-group.component.spec.ts
</code></pre>
<p>Here the entire testing goes here and i am including all the imports require to this application please check.</p>
<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import {tick, fakeAsync} from '@angular/core/testing';
import { Location} from '@angular/common';

import { PatientGroupComponent } from './patient-group.component';
import { Router, RouterOutlet, RouterModule } from &quot;@angular/router&quot;;
import { RouterTestingModule} from  '@angular/router/testing';
import  { HttpClientTestingModule} from '@angular/common/http/testing';
import { AppComponent} from '../app.component';

describe('PatientGroupComponent', () =&gt; {
  let location : Location;
  let  router : Router;
  let component: PatientGroupComponent;
  let fixture: ComponentFixture&lt;PatientGroupComponent&gt;;
  let fixture1;

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports : [RouterTestingModule,RouterModule, HttpClientTestingModule],
      declarations: [ PatientGroupComponent , AppComponent],
      providers : [ RouterOutlet , Router,
         { provide: Router, useClass: RouterModule }
      
      ]
    })
    .compileComponents();

     location = TestBed.get(Location);
     router = TestBed.get(Router);
     fixture1 = TestBed.createComponent(AppComponent);
    router.initialNavigation();

  }));

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

  it('should navigate to  /patientGroup', fakeAsync(()=&gt;{
    router.navigate(['']);
    tick();
    expect(location.path()).toBe('/patientGroup');
  }))

  it('should create', () =&gt; {
    const btn = fixture.debugElement.nativeElement.querySelector('group-btn');
    btn.click();
    const h1 = fixture.debugElement.nativeElement.querySelector('group-data')
    expect(h1.innerHTML).toBeTruthy();
  });
});

patient-group.component.html

&lt;form&gt;
    &lt;div *ngIf = &quot;data&quot;&gt;  
        &lt;div *ngFor=&quot;let arrayList of data let index = i&quot; style=&quot;text-align: center;&quot;&gt;
            &lt;span style=&quot;font-size: 30px;&quot;&gt;[&lt;/span&gt;&lt;span *ngFor=&quot;let arrayList2 of arrayList&quot;&gt;
                &lt;span style=&quot;font-size:30px !important; color: red; margin: 10px;&quot;
                contenteditable=&quot;true&quot; [ngModelOptions]=&quot;{standalone: true}&quot;   [(ngModel)] = &quot;data[i]&quot; ngDefaultControl &gt;{{arrayList2}}&lt;/span&gt;
            &lt;/span&gt;&lt;span style=&quot;font-size: 30px;&quot;&gt;]&lt;/span&gt;
        &lt;/div&gt;

        &lt;div style=&quot;text-align: center;&quot;&gt;
            &lt;button class=&quot;group-btn&quot;
                style=&quot;padding: 22px;color: white; font-size : 20px;background-color: blue;border-radius: 50%; margin: 20px 0px;&quot;
                (click)=&quot;getPatientGroups()&quot;&gt;Click for Patient groups&lt;/button&gt;
        &lt;/div&gt;

        &lt;h1 class=&quot;group-data&quot; *ngIf=&quot;patientData &gt;= 0&quot; style=&quot;color: green; text-align: center;&quot;&gt; The Patient Group &lt;span
                *ngIf=&quot;patientData &gt; 1&quot;&gt;'s&lt;/span&gt; are : &lt;span style=&quot;color: black;&quot;&gt;{{patientData}}&lt;/span&gt;&lt;/h1&gt;
    &lt;/div&gt;
&lt;/form&gt;


app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule,Routes } from '@angular/router';



import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatDialogModule} from '@angular/material/dialog';
import {MatIconModule} from '@angular/material/icon';
import { chatSupportService } from './services/chat-support.service';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {MatFormFieldModule, MatFormFieldControl} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';
import { HttpClientModule,HTTP_INTERCEPTORS} from '@angular/common/http';
import {MatButtonModule, MatCheckboxModule} from '@angular/material';

import { TokenInterceptor } from './app.interceptor';
import { PatientGroupComponent } from './patient-group/patient-group.component';
//import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/compiler/src/core';

const routes : Routes = [
  { path : '', redirectTo : 'patientGroup', pathMatch : 'full'},
  { path : 'patientGroup', component : PatientGroupComponent}
]

@NgModule({
  declarations: [
    AppComponent,
    PatientGroupComponent,
    
    
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(routes),
    MatFormFieldModule,
    BrowserAnimationsModule,
    MatInputModule,
    MatDialogModule,
    MatIconModule,
    HttpClientModule,
    MatButtonModule, 
    MatCheckboxModule,
    FormsModule, ReactiveFormsModule
    
    
    
  ],
  entryComponents:[
   
    
    

  ],
  providers: [chatSupportService,
  
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    },



  ],
  //schemas : [CUSTOM_ELEMENTS_SCHEMA],
  
  bootstrap: [AppComponent]
})
export class AppModule { }


app.component.html
</code></pre>
<p>This is app component i am not using any dom here.
But in main.component.html file when I do  . It shows errors:</p>
<pre><code>If 'router-outlet' is an Angular component, then verify that it is part of this module.
If 'router-outlet' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.


&lt;div&gt;
  &lt;router-outlet&gt;&lt;/router-outlet&gt;
&lt;/div&gt;
</code></pre>
",https://stackoverflow.com/questions/69615141/router-outlet-is-a-web-component-then-add-custom-elements-schema-when-ever-i,"['javascript', 'angular', 'typescript', 'karma-jasmine', 'angular-test']",190,False,-1,1
How to trigger DataReceivedEventHandler?,"<p>5-cent Version: How do you manually trigger a DataReceivedEventHandler? I recall using asynchronous delayed delegates to trip it, but I cannot figure out how.</p>
<p>5-dollar Version: I am currently doing Unit Testing on a project of mine, and I am currently trying to simulate a successful communication event. The method under test is as follows.</p>
<pre><code>   public async Task&lt;CommandResponse&gt; StartScanAsync()
        {
            if (_isCommandInProgress)
            {
                Trace.WriteLine(&quot;Command in progress.&quot;);
                return new CommandResponse(CommandStatus.CommandInProgress);
            }
            else
            {
                Task&lt;DongleResponse&gt; t = WaitForDongleResponse(CommandId.CMD_START);
                byte[] sendBuf = { 0x00 };
                _serialDriver.send(sendBuf, 1);
                Trace.WriteLine(&quot;Command send. Waiting for response&quot;);

                // Wait for either dongle response or timeout
                // If dongleResponse comes first, set 
                if (await Task.WhenAny(t, Task.Delay(RECEIVE_TIMEOUT)) == t) {
                    _isScanning = true;
                    _isCommandInProgress = false;
                    return new CommandResponse(CommandStatus.OK, t.Result);
                }
                else
                {
                    _isCommandInProgress = false;
                    _rspRxTcs.SetCanceled();
                    return new CommandResponse(CommandStatus.ResponseTimeout);
                }
            }
        }
</code></pre>
<p>and below is my unit test code</p>
<pre><code>using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using FluentAssertions;
using System.Threading.Tasks;

namespace TriggerDataHandler.Tests
{// SUCCESSFULLY TRIGGER TIMEOUT AND SUCCESS PROMPTS
    [TestClass()]
    public class CommandServiceTestClass
    {
        private readonly Mock&lt;ISerialDriver&gt; MockDriver
            = new Mock&lt;ISerialDriver&gt;();

        [TestMethod()]
        public async Task StartScan_And_ReturnSUCCESS()
        //How to trigger dataHandler? return 0x0000
        {
            //Arrange: Set up variables for Act to work
            CommandService csGO = new CommandService(MockDriver.Object);

            //Act: Initiate StartScan and wait for a timeout to occur
            
            CommandResponse result = await csGO.StartScanAsync();

            //Assert: Your end goal which should be true
            Assert.AreEqual(result.Status, CommandStatus.OK);
        }
    }
}
</code></pre>
<p>I ain't allowed to put out anymore code at the moment, so if the information provided is insufficient, please provide me instead with some links you feel are relevant to the situation, and I'll try working my way up from there instead.</p>
<p>Thanks for reading btw.</p>
",https://stackoverflow.com/questions/68033776/how-to-trigger-datareceivedeventhandler,"['c#', '.net', 'wpf']",95,False,0,1
unit testing for aem not covering a condition,"<p>im new to unit testing. I am using junit5 for an aem 6.5 application. Im trying to write unit test so that i can migrate to cloud which has a requirement of atleast 50% unit test, thus what im doing now. My code has an init method for the getTags(). My unit test works fine but the jacoco reports a line that is not being covered. Any help would be appreciated to pint me in the right direction.</p>
<p>I have this class:</p>
<pre><code>@Self
private SlingHttpServletRequest request;

@ValueMapValue
private List&lt;String&gt; tags;

@Override
public String getExportedType() {
    return RESOURCE_TYPE;
}

@PostConstruct
public void init() {
    Resource tagsNode = request.getResource().getChild(&quot;tags&quot;);
    tags = new ArrayList&lt;&gt;();
    if (tagsNode!=null) {
        for (Resource child : tagsNode.getChildren()) {
            TagModel tag = child.adaptTo(TagModel.class);
            tags.add(tag.getTag());
        }
    }
}

public List&lt;String&gt; getTags() {
    return this.tags;
}
</code></pre>
<p>And i have this unit test for aem</p>
<pre><code>@Test
void testGetTags() {
    List&lt;String&gt; expected = new ImmutableList.Builder&lt;String&gt;()
            .add(&quot;4&quot;)
            .add(&quot;22&quot;)
            .build();

    ctx.currentResource(&quot;/content/blog_placeholder&quot;);

    BlogPlaceholderModel blogPlaceholderModel = ctx.request().adaptTo(BlogPlaceholderModel.class);

    List&lt;String&gt; actual = blogPlaceholderModel.getTags();

    assertEquals(expected, actual);
}

@Test
void testGetExportedType() {
    final String expected = &quot;furniture-row/components/content/blog-placeholder&quot;;

    ctx.currentResource(&quot;/content/blog_placeholder&quot;);

    BlogPlaceholderModel blogPlaceholderModel = ctx.request().adaptTo(BlogPlaceholderModel.class);

    String actual = blogPlaceholderModel.getExportedType();

    assertEquals(expected, actual);
}
</code></pre>
<p>For some reason my test is not covering the if condition:</p>
<p><a href=""https://i.stack.imgur.com/Pktmm.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Pktmm.png"" alt=""enter image description here"" /></a></p>
<p>what am i missing ? thanks</p>
",https://stackoverflow.com/questions/68627442/unit-testing-for-aem-not-covering-a-condition,"['unit-testing', 'junit', 'aem', 'junit5']",204,True,0,1
Angular Test Mock ContentChild,"<p>I want to test an Angular Component and replace the contentChild with a Mock. I followed this guide: <a href=""https://medium.com/angular-in-depth/angular-unit-testing-viewchild-4525e0c7b756"" rel=""nofollow noreferrer"">https://medium.com/angular-in-depth/angular-unit-testing-viewchild-4525e0c7b756</a>
The guide is for a viewChild, but I thought this could also work for a content Child.</p>
<p>My contentChild has a Observable to which the parent subscribe. If I test the code with the real child, it works. If I mock the child, the test doesn't work. I think the child mock, I query in the test to emit a new value, is a different instance, than the one which the parent subscribed to.</p>
<p>My parent:</p>
<pre><code>@Component({
  // tslint:disable-next-line:component-selector
  selector: '[appParent]',
  template: `
    &lt;div&gt;
      &lt;span class=&quot;true&quot; *ngIf=&quot;display$ | async; else other&quot;&gt;True&lt;/span&gt;
    &lt;/div&gt;
    &lt;ng-content&gt;&lt;/ng-content&gt;
    &lt;ng-template #other&gt;&lt;span class=&quot;false&quot;&gt;False&lt;/span&gt;&lt;/ng-template&gt;
  `
})
export class ParentComponent implements AfterContentInit {

  @ContentChild(ChildComponent) child!: ChildComponent;

  display$: Observable&lt;boolean&gt;;

  ngAfterContentInit(): void {
    this.display$ = this.child.display$;
  }
}
</code></pre>
<p>My mock:</p>
<pre><code>@Component({
  selector: 'app-child',
  template: '',
  providers: [
    {
      provide: ChildComponent,
      useExisting: ChildStubComponent
    }
  ]
})
export class ChildStubComponent {
  displaySubject = new BehaviorSubject(false);
  display$: Observable&lt;boolean&gt; = this.displaySubject.asObservable();
}
</code></pre>
<p>And the test:</p>
<pre><code>describe('ParentComponentTest', () =&gt; {
  @Component({
    template: `
      &lt;div appParent&gt;
        &lt;app-child&gt;&lt;/app-child&gt;
      &lt;/div&gt;
    `
  })
  class TestComponent {
    @ViewChild(ChildStubComponent)
    child!: ChildStubComponent;
  }

  let component: TestComponent;
  let fixture: ComponentFixture&lt;TestComponent&gt;;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [
        TestComponent,
        ChildStubComponent,
        ParentComponent
      ]
    }).compileComponents();
  });

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

  it('should find true', () =&gt; {
    component.child.displaySubject.next(true);
    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('.true'))).toBeTruthy();
  });

});
</code></pre>
",https://stackoverflow.com/questions/66712667/angular-test-mock-contentchild,"['angular', 'unit-testing', 'mocking', 'angular-content-projection']",1239,True,0,2
Function is casting uint8 &lt;--&gt;uint16?,"<p>I'm unit testing(UT) my code and I found something odd that maybe someone can explain to me.
I have two functions similar to those beneath this lines. When I call &quot;fun_16bit&quot; from the test I pass a value above 255 to see what &quot;fun_8bit&quot; does. If I write value=256 --&gt;fun_8bit will print 0. If I call from UT fun_8bit with value=-1--&gt;It prints 255.</p>
<p>What is happening?????
Why the func8bit does only take the first 8 bits and doesn't the compiler say something?</p>
<p>By the way I'm compiling C with gcc.</p>
<pre><code>void fun_16bit(uint16_t value)
{
    printf(&quot;value: %d&quot;, value);
    fun_8bit(value);
}

void fun_8bit(uint8_t value)
{
    printf(&quot;value: %d&quot;, value);
}



int main() {
  fun_16bit(0x1234);
}
</code></pre>
<p>Expected output: some error from compiler or warning
Actual output:
value: 1234
value: 34</p>
<p>Thankyou all.</p>
",https://stackoverflow.com/questions/67900751/function-is-casting-uint8-uint16,"['c', 'casting']",907,True,0,3
JEST unit testcase - beginner and facing issues,"<p><strong>im trying to to convert below code snippet to JEST unit testing but its throwing error please help me out in resolving it</strong>
import React from 'react'
import { BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import IdleTimer from 'react-idle-timer';
import { ApolloProvider } from '@apollo/react-hooks';
import Dashboard from '../pages/Dashboard';
import Loader from '../components/Loader';
import Alert from '../components/Alert';
import NoAccess from '../pages/NoAccess';
import { GQL } from '../services/GQL';
import { IdleTimeOutModal } from './IdleTimeoutModal';
import PropTypes from 'prop-types';
import 'bootstrap/dist/css/bootstrap.min.css';
import '../App.scss';
import '../assets/css/loader.scss';
import AuthenticatedRoute from '../guards/AuthenticatedRoute';
import auth from '../services/Auth';
import { connect } from 'react-redux';</p>
<pre><code>class Layout extends React.Component {

    constructor(props){
      super(props);
        this.state = {
            timeout:1000 * 900 * 1,
            showModal: false,
            userLoggedIn: window.localStorage.getItem('loginUser'),
            isTimedOut: false,
            
        }

        this.idleTimer = null
        this.onAction = this._onAction.bind(this)
        this.onActive = this._onActive.bind(this)
        this.onIdle = this._onIdle.bind(this)
        this.handleClose = this.handleClose.bind(this)
        this.handleLogout = this.handleLogout.bind(this)
    }

    _onAction(e) {
      // console.log('user did something', e)
      this.setState({isTimedOut: false})
    }
   
    _onActive(e) {
      // console.log('user is active', e)
      this.setState({isTimedOut: false})
    }
   
    _onIdle(e) {
      // console.log('user is idle', e)
      const isTimedOut = this.state.isTimedOut
      if (isTimedOut) {
        this.setState({showModal: false})
         window.localStorage.setItem('loginUser', 'false');
      } else {
        this.setState({showModal: true})
        this.idleTimer.reset();
        this.setState({isTimedOut: true})
      }
      
    }

    handleClose() {
      this.setState({showModal: false})
    }

    handleLogout() {
      this.setState({showModal: false})
      auth.signout();
    }

    render(){
      // console.log(window.location)
      const {match} = window.location.href;
      // const { match } = this.location
      return(
        &lt;&gt;
          &lt;IdleTimer
            ref={ref =&gt; { this.idleTimer = ref }}
            element={document}
            onActive={this.onActive}
            onIdle={this.onIdle}
            onAction={this.onAction}
            debounce={250}
            timeout={this.state.timeout} /&gt;

            &lt;div className=&quot;&quot;&gt;
            &lt;ApolloProvider client={GQL}&gt;
                &lt;Router&gt;
                  &lt;Switch&gt;
                    {/* &lt;Route component={NoAccess} path=&quot;/no-access&quot; exact={true} /&gt; */}
                    &lt;AuthenticatedRoute  path={`${window.location.pathname}`} component={Dashboard} /&gt;
                  &lt;/Switch&gt;
                &lt;/Router&gt;
                {/* &lt;Loader isOpen={loader.isLoading} /&gt; */}
                {/* &lt;Alert /&gt; */}
            &lt;/ApolloProvider&gt;
                &lt;IdleTimeOutModal 
                    showModal={this.state.showModal} 
                    handleClose={this.handleClose}
                    handleLogout={this.handleLogout}
                /&gt;
            &lt;/div&gt;
        &lt;/&gt;
      )
   }

 }

***JEST throwing error while converting to JEST -     ShallowWrapper::state() can only be called on class components 
jest help***

export default connect((props) =&gt;({
  match: props.uiel.isRequired,
  history: props.uiel.isRequired
}))(Layout);     

import React from 'react';
import { BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import { render, cleanup, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import Enzyme, { shallow, mount } from 'enzyme';
import Layout from './Layout';
import Adapter from 'enzyme-adapter-react-16';
import { Provider } from &quot;react-redux&quot;;
import configureMockStore from &quot;redux-mock-store&quot;;
import { IdleTimeOutModal } from './IdleTimeoutModal';
import { wrap } from 'module';

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

const mockStore = configureMockStore();

let handleLogout:any;
let showModal: any;
let handleClose:any;
let remainingTime:any;
let _onAction:any;
let _onIdle:any;
let _onActive:any;
let idleTimer:any;

describe(&quot;Render Layout Component&quot;, ()=&gt;{
  let store;
  let wrapperlayout:any;
  beforeEach(()=&gt;{
    store = mockStore({
      loader: false
    });
    wrapperlayout = shallow(
      &lt;Provider store={store}&gt;
       &lt;Layout /&gt;
      &lt;/Provider&gt;
    );
  });
  it('should render the value of color', () =&gt; {
    wrapperlayout.setProps({ timeout:1000 * 900 * 1 });
    wrapperlayout.setProps({ showModal: false });
    wrapperlayout.setProps({ userLoggedIn: window.localStorage.getItem('loginUser') });
    wrapperlayout.setProps({ isTimedOut: false });
    //expect(wrapper.state('color')).toEqual('transparent');
 });
 it(&quot;should increment index - function test&quot;, () =&gt; {
  //const app = shallow(&lt;Normal /&gt;);
  expect(wrapperlayout.state(&quot;isTimedOut&quot;)).toEqual('false');
  wrapperlayout.instance()._onAction();
  expect(wrapperlayout.state(&quot;isTimedOut&quot;)).toEqual('false');
});
  test(&quot;Render Modal Layout&quot;, ()=&gt;{
    expect(wrapperlayout.exists()).toBe(true);
  }); 
});
</code></pre>
",https://stackoverflow.com/questions/69160264/jest-unit-testcase-beginner-and-facing-issues,"['unit-testing', 'jestjs']",86,False,0,0
How to handle runtime errors in C++?,"<p>So, I'm kinda new to C++ and I wanted to know what are the good practices or even how do I handle runtime errors when programming, here is an example:</p>
<pre><code>State s_toState(std::string state){
  if (state == &quot;MG&quot;)
    return State::MG;
  else if (state == &quot;PR&quot;)
    return State::PR;
  else if (state == &quot;SP&quot;)
    return State::SP;
  else if (state == &quot;SC&quot;)
    return State::SC;
  else if (state == &quot;RJ&quot;)
    return State::RJ;
  else if (state == &quot;RN&quot;)
    return State::RN;
  else if (state == &quot;RS&quot;)
    return State::RS;

  // ???
}
</code></pre>
<p>So I have this function that transforms a <code>string</code> into a <code>State</code>. Without using exception, what is the ideal way for me to assert that the given state is an existing one (MG, PR, SP, etc...)?</p>
<p>Gave an example but I'm asking for the general rule. As far as I know i could use exceptions, assertions or just print the error. I do pretend to unit test this too (also new to unit testing and know nothing about it).</p>
",https://stackoverflow.com/questions/70028944/how-to-handle-runtime-errors-in-c,"['c++', 'unit-testing', 'error-handling', 'assert']",436,True,0,3
spring.datasource.url how to create multiple enum/domain before hibernate is scanning the entities,"<p>I have spring boot application with pgsql as db. I am writing test cases for the api's and for the test cases i am using h2 db. I have multiple entities where i have multiple enums. For the test cases we have</p>
<pre><code>spring.jpa.hibernate.ddl-auto = create-drop
</code></pre>
<p>When hibernate is creating the tables from entity it is giving Unknown data type: &quot;enum_type1&quot;.</p>
<p>I took a reference from this question:
<a href=""https://stackoverflow.com/questions/7988599/how-to-fake-enum-columns-in-the-h2-database-for-play-unit-testing"">How to fake ENUM columns in the H2 database for play unit testing?</a></p>
<p>So i updated my property as follows:</p>
<pre><code>spring.datasource.url= jdbc:h2:mem:test;MODE=PostgreSQL;INIT=CREATE DOMAIN IF NOT EXISTS enum_type1 as VARCHAR(255),CREATE DOMAIN IF NOT EXISTS enum_type2 as VARCHAR(255);DB_CLOSE_ON_EXIT=FALSE
</code></pre>
<p>But it is giving following error:</p>
<pre><code>org.h2.jdbc.JdbcSQLSyntaxErrorException: Syntax error in SQL statement &quot;CREATE DOMAIN IF NOT EXISTS enum_type1 AS VARCHAR(255),[*]CREATE DOMAIN IF NOT EXISTS enum_type2 AS VARCHAR(255)&quot;; SQL statement:
</code></pre>
<p>So how can we create multiple enum/domain before hibernate is scanning the entities?
Any help will be appreciated, Thanks.</p>
",https://stackoverflow.com/questions/65697000/spring-datasource-url-how-to-create-multiple-enum-domain-before-hibernate-is-sca,"['java', 'spring-boot', 'hibernate', 'h2']",520,False,-1,1
initializationError when trying to use JUnit in vscode,"<p>I am trying to do Java unit testing in Visual studio code using JUnit.
I have:</p>
<ul>
<li>Installed JUnit 4 jar to a folder</li>
<li>Made a reference to the .jar in VSCodes &quot;Referenced Libraries&quot; section</li>
<li>Made simple folder structure using no build tools</li>
</ul>
<p>This is the directory structure of the project</p>
<pre><code>(root project)
   |__ src/com/example
        |__ Add.java
   |__ src/test
        |__ TestAdd.java          
</code></pre>
<p>Add.java:</p>
<pre><code>package src.com.example;

public class Add {
    public Add() {
    }
    
    public int add(int a, int b) {
        return a + b;
    }
}
</code></pre>
<p>TestAdd.java:</p>
<pre><code>package src.test;

import static org.junit.Assert.assertEquals;
import org.junit.Test;
import src.com.example.Add;

public class TestAdd {

    public TestAdd() {
    }

    @Test
    public void testAdd() {
        Add add = new Add();
        
        assertEquals(2, add.add(1, 1));
    }
}
</code></pre>
<p><strong>The issue</strong></p>
<p>When I click run test, VSCode doesn't run the tests and says:</p>
<blockquote>
<p>initializationError(src.test.TestAdd)</p>
</blockquote>
<p>As the reason for not running the test under the testing tab in VSCode.</p>
<p><strong>Screenshots:</strong>
Folder structure + libraries:
<a href=""https://i.stack.imgur.com/rw7Aq.png"" rel=""nofollow noreferrer"">Folder structure + libraries</a>
Error shown:
<a href=""https://i.stack.imgur.com/HHzAq.png"" rel=""nofollow noreferrer"">Error shown</a></p>
<p><strong>Please be forgiving, this is my first StackOverflow question - apologies in advance!</strong></p>
",https://stackoverflow.com/questions/69131052/initializationerror-when-trying-to-use-junit-in-vscode,"['java', 'visual-studio-code', 'junit', 'junit4']",629,True,0,2
Rcpp functions cause crash in package,"<p>I have a package, <a href=""https://github.com/tfrostig/RSEE"" rel=""nofollow noreferrer"">https://github.com/tfrostig/RSEE</a>, which includes a few (3) RcppArmadillo functions. The package works well on other computer. When I build the package no errors appear, but whenever I call any of the RCPP functions it causes R to crash.</p>
<p>When I try to use my Unit Testing, I obtain the error: &quot;Exited with status -1073741819&quot; .</p>
<p>If I use <code>Rcpp::sourceCpp()</code> and then call the functions, everything works well. Other packages with Rcpp functions work well.</p>
<p>For example:</p>
<pre><code>`// [[Rcpp::depends(RcppArmadillo)]]
#include &lt;RcppArmadillo.h&gt;
using namespace Rcpp;
using namespace arma;


// [[Rcpp::export]]
arma::mat localRegression(arma::mat weightmat, arma::mat modelmat, arma::vec xtemp) {
  return inv(modelmat.t() * weightmat * modelmat) * modelmat.t() * weightmat * xtemp;
}
</code></pre>
<p>Using <code>RSEE:::localRegression</code> will cause it to crash. If I load the source code using <code>sourceCpp</code> and then call <code>localRegression</code> it works ok.</p>
<p>What can cause this type of problem?</p>
<pre><code>The session info is: 
R version 4.0.3 (2020-10-10)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19042)

Matrix products: default

locale:
[1] LC_COLLATE=English_Israel.1252  LC_CTYPE=English_Israel.1252    LC_MONETARY=English_Israel.1252
[4] LC_NUMERIC=C                    LC_TIME=English_Israel.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] RSEE_0.1.0

loaded via a namespace (and not attached):
[1] compiler_4.0.3 tools_4.0.3    Rcpp_1.0.6    
</code></pre>
",https://stackoverflow.com/questions/66205736/rcpp-functions-cause-crash-in-package,"['r', 'package', 'rcpp', 'rcpparmadillo']",76,True,0,1
onRequest Firebase function seems to replace the response parameter object on exception,"<p>I'm currently trying to unit test my HTTPS functions. I would like to test my error responses so I voluntarily cause an exception in my https function. I catch an error displayed in the <code>console.debug(e)</code> but the <code>res.status().json()</code> that I provide in my unit tests is never called, and so the <code>done()</code> function is never called neither.</p>
<p>However, it seems that when the <code>onCreateUserAndAgency()</code> is successful, the <code>res.json()</code> that I provide is called, and the test is successful.</p>
<p>Is there a step when the Response object is replaced in case of an exception ? Am I doing something wrong ?</p>
<p>The stack I use is <code>Firebase Functions</code> with <code>Typescript</code> and <code>Mocha</code> for unit testing.</p>
<pre class=""lang-js prettyprint-override""><code>export default functions.https.onRequest((req, res) =&gt; {
    /* here, when I put res.status(200).json({}), the test's successful so it means done() is called */
    onCreateUserAndAgency({
        body: req.body,
    }).then(r =&gt; {
        res.json(r);
    }).catch(e =&gt; {
        console.debug(e);
        res.status(e.error.status).json(e);
    })
});
</code></pre>
<pre class=""lang-js prettyprint-override""><code>describe('User', async function() {
  describe('#createUser()', async function() {
    it('should return error 500 for unknown errors', async function(done) {
      const req: any = { };
      const res: any = {
        status: (status: number) =&gt; {
          assert.equal(status, 500);
          console.log(&quot;TEST&quot;);
          done();
        },
        json: (data: any) =&gt; {
          console.log(&quot;TEST&quot;);
          done();
        } 
      };
      fcts.createUserViaEmail(req, res);
    });
  });
});
</code></pre>
<p>The error log :</p>
<pre><code>&gt; test
&gt; mocha --require ts-node/register test/**/*.spec.ts

{&quot;severity&quot;:&quot;WARNING&quot;,&quot;message&quot;:&quot;Warning, estimating Firebase Config based on GCLOUD_PROJECT. Initializing firebase-admin may fail&quot;}


  User
    #createUser()
TypeError: Cannot read properties of undefined (reading 'user')
    at onCreateUserAndAgency (C:\Users\Orionss\Projets\PATH\functions\src\users\on-create.ts:20:70)
... Many less specific error lines
{
  error: {
    status: 500,
    message: &quot;Une erreur inattendue s'est produite.&quot;,
    date: 2021-12-21T14:04:42.842Z
  }
}
      1) should return error 500 for unknown errors


  0 passing (2s)
  1 failing

  1) User
       #createUser()
         should return error 400 for missing info:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure &quot;done()&quot; is called; if returning a Promise, ensure it resolves. (C:\Users\Orionss\Projets\PATH\functions\test\main.spec.ts)
      at listOnTimeout (node:internal/timers:557:17)
      at processTimers (node:internal/timers:500:7)
</code></pre>
",https://stackoverflow.com/questions/70436776/onrequest-firebase-function-seems-to-replace-the-response-parameter-object-on-ex,"['typescript', 'firebase', 'google-cloud-functions', 'mocha.js']",149,True,0,1
fixture.detectchanges() method resulting in test case to fail,"<p>I am unit testing my component using Karma and jasmine. fixture.detechChanges() should be use for every test in order to detect the changes. But this method is making the test case to fail and giving error</p>
<p><strong>Error: InvalidPipeArgument: 'Unable to convert &quot;Invalid Date&quot; into a date' for pipe 'DatePipe'</strong></p>
<p>Since I am new to this can anyone let me know why this is behaving like this and what is the correct place to use this.</p>
<p>Out the three test cases 2nd test case is failing. I have done lot of research but i am not sure why my test case is failing.</p>
<p>below is my code</p>
<h2>component.ts</h2>
<pre><code>export class ResourceOverviewComponent implements OnInit {
  id = '--';
  
  lastupdated : any;
  creationDate = '--'
  description = '--'
  tags = '--'
  dateTimeFormat = 'MMM d, y h:mm a';
 
  dateTimeZone: any;
  
  constructor(
    private readonly resourceOverviewService: ResourceOverviewService,
    private readonly utilsService: UtilsService,
    private readonly router: Router,
    readonly route: ActivatedRoute,
  ) {}

  ngOnInit() {
    this.id = this.route.snapshot.queryParamMap.get('id');
    this.getDetails();
  }

  viewInventory(){
    this.router.navigate(['..'], {
      relativeTo: this.route
    });
  }

  getDetails() {
    if (this.id) {
      this.getResourceOverview();
    }
  }

  getResourceOverview(): void {
    const resourceID = `search_keys=${&quot;resource_id&quot;}&amp;search=${this.id}`
    this.resourceId = this.id
    this.resourceOverviewService
      .getResourceOverview(resourceID)
      .subscribe(
        (response) =&gt; {
          const result = response as any;
          if (result &amp;&amp; result.raw_items[0]) {
       
            this.creationDate = result.raw_resource_created || '--' ;
          }
        },
        (error) =&gt; {
          console.log('Resource overview details failed with error', error);
        }
      );
  }
}
</code></pre>
<h2>component.spec.ts</h2>
<pre><code>class mockHttpWrapperService {
  readonly isApiReady = false;
}

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ SomeComponent ],
      imports: [
        some module,some-module,somemodule.forRoot(),
        RouterModule.forRoot([]),
      ],
      providers: [
        { provide: NGXLogger, useClass: MockNGXLogger },
        { provide: HttpWrapperService, useClass: mockHttpWrapperService },
        { provide: Router, useClass: class { navigate = jasmine.createSpy(&quot;navigate&quot;); }},
        ApiService,
        SomeService,
        SomeService,
        SomeService,
        SomeService,
        {
          provide: ActivatedRoute,
          useValue: {
            params: of({ id: 'aeb24ca0549c', code: 'IBM' }),
            snapshot: {
              queryParamMap: convertToParamMap({
                id: 'aeb24ca0549c',
                code: 'IBM',
              })
            }
          }
        },
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    })
    .compileComponents()
  }));

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

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

  it('should init object for action tabs', async () =&gt; {
    await fixture.whenStable();
    component.ngOnInit();
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });

  it('should get resource data ', () =&gt; {
    someService = TestBed.inject(SomeService);
    const data = {some-xyz-object};
    spyOn(someService, &quot;getResourceOverview&quot;).and.callFake(() =&gt; {
      return of(data)
    })
    component.getDetails();
    fixture.detectChanges();
    expect(component).toBeTruthy();
  });
});
</code></pre>
<h2>component.html</h2>
<pre><code>&lt;div class=&quot;container-wrapper&quot;&gt;
  &lt;div class=&quot;breadcrumWrapper&quot; &gt;
  &lt;ibm-breadcrumb&gt;
   
        &lt;ibm-breadcrumb-item &gt;
            {{ id }}
        &lt;/ibm-breadcrumb-item&gt;
    &lt;/ibm-breadcrumb&gt;
  &lt;div class=&quot;breadcrumWrapper&quot; &gt;
  
  &lt;/div&gt;
  &lt;div&gt;
   
  &lt;/div&gt;
&lt;/div&gt;
  &lt;div class=&quot;container-overview&quot; &gt;
    &lt;div class=&quot;overview&quot; &gt;
    
    &lt;/div&gt;
    &lt;div class=&quot;marginTop &quot;&gt;
      &lt;div class=&quot;bx--row&quot;&gt;
        &lt;div class=&quot;bx--col-xs-6&quot;&gt;
          &lt;div class=&quot;bx--row rowMargins&quot;&gt;
            &lt;span
              class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
              title=&quot;{{ id }}&quot;
              &gt;{{ id }}&lt;/span
            &gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=&quot;bx--col-xs-6&quot;&gt;
          &lt;div class=&quot;bx--row rowMargins&quot;&gt;
           
            &lt;span
              class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
              title=&quot;{{ resourceType }}&quot;
              &gt;{{ resourceType }}&lt;/span
            &gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=&quot;bx--row&quot;&gt;
        &lt;div class=&quot;bx--col-xs-6&quot;&gt;
          &lt;div class=&quot;bx--row rowMargins&quot;&gt;
           
            &lt;span
              class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
              title=&quot;{{ region }}&quot;
              &gt;{{ region }}&lt;/span
            &gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=&quot;bx--col-xs-6&quot;&gt;
          &lt;div class=&quot;bx--row rowMargins&quot;&gt;
           
            &lt;div *ngFor=&quot;let k of keyValue; let i = index;&quot;&gt;
            &lt;span *ngIf=&quot;i!=(keyValue.length-1)&quot;
            class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
            title=&quot;{{ id }}&quot;
            &gt;{{ k.Key }} : {{ k.Value }} ,
            &lt;/span&gt;
            &lt;span *ngIf=&quot;i==(keyValue.length-1)&quot;
            class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
            title=&quot;{{ id }}&quot;
            &gt;{{ k.Key }}:{{ k.Value }}
            &lt;/span&gt;
          &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
       &lt;div class=&quot;bx--row&quot;&gt;
        &lt;div class=&quot;bx--col-xs-6&quot;&gt;
          &lt;div class=&quot;bx--row rowMargins&quot;&gt;
          
            &lt;span
              class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
              title=&quot;{{ correlationID }}&quot;
              &gt;{{ correlationID }}&lt;/span
            &gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=&quot;bx--col-xs-6&quot;&gt;
          &lt;div class=&quot;bx--row rowMargins&quot;&gt;
           
            &lt;span
              class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
              title=&quot;{{ resourceCategory }}&quot;
              &gt;{{ resourceCategory }}&lt;/span
            &gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;/div&gt;
        &lt;div *ngIf=&quot;showMore&quot;&gt;
        &lt;div class=&quot;bx--row&quot;&gt;
       &lt;div class=&quot;bx--col-xs-6&quot;&gt;
          &lt;div class=&quot;bx--row rowMargins&quot;&gt;
          
            &lt;span
              class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
              title=&quot;{{ status }}&quot;
              &gt;{{ status }}&lt;/span
            &gt;
          &lt;/div&gt;
        &lt;/div&gt;
        &lt;div class=&quot;bx--col-xs-6&quot;&gt;
          &lt;div class=&quot;bx--row rowMargins&quot;&gt;
           
            &lt;span
              class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
              title=&quot;{{ provider }}&quot;
              &gt;{{ provider }}&lt;/span
            &gt;
          &lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
      
        &lt;div class=&quot;bx--row&quot;&gt;
          &lt;div class=&quot;bx--col-xs-6&quot;&gt;
            &lt;div class=&quot;bx--row rowMargins&quot;&gt;
           
              &lt;span
                class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
                title=&quot;{{ providerAccount }}&quot;
                &gt;{{ providerAccount }}&lt;/span
              &gt;
            &lt;/div&gt;
          &lt;/div&gt;
          &lt;div class=&quot;bx--col-xs-6&quot;&gt;
            &lt;div class=&quot;bx--row rowMargins&quot;&gt;
            
              &lt;span
                class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
                title=&quot;{{ resourceName }}&quot;
                &gt;{{ resourceName }}&lt;/span
              &gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
       
      &lt;/div&gt;
      
  &lt;/div&gt;
  &lt;div class=&quot;container-overview complex-data-viewer-wrap&quot; &gt;
   
    
    &lt;div class=&quot;bx--row&quot;&gt;
    &lt;div class=&quot;bx--col-xs-6&quot;&gt;
      &lt;div class=&quot;bx--row rowMargins&quot;&gt;
      
        &lt;span
          class=&quot;ellipsis overViewcontent bx--col-xs-5&quot;
          title=&quot;{{ creationDate }}&quot;
          &gt;{{ creationDate }}&lt;/span
        &gt;
      &lt;/div&gt;
    &lt;/div&gt;
     
    
  &lt;/div&gt;
&lt;/div&gt;
</code></pre>
",https://stackoverflow.com/questions/69879126/fixture-detectchanges-method-resulting-in-test-case-to-fail,"['angular', 'unit-testing', 'jasmine', 'angular-cli', 'karma-jasmine']",2854,True,0,2
How to include PS code with shared YAML templates in Azure DevOps Server 2020?,"<p>We use shared YAML templates extensively in our YAML builds. Something like this:</p>
<pre><code>trigger: none

resources:
  repositories:
    - repository: templates
      type: git
      name: DFDevOps\cicd-templates
      ref: refs/tags/stable-1
      # http://tdc1tfsapp01:8080/tfs/DefaultCollection/DFDevOps/_git/cicd-templates

name: $(BuildVersionPrefix).$(DayOfYear)$(Date:HH)

jobs:
  - job: Build
    pool:
      demands: DotNetFramework
    workspace:
      clean: outputs
    timeoutInMinutes: 180
    steps:
      - checkout: self # self represents the repo where the initial Pipelines YAML file was found
        clean: true
        lfs: true

      - template: ci/ci-build.yml@templates
        parameters:
          releaseBranch: $(ReleaseBranch)
</code></pre>
<p>However, the shared YAML templates often need to execute Powershell code. So far we either embed it or put it in a PS module, which the templates load.</p>
<p>I hate both approaches. I hate embedding because:</p>
<ol>
<li>No intellisens</li>
<li>No unit testing</li>
<li>No proper error reporting on pipeline failures</li>
</ol>
<p>I hate putting in a module, because it is detached from the origin and requires a lot of overhead.</p>
<p>My question - is it possible to have the PS code in dedicated ps1 files in the same repo as the YAML templates and yet have them available at run time?</p>
",https://stackoverflow.com/questions/66159486/how-to-include-ps-code-with-shared-yaml-templates-in-azure-devops-server-2020,"['azure-devops', 'yaml', 'azure-devops-server', 'azure-devops-server-2020']",128,False,0,1
Global mock objects for tests?,"<p>I am creating Spring Boot Web application, and I am using JUnit 5 for unit tests.</p>
<p>I have one concern about unit testing. Is good practice to make some mock objects global in one class, and after just return them with function when we need them in different tests classes?</p>
<p>I am asking this because I recently added one new field in my model class, and needed to modify bunch of test classes and add this field to constructor in every test class.</p>
<p>Lets for example take three classes Semester, Module and Course, where Course have Semester and Module as a fields:</p>
<pre><code>@AllArgsConstructor
public class Module{
  private Long id;
  private String name;
}


@AllArgsConstructor
public class Semester{
  private Long id;
  private LocalDate startingDate;
}

@AllArgsConstructor
public class Course {
  private Long id;
  private String name;
  private Module module;
  private Semester semester;
}
</code></pre>
<p>Now, in all test classes where we need some kind of Course object we will need to create all of them, like this:</p>
<pre><code>private final Module mockModule = Module(1L, &quot;Computer Sciences&quot;);
private final Semester mockSemester = Semester(1L, LocalDate.of(2021, Month.MARCH, 1));
private final Course mockCourse = Course(1L, &quot;DSA&quot;, mockModule, mockSemester); 
</code></pre>
<p>And after some time we discovered that we need one more field in module class, for example codeName:</p>
<pre><code>@AllArgsConstructor
public class Module{
  private Long id;
  private String name;
  private String codeName;
}
</code></pre>
<p>After this one field change, we will need to edit all of the test classes where we are using Module constructor. The same will be if we want to add new field in Semester class.</p>
<p>But in the situation where we have all mock objects in one class, we will need to edit only constructor in this one class, not in all test classes. And the code in test class will be:</p>
<pre><code>private final Course mockCourse = mockObjects.getMockCourse();
</code></pre>
<p>Is there a &quot;cleaner&quot; way of doing this?</p>
<p>I tried to find answer to this, but in all tutorials/articles about unit testing I found that every test class have their own mock objects.</p>
",https://stackoverflow.com/questions/69282121/global-mock-objects-for-tests,"['java', 'unit-testing', 'testing', 'junit', 'spring-test']",294,True,0,1
what is getRepositoryToken in nestjs typeorm and when to use it?,"<p>The docs <a href=""https://docs.nestjs.com/techniques/database#testing"" rel=""noreferrer"">here</a> are as below:</p>
<blockquote>
<p>When it comes to unit testing an application, we usually want to avoid
making a database connection, keeping our test suites independent and
their execution process as fast as possible. But our classes might
depend on repositories that are pulled from the connection instance.
How do we handle that? The solution is to create mock repositories. In
order to achieve that, we set up custom providers. Each registered
repository is automatically represented by a Repository
token, where EntityName is the name of your entity class.</p>
<p>The @nestjs/typeorm package exposes the getRepositoryToken() function
which returns a prepared token based on a given entity.</p>
</blockquote>
<p>What does that even mean? Autocomplete docs just give the signature with no explanation.</p>
",https://stackoverflow.com/questions/65570680/what-is-getrepositorytoken-in-nestjs-typeorm-and-when-to-use-it,"['jestjs', 'nestjs', 'typeorm']",6832,True,9,1
Is it possible to conditionally specify a mocked object that is created after initialization?,"<p>I am wondering if it's possible to create a repository as a mock version (in Swift, using Xcode 12.5) only for unit testing, when that repository is not set at initialization?</p>
<p>I am creating a viewModel that looks at two different types of objects (<code>Foo</code> and <code>FooTwo</code>), and depends on two different repositories (<code>fooRepository</code> (which has a factory type of <code>fooStoreType</code>) and <code>FooTwoRepository</code> (which has a factory type of <code>fooStoreType</code>)).</p>
<p>The <code>fooTwoRepository</code> is dependent on having a <code>featuredFoo</code>, too determine which 'FooTwo' objects should be returned. <code>featuredFoo</code> may not be set until the user takes some action (or at least until a downstream code flow completes), so I am setting the <code>fooTwoRepository(foo: featuredFoo!)</code> as part of a didSet whenever the <code>featuredFoo</code> gets set.</p>
<p>My issue is related to testing. I have a <code>MockFooRepository</code> and a <code>MockFooTwoRepository</code> for my unit tests. When I create the ViewModel in my test class, I can initialize my <code>MockFooRepository</code>, but since my <code>MockFooTwoRepository</code> doesn't get created until this didSet, I don't think I can create it this way.</p>
<p>Is there a good way to create this as the mock version only for unit testing in Xcode?
Or do I need to just create my <code>FooTwoRepository</code> on initialization, and have <code>featuredFoo</code> as an optional value so I don't have to set it right away, and then have it not do anything until <code>featuredFoo</code> gets set (and my didSet would just set <code>featuredFoo</code> in the repository for <code>FooTwo</code>)?</p>
<p>Here's my ViewModel:</p>
<pre><code>class FooViewModel: ObservableObject {
    @Published var fooTwoRepository: FooTwoStoreType?
    @Published var fooRepository: FooStoreType
    
    @Published var featuredFoo: Season? {
        didSet {
            guard featuredFoo != nil else {
                print(&quot;Trying to set FooTwoRepository based on featured Foo. Featured Foo is nil.&quot;)
                return
            }
            
            self.fooTwoRepository = MyFooTwoRepository(foo: featuredFoo!)
        }
    }
    
    
    init(fooRepository: FooStoreType = FooRepository()) {

        self.fooRepository = fooRepository
 
    }
</code></pre>
<p>And for reference, my <code>FooTwoRepository</code> conforms to a factory method, <code>FooTwoStoreType</code>, which my <code>MockFooTwoRepository</code> also conforms to.</p>
<p>But it requires a <code>featuredFoo</code> to loadData, so I wait until the viewModel has gotten a <code>featuredFoo</code> to initialize this repository:</p>
<pre><code>class FooTwoRepository: ObservableObject, FooTwoStoreType {

    var featuredFoo: featuredFoo
    
    init(featuredFoo: featuredFoo) {
        self.featuredFoo = featuredFoo
        loadData()
    }
</code></pre>
",https://stackoverflow.com/questions/68099713/is-it-possible-to-conditionally-specify-a-mocked-object-that-is-created-after-in,"['swift', 'xcode', 'unit-testing', 'mocking']",228,False,0,1
How to unit test calculation in code in nodejs?,"<p>I have below code where I'm adding few parameters. Now I want to check whether this addition is getting performed correctly or not. Below is my code,</p>
<pre><code>&quot;use strict&quot;;

const account = require('account');
async function main() {
  try {
    //calling an API to get data
    const mainData = await account.getData();
    const data = platformEarnings.data.items;
    const first_value =
      data[i].first_value != undefined
        ? data[i].first_value.split(&quot;@&quot;)[1]
        : &quot;0.00&quot;;
    const second_value =
      data[i].second_value != undefined
        ? data[i].second_value.split(&quot;@&quot;)[1]
        : &quot;0.00&quot;;
    const total_value = parseFloat(first_value) + parseFloat(second_value);
    return true;
  } catch (e) {
    logger.error(&quot;Error - [%s]&quot;, e);
    return false;
  }
}
module.exports = main;
</code></pre>
<p>And the test I tried is below,</p>
<pre><code>'use strict';

const { expect } = require('chai');
require('app-module-path').addPath('./src');
const axios = require('axios');
const sinon = require('sinon');
let axiosStub;

describe('Tests', () =&gt; {
  function resetSinon() {
    axiosStub.restore();
    axiosStub.reset();
    sinon.restore();
    sinon.reset();
  }

  context('when appropriate data is returned', () =&gt; {
    let result;
    before(async () =&gt; {
      axiosStub = sinon.stub(axios, 'request').callsFake((req) =&gt; {
          data = { data: {} };
          data.data = {items: [{
            first_value: '@100.00',
            second_value: '@100.00',
          }]
        };
        return data;
      });
      let testData = require('main');
      result = await testData();
    });

    after(() =&gt; {
      resetSinon();
    });

    it('should calculate correct value', async () =&gt; {
      data.data.items.forEach((items) =&gt; {
        let first_value = '0.00';
        let second_value = '0.00';
        if (items.first_value.includes('@')){
            first_value = items.first_value.split('@')[1]
        }
        if (items.second_value.includes('@')){
          second_value = items.second_value.split('@')[1]
        }
        const total_value = parseFloat(first_value) + parseFloat(second_value)
        expect(total_value).to.equal(200)
      });
    });
  });
});
</code></pre>
<p>In above test I'm adding first_value and second_value in test and comparing on next line. But I want to change this where I should be able to check if the addition in actual code is exactly what I am expecting instead of just adding it in test case. Or maybe I have written the test case wrong. Let me know how can I make this test as per my expectation.</p>
<p>I'm new to unit testing in NodeJS so any help would be appreciated.</p>
",https://stackoverflow.com/questions/68057205/how-to-unit-test-calculation-in-code-in-nodejs,"['node.js', 'unit-testing', 'chai', 'sinon', 'sinon-chai']",338,False,3,1
React Unit test using jest failed,"<p>I am doing Unit tests with jest and enzyme. I have following connected component with hooks.
I called redux actions to load data.</p>
<pre><code>import React, {useEffect, useState, useCallBack} from &quot;react&quot;;
import {connect} from &quot;react-redux&quot;;
import CustomComponent  from &quot;../Folder&quot;;
import { loadData, createData, updateData } from &quot;../../redux/actions&quot;;

const AccountComponent = (props) =&gt; {
  const total = 50;
  const [aIndex, setAIndex] = useState(1);
  const [arr, setArr] = useState(['ds,dsf']);
 //... some state variables here

const getData = () =&gt; {
   props.loadData(aIndex, total, arr);
}

useEffect(() =&gt; {

  getData();

},[aIndex, total])

//some other useEffect and useCallback

return(
 &lt;React.Fragment&gt;
   &lt;CustomComponent {...someParam}/&gt;
    &lt;div&gt;
     ...
    &lt;/div&gt;
 &lt;/React.Fragment&gt;
)

}

const mapStateToProps = (state) =&gt; {
 const { param1, param2, parma3 } = state.AccountData;
 return {
  param1,
  param2,
  parma3
 }
}

export default connect(mapStateToProps, { loadData, createData, updateData })(AccountComponent)
</code></pre>
<p>Here, like following I created some test case for above component.</p>
<pre><code>import AccountComponent from &quot;../&quot;;
import React from &quot;react&quot;;
import renderer from &quot;react-test-renderer&quot;

describe(&quot;AccountComponent component&quot;, () =&gt; {

 const loadData = jest.fn();
 let wrapper;

 it(&quot;snapshot testing&quot;, () =&gt; {
  const tree = renderer.create(&lt;AccountComponent loadData={loadData} /&gt;).toJSON();
  expect(tree).toMatchSnapshot();
 })

  beforeEach(() =&gt; {
    wrapper = shallow(&lt;AccountComponent loadData={loadData} /&gt;).instance();
  });

  it('should call loadData', () =&gt; {
    expect(wrapper.loadData).toHaveBeenCalled();
  });
})
</code></pre>
<p>But, It doesn't pass and shows error.</p>
<p>Error for snapshot testing:</p>
<blockquote>
<p>invariant violation element type is invalid: expected string or a class/function</p>
</blockquote>
<p>Error for method call testing:</p>
<blockquote>
<p>Cannot read property 'loadData' of undefined.</p>
</blockquote>
<blockquote>
<p>Enzyme Internal error: Enzyme expects and adapter to be configured, but found none. ...</p>
</blockquote>
<p>Not sure what the issue as I am not good in unit testing.</p>
<p>I am using react-redux 7.</p>
<p>Any help would be greatly appreciated.</p>
<p><strong>Edit:</strong></p>
<p>I also tried with provider like following. But, didn't help.</p>
<pre><code>import { Provider } from &quot;react-redux&quot;;
import {createStore} from &quot;redux&quot;;
import reducer from &quot;../../reducers&quot;;

const store = createStore(reducer);

it(&quot;snapshot testing&quot;, () =&gt; {
      const tree = renderer.create(&lt;Provider store={store}&gt;&lt;AccountComponent loadData={loadData} /&gt;&lt;/Provider&gt;).toJSON();
      expect(tree).toMatchSnapshot();
     })


beforeEach(() =&gt; {
        wrapper = shallow(&lt;Provider store={store}&gt;&lt;AccountComponent loadData={loadData} /&gt;&lt;/Provider&gt;).instance();
      });
</code></pre>
",https://stackoverflow.com/questions/67920606/react-unit-test-using-jest-failed,"['reactjs', 'unit-testing', 'react-redux', 'jestjs']",1348,True,3,3
Jest assert on style after animate is performed,"<p>I have a React Application using Jest and React Testing Library for unit testing. I have difficulties asserting that a component's style has changed. My component takes in an <code>isSelected</code> boolean and performs an animation based on that.</p>
<p>My component: (Using <a href=""https://www.framer.com/docs/examples/"" rel=""nofollow noreferrer"">framer-motion</a>)</p>
<pre><code>
const MotionImage = motion(Image);

const SCALE_SIZE = 1.5;

export interface IPreviewer{
  isSelected: boolean;
}

export function Previewer({
  isSelected,
}: IPreviewer): JSX.Element {

  return (
    &lt;MotionImage
      animate={{
        scale: isSelected ? SCALE_SIZE : 1,
      }}
    /&gt;
  );
}
</code></pre>
<p>My test:</p>
<pre><code>test(&quot;Component when isSelected highlights the image&quot;, () =&gt; {
  const { debug } = render(
    &lt;Previewer
      isSelected
    /&gt;
  );

  const image = screen.getByRole(&quot;img&quot;);

  debug(image);

  expect(image).toHaveStyle(&quot;transform: scale(1.5) translateZ(0)&quot;);
});
</code></pre>
<p>The test debug giving me:</p>
<pre><code>     &lt;img
       class=&quot;chakra-image css-yk396h&quot;
       src=&quot;http://placeimg.com/222.07846627773333/3.4102996091771587&quot;
       style=&quot;transform: none;&quot;
      /&gt;
</code></pre>
<p>As you can see the <code>img</code> is found but the style is not as expected:  <code>style=&quot;transform: none;&quot;</code></p>
<p><strong>I will appreciate any suggestions on how to test this right?</strong></p>
<p><strong>Note</strong></p>
<p>Setting <code>initial={false}</code> to the component itself will make the test pass but will lose the initial animation so I will avoid that.</p>
<p>Introducing a timeOut promise inside the test before asserting will work, but I would like to avoid that as well.</p>
",https://stackoverflow.com/questions/69798944/jest-assert-on-style-after-animate-is-performed,"['reactjs', 'typescript', 'jestjs', 'react-testing-library']",2001,False,3,1
Unit test Polly - Check whether the retry policy is triggered on timeout / error,"<p>Problem stmt : I have a service which fetches result from graphql sometime due to server issue the service might throw 500 error</p>
<p>Solution: To resolve the above issue I needed to write a retry logic to retry the service when timeout occurs.</p>
<p>Obstacle : I don't know how to assert the whether the given logic is calling the service three times as specified. Any help is appreciated.</p>
<p>I created a retry policy to retry if the given client is timeout after some time.</p>
<pre><code>public override void ConfigureServices(IServiceCollection services)
{
  services.AddHttpClient&lt;GraphQueryService&gt;(Constants.PPQClient)
        .ConfigureHttpClient(client =&gt;
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));
            client.Timeout = TimeSpan.FromMilliseconds(Constants.ClientTimeOut);
        }).AddRetryPolicy();
}
</code></pre>
<p>RetryLogic :</p>
<pre><code>using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Polly;

namespace PA.Com.Integration
{
    public static class HttpClientBuilderExtensions
    {
        public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder builder)
        {
            var serviceProvider = builder.Services.BuildServiceProvider();

            var options = serviceProvider.GetRequiredService&lt;IOptions&lt;RetryOptions&gt;&gt;();

            return builder.AddTransientHttpErrorPolicy(b =&gt; b.WaitAndRetryAsync(new[]
            {
                options.Value.RetryDelay1,
                options.Value.RetryDelay2,
                options.Value.RetryDelay3
            }));
        }
    }
}
</code></pre>
<p>I'm new to unit testing I believe I called the code to check the timeout but not sure how to assert whether it is called three time on timeout.</p>
<p>Unit Test I tried:</p>
<pre><code>[Fact]
public async Task Check_Whether_Given_Policy_Executed_OnTimeout()
{
    // Given / Arrange 
    IServiceCollection services = new ServiceCollection();

    bool retryCalled = false;

    HttpStatusCode codeHandledByPolicy = HttpStatusCode.InternalServerError;

   var data =  services.AddHttpClient&lt;GraphQueryService&gt;(Constants.PPQClient)
            .ConfigureHttpClient(client =&gt;
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));
                client.Timeout = TimeSpan.FromMilliseconds(Constants.ClientTimeOut);
            }).AddRetryPolicy()
    .AddHttpMessageHandler(() =&gt; new StubDelegatingHandler(codeHandledByPolicy));

 //Need to Check the retry logic is called three times. Not sure How to continue after this.

    Assert.Equal(codeHandledByPolicy, HttpStatusCode.InternalServerError);
    Assert.True(retryCalled);
}
</code></pre>
",https://stackoverflow.com/questions/68532973/unit-test-polly-check-whether-the-retry-policy-is-triggered-on-timeout-error,"['c#', 'unit-testing', 'dotnet-httpclient', 'polly', 'retry-logic']",4363,True,2,1
How to mock a promise rejection with Jest,"<h2>What am I doing?</h2>
<p>I am following a course on nestjs which has some unit testing it it. I wrote this test that checks the signUp method in an repository class. The problem is that in order to trigger the exceptions the line <code>user.save()</code> should return a promise rejection (simulating some problem writing to db). I tried a few ways (see below) but none that work.</p>
<h2>The problem</h2>
<p>The result is that the test succeeds, but there is an <code>unhandled Promise rejection</code>. This way even if I assert that is does <code>not.toThow()</code> it will succeed with the same <code>unhandled Promise rejection</code></p>
<pre><code>(node:10149) UnhandledPromiseRejectionWarning: Error: expect(received).rejects.toThrow()

Received promise resolved instead of rejected
Resolved to value: undefined
(Use `node --trace-warnings ...` to show where the warning was created)
</code></pre>
<p>How do I make it reject the promise correctly?</p>
<h2>The code</h2>
<p>Below is the code of my test and the function under test.</p>
<pre><code>import { ConflictException } from '@nestjs/common';
import { Test } from '@nestjs/testing';
import { AuthCredentialsDto } from './dto/auth-credentials.dto';
import { UserRepository } from './user.repository';

describe('UserRepository', () =&gt; {
  let userRepository: UserRepository;

  let authCredentialsDto: AuthCredentialsDto = {
    username: 'usahh',
    password: 'passworD12!@',
  };

  beforeEach(async () =&gt; {
    const module = await Test.createTestingModule({
      providers: [UserRepository],
    }).compile();

    userRepository = module.get&lt;UserRepository&gt;(UserRepository);
  });

  describe('signUp', () =&gt; {
    let save: any;
    beforeEach(() =&gt; {
      save = jest.fn();
      userRepository.create = jest.fn().mockReturnValue({ save });
    });

    it('throws a conflict exception if user already exist', () =&gt; {
      // My first try:
      // save.mockRejectedValue({
      //   code: '23505',
      // });

      // Then I tried this, with and without async await:
      save.mockImplementation(async () =&gt; {
        await Promise.reject({ code: '23505' });
      });
      expect(userRepository.signUp(authCredentialsDto)).rejects.toThrow(
        ConflictException,
      );
    });
  });
});


</code></pre>
<p>The function under test here is:</p>
<pre><code>@EntityRepository(User)
export class UserRepository extends Repository&lt;User&gt; {
  async signUp(authCredentialsDto: AuthCredentialsDto): Promise&lt;void&gt; {
    const { username, password } = authCredentialsDto;
    const user = this.create();

    user.salt = await bcrypt.genSalt();
    user.username = username;
    user.password = await this.hashPassword(password, user.salt);

    try {
      await user.save();
    } catch (e) {
      if (e.code === '23505') {
        throw new ConflictException('Username already exists');
      } else {
        throw new InternalServerErrorException();
      }
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/66900133/how-to-mock-a-promise-rejection-with-jest,"['unit-testing', 'promise', 'jestjs', 'nestjs', 'ts-jest']",20938,True,7,1
"Snapshots failing with --watchAll=true, but not --watchAll=false","<p>I'm using jest to run unit testing on a large react project.  Many tests are snapshot tests which make sure the component renders the same every time and that every render matches the snapshot.</p>
<p>I noticed that our test script, which is just <code>react-scripts test</code> is failing, with a handful of failing snapshots since someone made some changes.  However, the script we use for CI/CD is <code>react-scripts test -u --watchAll=false</code>, so that the test suite will exit on completion and continue the CI/CD process.  With the <code>--watchAll-false</code> tag, I dont see any failing snapshots.</p>
<p>Why would that be?  What effect does <code>--watchAll</code> have on snapshot testing?  I can't seem to find any documentation on the relationship between the two.</p>
",https://stackoverflow.com/questions/67438631/snapshots-failing-with-watchall-true-but-not-watchall-false,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'snapshot']",379,False,2,0
How to use correctly MockMvc to test post method in Junit?,"<p>I am unit testing with MockMvc for the first time and I have not figured it out yet how to use it correctly.
I am trying to test a simple POST method.
My code (class code) works good, I tested it with postman, so clearly the problem is with the testing code.</p>
<p>Controller:</p>
<pre><code>@Controller
@RequestMapping(&quot;/employees&quot;)
public class EmployeeController {

    private final EmployeeService employeeService;
    private final EmployeeModelAssembler assembler;

    @Autowired
    public EmployeeController(EmployeeService employeeService, EmployeeModelAssembler assembler){
        this.employeeService = employeeService;
        this.assembler = assembler;
    }

    @PostMapping()
    public ResponseEntity&lt;?&gt; addEmployee(@RequestBody Employee employee, UriComponentsBuilder builder){
        EntityModel&lt;Employee&gt; entityModel = this.assembler.toModel(this.employeeService.addEmployee(employee));
        return ResponseEntity.created(entityModel.getRequiredLink(IanaLinkRelations.SELF).toUri()).body(entityModel);
    }
...

</code></pre>
<p>There are more methods above, but addEmployee is the method i am trying to test.</p>
<p>Test:</p>
<pre><code>@ExtendWith(SpringExtension.class)
@WebMvcTest(EmployeeController.class)
@AutoConfigureMockMvc
public class EmployeeControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private EmployeeService employeeService;

    @MockBean
    private EmployeeModelAssembler assembler;

    @InjectMocks
    private EmployeeController employeeController;

    @Before
    public void setUp(){
        MockitoAnnotations.openMocks(this);
    }


    @Test
    public void testAddEmployee() throws Exception {
        String mockEmployeeJson =
                &quot;    \&quot;firstName\&quot;: \&quot;new\&quot;,\n&quot; +
                &quot;    \&quot;lastName\&quot;: \&quot;Employee\&quot;,\n&quot; +
                &quot;    \&quot;emailAddress\&quot;: \&quot;new@Employee.com\&quot;,\n&quot; +
                &quot;    \&quot;roll\&quot;: \&quot;Software Engineer\&quot;,\n&quot; +
                &quot;    \&quot;team\&quot;: \n&quot; +
                &quot;    {\n&quot; +
                &quot;        \&quot;teamId\&quot;: 1\n&quot; +
                &quot;    }\n&quot; +
                &quot;}&quot;;

        mockMvc.perform(MockMvcRequestBuilders.post(&quot;/employees&quot;)
                .contentType(MediaType.APPLICATION_JSON)
                .content(mockEmployeeJson)
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }
</code></pre>
<p>output:</p>
<pre><code>
MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /employees
       Parameters = {}
          Headers = [Content-Type:&quot;application/json;charset=UTF-8&quot;, Accept:&quot;application/json&quot;, Content-Length:&quot;171&quot;]
             Body =     &quot;firstName&quot;: &quot;new&quot;,
    &quot;lastName&quot;: &quot;Employee&quot;,
    &quot;emailAddress&quot;: &quot;new@Employee.com&quot;,
    &quot;roll&quot;: &quot;Software Engineer&quot;,
    &quot;team&quot;: 
    {
        &quot;teamId&quot;: 1
    }
}
    Session Attrs = {}

Handler:
             Type = com.Ventura.Notifier.controller.EmployeeController
           Method = com.Ventura.Notifier.controller.EmployeeController#addEmployee(Employee, UriComponentsBuilder)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = []
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: Status expected:&lt;200&gt; but was:&lt;400&gt;
Expected :200
Actual   :400
&lt;Click to see difference&gt;
</code></pre>
<p><strong>Edit 1</strong>
changed the test to:</p>
<pre><code>    private Employee employee;

    @BeforeEach
    public void setUpEmployee(){
        Team team = new Team();
        team.setTeamId(1);

        employee = new Employee();
        employee.setTeam(team);
        employee.setRoll(&quot;software developer&quot;);
        employee.setLastName(&quot;Levi&quot;);
        employee.setEmailAddress(&quot;a@a.com&quot;);
        employee.setFirstName(&quot;David&quot;);
    }


    @Test
    public void testAddEmployee() throws Exception {
        ObjectMapper objectMapper = new ObjectMapper();

        mockMvc.perform(MockMvcRequestBuilders.post(&quot;/employees&quot;)
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(employee))
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk());
    }

</code></pre>
<p>but I am getting a null pointer exception.</p>
<p><strong>Edit 2</strong></p>
<p>I solved the null pointer exception, not sure why though. if anyone is interested in the solution:</p>
<p>The test:</p>
<pre><code>@Test
public void testAddEmployee() throws Exception {

    ObjectMapper objectMapper = new ObjectMapper();

    mockMvc.perform(MockMvcRequestBuilders.post(&quot;/employees&quot;)
            .contentType(MediaType.APPLICATION_JSON)
            .content(objectMapper.writeValueAsString(employee))
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().is2xxSuccessful());
}
</code></pre>
<p>and i changed the return statement in the addEmployee method to:</p>
<pre><code>    return new ResponseEntity&lt;&gt;(entityModel, HttpStatus.CREATED);
</code></pre>
",https://stackoverflow.com/questions/65939134/how-to-use-correctly-mockmvc-to-test-post-method-in-junit,"['java', 'spring', 'spring-boot', 'junit', 'mockmvc']",7519,True,2,2
XCTestCase - how to delete app in setup method,"<p>I am writing unit tests for my Swift application and I would like to delete the app in between each test case for certain suites. I already have a script action set up that uninstalls the app before the whole suite runs. But I have not found a way to be able to delete the app off the simulator in between each <code>test</code> invocation. Is there a way to do this?</p>
<p>What I want is:</p>
<pre class=""lang-swift prettyprint-override""><code>import XCTest
@testable import My_App

class MyTests: XCTestCase {

  override func setUpWithError throws () {
    magic(&quot;xcrun simctl uninstall booted ${PRODUCT_BUNDLE_IDENTIFIER}&quot;)
  }
  
  func testTheThings() {
    // test runs with a completely fresh slate...
  }
}
</code></pre>
<p>Please note that this is <strong>unit testing</strong> and not UI testing - so I don't think I can have the test delete the app from the Springboard, which is what I otherwise do in my UI tests to give each test a clean slate.</p>
",https://stackoverflow.com/questions/69147623/xctestcase-how-to-delete-app-in-setup-method,"['swift', 'xctest']",107,False,2,0
How can I unit test my JavaScript code in a way that allows it to be used in a website?,"<p>I have built a web app and I am trying to build out an automated unit testing suite so that I can more easily refactor the code.</p>
<p>I have javascript code that functions correctly on my website. Simple hypothetical code:</p>
<pre><code>function timesTwo(x){x*=2;return x}
</code></pre>
<p>If I were writing my code for NodeJS I would add the tests to confirm that the code is working correctly. Below is an example using Wish and Mocha:</p>
<pre class=""lang-js prettyprint-override""><code>describe('timesTwo()', function() {
  it('multiplies by two', function() {
    var result = timesTwo(5);
    wish(result === 10);
  });
});
</code></pre>

<p>This code (including tests) works fine if I run it in node.JS to test it, but now it throws errors in my browser:</p>
<pre><code>require is not defined

describe is not defined

wish is not defined
</code></pre>
<p>How can I create an automated test suite for my code in a way that doesn't throw errors in the browser?</p>
",https://stackoverflow.com/questions/65871322/how-can-i-unit-test-my-javascript-code-in-a-way-that-allows-it-to-be-used-in-a-w,"['javascript', 'unit-testing', 'mocha.js']",263,True,2,1
How to correctly create Python feature branch releases in development? (pip and PEP-440),"<p>I develop a Python library using <strong>Gitflow</strong> development principle and have a <a href=""https://en.wikipedia.org/wiki/Continuous_integration"" rel=""noreferrer"">CI</a> stage for unit testing and package upload to a (private) PyPI. I want to consume the uploaded package for testing purposes <em>before</em> I merge it back to the integration branch.</p>
<p>Other <a href=""https://learn.microsoft.com/de-de/nuget/concepts/package-versioning"" rel=""noreferrer"">package managers</a> (and <a href=""https://gitversion.net/docs/learn/branching-strategies/gitflow/"" rel=""noreferrer"">popular tools</a>) allow for version identifiers that contain feature branch specific identifiers, such as <code>1.2.3-my-feature-alpha.1</code> in compliance with <a href=""https://semver.org/lang/de/"" rel=""noreferrer"">SemVer</a>. However, <a href=""https://www.python.org/dev/peps/pep-0440/"" rel=""noreferrer"">PEP-440</a> forbids the use of such versioning schemes and <a href=""https://pypi.org/project/twine/"" rel=""noreferrer"">twine</a> even rejects such uploads.</p>
<p>What is the correct (or a workable) approach to name Python package versions if wanting to create such pre-releases (that potentially can happen in parallel with multiple feature branches) without version identifier conflicts in compliance with PEP-440?</p>
",https://stackoverflow.com/questions/69344089/how-to-correctly-create-python-feature-branch-releases-in-development-pip-and,"['python', 'pip', 'continuous-integration', 'git-flow', 'twine']",872,True,6,2
Assert.Contains doesn&#39;t find the object in a list,"<p>I'm new to unit testing, and I wanted to test a method that gets a string array that contains some names like &quot;John,Doe&quot; and then it splits the name by the &quot;,&quot; and populates a list of <code>PersonModel</code> with those names, so I expect that there is a PersonModel with first name John, and last name Doe, in the returned list, but the <code>Assert.Contains</code> method keeps throwing this error:</p>
<blockquote>
<p>Assert.Contains() Failure</p>
<p>Not found: PersonModel { FirstName = &quot;John&quot;, FullName = &quot;John Doe&quot;,
LastName = &quot;Doe&quot; }</p>
<p>In value:  List [PersonModel {
FirstName = &quot;John&quot;, FullName = &quot;John Doe&quot;, LastName = &quot;Doe&quot; },
PersonModel { FirstName = &quot;Jane&quot;, FullName = &quot;Jane Doe&quot;, LastName =
&quot;Doe&quot; }]</p>
</blockquote>
<p>This is the method for converting names to people list in the <code>DataAccess</code> class:</p>
<pre><code>public static List&lt;PersonModel&gt; ConvertCsvNamesToPeopleList(string[] csvContent)
{
    List&lt;PersonModel&gt; output = new List&lt;PersonModel&gt;();

    foreach (string line in csvContent)
    {
        string[] data = line.Split(',');
        output.Add(new PersonModel { FirstName = data[0], LastName = data[1] });
    }

    return output;
}
</code></pre>
<p>And this is the test:</p>
<pre><code>[Fact]
public void ConvertCsvNamesToPeopleList_ValidCsvContent_ShouldWork()
{
    string[] csvContent = { &quot;John,Doe&quot;, &quot;Jane,Doe&quot; };

    var expectedPerson = new PersonModel { FirstName = &quot;John&quot;, LastName = &quot;Doe&quot; };
    var expectedPerson2 = new PersonModel { FirstName = &quot;Jane&quot;, LastName = &quot;Doe&quot; };
    var actual = DataAccess.ConvertCsvNamesToPeopleList(csvContent);

    Assert.Contains(expectedPerson, actual);
    Assert.Contains(expectedPerson2, actual);
}
</code></pre>
<p>The person model:</p>
<pre><code>public class PersonModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName =&gt; $&quot;{ FirstName } { LastName }&quot;;
}
</code></pre>
",https://stackoverflow.com/questions/70438478/assert-contains-doesnt-find-the-object-in-a-list,"['c#', 'unit-testing', 'xunit']",1248,True,1,1
Can I run xUnit tests against classes in my Win Ui 3 Class Library?,"<p>I have created a brand new &quot;Class Library (Win Ui in Desktop)&quot; library via the Add New Project functionality of Visual Studio.</p>
<p>For the purposes of this question I have replaced the name of the library with <code>&lt;MYLIBRARY&gt;</code>.</p>
<p>After creating an &quot;xUnit Test Project&quot;, and selecting &quot;.NET Core 3.1 (Long-term support)&quot; as the Target Framework, then adding a Project Reference to the Class Library, I get these errors:</p>
<pre><code>Error NU1201 Project &lt;MYLIBRARY&gt; is not compatible with netcoreapp3.1 (.NETCoreApp,Version=v3.1). Project &lt;MYLIBRARY&gt; supports: net5.0-windows10.0.19041 (.NETCoreApp,Version=v5.0) &lt;MYLIBRARY&gt;.UnitTests

Error Project '..\&lt;MYLIBRARY&gt;\&lt;MYLIBRARY&gt;.csproj' targets 'net5.0-windows10.0.19041.0'. It cannot be referenced by a project that targets '.NETCoreApp,Version=v3.1'. &lt;MYLIBRARY&gt;.UnitTests C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets 1718
</code></pre>
<p>After deleting that test project, and creating a new &quot;xUnit Test Project&quot; and selecting &quot;.NET 5 (Current)&quot; as the Target Framework, then adding a Project Reference to the Class Library, I get these errors:</p>
<pre><code>Error NU1201 Project &lt;MYLIBRARY&gt; is not compatible with net5.0 (.NETCoreApp,Version=v5.0). Project &lt;MYLIBRARY&gt; supports: net5.0-windows10.0.19041 (.NETCoreApp,Version=v5.0) &lt;MYLIBRARY&gt;.UnitTests

Error Project '..\&lt;MYLIBRARY&gt;\&lt;MYLIBRARY&gt;.csproj' targets 'net5.0-windows10.0.19041.0'. It cannot be referenced by a project that targets '.NETCoreApp,Version=v5.0'. &lt;MYLIBRARY&gt;.UnitTests C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets 1718
</code></pre>
<p>In the .csproj of the unit test project I tried changing <code>&lt;TargetFramework&gt;net5.0&lt;/TargetFramework&gt;</code> to <code>&lt;TargetFramework&gt;net5.0-windows&lt;/TargetFramework&gt;</code> but that didn't fix anything.</p>
<p>I've looked around at various websites but I found some answers that seemed to say that I should be able to do what I want as &quot;Unit testing frameworks like xUnit.net are generally agnostic of the libraries that your production code uses.&quot;, without explanation of how to get it working if it's not, and others which say that I can't do what I want because xUnit and Win Ui 3 are not compatible yet, e.g. &quot;WinUI 3 does not currently support any of the .NET unit testing frameworks.&quot;.</p>
<p>I did some searches of Stack Overflow - for Win Ui / xUnit / etc. - but none of the results I found were of any use to me.</p>
<p>Is it possible for me to run xUnit unit tests against the classes in my Class Library?</p>
<p>(I might be getting some things mixed up because this is my first Win Ui project.)</p>
",https://stackoverflow.com/questions/70004920/can-i-run-xunit-tests-against-classes-in-my-win-ui-3-class-library,"['xunit', 'winui-3']",516,True,2,1
How would I Unit Test these Serialization/Deserialization methods in C#?,"<p>I am currently trying to write some Unit Tests for a project of mine that stores lists of details about sessions in a gym and have no idea how to do so as Unit Testing is rather new to me. The method to serialize is SaveState() and the method to deserialize is LoadState() and both work perfectly fine when ran thankfully, I just need to write some unit tests to prove that at quickly. The list(session) that allSessions takes from is from another class that holds the data but I don't know if that is actually needed when testing or if you just substitute something else in within the test itself. Any help is greatly appriciated.</p>
<pre><code>    public class SessionsManager
    {
        const string FILENAME = &quot;SessionFile.dat&quot;;
        //declare private list for events 
        private List&lt;Session&gt; allSessions;

        // Public Property
        public List&lt;Session&gt; AllSessions { get =&gt; allSessions; set =&gt; allSessions = value; }

        //creating constructor to hold lists 
        public SessionsManager()
        {
            AllSessions = new List&lt;Session&gt;();
        }

        public void SaveState()
        {
            
            //Formatter object
            BinaryFormatter biFormatter = new BinaryFormatter();

            //stream object to create file types
            FileStream outFile = new FileStream(FILENAME, FileMode.Create, FileAccess.Write);

            //Save the whole list in one
            biFormatter.Serialize(outFile, allSessions);

            //Close the stream, dont want them crossing after all
            outFile.Close();
        }

        public void LoadState()
        {
            //Formatter object
            BinaryFormatter biiFormatter = new BinaryFormatter();

            //stream object to read file
            FileStream InFile = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);

            //Deserialise the whole list
            allSessions = ((List&lt;Session&gt;)biiFormatter.Deserialize(InFile));

            //close stream
            InFile.Close();
        }

    }

</code></pre>
",https://stackoverflow.com/questions/65595654/how-would-i-unit-test-these-serialization-deserialization-methods-in-c,"['c#', 'list', 'unit-testing', 'serialization', 'deserialization']",671,True,1,1
C# Xunit testing a list that must contain 4 of each value,"<p>So I'm practicing unit testing (Xunit) and C#. I'm making a poker game console application. I have a card deck that is a list of 52 cards. The list is made of Card class and each card has an int value that represents what card it is eg value 1 is ace and value 13 is king.
How could I make an unit test that checks that the list of 52 cards has 4 of each value? I'm just doing it for practice and can't think of an unit test that's not too complicated.</p>
<p>Here's the card class very simple:</p>
<pre><code>public class Card
{
    public enum Suit
    {
        HEART = 1,
        SPADE,
        CLUB,
        DIAMOND
    }

    public int value { get; set; }
    public int suit { get; set; }
    public char letter { get; set; }
}
</code></pre>
<p>CreateDeck() method creates and returns the card deck:</p>
<pre><code>public class CardDeck
{
    public static List&lt;Card&gt; CreateDeck()
    {
        List&lt;Card&gt; cardDeck = new List&lt;Card&gt;();
        int maxCards = 52;

        int currentCardValue = 1;
        int currentSuitValue = 1;
        
        for (int i = 0; i &lt; maxCards; i++)
        {
            cardDeck.Add(new Card { value = currentCardValue, suit = currentSuitValue, letter = Card.ReturnLetter(currentCardValue) });
            currentSuitValue++;
            if (currentSuitValue &gt; 4) { currentSuitValue = 1; }
            //After 4 cards of the same value we raise the cards value
            if(i + 1 % 4 == 0)
            {
                currentCardValue++;
            }
        }
        return cardDeck;
    }
}
</code></pre>
<p>So I want to make a Xunit test:</p>
<pre><code> [Fact]
        public void CardDeck_ShouldHave4CardsOfEachValue()
        {
            List&lt;Card&gt; cardDeck = CardDeck.CreateDeck();

            ??????

        }
</code></pre>
",https://stackoverflow.com/questions/65943988/c-xunit-testing-a-list-that-must-contain-4-of-each-value,"['c#', 'unit-testing', 'xunit']",398,True,1,2
Why is Mocha &amp; Chia unit test failing to catch expected error in web-component constructor?,"<p>I have a unit testing set up using Mocha and Chia run in a Chrome browser as shown below. To enforce the Component class' static htmlTagName property, I am using an error in the Component base-class that gets thrown if the htmlTagName property is not overwritten by a child class. The problem that I am encountering is that the error thrown in the constructor does not appear to be caught by chia.assert.throw(...) instead it causes the test to fail as shown in the link below. The behavior I expected to see is that chia catches the expected error and the test passes. I have included the relevant code below.</p>
<p><a href=""https://i.stack.imgur.com/hg1Lv.png"" rel=""nofollow noreferrer"">Unit-test error result image</a></p>
<pre class=""lang-html prettyprint-override""><code>&lt;!DOCTYPE html&gt;
&lt;!-- index.html --&gt;
&lt;html&gt;
  &lt;head&gt;
    &lt;title&gt;Mocha Tests&lt;/title&gt;
    &lt;link rel=&quot;stylesheet&quot; href=&quot;../../node_modules/mocha/mocha.css&quot;&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;div id=&quot;mocha&quot;&gt;&lt;/div&gt;
    &lt;script src=&quot;../../node_modules/mocha/mocha.js&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;../../node_modules/chai/chai.js&quot;&gt;&lt;/script&gt;
    &lt;script type=&quot;module&quot; class=&quot;mocha-init&quot;&gt;mocha.setup('bdd')&lt;/script&gt;

    &lt;!-- load code you want to test here --&gt;

    &lt;!-- load your test files here --&gt;
    &lt;script type='module' src=&quot;./objective-styles.test.js&quot;&gt;&lt;/script&gt;
    &lt;script type='module' src=&quot;./base-classes.test.js&quot;&gt;&lt;/script&gt;
    &lt;script type='module' src=&quot;./calendar-widget.test.js&quot;&gt;&lt;/script&gt;

    &lt;script type=&quot;module&quot;&gt;
      mocha.run();
    &lt;/script&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<pre class=""lang-js prettyprint-override""><code>//base-classes.ts
export class Component extends HTMLElement {

    static htmlTagName: string | undefined;

    constructor() {
        super();

        // Enforce classes having htmlTagName
        if(!this.htmlTagName) {
            throw (`${this.constructor.name} htmlTagName property is undefined`);
        }
    }

    get htmlTagName() {
        return this.constructor.htmlTagName;
    }

    set htmlTagName(htmlTagName: string) {
        this.constructor.htmlTagName = htmlTagName;
    }
}


</code></pre>
<pre class=""lang-js prettyprint-override""><code>// base-classes.test.ts
import { GuiTestingUtils } from &quot;./gui-testing-utils.js&quot;;
import { Component, Widget} from &quot;../../app/js/widgets/base-classes.js&quot;;


describe(&quot;Component test suite&quot;, ()=&gt;{

    let sandbox: HTMLDivElement;
    let fakeDOM: ShadowRoot;
    let style: HTMLStyleElement;

    before(()=&gt;{
        // set up the sandbox
        let body = document.querySelector('body');
        sandbox = GuiTestingUtils.addSandbox(body!);
        fakeDOM = sandbox.shadowRoot!;
        style = document.createElement('style');
    });

    beforeEach(()=&gt;{
        // clean the sandbox
        GuiTestingUtils.refreshSandbox(sandbox);
        fakeDOM.appendChild(style);
    });

    after(()=&gt;{
        // tear down the sandbox
        let body = document.querySelector('body');
        body!.removeChild(sandbox);
    });

    it(&quot;Component does throw error if htmlTagName is not defined&quot;, ()=&gt;{
        // chia.assert.throw does not catch the error as expected...
        customElements.define(&quot;base-component&quot;, Component);
        chai.assert.throw(()=&gt;{
            document.createElement(&quot;base-component&quot;);
        });
    });
});
</code></pre>
",https://stackoverflow.com/questions/68614330/why-is-mocha-chia-unit-test-failing-to-catch-expected-error-in-web-component-c,"['unit-testing', 'mocha.js', 'web-component', 'typescript']",78,False,1,0
Comparing 2 Soap Requests in Karate framework,"<p>I am new to webservice testing and I have started learning Karate to test APIs. I have been successful in building a basic smoke test suite that runs to see if the API is returning the right response using Karate framework.</p>
<p>I want to extend my validation of APIs further. What I want to achieve is - if a API has changed/updated, how do I know of those changes if no one told me?[in a big organization sometimes its hard to know if someone has made a change and checked in their code with some unit testing].
Is there a way to compare the 2 soap requests and pin-point what has changed?</p>
",https://stackoverflow.com/questions/70387200/comparing-2-soap-requests-in-karate-framework,['karate'],101,False,1,0
Angular library include stubs and testing helper files,"<p>I have a simple Angular library for internal use with some pipes and directives, the library is used in several projects.
When the developers need to write the unit testing, they are creating a stub file for the pipe. They have the same stub in 5 projects duplicate always the same code.</p>
<p>What I want to do is provide this stub file for the pipe or directive, something similar to what does the <code>RouterTestingModule</code>, including a test module or include the stub itself inside my library, but I don't have any clue of how to do it.</p>
<p>Should I have to create a <code>LibraryTestingModule</code> and include it inside the main <code>public_api</code> and also include it in <code>LibraryModule</code>, that make sense?</p>
",https://stackoverflow.com/questions/66168538/angular-library-include-stubs-and-testing-helper-files,"['angular', 'stub', 'angular-library']",325,True,1,1
Is possible run command on different terminal on Github action?,"<p>1.Currently, I'm building a flask project and I also wrote some unit testing code. Now I would like to run the Unit test on the GitHub action, but it stuck at the ./run stage(./run will turn on the <a href=""http://127.0.0.1:5000/"" rel=""nofollow noreferrer"">http://127.0.0.1:5000/</a>), and does not run the $pytest command. I know the reason why $pytest will not be executed because the Github Action is running the port  <a href=""http://127.0.0.1:5000/"" rel=""nofollow noreferrer"">http://127.0.0.1:5000/</a>. In this case, it can not execute any commands after./run. I was wondering can I run $pytest on another terminal in GitHub action? Is this possible?</p>
<p>Here is the output of my github action:</p>
<pre><code>Run cd Flask-backend
  cd Flask-backend
  ./run
  pytest 
  shell: /usr/bin/bash -e {0}
  env:
    pythonLocation: /opt/hostedtoolcache/Python/3.8.10/x64
 * Serving Flask app 'app.py' (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 404-425-256
</code></pre>
<p>2.Here is my code for yml file:</p>
<pre><code>name: UnitTesting
on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Install Python 3
        uses: actions/setup-python@v1
        with:
          python-version: 3.8
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirement.txt
          
      - name: Run tests with pytest
        run: |
           cd Flask-backend
           ./run
           pytest 
</code></pre>
",https://stackoverflow.com/questions/67645636/is-possible-run-command-on-different-terminal-on-github-action,"['flask', 'github', 'github-actions']",836,True,1,2
Check created queries with Entity Manager when unit testing in Spring Boot,"<p>I'm currently building an API using springboot. In my service layer, I used entity manager to create queries. As an example,</p>
<pre><code>public Object editFeedback(Long user_id, Long reservation_id, String feedback){
    String s = &quot;select r from  Reservation  r left join fetch r.driverAssignment where r.id=:id and r.reservation_done_by.id=:user_id &quot;;
    List&lt;Reservation&gt; reservations = em.createQuery(s).setParameter(&quot;id&quot;, reservation_id).setParameter(&quot;user_id&quot;, user_id).getResultList();
    if (reservations.size() == 0)
        return new DefaultResponseDTO(201, ResponseStatus.INVALID_INPUTS, &quot;Wrong reservation id&quot;);
    Reservation reservation = reservations.get(0);
    reservation.setFeedback(feedback);
    reservationRepository.save(reservation);
    return new DefaultResponseDTO(200, ResponseStatus.OK, &quot;Successfully done&quot;);

}
</code></pre>
<p>My question is when writing unit tests for methods in the service layer, how can I check those queries are working correctly without affecting or fetching data from the original database?</p>
<p>For additional details, If I get data from the original database to check the query, then the output changes from time to time. So, I have to mock the Entity manager. Then the queries don't get checked.</p>
<pre><code>  Query query = Mockito.mock(Query.class);
  Mockito.when(em.createQuery(Mockito.anyString())).thenReturn(query);
  Mockito.when(query.getResultList()).thenReturn(sampleReservations.getReservationsForUserReservations());
</code></pre>
<p>Is there any proper way to check that queries are working fine using a mocked entity manager? or If I have understood unit testing wrongly or any other suggestions?</p>
",https://stackoverflow.com/questions/69395276/check-created-queries-with-entity-manager-when-unit-testing-in-spring-boot,"['java', 'spring-boot', 'unit-testing', 'mocking', 'entitymanager']",615,True,1,1
How to create a simple unit test in flutter for user input validation and maxLength with null safety,"<p>I am trying to do simple unit test for the form I have created. I referred some documents and YouTube videos to do that. But there are not many resources for unit testing in form and the available once are not compatible with current version (null safety).</p>
<p>Can any one explain me how I can do a unit test for my validation part and for maxLength in form field.</p>
<p>This is the code I tried but it is showing error and unable to continue.</p>
<pre><code>class FullNameValidator{
  static String? validate(String value){
    return value.isEmpty ? 'Please enter full name' : null;
  }
}
</code></pre>
<hr />
<pre><code>              TextFormField(
                  decoration: InputDecoration(
                    labelText: &quot;FullName&quot;,
                    labelStyle: TextStyle(color: Colors.black),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                  maxLength: 30,
                  keyboardType: TextInputType.text,
                  controller: fullName,
                  validator: FullNameValidator.validate, //Showing error in here
                ),
</code></pre>
<p><a href=""https://i.stack.imgur.com/4ahAc.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4ahAc.png"" alt=""Error"" /></a></p>
<p>The test I tried</p>
<pre><code>void main(){
  test('empty email returns error string', (){
    var result = FullNameValidator.validate(&quot;&quot;);
    expect(result, 'Please enter your full name');
  });
}
</code></pre>
<p>Can anyone please explain how to do unit test for validation and maxLength.
I searched every document/ video I can, but unable to find a solution. Please help</p>
",https://stackoverflow.com/questions/69588654/how-to-create-a-simple-unit-test-in-flutter-for-user-input-validation-and-maxlen,"['flutter', 'unit-testing', 'flutter-test']",740,True,1,1
Unit Test with InMemory Database gives &quot;Unable to track an instance of type &#39;VwCustomerUser&#39; because it does not have a primary key&quot;,"<p>I am trying to use In memory database unit testing to test my Entity Framework DbContext class as per <a href=""https://www.thecodebuzz.com/dbcontext-mock-and-unit-test-entity-framework-net-core/comment-page-1/?unapproved=3553&amp;moderation-hash=befd47d3c1cab4bc7716b080618b2a0b#comment-3553"" rel=""nofollow noreferrer"">https://www.thecodebuzz.com/dbcontext-mock-and-unit-test-entity-framework-net-core/comment-page-1/?unapproved=3553&amp;moderation-hash=befd47d3c1cab4bc7716b080618b2a0b#comment-3553</a></p>
<p>I am able to generate a DbContext in memory for my entities and test my code. However, one of my entities comes from a view, and does not have a primary key. When I populate my DbContext like, e.g.,</p>
<pre><code>    context.MyView.Add(new MyView { 
        Country = “USA”, 
        State = “NY”, 
        Address = “Test1”, 
        ZipCode = “121312” 
     }); 
</code></pre>
<p>I get the error: “Unable to track an instance of type ‘MyView’ because it does not have a primary key. Only entity types with primary keys may be tracked.”.</p>
<p>Could anybody please advise? Thank you so much.</p>
<p>Ray</p>
",https://stackoverflow.com/questions/68718533/unit-test-with-inmemory-database-gives-unable-to-track-an-instance-of-type-vwc,"['c#', 'entity-framework', 'unit-testing', 'entity-framework-core', 'in-memory-database']",889,False,1,0
pytest does not find tests when structlog is configured,"<p>I have a python project where I use pytest for my unit testing.</p>
<p>Normally if I run the following command from my test folder:</p>
<pre><code>pytest --collect-only
</code></pre>
<p>I will get all my tests:</p>
<pre><code>...
40 tests collected
...
</code></pre>
<p>Now let's say I define a new class <strong>structlogconf.py</strong> (Based on this <a href=""https://www.structlog.org/en/17.1.0/standard-library.html?highlight=re#rendering-using-structlog-based-formatters-within-logging"" rel=""nofollow noreferrer"">example</a>)</p>
<pre><code>import logging
import logging.config
import structlog


def configure() -&gt; None:
    timestamper = structlog.processors.TimeStamper(fmt=&quot;%Y-%m-%d %H:%M:%S&quot;)
    pre_chain = [
        # Add the log level and a timestamp to the event_dict if the log entry
        # is not from structlog.
        structlog.stdlib.add_log_level,
        timestamper,
    ]

    logging.config.dictConfig(
        {
            &quot;version&quot;: 1,
            &quot;disable_existing_loggers&quot;: False,
            &quot;formatters&quot;: {
                &quot;plain&quot;: {
                    &quot;()&quot;: structlog.stdlib.ProcessorFormatter,
                    &quot;processor&quot;: structlog.dev.ConsoleRenderer(colors=False),
                    &quot;foreign_pre_chain&quot;: pre_chain,
                },
                &quot;colored&quot;: {
                    &quot;()&quot;: structlog.stdlib.ProcessorFormatter,
                    &quot;processor&quot;: structlog.dev.ConsoleRenderer(colors=True),
                    &quot;foreign_pre_chain&quot;: pre_chain,
                },
            },
            &quot;handlers&quot;: {
                &quot;default&quot;: {
                    &quot;level&quot;: &quot;DEBUG&quot;,
                    &quot;class&quot;: &quot;logging.StreamHandler&quot;,
                    &quot;formatter&quot;: &quot;colored&quot;,
                },
                &quot;file&quot;: {
                    &quot;level&quot;: &quot;DEBUG&quot;,
                    &quot;class&quot;: &quot;logging.handlers.WatchedFileHandler&quot;,
                    &quot;filename&quot;: &quot;test.log&quot;,
                    &quot;formatter&quot;: &quot;plain&quot;,
                },
            },
            &quot;loggers&quot;: {
                &quot;&quot;: {
                    &quot;handlers&quot;: [&quot;default&quot;, &quot;file&quot;],
                    &quot;level&quot;: &quot;DEBUG&quot;,
                    &quot;propagate&quot;: True,
                },
            },
        }
    )
    structlog.configure(
        processors=[
            structlog.stdlib.add_log_level,
            structlog.stdlib.PositionalArgumentsFormatter(),
            timestamper,
            structlog.processors.StackInfoRenderer(),
            structlog.processors.format_exc_info,
            structlog.stdlib.ProcessorFormatter.wrap_for_formatter,
        ],
        logger_factory=structlog.stdlib.LoggerFactory(),
        wrapper_class=structlog.stdlib.BoundLogger,
        cache_logger_on_first_use=True,
    )
</code></pre>
<p>If now I run the pytest collect command again, pytest will not recover any test suite which import directly or indirectly the <em>configure()</em> function from the <strong>structlogconf.py</strong>. So I now obtain someting like:</p>
<pre><code>...
5 tests collected
...
</code></pre>
<p>Is there anyone here which know how to use a <a href=""https://www.structlog.org/en/17.1.0/standard-library.html?highlight=re#rendering-using-structlog-based-formatters-within-logging"" rel=""nofollow noreferrer"">struct log conf</a> in a way that won't affect my pytest tests dicscovery?</p>
<p><strong>FYI</strong>: Here is the stacktrace when running the collect in the problematic scenario:</p>
<pre><code>... 
my remaining 5 tests which does not indirectly import my configure() function are showing here
...
================================================================== 5 tests collected in 1.03s ===================================================================
Traceback (most recent call last):
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\main.py&quot;, line 269, in wrap_session
    session.exitstatus = doit(config, session) or 0
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\main.py&quot;, line 322, in _main
    config.hook.pytest_collection(session=session)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_hooks.py&quot;, line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_manager.py&quot;, line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_callers.py&quot;, line 60, in _multicall
    return outcome.get_result()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_result.py&quot;, line 60, in get_result
    raise ex[1].with_traceback(ex[2])
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_callers.py&quot;, line 39, in _multicall
    res = hook_impl.function(*args)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\main.py&quot;, line 333, in pytest_collection
    session.perform_collect()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\main.py&quot;, line 634, in perform_collect
    self.items.extend(self.genitems(node))
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\main.py&quot;, line 811, in genitems
    yield from self.genitems(subnode)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\main.py&quot;, line 808, in genitems
    rep = collect_one_node(node)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\runner.py&quot;, line 458, in collect_one_node
    rep: CollectReport = ihook.pytest_make_collect_report(collector=collector)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_hooks.py&quot;, line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_manager.py&quot;, line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_callers.py&quot;, line 55, in _multicall
    gen.send(outcome)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 796, in pytest_make_collect_report
    out, err = self.read_global_capture()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 718, in read_global_capture
    return self._global_capturing.readouterr()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 622, in readouterr
    err = self.err.snap()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 479, in snap
    self.tmpfile.seek(0)
ValueError: I/O operation on closed file.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\main.py&quot;, line 289, in wrap_session
    config.notify_exception(excinfo, config.option)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\config\__init__.py&quot;, line 1037, in notify_exception
    res = self.hook.pytest_internalerror(excrepr=excrepr, excinfo=excinfo)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_hooks.py&quot;, line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_manager.py&quot;, line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_callers.py&quot;, line 60, in _multicall
    return outcome.get_result()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_result.py&quot;, line 60, in get_result
    raise ex[1].with_traceback(ex[2])
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_callers.py&quot;, line 39, in _multicall
    res = hook_impl.function(*args)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 826, in pytest_internalerror
    self.stop_global_capturing()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 693, in stop_global_capturing
    self._global_capturing.pop_outerr_to_orig()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 573, in pop_outerr_to_orig
    out, err = self.readouterr()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 622, in readouterr
    err = self.err.snap()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 479, in snap
    self.tmpfile.seek(0)
ValueError: I/O operation on closed file.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\runpy.py&quot;, line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\runpy.py&quot;, line 87, in _run_code
    exec(code, run_globals)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\Scripts\pytest.exe\__main__.py&quot;, line 7, in &lt;module&gt;
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\config\__init__.py&quot;, line 185, in console_main
    code = main()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\config\__init__.py&quot;, line 162, in main
    ret: Union[ExitCode, int] = config.hook.pytest_cmdline_main(
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_hooks.py&quot;, line 265, in __call__
    return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_manager.py&quot;, line 80, in _hookexec
    return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_callers.py&quot;, line 60, in _multicall
    return outcome.get_result()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_result.py&quot;, line 60, in get_result
    raise ex[1].with_traceback(ex[2])
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\pluggy\_callers.py&quot;, line 39, in _multicall
    res = hook_impl.function(*args)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\main.py&quot;, line 316, in pytest_cmdline_main
    return wrap_session(config, _main)
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\main.py&quot;, line 311, in wrap_session
    config._ensure_unconfigure()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\config\__init__.py&quot;, line 991, in _ensure_unconfigure
    fin()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 693, in stop_global_capturing
    self._global_capturing.pop_outerr_to_orig()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 573, in pop_outerr_to_orig
    out, err = self.readouterr()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 622, in readouterr
    err = self.err.snap()
  File &quot;C:\Users\MY_USER\.conda\envs\MY_ENV\lib\site-packages\_pytest\capture.py&quot;, line 479, in snap
    self.tmpfile.seek(0)
ValueError: I/O operation on closed file.
</code></pre>
",https://stackoverflow.com/questions/70087443/pytest-does-not-find-tests-when-structlog-is-configured,"['python', 'pytest', 'structlog']",267,False,1,1
How to implement e2e testing in Nest JS Framework,"<p>I am new this Framework. I implemented crud operation, migration, unit testing also but I do know how to implement e2e testing in nest JS Framework. I tried to run the e2e testing program it's throwing an error
How to fix this error. I tried many ways but I could not get the solution
<a href=""https://i.stack.imgur.com/5hjwa.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/5hjwa.png"" alt=""enter image description here"" /></a>It showing this error <strong>No repository for &quot;UserEntity&quot; was found. Looks like this entity is not registered in current &quot;default&quot; connection?</strong>. So, I tried to change my database configuration</p>
<p><strong>Database configuration</strong></p>
<pre><code>{
              type: 'postgres',
              host:  process.env[`${process.env.NODE_ENV}_POSTGRES_HOST`],
              port: parseInt(process.env[`${process.env.NODE_ENV}_POSTGRES_PORT`]) || 5432,
              username: process.env[`${process.env.NODE_ENV}_POSTGRES_USER`],
              password: process.env[`${process.env.NODE_ENV}_POSTGRES_PASSWORD`],
              database: process.env[`${process.env.NODE_ENV}_POSTGRES_DATABASE`],
              entities: [&quot;dist/**/*.entity{ .ts,.js}&quot;],
              migrations: [&quot;dist/database/migration/*.js&quot;],
              cli:{
                  migrationsDir: 'src/database/migration',
                  }
            }
</code></pre>
<p>This problem is occurred in the <strong>entities column</strong> in the database configuration. If I change the entities directory the application cannot run. how to fix this issue</p>
<p><strong>tsconfig.json</strong></p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;module&quot;: &quot;commonjs&quot;,
    &quot;declaration&quot;: true,
    &quot;removeComments&quot;: true,
    &quot;emitDecoratorMetadata&quot;: true,
    &quot;experimentalDecorators&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;target&quot;: &quot;es2017&quot;,
    &quot;sourceMap&quot;: true,
    &quot;outDir&quot;: &quot;./dist&quot;,
    &quot;baseUrl&quot;: &quot;./&quot;,
    &quot;incremental&quot;: true
  }
}
</code></pre>
",https://stackoverflow.com/questions/66988418/how-to-implement-e2e-testing-in-nest-js-framework,"['node.js', 'nestjs', 'nestjs-swagger', 'nestjs-config', 'nestjs-passport']",6361,True,1,1
Typescript circular reference when testing prisma with jest-mock-extended,"<p>I started writting tests revolving around prisma(v3.6.0) usage in my application.</p>
<p>To do so I followed the official prisma page <a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""noreferrer"">Unit testing with prisma</a> and I am using <code>jest-mock-extended</code>.</p>
<p>My issue is that I have a typescript error when using the mocked prisma functions :</p>
<pre class=""lang-js prettyprint-override""><code>describe('User routes', () =&gt; {
    it('should respond success with array of users', async () =&gt; {
        prismaMock.user.findMany.mockResolvedValue([]); // &lt;- here is the error
    }
}
</code></pre>
<pre><code>Type of property 'AND' circularly references itself in mapped type 
</code></pre>
<p>There is some discussion about this issue on github <a href=""https://github.com/prisma/prisma/discussions/2083#discussioncomment-559689"" rel=""noreferrer"">Testing with prisma</a>. I got 3 options from this discussion :</p>
<ul>
<li>Adding <code>&quot;skipLibCheck&quot;: true</code> in tsconfig.json. This breaks some things in my code and doesn't resolve my issue</li>
<li>Adding <code>&quot;strictNullChecks&quot;: true</code>, no effect either</li>
<li><code>//@ts-ignore</code> the line. This effectively remove the error, and the test runs smoothly</li>
</ul>
<p>While I am able to do my tests, I would like not to have to ignore this error everywhere in my tests, and ignoring errors is only a good idea until it's not.</p>
<p>Does someone have more information or recommendations about this issue ?</p>
",https://stackoverflow.com/questions/70433672/typescript-circular-reference-when-testing-prisma-with-jest-mock-extended,"['typescript', 'testing', 'prisma', 'jest-mock-extended']",1490,False,15,1
How to unit test a WPF application which uses XamlIslands?,"<p>I'm developing a <code>WPF</code> application and I'm using <code>Xaml Islands</code> to display win10 UI components. For this I needed to create a UWP project where I can implement those components.</p>
<p>I'd like to write unit tests for my business logic, which is in the WPF project. I can't create a <code>Unit Test App (Universal Windows)</code>, because it's not possible to add as a reference to this project the WPF app. So I tried to create a testing project, which targets .NET Core (tried <code>MSTest Project</code> and <code>xUnit Test Project</code>), but as I add to the references my WPF app, it shows the following error:</p>
<p><code>Project &lt;UWP...&gt; is not compatible with netcoreapp3.1 (.NETCoreApp,Version=v3.1). Project &lt;UWP...&gt; supports: uap10.0.18362 (UAP,Version=v10.0.18362)</code></p>
<p>This is because the WPF app references the UWP app, to display the win10 components.</p>
<p>So, any idea, how can I add unit testing project to my solution?</p>
",https://stackoverflow.com/questions/66371462/how-to-unit-test-a-wpf-application-which-uses-xamlislands,"['c#', 'wpf', 'unit-testing', 'uwp', 'xaml-islands']",366,True,0,1
"not sure what to test exactly in white box testing, is it each function?","<p>this is probably the wrong place to ask but i searched and couldn't find an answer, i have a website, i want to do white box testing, first of all i don't know what type of white box testing i should use, should i use line coverage? or branch coverage? and what exactly is tested? is it each function by it's own? what if there's an if statement not in a function? is me choosing a function to test is unit testing?</p>
<p>my code has multiple classes and multiple functions in each class, there's a handler page that calls each class function based on what form was submitted, should i test the handler page too?</p>
<p>handler page</p>
<pre><code>switch ($_POST['formSubmit']) {
    
case 'complete-regP':

$passenger = new LogRegValidation();
$passenger-&gt;userInfoValidate();

break;
</code></pre>
<p>logRegValidation class</p>
<pre><code>function userInfoValidate();
{
//code
}

function  function loginValidate()
{
//code
}

</code></pre>
",https://stackoverflow.com/questions/68783176/not-sure-what-to-test-exactly-in-white-box-testing-is-it-each-function,"['php', 'testing']",39,False,0,0
django Testing views works only with a primary key,"<p>I am working on a django project. i have build the front end and back-end. now i want to write unit test.</p>
<p>i want to test a class based view for creating,deleting and retrieving blog post from url '''path('posts/', Postview.as_view(),name=&quot;posts&quot;),'''
my Postview view is here:</p>
<pre><code>class Postview(views.APIView, LimitOffsetPagination):
    authentication_classes = [TokenAuthentication, ]
    permission_classes = [IsAuthenticated, ]

    def get(self, request, pk=None):
        if pk:
            try:
                query = Post.objects.filter(pk=pk)
                # print(query)
                print(&quot;in post get&quot;)
                serializer = PostSerializer(
                    query, many=True, context={'request': request})
                data = commonPost(serializer.data, request)
                return Response(data)
            except:
                return Response({&quot;message&quot;: &quot;No Data found&quot;})
        else:
            query = Post.objects.all().order_by('-id')
            serializer = PostSerializer(
                query, many=True, context={'request': request})
            data = commonPost(serializer.data, request)
            return Response(data)

    def post(self, request, pk=None):
        if pk:
            snapshot = Post.objects.get(pk=pk)
            serializers = PostSerializer(
                snapshot, data=request.data, context={'request': request})
            if serializers.is_valid():
                serializers.save()
                return Response({'error': False})
            return Response({'error': True})
        else:
            serializer = PostSerializer(
                data=request.data, context={'request': request})
            if serializer.is_valid():
                serializer.save()
                return Response({'error': False})
            return Response({'error': True})

    def delete(self, request, pk):
        try:
            snippet = Post.objects.get(pk=pk)
            if snippet.profile.id == request.user.profile.id:
                snippet.delete()
                return Response({&quot;error&quot;: False})
            else:
                return Response({&quot;error&quot;: True})
        except:
            return Response({&quot;message&quot;: &quot;No data found for this ID&quot;})
</code></pre>
<p>now my unit test</p>
<pre><code>def test_post_view(self):
        client=self.get_client()
        response=client.get(&quot;/api/posts/&quot;)# this line
        self.assertEqual(response.status_code,200)
</code></pre>
<p>this test gives error of 401!=200
but if i change the url
to</p>
<pre><code>response=client.get(&quot;/api/posts/1&quot;)

</code></pre>
<p>the test gives 200_k.
also if i create a new post via <code>client.post(&quot;/api/posts/&quot;,self.post) #here the post object created through Post model of my Custom Post class.</code>
the response returns 401!=200.
i want to know why it is behaving like this and i would like to know how to create unit testing for this piece of code.
Thank YOU.</p>
",https://stackoverflow.com/questions/66813365/django-testing-views-works-only-with-a-primary-key,"['python', 'django', 'unit-testing', 'django-rest-framework', 'django-views']",451,True,0,1
Unit test fails for coroutine if &quot;by inject{parametersOf(&quot;someValue&quot;)}&quot; is present within coroutine,"<p>I have a coroutine in my viewModel which runs perfectly fine. When I try to unit test the same, it throws the following error &quot;<code>Could not create instance for [type:Factory,primary_type:..MyService</code>&quot;</p>
<p>I am injecting a service and making an API call which works fine while unit testing. If the API fails, I am retrying the same API call with a new instance of Service with different parameters. This works fine in my application but fails in unit test. Here is the following code:</p>
<pre><code>coroutineScope.launch {
        try {
            var getResponse = myApi?.getCodeApi()
            if (getResponse?.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
                // Retrying with instance of service with a different token
                val newMyApiService: MyService? by inject { parametersOf(newToken) }
                getResponse = newMyApiService?.getCodeApi()

            }
            checkResponse(getResponse)
        } catch (exception: Exception) {
            Timber.e(exception)
        }
    }
</code></pre>
<p>Is there a way to fix this?. I have taken all the required measures like startingKoinApp for the test environment, also included the required Koin modules before starting to test.</p>
<p>A part of unit test looks something like this</p>
<pre><code> whenever(myAPi.getCodeApi()).thenReturn(properResponse)
        val errorResponse : Response&lt;DataModel&gt; = mock()
        whenever(response.code()).thenReturn(HttpsURLConnection.HTTP_UNAUTHORIZED)
        whenever(myAPi.getCodeApi()).thenReturn(errorResponse)
</code></pre>
",https://stackoverflow.com/questions/65874293/unit-test-fails-for-coroutine-if-by-injectparametersofsomevalue-is-prese,"['android', 'kotlin-coroutines', 'koin', 'android-unit-testing']",97,True,0,1
"Realm file for unit testing path permission (Xcode, Swift)","<p>Please forgive me if there is answered question similar to this. I tried to find any but couldn't find it</p>
<p>Hi guys, i am having problem with running Realm file for my unit testing</p>
<p>So i have moved the realm files to my project test folder</p>
<pre><code>   SampleAppTest
      + SampleAppTest.swift
      + SampleRealm.realm
</code></pre>
<p>I can successfully located the realm file, however, when I tried to instantiate the Realm connection, it threw me an error saying</p>
<p><code>Please use a path where your app has read-write permissions.</code></p>
<pre><code>    let bundle = Bundle(for: type(of: self))
    if let path = bundle.path(forResource: &quot;SampleRealm&quot;, ofType: &quot;realm&quot;) {
        let realmLocationURL = URL(string: path)
        
        let realmVersion: UInt64 = 1
        let config = Realm.Configuration(fileURL: realmLocationURL, schemaVersion: realmVersion, migrationBlock: { migration, oldSchemaVersion in
                if (oldSchemaVersion &lt; realmVersion) {}
            }
        )
        let realm = try! Realm(configuration: config) // throws error
    }
    else {
        print(&quot;path not found&quot;)
    }
</code></pre>
<p><code>Folder access in Finder -&gt; Get Info -&gt; Read &amp; Write</code></p>
<p>So in general, where can I put a file that my app has a permission to read-write? Is there a possible way to put within the project so that other team member that clone the project can also run the test with same realm file? Thank you</p>
",https://stackoverflow.com/questions/67897554/realm-file-for-unit-testing-path-permission-xcode-swift,"['ios', 'swift', 'realm']",235,False,0,1
How to use assertEqual with two inputs of a function?,"<p>Newbie here, sorry in advance! I tried looking for answers in other Stack posts on unit testing/ the <code>assertEqual</code>  function but didn't find an answer to what I was looking for.</p>
<p>In a case when there is one input in a function, you could set up a unit-test as follows:</p>
<pre><code>def test_some_function(self):
        inputted = 2
        some_function(inputted)
        output_expected = 3 #made up an expected output
        self.assertEqual(output_expected, inputted)
</code></pre>
<p>But how would you use <code>self.assertEqual</code> when your function takes two inputs?</p>
<p>I tried the below, but this runs into positional issues with <code>self</code>:</p>
<pre><code>def test_some_function(self):
        inputted_one = 1
        inputted_two = 2
        some_function(inputted_one, inputted_two)
        output_expected = 3 
        self.assertEqual(output_expected, inputted_one, inputted_two) 
</code></pre>
<p>And I want to avoid setting a value to the function output, likeso:</p>
<pre><code>def test_some_function(self):
        inputted_one = 1
        inputted_two = 2
        set_value = some_function(inputted_one, inputted_two)
        output_expected = 3
        self.assertEqual(output_expected, set_value) 
</code></pre>
<p><strong>EDIT</strong> I also want to avoid something like</p>
<p><code>self.assertEqual(output_expected, some_function(inputted_one, inputted_two))</code> because <code>self.assertEqual</code> should already be applying the function to the inputs.</p>
<p>ie, with one input it was not necessary to do <code>self.assertEqual(output_expected, some_function(inputted_one)</code></p>
",https://stackoverflow.com/questions/69963800/how-to-use-assertequal-with-two-inputs-of-a-function,"['python', 'unit-testing']",206,False,0,2
React-Jest : axios.get.mockRejectedValue doesnt respect async-await,"<p>I am using jest and enzyme for Unit Testing of a React App created using create-react-app. I have an axios call and I call other functions like <code>myfunction.onSuccess()</code> and <code>myfunction.onError()</code> from another component on success and error of the axios call respectively. I have put an assert to <code>expect(myfunction.onSuccess).toHaveBeenCalledTimes(1);</code> This works fine for <code>mockResolvedValue</code> but not for <code>mockRejectedValue</code>. I see that async-await is not respected for <code>mockRejectedValue</code>.</p>
<p>I have created a sample code and used <code>window.alert</code> as the function to be called in both then and catch block to keep it simple here and expecting this function to be called once as an assert. Why is there a difference and how to tackle this?</p>
<p>Async.js</p>
<pre><code>import React from 'react';
import axios from 'axios';

class Async extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
  }

  getAllPosts() {

    axios.get(`https://jsonplaceholder.typicode.com/posts`)
      .then(response =&gt; {
        if (response.data) {
          this.setState({ posts: response.data });
          window.alert(&quot;Data fetch Success&quot;);
        }
      }).catch(error =&gt; {
        window.alert(error.message);
      });
  }

  render() {
    return (
      &lt;div&gt;
        &lt;button onClick={() =&gt; { this.getAllPosts() }}&gt;Fetch Posts&lt;/button&gt;
        &lt;ul&gt;
          {this.state.posts.map((post) =&gt; (
            &lt;li key={post.id}&gt;{post.title}&lt;/li&gt;
          ))}
        &lt;/ul&gt;
      &lt;/div&gt;
    );
  }
}
export default Async;


</code></pre>
<p>Async.test.js</p>
<pre><code>import React from 'react';
import Async from './Async';
import { shallow } from 'enzyme';
import axios from &quot;axios&quot;;

jest.mock(&quot;axios&quot;);

describe('Async Component', () =&gt; {
  const wrapper = shallow(&lt;Async /&gt;);
  const layout = wrapper.instance();

  it('to notify success when posts', async () =&gt; {
    window.alert = jest.fn();
    const response = { data: [{ id: '1', title: 'something' }, { id: '2', title: 'something else' }] };
    axios.get.mockResolvedValue(response);
    await layout.getAllPosts();
    expect(layout.state.posts).not.toBe([])
    expect(window.alert).toHaveBeenCalledTimes(1);
  });

  it('to notify failure when error is encountered', async () =&gt; {
    window.alert = jest.fn();
    const error = { message: '500 Internal Server Error' };
    axios.get.mockRejectedValue(error);
    await layout.getAllPosts();
    expect(window.alert).toHaveBeenCalledTimes(1); // why doesn't this work?
  });
});


</code></pre>
",https://stackoverflow.com/questions/68258213/react-jest-axios-get-mockrejectedvalue-doesnt-respect-async-await,"['reactjs', 'unit-testing', 'jestjs', 'enzyme']",556,False,0,0
Testing gRPC services using xUnit in c#,"<p>I have a repository as a seperate project  <strong>(MyRepo)</strong> and using this repository I call various grpc services.</p>
<p>I haven't deployed the grpc servers yet so I run them on localhost:5000 for testing purposes.</p>
<p><strong>The error I'm getting is :</strong></p>
<blockquote>
<p>No connection could be made because the target machine actively
refused it. (localhost:5000)</p>
</blockquote>
<p>which is obviously caused because the grpc server is not running.</p>
<p>if I open a new instance of the visual studio and start the grpc server and then run the unit test, everythings works perfectly.</p>
<p>I'm very new to the unit testing conecpt and I would like to learn how test this.</p>
<p><strong>My Code:</strong></p>
<pre><code>public class StartupFixture
{
    public ServiceProvider ServiceProvider { get; private set; }

    private readonly IConfiguration configuration;

     public StartupFixture()
    {
        var configBuilder = new ConfigurationBuilder()
                .AddJsonFile(&quot;appsettings.json&quot;, optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

        configuration = configBuilder.Build();

        IServiceCollection services = new ServiceCollection();

        services.AddOptions();

        services.Configure&lt;PlatformSettings&gt;(configuration.GetSection(&quot;PlatformSettings&quot;));
        
        services.AddScoped&lt;ICmsService, CmsService&gt;();

        services.AddScoped&lt;IMyRepo, MyRepo&gt;();

        ServiceProvider = services.BuildServiceProvider();
    }
}


public class UnitTestCmsPlatforms : IClassFixture&lt;StartupFixture&gt;
{
    private ServiceProvider _serviceProvider;


    public ImyRepo myRepo =&gt; _serviceProvider.GetService&lt;IKoopRepo&gt;();
    public UnitTestCmsPlatforms(StartupFixture fixture)
    {
        _serviceProvider = fixture.ServiceProvider;       
    }

    [Fact]
    public async Task&lt;List&lt;Platforms&gt;&gt; Test1()
    {
       return  await myRepo.CmsService.GetAllPlatformsAsync();
    }
}
</code></pre>
<p>any help is much appreciated, Thanks!</p>
",https://stackoverflow.com/questions/67173811/testing-grpc-services-using-xunit-in-c,"['c#', 'grpc', 'xunit']",727,False,0,1
Stencil unit testing: How to mock initial state and load newSpecPage?,"<p>I am new to unit testing and planning to write unit test cases but not E-2-E for the below mentioned scenario and playgrounnd link for scenario is at the bottom.</p>
<p><code>Scenario:-</code></p>
<p>I have a <code>@State</code> variable called <code>&quot;ifSuccessResponse&quot;</code> with initial value set as <code>false</code>.</p>
<p>When <code>@State</code> variable <code>&quot;ifSuccessResponse&quot;</code> is <code>true</code>, <code>green-div</code> loads.</p>
<p>When <code>@State</code> variable <code>&quot;ifSuccessResponse&quot;</code> is <code>false</code>, <code>red-div</code> loads.</p>
<ol>
<li>How to mock initial state to have <code>@State</code> variable <code>ifSuccessResponse</code> to have value set as <code>true</code> and then load the newSpecPage so that I can test <code>green-div</code> is loaded.</li>
</ol>
<ol start=""2"">
<li>Is it possible to update the <code>@State</code> variable <code>ifSuccessResponse</code> after loading the page in Moc Doc using <code>newSpecPage</code> . Curious to know whether we can do this like how we can do in <code>enzyme</code> library using <code>setState method</code>.</li>
</ol>
<p><code>Playground-link</code>:
<a href=""https://webcomponents.dev/edit/Cbr1NS2QTrvC5scsmFZQ/src/index.stories.tsx"" rel=""nofollow noreferrer"">https://webcomponents.dev/edit/Cbr1NS2QTrvC5scsmFZQ/src/index.stories.tsx</a></p>
",https://stackoverflow.com/questions/69979647/stencil-unit-testing-how-to-mock-initial-state-and-load-newspecpage,"['jestjs', 'stenciljs', 'stencil-component']",1277,True,0,2
Entity Framework Core: Enable Duplicate Primary Keys in InMemoryDb Testing,"<p>I am receiving this error below in Entity Framework Core 3.1, InMemoryDB Unit Test.</p>
<blockquote>
<p>The instance of entity type cannot be tracked because another instance
with the key value is already being tracked. When attaching existing
entities, ensure that only one entity instance with a given key value
is attached.</p>
<p>Stack Trace:
IdentityMap<code>1.ThrowIdentityConflict(InternalEntityEntry entry) IdentityMap</code>1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
IdentityMap`1.Add(TKey key, InternalEntityEntry entry)</p>
</blockquote>
<p>Basically, I am adding a value with the same PrimaryKey Id. I have <code>AsNoTracking</code> in all queries along with <code>QueryTrackingBehavior.NoTracking</code>, and its still giving error.</p>
<p>How do I Enable duplicate Primary Keys in InMemory DB Unit testing?
Anything else I should do?</p>
<pre><code>services.AddDbContext&lt;PropertyContext&gt;(
   a =&gt; a.UseInMemoryDatabase($&quot;Ipts-{Guid.NewGuid()}&quot;)
   .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).EnableSensitiveDataLogging(),
    ServiceLifetime.Scoped);

new Property
{
    PropertyId = 1,
    
</code></pre>
<p>History behind this, Currently migrating a existing unit test dataset, into EFInMemoryDb.</p>
",https://stackoverflow.com/questions/66022434/entity-framework-core-enable-duplicate-primary-keys-in-inmemorydb-testing,"['c#', '.net', 'entity-framework', '.net-core', 'entity-framework-core']",897,True,0,1
always failed to create a document when it has a Firestore Geopoint field when using Firebase rules unit testing library,"<p>I am tryin to perform testing to my security rules using <a href=""https://www.npmjs.com/package/@firebase/rules-unit-testing"" rel=""nofollow noreferrer"">@firebase/rules-unit-testing</a> library using emulators</p>
<p>I have an Event class like this</p>
<pre><code>class Event {

  title: string 
  coordinate: FirebaseFirestore.GeoPoint

}
</code></pre>
<p>create an instance</p>
<pre><code>const event = new Event(&quot;event title&quot;, new admin.firestore.GeoPoint(-6.931980, 107.559540))
</code></pre>
<p>and then I write testing for my security rules like this using Mocha</p>
<pre><code>import * as firebase from &quot;@firebase/rules-unit-testing&quot;;

function getFirestore(auth?: TokenOptions) {
    return firebase.initializeTestApp({projectId: projectID, auth: auth}).firestore();
}

it(&quot;should create an event document&quot;, async () =&gt; {

     const db = getFirestore(myAuth);
     const ref = db.collection(&quot;events&quot;).doc(&quot;myEvent&quot;);
     const event = new Event(&quot;event title&quot;, new admin.firestore.GeoPoint(-6.931980, 107.559540))
     const eventData = { ...event};
      
     const promise = ref.set(eventData);
     await firebase.assertSucceeds(promise);
});
</code></pre>
<p>but I have error</p>
<blockquote>
<p>FirebaseError: Function DocumentReference.set() called with invalid
data. Unsupported field value: a custom object (found in field
coordinate in document events/myEvent)</p>
</blockquote>
<p>the error said that the coordinate property using custom object (i.e FirebaseFirestore.GeoPoint)</p>
<p>but I need to test my security rules. I have rules like this</p>
<pre><code>request.resource.data.coordinate is latlng
</code></pre>
<p>so how do I test if a field is latlng or not but, I can't create a document which is a Firestore Geopoint?</p>
<p>is it a bug?</p>
",https://stackoverflow.com/questions/66900714/always-failed-to-create-a-document-when-it-has-a-firestore-geopoint-field-when-u,"['node.js', 'firebase', 'google-cloud-firestore']",82,True,0,1
FlatFileItemWriter - Writer must be open before it can be written to,"<p>I've a SpringBatch Job where I skip all duplicate items write to a Flat file.</p>
<p>However the FlatFileItemWriter throws the below error whenever there's a duplicate:</p>
<p><code>Writer must be open before it can be written to</code></p>
<p>Below is the Writer &amp; SkipListener configuration -</p>
<pre><code>    @Bean(name = &quot;duplicateItemWriter&quot;)
    public FlatFileItemWriter&lt;InventoryFileItem&gt; dupItemWriter(){

        return new FlatFileItemWriterBuilder&lt;InventoryFileItem&gt;()
                .name(&quot;duplicateItemWriter&quot;)
                .resource(new FileSystemResource(&quot;duplicateItem.txt&quot;))
                .lineAggregator(new PassThroughLineAggregator&lt;&gt;())
                .append(true)
                .shouldDeleteIfExists(true)
                .build();
    }


public class StepSkipListener implements SkipListener&lt;InventoryFileItem, InventoryItem&gt; {

    private FlatFileItemWriter&lt;InventoryFileItem&gt; skippedItemsWriter;
    
    public StepSkipListener(FlatFileItemWriter&lt;InventoryFileItem&gt; skippedItemsWriter) {
        this.skippedItemsWriter = skippedItemsWriter;
    }
    @Override
    public void onSkipInProcess(InventoryFileItem item, Throwable t) {
        System.out.println(item.getBibNum() + &quot; Process - &quot; + t.getMessage());
        
        try {
            skippedItemsWriter.write(Collections.singletonList(item));
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }


</code></pre>
<p>The overall Job is defined as below and I'm using the duplicateItemWriter from the SkipListener.</p>
<pre><code>@Bean(name = &quot;fileLoadJob&quot;)
    @Autowired
    public Job fileLoadJob(JobBuilderFactory jobs, StepBuilderFactory steps,
            FlatFileItemReader&lt;inventoryFileItem&gt; fileItemReader,
            CompositeItemProcessor compositeItemProcessor,
            @Qualifier(value = &quot;itemWriter&quot;) ItemWriter&lt;InventoryItem&gt; itemWriter,
            StepSkipListener skipListener) {

        return jobs.get(&quot;libraryFileLoadJob&quot;)
                .start(steps.get(&quot;step&quot;).&lt;InventoryFileItem, InventoryItem&gt;chunk(chunkSize)
                        .reader(FileItemReader)
                        .processor(compositeItemProcessor)
                        .writer(itemWriter)
                        .faultTolerant()
                        .skip(Exception.class)
                        .skipLimit(Integer.parseInt(skipLimit))
                        .listener(skipListener)
                        .build())
                .build();
    }
</code></pre>
<p>I've also tried to write all data to FlatFileItemWriter - that doesn't work as well. However if write to a DB, then there's no issue with it.</p>
<p>The Spring-Batch version I'm using is - 4.3.3
I've referred to the below threads as well:</p>
<ul>
<li><a href=""https://stackoverflow.com/questions/63596068/unit-testing-a-flatfileitemwriter-outside-of-spring-writer-must-be-open-befor"">unit testing a FlatFileItemWriter outside of Spring - &quot;Writer must be open before it can be written to&quot; exception</a></li>
<li><a href=""https://stackoverflow.com/questions/43043554/spring-batch-writernotopenexception"">Spring Batch WriterNotOpenException</a></li>
<li><a href=""https://stackoverflow.com/questions/65996526/flatfileitemwriter-with-compositewriter-example"">FlatfileItemWriter with Compositewriter example</a></li>
</ul>
",https://stackoverflow.com/questions/69061463/flatfileitemwriter-writer-must-be-open-before-it-can-be-written-to,"['java', 'spring', 'spring-batch-admin']",1921,True,-1,3
Get variable name of argument of function TypeScript,"<p>I would like to set up an quick easy way to test functions in Angular where I would just input the name of functions once in the constructor and test them.
eg:</p>
<pre><code>constructor() {
    this.test(this.FucntionName)  &lt;= logs function name and output
  }
</code></pre>
<p>The issue with this is that if I try to pass a function as an argument without calling it, I get a <strong>this.</strong> scope error. How can I get both the name of the function and its return value when I pass it into the test() function, without having to type two arguments?</p>
<p>Is there a better option, maybe some unit testing frameworks provide this?</p>
<p>My current approach works, but it is clunky and I would like to remove the need for the second argument:</p>
<pre><code>export class AuthService {
  constructor(
    ...
  ) {
    this.test(this.FunctionName(), 'FunctionName')// I would like to remove the need to repeat the name as string
  }

  test(sub: any, name) {
    sub.subscribe(
      data =&gt; {
        console.group(&quot;==========&quot;, name, &quot;()    TEST  ===============&quot;)
        console.log(&quot;Output Type:&quot;, typeof data)
        typeof data == 'object' ? console.table(data) : console.log(data);
        console.groupEnd()
      }
    )
  }
</code></pre>
",https://stackoverflow.com/questions/70089777/get-variable-name-of-argument-of-function-typescript,"['angular', 'typescript']",595,True,0,2
"Why Bootstrap-Vue tables (b-table) are mounted as &quot;b-table-stub&quot; in unit testing in @vue/test-utils , not just b-table?","<p>I'm new to unit testing in Vue and I use @vue/test-utils. Here is my <code>Foo.vue</code></p>
<pre><code>&lt;template&gt;
  &lt;div class=&quot;hello&quot;&gt;
    &lt;b-table striped hover :items=&quot;items&quot;&gt;&lt;/b-table&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  name: &quot;Foo&quot;,
  data() {
    return {
      items: [
        {
          id: 0,
          name: &quot;foo&quot;,
        },
        {
          id: 1,
          name: &quot;bar&quot;,
        },
      ],
    };
  },
};
&lt;/script&gt;
</code></pre>
<p>And here is my <code>Foo.spec.js</code> file for testing <code>Foo.vue</code> component:</p>
<pre><code>import { shallowMount,createLocalVue } from '@vue/test-utils'
import Foo from '@/components/Foo.vue'
import {BootstrapVue} from &quot;bootstrap-vue&quot;

const localVue = createLocalVue();

localVue.use(BootstrapVue);

describe('Foo.vue', () =&gt; {
  it('renders bootstrap table', () =&gt; {
    const wrapper = shallowMount(Foo, {localVue})
    expect(wrapper.contains(&quot;b-table&quot;)).toBe(true)
  })
})
</code></pre>
<p>When I run the test I get the error;</p>
<pre><code>● Foo.vue › renders bootstrap table

    expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false
</code></pre>
<p>even though there must be a b-table element mounted. When I replace the code piece <code>expect(wrapper.contains(&quot;b-table&quot;)).toBe(true)</code> with <code>expect(wrapper.contains(&quot;b-table-stub&quot;)).toBe(true)</code> I didn't encounter any error.</p>
<p>Additionally when I remove the <strong>localVue</strong> asset from the <strong>shallowMount</strong> function like,</p>
<pre><code> const wrapper = shallowMount(Foo, {localVue})
 expect(wrapper.contains(&quot;b-table&quot;)).toBe(true)
</code></pre>
<p>no error remains and test case runs smoothly.</p>
<p>My question is that why b-table, b-pagination, etc. (b-x) elements are mounted as <code>b-table-stub</code>? Am I forced to check all b-x elements like b-x-stub in test cases or is there any shortcut for this?</p>
",https://stackoverflow.com/questions/68914343/why-bootstrap-vue-tables-b-table-are-mounted-as-b-table-stub-in-unit-testing,"['vue.js', 'unit-testing', 'bootstrap-vue', 'stub', 'vue-test-utils']",311,True,0,1
How to properly create unit test for logic inside arrow function,"<p>I'm working on an existing NodeJS web service using HapiJS, Hapi Lab for testing along with Sinon. The service connects to a Postgres DB using massiveJs. There's a method implemented by someone else, that doesn't have unit tests. Now I'm reusing this method and I want to implement some unit tests for it.
This method executes a massivejs transaction inside of it, persisting to several tables.</p>
<pre><code>async createSomething(payload) {

    const { code, member } = payload;

    const foundCompany = await this.rawDb.ethnics.tenants.findOne({ code });

    if (foundCompany &amp;&amp; foundCompany.companyId) {

        const { companyId } = foundCompany;
        const { foreignId } = member;

        return await this.rawDb.withTransaction(async (tx) =&gt; {

            const foundMember = await tx.ethnics.members.findOne({ foreign_id: foreignId, company_id: companyId });

            if (!foundMember) {

                //some business logic...
                const newMember = await tx.ethnics.members.insert(member);
                //more business logic persisting to other tables...
                return newMember;
            }
        });
    }
}
</code></pre>
<p>Problem is, I don't know how to stub stuff only inside the arrow function, without stubbing the entire arrow function. I just want to stub the calls of tx. I also don't want to use a database but stub the rawDb property. Is that doable from unit testing perspective?</p>
",https://stackoverflow.com/questions/67082570/how-to-properly-create-unit-test-for-logic-inside-arrow-function,"['javascript', 'unit-testing', 'sinon', 'stub']",369,True,0,1
python testing as an independent script,"<p>I have taken a below code from a large code repository of interdependent modules. I want to run this as an independent unit for testing.</p>
<p>In below while calling db_obj.create_connection() i have to pass the value of debug_obj which means I have to import all the dependent implementation of that which I do not want.</p>
<p>However, if I pass None as db_obj.create_connection(None) then it will fail at debug_obj.info('inside create_connection')  due to attribute error. Unless I go and disable debug_obj.info() wherever used.</p>
<p>What could be the best possible way to handle such a situation where you wanted to disable you dependent library codes just for your unit testing without commenting its callings.</p>
<pre><code>import pyodbc

class DBOperations(object):
    def __init__(self,db_params):
        self.db_params=db_params
        
    def create_connection(self, debug_obj):
        debug_obj.info('inside create_connection')
        mycode_to_run_create_connection

if __name__ == '__main__':    
    db_obj = DBOperations(db_params ='param_for_db_connection')
    db_obj.create_connection(None)    
</code></pre>
",https://stackoverflow.com/questions/66437130/python-testing-as-an-independent-script,['python'],51,False,0,1
How to test a static class method in MongoDB-Memory-Server?,"<p>I am thoroughly confused on unit testing with mongodb-memory-server and jest. I setup the memory server, <a href=""https://github.com/shelfio/jest-mongodb"" rel=""nofollow noreferrer"">github -  @shelf/jest-mongodb</a>. I'm using the node driver for mongodb and I have a DataAccessObject class:</p>
<pre><code>const chalk = require('chalk')
const ObjectId = require('bson')

let orders

module.exports = class OrdersDAO {
  static async injectDB(clientConnection) {
    if (orders) {
      return
    }
    try {
      orders = await clientConnection
        .db(process.env.DATABASE)
        .collection('orders')

      console.log(
        chalk.magentaBright(
      'OrdersDAO.injectDB() ~~~ line 16 ordersDAO injected DB with client connection....'
        )
      )
    } catch (error) {
      console.error(
        `Unable to establish collection handles in OrdersDAO: ${error}`
      )
    }
  }

  static async getOrders() {
    try {
      const cursor = orders.find({})
      const allOrders = await cursor.toArray()
      return allOrders
    } catch (e) {
      console.error(`OrdersDAO.getOrders() ~~~ Unable to get orders: ${e}`)
      return { e }
    }
  }

  static async addOrder(order) {
    try {
      return await orders.insertOne(order)
    } catch (error) {
      console.error(
        chalk.greenBright(
          `OrdersDAO.addOrder() ~~~ Unable to post order:) ${error}`
        )
      )
      return { error, e }
    }
  }
  static async deleteOrder(orderId) {
    try {
      const deleteResponse = await orders.deleteOne({ _id: ObjectId(orderId) })
      return deleteResponse
    } catch (error) {
      console.log(
        chalk.greenBright(
          `OrdersDAO.deleteOrder() ~~~ Unable to delete order ~~~`
         ),
        error
      )
      return error
    }
  }
</code></pre>
<p>And my ordersDAO.spec.js</p>
<pre><code>   import { MongoClient } from 'mongodb'
   import 'regenerator-runtime/runtime'
   import OrdersDAO, { getOrders } from '../dao/ordersDAO'
   import { mockOrder, mockOrders } from '../mocks/fixtures'

/*
I commented out below because I was trying jests manual mocks,
https://jestjs.io/docs/es6-class-mocks 
*/
// import OrdersDAO, {
//   mockGetOrders,
//   mockAddOrder,
//   mockDeleteOrder,
//   mockInjectDB,
// } from '../__mocks__/ordersDAO'
// jest.mock('../src/dao/OrdersDAO')

// const getOrders = jest.fn()

describe('insert1', () =&gt; {
  let connection
  let db

  beforeAll(async () =&gt; {
    connection = await MongoClient.connect(global.__MONGO_URI__, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      poolSize: 50,
    })
    db = connection.db(global.__MONGO_DB_NAME__)
  })
  beforeEach(async () =&gt; {
    await db.collection('orders').deleteMany({})
  })

  afterAll(async () =&gt; {
    await connection.close()
  })

  test('sanity check', async () =&gt; {
    const num = 1
    expect(num).toEqual(1)
  })
  test('should insert a doc into collection, mdb-memory-server', async () =&gt; {
    const orders = db.collection('orders')
    await orders.insertOne(mockOrder)
    const insertedOrder = await orders.findOne({ orderId: 'eHjMpYG4o3' })
    expect(insertedOrder).toEqual(mockOrder)
  })
  test('Positive, OrdersDAO.getOrders should retrieve orders', async () =&gt; {
    const mockGetOrders = jest.fn()
    mockGetOrders.mockReturnValue(Promise.resolve(mockOrders))
    OrdersDAO.prototype.getOrders = mockGetOrders
    const orders = db.collection('orders')
    await orders.insert(mockOrders)
    const result = await OrdersDAO.getOrders()
// result is undefined
    console.log(OrdersDAO.getOrders())
  })
})
</code></pre>
<p>Test number 2 works as expected using the memory server. But I really don't know what that is telling me other than it found a fake order I inserted and not with ordersDAO functionality.</p>
<p>How do I test my functionality in OrdersDAO, like getOrders(), addOrder(), etc? Am I supposed to mock these functions and then use the memory server? Since is is a fake db, do I even need to mock or spy on the static methods?</p>
",https://stackoverflow.com/questions/68684135/how-to-test-a-static-class-method-in-mongodb-memory-server,"['javascript', 'node.js', 'mongodb', 'unit-testing', 'jestjs']",246,False,0,1
Angular Testing: How can i call expectations after a function got executetd,"<p>I am currently unit testing my application in angular and got the problem that I need to use a http call on a local file. Therefore the expects of the test got called before and after the http call so it crashes. How can I fix that problem?</p>
<p>I am currently trying to call the expects inside the .subscribe of the http call:</p>
<pre><code>fit('should get local file and work with it', (done: DoneFn) =&gt; {
        let file: File;

        var blob: Blob;

        httpMockService.get('/assets/testFiles/testImage.png', { 
                      responseType: 'blob' }).subscribe((resp: any) =&gt; {
      
    blob = resp
    file = new File([blob], 'logo.png', 
                     { type: 'image/png', lastModified: Date.now() });

    component.submitFile(file); &lt;- get called seecond

    expect(component.canBeProgressed).toEqual(true); &lt;- get called first
    expect(component.submited).toEqual(false);

    done();

});
</code></pre>
<p>The problem is that the expected values are wrong, because component.submitFile got called after the expects. I tried it with a spy, but that doesn't work. Can anybody help me out?</p>
<p>Edit: In the submitFile() method is a FileReader included which loads the image and work with its pixels. I think that causes the problem</p>
",https://stackoverflow.com/questions/69173007/angular-testing-how-can-i-call-expectations-after-a-function-got-executetd,"['angular', 'unit-testing', 'http', 'karma-jasmine']",125,False,0,1
PerlXS: Possible crash trying to free(),"<p>I am seeing subtle crashes, which I think is down to the following XS code:</p>
<pre><code>void
tiff_ReadRawStrip (tif, strip, size)
            TIFF            *tif
            uint32_t        strip
            tmsize_t        size
INIT:
            void            *buf;
            tmsize_t        stripsize, bufsize;
PPCODE:
            stripsize = TIFFStripSize(tif);
            buf = (unsigned char *)_TIFFmalloc(stripsize);
            bufsize = TIFFReadRawStrip(tif, strip, buf, size);
            if (bufsize &gt; 0) {
                XPUSHs(sv_2mortal(newSVpvn(buf, bufsize)));
            }
            _TIFFfree(buf);
</code></pre>
<p>Am I trying to free <code>buf</code> twice? Is there something else going on?</p>
<h2>Background info</h2>
<p>Some years ago, I wrote <a href=""https://github.com/carygravel/graphics-tiff"" rel=""nofollow noreferrer"">Graphics::TIFF - Perl bindings for libtiff</a> and have been using them successfully in various other Linux-based projects. More recently, I got them to compile on Windows in Github actions.</p>
<p>Now a project using Graphics::TIFF is seeing <a href=""https://github.com/carygravel/Perl-PDF-Builder/runs/4010720394?check_suite_focus=true"" rel=""nofollow noreferrer"">random crashes on Windows during unit testing</a>, which seem to be caused by Graphics::TIFF. I can only reproduce them in Github actions, as I don't have access to a Windows machine.</p>
<p>The Linux runners pass with no problems, so perhaps the Windows compiler is less forgiving about something.</p>
",https://stackoverflow.com/questions/69750699/perlxs-possible-crash-trying-to-free,"['perl', 'xs']",94,False,3,0
Firebase security rules -- test server timestamp,"<p>Using <code>@firebase/rules-unit-testing</code> to test firebase security rules, how you test that a document's createdAt field is the current time? This is for Cloud Firestore.</p>
<h3>Background</h3>
<p>With firebase security rules, you can make sure a field is saved as the server timestamp.</p>
<pre><code>match /collection/{docId} {
    allow create: if request.time == request.resource.data.createdAt
}
</code></pre>
<p>This security rule works. And if you were to write to the document in the browser, you would then do:</p>
<pre class=""lang-js prettyprint-override""><code>firebase.firestore().collection('collection').add({
    createdAt: firebase.firestore.FieldValue.serverTimestamp()
})
</code></pre>
<p>However, the server timestamp method does not exist in <code>@firebase/rules-unit-testing</code>.</p>
<h3>The code</h3>
<p>Here's the boilerplate for the test setup, using Jest:</p>
<pre><code>import { initializeTestApp } from '@firebase/rules-unit-testing'

const app = initializeTestApp({ projectId: 'id' })

test('some test', async () =&gt; {
    firebase.assertSuccees(
        app.firestore().collection('collection').add({
            createdAt: firebase.firestore.FieldValue.serverTimestamp()
        })
    )
})

</code></pre>
<p>The issue is that <code>firebase.firestore.FieldValue</code> is not defined (unlike in the browser example).</p>
<p>Furthermore, <code>app.firestore.FieldValue</code> is also not defined.</p>
<p>So how would you get the server timestamp to test this security rule?</p>
<h3>Metadata</h3>
<ul>
<li>firebase-tools: 9.3.0</li>
<li>@firebase/rules-unit-testing: 1.1.9</li>
<li>jest: 26.6.3</li>
<li>Using the emulator</li>
</ul>
",https://stackoverflow.com/questions/66096350/firebase-security-rules-test-server-timestamp,"['firebase', 'google-cloud-firestore', 'firebase-security', 'firebase-tools']",392,False,3,0
Auth0 Angular error during unit test: Unexpected value &#39;AuthModule&#39; imported by the module &#39;DynamicTestModule&#39;. Please add an @NgModule annotation,"<p>We're in the process of migrating to using Jest over Karma in our Angular 12 App and are getting an error across the board in our spec files which use Auth0:</p>
<p><code>Unexpected value 'AuthModule' imported by the module 'DynamicTestModule'. Please add an @NgModule annotation.</code></p>
<p><em><strong>Weird part:</strong> Our current unit-testing with Karma works like a charm with no errors</em></p>
<p>Example spec :</p>
<pre class=""lang-js prettyprint-override""><code>beforeEach(waitForAsync(() =&gt; {
  TestBed.configureTestingModule({
    imports: [
      AuthModule.forRoot(mockAuth0Config),
      HttpClientTestingModule
    ],
    declarations: [
      MyComponent
    ]
  }).compileComponents();
}));
</code></pre>
<p>Auth0's library looks good to me (it's not a component or service, it is indeed a &quot;Module&quot; using the <code>ModuleWithProviders</code> interface:</p>
<p><a href=""https://i.stack.imgur.com/7pcWw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7pcWw.png"" alt=""enter image description here"" /></a></p>
<p>All of the other issues I've come across are when components or services are imported incorrectly, which is not the case here.</p>
<p>Additionally, <code>AuthModule.forRoot({...})</code> is used in the <code>imports</code> our <code>app.module.ts</code> just fine and is the basis for using Auth0 with Angular, which all work without issue in production.</p>
<p>The above error only happens when running our existing tests in Jest.</p>
",https://stackoverflow.com/questions/70429415/auth0-angular-error-during-unit-test-unexpected-value-authmodule-imported-by,"['angular', 'jestjs', 'auth0']",579,True,3,2
Python sorted() on list of numerical stings with leading zero not behaving as expected,"<p>I swear to the computer gods, previously I had a test involving the following built-in function sorting [ '002345', '98369'] to ['98369', '002345'] because lexicographically the zero should come last, right? But now a UnitTest that was previously functioning under that assumption is performing as pictured below.</p>
<pre class=""lang-py prettyprint-override""><code>In[2]: x = ['98369', '002345']
In[3]: sorted(x)
Out[3]: ['002345', '98369']
</code></pre>
<p>So tell me, am I loosing my mind? There may have been a transition from python3.5 to 3.6, but I have documentation of successful unit testing after than transition.</p>
<p>-----EDIT-----</p>
<p>So I'm not losing my mind, I'm just a dummy.</p>
<p>I should have added that prior to asserting the results of the sorted list, I was casting the sorted list to a set. I know that negates the sort, so that is why I was getting variable results.</p>
",https://stackoverflow.com/questions/67288627/python-sorted-on-list-of-numerical-stings-with-leading-zero-not-behaving-as-ex,"['python', 'python-3.x', 'sorting']",137,True,2,1
Pytest doesn&#39;t run with &quot;docker-compose exec -T web_service pytest&quot; in Gitlab CI Docker executor with Docker-Compose,"<p>The main reason I'm trying to use Gitlab CI is to automate unit testing before deployment. I want to</p>
<ol>
<li>build my Docker images and push them to my image repository, then</li>
<li>ensure all my pytest unit tests pass, and finally</li>
<li>deploy to my production server.</li>
</ol>
<p>However, my pytest command doesn't run at all if I include the <code>-T</code> flag as follows. It just instantly returns 0 and &quot;succeeds&quot;, which is <strong>not correct</strong> because I have a failing test in there:</p>
<pre><code>docker-compose exec -T web_service pytest /app/tests/ --junitxml=report.xml
</code></pre>
<p>On my local computer, I run the tests without the <code>-T</code> flag as follows, and it runs correctly (and the test fails as expected):</p>
<pre><code>docker-compose exec web_service pytest /app/tests/ --junitxml=report.xml
</code></pre>
<p>But if I do that in Gitlab CI, I get the error <code>the input device is not a TTY</code> if I omit the <code>-T</code> flag.</p>
<p>Here's some of my &quot;.gitlab-ci.yml&quot; file:</p>
<pre class=""lang-yaml prettyprint-override""><code>image:
  name: docker/compose:1.29.2
  # Override the entrypoint (important)
  entrypoint: [&quot;&quot;]

# Must have this service
# Note: --privileged is required for Docker-in-Docker to function properly,
# but it should be used with care as it provides full access to the host environment
services:
  - docker:dind

stages:
  - build
  - test
  - deploy

variables:
  # DOCKER_HOST is essential
  DOCKER_HOST: tcp://docker:2375
  DOCKER_DRIVER: overlay2

before_script:
  # First test that gitlab-runner has access to Docker
  - docker --version
  # Set variable names
  - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME
  - export MY_IMAGE=$IMAGE:web_service
  # Install bash
  - apk add --no-cache bash
  # Add environment variables stored in GitLab, to .env file
  - chmod +x ./setup_env.sh
  - bash ./setup_env.sh
  # Login to the Gitlab registry and pull existing images to use as cache
  - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY

build:
  stage: build
  script:
    # Pull the image for the build cache, and continue even if this image download fails (it'll fail the very first time)
    - docker pull $MY_IMAGE || true
    # Build and push Docker images to the Gitlab registry
    - docker-compose -f docker-compose.ci.build.yml build
    - docker push $MY_IMAGE
  only:
    - master

test:
  stage: test
  script:
    # Pull the image
    - docker pull $MY_IMAGE
    # Start the containers and run the tests before deployment
    - docker-compose -f docker-compose.ci.test.yml up -d
    # TODO: The following always succeeds instantly with &quot;-T&quot; flag,
    # but won't run at all if I exclude the &quot;-T&quot; flag...
    - docker-compose -f docker-compose.ci.test.yml exec -T web_service pytest --junitxml=report.xml
    - docker-compose -f docker-compose.ci.test.yml down
  artifacts:
    when: always
    paths:
      - report.xml
    reports:
      junit: report.xml
  only:
    - master

deploy:
  stage: deploy
  script:
    - bash deploy.sh
  only:
    - master
</code></pre>
",https://stackoverflow.com/questions/69518739/pytest-doesnt-run-with-docker-compose-exec-t-web-service-pytest-in-gitlab-ci,"['docker', 'docker-compose', 'pytest', 'gitlab-ci', 'gitlab-ci-runner']",545,False,1,1
Django Test key association,"<p>I am new to Django and Unit Testing.</p>
<p>I'm writing tests for my app which is a learning platform consisting of several labs that include a lesson and questions (of 3 different types), the relationship between questions and labs is done via foreign key.</p>
<p>I am trying to write tests in which I add a lab to the database and a multiple choice question.</p>
<p>The problem is that the tests always end with the same error:</p>
<pre><code>DETAIL: Key (lab_id)=(1) is not present in table &quot;labs_lab&quot;.
</code></pre>
<p>I understand the meaning of the sentence, but how come this happens if I provide an id to the questions to link them to the respective test-lab?</p>
<p>Thank you</p>
<p>Models.py</p>
<pre><code>class Lab(models.Model):
    lab_name = models.CharField(max_length=200)
    category = models.ForeignKey(Category, unique=True, null=True, on_delete=models.PROTECT)
    pub_date = models.DateTimeField('date published')
    lab_theory = models.TextField()
    def __str__(self):
        return self.lab_name

class QuestionMultipleChoice(models.Model):
    lab = models.ForeignKey(Lab, on_delete=models.CASCADE)
    type = QuestionType.multiplechoice
    question = models.CharField(max_length=200,null=True)
    option1 = models.CharField(max_length=200,null=True)
    option2 = models.CharField(max_length=200,null=True)
    option3 = models.CharField(max_length=200,null=True)
    option4 = models.CharField(max_length=200,null=True)
    answer = models.IntegerField(max_length=200,null=True)
    
    def __str__(self):
        return self.question

    @property
    def html_name(self):
        return &quot;q_mc_{}&quot;.format(self.pk)

    @property
    def correct_answer(self):
        correct_answer_number = int(self.answer)
        correct_answer = getattr(self, &quot;option{}&quot;.format(correct_answer_number))
        return correct_answer

    def check_answer(self, given):
        return self.correct_answer == given
</code></pre>
<p>test.py</p>
<pre><code>class TestData(TestCase):
    @classmethod
    def setUpTestData(cls):
        past_date = date(1997, 3, 2)
        future_date = date(2050, 3, 2)
        Lab.objects.create(lab_name=&quot;testlab&quot;, pub_date=datetime.now(), lab_theory=&quot;test theory&quot;)
        Lab.objects.create(lab_name=&quot;test lab past question&quot;, pub_date=past_date, lab_theory=&quot;test lab past question&quot;)
        Lab.objects.create(lab_name=&quot;test lab future question&quot;, pub_date=future_date, lab_theory=&quot;test lab future question&quot;)
        

class QuestionIndexViewTests(TestCase):
    def test_no_questions(self):
        &quot;&quot;&quot;
        If no questions exist, an appropriate message is displayed.
        &quot;&quot;&quot;
        response = self.client.get(reverse('labs:index'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, &quot;No labs are available.&quot;)
        self.assertQuerysetEqual(response.context['latest_question_list'], [])

    def test_past_question(self):
        &quot;&quot;&quot;
        Questions with a pub_date in the past are displayed on the
        index page.
        &quot;&quot;&quot;
        past_question = QuestionMultipleChoice.objects.create(question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1', lab_id=2)
        response = self.client.get(reverse('labs:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            [past_question],
        )
</code></pre>
<p><strong>UPDATE:</strong></p>
<p>Update:
I changed the test, and i gave the &quot;QuestionMultipleChoice&quot; different parameters:</p>
<pre><code>
question1 = QuestionMultipleChoice.objects.create(lab=1, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1')        
</code></pre>
<p>Result now is:</p>
<pre><code>ValueError: Cannot assign &quot;1&quot;: &quot;QuestionMultipleChoice.lab&quot; must be a &quot;Lab&quot; instance.
</code></pre>
",https://stackoverflow.com/questions/70420013/django-test-key-association,"['python', 'django', 'unit-testing', 'django-models']",70,True,1,1
Does a function that receives a function as a parameter can still be considered a pure function?,"<p>is addVat a pure function?</p>
<pre><code>function addVat(country, getVat, amount)
{
   if(amount &gt; 0) {
     return amount + getVat(country)*amount
   }
   
   return amount
}
</code></pre>
<p>Having a function as a parameter - getVat - makes addVat automatically impure?</p>
<p>Depending on the implementation of getVat, we could introduce any side effects... getVat could return a random value making the result of addVat unpredictable.</p>
<pre><code>const getVat = ()=&gt; Math.random()
addVat('UK',getVat, 20)
</code></pre>
<p>Case of producing external side-effects...</p>
<pre><code>const getVat = ()=&gt; {
  updateDbWithVatUsed(0.2)
  return 0.2
}
addVat('UK',getVat, 20)
</code></pre>
<p>By other hand, the unit testing is feasible as side effects or data variability is outside of the pure function and we can stub this to make testing totally predictable.</p>
<pre><code>const getUKVat = ()=&gt; 0.2
assert.equal(addVat('UK',getUkVat, 20), 24)

</code></pre>
<p>My doubts come from... is purity defined as what the function does excluding anything what happens to an external call that has been passed as a parameter?</p>
<p>Otherwise, as high order function is a theme for Functional programming... does it not make it impossible to classify a function as pure just by itself without considering invocation considerations.</p>
",https://stackoverflow.com/questions/69699276/does-a-function-that-receives-a-function-as-a-parameter-can-still-be-considered,['javascript'],103,True,6,2
Spring password encoder for the default Django password format (pbkdf2_sha256),"<p>I am working on a Spring Boot application using Spring Security connected to a database originally generated by Django, in which all of the user passwords are stored in Django's <code>pbkdf2_sha256</code> <a href=""https://docs.djangoproject.com/en/3.1/topics/auth/passwords/"" rel=""nofollow noreferrer"">format</a>.</p>
<pre><code>&lt;algorithm&gt;$&lt;iterations&gt;$&lt;salt&gt;$&lt;hash&gt;
</code></pre>
<p>Looking at Spring Security's <code>Pbkdf2PasswordEncoder</code>, I was able to mostly figure it out and create an encoder that is able to encode and match Django's format.</p>
<p>After successfully unit testing it, I tried it on a sample value generated by Django... and it failed.</p>
<p>Why is this encoder not matching Django-generated values? Is Django performing some ~magic~ under the hood? I have also tried multiple replacements for Java's <code>SecurityFactory</code> implementation. This <a href=""https://github.com/django/django/blob/9ee693bd6cf4074f04ec51c6f3cfe87cad392f12/django/contrib/auth/hashers.py#L276"" rel=""nofollow noreferrer"">line</a> in Django's source code caught my attention as well, but writing the equivalent Kotlin did not fix the issue.</p>
<pre class=""lang-kotlin prettyprint-override""><code>class DjangoPbkdf2PasswordEncoder : PasswordEncoder {

    companion object {
        private const val PREFIX = &quot;pbkdf2_sha256&quot;
        private const val SEPARATOR = &quot;\$&quot;
        private const val ITERATIONS = 180000
        private const val HASH_WIDTH = 256
        private const val ALGORITHM = &quot;PBKDF2WithHmacSHA256&quot;
    }

    private val saltGenerator: BytesKeyGenerator = KeyGenerators.secureRandom()

    private fun base64Decode(string: String): ByteArray {
        return Base64.getDecoder().decode(string)
    }

    private fun base64Encode(bytes: ByteArray): String {
        return Base64.getEncoder().encodeToString(bytes)
    }

    override fun encode(rawPassword: CharSequence): String {
        val salt = saltGenerator.generateKey()
        val hash = encodeWithSalt(rawPassword, salt)

        val encodedHash = base64Encode(hash)
        val encodedSalt = base64Encode(salt)

        return listOf(PREFIX, ITERATIONS, encodedSalt, encodedHash).joinToString(SEPARATOR)
    }

    private fun encodeWithSalt(rawPassword: CharSequence, salt: ByteArray): ByteArray {
        return encodeWithSaltAndIterations(rawPassword, salt, ITERATIONS)
    }

    private fun encodeWithSaltAndIterations(rawPassword: CharSequence, salt: ByteArray, iterations: Int): ByteArray {
        val keySpec = PBEKeySpec(
            rawPassword.toString().toCharArray(),
            salt,
            iterations,
            HASH_WIDTH
        )

        return try {
            SecretKeyFactory.getInstance(ALGORITHM)
                .generateSecret(keySpec)
                .encoded
        } catch (e: GeneralSecurityException) {
            throw IllegalStateException(&quot;Could not create hash&quot;, e)
        }
    }

    override fun matches(rawPassword: CharSequence, partsEncodedPassword: String): Boolean {
        if (!partsEncodedPassword.startsWith(PREFIX)) {
            throw IllegalArgumentException(&quot;Encoded password does not start with: $PREFIX&quot;)
        }

        val parts = partsEncodedPassword.split(SEPARATOR)
        if (parts.size != 4) {
            throw IllegalArgumentException(&quot;The encoded password format does not have 4 parts&quot;)
        }

        val iterations = parts[1].toInt()
        val salt = base64Decode(parts[2])
        val hash = base64Decode(parts[3])

        return MessageDigest.isEqual(
            hash,
            encodeWithSaltAndIterations(rawPassword, salt, iterations)
        )
    }
}
</code></pre>
",https://stackoverflow.com/questions/66915730/spring-password-encoder-for-the-default-django-password-format-pbkdf2-sha256,"['django', 'spring', 'kotlin', 'spring-security', 'password-protection']",342,False,1,1
Issue Getting correct Full Path in Unit Testing,"<p>Having an issue in getting the correct path to a file during unit testing, the file exist in &quot;C:\Users\Name\source\repos\ProjectOne\ProjectOneTests\bin\Debug\netcoreapp3.1\Test\textFile.txt&quot;</p>
<pre><code> string fileName = &quot;textFile.txt&quot;;
 string directoryName = Path.GetFullPath(fileName);
</code></pre>
<p>directoryName =<strong>&quot;C:\Users\Name\source\repos\ProjectOne\ProjectOneTests\bin\Debug\netcoreapp3.1&quot;</strong></p>
<p>directoryName should be <strong>&quot;C:\Users\Name\source\repos\ProjectOne\ProjectOneTests\bin\Debug\netcoreapp3.1\Test&quot;</strong></p>
<p>If I write code</p>
<pre><code> string fileName = &quot;Test\\textFile.txt&quot;;
 string directoryName = Path.GetFullPath(fileName);
</code></pre>
<p>Then directoryName =<strong>&quot;C:\Users\Name\source\repos\ProjectOne\ProjectOneTests\bin\Debug\netcoreapp3.1\Test&quot;</strong></p>
<p>Why is Path.GetFullPath giving me the incorrect path when I only call file name <strong>&quot;textFile.txt&quot;</strong>
I can't seem to find any sources on stack or google to explain why and how I can get the correct path inside netcoreapp3.1 path, any advice, sources or help would be appreciated</p>
",https://stackoverflow.com/questions/68307692/issue-getting-correct-full-path-in-unit-testing,"['c#', 'asp.net', 'visual-studio', 'unit-testing', 'asp.net-core']",131,False,1,0
Testing React Context update,"<p>I have been struggling to test a React Context update for a while. I can predefine the value of the <code>Context.Provider</code> however, the solution is not ideal because an update to the context which is supposed to happen within component utilising the context is not actually happening.</p>
<p>When I test this manually the text 'Account name: abc' changes to 'Account name: New account name' but not in the test. The context value remains the same.</p>
<p>The reason I predefine the value is because the component relies on a fetch response from a parent and I am unit testing <code>&lt;ImportAccounts /&gt;</code> only.</p>
<p>In a test I am rendering a component with predefined value</p>
<pre><code>test('accountName value is updated on click', () =&gt; {
  const { getByText, getByLabelText, getByRole } = render(
    &lt;ImportAccountsContext.Provider value={{ accountName: { value: 'abc', setValue: jest.fn() }}}&gt;
      &lt;ImportAccounts /&gt;
    &lt;/ImportAccountsContext.Provider&gt;,
  );

  expect(getByText('Account name: abc')).toBeInTheDocument();

  const input = getByLabelText('Account name');
  fireEvent.change(input, { target: { value: 'New account name' } });
  fireEvent.click(getByRole('button', { name: 'Update' }));
  expect(getByText('Account name: New account name')).toBeInTheDocument();
});
</code></pre>
<p>Here's my context</p>
<pre><code>import React, { createContext, useContext, useState, useCallback, Dispatch, SetStateAction } from 'react';

export interface StateVariable&lt;T&gt; {
  value: T;
  setValue: Dispatch&lt;SetStateAction&lt;T&gt;&gt;;
}

export interface ImportAccountsState {
  accountName: StateVariable&lt;string&gt;;
}

export const ImportAccountsContext = createContext&lt;ImportAccountsState&gt;(
  {} as ImportAccountsState,
);

export const ImportAccountsProvider = ({ children }: { children: React.ReactNode }) =&gt; {
  const [accountName, setAccountName] = useState('');

  const initialState: ImportAccountsState = {
    accountName: {
      value: accountName,
      setValue: setAccountName,
    },
  };

  return (
    &lt;ImportAccountsContext.Provider value={initialState}&gt;
      {children}
    &lt;/ImportAccountsContext.Provider&gt;
  );
};

export const useImportAccountsContext = () =&gt; {
  return useContext&lt;ImportAccountsState&gt;(ImportAccountsContext);
};
</code></pre>
<p>Import Accounts is as simple as</p>
<pre><code>export const ImportAccounts = () =&gt; {
  const { accountName } = useImportAccountsContext();
  const [newAccountName, setNewAccountName] = useState(accountName.value);
  
  const handleAccountNameChange = () =&gt; {
    accountName.setValue(newAccountName);
  };
  
  return (
    &lt;&gt;
      &lt;h1&gt;Account name: {accountName.value}&lt;/h1&gt;
    
      &lt;label htmlFor=&quot;accountName&quot;&gt;Account name&lt;/label&gt;
      &lt;input
        value={newAccountName}
        onChange={e =&gt; setNewAccountName(e.target.value)}
        id=&quot;accountName&quot;
      /&gt;
      &lt;button
        type=&quot;button&quot;
        onClick={handleAccountNameChange}&gt;
          Update
      &lt;/button&gt;
    &lt;/&gt;
  );
}
</code></pre>
<p>How can I test that accountName has actually updated?</p>
",https://stackoverflow.com/questions/68314294/testing-react-context-update,"['reactjs', 'jestjs', 'react-testing-library']",1708,True,1,1
Function to equal Function error on angular unit test FormGroup,"<p>I am new to Angular unit testing and I am currently driving myself crazy with one of the tests.</p>
<p>I have a service with one function that takes in some questions and and are returning a FormGroup:</p>
<pre><code>import { Injectable }   from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

import { QuestionBase } from './question-base';

@Injectable()
export class QuestionControlService {
 constructor() { }

 toFormGroup(questions: QuestionBase&lt;any&gt;[] ) {
   let group: any = {};

   questions.forEach(question =&gt; {
     group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
                                             : new FormControl(question.value || '');
   });
   return new FormGroup(group);
 }
}
</code></pre>
<p>Rather straight forward. In my test I then mock a FormGroup from some mocked questions, and expects my service function to return the same. It seems fine when I print the output, but the expect function is returning follow error:</p>
<pre><code>Chrome Headless 91.0.4469.0 (Mac OS 10.15.7) QuestionControlService creates toFormGroup successfully FAILED
        Expected $._onCollectionChange = Function to equal Function.
        Expected $.controls.name._onCollectionChange = Function to equal Function.
        Expected $.controls.username._onCollectionChange = Function to equal Function.
        Expected $.controls.email._onCollectionChange = Function to equal Function.
        Error: Expected $._onCollectionChange = Function to equal Function.
        Expected $.controls.name._onCollectionChange = Function to equal Function.
        Expected $.controls.username._onCollectionChange = Function to equal Function.
        Expected $.controls.email._onCollectionChange = Function to equal Function.
            at &lt;Jasmine&gt;
            at UserContext.&lt;anonymous&gt; (src/app/dynamic-form/question-control.service.spec.ts:34:17)
            at ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:372:1)
            at ProxyZoneSpec.onInvoke (node_modules/zone.js/fesm2015/zone-testing.js:287:1)

</code></pre>
<p>My test spec looks like this:</p>
<pre><code>import { TestBed } from '@angular/core/testing';
import { FormGroup, FormControl, Validators } from '@angular/forms';

import { QuestionControlService } from './question-control.service';

describe('QuestionControlService', () =&gt; {
  let service: QuestionControlService;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({ providers: [QuestionControlService] });
    service = TestBed.inject(QuestionControlService);
  });

  it('can load instance', () =&gt; {
    expect(service).toBeTruthy();
  });

  it('creates toFormGroup successfully', () =&gt; {
    var mockedQuestions = [
      {value: undefined, key: 'name', label: 'Name', required: true, order: 1, group: 1, controlType: 'textbox', type: 'text'},
      {value: undefined, key: 'username', label: 'Username', required: false, order: 1, group: 2, controlType: 'textbox', type: 'text'},
      {value: 'john@doe.com', key: 'email', label: 'Email', required: true, order: 2, group: 1, controlType: 'textbox', type: 'email'}
    ]

    var mockedGroup = {
      'name': new FormControl('', Validators.required),
      'username': new FormControl(''),
      'email': new FormControl('john@doe.com', Validators.required)
    }
    var mockedFormGroup = new FormGroup(mockedGroup);

    const res = service.toFormGroup(mockedQuestions);

    expect(res).toEqual(mockedFormGroup);
  });
});
</code></pre>
<p>What am I doing wrong?</p>
<p>Also, I have tested to create another helloWorld function that returns only text, and that is working perfectly fine. So my guess is that the problem is the return type of FormGroup in some way.</p>
",https://stackoverflow.com/questions/67649018/function-to-equal-function-error-on-angular-unit-test-formgroup,"['angular', 'unit-testing', 'karma-jasmine', 'formgroups']",3508,True,1,3
"Docker Run MongoDB replica set.., how is it working?","<p>So I'm creating some softwaare that makes heavy use of mongo transactions.
So far, I've tried only with testcontainers mongo, and pure unit testing.
Now I'm moving to test it manually and I get an error that says something like: <code>Transaction numbers are only allowed on a replica set ...</code>, yet that error doesn't happen during unit tests.</p>
<p>I read that this error happens because transactions are only possible on a replica set, but then, how is testcontainers working? I checked <code>docker ps</code> during running of tests and only one mongo docker container is up.</p>
<p>I checked the args passed by <code>testcontainers</code>, and it resulted they pass <code>--replSet docker-rs</code>. So I did, but then I get this error: <code>NotYetInitialized: Cannot use non-local read concern until replica set is finished initializing.</code></p>
<p>I'm scratching my head bad, wondering how is testcontainers running a ONE mongo docker container that behaves like a replica set.</p>
",https://stackoverflow.com/questions/69891028/docker-run-mongodb-replica-set-how-is-it-working,"['mongodb', 'docker', 'replicaset', 'testcontainers', 'mongodb-replica-set']",1427,True,1,1
How to make a unit test for the Google Sign In delegate functions?,"<p>I am trying to implement Google Sign In to my project. And I created an interface adapter as the gateway between the Google Sign In and the app.</p>
<pre><code>import GoogleSignIn
import RxSwift

class GoogleSignInAdapter: NSObject {
    struct SignInDTO {
        let idToken: String
        let fullName: String
        let email: String
    }

    private(set) lazy var signInSuccessful = signInSuccessfulRelay.asSignal()
    private let signInSuccessfulRelay = PublishRelay&lt;SignInDTO&gt;()

    private(set) lazy var signInFailed = signInFailedRelay.asSignal()
    private let signInFailedRelay = PublishRelay&lt;Error&gt;()

    init() {
        GIDSignIn.sharedInstance()?.clientID = &quot;******&quot;
        GIDSignIn.sharedInstance()?.delegate = self
    }
}

extension GoogleSignInAdapter: GIDSignInDelegate {
    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
        if let error = error {
            signInFailedRelay.accept(error)
        } else {
            let idToken = user.authentication.idToken
            let fullName = user.profile.name
            let email = user.profile.email
            let result = SignInDTO(idToken: idToken, fullName: fullName, email: email)
            signInSuccessfulRelay.accept(result)
        }
        
    }
    
    func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
        
    }
}
</code></pre>
<p>I am still having trouble to mock and test this adapter so I can trigger the <code>signInSuccessfulRelay</code> and <code>signInFailedRelay</code> with their respective params because the only way to do it is by triggering the delegate itself. But the only way that I can get it to trigger is by using the <code>GIDSignInButton</code> which is a derivative of <code>UIView</code>. That means I have to introduce a part of the view (which is more suited for UI testing instead of unit testing) into the unit test. Can anybody tell me how to make the tests for this class?</p>
",https://stackoverflow.com/questions/66252796/how-to-make-a-unit-test-for-the-google-sign-in-delegate-functions,"['ios', 'swift', 'unit-testing', 'google-signin']",209,False,1,0
Unit testing Spring Boot based REST endpoint which returns collection of objects ordered by given direction,"<p>I am new to spring boot and still learning. Please bear with me if I am asking a question which is not much relevant. I have seen a code something like below and as I understood this code is essentially searching some record based on given sorting order ASC or DESC and return the ordered result set. Do we really need to write a unit test to verify the order of the result set serialized by rest controller or do you think unit testing ordering behaviour is not belong to controller level responsibility ? Your suggestions and thoughts are very much appreciated.</p>
<pre><code>@RestController
@RequestMapping
@RequiredArgsConstructor
public class OrderController {
    
    private final OrderService orderService;

    @GetMapping(&quot;/orders&quot;)
    public ResponseEntity&lt;List&lt;Order&gt;&gt; getAllOrders(@RequestParam(required = false) String direction){
        return ResponseEntity.ok(orderService.getAllOrdersSortedByName(direction));
    }

}
</code></pre>
<p>If we write a unit test like below with mocking service call behaviour, can it be consider as a meaningful test case ?</p>
<pre><code>@Test
void findAllOrderDesc() {

    Order o1 = Order.id(1).name(&quot;A&quot;).build();
    Order o2 = Order.id(2).name(&quot;B&quot;).build();

        
    when(orderService.getAllOrdersSortedByName(anyString())).thenReturn(List.of(o2,o1));

        mockMvc.perform(get(&quot;/orders?direction=DESC&quot;))
                .andExpect(status().isOk())
                .andExpect(jsonPath(&quot;$&quot;,hashSize(2)))
                .andExpect(jsonPath(&quot;$.[0].name&quot;,is(&quot;B&quot;)))
                .andExpect(jsonPath(&quot;$.[1].name&quot;,is(&quot;A&quot;)));
                

}
</code></pre>
",https://stackoverflow.com/questions/68869736/unit-testing-spring-boot-based-rest-endpoint-which-returns-collection-of-objects,"['java', 'spring-boot', 'unit-testing', 'spring-restcontroller', 'spring-boot-test']",548,False,1,1
How best to utilize a junit test for classes that expect ThrreadLocal variables to have been setup?,"<p>I found a very old question asking the same thing (<a href=""https://stackoverflow.com/questions/9498466/unit-testing-parts-of-the-application-that-use-thread-local"">Unit testing parts of the application that use Thread Local</a> ) but it only has 3 answers despite its age and those recomnded differnet frameworks.  Does junit5 (or even junit4) offer a better solution?</p>
<p>to restate the problem, If a class expects to be called only from threads started in the application and expects threadlocals to have been established</p>
<pre><code>    class workers implments runnable {
    ...
    public static ThreadLocal&lt;String&gt; myString = new ThreadLocal&lt;String&gt;... 
    ...
    }
    class foo {
        public static calledByJunitAndApp {
            ..myString.get()..
        }
    }
</code></pre>
<p>then what is the cleaneest and easiets way to establish the expected environment for a junit test that never goes through the runnable but that calls some class that expects it?   The &quot;easiest&quot; part is key since this is for junit tests where the classes they call did not previiously access ThreadLocals, but now do so.</p>
",https://stackoverflow.com/questions/66446678/how-best-to-utilize-a-junit-test-for-classes-that-expect-thrreadlocal-variables,"['java', 'junit', 'junit4', 'junit5', 'thread-local-storage']",568,False,1,1
Calling toast.show function in Unit Testing in Android Studio,"<p>I wish to test out my Alert toast class inside Unit Testing. However, when I call <code>alert_toast.show</code>, I get an error <code>Can't create handler inside thread that has not called Looper.prepare()</code>.</p>
<p>I understand that I cant call UI related elements such as Toast from worker class or other processing class, such as Unit Testings. However, is there a way I can call <code>alert_toast.show</code> inside my Unit Testings?</p>
<p>My alert_toast class code</p>
<pre><code>public class Custom_toasts {
    private Context context;
    private final int TOAST_TEXT_COLOR = R.color.white;
    private final int TOAST_TEXT_GRAVITY = Gravity.CENTER;
    private boolean toast_shown = false;
    private Toast toast;

    public Custom_toasts(Context context){
        this.context = context;

    }
    public Toast getToast(){
        return toast;
    }
    public void show_toast(String message,int toast_color){
        toast_shown = false;

        toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
        View view = toast.getView();

        //Gets the actual oval background of the Toast then sets the colour filter
        int background_color = ContextCompat.getColor(context, toast_color);
        view.getBackground().setColorFilter((background_color), PorterDuff.Mode.SRC_IN);

        //Gets the TextView from the Toast so it can be editted
        TextView text = view.findViewById(android.R.id.message);

        int string_color = ContextCompat.getColor(context, TOAST_TEXT_COLOR);
        text.setTextColor((string_color));
        text.setGravity(TOAST_TEXT_GRAVITY);

        toast.show();
        toast_shown = true;
    }
    public boolean getToast_shown(){
        return toast_shown;
    }

}

</code></pre>
<p>I've done a little research, and most answers show that I can show toast, but only if the toast is shown <strong>after</strong> I've clicked on a button on the UI, say clicking on a button will show a toast. As seen here: (<a href=""https://gist.github.com/brunodles/badaa6de2ad3a84138d517795f15efc7"" rel=""nofollow noreferrer"">https://gist.github.com/brunodles/badaa6de2ad3a84138d517795f15efc7</a>).</p>
<p>I don't want to create another layout.xml just to test this toast will show when alert_toast.show is called.</p>
",https://stackoverflow.com/questions/66613461/calling-toast-show-function-in-unit-testing-in-android-studio,"['android', 'unit-testing', 'toast', 'android-toast']",131,False,1,0
Test javascript in node&#39;s public folder using jest,"<p>I have a simple javascript function in an example.js file placed inside the node js public directory.<br>
I am using jest for unit testing.<br>
The problem is if I write the following in the example.js javascript file in the public folder:<br>
<strong>module.exports.myFunction = myFunction;</strong> <br>
Jest test file is able to import it, using <strong>require()</strong> and perform tests, however when I run the web application, the browser complains when I service the page containing this javascript:
<strong>Uncaught ReferenceError: module is not defined</strong></p>
<p><strong>What is the correct way to test javascript files in the public directory of the node application?</strong> <br>
Using export and/or import in the project is reported an being unrecognized and results in errors as well.</p>
<p>How is this done?</p>
",https://stackoverflow.com/questions/68664749/test-javascript-in-nodes-public-folder-using-jest,"['javascript', 'jestjs', 'public']",426,True,1,1
How to test express + dynamodb using Jest?,"<p>I am new to Jest and unit testing, I have an express API deployed on serverless(Lambda) on AWS.Express api uses dynamodb for crud operations</p>
<p><strong>Note:- my api is based out of express and not just plain node, because on <a href=""https://jestjs.io/docs/dynamodb"" rel=""nofollow noreferrer"">jest website</a> they are telling ways for plain nodejs</strong></p>
<p>I am able to do unit test on express on the methods which doesnt use dynamodb.However it fails for the methods which are using dynamodb, as to my understanding this has something to do with dynamodb being remote, <strong>because the code present in app.js corresponds to dyanmo db which is hosted on aws using lambda.</strong></p>
<p>How do I go about it?</p>
<p>Note:- my api is based out of express and not just plain node</p>
<pre><code>const isUrl = require('is-url');
const AWS = require('aws-sdk');
const { nanoid } = require('nanoid/async');
const express = require('express');

const router = express.Router();
const dynamoDb = new AWS.DynamoDB.DocumentClient();

// URL from users

router.post('/', async (req, res, next) =&gt; {
  // urlId contains converted short url characters generated by nanoid

  const urlId = await nanoid(8);
  const { longUrl } = req.body;

  // Veryfying url Format using isUrl, this return a boolean
  const checkUrl = isUrl(longUrl);
  if (checkUrl === false) {
    res.status(400).json({ error: 'Invalid URL, please try again!!!' });
  }

  const originalUrl = longUrl;
  const userType = 'anonymous'; // user type for anonymous users
  const tableName = 'xxxxxxxxxxxxx'; // table name for storing url's

  const anonymousUrlCheckParams = {
    TableName: tableName,
    Key: {
      userId: userType,
      originalUrl,
    },
  };

  dynamoDb.get(anonymousUrlCheckParams, (err, data) =&gt; {
    const paramsForTransaction = {
      TransactItems: [
        {
          Put: {
            TableName: tableName,
            Item: {
              userId: userType,
              originalUrl,
              convertedUrl: `https://xxxxxxxxxxxxxxxx/${urlId}`,
            },
          },
        },

        {
          Put: {
            TableName: tableName,
            Item: {
              userId: urlId,
              originalUrl,
            },
            ConditionExpression: 'attribute_not_exists(userId)',
          },
        },
      ],
    };
    if (err) {
      console.log(err);
      res
        .status(500)
        .json({ error: 'Unknown Server Error, Please Trimify Again!' });
    } else if (Object.keys(data).length === 0 &amp;&amp; data.constructor === Object) {
      dynamoDb.transactWrite(paramsForTransaction, async (error) =&gt; {
        if (error) {
          // err means converted value as userId is repeated twice.

          console.log(error);
          res
            .status(500)
            .json({ error: 'Unknown Server Error, Please trimify again. ' });
        } else {
          res.status(201).json({
            convertedUrl: `https://xxxxxxxxxxxx/${urlId}`,
          });
        }
      });
    } else {
      res.status(201).json({
        convertedUrl: data.Item.convertedUrl,
      });
    }
  });
});

module.exports = router;
</code></pre>
<p>my test.js</p>
<pre><code>const request = require('supertest');
const app = require('../app');

test('Should convert url from anonymous user ', async () =&gt; {
  await request(app)
    .post('/anon-ops/convert')
    .send({
      longUrl: 'https://google.com',
    })
    .expect(201);
});
</code></pre>
",https://stackoverflow.com/questions/68894242/how-to-test-express-dynamodb-using-jest,"['amazon-web-services', 'express', 'aws-lambda', 'jestjs', 'aws-serverless']",819,True,1,1
Jest spy on super class method &#39;No overload matches this call&#39;,"<p>I have the unit testing of a code in nestjs, where basicly i have a services that extends from a another class, in that class i update the record that has been passed by the function and set the status as inactive. When i'm trying to mock the function inactivate of the UsersService, it works one time, if a do some changes to the test it fails (for example add some white spaces), if i changes again (it success again). Every time that i change the test file, it fails or success, but never twice in a row.</p>
<pre><code>@Injectable({ scope: Scope.REQUEST })
export class UsersService extends DataProvider&lt;User&gt; {

  constructor(
    @Inject(REQUEST)
    private readonly _userRequest: Request,
    @InjectRepository(User)
    private readonly _userRepository: Repository&lt;User&gt;,
    private readonly _configService: ConfigService,
    @Inject(forwardRef(() =&gt; TokensService))
    private readonly _tokenService: TokensService,
    private readonly _rolesService: RolesService,
  ) {
    super(_userRequest, _userRepository);
  }


  /**
   * Get user by id
   * @param {number} id - id of the user to be found
   * @returns {Promise&lt;User&gt;} - User in system
   */
  async getById(id: number): Promise&lt;User&gt; {
    const user = await this._userRepository
      .findOneOrFail({
        where: { id, status: Not(StatusEnum.deleted) },
      })
      .catch(() =&gt; {
        throw new ForbiddenException({
          success: false,
          message: 'You do not have permission on user.',
        });
      });

    return this.format(user);
  }


  /**
   * Inactivate user
   * @param {number} id - id of the user to be activated
   * @returns {Promise&lt;User&gt;} - Inactivate User
   */
  async inactivate(id: number): Promise&lt;User&gt; {
    return await this.inactivateByStatus(await this.getById(id));
  }
}
</code></pre>
<p>Data Provider</p>
<pre><code>export class DataProvider&lt;Entity extends ObjectLiteral&gt; {
  constructor(
    private readonly _request: Request,
    private readonly _repository: Repository&lt;Entity&gt;,
  ) {}

  /**
   * Set the status of the entity as Inactive
   * @param {Entity} entity - entity to inactivate
   * @param {number} [user] - User performing the request
   * @returns {Promise&lt;Entity&gt;} - Inactivated Entity
   */
  protected async inactivateByStatus(
    entity: Entity,
    user?: number,
  ): Promise&lt;Entity&gt; {
    return this.updateEntity(entity, { status: StatusEnum.inactive }, user);
  }

}
</code></pre>
<p>When i perform testing on inactivate function, sometimes works and sometimes dont (without making any change to the code)</p>
<p>Error:</p>
<pre><code>    src/modules/users/test/users.service.spec.ts:55:25 - error TS2769: No overload matches this call.
      Overload 1 of 4, '(object: UsersService, method: FunctionPropertyNames&lt;Required&lt;UsersService&gt;&gt;): SpyInstance&lt;Promise&lt;void&gt; | Promise&lt;...&gt; | Promise&lt;...&gt; | Promise&lt;...&gt;, [id: ...] | ... 7 more ... | [id: ...]&gt;', gave the following error.
        Argument of type '&quot;inactivateByStatus&quot;' is not assignable to parameter of type 'FunctionPropertyNames&lt;Required&lt;UsersService&gt;&gt;'.
      Overload 2 of 4, '(object: UsersService, method: never): SpyInstance&lt;never, never&gt;', gave the following error.
        Argument of type 'string' is not assignable to parameter of type 'never'.

    55     jest.spyOn(service, 'inactivateByStatus').mockImplementation(() =&gt; {
</code></pre>
<p>Test Working:</p>
<p><a href=""https://i.stack.imgur.com/bsMWy.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/bsMWy.png"" alt=""Test working"" /></a></p>
",https://stackoverflow.com/questions/68885020/jest-spy-on-super-class-method-no-overload-matches-this-call,"['typescript', 'unit-testing', 'inheritance', 'jestjs', 'nestjs']",499,False,1,0
Unit test is only running one test (python),"<p>I am trying to implement some unit-testing, and I have various different input files I want to call into my program to test. The function I want to test is located in <code>my_file</code>,
for a function called <code>test_func</code>.</p>
<p>Here is my code:</p>
<pre class=""lang-py prettyprint-override""><code>import unittest
import make_html
    
  
class TestBuild(unittest.TestCase):
        def test_test_func(self):
            # Case 1: blank input file -&gt; Return 'Blank'
            expected_output = 'Blank'
            self.assertEqual(make_html.test_func('blank'),expected_output)

            # Case 2: Non-numeric -&gt; Should raise ValueError
            with self.assertRaises(ValueError):
                make_html.test_func('non_numeric')
                                  

if __name__ == '__main__': # run the main file within unit test package
    unittest.main()

</code></pre>
<p>When I try to run this unit test, it only ever runs 1 of the tests. If I run them separately, they return 'OK'. What am I doing wrong? How do I get it so both tests are run. Furthermore, I want to add even more cases. I am not really sure what it going in here, regarding the syntax surrounding <code>class</code>, <code>self</code>, <code>__name__</code> and <code>__main__</code>.</p>
<p>Update: I tried splitting it into two tests, but I am getting the same result:</p>
<pre class=""lang-py prettyprint-override""><code>import unittest
import make_html
    
  
class TestBuild(unittest.TestCase):
        def test_test_func(self):
            # Case 1: blank input file -&gt; Return 'Blank'
            expected_output = 'Blank'
            self.assertEqual(make_html.test_func('blank'),expected_output)

        def test_test_func(self):
            # Case 2: Non-numeric -&gt; Should raise ValueError
            with self.assertRaises(ValueError):
                make_html.test_func('non_numeric')
                                  

if __name__ == '__main__': # run the main file within unit test package
    unittest.main()

</code></pre>
<p>My output is still just:</p>
<pre><code>----------------------------------------------------------------------
Ran 1 test in 0.001s
</code></pre>
",https://stackoverflow.com/questions/68210412/unit-test-is-only-running-one-test-python,"['python', 'python-3.x', 'unit-testing']",677,True,-1,1
Service method mock with Jest in React app,"<p>I am using React with Typescript and Jest for unit testing. I'm <strong>not</strong> using Enzyme.</p>
<p>I'm trying to understand the mocking capabilities with Jest and specifically to determine something wrong.</p>
<p>I've created a react app using the create-react-app with typescript, i.e.</p>
<pre><code>npx create-react-app my-app --template typescript
</code></pre>
<p>My next step was to create the following inside the src directory.</p>
<pre><code>// services/serviceResponse.ts

export interface ServiceResponse {
    label: string;
    id: string;
  }

// services/myservice.ts

import { ServiceResponse } from &quot;./serviceResponse&quot;;

const cannedServiceResponse: ServiceResponse[] = [
    {
        label: 'label1',
        id: 'id1',
    },
    {
        
        label: 'label2',
        id: 'id2',
    },
]

async function GetServiceData(): Promise&lt;ServiceResponse[] | Error&gt; {
    return cannedServiceResponse;
}
  
export default {
    GetServiceData,
};
  
// components/mycomponent.tsx
import React, { useState, useEffect } from 'react';
import myservice from '../services/myservice';
import { Row } from 'react-bootstrap';
import { ServiceResponse } from '../services/serviceResponse';

export const MyComponent = () =&gt; {
    const [data, setData] = useState&lt;ServiceResponse[] | undefined&gt;();

    useEffect(() =&gt; {
        const fetchData = async () =&gt; {
        const serviceData = await myservice.GetServiceData();
        if (!(serviceData instanceof Error)) {
            setData(serviceData);
        }
        };

        fetchData();
    }, []);

    if (!data) {
        return &lt;&gt;&lt;/&gt;;
    }

    return (
        &lt;&gt;
            &lt;Row xs={1} md={4} className=&quot;col-lg-12&quot;&gt;
            &lt;/Row&gt;
        &lt;/&gt;
    );
};

</code></pre>
<p>Then I want to unit test the Component by mocking the data returned from the service method <code>GetServiceData</code>.  My code for the test component is</p>
<pre><code>// components/mycomponents.test.tsx
import React from 'react';
import TestRenderer from 'react-test-renderer';
import { MyComponent } from './mycomponent';
import myservice from '../services/myservice';
import { Row } from 'react-bootstrap';
import { ServiceResponse } from '../services/serviceResponse';

const mockData: ServiceResponse[] = [
  { label: 'a', id: 'b'},
  { label: 'f', id: 'g'},
];

describe('mycomponent', () =&gt; {
  
  it('MyComponent returns data', () =&gt; {
    jest.spyOn(myservice, 'GetServiceData').mockImplementation(
      () =&gt;
        new Promise&lt;ServiceResponse[]&gt;((resolve) =&gt; {
          resolve(mockData);
        })
    );

    const component = TestRenderer.create(&lt;MyComponent /&gt;);
    const componentInstance = component.root;
    console.log(component.toJSON());
    // TODO - Add an expect line here for assertion
  });
});

</code></pre>
<p>The problem is that the jest.spyOn() doesn't mock the data. I tried using the following also</p>
<pre><code>jest.mock('../services/myservice', () =&gt; ({
  GetServiceData: jest.fn().mockReturnValue(() =&gt; Promise.resolve(mockData)),
}));
</code></pre>
<p>I understand there are ways to test with Enzyme as used <a href=""https://stackoverflow.com/questions/48461243/mocking-external-class-method-inside-react-component-with-jest"">here</a> but I'm trying to understand mocking with Jest and what I'm doing wrong.</p>
",https://stackoverflow.com/questions/69293771/service-method-mock-with-jest-in-react-app,"['reactjs', 'typescript', 'unit-testing', 'jestjs']",811,True,0,1
Vue 3 Unit Test Error - &quot;Cannot find module &#39;@jest/globals&#39;,"<p>I'm pretty new to Vue and also new to Unit Testing. I'm trying to setup my first unit test in my Vue 3 project and I get this error when I try to run the test:</p>
<pre><code>Cannot find module '@jest/globals
</code></pre>
<p>This occurs in my test spec as soon as I try:</p>
<pre><code>jest.mock(&quot;@services/myService.service&quot;);
</code></pre>
<p>My package.json looks like this:</p>
<pre><code>{
  &quot;name&quot;: &quot;vue-myApp&quot;,
  &quot;version&quot;: &quot;0.1.0&quot;,
  &quot;private&quot;: true,
  &quot;scripts&quot;: {
    &quot;serve&quot;: &quot;vue-cli-service serve&quot;,
    &quot;build&quot;: &quot;vue-cli-service build&quot;,
    &quot;test:unit&quot;: &quot;vue-cli-service test:unit&quot;,
    &quot;lint&quot;: &quot;vue-cli-service lint&quot;
  },
  &quot;dependencies&quot;: {
    &quot;axios&quot;: &quot;^0.21.1&quot;,
    &quot;core-js&quot;: &quot;^3.6.5&quot;,
    &quot;dayjs&quot;: &quot;^1.10.6&quot;,
    &quot;primeflex&quot;: &quot;^2.0.0&quot;,
    &quot;primeicons&quot;: &quot;^4.1.0&quot;,
    &quot;primevue&quot;: &quot;^3.5.1&quot;,
    &quot;vue&quot;: &quot;^3.0.0&quot;,
    &quot;vue-class-component&quot;: &quot;^8.0.0-0&quot;,
    &quot;vue-router&quot;: &quot;^4.0.0-0&quot;,
    &quot;vuex&quot;: &quot;^4.0.0&quot;,
    &quot;vuex-persistedstate&quot;: &quot;^4.0.0-beta.3&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@types/jest&quot;: &quot;^24.0.19&quot;,
    &quot;@typescript-eslint/eslint-plugin&quot;: &quot;^4.18.0&quot;,
    &quot;@typescript-eslint/parser&quot;: &quot;^4.18.0&quot;,
    &quot;@vue/cli-plugin-babel&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-plugin-eslint&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-plugin-router&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-plugin-typescript&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-plugin-unit-jest&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-plugin-vuex&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/cli-service&quot;: &quot;~4.5.0&quot;,
    &quot;@vue/compiler-sfc&quot;: &quot;^3.0.0&quot;,
    &quot;@vue/eslint-config-prettier&quot;: &quot;^6.0.0&quot;,
    &quot;@vue/eslint-config-typescript&quot;: &quot;^7.0.0&quot;,
    &quot;@vue/test-utils&quot;: &quot;^2.0.0-rc.14&quot;,
    &quot;eslint&quot;: &quot;^6.7.2&quot;,
    &quot;eslint-plugin-prettier&quot;: &quot;^3.3.1&quot;,
    &quot;eslint-plugin-vue&quot;: &quot;^7.0.0&quot;,
    &quot;flush-promises&quot;: &quot;^1.0.2&quot;,
    &quot;prettier&quot;: &quot;^2.2.1&quot;,
    &quot;sass-loader&quot;: &quot;^11.0.1&quot;,
    &quot;typescript&quot;: &quot;~4.1.5&quot;,
    &quot;vue-jest&quot;: &quot;^5.0.0-0&quot;,
    &quot;webpack&quot;: &quot;^4.46.0&quot;
  }
}
</code></pre>
<p>Are there any packages here that need updating to get this to work?  Is it the Jest version (24.0.19) that is perhaps the cause of this?  Or the version of vue-jest maybe? I've seen another answer somewhere else to a similar question talking about the versions of babel-jest but that does not seem to be in my project? (should it be?)</p>
<p>Many thanks if anyone can help!</p>
",https://stackoverflow.com/questions/69086010/vue-3-unit-test-error-cannot-find-module-jest-globals,"['vue.js', 'jestjs']",460,False,0,0
Unit Test ViewModels and Helper/Manager classes,"<p>I have a question related to Unit testing in android.
The app is written in Kotlin, MVVM architecture, Dagger-Hilt, Room, etc…
I have written all the tests for Room DAOs, according to official docs. I have created fake repositories so I can test some Managers/Helpers (these classes encapsulate logic I have to reuse in many ViewModels) that handle business logic. Now I need to test ViewModels which have these Managers/Helpers as dependencies.
I don’t want to fall into trap of re-testing the same code all over again, the question is how to test ViewModels?
Should I only test the parameters that are passed to functions in these Managers/Helpers, and write assertions for that, or what to do?</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/70276980/unit-test-viewmodels-and-helper-manager-classes,"['android', 'android-viewmodel', 'android-mvvm', 'android-unit-testing']",397,False,0,1
Can I create a unit test in ANgular that makes real http calls without mocking them?,"<p>I have a monolite app in Angular and i'm still trying to understand everything related to unit testing, i need to test some services, i often read online that when it comes to test a service i have to mock the http calls, like get, post, ecc... i can't understand why, is there a way to test it without mocking?
i've also read that i could use a spy, but i don't understand how should i use it...
I just need to test if some http calls returns the values that i expect, what's the most complete way i can do it?
please explain it to me in the siplest way you can or paste any link related to this specific topic.
thanks :)</p>
",https://stackoverflow.com/questions/70196415/can-i-create-a-unit-test-in-angular-that-makes-real-http-calls-without-mocking-t,"['angular', 'typescript', 'unit-testing', 'testing']",618,True,-1,1
Unit testing lists with CollectionAssert.AreEquivalent(),"<p>First, I would like to let you know that this is part of a homework exercise over Unit Testing.</p>
<p>What I need the test to do: I need to test that the list &quot;actual&quot; is equivalent to the list &quot;expected&quot;.</p>
<p>This test fails and I receive this message:</p>
<p><em>CreatePurchasableList_IncludesExpectedItems
Source: GrandTotal.UnitTests.cs line 13
Duration: 30 ms
Message:
CollectionAssert.AreEquivalent failed. The expected collection contains 1 occurrence(s) of &lt;GrandTotal_exercise.Appointment&gt;. The actual collection contains 0 occurrence(s).
Stack Trace:
ProgramTests.CreatePurchasableList_IncludesExpectedItems() line 51</em></p>
<p><strong>The method we want to test...</strong></p>
<pre class=""lang-cs prettyprint-override""><code>public static List&lt;IPurchasable&gt; CreatePurchasableList()
{
    var appointment = new Appointment()
    {
        Name = &quot;James&quot;,
        StartDateTime = DateTime.Now.AddHours(1),
        EndDateTime = DateTime.Now.AddHours(2),
        Price = 100D
    };
    var book = new Book()
    {
        Title = &quot;Welcome to Advanced C#&quot;,
        Price = 50D,
        TaxRate = 0.0825D,
        ShippingRate = 5D
     };
     var snack = new Snack()
     {
         Price = 2D
     };
     var tshirt = new TShirt()
     {
         Size = &quot;2X&quot;,
         Price = 25D,
         TaxRate = 0.0625D,
         ShippingRate = 2
     };

     var items = new List&lt;IPurchasable&gt;();
     items.Add(appointment);
     items.Add(book);
     items.Add(snack);
     items.Add(tshirt);

     return items;
}
</code></pre>
<p><strong>TestMethod...</strong></p>
<pre><code>[TestMethod]
public void CreatePurchasableList_IncludesExpectedItems()
{
    //Arrange
    var appointment = new Appointment()
    {
        Name = &quot;James&quot;,
        StartDateTime = DateTime.Now.AddHours(1),
        EndDateTime = DateTime.Now.AddHours(2),
        Price = 100D
    };
    var book = new Book()
    {
        Title = &quot;Welcome to Advanced C#&quot;,
        Price = 50D,
        TaxRate = 0.0825D,
        ShippingRate = 5D
    };
    var snack = new Snack()
    {
         Price = 2D
    };
    var tshirt = new TShirt()
    {
        Size = &quot;2X&quot;,
        Price = 25D,
        TaxRate = 0.0625D,
        ShippingRate = 2
    };
    var expectedList = new List&lt;IPurchasable&gt;();         
    var purchasableListActual = Program.CreatePurchasableList();
            
    //Act
    expectedList.Add(appointment);
    expectedList.Add(book);
    expectedList.Add(snack);
    expectedList.Add(tshirt);
    //Assert
    CollectionAssert.AreEquivalent(expectedList, purchasableListActual);
}
</code></pre>
<p>To be more clear I want to ensure that both tests include &quot;appointment&quot;, &quot;book&quot;, &quot;snack&quot;, and &quot;t-shirt&quot;.</p>
<p>I do not care what is inside of these objects or the order that they are in.</p>
",https://stackoverflow.com/questions/66198649/unit-testing-lists-with-collectionassert-areequivalent,"['c#', 'unit-testing', 'mstest']",156,False,0,0
"Disable TestNG for failsafe maven plugin, keep only for surefire","<p>I have mixed unit testing frameworks (for surefire maven plugin) in a project: JUnit + TestNG (almost all tests are JUnit tests but TestNG was included by <a href=""https://www.reactive-streams.org/reactive-streams-tck-1.0.3-javadoc/org/reactivestreams/tck/package-summary.html"" rel=""nofollow noreferrer"">reactive-streams TCK</a> framework, which is required for two tests. All integration tests (failsafe) are only JUnit tests. I managed to configure surefire to run both tests: JUnit and TestNG with this plugin configuration:</p>
<pre class=""lang-xml prettyprint-override""><code>    &lt;plugins&gt;
      &lt;plugin&gt;
        &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
        &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
        &lt;version&gt;${surefire.version}&lt;/version&gt;
        &lt;dependencies&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.7.2&lt;/version&gt;
          &lt;/dependency&gt;
        &lt;/dependencies&gt;
        &lt;executions&gt;
          &lt;execution&gt;
            &lt;id&gt;surefire-testng&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;false&lt;/skip&gt;
              &lt;includes&gt;
                &lt;include&gt;&lt;!-- test one --&gt;&lt;/include&gt;
                &lt;include&gt;&lt;!-- test two --&gt;&lt;/include&gt;
              &lt;/includes&gt;
              &lt;junitArtifactName&gt;none:none&lt;/junitArtifactName&gt;
            &lt;/configuration&gt;
          &lt;/execution&gt;
          &lt;execution&gt;
            &lt;id&gt;surefire-junit&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;false&lt;/skip&gt;
              &lt;excludes&gt;
                &lt;exclude&gt;&lt;!-- test one --&gt;&lt;/exclude&gt;
                &lt;exclude&gt;&lt;!-- test two --&gt;&lt;/exclude&gt;
              &lt;/excludes&gt;
              &lt;testNGArtifactName&gt;none:none&lt;/testNGArtifactName&gt;
            &lt;/configuration&gt;
          &lt;/execution&gt;
        &lt;/executions&gt;
      &lt;/plugin&gt;
</code></pre>
<p>And this config is working fine, when I run <code>mvn test</code> Maven run surefire tests.</p>
<p>But when I try to run <code>mvn verify</code> to check failsafe tests, Maven fails with error:</p>
<pre><code>[ERROR] org.apache.maven.surefire.booter.SurefireExecutionException: Exception in provider
[ERROR]     at org.apache.maven.plugin.surefire.InPluginVMSurefireStarter.runSuitesInProcess(InPluginVMSurefireStarter.java:91)
[ERROR]     at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1198)
[ERROR]     at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:1063)
[ERROR]     at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:889)
[ERROR]     at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
[ERROR]     at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
[ERROR]     at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
[ERROR]     at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
[ERROR]     at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
[ERROR]     at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
[ERROR]     at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
[ERROR]     at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
[ERROR]     at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
[ERROR]     at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
[ERROR]     at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
[ERROR]     at org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)
[ERROR]     at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)
[ERROR]     at org.apache.maven.cli.MavenCli.main(MavenCli.java:193)
[ERROR]     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[ERROR]     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[ERROR]     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[ERROR]     at java.base/java.lang.reflect.Method.invoke(Method.java:566)
[ERROR]     at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
[ERROR]     at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
[ERROR]     at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
[ERROR]     at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
[ERROR] Caused by: java.lang.NoSuchMethodError: 'void org.testng.xml.XmlSuite.setParallel(java.lang.String)'
[ERROR]     at org.apache.maven.surefire.testng.conf.TestNGMapConfigurator.configure(TestNGMapConfigurator.java:71)
[ERROR]     at org.apache.maven.surefire.testng.conf.TestNG510Configurator.configure(TestNG510Configurator.java:40)
[ERROR]     at org.apache.maven.surefire.testng.TestNGExecutor.run(TestNGExecutor.java:110)
[ERROR]     at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.executeSingleClass(TestNGDirectoryTestSuite.java:112)
[ERROR]     at org.apache.maven.surefire.testng.TestNGDirectoryTestSuite.execute(TestNGDirectoryTestSuite.java:99)
[ERROR]     at org.apache.maven.surefire.testng.TestNGProvider.invoke(TestNGProvider.java:146)
[ERROR]     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[ERROR]     at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[ERROR]     at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[ERROR]     at java.base/java.lang.reflect.Method.invoke(Method.java:566)
[ERROR]     at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray2(ReflectionUtils.java:186)
[ERROR]     at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:161)
[ERROR]     at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:84)
[ERROR]     at org.apache.maven.plugin.surefire.InPluginVMSurefireStarter.runSuitesInProcess(InPluginVMSurefireStarter.java:87)
[ERROR]     ... 25 more
[ERROR] -&gt; [Help 1]
</code></pre>
<p>The full source code and plugin configuration is available here: <a href=""https://github.com/artipie/http/tree/multipart"" rel=""nofollow noreferrer"">https://github.com/artipie/http/tree/multipart</a></p>
<p>What is the correct way to disable TestNG in failsafe plugin and keep it only in surefire?</p>
",https://stackoverflow.com/questions/68450545/disable-testng-for-failsafe-maven-plugin-keep-only-for-surefire,"['java', 'maven', 'junit', 'testng']",370,True,0,1
How to monkeypatch method that&#39;s deep inside a library for only a single module?,"<p>I want to monkeypatch the <code>assert_fingerprint</code> method defined for urllib3 in this file: <a href=""https://github.com/urllib3/urllib3/blob/main/src/urllib3/util/ssl_.py"" rel=""nofollow noreferrer"">https://github.com/urllib3/urllib3/blob/main/src/urllib3/util/ssl_.py</a></p>
<p>However, we're not using urllib3 directly. We're using the requests library, which uses urllib3 below the surface. Additionally, I only want a single class in my code to have the &quot;monkeypatched version&quot; when using the requests interface, everywhere else in my code the normal behavior is expected. This is for production use, not for (unit)testing usage.</p>
<p>There's a lot of information out and about on how to patch or monkeypatch, but they're usually very tailored to specific classes that can be imported directly. Would I have to track down the entire import-chain here starting from requests to get down to this file?</p>
",https://stackoverflow.com/questions/66099221/how-to-monkeypatch-method-thats-deep-inside-a-library-for-only-a-single-module,"['python', 'python-3.x', 'python-requests', 'urllib3']",144,False,0,0
How do I unit test &quot;non standalone functions&quot;?,"<p>I have the knowledge of unit testing standalone functions like helper classes but how do I deal with functions that are not standalone, typically within a class file that has multiple validations and results?</p>
<p>Example below showing multiple conditions check and response in different result.</p>
<ul>
<li>Do I call the <code>valueCheck</code> and <code>proceedApiCheck</code> function in my test case? But there're different scenarios or actions I don't need within test. (eg, setState / navigating)</li>
<li>Do I write a new function of <code>valueCheck</code> and <code>proceedApiCheck</code> in my test case? But this will means I'm having 2 different logic in my code. Someday if I change my logic in app, my test case will not fail since it's referring to the old logic.</li>
</ul>
<p>Can any of you shed some light on this?</p>
<p><strong>Example</strong></p>
<pre><code>export class Screen1 extends React.Component {

    valueCheck = (value) =&gt; {
        if(value === 'abc'){
            this.setState({ isNavigating:true, transfer: true })
            this.proceedApiCheck(value)
        }
        if(value === '123'){
            this.setState({ isNavigating:true, transfer: false })
            this.proceedApiCheck(value)
        }
    }

    proceedApiCheck = async(value) =&gt;{
        let data
        try{
            data = await FirstApi(value);
            this.setState(data)
        }catch(){
            this.navigateToScreen('Failure')
            return;
        }

        switch(data.name){
            case 'fake adidas':
                this.navigateToScreen('Failure')
                return;
            case 'fake nike':
                this.navigateToScreen('Failure')
                return; 
        }
        
        try{
            const result = await secondApi(data.price);

            switch(result.currency){
                case 'EURO':
                    this.navigateToScreen('Euro')
                case 'Pound':
                    this.navigateToScreen('Pound')
                default: 
                    this.navigateToScreen('Dollar')
            }
        }catch(){
            this.navigateToScreen('Failure')
            return;
        }
    }


}
</code></pre>
",https://stackoverflow.com/questions/68707959/how-do-i-unit-test-non-standalone-functions,"['javascript', 'reactjs', 'react-native', 'jestjs']",184,True,0,2
Updating state causing tests to not stop,"<p>I have a React application. I am using Jest and React Testing library for unit testing.</p>
<p>I have to test a component. In the useEffect of the component, there is an API call made and once the response is received, we update the component's local state.</p>
<pre><code>const [data, setData] = useState({})

useEffect(()=&gt;{
  // Make API call to a custom fetch hook
},[])

useEffect(()=&gt;{
  setData(response.data) //response data is a JSON object
},[response])
</code></pre>
<p>The test files code snippet is as below -</p>
<pre><code>const {getByTestId} = render(&lt;MyComponent&gt;&lt;/MyComponent&gt;)
</code></pre>
<p>I have not put any assertions yet because of the inifinite running test cases</p>
<p>What have I done? I have been able to mock the fetch call and execute setData.</p>
<p>The problem - The tests keep running forever. But if I change the response.data to some boolean or string or number, the tests do not run infinitly.
Also, if I put a dummy object in the initialization of the state, the tests run fine.</p>
<pre><code>const [data, setData] = useState({
  name: 'Test',
  Age: '99'
})
</code></pre>
",https://stackoverflow.com/questions/69089546/updating-state-causing-tests-to-not-stop,['javascript'],83,True,0,1
Making mockito to use the real Log4j during unit testing,"<p>During the unit testing of method <em>Utility#sum</em>, I want that the <em>log</em> should print the <em>sum</em> on the console.</p>
<pre class=""lang-java prettyprint-override""><code>public class Utility {

    private static Logger log = Logger.getLogger(Utility.class);
   
    private Utility() {
    }

    public static Integer getSum(Integer a, Integer b) {
        Integer sum = a + b
        log.info(sum);
        return sum;
    }
}
</code></pre>
<p>For that in my test <em>testGetSumRealLogger</em> I am passing a real <em>Logger log = Logger.getLogger(getClass())</em>, but in method <em>Utility#sum</em> its is initialized to null.</p>
<p>In my second test <em>testGetSumMockedLogger</em> I am passing a mocked  <em>Logger log = Mockito.mock(Logger.class)</em>, this time the log inside method Utility#sum is not null, but does not print anything.</p>
<pre class=""lang-java prettyprint-override""><code>class UtilityTest {

    @Test
    void testGetSumRealLogger() throws Exception {
        try (MockedStatic&lt;Logger&gt; mockedStaticLoggerBean = Mockito.mockStatic(Logger.class)) {

            Logger log = Logger.getLogger(getClass());
            mockedStaticLoggerBean.when(() -&gt; Logger.getLogger(Utility.class)).thenReturn(log);

            assertEquals(4, Utility.getSum(2, 2));
        }
    }

    @Test
    void testGetSumMockedLogger() throws Exception {
        try (MockedStatic&lt;Logger&gt; mockedStaticLoggerBean = Mockito.mockStatic(Logger.class)) {

            Logger log = Mockito.mock(Logger.class);
            mockedStaticLoggerBean.when(() -&gt; Logger.getLogger(Utility.class)).thenReturn(log);

            assertEquals(4, Utility.getSum(2, 2));
        }
    }

}

</code></pre>
<p>How can I get the Logger to print something in the Utility#sum method without refactoring the code.
I am using Junit 5 with mockito-inline, 3.11.2.
I also have a proper log4j.xml in the test resources.
Please avoid suggesting logging is bad during the unit test.</p>
",https://stackoverflow.com/questions/68834741/making-mockito-to-use-the-real-log4j-during-unit-testing,"['mockito', 'log4j', 'junit5']",847,True,0,1
How to initialize object without default constructor and heap usage?,"<p>During programming an embedded system without MMU, I should not use heap (because of memory fragmentation problem).</p>
<p>Part of the software is written in <em>C</em> (drivers) and the logic is written in <em>C++</em> subset without dynamic allocation of memory.</p>
<p>Because of unit testing the default constructor is deleted. Instead - there is single parameter constructor with reference to structure of driver function pointers.</p>
<p><strong>driver.h:</strong> (the pure C module)</p>
<pre class=""lang-c prettyprint-override""><code>#pragma once
bool Init();
uint32_t ReadMeasurement();
</code></pre>
<p><strong>module.hpp:</strong> (the C++ part)</p>
<pre class=""lang-c++ prettyprint-override""><code>class Module {
public:
  struct DriverApi {
    void (*Init)();
    uint32_t (*ReadData)();
  };

  Module() = delete;
  explicit Module(DriverApi &amp;aDriverApi);

private:
  DriverApi&amp; mDriverApi;
};
</code></pre>
<p>The module manager:</p>
<p><strong>module_manager.hpp:</strong></p>
<pre class=""lang-c++ prettyprint-override""><code>class ModuleManager {
//  (...)
private:
  Module::DriverApi module_1; // I can't declare this in this way
  Module::DriverApi module_2; // because of lack of default constructor.
  Module::DriverApi module_3;
  etc.
};
</code></pre>
<p>How to initialize <code>module_1</code>, <code>module_2</code> and <code>module_3</code> without using heap? And <code>n</code> parameters constructor?</p>
<p><strong>Options I'm aware:</strong></p>
<ul>
<li>It look's easy to use <code>std::shared_ptr</code>, but then <code>std::make_shared</code> <em>use heap</em>.</li>
<li>I can leave default constructor and then call sth. like <code>Init(Module::DriverApi *aDriverApi)</code> but this <em>&quot;violates&quot; RAII</em>.</li>
</ul>
<p>Is there any other way to create &quot;elegant&quot; and <em>embedded safe</em> initialization?</p>
",https://stackoverflow.com/questions/66475605/how-to-initialize-object-without-default-constructor-and-heap-usage,"['c++', 'embedded']",389,True,0,2
Unit testing Flask-wtfoms with pytest,"<p>This is a follow up to my <a href=""https://stackoverflow.com/questions/68489027/sorting-and-deleting-a-1-to-many-relatiionship-in-sqlalchemy-and-flask"">previous question.</a> I have built the forms and pages and have moved onto testing it with unit testing. However when I try running my unit tests with a new SQLite database test.db it cannot find the tables within and if I use my main data.db it is unable to read the content of <a href=""https://i.stack.imgur.com/4XgSJ.png"" rel=""nofollow noreferrer"">homepage table</a></p>
<p>In my unit_test.py I have the following for the test base</p>
<pre><code>from flask_testing import TestCase
from flask_sqlalchemy import SQLAlchemy
from flask import url_for
import os

from application import app, db
from application.models import Company, Frankendama
class TestBase(TestCase):
def create_app(self):

    app.config.update(
        SQLALCHEMY_DATABASE_URI=&quot;sqlite:///test.db&quot;,
        SECRET_KEY='TEST_SECRET_KEY',
        DEBUG=True,
        WTF_CSRF_ENABLED=False
    )

    return app

def set_up(self):
    db.create_all()

    frank1 = Frankendama(
        title=&quot;Taps&quot;,
        description=&quot;A combo of damas designed for taps&quot;,
        tama=&quot;SK x Cereal STIK&quot;,
        sarado=&quot;Lomond Shape&quot;,
        sword=&quot;Lomond Shape&quot;,
        string=&quot;72&quot;,
        bearing=&quot;Yes&quot;
    )

    company1 = Company(name = &quot;CEREAL&quot;, frankendama_id = 1)
    company2 = Company(name = &quot;SK&quot;, frankendama_id = 1)

    db.session.add(frank1)
    db.session.add(company1)
    db.session.add(company2)

    db.session.commit()

def tear_down(self):

    db.session.remove()
    db.drop_all()
</code></pre>
<p>After the base I have 3 more test classes:</p>
<ul>
<li>TestRead</li>
<li>TestUpdate</li>
<li>TestDelete</li>
</ul>
<p>They look like this:</p>
<p>class TestRead(TestBase):</p>
<pre><code>def test_home(self):
    response = self.client.get(
        url_for('home'),
        follow_redirects= True
        )

    assert &quot;Taps&quot; in response.data.decode()
    assert &quot;Check updated task&quot; in response.data.decode()
    assert &quot;SK x Ceral STIK&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;72&quot; in response.data.decode()
    assert &quot;Yes&quot; in response.data.decode()
    assert &quot;CEREAL&quot; in response.data.decode()
    assert &quot;SK&quot; in response.data.decode()
</code></pre>
<p>class TestUpdate(TestBase):</p>
<pre><code>def test_update(self):
    response = self.client.post(
        url_for('update', id=1),
        data={&quot;description&quot;: &quot;Check updated task&quot;},
        follow_redirects= True
    )

    assert &quot;Taps&quot; in response.data.decode()
    assert &quot;Check updated task&quot; in response.data.decode()
    assert &quot;SK x Ceral STIK&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;72&quot; in response.data.decode()
    assert &quot;Yes&quot; in response.data.decode()
    assert &quot;CEREAL&quot; in response.data.decode()
    assert &quot;SK&quot; in response.data.decode()

    assert &quot;A combo of damas designed for taps&quot; not in response.data.decode()


def test_update_companies(self):
    response = self.client.post(
        url_for('update', id=1),
        data={&quot;companies&quot;: &quot;SWEETS&quot;},
        follow_redirects= True
    )

    assert &quot;Taps&quot; in response.data.decode()
    assert &quot;A combo of damas designed for taps&quot; in response.data.decode()
    assert &quot;SK x Ceral STIK&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;Lomond Shape&quot; in response.data.decode()
    assert &quot;72&quot; in response.data.decode()
    assert &quot;Yes&quot; in response.data.decode()
    assert &quot;SWEETS&quot; in response.data.decode()
    assert &quot;SK&quot; not in response.data.decode()
    assert &quot;CEREAL&quot; not in response.data.decode()
</code></pre>
<p>class TestDelete(TestBase):</p>
<pre><code>def test_delete(self):
    response = self.client.get(
        url_for('delete', id=1),
        follow_redirects=True
    )

    assert &quot;Taps&quot; not in response.data.decode()
    assert &quot;A combo of damas designed for taps&quot; not in response.data.decode()
    assert &quot;SK x Ceral STIK&quot; not in response.data.decode()
    assert &quot;Lomond Shape&quot; not in response.data.decode()
    assert &quot;Lomond Shape&quot; not in response.data.decode()
    assert &quot;72&quot; not in response.data.decode()
    assert &quot;Yes&quot; not in response.data.decode()
</code></pre>
<p>Everytime I try run pytest --cov=app to see the coverage i get these errors:</p>
<pre><code>  sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: frankendama
  ======== 6 failed, 1 passed, 21 warnings in 5.72s =========
  
</code></pre>
<p>Overall I am super stumped, any suggestions are <em>hugely</em> welcome!</p>
",https://stackoverflow.com/questions/68501851/unit-testing-flask-wtfoms-with-pytest,"['python', 'flask-wtforms', 'pytest-cov']",78,True,0,1
try-catch dependencies in unit tests?,"<p>I'm relative new to unit tests but I want to start unit testing legacy ASP NET MVC app.
For example I have function PrepareModel that does a lot of things and have multiple dependencies.
I added newFeature to my model and created myNewCode, to get this feature.</p>
<pre><code>public Model PrepareModel(){
  Model model = new Model();
  model.mainPropertie = getFromDataBase();
  
  model.someIrrelevantProperty1 = getValueFromSomeDependency();
  model.someIrrelevantProperty2 = getValueFromSomeDependency();
  
  model.newFeature = myNewCode();
  return model;
}
</code></pre>
<p><strong>I want to Unit test PrepareModel() that model.newFeature is got correctly.</strong></p>
<p>I successfully mocked database but there are plenty of irrelevant dependencies. I don't have so much time to refactor out them all.</p>
<p><strong>Would it be acceptable to add try-catch wrap around features that's irrelevant to test?</strong>
And maybe in future I would refactor them out when there will be next task in this functionality.</p>
<pre><code>public static bool isTest { get; set; }
public Model PrepareModel(){
  Model model = new Model();
  model.mainPropertie = getFromDataBase();
  
  try{
    model.someIrrelevantProperty1 = getValueFromSomeDependency();
    model.someIrrelevantProperty2 = getValueFromSomeDependency();
  } 
  catch(Exception ex) {
    if (!isTest)
      throw ex;
  }
  
  model.newFeature = myNewCode();
  return model;
}
</code></pre>
<p>If that's not acceptable what should I do?</p>
",https://stackoverflow.com/questions/66060905/try-catch-dependencies-in-unit-tests,"['c#', 'unit-testing']",70,True,0,1
"In Angular, why would I use jasmine.createSpyObj instead of simply passing an object to the provider&#39;s useValue?","<p>I'm just getting started with Angular and unit testing and I'd like to test a <code>Component</code> that has a dependency on <code>ActivatedRoute</code>.</p>
<p>My <code>Component</code> has an <code>ngOnInit</code> method that looks like so:</p>
<pre><code>async ngOnInit() {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    //get data using the id
}
</code></pre>
<p>So in my test's <code>beforeEach</code> function I'm trying to set up the testbed like so (note, this was <em>before</em> I got my test to work):</p>
<pre><code>    let mockRoute;

    beforeEach(async () =&gt; {
        //this example didn't work, the test failed trying to reach the .get('id') call
        mockRoute = jasmine.createSpyObj('mockRoute', ['snapshot.paramMap.get']);
        await TestBed.configureTestingModule({
            providers: [{ provide: ActivatedRoute, mockRoute }],
            declarations: [ MyComponentToTest ]
        })
        .compileComponents();
    });
</code></pre>
<p>I was using <code>jasmine.createSpyObj</code> because I was following a pluralsight example, but after the example above didn't work, I ended up finding this on the interwebs:</p>
<pre><code>beforeEach(async () =&gt; {
    //this example worked
    await TestBed.configureTestingModule({
        providers: [
        {
            provide: ActivatedRoute,
            useValue: {
                snapshot: {
                    paramMap: {
                        get: () =&gt; 1
                    }
                }
            }
        }],
        declarations: [ MyComponentToTest ]
    })
    .compileComponents();
});
</code></pre>
<p>I see plenty of documentation (and the pluralsight video) on using <code>jasmine.createSpyObj</code> to create mocks but in my case it did not work as well as <code>useValue</code>, so then does anybody know why anyone would use the <code>jasmine.createSpyObj</code> instead? does it exist for a very specific use that <code>useValue</code> can't work with?</p>
",https://stackoverflow.com/questions/67374555/in-angular-why-would-i-use-jasmine-createspyobj-instead-of-simply-passing-an-ob,"['angular', 'unit-testing', 'jasmine']",650,False,0,1
Running unit test using Xunit,"<p>I have added a unit testing class and added the below references to my main class library in the UWP project.</p>
<p><a href=""https://i.stack.imgur.com/w4ZT4.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/w4ZT4.png"" alt=""references"" /></a></p>
<p>When I add a new class library and add my test classes there the test methods on the class library execute but the test methods on the main project throw the below exception.</p>
<pre><code>System.InvalidOperationException: The following test container was not found: 'F:\test\WinApp\bin\x64\Debug\WinApp.exe'. This can be resolved by one or more of the following steps:
1. The test container does not exist on disk and the corresponding project might need to be built successfully.
2. For .NET Core based test projects, please ensure that a nuget package reference to &quot;Microsoft.NET.Test.SDK&quot; exists and that it uses the latest stable version.
3. For .NET based test projects, the project might be marked as a non-test project through an msbuild property, &quot;IsTestProject&quot;. Please consider clearing it or set &quot;&lt;IsTestProject&gt;true&lt;/IsTestProject&gt;&quot; in a &quot;&lt;PropertyGroup&gt;&quot; in the test project.
   at Microsoft.VisualStudio.TestWindow.Client.TestContainer.TestContainerProvider.&lt;GetTestContainerAsync&gt;d__42.MoveNext()
</code></pre>
<p>I tried the above approaches but no use.</p>
<p>I want to write my test classes inside my main class library which is executable any suggestions.I am trying this as I cannot add references to the main class library from the test project and run it.Below error throws if I try to do so.</p>
<p><a href=""https://i.stack.imgur.com/RZauD.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/RZauD.png"" alt=""enter image description here"" /></a>
My test project is a Unit Test App(Universal Windows)</p>
<p><a href=""https://i.stack.imgur.com/acsOH.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/acsOH.png"" alt=""enter image description here"" /></a></p>
<p>I am not running in a build server</p>
",https://stackoverflow.com/questions/66471180/running-unit-test-using-xunit,"['c#', 'visual-studio', 'unit-testing', 'uwp', 'xunit']",616,False,0,0
XUnit Mock not throwing exception like I would expect,"<p>I have the following test that uses a mock of a class. When I try to throw an exception it never actually throws the exception. It goes on as if the method is actually being called and I am unsure why.</p>
<p>Here is the test:</p>
<pre><code>[Fact]
public async Task ReadResultSetShouldRetry()
{
    // Arrange
    _cosmosUtilWrapper.Setup(x =&gt; x.ReadCosmosResultSet&lt;CosmosRepositoryTests&gt;(It.IsAny&lt;FeedIterator&gt;(), It.IsAny&lt;ILogger&gt;(), It.IsAny&lt;CancellationToken&gt;()))
        .Throws(new Exception(&quot;It broke&quot;));

    var cosmosReadPolicy = new CosmosReadPolicy();

    // Act
    await Assert.ThrowsAsync&lt;Exception&gt;(async () =&gt; await CosmosRepository.ReadCosmosResultSetWithRetry&lt;CosmosRepositoryTests&gt;(_mockFeedIterator.Object, _logger, cosmosReadPolicy, CancellationToken.None));
    // Assert
    _cosmosUtilWrapper.Verify(x =&gt; x.ReadCosmosResultSet&lt;CosmosRepositoryTests&gt;(_mockFeedIterator.Object, _logger, default));
}
</code></pre>
<p>Here is the method that it is calling and I have it wrapped in a retry policy:</p>
<pre><code>public static async Task&lt;List&lt;T&gt;&gt; ReadCosmosResultSetWithRetry&lt;T&gt;(
    FeedIterator resultSet,
    ILogger logger,
    CosmosReadPolicy cosmosReadPolicy,
    CancellationToken cancellationToken = default)
    where T : class
{
    CosmosUtilWrapper utilWrapper = new CosmosUtilWrapper();

    var readCosmosResultSet = await cosmosReadPolicy.GetPolicy.ExecuteAsync(async () =&gt; await utilWrapper.ReadCosmosResultSet&lt;T&gt;(resultSet, logger, cancellationToken));

    return readCosmosResultSet;
}
</code></pre>
<p>Here is the CosmosUtilWrapper and below is the actual Cosmos Util class:</p>
<pre><code>public class CosmosUtilWrapper
{
    public virtual async Task&lt;List&lt;T&gt;&gt; ReadCosmosResultSet&lt;T&gt;(
        FeedIterator resultSet,
        ILogger logger,
        CancellationToken cancellationToken = default)
        where T : class
    {
        return await CosmosUtil.ReadCosmosResultSet&lt;T&gt;(resultSet, logger, cancellationToken);
    }
}
</code></pre>
<p>Here is the actual static Util method that is being returned in the above class. Had to go about it this way since this class is a static class and unit testing those are not very fun.</p>
<pre><code>public static async Task&lt;List&lt;T&gt;&gt; ReadCosmosResultSet&lt;T&gt;(
    FeedIterator resultSet,
    ILogger logger,
    CancellationToken cancellationToken = default)
    where T : class
{
    var foundDocuments = new List&lt;T&gt;();
    while (resultSet.HasMoreResults)
    {
        using ResponseMessage responseMessage = await resultSet.ReadNextAsync(cancellationToken);
        if (responseMessage.IsSuccessStatusCode)
        {
            using StreamReader streamReader = new StreamReader(responseMessage.Content);
            using JsonTextReader textReader = new JsonTextReader(streamReader);
            foundDocuments.AddRange((await JObject.LoadAsync(textReader, cancellationToken)).GetValue(&quot;Documents&quot;).ToObject&lt;List&lt;T&gt;&gt;());
        }
        else
        {
            throw new Exception($&quot;Unable to read cosmos result set. Status code: {responseMessage.StatusCode}&quot;);
        }
    }

    return foundDocuments;
}
</code></pre>
<p>Finally, Here is the message I get when running the tests</p>
<pre><code>  Message: 
    Assert.Throws() Failure
    Expected: typeof(System.Exception)
    Actual:   (No exception was thrown)
</code></pre>
",https://stackoverflow.com/questions/68025782/xunit-mock-not-throwing-exception-like-i-would-expect,"['c#', 'unit-testing', 'xunit']",729,True,0,1
Jest only run tests that end in .test.js inside &quot;__tests__&quot; folder,"<p>Answer: it had nothing to do with the regex but with the position of the <code>jest.config.js</code> file, changing <code>rootDir</code>in the config fixed the issue</p>
<p>I have a working regex in regex101.com but I can make it work in Jest</p>
<pre><code>__tests__\/.*test.[jt]sx?$
</code></pre>
<p>result given (regex101):</p>
<pre><code>__tests__/__config/jest.config.js -&gt; no
__tests__/app.test.js -&gt; yes
__tests__/app.test.ts -&gt; yes
__tests__/app.test.tsx -&gt; yes
__tests__/api/app.test.js -&gt; yes
__tests__/api/app.test.not -&gt; no
__tests__/api/api2/api3/app.test.js -&gt; yes
toto.test.js -&gt; no
</code></pre>
<p>which is exactly what I want, but when I update the <code>jest.config.js</code></p>
<p>Jest config:</p>
<pre><code>module.exports = {
  testRegex: [&quot;__tests__/.*test.[jt]sx?$&quot;],
};
</code></pre>
<p>it doesn't find anything.</p>
<p><strong>What I'm looking to do</strong>: I want to store everything related to unit testing inside the <code>__tests__</code> folder, including the <code>jest.config.js</code> and other stuff that does not has to be run by Jest.</p>
<p>In <em>package.json</em> run the config inside the <code>__tests__</code> folder</p>
<pre><code>...
&quot;test&quot;: &quot;jest --config ./__tests__/__config/jest.config.js&quot;
...
</code></pre>
<p>So it gives me something like:</p>
<pre><code>__tests__/
    __config/
        jest.config.js -&gt; do not run
        dabatase.js -&gt; do not run
    user/
        user.test.js -&gt; run this
        user.mock.js -&gt; do not run 
</code></pre>
<p>So basically only the things that end in <code>.test.js/ts</code> that are inside the <code>__tests__</code> folder</p>
<p>Here is a small repo with the current (non functional) config: <a href=""https://github.com/Antoine-lb/jest-regex-config"" rel=""nofollow noreferrer"">Github Repo</a></p>
<p>Thanks</p>
",https://stackoverflow.com/questions/66784214/jest-only-run-tests-that-end-in-test-js-inside-tests-folder,"['javascript', 'regex', 'jestjs']",1081,False,4,0
Firebase deploy: Missing expected firebase config value databaseURL,"<p>I'm trying to deploy my first function with firebase cloud functions.
I deployed the standard function &quot;helloWorld&quot; without problem, but then, when I added this:</p>
<pre><code>const admin = require(&quot;firebase-admin&quot;);
admin.initializeApp(); 
</code></pre>
<p>firebase deploy didn't work anymore and caused this error:</p>
<blockquote>
<p>Missing expected firebase config value databaseURL, config is actually{&quot;projectId&quot;:&quot;PROJECT-ID&quot;,&quot;storageBucket&quot;:&quot;PROJECT-ID.appspot.com&quot;,&quot;locationId&quot;:&quot;europe-west&quot;}</p>
<p>If you are unit testing, please set process.env.FIREBASE_CONFIG</p>
</blockquote>
<p>How can I set config or the value of databaseURL? I don't find anywhere the file where these things are written... I also looked in documentation but I didn't find anything useful
I tried also with</p>
<pre><code>admin.initializeApp(process.env.FIREBASE_CONFIG); 
</code></pre>
<p>but this give me this error:</p>
<blockquote>
<p>Error: Error occurred while parsing your function triggers.</p>
<p>Error: Invalid Firebase app options passed as the first argument to initializeApp() for the app named &quot;[DEFAULT]&quot;. Options must be a non-null object.</p>
</blockquote>
",https://stackoverflow.com/questions/66205288/firebase-deploy-missing-expected-firebase-config-value-databaseurl,"['javascript', 'firebase', 'google-cloud-functions']",4623,True,4,2
Is there a way to call TestServer using only Httpclient without using TestServer.GetTestClient()?,"<p>I have built a unit test project in .NET Core 5.0 to test my API's. I have created a test server using HostBuilder. In my unit testing class I am calling an API using
HttpClient client;
client = TestServer.GetTestClient(); in all methods. It' working and no issues.</p>
<p>But in couple of unit test methods when request goes to BL(Business logic level) I need to make a call to TestServer to get the token then the actual problem starts. I can't make a call using Httpclient without using TestServer.GetTestClient() because if I do that it says the hosting server have actively refused to connect. And I can't make a call using TestServer.GetTestClient() because it will be a cyclic dependency on main project.</p>
<p>Is there a way to call TestServer using only Httpclient without using TestServer.GetTestClient()?</p>
",https://stackoverflow.com/questions/66597404/is-there-a-way-to-call-testserver-using-only-httpclient-without-using-testserver,"['.net-core', 'xunit.net', 'testserver']",101,False,4,0
How to do a unit test of an external devices register which is read-only?,"<p>I am a newbie at TDD and Unit testing and currently reading James Greenings book TDD for Embedded C.</p>
<p>I really adopt to use dual targeting because it provides to test my case in both host and target device.</p>
<p>I am unit testing my amplifier driver and there are two requirements which are declared as</p>
<p><em>Driver shall read fault notification pin on amplifier IC manually, whenever requested.</em></p>
<p><em>Fault notification pin shall trigger the system when any fault occurred.</em></p>
<p>As you see, there should be a read_fault_notification function which is passed address and access the hardware. Everything is ok till here.</p>
<p>Here is my <strong>amplifier_get_fault_notification function</strong> in <strong>amplifier.c</strong></p>
<p><strong>amplifier.c</strong></p>
<pre><code>fault_state_t amplifier_get_fault_notification(amplifier_t device)
{   
    return device-&gt;fault.fault_state= amplifier_gpio_read(device-&gt;fault.fault_address);
}
</code></pre>
<p>Now, amplifier_gpio_read is linked to the target-specific function at <strong>hardware.c</strong> hence, Hardware abstraction provides.</p>
<pre><code>static state_t target_device_gpio_read(uint8_t pin_name)
{
    switch(pin_name)
    {
    case FAULT1:/*Fault pin @ Loudspeaker1*/
            /*
                 * TO DO: Read IO for fault pin of Loudspeaker Amplifier1, if required.
                 */
        break;
    case FAULT2:/*Fault pin @ Loudspeaker2*/
            /*
                * TO DO: Read IO for fault pin of Loudspeaker Amplifier2, if required.
                */
        break;
    case FAULT3:/*Fault pin @ Loudspeaker3*/
            /*
                * TO DO: Read IO for fault pin of Loudspeaker Amplifier3, if required.
                */
        break;
    case FAULT4:/*Fault pin @ Loudspeaker4*/
            /*
                * TO DO: Read IO for fault pin of Loudspeaker Amplifier4, if required.
                */
        break;
    default:
        
        break;
    }
    return 1;/*hard coded*/
}
</code></pre>
<p>The question is how should I test this requirement &quot;Driver shall read fault notification pin on amplifier IC manually, whenever requested&quot;. @kamilcuk tells me if you want to this event, do integration. If you want to test your function mock it but did not tell me how to I set up that test case.</p>
<p>Another question which seems more diffucult is how and where( in this driver layer or app layer ? ) should I test this requirement &quot; Fault notification pin shall trigger the system when any fault occured.&quot;</p>
<p>Everybody tells me to use mock. The problem is not using a mock framework, this is simple one, the problem is although I've read lot of readings, still don't understand the concept of Mocking. Because, in James's book, he was filling the function body of hardware dependent codes to be act just like a real, this made confused my mind. Once writing hardware depending codes virtually, testing nested instructed functions according to this virtual functions did not make sense to me. What is the aim is here. Dual targeting approaches was good. I feel myself little bit idiot.</p>
",https://stackoverflow.com/questions/65915570/how-to-do-a-unit-test-of-an-external-devices-register-which-is-read-only,"['c++', 'mocking', 'cpputest']",308,False,0,0
ChiselTest: Cast a signed int to unsigned int for an expected value,"<p>I'm having trouble identifying the correct method for converting a signed int to unsigned int for unit testing using the new ChiselTest framework.</p>
<p>Here is the method I have been using to unit test an ALU (example is 16-bit), the problem is that it is not scalable:</p>
<pre class=""lang-scala prettyprint-override""><code>    test(new ALU) { c =&gt;
    ...
        /* Sub */
        c.io.ctl.poke(Control.ALU_SUB)
        c.io.src0.poke(4321.U)
        c.io.src1.poke(1234.U)
        c.io.out.expect(3087.U)
        c.io.src0.poke(1234.U)
        c.io.src1.poke(4321.U)
        c.io.out.expect(&quot;b_1111_0011_1111_0001&quot;.U) /* 2's compliment */
    }
</code></pre>
<p>The problem with this method is that when I generate a 32-bit ALU (which outputs an unsigned int), the unit test will fail because the string will zero extend to 32-bits using the hacky string method above...</p>
<p>I'd like to rewrite the test like this:</p>
<pre class=""lang-scala prettyprint-override""><code>test(new ALU) { c =&gt;
    /* Sub */
    c.io.ctl.poke(Control.ALU_SUB)
    c.io.src0.poke(4321.U)
    c.io.src1.poke(1234.U)
    c.io.out.expect(3087.U)
    c.io.src0.poke(1234.U)
    c.io.src1.poke(4321.U)
    c.io.out.expect(-3087.S.asUInt)
}
</code></pre>
<p>But, although the design does elaborate, I get the following error:</p>
<pre class=""lang-sh prettyprint-override""><code>[error] (run-main-9) chisel3.internal.ChiselException: Error: Not in a UserModule. Likely cause: Missed Module() wrap, bare chisel API call, or attempting to construct hardware inside a BlackBox.
[error] chisel3.internal.ChiselException: Error: Not in a UserModule. Likely cause: Missed Module() wrap, bare chisel API call, or attempting to construct hardware inside a BlackBox.
[error]         at chisel3.internal.throwException$.apply(Error.scala:85)
[error]         at chisel3.internal.Builder$.forcedUserModule(Builder.scala:298)
[error]         at chisel3.internal.Builder$.pushOp(Builder.scala:336)
[error]         at chisel3.SInt.do_asUInt(Bits.scala:925)
[error]         at cpu.alu$.$anonfun$new$2(Main.scala:26)
[error]         at cpu.alu$.$anonfun$new$2$adapted(Main.scala:18)
[error]         at chiseltest.backends.treadle.TreadleBackend.$anonfun$run$1(TreadleBackend.scala:144)
[error]         at chiseltest.internal.ThreadedBackend$TesterThread$$anon$1.$anonfun$run$1(ThreadedBackend.scala:453)
[error]         at chiseltest.backends.treadle.TreadleBackend.doTimescope(TreadleBackend.scala:103)
[error]         at chiseltest.internal.ThreadedBackend$TesterThread$$anon$1.run(ThreadedBackend.scala:453)
[error]         at java.lang.Thread.run(Thread.java:748)
[error] stack trace is suppressed; run last Test / bgRunMain for the full output
[error] Nonzero exit code: 1
[error] (Test / runMain) Nonzero exit code: 1
</code></pre>
<p>I can't figure out the right way of addressing this. Any help would be much appreciated.</p>
<p>For reference, the ALU is pretty simple, here is the ALU class:</p>
<pre class=""lang-scala prettyprint-override""><code>class ALU extends Module {
  val io = IO(new Bundle {
    val ctl   = Input(UInt(Control.ALU_BITWIDTH))
    val src0  = Input(UInt(Instructions.WORD_SIZE.W))
    val src1  = Input(UInt(Instructions.WORD_SIZE.W))
    val out   = Output(UInt(Instructions.WORD_SIZE.W))
  })

  val shift = io.src1(3,0).asUInt

  /* Lookup the operation to execute */
  io.out := MuxLookup(io.ctl, 0.U, Seq(
    Control.ALU_ADD -&gt; (io.src0 + io.src1),
    Control.ALU_SUB -&gt; (io.src0 - io.src1),
    Control.ALU_AND -&gt; (io.src0 &amp; io.src1),
    Control.ALU_OR  -&gt; (io.src0 | io.src1),
    Control.ALU_XOR -&gt; (io.src0 ^ io.src1),
    Control.ALU_NOT -&gt; (~io.src0),
    Control.ALU_SLL -&gt; (io.src0 &lt;&lt; shift),
    Control.ALU_SRL -&gt; (io.src0 &gt;&gt; shift),
  ))
}
</code></pre>
",https://stackoverflow.com/questions/66294784/chiseltest-cast-a-signed-int-to-unsigned-int-for-an-expected-value,"['scala', 'chisel']",347,True,3,2
How to correctly mock a gcp client library call in python,"<p>How do I correctly write a unit test for a function that uses the GCP secret manager client library. I've been reading up on unit testing and mocking but I just can't seem to grasp what's going wrong here. I've never really written unit tests other than very basic ones, or done mocking either. I have the following <code>get_secret</code> function in a file <code>main.py</code> that returns a string.</p>
<pre><code>from google.cloud import secretmanager

def get_secret(project_id,secret_name) -&gt; str:
    &quot;&quot;&quot;
    Get secret from gcp secrets manager
    &quot;&quot;&quot;

    client = secretmanager.SecretManagerServiceClient()
    request = {&quot;name&quot;: f&quot;projects/{project_id}/secrets/{secret_name}/versions/latest&quot;}

    response = client.access_secret_version(request)
    secret_string = response.payload.data.decode(&quot;UTF-8&quot;)

    return secret_string
</code></pre>
<p>I have the following <code>test_main.py</code> file where I try to mock the secretmanager.</p>
<pre><code>import pytest
from unittest.mock import patch

from main import get_secret

@pytest.fixture()
def secret_string():
    return 'super_secret_token'

@patch(&quot;main.secretmanager&quot;) # mock secretmanager from main.py
def test_get_secret(secretmanager,secret_string):

    secretmanager.SecretManagerServiceClient().access_secret_version().return_value = secret_string

    secret_string = get_secret('project_id','secret_name')

    assert secret_string == 'super_secret_token'
</code></pre>
<p>When I run <code>pytest</code> it test fails with <code>AssertionError: assert &lt;MagicMock name='secretmanager.SecretManagerServiceClient().access_secret_version().payload.data.decode()' id='4409262192'&gt; == 'super_secret_token'</code></p>
<p>I have an idea why but I'm not entirely sure. I assume it's to do with <code>access_secret_version()</code> returning an object of type <code>google.cloud.secretmanager_v1.types.service.AccessSecretVersionResponse</code> which has a <code>payload</code> object of type <code>google.cloud.secretmanager_v1.types.SecretPayload</code> which is a <code>data</code> object of type <code>bytes</code></p>
<p>Any help on how to do this correctly would be appreciated.</p>
",https://stackoverflow.com/questions/68766574/how-to-correctly-mock-a-gcp-client-library-call-in-python,"['python-3.x', 'unit-testing', 'google-cloud-platform', 'mocking', 'google-secret-manager']",2554,True,3,1
Unit testing in Angular: Mocking RxJS observable with Jasmine,"<p>I am unit testing an Angular 12 component.  The component fetches, on initialisation, an observable returned from a service (see <code>thing.service.ts</code> below).  It is assigned to a Subject, which is displayed in the html template (see <code>app.component.html</code> below) via the <code>async</code> pipe.</p>
<p><strong>AppComponent.ts</strong></p>
<pre><code>export class AppComponent  {
  public errorObjectSubject = null;
  public thingsSubject: Subject&lt;Array&lt;IThing&gt;&gt; = new Subject();

  constructor(private readonly _service: ThingService) {
    this._getAllProducts();
  }

  private async _getAllProducts(): Promise&lt;void&gt; {
    this._service.getAllObservableAsync()
      .pipe(take(1),
        catchError(err =&gt; {
          this.errorObjectSubject = err;
          return throwError(err);
        })
      ).subscribe(result =&gt; { this.thingsSubject.next(result) });
  }
}
</code></pre>
<p>The template subscribes to <code>public thingsSubject: Subject&lt;Array&lt;IThing&gt;&gt; = new Subject();</code> with the <code>async</code> pipe:</p>
<p><strong>app.component.html</strong></p>
<pre><code>&lt;div&gt;
  &lt;app-thing *ngFor=&quot;let thing of thingsSubject | async&quot; [thing]=&quot;thing&quot;&gt;&lt;/app-thing&gt;
&lt;/div&gt;
</code></pre>
<p><strong>thing.service.ts</strong></p>
<pre><code>  constructor(private readonly _http: HttpClient) { }

  public getAllObservableAsync(): Observable&lt;Array&lt;IThing&gt;&gt; {
    return this._http.get&lt;Array&lt;IThing&gt;&gt;('https://jsonplaceholder.typicode.com/todos'); }
</code></pre>
<p>Here is the test setup.</p>
<p><strong>app.component.spec.ts</strong></p>
<pre><code>describe('AppComponent', () =&gt; {
  let component: AppComponent,
    fixture: ComponentFixture&lt;AppComponent&gt;,
    dependencies: { thingService: ThingServiceStub };

  function getThings(): Array&lt;DebugElement&gt; {
    return fixture.debugElement.queryAll(By.directive(ThingComponentStub));
  }

  beforeEach(async () =&gt; {
    dependencies = {
      thingService: new ThingServiceStub()
    };
    await TestBed.configureTestingModule({
      declarations: [AppComponent, ThingComponentStub],
      providers: [
        { provide: ThingService, useValue: dependencies.thingService }
      ]
    }).compileComponents();
  });

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

  describe('on initialisation', () =&gt; {
    let getThingsSubject: Subject&lt;Array&lt;IThing&gt;&gt;;

    beforeEach(() =&gt; {
      getThingsSubject = new Subject();
      (dependencies.thingService
        .getAllObservableAsync as jasmine.Spy).and.returnValue(
        getThingsSubject.asObservable()
      );
      fixture.detectChanges();
    });

    it('should fetch all of the things', () =&gt; {
      //fixture.detectChanges();
      expect(
        dependencies.thingService.getAllObservableAsync
      ).toHaveBeenCalledWith();
    });

    describe('when the things have been fetched', () =&gt; {
      beforeEach(fakeAsync(() =&gt; {
        getThingsSubject.next()
        // getThingsSubject.next([
        //   {
        //     userId: 1,
        //     id: 1,
        //     title: 'string',
        //     completed: 'string'
        //   }
        // ]);
        //getThingsSubject.pipe().subscribe()

        tick();

        fixture.detectChanges();
      }));

      it('should display the things', () =&gt; {
        expect(getThings()[0].componentInstance.product).toEqual({
          name: 'product',
          number: '1'
        });
      });
    });
  });
});
</code></pre>
<p><strong>thing.service.stub.ts</strong></p>
<pre><code>export class ProductServiceStub {
    public getAllObservableAsync: jasmine.Spy = jasmine.createSpy('getAllObservableAsync');
  }
</code></pre>
<p>I am trying to test how it works after the template has been populated with things (<code>IThing[]</code>).  I have a <em>passing</em> spec which calls the mock observable:</p>
<pre><code>it('should fetch all of the things', () =&gt; {
  expect(
    dependencies.thingService.getAllObservableAsync
  ).toHaveBeenCalledWith();
});
</code></pre>
<p>However I hit the 'Error: Uncaught (in promise): TypeError: Cannot read property 'pipe' of undefine' when I attempt to test the template: <code>describe('when the things have been fetched'</code>.</p>
<p>I am not quite sure what is the problem.  Is it how I have setup the subscription to the Subject?  Or the change detection?</p>
",https://stackoverflow.com/questions/68224715/unit-testing-in-angular-mocking-rxjs-observable-with-jasmine,"['angular', 'jasmine', 'angular12']",5277,True,2,1
What is the proper way to test Vue3 async setup component with suspense?,"<p>No doubt that Suspense feature leads to a cleaner code base, but as tidy as it is, it turns to be hard to test. Specifically it is not well documented yet.</p>
<h3>case:</h3>
<p>Regular app generated by VUE CLI</p>
<ul>
<li>Tech stack: Vuex, Router, PWA, jest for unit testing</li>
</ul>
<h3>Challenge:</h3>
<p>I made use of Suspense component as recommended as follows:</p>
<pre class=""lang-js prettyprint-override""><code>    &lt;RouterView name=&quot;default&quot; v-slot=&quot;{ Component, route }&quot;&gt;
      &lt;transition :name=&quot;route.meta.transition&quot; mode=&quot;out-in&quot; :duration=&quot;300&quot; :key=&quot;route.path&quot;&gt;
        &lt;Suspense &gt;
          &lt;template #default&gt;
            &lt;component :is=&quot;Component&quot; :key=&quot;route.path&quot;/&gt;
          &lt;/template&gt;
          &lt;template #fallback&gt;
            &lt;div class=&quot;top-0 right-0 h-screen w-screen z-50 flex justify-center items-center&quot;&gt;
               &lt;div class=&quot;animate-spin rounded-full h-32 w-32 border-t-2 border-b-2 border-yellow-700&quot;&gt;&lt;/div&gt;
            &lt;/div&gt;
          &lt;/template&gt;
        &lt;/Suspense&gt;
      &lt;/transition&gt;
    &lt;/RouterView&gt;

</code></pre>
<h3>I have few routes and views:</h3>
<ul>
<li>one of them is for Login view</li>
</ul>
<pre><code>  // here is the gotcha, if ever I removed async from setup the test runs well otherwise it always returns empty vm.
  async setup(){
    const router = useRouter()
    const route = useRoute()
    const form = reactive(new Form({
          username:'',
          password:'',
      }))
}
</code></pre>
<h3>And my test suite as follows:</h3>
<pre><code>
  test('Shows login form',  async () =&gt; {
      let wrapper = mount(Login,{
        // tried set global.stubs.transition to false
        renderDefaultSlot: true // tried as well to move this attr to beforeEach hook
      })
      expect(wrapper.exists()).toBe(true) // passes
      await nextTick()
      // tried to flushPromises()
      console.log(wrapper.vm) // always empty object {}
      expect(wrapper.findAll('div')).toBeTruthy() // fails accordingly as it can't run helper methods to get the parentElement
    })

</code></pre>
<h2>Does any VUE veteran here can give a hint or workaround!</h2>
<p>All open discussions on Github shows that I am not the only one stumbled on this issue, but for now it is just a discussion.</p>
<p><a href=""https://github.com/vuejs/vue-test-utils-next/issues/108#issue-611802592"" rel=""nofollow noreferrer"">https://github.com/vuejs/vue-test-utils-next/issues/108#issue-611802592</a></p>
<p><a href=""https://github.com/vuejs/vue-test-utils/issues/956"" rel=""nofollow noreferrer"">https://github.com/vuejs/vue-test-utils/issues/956</a></p>
",https://stackoverflow.com/questions/65654965/what-is-the-proper-way-to-test-vue3-async-setup-component-with-suspense,"['javascript', 'ecmascript-6', 'jestjs', 'vuejs3']",2579,True,2,1
how to programmatically get the number of properties of a class in dart?,"<p>let say I have a class like this</p>
<pre><code>class Human {

   String name;
   int age;
   HairColor hairColor;

   static const int numberOfLegs = 2

}
</code></pre>
<p>as you can see I have 3 properties and 1 static property in <code>Human</code> class above, I want to get the number of class properties (without the static) of a class</p>
<p>so I need to get something like this</p>
<pre><code>final john = Human(name: &quot;John&quot;, age: 24, hairColor: HairColor.black)
print(john.length) // will print '3'
</code></pre>
<p>I need to programmatically get the number of properties of a class because I will use it in unit testing, because I create a method to convert that class to map, but If I add a new property, I often forget to add it to the method</p>
<pre><code>Map&lt;String, dynamic&gt; toMap() {

   return {
      &quot;name&quot; : this.name,
      &quot;age&quot; : this.age
      &quot;hairColor&quot; : this.hairColor
      &quot;newProperty&quot; : &quot;I often forget to add this new property in this method&quot;
   }

}
</code></pre>
<p>I see an article to do something like this <a href=""https://www.woolha.com/tutorials/dart-getting-list-of-fields-and-methods-in-a-class"" rel=""nofollow noreferrer"">in here</a> and also from SO in <a href=""https://stackoverflow.com/questions/17021327/how-do-i-get-all-fields-for-a-class-in-dart"">How do I get all fields for a class in Dart?</a> , both of them using <code>dart:mirrors</code> , but it seems <code>dart:mirrors</code> is no longer available</p>
",https://stackoverflow.com/questions/68796134/how-to-programmatically-get-the-number-of-properties-of-a-class-in-dart,['dart'],129,False,2,0
Static model instances in SQLALchemy with Flask (fixtures),"<p>I am developing a Flask application using SQLAlchemy. For authorization I am using user roles which are a simple SQLAlchemy model with a m2m relation to users. I want that some roles, e.g. 'admin' are automatically created on application startup in case they do not already exist. This is similar to fixtures for unit testing, just without the testing part.</p>
<p>I have tried putting the required code into a function that is registered with the <code>before_app_first_request</code> decorator, however I need to push an application context for that to work. The app is not accessible to me in the relevant code, as it is part of an isolated blueprint.</p>
<p>The code would look similar to this:</p>
<pre><code>from app import db
my_blueprint = flask.Blueprint(...)
from .models import Role


@my_blueprint.before_app_first_request
def load_fixtures():
    admin_role = Role.query.filter_by(name='admin').first()
    if coach_role is None:
        db.session.add(Role(name='admin'))
        db.session.commit()
</code></pre>
<p>Is there a preferred way to do this? I.e. run fixtures upon application startup?</p>
",https://stackoverflow.com/questions/65761506/static-model-instances-in-sqlalchemy-with-flask-fixtures,"['python', 'flask', 'sqlalchemy', 'fixtures']",108,False,1,0
django Model.objects.create not immediately assign primary key to variable how to access that?,"<p>I have django <code>Student</code> model like below</p>
<pre class=""lang-py prettyprint-override""><code>class Student(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=20)
    score = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        return f&quot;Student(id: {self.id}, name: {self.name}, salary: {self.score})&quot;
</code></pre>
<p>I have created some users in database also below is <code>django shell</code> output</p>
<pre><code>&gt;&gt;&gt; s = Student.objects.create(name=&quot;erik&quot;, score=90)
&gt;&gt;&gt; print(s)
Student(id: None, name: erik, salary: 90)   # &lt;----- here is showing id None
&gt;&gt;&gt; Student.objects.all()                                                                                                       
&lt;QuerySet [&lt;Student: Student(id: 1, name: alex, salary: 40.00)&gt;, &lt;Student: Student(id: 2, name: john, salary: 60.00)&gt;, &lt;Student: Student(id: 3, name: erik, salary: 90.00)&gt;]&gt;
</code></pre>
<p>when i have called <code>Student.objects.all()</code> then it is showing id.</p>
<p>I want to get <code>id</code> from <code>s</code> variable because i am performing unit testing like below.</p>
<pre class=""lang-py prettyprint-override""><code>class GetSingleStudentTest(TestCase):

    def setUp(self):
        Student.objects.create(name=&quot;student1&quot;, score=50)
        Student.objects.create(name=&quot;student2&quot;, score=55)
        Student.objects.create(name=&quot;student3&quot;, score=80)
        Student.objects.create(name=&quot;student4&quot;, score=36)

    def test_get_single_student(self):
        # get API response
        response = client.get(reverse(&quot;student-detail&quot;, kwargs={&quot;pk&quot; : self.student2.pk }))

        # get data from db
        student = Student.objects.get(pk=self.student2.pk)
        serializer = StudentSerializer(student)
        self.assertEqual(response.data, serializer.data)
</code></pre>
<p>So when i have tried to access <code>self.student2.pk</code> it is <code>None</code> like we saw in <code>django shell</code> also. So how can i get that <code>id</code>?</p>
<p>because as i know <code>Model.objects.create</code> creates a user and also save into database then why <code>id</code> is <code>None</code> here? I am learning from this guide <a href=""https://realpython.com/test-driven-development-of-a-django-restful-api/"" rel=""nofollow noreferrer"">https://realpython.com/test-driven-development-of-a-django-restful-api/</a> but they not showed this kind of issues that's why I asked here. I have used <code>setUpTestData</code> method also but same kind of issue is there.</p>
<p>I think <code>AutoField</code> is working perfectly. Is it same as <code>IntegerField</code> but i have specified <code>primary_key=True</code>.</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/69236442/django-model-objects-create-not-immediately-assign-primary-key-to-variable-how-t,"['python', 'django', 'django-models']",1358,False,1,1
VueJS and Jest. Testing component with local imported mixin,"<p>I am learning VueJS by recreating MineOS interface. I have replicated a bunch of functionality without actually calling the backend. I've run into an issue with unit testing.
It looks like I've done everything I can but I think that my mixin method isn't being called.
I think what I am doing is:</p>
<ol>
<li>mocking the store/state with my test (which I have done in my login spec).</li>
<li>mocking the action that the mixin uses and assigning to the store, which should be mapped in the mixin.</li>
<li>populating the java_xmx input with 235 and then triggering the input event.</li>
<li>trigger next tick</li>
<li>interrogate the action to see if it's been called.</li>
</ol>
<p>Is the only way to test with mixins to import globally and mock?</p>
<p>javaoptions.vue</p>
<pre><code>&lt;template&gt;
  &lt;div class=&quot;tile is-vertical&quot;&gt;
    &lt;div class=&quot;tile is-child has-text-left&quot;&gt;
      &lt;b-dropdown
        aria-role=&quot;list&quot;
        @change=&quot;updateConfig('java', 'jarfile', $event)&quot;
      &gt;
        &lt;template #trigger=&quot;{ active }&quot;&gt;
          &lt;b-button
            label=&quot;Change runnable JAR to:&quot;
            :icon-right=&quot;active ? 'menu-up' : 'menu-down'&quot;
          /&gt;
        &lt;/template&gt;
        &lt;b-dropdown-item aria-role=&quot;listitem&quot; value=&quot;minecraft_server_17.1.jar&quot;
          &gt;minecraft_server_17.1.jar&lt;/b-dropdown-item
        &gt;
      &lt;/b-dropdown&gt;
    &lt;/div&gt;
    &lt;div class=&quot;tile is-child has-text-left&quot;&gt;
      &lt;div class=&quot;tile&quot;&gt;
        &lt;b-field label=&quot;Memory Allocation (Heapsize)&quot;&gt;
          &lt;div class=&quot;tile is-vertical&quot;&gt;
            &lt;div class=&quot;tile is-child&quot;&gt;
              &lt;b-field class=&quot;has-addons&quot;&gt;
                &lt;p class=&quot;control&quot;&gt;
                  &lt;b-button class=&quot;button is-static&quot;&gt;-Xmx&lt;/b-button&gt;
                &lt;/p&gt;
                &lt;b-input
                  id=&quot;java_xmx&quot;
                  :lazy=&quot;true&quot;
                  type=&quot;number&quot;
                  @input=&quot;updateConfig('java', 'java_xmx', $event)&quot;
                &gt;&lt;/b-input&gt;
                &lt;p class=&quot;control&quot;&gt;
                  &lt;b-button class=&quot;button is-static&quot;&gt;MB&lt;/b-button&gt;
                &lt;/p&gt;
              &lt;/b-field&gt;
            &lt;/div&gt;
            &lt;div class=&quot;tile is-child&quot;&gt;
              &lt;b-field class=&quot;has-addons&quot;&gt;
                &lt;p class=&quot;control&quot;&gt;
                  &lt;b-button class=&quot;button is-static&quot;&gt;-Xms&lt;/b-button&gt;
                &lt;/p&gt;
                &lt;b-input
                  id=&quot;java_xms&quot;
                  type=&quot;number&quot;
                  :lazy=&quot;true&quot;
                  @input=&quot;updateConfig('java', 'java_xms', $event)&quot;
                &gt;&lt;/b-input&gt;
                &lt;p class=&quot;control&quot;&gt;
                  &lt;b-button class=&quot;button is-static&quot;&gt;MB&lt;/b-button&gt;
                &lt;/p&gt;
              &lt;/b-field&gt;
            &lt;/div&gt;
            &lt;div class=&quot;tile is-child&quot;&gt;
              &lt;b-field label=&quot;Additional Java arguments:&quot;&gt;
                &lt;b-input
                  id=&quot;java_tweaks&quot;
                  placeholder=&quot;-XX:+DisableExplicitGC&quot;
                  :lazy=&quot;true&quot;
                  @input=&quot;updateConfig('java', 'java_tweaks', $event)&quot;
                /&gt;
              &lt;/b-field&gt;
            &lt;/div&gt;
            &lt;div class=&quot;tile is-child&quot;&gt;
              &lt;b-field label=&quot;Additional Jar arguments:&quot;&gt;
                &lt;b-input
                  id=&quot;jar_args&quot;
                  placeholder=&quot;nogui&quot;
                  :lazy=&quot;true&quot;
                  @input=&quot;updateConfig('java', 'jar_args', $event)&quot;
                /&gt;
              &lt;/b-field&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/b-field&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import updateConfigMixin from '@/mixins/updateconfig-mixin.js';

export default {
  name: 'JavaOptions',
  mixins: [updateConfigMixin],
  computed: {},
  methods: {},
};
&lt;/script&gt;

&lt;style lang=&quot;scss&quot; scoped&gt;&lt;/style&gt;
</code></pre>
<p>JavaSettings.spec.js</p>
<pre><code>import { mount, createLocalVue } from '@vue/test-utils';
import JavaOptions from '@/components/partials/java_settings/javaoptions.vue';
import Buefy from 'buefy';
import Vuex from 'vuex';

const localVue = createLocalVue();

localVue.use(Vuex);
localVue.use(Buefy);

describe('JavaOptions.vue', () =&gt; {
  let actions;
  let store;

  beforeEach(() =&gt; {
    actions = {
      updateServerConfigAction: jest.fn(),
    };

    store = new Vuex.Store({
      actions,
      selected: { config: { java_xmx: '' } },
    });
  });

  it(&quot;expect 'updateServerConfigAction' to be called on setting change&quot;, async () =&gt; {
    const wrapper = mount(JavaOptions, {
      store,
      localVue,
      attachTo: document.body,
    });

    const java_xmx = wrapper.find('#java_xmx');
    java_xmx.element.value = 235;
    java_xmx.trigger('input');
    await wrapper.vm.$nextTick();
    expect(java_xmx.element.value).toBe('235');
    expect(wrapper.vm.updateServerConfigAction).toHaveBeenCalled();
  });
});
</code></pre>
<p>updateconfig-mixin.js</p>
<pre><code>import cloneDeep from 'clone-deep';
import { mapActions, mapState } from 'vuex';

export default {
  computed: {
    ...mapState({ config: state =&gt; state.selected.config }),
  },
  methods: {
    ...mapActions(['updateServerConfigAction']),
    updateConfig(section, propKey, newVal) {
      const config = cloneDeep(this.config);
      const selectedSection = config[section];
      selectedSection[propKey] = newVal;
      this.updateServerConfigAction(config);
    },
  },
};
</code></pre>
<p>TERMINAL OUTPUT</p>
<pre><code>peter@peter-VirtualBox:/usr/development/mineos-vue$ npm run -s test:unit
 FAIL  tests/unit/JavaSettings.spec.js
  ● JavaOptions.vue › expect 'updateServerConfigAction' to be called on setting change

    expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: &gt;= 1
    Received number of calls:    0

      36 |     await wrapper.vm.$nextTick();
      37 |     expect(java_xmx.element.value).toBe('235');
    &gt; 38 |     expect(actions.updateServerConfigAction).toHaveBeenCalled();
         |                                              ^
      39 |   });
      40 | });
      41 |

      at Object.it (tests/unit/JavaSettings.spec.js:38:46)

 PASS  tests/unit/Login.spec.js
-----------------------------------|----------|----------|----------|----------|-------------------|
File                               |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
-----------------------------------|----------|----------|----------|----------|-------------------|
All files                          |       50 |      100 |    33.33 |       50 |                   |
 components/partials               |      100 |      100 |      100 |      100 |                   |
  Login.vue                        |      100 |      100 |      100 |      100 |                   |
 components/partials/java_settings |      100 |      100 |      100 |      100 |                   |
  javaoptions.vue                  |      100 |      100 |      100 |      100 |                   |
 mixins                            |        0 |      100 |        0 |        0 |                   |
  updateconfig-mixin.js            |        0 |      100 |        0 |        0 |     6,11,12,13,14 |
-----------------------------------|----------|----------|----------|----------|-------------------|

Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.063s
Ran all test suites.
</code></pre>
",https://stackoverflow.com/questions/69669787/vuejs-and-jest-testing-component-with-local-imported-mixin,"['vue.js', 'unit-testing', 'jestjs', 'vue-jest']",946,True,1,1
Mock an attribute of a property of a class in python,"<p>I am having trouble mocking an <em>attribute</em> of a <em>property</em> of a <em>class</em>.</p>
<p>I have the following class:</p>
<pre class=""lang-py prettyprint-override""><code>import boto3

class QueryFetcher:
    def __init__(self, query: str):
        self._query = query
        self._athena = boto3.client(&quot;athena&quot;)
    
    @property
    def athena(self):
        return self._athena
    
    def query_athena(self):
        # need to mock start_query_execution function
        execution = self._athena.start_query_execution(. . .)
        execution_id = execution[&quot;QueryExecutionId&quot;]

        while True:
            # need to mock get_query_execution function
            stats = self._athena.get_query_execution(QueryExecutionId=execution_id)
            . . .

        return status, execution_id
</code></pre>
<p>I have to mock the functions <code>start_query_execution</code> and <code>get_query_execution</code> which are part of the property <code>athena</code> in the class.</p>
<p>I am trying to unit test the function <code>query_athena</code>. This is a sample file for unit testing:</p>
<pre class=""lang-py prettyprint-override""><code>import pytest
from query_fetcher import QueryFetcher
from unittest.mock import patch, PropertyMock


@pytest.fixture
def fetcher_user():
    return QueryFetcher(query=&quot;&quot;)


@mock.patch(
    &quot;query_fetcher.QueryFetcher.athena&quot;,
    new_callable=mock.PropertyMock,
)
def test_query_athena(mock_athena, fetcher_user):
    mock_athena.return_value.get_query_execution.return_value = {
        &quot;QueryExecution&quot;: {&quot;Status&quot;: {&quot;State&quot;: &quot;SUCCEEDED&quot;}}
    }
    mock_athena.return_value.start_query_execution.return_value = {
        &quot;QueryExecutionId&quot;: &quot;69320478-2452-465e-bc0d-89cdc8bd4428&quot;
    }
    fetcher_user.query_athena()
</code></pre>
<p>However, this does not work and I assumed it's because I have to create a new instance of the class. So then I tried the following:</p>
<pre class=""lang-py prettyprint-override""><code>@mock.patch(
    &quot;query_fetcher.QueryFetcher.athena&quot;,
    new_callable=mock.PropertyMock,
)
def test_query_athena(mock_athena):
    mock_athena.return_value.get_query_execution.return_value = {
        &quot;QueryExecution&quot;: {&quot;Status&quot;: {&quot;State&quot;: &quot;SUCCEEDED&quot;}}
    }
    mock_athena.return_value.start_query_execution.return_value = {
        &quot;QueryExecutionId&quot;: &quot;69320478-2452-465e-bc0d-89cdc8bd4428&quot;
    }
    # create a new class instance
    fetcher_user = QueryFetcher(query=&quot;&quot;)
    fetcher_user.query_athena()
</code></pre>
<p>But this doesn't work either. What am I missing here?</p>
<p>Ideally, I'd like to mock the property <code>athena</code> on my fixture <code>fetcher_user</code> instead of creating a new instance entirely. I also do not want to modify my fixture to mock the functionality inside the fixture. Is that even possible?</p>
<p>I'd appreciate any help on this issue, thanks!</p>
",https://stackoverflow.com/questions/68223924/mock-an-attribute-of-a-property-of-a-class-in-python,"['python', 'python-3.x', 'unit-testing', 'mocking', 'patch']",227,True,1,1
How to handle API call rate limit when unit testing?,"<p>I am building an application using YouTube's API. This is my first time using a proper API, so I don't <em>fully</em> understand how it works (hence I am here).</p>
<p>Every time I come to code for the application, I am finding that my unit tests run into the limit pretty quickly. How do people normally handle situations like this? Is it a case of <em>not</em> unit testing? Or there something I can do instead to prevent this issue?</p>
<p>For anyone familiar with YouTube's API, based on <a href=""https://stackoverflow.com/a/15580411/12488201"">this</a>, I am only making requests to retrieve 1-2 videos per test, and I currently have around 10 tests. If I am correct, assuming that I am requesting 2 videos per call, I should be able to run the tests <em>10,000/20 = <strong>500</strong></em> <strong>times</strong>, no?</p>
",https://stackoverflow.com/questions/66516916/how-to-handle-api-call-rate-limit-when-unit-testing,"['api', 'youtube', 'youtube-api']",888,True,1,1
Devops build pipeline not copying test files to bin folder,"<p>I have a yaml file for my build pipeline in which I trigger my unit test project. This project has a few <code>.csv</code> and <code>.xls(x)</code> files included used for unit testing. Theses files are set to <code>Copy Always</code>.</p>
<p>All tests run fine on local machine. But when my tests are run in Devops then it seems like the files aren't copied over to the bin directory.</p>
<p>In my yaml I have this to run the test project:</p>
<pre class=""lang-yaml prettyprint-override""><code>- task: DotNetCoreCLI@2
  displayName: Test .NET core Application
  inputs:
    command: test
    projects: '$(testProjects)'
    arguments: '--configuration $(buildConfig)'
</code></pre>
<p>In the build output log I see that the files are present on this location:</p>
<pre><code>##[debug]  D:\a\1\s\MyAppImport\Tests\Data\sales_04.csv (file)
##[debug]  D:\a\1\s\MyAppImport\Tests\Data\Sales_02.csv (file)
##[debug]  D:\a\1\s\MyAppImport\Tests\Data\sales_01.xls (file)
##[debug]  D:\a\1\s\MyAppImport\Tests\Data\sales_stock_01.csv (file)
</code></pre>
<p>But the actual test looks for the files in the <code>bin</code> folder:</p>
<pre><code>Failed Throws_A_FileNotFound_When_The_File_Does_Not_Exist [1 ms]
  Error Message:
   Assert.AreEqual failed. Expected:&lt;The file could not be found, read or did not contain data&gt;. 

Actual:&lt;The file 'D:\a\1\s\MyAppImport\Tests\bin\Release\net5.0\Data\sales_01.xls' could not be found, read or did not contain data&gt;. 
</code></pre>
<p>As you can see, the files paths are different. For some reason the files aren't copied to the <code>bin</code> folder, eventhough &quot;Copy Always&quot; is set for each file as build action.</p>
<p>How can I solve this issue?</p>
",https://stackoverflow.com/questions/69744778/devops-build-pipeline-not-copying-test-files-to-bin-folder,"['azure-devops', 'azure-pipelines', 'devops']",324,False,1,0
Mocking Microsoft.Toolkit.Mvvm.IMessenger,"<p>It seems that for some reason, Microsoft has created an interface for it's messenger and then gone and implemented the logic as extension methods on the interface itself.</p>
<p>Unfortunately, I cannot use this beautiful solution: <a href=""http://agooddayforscience.blogspot.com/2017/08/mocking-extension-methods.html"" rel=""nofollow noreferrer"">http://agooddayforscience.blogspot.com/2017/08/mocking-extension-methods.html</a> - because IMessenger extensions calls implemented code on Messenger with an <em><strong>internal</strong></em> type as argument.</p>
<p>Why would Microsoft go to such lengths to make unit testing hard? (If you know a good, technical reason for this, please comment with the answer. I am very curious).</p>
<p>I want to unit test the ViewModels, which injects IMessenger. So how do I do this?</p>
<p>My solution is: Wrap IMessenger in a wrapper with an interface and inject that instead.</p>
<p>Is there a simpler/better solution? (I want it to be easy to understand and maintain).</p>
",https://stackoverflow.com/questions/69084503/mocking-microsoft-toolkit-mvvm-imessenger,"['mvvm', 'mocking']",392,True,1,2
Is it possible to auto-start a WCF for only specific projects?,"<p>I have a WCF project which several other projects depend on, but others, like unit testing projects and other support utilities which don't need the service.  It contains the following XML in the .csproj file:</p>
<pre><code>&lt;ProjectExtensions&gt;
  &lt;VisualStudio&gt;
    &lt;FlavorProperties GUID=&quot;{3D9AD99F-2412-4246-B90B-4EAA41C64699}&quot;&gt;
      &lt;WcfProjectProperties&gt;
        &lt;AutoStart&gt;True&lt;/AutoStart&gt;
      &lt;/WcfProjectProperties&gt;
    &lt;/FlavorProperties&gt;
  &lt;/VisualStudio&gt;
&lt;/ProjectExtensions&gt;
</code></pre>
<p>Is there a way to get the &quot;auto-start service with project&quot; functionality to only apply to specific projects in the solution?  Or is it all or nothing?  Is there anything I could add to the other projects to tell them they depend on this service to make it auto-start in the debugging session?  Or add some condition to the service's .csproj that depends on which project is the current startup project?</p>
<p>I tried experimenting with Condition=&quot;'$(Configuration)' == 'Debug'&quot; in various places, but I couldn't get it to behave an different based on that Configuration variable.</p>
",https://stackoverflow.com/questions/66925140/is-it-possible-to-auto-start-a-wcf-for-only-specific-projects,"['visual-studio', 'wcf']",81,True,0,1
Hyperledger fabric 2.3 unit testing,"<p>I'm new to hyperledger fabric and I'm trying to write unit tests for my chaincode. Im using version 2.3 with the contract.api for writing my chaincode. Now i try to unit test this but all the resources i find are outdated and use the deprecated shimtest or deprecated shim versions.</p>
<p>What is the correct  up to date method of unit testing chaincode? Is there a example or tutorial i can follow? I did take a look at the hyperledger fabric examples. They refer to a ChaincodeStubInterface, but there is no further explanation on how to use this. I also noticed that many (recent) examples have a mock folder with generated files in it, that they use for their tests. But how these get generated, I have no clue.</p>
<p>Help is much appreciated!</p>
",https://stackoverflow.com/questions/67485816/hyperledger-fabric-2-3-unit-testing,"['unit-testing', 'hyperledger-fabric', 'chaincode']",300,False,0,1
ASP.NET: Unit testing controller fails because default response is null,"<p>I'm trying to unit test a controller. <code>SomeController</code> inherits from <code>BaseController</code>. <code>BaseController</code> inherits from <code>Microsoft.AspNetCore.Mvc.Controller</code>.</p>
<p>My NUnit tests fail because a property <code>Response</code> in <code>Controller</code> is always null when running my tests. My test currently looks like this:</p>
<pre><code>[Test]
public void GetByFilter_ShouldReturnABadRequest_WhenModelStateIsInvalid()
{
    _sut.ModelState.AddModelError(&quot;SessionName&quot;, &quot;Required&quot;);
    var result = _sut.GetByFilter(_mockedFilter);
    Assert.IsAssignableFrom&lt;BadRequestObjectResult&gt;(result);
}
</code></pre>
<p><code>_sut</code> is set by <code>[SetUp]</code> with this method:</p>
<pre><code>protected override void InitSut() =&gt; _sut =
        new SomeController(_mockedLogger, _mockedService, _mockedRepository, _mockedHtmlSanitizer);
</code></pre>
<p>The code that fails on tests but works fine when running looks like this:</p>
<pre><code>Response.Headers.Add(&quot;RowCount&quot;, result.Count().ToString());
return Ok(result);
</code></pre>
<p>Seems I need to do something to have the BaseController set the Response. In production the Response is filled with an instance of <code>HttpDefaultResponse</code>, but Response is <code>readonly</code>, so no way to set this myself.</p>
<p>I have tried following testing guides like this, but without luck:<br>
<a href=""https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/unit-testing-controllers-in-web-api</a></p>
<p>What do I need to do to start my controllers correctly and thus pass my tests?</p>
",https://stackoverflow.com/questions/69466131/asp-net-unit-testing-controller-fails-because-default-response-is-null,"['c#', 'asp.net', 'asp.net-mvc', 'unit-testing']",561,False,0,1
Angular Guard unit test with observable urltree,"<p>I am new to Angular and unit testing in that framework. I am trying to test my auth guard that I have below:</p>
<pre><code>import { AuthenticationService } from '../auth/authentication.service';
import { map, take } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationGuard implements CanActivate, CanActivateChild {

  constructor(private authService: AuthenticationService, private router: Router){}
  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean | UrlTree | Observable&lt;boolean | UrlTree&gt; | Promise&lt;boolean | UrlTree&gt; {
    return this.canActivate(childRoute,state,)
  }
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable&lt;boolean | UrlTree&gt; | Promise&lt;boolean | UrlTree&gt; | boolean | UrlTree {
      return this.canProceed()
  }

  private canProceed():  Observable&lt;boolean | UrlTree&gt;{
    return this.authService.user.pipe(
      take(1),
      map( user =&gt; {
        const isAuth = !!user;
        if(isAuth) return true;
        return this.router.createUrlTree(['/login'])
      })
    );
  }
}
</code></pre>
<p>I am having difficulty understanding how to test this. I done research an most people mock the router to run tests on their guards, but I keep getting errors when i try to do that. I have not really found anything that tests observable guards. Her is my test that I wrote.</p>
<pre><code>describe('AuthenticationGuard', () =&gt; {
  let injector: TestBed;
  let authService: AuthenticationService;
  let guard: AuthenticationGuard;
  let routeMock: any = { snapshot: {}};
  let routeStateMock: any = { snapshot: {}, url: '/login'};
  let routerMock = {navigate: jasmine.createSpy('navigate')}

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes([]),HttpClientTestingModule],
      providers: [{ provide: Router, useValue: routerMock },],
    });
    injector = getTestBed()
    authService = injector.inject(AuthenticationService)
    guard = TestBed.inject(AuthenticationGuard);
  });

  it('should be created', () =&gt; {
    expect(guard).toBeTruthy();
  });

  it('should allow the authenticated user to access app', () =&gt; {
    expect(true).toEqual(true)
  })

  it('should redirect an unauthenticated user to the login route', () =&gt; {
    authService.user = new BehaviorSubject&lt;User | null&gt;(null);
    expect(guard.canActivate(routeMock, routeStateMock)).toEqual(of(false))
    expect(routerMock.navigate).toHaveBeenCalledWith(['/login']);
  })
});
</code></pre>
<p>In my auth service I have a behavior subject that contains the user information and is update to null if the user logs out, or updates the user info if the users information has been updated.
I get that the error is Expected AnonymousSubject. I am strggling to understand what is going on her any help would be great.</p>
",https://stackoverflow.com/questions/66556237/angular-guard-unit-test-with-observable-urltree,"['angular', 'jasmine', 'karma-jasmine']",1985,True,0,1
"how to test component with setState hook inside async api call in useEffect(func, [])","<p>I'm facing a problem unit-testing a component with react-native-testing-library.</p>
<p>I have a component like this:</p>
<pre><code>// components/TestComponent.js
function TestComponent() {
  const [data, setData] = useState();

  useEffect(() =&gt; {
    clientLibrary.getData()
      .then((result) =&gt; { setData(result.data); } )
      .catch((err) =&gt; { //handle error here } )
  }, []);

  render (
    &lt;ListComponent 
      testID={&quot;comp&quot;} 
      data={data})
      renderItem={(item) =&gt; &lt;ListItem testID={'item'} data={item} /&gt;}
    /&gt;
  );
}
</code></pre>
<p>And I test it like this:</p>
<pre><code>// components/TestComponent.test.js

it('should render 10 list item', async () =&gt; {
  const data = new Array(10).fill({}).map((v, idx) =&gt; ({
      id: `v_${idx}`,
    }));

  const req = jest.spyOn(clientLibrary, 'getData').mockImplementation(() =&gt; {
      return Promise.resolve(data);
    });

  const {queryByTestId, queryAllByTestId} = render(
    &lt;TestComponent /&gt;,
  );

  expect(await queryByTestId('comp')).toBeTruthy(); // this will pass
  expect(await queryAllByTestId('item').length).toEqual(10); // this will fail with result: 0 expected: 10
}); // this failed
</code></pre>
<p>The test will fail/pass with</p>
<p><code>Attempted to log &quot;Warning: An update to TestComponent inside a test was not wrapped in act(...).</code> pointing to <code>setData</code> in useEffect.</p>
<p>I've tried wrapping the render with <code>act()</code>, the assertion with <code>act()</code>, not mocking the api call, wrapping the whole test in <code>act()</code>, but the error won't go away.</p>
<p>I have tried looking at testing-library docs/git/q&amp;a for this case, scoured stackoverflow questions too, but I still can't make this test works.</p>
<p><strong>Can anyone point me to the right direction to solve this?</strong></p>
<p>A note: I'm not trying to test implementation detail. I just want to test that given a fetch result X, the component would render as expected, which is rendering 10 list item.</p>
",https://stackoverflow.com/questions/69145023/how-to-test-component-with-setstate-hook-inside-async-api-call-in-useeffectfunc,"['react-native', 'jestjs', 'react-native-testing-library']",1668,True,0,1
Moq and validating a private method ios called with correct parameters,"<p>I'm probably below average on Unit Testing skills, but been asked to write a unit test for something I fixed. Basically, a method now allows a null value to be passed in, and I need to validate that it gets switched to the correct value, if null.(Please note, method code reduced to remove supurfluous code - it actually does more than return true...)</p>
<pre><code> public IDictionary&lt;string, JToken&gt; MethodINeedToTest(
            long? userId,
            long? orgId
        )
 {
       userId ??= DataServicesHelper.SystemUserKey;
            
       var myResults = APrivateMethod(userId.Value, orgId, false);

       return true;
}
</code></pre>
<p>I was hoping to just verify that <code>APrivateMethod</code> was called with the value from <code>DataServicesHelper.SystemUserKey</code>. However, the method is private. So with Moq, I cannot do a verify on a private method (I believe).</p>
<p>Is there anyway to validate that when <code>userId</code> is passed in as null, the method is called with <code>DataServicesHelper.SystemUserKey</code>? (Other test is to validate that it gets called with userId when it's not null).</p>
<p>Or is the code just not testable?</p>
",https://stackoverflow.com/questions/65910827/moq-and-validating-a-private-method-ios-called-with-correct-parameters,"['c#', 'unit-testing', 'moq']",46,True,0,1
Spring boot test with AttributeConverter not working with Maven test,"<p>I have Spring boot unit tests (class annotated with @SpringBootTest) that run just fine when using my IDE. When I run them with Maven (mvn test), they all fail for the same reason :</p>
<blockquote>
<p>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [my/package/config/DatasourceConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unable to instantiate AttributeConverter [my.package.enum.AbstractEnumConverter]
Caused by: org.hibernate.AnnotationException: Unable to instantiate AttributeConverter [my.package.enum.AbstractEnumConverter]
Caused by: java.lang.NoSuchMethodException: my.package.AbstractEnumConverter.&lt;init&gt;()</p>
</blockquote>
<p>I use a generic AbstractEnumConverter to convert my enums on my entities.
It looks like this :</p>
<pre><code>@Converter
public abstract class AbstractEnumConverter&lt;T extends Enum&lt;T&gt; &amp; EnumInterface&lt;E&gt;, E&gt; implements AttributeConverter&lt;T, E&gt; {

    private static Logger logger = LoggerFactory.getLogger(AbstractEnumConverter.class);
    private final Class&lt;T&gt; clazz;

    public AbstractEnumConverter(Class&lt;T&gt; clazz) {
        this.clazz = clazz;
    }

    @Override
    public E convertToDatabaseColumn(T attribute) {
        return attribute != null ? attribute.getKey() : null;
    }

    @Override
    public T convertToEntityAttribute(E dbData) {
        if (dbData == null)
            return null;

        T[] enums = clazz.getEnumConstants();

        for (T e : enums) {
            if (e.getKey().equals(dbData))
                return e;
        }

        logger.info(&quot;Could not find value {} for class {}&quot;,dbData,clazz.getName());
        return null;
    }
}
</code></pre>
<p>Here is an example of an enum I use :</p>
<pre><code>public enum ExampleEnum implements EnumInterface&lt;Integer&gt; {

    KEY(1);

    private final Integer key;

    ExampleEnum(Integer key) {
        this.key = key;
    }

    @Override
    public Integer getKey() {
        return key;
    }
    
    public static class Converter extends AbstractEnumConverter&lt;ExampleEnum, Integer&gt; {
        public Converter() {
            super(ExampleEnum.class);
        }
    }
}
</code></pre>
<p>It seems like maven tries to instantiate my AbstractEnumConverter class for some reasons unknown to me. Everything works fine with IDE unit testing and when I run my application.</p>
",https://stackoverflow.com/questions/69057958/spring-boot-test-with-attributeconverter-not-working-with-maven-test,"['java', 'spring-boot', 'hibernate', 'maven', 'unit-testing']",604,True,0,1
"When unit testing a class method, how do I mock a function it calls--one defined in an imported module?","<p>I am unit testing a particular method, and am having issues mocking another function that is called during the process.  In my case, the method to test is defined in a class, and the function I'd like to mock is defined in a separate module. How do I mock this function? See below for my code.</p>
<p>In the past, I've used the Sinon package to mock/stub a dependency (<a href=""https://sinonjs.org/how-to/stub-dependency/"" rel=""nofollow noreferrer"">example</a>).  But that doesn't work in this case.  This is the first time I'm testing a method defined in a class, so perhaps that's why mocking the dependency isn't working.</p>
<hr />
<p><strong>My Code</strong></p>
<p><em>Module Containing Test Function (myLib/myDir/combo.js)</em></p>
<pre><code>const { externalFunction } = require('./external-function')
class Combo {
  constructor(props) {}
  async myMethod () {// The function under test.
    externalFunction()
  }
}
const myCombo = props =&gt; new Combo(props)
module.exports = { myCombo }
</code></pre>
<p><em>My Test File (test/myLib/myDir/combo.test.js); no attempt at mocking</em></p>
<pre><code>const { myCombo } = require('../../../myLib/myDir/combo')

const comboObj = myCombo({}) // Instantiate object to expose method to test.
await comboObj.myMethod()// Call method that I want to test.  This throws type error because myMethod function calls externalFunction, which throws an error in the test environment.
</code></pre>
<p><em>My Test File (test/myLib/myDir/combo.test.js); attempt to use Sinon package to mock</em></p>
<pre><code>const sinon = require('sinon')

const dependencyModule = require('./external-function')// Defines the method dependencyModule.methodToMock

const myStub = sinon.stub(dependencyModule, 'methodToMock').returns(555) // Stubs dependencyModule.methodToMock and ensures it always returns the value: 555.

const comboObj = myCombo({}) // Instantiate object to expose method to test.

await comboObj.myMethod()// Call method that I want to test.  This throws type error because myMethod function calls externalFunction, which throws an error in the test environment.
</code></pre>
",https://stackoverflow.com/questions/67568211/when-unit-testing-a-class-method-how-do-i-mock-a-function-it-calls-one-defined,"['javascript', 'class', 'module', 'mocking', 'sinon']",770,True,0,1
UTF-8 BOM in received-files from Verify,"<p>I'm trying out <a href=""https://github.com/VerifyTests/Verify"" rel=""nofollow noreferrer"">https://github.com/VerifyTests/Verify</a> for unit testing.
It outputs snapshots in UTF-8 but does not include the UTF-8 byte order mark at the beginning of the received file. This makes my diff tool think the file is using the system encoding which is incorrect, and causes some minor issues.</p>
<p>Is there any way of forcing the BOM in Verify?</p>
<p>I've tried both 13.0.3 and 11.27.0 of Verify with the same results. My test project uses .NET Framework 4.7.2.</p>
<p>I tried writing directly to files using <code>new UTF8Encoding(true, true)</code> and that outputs the BOM at the beginning of the files just fine. (I check the files with a hex editor)</p>
<p>This is just a minor nuisance though. I have to manually check the encoding in KDiff3 every time there's a difference.</p>
",https://stackoverflow.com/questions/69515822/utf-8-bom-in-received-files-from-verify,"['c#', '.net', 'unit-testing', 'verify', 'snapshot-testing']",158,True,0,1
Assigning html tag a value using interpolation throws error during unit testing in angular,"<p>I am trying to run a unit test in angular. But I am getting the below error message. It is not throwing during compilation process and my application works fine as expected  but this error is thrown only when the unit testing is carried out.</p>
<blockquote>
<p><strong>Error message</strong>: Template parse error,Cant bind to ngxrow since it is not a known property of div.  &lt;div [ERROR -&gt;]ngxcol=&quot;{{newwidth}}&quot;&gt;</p>
</blockquote>
<p>I am not sure if the error is due to assigning value using interpolation {{}}.Is there anyway I can fix this. Trying to find a solution for past  2 days
Below is my partial code:</p>
<h2>component.html</h2>
<pre><code>&lt;div ngxlayout=&quot;grid&gt;
 &lt;div ngxrow&gt;
  &lt;div ngxcol={{newwidth}}&gt;
   html core logic implemented
  &lt;/div&gt;
 &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<h2>component.ts</h2>
<pre><code>export class AppComponent {
newwidth:any=&quot;30&quot;
constructor(){}
}
</code></pre>
<p>I am not getting error if i directly assign the width as 30 in the ngxcol property directly but issue happens only if the value 30 is assigned using interpolation.</p>
",https://stackoverflow.com/questions/69663684/assigning-html-tag-a-value-using-interpolation-throws-error-during-unit-testing,"['html', 'angular', 'jestjs', 'karma-jasmine']",125,True,0,1
Using unittests and moto to mock AWS,"<p>I am used to <code>pytest</code> approach for unit testing, without using classes.  Today I wanted to give a try to <code>unittest</code> and I wanted to encapsulate my tests inside a <a href=""https://docs.python.org/3/library/unittest.html#unittest.TestCase"" rel=""nofollow noreferrer"">TestCase</a>.</p>
<p>Then consider this sample test class:</p>
<pre class=""lang-py prettyprint-override""><code>import unittest
import moto
import boto3

class TestMyClass(unittest.TestCase):
    @classmethod
    @moto.mock_ssm
    def setUpClass(cls) -&gt; None:
        cls.ssm_client = boto3.client('ssm')
        cls.ssm_client.put_parameter(Name='test', Value='foo', Type='String')

    @moto.mock_ssm
    def test_something(self):
        value = self.ssm_client.get_parameter(Name='test').get('Parameter').get('Value')
        self.assertEqual(value, 'foo')

</code></pre>
<p>Why is not the parameter placed in <code>setUpClass</code> visible from the test?  I could imagine that by using the <code>@moto.mock_ssm</code> decorator there it would all have been done in the mocked context.</p>
<p>I can, however, place the parameter within <code>test_something</code> as just:</p>
<pre class=""lang-py prettyprint-override""><code>@moto.mock_ssm
def test_something(self):
    self.ssm_client.put_parameter(Name='test', Value='foo', Type='String')
    value = self.ssm_client.get_parameter(Name='test').get('Parameter').get('Value')
    self.assertEqual(value, 'foo')
</code></pre>
<p>And then it (obviously) works.  Why not with my first approach?  I do not want to be populating the fake <em>ssm</em> parameter for each test that will rely on it.  What is the best way of doing so here?</p>
<p>The reason why I am asking this is because the class I want to test requires this parameter when it is initialised.</p>
",https://stackoverflow.com/questions/66660745/using-unittests-and-moto-to-mock-aws,"['python', 'python-unittest', 'moto']",1892,True,0,1
How do I take a screenshot of a Text-Based User Interface?,"<p>I have a program which is a Text-Based User Interface (TUI). Think ncurses. Everything is displayed in the terminal and a lot of ANSI escape sequences are used to display colors, scroll bars, windows, etc...</p>
<p>For unit testing, I want to take &quot;screenshots&quot; of the TUI and compare them to the expected screenshot. Essentially, the unit test needs to run a virtual terminal and save the output to a png image file.</p>
<p>Keep in mind, these tests need to run on a headless CI system like travis or circleci. I cannot simply run gnome-terminal and take a screenshot with gnome-screenshot. The CI system does not have graphics running.</p>
<p>How do I programmatically take a screenshot of a Text-Based User Interface on a &quot;headless&quot; system?</p>
",https://stackoverflow.com/questions/68089362/how-do-i-take-a-screenshot-of-a-text-based-user-interface,"['unit-testing', 'terminal', 'screenshot', 'terminal-emulator']",105,False,-2,1
How can I use TypeScript Partials to test AWS Lambda?,"<p>Very similar to <a href=""https://stackoverflow.com/questions/37355719/using-partial-shape-for-unit-testing-with-typescript"">Using partial shape for unit testing with typescript</a> but I'm failing to understand why the Partial type is seen as being incompatible with the full version.</p>
<p>I have a unit test which check if a lambda returns 400 if the <code>body</code> in an AWS lambda event isn't valid. To avoid creating noise for my colleagues, I don't want to create <code>invalidEvent</code> with all the properties of a full <code>APIGatewayProxyEvent</code>. Hence using a <code>Partial&lt;APIGatewayProxyEvent&gt;</code>.</p>
<pre><code>  it(&quot;should return 400 when request event is invalid&quot;, async () =&gt; {
    const invalidEvent: Partial&lt;APIGatewayProxyEvent&gt; = {
      body: JSON.stringify({ foo: &quot;bar&quot; }),
    };
    const { statusCode } = await handler(invalidEvent);
    expect(statusCode).toBe(400);
  });
</code></pre>
<p>The <code>const { statusCode } = await handler(invalidEvent);</code> line fails compilation with:</p>
<pre><code>Argument of type 'Partial&lt;APIGatewayProxyEvent&gt;' is not assignable to parameter of type 'APIGatewayProxyEvent'.
  Types of property 'body' are incompatible.
    Type 'string | null | undefined' is not assignable to type 'string | null'.
      Type 'undefined' is not assignable to type 'string | null'.ts(2345)
</code></pre>
<p>I understand <code>APIGatewayProxyEvent</code> body can be <code>string | null</code> (from looking at the types) but where did <code>string | null | undefined</code> come from? Why isn't my <code>body</code> - which is a string - a valid body for <code>APIGatewayProxyEvent</code></p>
<p><strong>How can I use TypeScript Partials to test AWS Lambda?</strong></p>
<p>I could use <a href=""https://stackoverflow.com/questions/52296152/typescript-cast-using-as""><code>as</code> to do type assertions</a> but I find Partials more explicit. The following code works though:</p>
<pre><code>    const invalidEvent = { body: JSON.stringify({ foo: &quot;bar&quot; }) } as APIGatewayProxyEvent;
</code></pre>
<h4>Update: using Omit and Pick to make a new type</h4>
<pre><code>  type TestingEventWithBody = Omit&lt;Partial&lt;APIGatewayProxyEvent&gt;, &quot;body&quot;&gt; &amp; Pick&lt;APIGatewayProxyEvent, &quot;body&quot;&gt;;

  it(&quot;should return 400 when request event is invalid&quot;, async () =&gt; {
    const invalidEvent: TestingEventWithBody = { body: JSON.stringify({ foo: &quot;bar&quot; }) };
    const { statusCode } = await handler(invalidEvent);
    expect(statusCode).toBe(400);
  });
</code></pre>
<p>Fails with:</p>
<pre><code>Argument of type 'TestingEventWithBody' is not assignable to parameter of type 'APIGatewayProxyEvent'.
  Types of property 'headers' are incompatible.
    Type 'APIGatewayProxyEventHeaders | undefined' is not assignable to type 'APIGatewayProxyEventHeaders'.
      Type 'undefined' is not assignable to type 'APIGatewayProxyEventHeaders'.ts(2345)
</code></pre>
",https://stackoverflow.com/questions/69769503/how-can-i-use-typescript-partials-to-test-aws-lambda,"['typescript', 'amazon-web-services', 'jestjs', 'partials', 'ts-jest']",2081,True,3,2
How to unit test sequelize database calls using jest and sequelize-typescript,"<p>I am getting the following error while unit testing a function that creates a record in the database model.</p>
<pre><code>Model not initialized: Member &quot;create&quot; cannot be called. &quot;UserModel&quot; needs to be added to a Sequelize instance.
</code></pre>
<p>I found a github issue regarding this on <a href=""https://github.com/RobinBuschmann/sequelize-typescript/issues/688"" rel=""nofollow noreferrer"">https://github.com/RobinBuschmann/sequelize-typescript/issues/688</a></p>
<p>I tried a solution of using <code>validateOnly: true</code> and it introduces another error:</p>
<pre><code>this.lib.Database is not a constructor
</code></pre>
<p>The model class looks something like this:</p>
<pre><code>@Table({ tableName: 'User' })
export class UserModel extends Model {
    @AutoIncrement
    @PrimaryKey
    @Column(DataType.INTEGER)
    public id: number;

    @Unique
    @AllowNull(false)
    @Column(DataType.STRING(100))
    public email!: string;

    @AllowNull(false)
    @Column(DataType.TEXT)
    public password!: string;
}
</code></pre>
<p>The function that I want to test looks like:</p>
<pre class=""lang-js prettyprint-override""><code>    public async register(registerRequest: RegisterRequest) {
    return UserModel.create({
            email: registerRequest.email,
            password: registerRequest.password
        })
    }
</code></pre>
<pre class=""lang-js prettyprint-override""><code>// A sample unit test looks like:

    test('1# Register user', async () =&gt; {
        const userService = new UserAccountService()
        jest.spyOn(UserModel, 'create')
    
        const registerRequest: RegisterRequest = {
            email: 'abc@abc.com',
            password: '1234'
        }
        const registeredUser = await userService.register(registerRequest);
    
        expect(UserModel.create).toHaveBeenCalledTimes(1);
        expect(registeredUser).toBeInstanceOf(UserModel);
        expect(registeredUser.email).toEqual('abc@abc.com')
    });
</code></pre>
<p>Can someone help me on how to unit test with such Sequelize database calls? I know we can use <code>mockImplementationOnce()</code> or <code>mockResolvedValue()</code> with a fake <code>UserModel</code> object, but what if I have a lot of database calls in a function with multiple models, mocking or creating all fake model objects is very annoying and that leads to creating complicated and big test cases, which apparently is a bad sign. Is there any other way how we can unit test with Sequelize model functions?</p>
",https://stackoverflow.com/questions/67822326/how-to-unit-test-sequelize-database-calls-using-jest-and-sequelize-typescript,"['jestjs', 'sequelize.js', 'ts-jest', 'sequelize-typescript']",6081,False,3,1
Getting &#39;_axios.default.create is not a function&#39; when trying to test a component that makes an axios call with Jest,"<p>I am attempting to use Jest/Enzyme to test if an axios function goes through. I've tried various solutions, ways of mocking, as well as just redesigning the component itself to have the test recognize the axios request but I keep getting the same error.</p>
<p>At this point I've modified my test to just get past the axios failure, and then I will will return to a conditional pass/fail test. Right now my test is plainly:</p>
<pre><code>import { shallow }  from 'enzyme';
import Assets from '../src/components/App';

jest.mock('axios', () =&gt; {
  return {
    __esModule: true,
    default: jest.fn()
  }
});

describe(&quot;Component&quot;, () =&gt; {
  const component = shallow(&lt;App /&gt;);    
})
</code></pre>
<p>and I get returned the error:</p>
<pre><code>TypeError: _axios.default.create is not a function
</code></pre>
<p>The app is question has a reference to an axios request from another file on App.js there is a command:</p>
<pre><code>let response = await axiosGetTest.get('...');
</code></pre>
<p>axiosGetTest is a function in another file where the error is originating from, in that file we have:</p>
<pre><code>const axiosGetTest = axios.create({
    baseURL: '...',
    timeout: 15000,
    headers: {
     ...
    }
});
</code></pre>
<p>Sorry if the explanation is crude, I am very new to unit testing in JavaScript</p>
",https://stackoverflow.com/questions/66465749/getting-axios-default-create-is-not-a-function-when-trying-to-test-a-componen,"['reactjs', 'unit-testing', 'jestjs', 'axios', 'enzyme']",4699,True,2,1
Getting code coverage reports with Cypress and React app,"<p>I am working on a project given to me by a client with an existing code base. It is React based, without using Create-React-App. I'm not the most versed in using babel and webpack at all, as I typically rely on CRA and react-scripts. I'm using Cypress with Istanbul for unit testing, and after following the docs and several guides I have been unable to get code coverage reports to generate.</p>
<p>I am not entirely sure what code would be necessary for anyone looking to help, so I will put what I think is relevant here and add as recommended by anyone commenting.</p>
<p>My babelrc file:</p>
<pre><code>  &quot;presets&quot;: [
    [
      &quot;@babel/preset-env&quot;,
      {
        &quot;targets&quot;: {
          &quot;node&quot;: &quot;current&quot;
        }
      },
      &quot;@babel/preset-react&quot;
    ]
  ],
  &quot;plugins&quot;: [
    [
      &quot;module-resolver&quot;,
      {
        &quot;root&quot;: [
          &quot;./src&quot;
        ]
      }
    ],
    [
      &quot;@babel/plugin-syntax-dynamic-import&quot;
    ],
    [
      &quot;transform-class-properties&quot;
    ],
    [
      &quot;istanbul&quot;
    ]
  ],
  &quot;env&quot;: {
    &quot;test&quot;: {
      &quot;plugins&quot;: [
        &quot;istanbul&quot;
      ]
    },
    &quot;e2e&quot;: {
      &quot;plugins&quot;: [
        &quot;istanbul&quot;
      ]
    }
  }
}
</code></pre>
<p>index.js of cypress plugins:</p>
<pre><code>// ***********************************************************
// This example plugins/index.js can be used to load plugins
//
// You can change the location of this file or turn off loading
// the plugins file with the 'pluginsFile' configuration option.
//
// You can read more here:
// https://on.cypress.io/plugins-guide
// ***********************************************************

// This function is called when a project is opened or re-opened (e.g. due to
// the project's config changing)

/**
 * @type {Cypress.PluginConfig}
 */
// eslint-disable-next-line no-unused-vars
module.exports = (on, config) =&gt; {
  require('@cypress/code-coverage/task')(on, config)
  on('file:preprocessor', require('@cypress/code-coverage/use-babelrc'))
  return config
}
</code></pre>
<p>index.js of my support folder for Cypress:</p>
<pre><code>import '@cypress/code-coverage/support'
</code></pre>
<p>And the script I execute for testing</p>
<pre><code> &quot;cy&quot;: &quot;cypress run &amp;&amp; nyc report --reporter=text --reporter=text-summary&quot;
</code></pre>
<p>Everything was instrumented by NYC, as well.</p>
<p>Thanks for any help!</p>
",https://stackoverflow.com/questions/70188936/getting-code-coverage-reports-with-cypress-and-react-app,"['reactjs', 'cypress']",966,False,2,0
pytest: Run test modules in a specific order,"<p>Let me say I'm still new to unit testing and using <code>pytest</code>.</p>
<p>I'm building unit tests and running them with GitHub Actions and I understand why it failed. I need to run the test modules in a specific order.</p>
<p>For reference, I have a following repo structure (generalized for simplicity)</p>
<pre><code>mypackage/
├── __init__.py
├── foo.py
└── bar.py
tests/
├── __init__.py
├── test_foo.py
└── test_bar.py
</code></pre>
<p>My question (written for generalization): Is there a way to run specific test modules (not functions) in a given order with <code>pytest</code>? By default <code>pytest</code> will run in alphabetical order, i.e., <code>test_bar</code> before <code>test_foo</code>. However, in my case, <code>test_bar</code> uses data from <code>test_foo</code>, so I would like the order to be flipped. I can find other work arounds, but from my search I only found explanations of using <code>pytest-order</code> or <code>pytest-ordering</code> for specific functional orders in a <em>given</em> module. I thought this would be a good question for end-to-end testing while still ensuring 100% code coverage.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/66307767/pytest-run-test-modules-in-a-specific-order,"['python', 'python-3.x', 'pytest', 'github-actions']",729,False,2,0
Svelte Stores &amp; Jest,"<p>I'm looking for an way to mock/stub stores that are used in Svelte components, specifically with the auto-subscribe syntax (ie <code>$myStore</code> or <code>$myStore.property</code>).</p>
<p>I've tried a couple of different mocks, mostly along the lines of the following:</p>
<pre><code>jest.mock('./stores/users', () =&gt; ({
  currentUser: jest.fn().mockImplementation(() =&gt;
    writable({
      isAdmin: true,
    }),
  ),
}));
</code></pre>
<p>The test will error out on any auto-subscribed references to the store, which are undefined. For example, if I am referencing a store from <code>&quot;../../stores/users&quot;</code> in my component like so...</p>
<pre><code>{#if $user.isAdmin}
  &lt;div&gt;Hello I'm an admin&lt;/div&gt;
{/if}

</code></pre>
<p>... then I receive <code>TypeError: Cannot read property 'isAdmin' of undefined</code></p>
<p>It seems that even when mocking a Svelte store, the <code>$</code> auto-subscribe syntax is not breaking the test. I should point out that when logging the mocked store, the expected Svelte store methods (<code>subscribe()</code>, <code>set()</code> and <code>update()</code>) are there, and executing the <code>subscribe()</code> method exposes the <code>isAdmin</code> attribute also as expected.</p>
<p>I can't seem to find any established unit testing patterns that deal with Svelte and the use of stores, so any and all input on the topic would be greatly appreciated!</p>
",https://stackoverflow.com/questions/70042233/svelte-stores-jest,"['unit-testing', 'jestjs', 'svelte', 'svelte-store']",834,True,6,1
dotnet-reportgenerator is not able to find any coverage.cobertura.xml when running inside Gitlab CI pipeline,"<p>I want to generate a single coverage report for my C# project based on this tutorial</p>
<p><a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage</a></p>
<p>When starting a Gitlab CI pipeline with the following configuration</p>
<pre><code>image: mcr.microsoft.com/dotnet/sdk:5.0

stages:
  - build
  - unit-tests

build:
  stage: build
  script:
    - dotnet build --output build
  artifacts:
    paths:
      - build

unit-tests:
  stage: unit-tests
  script:
    - |-
      dotnet test --no-build --output build --collect:&quot;XPlat Code Coverage&quot;;
      
      dotnet tool install -g dotnet-reportgenerator-globaltool;

      reportgenerator -reports:'**/coverage.cobertura.xml' -targetdir:'CoverageReports' -reporttypes:'Cobertura';
  artifacts:
    reports:
      cobertura: CoverageReports/Cobertura.xml
  dependencies:
    - build
</code></pre>
<p>I get the following error</p>
<blockquote>
<p>The report file pattern '**/coverage.cobertura.xml' is invalid. No matching files found.</p>
</blockquote>
<p>When using <code>ls</code> to inspect the directory before running the reportgenerator command I can see that there are no matching files (although they should exist).</p>
<p>I would expect to have one coverage.cobertura.xml file per test project e.g.</p>
<ul>
<li><code>...\myRepo\xUnitTestProject1\TestResults\380e65f7-48d5-468f-9cbc-550c8e0aeda8\coverage.cobertura.xml</code></li>
<li><code>...\myRepo\xUnitTestProject2\TestResults\c96c55f7-40d3-483e-a136-573615e3a9c3\coverage.cobertura.xml</code></li>
</ul>
<hr />
<p><strong>My current solution:</strong></p>
<p>It seems I have to run the build again. So I replaced this line</p>
<p><code>dotnet test --no-build --output build --collect:&quot;XPlat Code Coverage&quot;;</code></p>
<p>with</p>
<p><code>dotnet test --collect:&quot;XPlat Code Coverage&quot;;</code></p>
<p>Now it's working fine but an additional build seems to be redundant because I already created a build artifact...</p>
<hr />
<p>So do you have any ideas how to improve the configuration so that I don't have to build a second time?</p>
",https://stackoverflow.com/questions/68591472/dotnet-reportgenerator-is-not-able-to-find-any-coverage-cobertura-xml-when-runni,"['c#', 'continuous-integration', 'gitlab-ci', 'gitlab-ci-runner']",8979,True,6,1
Create Package from folder structure with subpackages,"<p>I have been given a folder called <code>PackageName</code> with the following structure.</p>
<pre><code>PackageName/
    |- SubPackage.jl/
           |- src/
                  |- MyModule.jl
           |- test/
                  |- runtests.jl
           |- Project.toml
           |- Manifest.toml
    |- Project.toml
    |- Manifest.toml
    |- .gitignore
    |- .gitattributes
    |- README.md
</code></pre>
<p>Inside <code>PackageName</code> there are various <code>.git</code> files like <code>.gitignore</code>, <code>.gitattributes</code> and <code>README.md</code>. There are also a <code>Project.toml</code> and a <code>Manifest.toml</code> which are required in a Julia package. Finally, there are various folders with the structure of <code>SubPackage</code>. Essentially they also contain a <code>Project.toml</code> and a <code>Manifest.toml</code>. They also contain a <code>src/</code> directory with a Module named <code>MyModule.jl</code> and a <code>test/</code> directory with some unit testing. The <code>MyModule.jl</code> has a function called <code>myfunction()</code>, which is exported.</p>
<p>I would like to use all the <code>SubPackage</code>-style packages but I am encountering some issues. <code>PackageName</code> doesn't seem to be a proper Julia package because</p>
<ul>
<li>it doesn't have a <code>src/</code> directory.</li>
<li>it's <code>Project.toml</code> has an <code>author</code>, a <code>version</code> and <code>[deps]</code> fields but lacks a <code>name</code> and <code>uuid</code>.</li>
</ul>
<p>What is the best way to go about using the packages in this folder properly within a Julia environment? Essentially I would like to be able to do <code>using PackageName</code> and being able to use <code>myfunction()</code>.</p>
",https://stackoverflow.com/questions/69826702/create-package-from-folder-structure-with-subpackages,['julia'],174,False,1,0
Using dune + qtest in a multi-file project,"<p>Let me begin by saying that I'm a complete beginner in OCaml, so if I seem to have made some weird choices, I'm most likely not aware of them being a choice.</p>
<p>I am trying to get unit testing working in my project. After some searching I settled on <code>qtest.lib</code>.</p>
<p>I've set up my project as follows:</p>
<pre><code>$ mkdir mylib
$ cd mylib
$ dune init lib mylib
</code></pre>
<p>In the <code>dune</code> file, I've written:</p>
<pre><code>(library
 (name mylib)
 (inline_tests (backend qtest.lib)))
</code></pre>
<p>In <code>mylib.ml</code>, I've put the following code:</p>
<pre class=""lang-ml prettyprint-override""><code>let foo x = x + 2

(*$T foo
  foo 2 = 4
*)
</code></pre>
<p>At this point, <em>everything works as expected</em>:</p>
<pre><code>$ dune runtest
Info: Creating file dune-project with this contents:
| (lang dune 2.9)
inline_test_runner_mylib alias runtest
random seed: 425752161
 [1 / 1] &gt;foo&gt;mylib.ml:4 *
 [1 / 1] &gt;foo&gt;;32;1mSUCCESS
</code></pre>
<p>The issues start if I try to introduce another file into the project. I created <code>helper.ml</code> with the following contents:</p>
<pre class=""lang-ml prettyprint-override""><code>let bar x = 3 * x

(*$T bar
  bar 3 = 9
*)
</code></pre>
<p>Now, <code>dune runtest</code> errors out with</p>
<pre><code>$ dune runtest
File &quot;mylib.ml&quot;, line 11, characters 5-11:
Error: Unbound module Helper
</code></pre>
<p>In some of my other attempts at reproducing it, the file mentioned was instead <code>_build/default/.mylib.inline-tests/inline_test_runner_mylib.ml-gen</code>.</p>
<p>I first assumed that this means I'm organizing my files incorrectly. However, I can access <code>Helper.bar</code> within <code>mylib.ml</code>:</p>
<pre><code>$ cat mylib.ml
let foo x = Helper.bar (x + 2)
$ dune build     # no errors
</code></pre>
<p>Thus I have no idea what the problem could be here. What's going on?</p>
",https://stackoverflow.com/questions/69514873/using-dune-qtest-in-a-multi-file-project,"['unit-testing', 'ocaml', 'ocaml-dune']",199,False,1,2
Mockito cannot resolve a public static method of a class,"<p>I have a <code>Component</code> class called <code>AppUtil</code> with a bunch of <code>public</code> <code>static</code> methods:</p>
<pre class=""lang-java prettyprint-override""><code>@Component
public class AppUtil {
    
    // Methods, fields...
    
    public static List&lt;String&gt; getActiveProfiles() {
        return newArrayList(appUtil.env.getActiveProfiles());
    }

    public static String readResourceFileAsString(String fileName) throws IOException {
        return IOUtils.toString(new FileReader(fileName));
    }
    
    // More methods....
    
}
</code></pre>
<p>The two <code>static</code> methods writen above are called by a method called <code>loadUserByUsername</code> of a class called <code>GearApiUserDetailsService</code>. In order to test <code>GearApiUserDetailsService.loadUserByUsername</code>, I want to mock the calls to these <code>static</code> methods of <code>AppUtil</code>. This is what my unit testing class looks like right now:</p>
<pre class=""lang-java prettyprint-override""><code>@RunWith(MockitoJUnitRunner.class)
public class GearApiUserDetailsServiceTest {

    @InjectMocks
    private GearApiUserDetailsService gearApiUserDetailsService;

    @Before
    public void setUp(){
        MockitoAnnotations.openMocks(this);
    }

    @Test
    public void testLoadUserByUsernameWithoutActiveProfiles(){
        try (MockedStatic&lt;AppUtil&gt; mockedStatic = Mockito.mockStatic(AppUtil.class)) {
            mockedStatic.when(AppUtil::getActiveProfiles).thenReturn(Collections.emptyList());
            mockedStatic.when(AppUtil::readResourceFileAsString).thenReturn(&quot;random string&quot;);
            final String apiKey = &quot;someExampleAPIKey&quot;; 
            UserDetails userDetails = gearApiUserDetailsService.loadUserByUsername(apiKey);
            assertEquals(apiKey, userDetails.getUsername());
        }
    }
}
</code></pre>
<p>The problem is that while the mock of <code>getActiveProfiles</code> works well (tested), the mock of <code>readResourceFileAsString</code> fails at <em><strong>compile</strong></em> time even, with IntelliJ reporting that it can't resolve it:</p>
<p><img src=""https://i.stack.imgur.com/t99Up.png"" alt=""enter image description here"" /></p>
<p>The methods are both <code>public</code> and <code>static</code>, with the only difference being that the second one takes an argument.</p>
<p><a href=""https://stackoverflow.com/questions/64461915/mockito-mockstatic-cannot-resolve-symbol"">This 2020 post</a> seems to suggest ensuring that the <code>pom</code> file contains a dependency of <code>mockito-core</code> at version <code>3.5.13</code>. I have included this dependency, invalidated caches / restarted, tried to re-run entire maven build lifecycle, but obviously it still fails at compile time because of the aforementioned error. Ideas? (=</p>
",https://stackoverflow.com/questions/68733709/mockito-cannot-resolve-a-public-static-method-of-a-class,"['spring', 'mocking', 'mockito', 'junit4', 'mockstatic']",600,True,1,1
sinon stub calls fake calling actual function,"<p>I'm having situation where I want to write unit test cases for a function to make sure if it is working fine or not. So I have created stub for that specific function and when I tries to calls fake that stub, the function is actually getting called instead of fake call. Below is my scenario:</p>
<ul>
<li>I have an main function from where I'm calling the function saveData(**).</li>
<li>saveData(**) function is calling AWS SQS to save an message to DB</li>
</ul>
<p>Below is my main function:</p>
<pre><code>'use strict';
async function mainFunction() {
  try {
    await saveData(
      name,
      age,
    );
    return true;
  } catch (e) {
    console.log('Error - [%s]', e);
    return null;
  }
}    
module.exports = { mainFunction };
</code></pre>
<p>Below is my saveData(**) function:</p>
<pre><code>'use strict';
const AWS = require('aws-sdk');
const sqs = new AWS.SQS();
const saveData = async (
  name,
  age,
) =&gt; {
    await sendMessage(JSON.stringify(dbData));
    const params = {
        DelaySeconds: &lt;some_delay&gt;,
        MessageAttributes: &lt;messageAttributes&gt;,
        MessageBody: {name:name, age:age},
        QueueUrl: &lt;URL_FOR_QUEUE&gt;,
      };
      return sqs.sendMessage(params).promise();
  return true;
};
module.exports = {
  saveData,
};
</code></pre>
<p>And my test case is,</p>
<pre><code>'use strict';

const express = require('express');
const bodyParser = require('body-parser');
require('app-module-path').addPath('./src');
const sinon = require('sinon');
const app = express();
const sqsSender = require('lib/queue');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const main = require('../../../src/main-function');
const routes = require('routes');
routes.configure(app);
let mainFunctionStub;
let saveDataStub;

describe('/v1/main', () =&gt; {
  beforeEach(() =&gt; {
    mainFunctionStub = sinon.stub(main, 'mainFunction');
    saveDataStub = sinon.stub(sqsSender, 'saveData');
  });
  describe('Test', () =&gt; {
    it(`should return success`, (done) =&gt; {
      const name = 'Name';
      const age = 'Age';
      saveDataStub.resolves({
        name,
        age,
      });
    });
  });

  afterEach(() =&gt; {
    mainFunctionStub.restore();
    mainFunctionStub.reset();

    saveDataStub.restore();
    saveDataStub.reset();
  });
});
</code></pre>
<p>But this test is returning,</p>
<pre><code>error: Jun-20-2021 20:07:05:    Error - [Error [ConfigError]: Missing region in config
</code></pre>
<p>and,</p>
<pre><code>Error: Timeout of 3500ms exceeded.
</code></pre>
<p>From this error I can say that this is actually calling SQS function instead of faking. How can I resolve this or how can I fake call to this function? I'm new to this unit testing so any help would be appriciated.</p>
",https://stackoverflow.com/questions/68057002/sinon-stub-calls-fake-calling-actual-function,"['node.js', 'unit-testing', 'sinon', 'stubbing', 'sinon-chai']",1198,True,1,1
"Jest running individual test passes, but running test suite makes it fail, what could be casuing this?","<p>I'm using Jest for unit testing in a NestJS project. I've been struggling because one of the tests passes when I run it individually but when running the full test suite (which has about 6 tests in total) this sepcific test fails, but the other 5 are fine. I checked twice on the values that are being used in the tested function and I also checked that the conditions are being fulfilled so everything should be working perfectly, but the function isn't returning what it's supposed to.</p>
<p>The data I'm using is mock data and just to make sure I'm not messing it up I copy it into another variable, here is the test I'm running:</p>
<pre class=""lang-js prettyprint-override""><code>it(&quot;doesn't apply, 2 consecutive returns are the two first&quot;, ()=&gt;{
      const loan = {...mockloan}
      loan.inputRecords[1].paymentAmount = '0'
      loan.schedule[0].status = ScheduleStatus.RETURNED
      loan.inputRecords[2].paymentAmount = '0'
      loan.schedule[1].status = ScheduleStatus.RETURNED
      loan.inputRecords[3].paymentAmount = '218.97'
      loan.schedule[2].status = ScheduleStatus.PENDING
      loan.inputRecords[4].paymentAmount = null
      loan.inputRecords.forEach((i, index )=&gt;{
        console.log(i.paymentID+&quot; -- &quot; + i.paymentAmount + &quot;-- &quot;+ ((index != 0)? (loan.schedule[index-1] ?loan.schedule[index-1].status: &quot;&quot;): &quot;&quot;))
      })
      const {action, reason, returnedInputs} = loanService.appliesForHalfPayment(loan);
      console.log(action)
      expect(action).toBe(&quot;collection&quot;)
      expect(reason).toBe(LoanTypeEvent.SECOND_RETURN_AFTER_FPD)
      expect(returnedInputs).toBeNull()
})
</code></pre>
<p>I reviewed the the test suite again and I'm receiving the expected values (in the console.log(action) but the the expect(action).toBe(&quot;collection&quot;) is receiving null</p>
",https://stackoverflow.com/questions/70522551/jest-running-individual-test-passes-but-running-test-suite-makes-it-fail-what,['jestjs'],743,False,1,0
How to configure unit testing for AnyLogic agent code?,"<p>How do you configure unit testing framework to help develop code that is part of AnyLogic agents?</p>
<p>To have a suitable test driven development rhythm, I need to be able to run all tests in a few seconds. I thought of exporting the project as a standalone application (jar) each time, but that's pretty slow.</p>
<p>I thought of trying to write all the code outside AnyLogic in separate classes, but there are many references to built-in AnyLogic classes, as well as various agents. My code would need to refer to these somehow, and I'm not sure how to do that except by writing the code inside AnyLogic.</p>
<p>I wonder if there's a way of adding the test runner as a dependency, and executing that test runner from within AnyLogic.</p>
<p>Does anyone have a setup that works nicely?</p>
",https://stackoverflow.com/questions/69005232/how-to-configure-unit-testing-for-anylogic-agent-code,"['unit-testing', 'junit', 'simulation', 'anylogic']",306,True,1,1
pytest: How to use test class instance variables as fixture params,"<p>I am trying to reuse some unit testing functionality. The only variable part is actually the set of test data. Therefore I encapsulate the testing logic in a class and inject the actual test data at object creation.</p>
<p>Unfortunately this does not seem to work with the <code>@pytest.fixture</code> decorator.</p>
<p>Some minimal code to reproduce.
This is the common definition of my test class in <code>define_test.py</code>:</p>
<pre><code>#!/usr/bin/env python3

import pytest

class TestDemo:
    def __init__(self, _data: list):
        self.__testData = _data

    @pytest.fixture(scope='module', params=self.__testData)
    def fixture(self, request):
        return request.param

    def test(self, fixture):
        foo = fixture
        assert foo is not None

</code></pre>
<p>Intended usage would be something like this in <code>use_test.py</code></p>
<pre><code>#!/usr/bin/env python3

import define_test

data1 = [1, 2, 3, 4]
test1 = define_test.TestDemo(data1)
data2 = [4, 3, 2, 1]
test2 = define_test.TestDemo(data2)
</code></pre>
<p>Trying to run this code produces</p>
<pre><code>define_test.py:9: in TestDemo
    ???
E   NameError: name 'self' is not defined
</code></pre>
<p>I am pretty sure that the problem is, that one cannot simply apply the usual OO mechanisms to the <code>pytest</code> decorator. It seems as either the decorator is evaluated before even an instance of this class exists or it cannot handle instances at all.</p>
<p><strong>So what would be the correct way of achieving the goal of reusable tests with variable data?</strong></p>
",https://stackoverflow.com/questions/69478940/pytest-how-to-use-test-class-instance-variables-as-fixture-params,"['python', 'pytest']",1149,True,1,1
Failed navigation test with React Router,"<p>In my code I use react-router-dom with react-boostrap elements. I've been trying to do some navigation tests. I have no experience in unit testing so every tip will be appreciated.</p>
<p>My Routes are in seperate file:</p>
<pre><code>function Routes() {
    return (
        &lt;div className=&quot;App&quot;&gt;
            &lt;Header /&gt;
            &lt;Switch&gt;
                &lt;Route exact path=&quot;/&quot;&gt;
                    &lt;Container&gt;
                        &lt;Row className=&quot;mt-3&quot;&gt;
                            &lt;Deck /&gt;
                        &lt;/Row&gt;
                        &lt;Row className=&quot;mt-3&quot;&gt;
                            &lt;Deck /&gt;
                        &lt;/Row&gt;
                    &lt;/Container&gt;
                &lt;/Route&gt;
                &lt;Route path=&quot;/about&quot;&gt;
                    &lt;h1&gt;About_us&lt;/h1&gt;
                &lt;/Route&gt;
                &lt;Route path=&quot;/dashboard&quot;&gt;
                    &lt;h1&gt;Dashboard&lt;/h1&gt;
                &lt;/Route&gt;
                &lt;Route path=&quot;/faq&quot;&gt;
                    &lt;h1&gt;FAQ&lt;/h1&gt;
                &lt;/Route&gt;
                &lt;Route path=&quot;/login&quot;&gt;
                    &lt;LoginPage /&gt;
                &lt;/Route&gt;
                &lt;Route path=&quot;/signup&quot;&gt;
                    &lt;SignUpPage /&gt;
                &lt;/Route&gt;
                &lt;Route&gt;
                    &lt;h1&gt;Bad page&lt;/h1&gt;
                &lt;/Route&gt;
            &lt;/Switch&gt;
        &lt;/div&gt;
    );
}

export default Routes;
</code></pre>
<p>The unit test portion:</p>
<pre><code>import '@testing-library/jest-dom';
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';

import Routes from '../src/Routes.js';


test('full app navigating', async () =&gt; {

    render(
        &lt;MemoryRouter initialEntries={['/']}&gt;
            &lt;Routes /&gt;
        &lt;/MemoryRouter&gt;
    );

    expect(screen.getAllByText(/Card info/i)[0]).toBeInTheDocument();


    fireEvent.click(screen.getByText(/Flashcards/i));
    let result = await screen.findAllByText(/Card info/i);
    expect(result[0]).toBeInTheDocument();

    fireEvent.click(screen.getByText(/Home/i));
    result = await screen.findAllByText(/Card info/i);
    expect(result[0]).toBeInTheDocument();


    fireEvent.click(screen.getByText(/About/i));
    result = await screen.findByText(/About_us/i);
});
</code></pre>
<p>So on the path &quot;/&quot; I'm displaying Deck component which basically has &quot;Card info&quot; text in it. That's why I  search for that text. On the other hand path &quot;/about&quot; just renders <code>&lt;h1&gt;About_us&lt;/h1&gt;</code>. App works fine when i run it but testing with jest results in error:</p>
<pre><code>FAIL  tests/Routes.test.js
  × full app navigating (1123 ms)

  ● full app navigating

    TestingLibraryElementError: Unable to find an element with the text: /About_us/i. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
</code></pre>
<p>It seems I do not navigate properly in my unit test.</p>
<p>EDIT: When I change initialEntries to &quot;/about&quot; the app renders stuff at that route so path works by itself. It must be related to that line:</p>
<pre><code>fireEvent.click(screen.getByText(/About/i));
</code></pre>
<p>About is just a &lt;Nav.Link&gt; bootstrap tag with href=&quot;/about&quot; so that's how I redirect to /about .</p>
",https://stackoverflow.com/questions/66229167/failed-navigation-test-with-react-router,"['javascript', 'reactjs', 'unit-testing', 'react-router', 'react-bootstrap']",464,True,1,1
Can a header with declared functions be mocked?,"<p>I'm working in a project targeting a Silicon Labs microcontroller. I want to create a wrapper for the Bluetooth SDK calls. SDK libraries are heavy on dependencies, so by creating a seem in that interface, I can avoid adding them to my tests. Note that this problem is not specific of the Silicon Labs platform, but I will leave the SiLabs SDK file names in case the reader is familiar with the platform.</p>
<p>I'm using CPPUTest as my testing framework. My code is a mix of C and C++, but for the purposes of this question, it's C.</p>
<p>For example, one of my wrapping functions (in a module called <code>Bluetooth_HW</code>) would be</p>
<pre class=""lang-c prettyprint-override""><code>/* On &quot;Bluetooth_HW.c&quot; */

#include &quot;native_gecko.h&quot; // declares gecko_cmd_le_gap_bt5_set_adv_data()

// Set a new advertisement, either as advertisement packet or as a response.
bool BT_setAdvertisementMessage(uint8_t scanResponse, uint8_t adLength, uint8_t* newAdvertisement) {
    uint16_t result = gecko_cmd_le_gap_bt5_set_adv_data(0, scanResponse, adLength, newAdvertisement)-&gt;result;
    if (result != bg_err_success) {
        return false;
    } // Else, no errors setting the advertisement
    return true;
}
</code></pre>
<p><code>BT_setAdvertisementMessage()</code> wraps <code>gecko_cmd_le_gap_bt5_set_adv_data()</code>, which is defined in <code>native_gecko.h</code>, an SDK header file. I declare <code>BT_setAdvertisementMessage()</code> in <code>Bluetooth_HW.h</code> and define it in <code>bluetooth_HW.c</code>. My code that needs to set the advertisement message then includes <code>Bluetooth_HW.h</code> instead of <code>native_gecko.h</code>, and <code>Bluetooth_HW.h</code> is easy to mock.</p>
<p>I would like to test <code>Bluetooth_HW.c</code>. I need to mock <code>native_gecko.h</code> for that, as I am not interested in running its code (it's provided by the manufacturer, I trust it, plus I'm not unit testing <code>native_gecko</code>, I'm unit testing <code>Bluetooth_HW</code>). Normally, I would include the production <code>.h</code> file in my tests, to get declarations of the functions, and then substitute the <code>.c</code> file that contains the production code definitions with my fake implementation.</p>
<p>My problem is that <code>native_gecko.h</code> defines <code>gecko_cmd_le_gap_bt5_set_adv_data()</code> as an inline inside the header, instead of the more common approach of doing it on a <code>.c</code> file.</p>
<p>I could wrap <code>native_gecko.h</code> itself on a header that just declares the functions that I need, and make my code include that header, but then I don't have access to other stuff declared in <code>native_gecko.h</code>, like custom types and enums. I can't move those types and enums to the wrapper, as I can't remove them from <code>native_gecko.h</code> and the compiler would then complain of being defined twice, and I don't want to touch <code>native_gecko.h</code>, because it's an SDK file.</p>
<p>So, my question is how to mock modules that define code in their headers?</p>
",https://stackoverflow.com/questions/70363258/can-a-header-with-declared-functions-be-mocked,"['c', 'cpputest']",618,True,1,1
Unit testing a service with many dependencies in NestJS,"<p>When building API's in Nest, I often come across an issue where a particular API might need to make use of several Nest modules to do it's job.  I'd like to know if there's a better way to structure my modules so that unit testing them is easier.</p>
<p>For example, imagine we have an <code>OrderService</code>.  The <code>OrderService</code> makes use of a few different dependencies in order to do it's job:</p>
<ul>
<li>It uses the <code>ProductsService</code> in order to look up product details and prices.</li>
<li>It uses the <code>UsersService</code> in order to look up customer information, such as a Stripe customer ID.</li>
<li>It uses a Typeorm to handle writing the <code>Order</code> into the database</li>
<li>And finally, let's say it uses a <code>CouponsService</code> in order to look up and validate coupon details for the <code>Order</code>.</li>
</ul>
<p>For the sake of this example, let's just imagine each of these 4 dependencies to be it's own Nest module.</p>
<p>When it comes to unit testing the <code>OrdersService</code>, I'd then need to stub out 4 different dependencies.  This seems like a lot more work than it should be, and so I realized there must be a better way.</p>
<p>One thing that I've tried doing is creating separate helper files for setting up each services mocks.  This cuts down on the amount of boilerplate for each service that uses a particular dependency, but you still end up in a situation where 1 service might have 4 different dependencies.</p>
<p>Ideally, I'd like to implement some pattern or structure so that when I test a file, the dependencies are either really simple or automatic to mock, or a particular file only has 1 dependency at a time, without oversimplifying the system.</p>
<p>My question really boils down to:</p>
<p>How do you handle many dependencies like this in a Service, without ending up in a situation where testing a function requires you to mock 4+ methods.  I'd love to hear a Nest specific way to do this, but I'd also appreciate any generic software engineering examples or patterns to look into as well.</p>
",https://stackoverflow.com/questions/68434502/unit-testing-a-service-with-many-dependencies-in-nestjs,"['unit-testing', 'nestjs']",4197,True,1,1
How to do basic testing in a SwiftUI project?,"<p>I have this super basic app which changes the colour of a circle when you press a button:</p>
<pre><code>struct ContentView: View {
    @State private var color: Color = .red
    
    var body: some View {
        VStack {
            Circle()
                .frame(width: 100, height: 100)
                .foregroundColor(color)
            
            Button(&quot;Press me&quot;) {
                color = color == .red ? .blue : .red
            }
        }
    }
}
</code></pre>
<p>All I want to do is write a test which checks if the button appropriately changes the colour of the circle.</p>
<p>I only just read about all the unit testing and UI testing capabilities of Xcode but am unsure how to go about this. From the resources I've read online they all recommend either Snapshot Testing or using a package called <code>ViewInspector</code>. However I just want to play around with the inbuilt capabilities of Xcode and am not looking for any rigorous testing frameworks or methods. Could someone tell me how Apple recommends to test SwiftUI Views? If there's no official/recommended way can someone tell me how to write a unit/UI test to check if the circle's colour changed appropriately.</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/68291370/how-to-do-basic-testing-in-a-swiftui-project,"['ios', 'swift', 'testing', 'swiftui', 'xctest']",723,True,0,1
Can&#39;t unit testing a method that gets values app.config,"<p>In a .NET Core 3.1 console application I have some methods that use app.config to get some values (System.Configuration.ConfigurationManager.AppSettings[&quot;my-key&quot;]). It gets the values correctly when running the application.</p>
<p>However when I try to unitTest (with Visual Studio TestTools) these methods the values I get are null. I tried creating an app.config file inside the unitTest project and using ConfigurationManager directly in the unitTest method, still null values.</p>
<p>I read there are some workarounds like mocking the configuration or passing these values as parameters to these methods, however I don't think these workarounds are the cleanest thing, also then my unitTests couldn't really check if my configuration file is alright.</p>
<p>So, does anyone know why the ConfigurationManager get null values while unit testing? Is it because its a static class by chance? Also is there a way to use it somehow?</p>
",https://stackoverflow.com/questions/69484592/cant-unit-testing-a-method-that-gets-values-app-config,"['c#', '.net-core-3.1']",264,False,0,0
Setting up a Symfony Bundle with unittests against a database,"<p>I am using Pimcore, a framework with Symfony at it's core. Pimcore is programmed by people that do not understand unit testing. They are tightly coupled to the database.</p>
<p>I am writing a bundle to extend the functionalities of Pimcore. However, it goes wrong when the internals of Pimcore try to write to the database:</p>
<pre><code>Error: Call to a member function getContainer() on null

/opt/vendor/pimcore/pimcore/lib/Pimcore.php:167
/opt/vendor/pimcore/pimcore/lib/Db.php:49
/opt/vendor/pimcore/pimcore/lib/Model/Dao/AbstractDao.php:37
/opt/vendor/pimcore/pimcore/lib/Model/AbstractModel.php:120
/opt/vendor/pimcore/pimcore/lib/Model/AbstractModel.php:54
/opt/vendor/pimcore/pimcore/models/DataObject/ClassDefinition.php:288
/opt/vendor/pimcore/pimcore/models/DataObject/Concrete.php:419
/opt/vendor/pimcore/pimcore/models/DataObject/Concrete.php:729
/opt/tests/DataObjectTest.php:28
</code></pre>
<p>The code that actually goes wrong is:</p>
<pre><code>/**
 * @return \Pimcore\Db\ConnectionInterface|Connection
 */
public static function get()
{
    /**
     * @var \Pimcore\Db\ConnectionInterface $db
     */
    $db = \Pimcore::getContainer()-&gt;get('database_connection');

    return $db;
}
</code></pre>
<p>I am willing to create the database schema and test against a database for this specific library since mocking away the database is literally impossible. However, I have no idea how to do that since I'm in a standalone bundle that doesn't have the whole config directory in which you define doctrine etc, nor does it have a Kernel.php which even builds the container.</p>
<p>So my question basically is, how can I set up a Kernel Database connection used by PHPUnit?</p>
",https://stackoverflow.com/questions/70234608/setting-up-a-symfony-bundle-with-unittests-against-a-database,"['symfony', 'doctrine', 'bundle', 'pimcore']",353,False,-1,1
apache bean unable to serialize due to interface that I want to mock,"<p>unable to serialize DoFnWithExecutionInformation{doFn=com.orderly.dataflow.RosterFileReader@60ec7684, mainOutputTag=Tag, sideInputMapping={}, schemaInformation=DoFnSchemaInformation{elementConverters=[]}}
java.lang.IllegalArgumentException: unable to serialize DoFnWithExecutionInformation{doFn=com.orderly.dataflow.RosterFileReader@60ec7684, mainOutputTag=Tag, sideInputMapping={}, schemaInformation=DoFnSchemaInformation{elementConverters=[]}}</p>
<p>I am not sure this is possible.  I understand in apache beam, these functions must be serializable for scaling out but during test time I also want to mock where we read from.</p>
<p>Is there some kind of context or something I can create to inject the interface which is mockable for reading?</p>
<p>Here is my code</p>
<pre><code>public class RosterFileReader extends DoFn&lt;String, PractitionerStandardOutputDto&gt; {

    private static final Logger log = LoggerFactory.getLogger(RosterFileReader.class);

    private final String projectId;
    private GCPBucketStorage storage;

    public RosterFileReader(String projectId, GCPBucketStorage storage) {
</code></pre>
<p>I am wondering if there is a context I can send in?  GCPBucketStorage.java is OUR API since googles was not that mockable.  In this way, we have full control of throwing exceptions and testing recovery as well as other scenarios.</p>
<p>EDIT: I would be willing to settle for some code like this</p>
<pre><code>if(isRunningLocally) {
     storage = new MockStorage();
} else { 
     storage = new GCPBucketStorageImpl();
}
</code></pre>
<p>it basically kind of sucks having test code like that in production code, but this END to END test has already caught bugs!!!!!!  bugs that are missed in the unit testing that people are doing.  We generally do not do single class or unit testing and only do what twitter calls Feature Testing since it allows huge refactors without touching tests -&gt; <a href=""https://blog.twitter.com/engineering/en_us/topics/insights/2017/the-testing-renaissance.html"" rel=""nofollow noreferrer"">https://blog.twitter.com/engineering/en_us/topics/insights/2017/the-testing-renaissance.html</a></p>
<p>I can reach into the Mock using static fields I guess(Again, I hate doing that but this test is so valuable having it end to end truly)</p>
<p>EDIT 2: Is serialization a ton like hadoop where you have to define classes to deploy along with the main jar?  Perhaps I just need a document to make GCPStorage and GCPBucketStorageImpl serializable (and MockStorage as well most likely since it is in production code :( ) -&gt; The if..else is totally worth it on the integration bugs we are finding pre-CI so people don't break the code on master ever.</p>
<p>EDIT 3:
This looks very promising -&gt; <a href=""https://gist.github.com/jlewi/f1cd323dc88bd58601ef"" rel=""nofollow noreferrer"">https://gist.github.com/jlewi/f1cd323dc88bd58601ef</a>
Will update post after trying.</p>
<p>thanks,
Dean</p>
",https://stackoverflow.com/questions/67014479/apache-bean-unable-to-serialize-due-to-interface-that-i-want-to-mock,"['apache-beam', 'apache-beam-io']",938,True,1,1
TypeError: Cannot read property &#39;getShaderPrecisionFormat&#39; of undefined when using Threejs and jest,"<p>I'm pretty knew to all the technologies in this q, so please bear with me</p>
<p>Following on from this question:  <a href=""https://stackoverflow.com/questions/51330753/unit-testing-a-threejs-application-with-jest"">Unit testing a ThreeJS application with Jest</a></p>
<p>I have implemented the solution in the answer and so have created this function to mock the viewport:</p>
<pre><code>export function createViewPort () {
  const canvasGL = new Canvas.Canvas(1000, 1000)

  canvasGL.addEventListener = function (event, func, bind_) {
    // mock function to avoid errors inside THREE.WebGlRenderer()
  }
  const glContext = gl(1, 1)
  const renderer = new THREE.WebGLRenderer({ context: glContext, antialias: true, canvas: canvasGL })
  var mvp = new BaseViewPort()
  mvp.initialise(1000, 1000, renderer)
  return mvp
}
</code></pre>
<p>BaseViewPort is my class which creates a camera and a scene.</p>
<p>I then use this in my jest tests and all runs fine on my local machine (windows pc).  When I push this up to the git repository and the build then runs on the server which run in linux, I get the error below:</p>
<p><code>TypeError: Cannot read property 'getShaderPrecisionFormat' of undefined</code></p>
<p>I don't have a clue where to start with looking what might cuase this. Obviously there is some difference between the two environments.  Any ideas where I might start looking?  Should I be using jest.mock to do this?</p>
",https://stackoverflow.com/questions/66256358/typeerror-cannot-read-property-getshaderprecisionformat-of-undefined-when-usi,"['three.js', 'jestjs', 'webgl']",327,False,0,1
Django/Graphene seems to clean database between individual tests in a test run,"<p>I'm testing Django/Graphene to see if it can fulfill what I need, but I'm getting trouble in unit testing.</p>
<p>I'm using the in-memory SQLite db, with the following code (tests.py):</p>
<pre><code>import json

from graphene_django.utils.testing import GraphQLTestCase

from graphene.test import Client

from users.schema import UserType

class APITestCase(GraphQLTestCase):
    def test01_query_users(self):
        print(&quot;Running test01_query_users&quot;)
        response = self.query(
            '''
            query {
                users {
                    id
                    username
                    email
                }
            }
            '''
        )
        print (response)
        content = json.loads(response.content)
        self.assertResponseNoErrors(response)
        print (content)
        assert content == {
            &quot;data&quot;: {
                &quot;users&quot;: []
            }
        }

    def test02_mutation_addUser(self):
        print(&quot;Running test02_mutation_addUser&quot;)
        response = self.query(
            '''
            mutation {
                createUser (username: &quot;testuser&quot;, email: &quot;testemail@testserver.com&quot;, password: &quot;123456&quot;) {
                    user {
                        id
                        username
                        email
                    }
                }
            }
            '''
        )
        print (response)

        content = json.loads(response.content)
        self.assertResponseNoErrors(response)
        print (content)
        
        assert content == {
            &quot;data&quot;: {
                &quot;createUser&quot;: {
                    &quot;user&quot;: {
                        &quot;id&quot;: &quot;1&quot;,
                        &quot;username&quot;: &quot;testuser&quot;,
                        &quot;email&quot;: &quot;testemail@testserver.com&quot;
                    }
                }
            }
        }

    def test03_mutation_addUser(self):
        print(&quot;Running test03_mutation_addUser&quot;)
        response = self.query(
            '''
            mutation {
                createUser (username: &quot;testuser2&quot;, email: &quot;testemail2@testserver.com&quot;, password: &quot;123456&quot;) {
                    user {
                        id
                        username
                        email
                    }
                }
            }
            '''
        )
        print (response)

        content = json.loads(response.content)
        self.assertResponseNoErrors(response)
        print (content)
        
        assert content == {
            &quot;data&quot;: {
                &quot;createUser&quot;: {
                    &quot;user&quot;: {
                        &quot;id&quot;: &quot;2&quot;,
                        &quot;username&quot;: &quot;testuser2&quot;,
                        &quot;email&quot;: &quot;testemail2@testserver.com&quot;
                    }
                }
            }
        }

    def test04_query_users(self):
        print(&quot;Running test04_query_users&quot;)
        response = self.query(
            '''
            query {
                users {
                    id
                    username
                    email
                }
            }
            '''
        )
        print (response)
        content = json.loads(response.content)
        self.assertResponseNoErrors(response)
        print (content)
        assert content == {
            &quot;data&quot;: {
                &quot;users&quot;: []
            }
        }
</code></pre>
<p>The test output is as follows:</p>
<pre><code>Using existing test database for alias 'default'...
System check identified no issues (0 silenced).
Running test01_query_users
&lt;HttpResponse status_code=200, &quot;application/json&quot;&gt;
{'data': {'users': []}}
.Running test02_mutation_addUser
&lt;HttpResponse status_code=200, &quot;application/json&quot;&gt;
{'data': {'createUser': {'user': {'id': '1', 'username': 'testuser', 'email': 'testemail@testserver.com'}}}}
.Running test03_mutation_addUser
&lt;HttpResponse status_code=200, &quot;application/json&quot;&gt;
{'data': {'createUser': {'user': {'id': '1', 'username': 'testuser2', 'email': 'testemail2@testserver.com'}}}}
FRunning test04_query_users
&lt;HttpResponse status_code=200, &quot;application/json&quot;&gt;
{'data': {'users': []}}
.
======================================================================
FAIL: test03_mutation_addUser (polls.tests.tests.APITestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File &quot;C:\Users\myuser\Projects\Python\virtual-environments\myproject\tests\tests.py&quot;, line 89, in test03_mutation_addUser
    assert content == {
AssertionError

----------------------------------------------------------------------
Ran 4 tests in 0.980s

FAILED (failures=1)
</code></pre>
<p>It runs first test just ok, then the 2nd one ok, adding a user. When it runs the 3rd it returns a different user with the same ID of the previous one, as if the previous mutation's results was wiped out from the DB, failing because the expected ID (2) is not met. When the 4th test is executed it shows the DB has 0 users. The expected result should be a DB with two different users.
Why it seems to wipe the DB after each test? What am I doing wrong? When I pass --keepdb it doesn't store the DB anywhere.</p>
",https://stackoverflow.com/questions/68145583/django-graphene-seems-to-clean-database-between-individual-tests-in-a-test-run,"['python', 'django', 'sqlite', 'unit-testing', 'graphene-django']",209,False,0,1
Entity Framework boolean Concurrency Token unexpected behaviour,"<p>I'm trying to implement an EF transaction which inside has to manage an entity's <code>ConcurrencyToken</code> that is a <code>bool</code> property.</p>
<p>The idea is that each <code>IdChain</code> associated to a <code>Registry</code> entity, <strong>can be used only once</strong>. So the <code>InUse</code> <code>bool</code> property of <code>MovementsChain</code> entity has to be set to <code>true</code> only from the first concurrent call that comes. All the others, should fail when trying to set the <code>InUse</code> property to <code>true</code> and then call <code>Context.SaveChangesAsync()</code>, so I expect a <code>DbUpdateConcurrencyException</code> to be thrown.</p>
<h4 id=""entity-and-its-configuration-urce"">Entity and its configuration</h4>
<pre><code>public partial class MovementsChain
{
    public Guid IdChain { get; set; }
    public int IdRegistry { get; set; }
    public DateTime Creation { get; set; }
    public bool InUse { get; set; }
}

public void Configure(EntityTypeBuilder&lt;MovementsChain&gt; entity)
{
    entity.HasKey(e =&gt; e.IdChain);
    
    entity.Property(e =&gt; e.IdChain).HasDefaultValueSql(&quot;(newid())&quot;);

    entity.Property(e =&gt; e.Creation).HasDefaultValueSql(&quot;(getutcdate())&quot;);
    
    entity.Property(e =&gt; e.InUse)
        .IsConcurrencyToken();
}
</code></pre>
<h4 id=""transaction-ilj4"">Transaction</h4>
<pre><code>// I tried to set different isolation levels for the transaction, like: ReadCommitted and ReadUncommitted, but with no changes in the final behaviour
using (var transaction = await Context.Database.BeginTransactionAsync())
{
    try
    {    
        // Get and lock the IdChain
        var register = await Context.Registers.FirstOrDefaultAsync(/* Predicate... */);

        if (register == null)
            return new TransactionResult(Error.InvalidRegisterIdentifier);

        var movementChain = await Context.MovementsChain
            .OrderByDescending(e =&gt; e.Creation)
            .FirstOrDefaultAsync(e =&gt; e.IdRegister == register.IdRegister);

        if (movementChain == null)
            return new TransactionResult(Error.IdChainNotFound);

        if (movementChain.InUse)
            return new TransactionResult(Error.IdChainAlreadyInUse);

        // The &quot;core&quot; part of the transaction where the concurrency is managed...
        try
        {
            movementChain.InUse = true;
            await Context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException ex)
        {
            // During the tests I never get there...
            return new TransactionResult(Error.IdChainAlreadyInUse); // The specified IdChain is being used by another operation. Cannot proceed.
        }

        // Validation for the client given Guid
        if (request.IdChain == Guid.Empty)
            return new TransactionResult(Error.IdChainNotSpecified);

        if (movementChain.IdChain != request.IdChain)
            return new TransactionResult(Error.InvalidIdChain); // The specified IdChain is not the last one generated by the system. Cannot proceed.
            
        /* The transaction proceeds doing some other stuff...
         * ...
         */
                
        /* Now that the transaction is almost completed and everything has gone well so far,
         * I generate the new Idchain, valid for the next operation
         * and set the current IdChain back to InUse = false.
         */
        
        // Create the new IdChain
        EntityFramework.Models.MovementsChain newMovementChain = new EntityFramework.Models.MovementsChain
        {
            IdRegister = register.IdRegister,
        };

        await Context.MovementsChain.AddAsync(newMovementChain);
                    
        // Unlock the current used IdChain
        movementChain.InUse = false;

        // Save and commit
        await Context.SaveChangesAsync();
        await transaction.CommitAsync();

        return new TransactionResult(Ok);
    }
    catch (Exception ex)
    {
        await transaction.RollbackAsync();
        throw;
    }
}
</code></pre>
<h4 id=""unit-testing-931c"">Unit testing</h4>
<pre><code>[TestMethod]
public async Task CreateMovements_WithSameIdChainInParallel_ReturnsOkJustOne()
{
    int maxConcurrentRequests = 20;
    string idChain = GetLastIdChain(50).ToString();
    int counterStart = 343;
    string payload = @&quot;[
        {{
            &quot;&quot;counter&quot;&quot;: {0},
            &quot;&quot;somOtherData&quot;&quot;: &quot;&quot;data&quot;&quot;
        }}
    ]&quot;;

    var contents = new List&lt;StringContent&gt;();

    for (int i = 0; i &lt; maxConcurrentRequests; i++)
    {
        var content = new StringContent(string.Format(payload, counterStart), Encoding.UTF8, &quot;application/json&quot;);
        content.Headers.Add(&quot;X-MyApp-IdChain&quot;, idChain);
        contents.Add(content);
        counterStart++;
    }

    var responses = new ConcurrentBag&lt;HttpResponseMessage&gt;();
    
    // Multiple Clients using Tasks
    var tasks = contents.Select(async content =&gt;
    {
        using (var client = await CreateClientAsync(content))
        {
            var response = await client.PostAsync(api, content);
            responses.Add(response);
            string responseString = await response.Content.ReadAsStringAsync();
        }
    }).ToList();
    await Task.WhenAll(tasks);

    Assert.IsTrue(responses.Count(r =&gt; r.IsSuccessStatusCode) == 1);
}
</code></pre>
<p>This test always fails because I usually get 6-7 requests out of the 20, that &quot;correctly&quot; complete with HTTP 200 OK status code. So the same IdChain is used multiple times.</p>
<p>Instead, the correct behaviour should be that <strong>just ONE (the first that is able to lock the IdChain) completes with 200 OK and all the others must fail</strong>.</p>
",https://stackoverflow.com/questions/68359293/entity-framework-boolean-concurrency-token-unexpected-behaviour,"['c#', 'concurrency', 'transactions', 'entity-framework-core', '.net-5']",263,False,0,1
node_modules&#39; is not recognized as an internal or external command,"<p>I'm trying to run npm test on an existing project.I've been getting this error. &quot;node-modules is not recognized as an internal or external command, operable command or batch file&quot;. (working on windows if it's relevant)</p>
<p>I've installed babel, upgraded npm, deleted node-modules installed it again, I tried adding ./ and node in my script file but it gives me an even weirder error.</p>
<p>Here is the script file that gives me this error.
script file:</p>
<p><a href=""https://i.stack.imgur.com/FQZxH.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/FQZxH.png"" alt=""enter image description here"" /></a></p>
<p>If i edit my file with node (with or without the ./)
edited script file:</p>
<p><a href=""https://i.stack.imgur.com/iQmFe.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/iQmFe.png"" alt=""enter image description here"" /></a></p>
<p>I get this error:</p>
<p><a href=""https://i.stack.imgur.com/1DYrB.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/1DYrB.png"" alt=""enter image description here"" /></a></p>
<p>I have no idea what's going on (complete beginner, have to work on unit testing for school).
Can someone help ?
Thanks.. (ps : first question here I have no idea if these informations are enough, please tell me if you need something else).</p>
",https://stackoverflow.com/questions/69992081/node-modules-is-not-recognized-as-an-internal-or-external-command,"['javascript', 'unit-testing', 'jasmine', 'gulp', 'node-modules']",1195,False,0,0
Unit Testing Http Calls in Angular,"<p>I am using Angular 9+.</p>
<p>While <code>unit testing</code> services that implement <strong><code>httpClient</code></strong> and make http requests, I referred this <a href=""https://angular.io/guide/http#testing-http-requests"" rel=""nofollow noreferrer"">documentation</a> by Angular Team. I followed the process and got success in the unit tests also.
Following is the code (taken from the doc):</p>
<pre><code>it('can test HttpClient.get', () =&gt; {
  const testData: Data = {name: 'Test Data'};

  // Make an HTTP GET request
  httpClient.get&lt;Data&gt;(testUrl)
    .subscribe(data =&gt;
      // When observable resolves, result should match test data
      expect(data).toEqual(testData)
    );

  // The following `expectOne()` will match the request's URL.
  // If no requests or multiple requests matched that URL
  // `expectOne()` would throw.
  const req = httpTestingController.expectOne('/data');

  // Assert that the request is a GET.
  expect(req.request.method).toEqual('GET');

  // Respond with mock data, causing Observable to resolve.
  // Subscribe callback asserts that correct data was returned.
  req.flush(testData);

  // Finally, assert that there are no outstanding requests.
  httpTestingController.verify();
});
</code></pre>
<p>My question is:</p>
<ul>
<li><p>Since <code>http calls</code> are <code>asynchronous</code>, why is not fakeAsync() written in any of the tests provided in the docs? Like normally when unit testing <strong><code>asynchronous methods</code></strong> ( <code>setTimeout() , setInterval()</code> ), the docs provided in angular shows that we need a fake zone.js which appends all the async requests to an array and then we use flushMicrotasks() or tick() to further facilitate the calls.</p>
</li>
<li><p>How is the control flow happening when <code>req.flush()</code> is called? We have made a call to the function <code>httpClient.get&lt;Data&gt;(testUrl)</code> which subscribes to the observable and and <strong>flush</strong> is used to just resolve it. So the entire flow in the test spec is happening async / sync?</p>
</li>
</ul>
",https://stackoverflow.com/questions/66208828/unit-testing-http-calls-in-angular,"['angular', 'unit-testing', 'jasmine', 'httprequest']",2211,True,0,1
mock method with exact arguments in python,"<p>In Python 3+</p>
<pre><code>def some_method():
   href = browser.find_element_by_css_selector('div').get_attribute('href')
   title = browser.find_element_by_css_selector('div &gt; a').get_attribute('title')
   text = browser.find_element_by_css_selector('div &gt; p &gt; h2').get_attribute('title')
</code></pre>
<p>This is some code snippet from code and i was performing unit testing on it, but could not get exact result as expected.
For above code I need to <strong>mock only <code>browser.find_element_by_css_selector('div').get_attribute('href')</code></strong> so that I can pass my custom link instead of getting this from browser.</p>
<p>tried till now:</p>
<pre><code>@patch.object(WebElement,'get_attribute',return_value = 'some_url')
</code></pre>
<p>If I patch this <code>get_attribute</code> method ,then this get mocked for all places which I do not want to.</p>
<pre><code> when(WebElement).get_attribute('href').thenReturn('some-url')
 expect(WebElement,atleast=1).get_attribute(eq(&quot;href&quot;)).thenReturn('some-url')
</code></pre>
<p>And if i mock this using mockito , then I get errors on next lines. I tried using both <code>when and expect</code> but nothing worked</p>
<pre><code>Exception caught:
Called but not expected: get_attribute('title')
    Stubbed invocations are:
         get_attribute('href')
         get_attribute(&lt;Eq: href&gt;)
</code></pre>
<p>How can we return the mocked value with multiple calls with exact arguments? For ex: if paramater being passed in <code>css_selector</code> and <code>get_attributes</code> are <code>div</code> and <code>href</code> then return some fake Url. If values are <code>p &gt; div</code> and <code>title</code> then return another fake value and leave as it is for rest of the calls</p>
",https://stackoverflow.com/questions/66830657/mock-method-with-exact-arguments-in-python,"['unit-testing', 'mocking', 'pytest', 'python-unittest', 'python-mock']",369,False,0,2
Flutter how to mock function response when it is called in tested function,"<p>I am trying to test some api call function:</p>
<pre><code>  Future&lt;SomeType&gt; getType(int id) async {
    String token = await retrieveToken();
    String api = await getApiEndpoint();
    final response = await client.get(&quot;$api/something/$id&quot;, headers: { &quot;Authorization&quot;: &quot;Bearer $token&quot;});
    if (response.statusCode == 200) {
      String body = utf8.decode(response.bodyBytes);
      return SomeType.fromJson(json.decode(body));
    } else {
      throw Exception('Failed to load some types from API');
    }
  }
</code></pre>
<p>The two functions:</p>
<pre><code>retrieveToken();
getApiEndpoint();
</code></pre>
<p>that are called inside are not members of the same class as getType() function. They also contain
inside them instances of FlutterSecureStorage().</p>
<p>I don't need to test this function, I just want to mock their responses in the test of getType function.</p>
<p>I've created following test example:</p>
<pre><code>class MockedApiEndpoint extends Mock implements ApiEndpoint {}
void main() {
    WidgetsFlutterBinding.ensureInitialized();
    test('returns SomeType', () async {
      final typesRepository = TypesRepository();
      final mockedApiEndpoint = MockedApiEndpoint();

      when(mockedApiEndpoint.getApiEndpoint()).thenAnswer((_) async =&gt; Future.value(&quot;some_url.com&quot;));
      when(mockedApiEndpoint.retrieveToken()).thenAnswer((_) async =&gt; Future.value(&quot;some_token&quot;));

      typesRepository.client = MockClient( (request) async {
        final mapJson = {'id' : 123};
        return Response(json.encode(mapJson), 200);
      });

      final type =  await typesRepository.getType(123);
      expect(type.id, 123);
    });
}

</code></pre>
<p>I was able to succesfully Mock the client reposne, I am also trying to mock responses of those two functions, but I am constantly receiveing following error:</p>
<p><strong>MissingPluginException(No implementation found for method read on channel plugins.it_nomads.com/flutter_secure_storage)</strong></p>
<p>I would be very greatful for any hints how to approach this topic and what I am doing wrong with this one. I am new to unit testing in Flutter, I've tried to find any similar problem to mine on the web but unfortunatelly failed.</p>
",https://stackoverflow.com/questions/67150548/flutter-how-to-mock-function-response-when-it-is-called-in-tested-function,"['flutter', 'unit-testing', 'dart', 'testing', 'mocking']",1150,False,0,1
How to use sinon to replace the same method with two different return values?,"<p>A method that I am unit testing calls the same helper method with different parameters multiple times within the method. In order for me to test my method, I want to use sinon's replace function to replace the return value of this helper method with my mock data, but I need each time I call that helper method to return different mock data. How can I do this?</p>
<p>As an example:</p>
<pre><code>const obj = {
  foo(num) {
    return 5 + num;
  },
  methodToTest() {
    return foo(1) + foo(2);
  },
};
</code></pre>
<p>I want to test whether methodToTest() will work properly if foo returns 6 when it is called with parameter value 1, and foo returns 7 when called with parameter value 2.</p>
<p>I guess what I'm looking for is a way to replace foo's return value depending on the parameter passed in, something like:</p>
<pre><code>   sinon.replace(obj, 'foo(1)', sinon.fake.returns(6));
   sinon.replace(obj, 'foo(2)', sinon.fake.returns(7));

</code></pre>
<p>Any idea how I could do this? Would be very much appreciated.</p>
",https://stackoverflow.com/questions/68463040/how-to-use-sinon-to-replace-the-same-method-with-two-different-return-values,"['javascript', 'typescript', 'sinon']",993,True,-1,1
Testing functions returning option&lt;T&gt;,"<p>Consider unit-testing a module defining <a href=""https://fsharpforfunandprofit.com/posts/designing-with-types-more-semantic-types/"" rel=""nofollow noreferrer"">strings of constrained length</a> as a type for representing user names:</p>
<pre><code>module UserName

type T = UserName of string
let create (userName : string) =
    if userName.Length &gt;= 6 &amp;&amp; userName.Length &lt;= 16 
    then Some (UserName userName)
    else None
let apply f (UserName userName) = f userName
let value userName = apply id userName
</code></pre>
<p>A unit test to ensure that the function returns <code>None</code> for an invalid input looks simple:</p>
<pre><code>[&lt;Fact&gt;]
let ``UserName must have at least six characters`` () =
    UserName.create &quot;aaa&quot; |&gt; should equal None
</code></pre>
<p>However, a unit test for the case when the function returns <code>Some</code> appears to require an extra line for completeness of the <code>match</code> expression:</p>
<pre><code>[&lt;Fact&gt;]
let ``Valid UserName`` () =
    match UserName.create &quot;validname&quot; with
    | Some result -&gt;
        UserName.value result |&gt; should equal &quot;validname&quot;
    | None -&gt; Assert.True(false)
</code></pre>
<p>This does not look right to me, because my tests must define code for testing the &quot;unhappy&quot; path that must yield a failure anyway.</p>
<p>I wish I could write this instead</p>
<pre><code>[&lt;Fact&gt;]
let ``Valid UserName`` () =
    UserName.create &quot;validname&quot; |&gt; should equal (Some (UserName &quot;validname&quot;))
</code></pre>
<p>but it does not compile (The value or constructor 'UserName' is not defined).</p>
<p>Is there a way to write a unit test of a function returning <code>option&lt;T&gt;</code> that does not require an explicit check of the &quot;unhappy&quot; path (e.g. <code>| None -&gt; Assert.True(false)</code>)? I am open to adding more types and/or functions to the <code>UserName</code> module to make it more testable.</p>
",https://stackoverflow.com/questions/70519732/testing-functions-returning-optiont,"['unit-testing', 'f#', 'fsunit']",67,True,0,1
NestJS Unit Testing for Controller: Mocking the Delete from Service Not Working,"<p>I am currently unit testing my NestJS Service. My entity is called 'User' and I established a basic Service that allows me to interact with a MS SQL server, with GET and POST endpoints established in my Controller.</p>
<p>I have a <code>delete</code> method in my Controller file that basically just calls the <code>delete</code> method from my Service:</p>
<pre><code>@Injectable()
export class ServiceName {
  constructor(@InjectEntityManager() private manager: EntityManager) {}


  async delete(id: number): Promise&lt;any&gt; {
    return await this.manager.delete(User, id);
  }
// some other functions 

</code></pre>
<p>To test the <code>delete</code> method of my Controller, I mock the same method from the Service. However, when I defined a clear mock return value for the delete method from the service, this mocked return value does not match the return value from the delete method from the Controller, although they should be the same.</p>
<p>Here are my configurations in my spec.ts file:</p>
<pre><code>    const mockService = {
        delete: jest.fn(),
    };

    beforeEach(async () =&gt; { 
        const module: TestingModule = await Test.createTestingModule({
            controllers: [ControllerName],
            providers: [ServiceName],
        })
            .overrideProvider(ServiceName)
            .useValue(mockService) 
            .compile();

        service = module.get&lt;ServiceName&gt;(ServiceName);
        controller = module.get&lt;ControllerName&gt;(ControllerName);
    });
</code></pre>
<p>Here's the test case in my spec.ts file:</p>
<pre><code>        it('testing delete', async () =&gt; {
            mockService.delete.mockReturnValue(5);
            expect(controller.delete(5)).toEqual(5);
        }) 
</code></pre>
<p>The above test case fails, and below is shown the error message:</p>
<pre><code>    expect(received).toEqual(expected) // deep equality

    Expected: 5
    Received: {}

      122 |         it('testing delete', async () =&gt; {
      123 |             mockService.delete.mockReturnValue(5);
    &gt; 124 |             expect(controller.delete(5)).toEqual(5);
          |                                          ^
      125 |         })
      126 |     });
      127 | });
</code></pre>
<p>Any help is greatly appreciated!</p>
",https://stackoverflow.com/questions/67524766/nestjs-unit-testing-for-controller-mocking-the-delete-from-service-not-working,"['typescript', 'unit-testing', 'nestjs']",3161,True,0,1
Global Reliance Making Unit Testing Impossible,"<p>Background:
I am a hobbyist Python coder whose first and only project is a text-based Adventure Game <strong>Engine</strong> (<a href=""https://github.com/zig13/scenzig"" rel=""nofollow noreferrer"">https://github.com/zig13/scenzig</a>).
An Adventure Game is a common first project but I realised I didn't have the creativity to write an adventure so decided instead to write a framework so someone else could do the adventure bit.
It started out as a monolithic script with no functions - at one point 712 lines long - but as I have learnt Python it has been repeatedly rewritten.</p>
<p>I recently learned of the concepts of unit testing and logging and I think they would be really helpful to me going forward but I have hit a snag.
The majority of my functions need access to the Adventure files and/or Character file to function.
These are accessed as a dictionary (thanks to ConfigObj) and a reference to the dictionaries is passed among the modules like this:</p>
<pre><code>def GiveAdv(a) :
    global adv
    adv = a
    efunc.GiveAdv(a)
def GiveChar(c) :
    global char
    char = c
    argsolve.GiveChar(char)
    efunc.GiveChar(c)
</code></pre>
<p>i.e. After importing another module, a module passes on it's reference to the adventure files and character files. Later in the same module <code>adv.f['Actions'][str(action)]</code> is used to get the information on a specific action from the Actions file for example.</p>
<p>I've never liked this but it has been <em>fine</em> until now but is a problem now because:</p>
<ol>
<li>I am trying to merge two modules rewriting much from scratch in the process and I have no way of testing as I go as everything is so inter-connected</li>
<li>Unit testing relies on a function taking arguments and producing outputs but most of mine also expect to have access to information in addition to their arguments</li>
</ol>
<p>As I see it, Logging (using the logging module) would require somehow passing a reference to the log file around and I just can't believe that people would resort to my horrible &quot;Give&quot; function solution so there must be a better way.</p>
<p>What is the Pythonic way of giving disparate modules access to the same information, class instances and loggers?</p>
",https://stackoverflow.com/questions/66339916/global-reliance-making-unit-testing-impossible,"['python', 'python-3.x', 'unit-testing', 'logging']",246,False,0,0
RIght way of writing module methods in Ruby,"<p>what is right way of writing module? is it only used to stock some peace of code to minimize the number of lines, or is it something much more important than that</p>
<p>I have used and seen ways of writing module, I am working on setting up correct way to define and standardised module. this example is kind of controller code that we use in rails</p>
<p>Way 1 :-</p>
<pre><code>module B
  extend ActiveSupport::Concern

  def process_items
    # do somthing...
    @items.pluck(:names)
  end
end


Class A
  include B
  
  def index
    @items = Item.all
    @item_names = process_items
  end
end
</code></pre>
<p>Way 2 :-</p>
<pre><code>module B
  extend ActiveSupport::Concern

  def process_items(items)
    # do somthing...
    items.pluck(:names)
  end
end


Class A
  include B
  
  def index
    @items = Item.all
    @item_names = process_items(@items)
  end
end
</code></pre>
<p>Way 1 :-</p>
<ol>
<li>When I see this independently, its not much readable as I don't know how @items appeared in this method</li>
<li>Unit testing would be hard for method as its dependent</li>
</ol>
<p>Way 2 :-</p>
<ol>
<li>Looking at method I can see input is coming we are processing it and returning it back (readablity is good)</li>
<li>Unit testing is easy to this, we wll call method pass what it needs and expect</li>
</ol>
<p>The way I see modules should be independent, self explanatory, it should be generic so that can be used in any class, kind of helpers. But other way could be dependent on where we use modules</p>
<p>We are using modules like in rails</p>
<ol>
<li>We use conccern in models, when we call module method we can use <code>self.&lt;field&gt;</code> we don't need to pass anything because instance variable is supposed to be accesssable in every instance method</li>
<li>View helpers are modules I see they put logic into it hard to understand how the variable come from may be instance variable or params, what about making it method which accept somthing and return it back</li>
<li>Concerns on controllers, like the example I have given</li>
</ol>
<p>I would like to have thoughts on this, what is best approach out of it? is it something which can be standarise or it is more situational or I don't know yet :)</p>
<p>Note: -
I was looking at this question but answer given on this question is no more valid as referenced links are not working.
<a href=""https://stackoverflow.com/questions/7399413/right-way-to-use-module"">Right Way to Use Module</a></p>
",https://stackoverflow.com/questions/67214617/right-way-of-writing-module-methods-in-ruby,"['ruby-on-rails', 'ruby']",92,True,0,1
Xunit new in memory database DBContext Class has live data,"<p>I am trying to unit test with the EF Core in-memory database like so:</p>
<pre><code>namespace ContosoTests
{
    public class TrendServiceTests
    {
       private static Microsoft.EntityFrameworkCore.DbContextOptions&lt;TestContext&gt; options = new 
       Microsoft.EntityFrameworkCore.DbContextOptionsBuilder&lt;TestContext&gt;()
                       .UseInMemoryDatabase(Guid.NewGuid().ToString())
                       .Options;

       private static TestContext _context = new TestContext(options);

       private readonly TrendService trendService = new TrendService(_context);

        private void SeedInMemoryDb()
        {
            if (!_context.TrendHistories.Any())
            {
                _context.TrendHistories.Add(new TrendHistory { IsActive = true, Quarter = E_Quarter.Q1, 
                TrendYear = 2020 });
            }

            if (!_context.Controls.Any())
            {
                _context.Controls.Add(new Control { IsActive = true});
                _context.Controls.Add(new Control { IsActive = true});
                _context.Controls.Add(new Control { IsActive = false});
            }

            _context.SaveChanges();
        }
}
</code></pre>
<p>My TestContext inherits from my live context class to avoid the error:<br>
<em>Services for database providers 'Microsoft.EntityFrameworkCore.InMemory', 'Microsoft.EntityFrameworkCore.SqlServer' have been registered in the service provider. Only a single database provider can be registered in a service provider</em></p>
<p>So my TestContext just looks like:<br></p>
<pre><code>public class TestContext : ContosoContext
    {
        public TestContext(DbContextOptions&lt;TestContext&gt; options)
        {
            
        }

        public TestContext()
        {

        }
    }
</code></pre>
<p>When I use the new instance of TestContext (_context) in my test class, all the live data for ContosoContext is there.
I was expecting it to be a new instance of the context class with no data so that I could test my DAL code with controlled data. But this is not the case.
<br><br>I am fairly new to unit testing so any help is much appreciated.</p>
<p><strong>Edit:</strong><br>
Here are the relevant parts of my contoso context class</p>
<pre><code>    public class ContosoContext: IdentityDbContext&lt;ContosoApplicationUser&gt;
    {
        public ContosoContext(DbContextOptions&lt;ContosoContext&gt; options) : base 
        (options)
        {

        }

        public ContosoContext()
        {

        }

        //all my DBSets here

        protected override void OnConfiguring(DbContextOptionsBuilder 
        optionsBuilder)
        {

            optionsBuilder.UseSqlServer(&quot;MyConnectionString&quot;);

        }
    }
</code></pre>
<p>So the issue is that my onconfiguring method handles the connection string directly??</p>
",https://stackoverflow.com/questions/66518060/xunit-new-in-memory-database-dbcontext-class-has-live-data,"['c#', 'unit-testing', 'entity-framework-core', 'blazor', 'in-memory-database']",1872,True,2,1
Visual Studio 2019 - Cannot run Python unittests - Failed to import test module:,"<p>Was successfully developing on Python with VS2019 for last several days now. So my environment seems to be properly installed and appropriate configured.</p>
<hr />
<p>So I want to use unittest for Python with Visual Studio 2019 and came along here:
<a href=""https://learn.microsoft.com/en-us/visualstudio/python/unit-testing-python-in-visual-studio"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/python/unit-testing-python-in-visual-studio</a></p>
<p>Then started with a freshly created empty project.
The test module 'test_A.py' is located in a subfolder called &quot;tests&quot;:</p>
<p><a href=""https://i.stack.imgur.com/p3lrx.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/p3lrx.jpg"" alt=""Solution Explorer"" /></a></p>
<p>It is exactly the same code from the MS Docs example (Link above):</p>
<pre><code>    import unittest

    class Test_test1(unittest.TestCase):
        def test_A(self):
            self.fail(&quot;Not implemented&quot;)

    if __name__ == '__main__':
        unittest.main()
</code></pre>
<p>In the project settings I turned on 'unittest' and set the root folder like this:</p>
<p><a href=""https://i.stack.imgur.com/rEZ7s.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/rEZ7s.jpg"" alt=""Project Settings"" /></a></p>
<p>The Test Explorer is directly showing the test class:</p>
<p><a href=""https://i.stack.imgur.com/waUbT.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/waUbT.jpg"" alt=""Test Explorer"" /></a></p>
<p>But running the tests, always this ImportError comes up, that the module cannot be found and therefore is not existing:</p>
<pre><code>Test Name:  test_A
Test FullName:  test_A::tests\test_A.py::Test_test1::test_A
Test Source:    D:\pyproject\pyproject\tests\test_A.py : line 4
Test Outcome:   Failed
Test Duration:  0:00:00

Test Name:  test_A
Test Outcome:   Failed
Result StackTrace:  3.7
Result Message: Failed to import test module: test_A
Traceback (most recent call last):
  File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\unittest\loader.py&quot;, line 154, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'test_A'
Result StandardError:   
Traceback (most recent call last):
  File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\unittest\case.py&quot;, line 59, in testPartExecutor
    yield
  File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\unittest\case.py&quot;, line 628, in run
    testMethod()
  File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\unittest\loader.py&quot;, line 34, in testFailure
    raise self._exception
ImportError: Failed to import test module: test_A
Traceback (most recent call last):
  File &quot;C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\lib\unittest\loader.py&quot;, line 154, in loadTestsFromName
    module = __import__(module_name)
ModuleNotFoundError: No module named 'test_A'
</code></pre>
<p>Why is Visual Studio in trouble, when previously detecting the test module??? Somewhat strange to me...
Thanks for any hint.</p>
",https://stackoverflow.com/questions/66504420/visual-studio-2019-cannot-run-python-unittests-failed-to-import-test-module,"['python', 'visual-studio', 'unit-testing']",1082,True,2,1
Is it possible to set event.isTrusted to true in JEST unit tests?,"<p>I am working with <strong>JavaScript</strong> events. As per the following MDN article, the event object has a flag called <code>isTrusted</code>. <a href=""https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted"" rel=""noreferrer"">https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted</a></p>
<p>I have written a code which differentiates user events (triggered as a result of an actual user action) from programmatic events (triggered as a result of <code>element.dispatchEvent(...)</code>. I cannot show the entire code but it goes something like below:</p>
<pre class=""lang-js prettyprint-override""><code>document.addEventListener('click', (event) =&gt; {
  if (event.isTrusted) {
    // ... client code follows
    // somewhere in the code I am dispatching another custom event on body element
    document.body.dispatchEvent(...);
  }
});
</code></pre>
<p>I am trying to <strong>unit test</strong> this code in <code>JEST</code> (a popular unit testing library). Unfortunately we cannot simulate real click events since it's an automated code that does it for you. The the flag <code>isTrusted</code> is always set to <code>false</code> in JEST, thereby restricting me to test the client code.</p>
<p>I cannot change the value of <code>isTrusted</code> directly since it is a read only property. I am looking for ways where I can mock the event and set the <code>isTrusted</code> flag to <code>true</code>.</p>
<hr />
<p><em>Edit:</em> Added the test code:</p>
<pre class=""lang-js prettyprint-override""><code>
describe('Event.isTrusted', () =&gt; {
  beforeAll(() =&gt; {
    document.body.dispatchEvent = jest.fn();
    const btn = document.createElement('button');
    btn.id = 'btn';
    document.body.appendChild(btn);
  });
  ...
  it('should allow user events', () =&gt; {
    const event = new MouseEvent('click', {
      bubbles: true,
      cancellable: true
    });
    document.getElementById('btn').dispatchEvent(event);
    expect(document.body.dispatchEvent).toHaveBeenCalled();
  });
});
</code></pre>
<p>Once again this is just a gist. I cannot show the client code. I hope this helps.</p>
",https://stackoverflow.com/questions/65935065/is-it-possible-to-set-event-istrusted-to-true-in-jest-unit-tests,"['javascript', 'unit-testing', 'events', 'dom-events', 'readonly']",1932,True,6,1
Tensorflow Keras URL fetch failure for Training Dataset,"<p>I'm trying to import my training dataset for my CNN (30,000 images), but there's something about this line that breaks the program.</p>
<pre><code>data_dir = tf.keras.utils.get_file(origin=dataset_url, 
                                   fname='functionidentifier', 
                                   untar=True)
</code></pre>
<p>Here's the full code block for more context:</p>
<pre><code>dataset_url = &quot;https://barisciencelab.tech/functionidentifier.tgz&quot;
data_dir = tf.keras.utils.get_file(origin = dataset_url,
                                   fname = &quot;functionidentifier&quot;,
                                   untar = True)
data_dir = pathlib.Path(data_dir)
</code></pre>
<p>It was working just last week, but suddenly broke: <a href=""https://i.stack.imgur.com/VEuTp.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VEuTp.png"" alt=""enter image description here"" /></a></p>
<p>Some things I tried:</p>
<ul>
<li>Changing extension of my training set from <code>.tar.gz</code> to <code>.zip</code> and <code>.tar.tar</code> and <code>.tgz</code>.</li>
<li>Unit testing (all other parts of code are fine; they're just importing stuff anyway)</li>
<li>Exact same code in a new Google Colab Notebook and Jupyter Notebook. Neither worked.</li>
<li>Checked the <a href=""https://www.tensorflow.org/tutorials/load_data/images"" rel=""nofollow noreferrer"">documentation</a>. My code is <strong>verbatim</strong> the same! The <em>only</em> thing that's different is <em>literally</em> my URL. That's it.</li>
</ul>
<p>Nothing worked. And no, I can't manually download the whole training set and do this locally (big-time hassle).</p>
<h3>MWE (<a href=""https://colab.research.google.com/drive/1c25FpjrmoBglMta5rW-CgYkM6UfZiSss?usp=sharing"" rel=""nofollow noreferrer""><strong>Full Code</strong></a>)</h3>
<pre><code>pip install tensorflow
pip install numpy
pip install matplotlib
!git clone https://github.com/Refath/SinusoidalAnalyzer.git
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPooling2D, Dropout
from tensorflow.keras import layers
from tensorflow.keras.utils import to_categorical
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
import pathlib
dataset_url = &quot;https://barisciencelab.tech/TrainingSet.tar.gz&quot;
data_dir = tf.keras.utils.get_file(origin = dataset_url, fname = &quot;TrainingSet&quot;, untar = True)
data_dir = pathlib.Path(data_dir)
</code></pre>
<p>Folks in the SO Chat valiantly tried to debug the issue as well, but to no avail. If anyone can help, that would be great.</p>
",https://stackoverflow.com/questions/69092893/tensorflow-keras-url-fetch-failure-for-training-dataset,"['python', 'tensorflow']",1285,True,1,3
Problems setting up mock services and calling it with jasmine/ karma and Angular,"<p>I have a method which calls another method. Within that method I subscribe to a service, if there is a match it then uses Angular router service to navigate. Here is a <a href=""https://stackblitz.com/edit/angular-queryparam-1fztjc?file=src%2Fapp%2Fsearch%2Fsearch.component.spec.ts"" rel=""nofollow noreferrer"">stackBlitz example</a></p>
<pre><code>  goToMain(): void {
    this.viewFunc(this.queryString);
  }

  viewFunc(queryString): void {
    this.reportService.getAnotherReport(queryString).subscribe(x =&gt; {
      if (x.label.toLowerCase() === &quot;accept &amp; view&quot;) {
        const url = &quot;main&quot;;
        this.router.navigate([url], {
          queryParams: { queryString: queryString }
        });
      }
    });
  }
</code></pre>
<p>I successfully created a test in my spec file to test that the <code>viewFunc</code> method is called. I have then tried to mock the subscription from the service being called in the next method. Ive tried to test for two things A. the subscription is called B. if a match then navigates.</p>
<p>I'm getting the error &quot;<strong>Expected spy getAnotherReport to have been called.</strong>&quot;</p>
<pre><code>  it(&quot;should call service&quot;, () =&gt; {
    const queryString = &quot;10987&quot;;
    const testee = component;
    expect(testee).toBeTruthy();

    const routerSpy = { navigate: jasmine.createSpy(&quot;navigate&quot;) };
    const mySpy = jasmine.createSpy(&quot;getAnotherReport&quot;).and.callThrough();

    testee.viewFunc(queryString);

    expect(mySpy).toHaveBeenCalled();
    expect(routerSpy.navigate).toHaveBeenCalledWith([&quot;/main&quot;], {
      queryParams: { queryString: queryString }
    });
  });
</code></pre>
<p>Here is a <a href=""https://stackblitz.com/edit/angular-queryparam-1fztjc?file=src%2Fapp%2Fsearch%2Fsearch.component.spec.ts"" rel=""nofollow noreferrer"">stackBlitz example</a></p>
<p>I cant quite get an understanding of jasmine yet and unit testing, I suspect I have incorrectly setup the describe / testbed for my spec file. Therefore if somebody can help and take a look at the <a href=""https://stackblitz.com/edit/angular-queryparam-1fztjc?file=src%2Fapp%2Fsearch%2Fsearch.component.spec.ts"" rel=""nofollow noreferrer"">stackBlitz example</a> I would be most appreciative.</p>
",https://stackoverflow.com/questions/66301459/problems-setting-up-mock-services-and-calling-it-with-jasmine-karma-and-angular,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",53,True,1,1
Jest manual mock sub modules with top level export,"<p>when using React and Jest I encountered a use case for manual mocks, that I do not know how to overcome. Given the following structure:</p>
<pre><code>.
├── code.test.tsx
└── module
    ├── __mocks__
    ├── index.tsx
    ├── module.tsx
    └── submodule
        ├── __mocks__
        └── index.tsx
</code></pre>
<p>I am writing tests inside <code>code.test.tsx</code>. The components <code>module</code> and <code>submodule</code> do contain manual file mocks that returns dummy code for unit testing purposes.</p>
<p><code>module/index.tsx</code> acts as an export point for the component itself and submodule:</p>
<pre><code>export * from './submodule'
export { module } from './module.tsx'
</code></pre>
<p>This way the imports inside <code>code.tsx</code> are more organized:</p>
<pre><code>import { module, submodule } from './module'
</code></pre>
<p>Finally inside <code>code.test.tsx</code> I mock the import of <code>module</code> by calling <code>jest.mock('./module')</code>. The desired behavior should be that <code>module</code> and <code>submodule</code> are getting mocked since both components contain a <code>__mocks__</code> folder.</p>
<p>Since <code>module/__mocks__</code> exports a mock that only defines itself, the underlying components are undefined. In this case I would normally adjust the imports to point to the components directly. But since the imports provide advanced readability I want to recursively mock the subfolders where ever there is a <code>__mocks__</code> directory. Is it possible to achieve it?</p>
",https://stackoverflow.com/questions/66889514/jest-manual-mock-sub-modules-with-top-level-export,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'mocking']",1198,True,1,1
Local Spark config,"<p>I have created a local spark environment in docker. I intend to use this as part of a CICD pipeline for unit testing code executed in the spark environment. I have two scripts which I want to use: 1 will create a set of persistent spark databases and tables and the other will read those tables. Even though the tables should be persistent, they only persist in that specific spark session. If I create a new spark session, I cannot access the tables, even though it is visible in the file system. Code examples are below:</p>
<h1>Create db and table</h1>
<p>Create_script.py</p>
<pre><code>from pyspark.sql import SparkSession
def main():
    spark = SparkSession.builder.appName('Example').getOrCreate()
    columns = [&quot;language&quot;, &quot;users_count&quot;]
    data = [(&quot;Java&quot;, &quot;20000&quot;), (&quot;Python&quot;, &quot;100000&quot;), (&quot;Scala&quot;, &quot;3000&quot;)]
    rdd = spark.sparkContext.parallelize(data)
    df = rdd.toDF(columns)
    spark.sql(&quot;create database if not exists schema1&quot;)
    df.write.mode(&quot;ignore&quot;).saveAsTable('schema1.table1')
</code></pre>
<h1>Load Data</h1>
<p>load_data.py</p>
<pre><code>from pyspark.sql import SparkSession
spark = SparkSession.builder.appName('example').getOrCreate()
df = spark.sql(&quot;select * from schema1.table1&quot;)
</code></pre>
<p>I know there is a problem as when I run this command: print(spark.catalog.listDatabases()) It can only find database default. But if I import Create_script.py then it will find schema1 db.</p>
<p>How do I make persistent tables across all spark sessions?</p>
<p><a href=""https://i.stack.imgur.com/fm1ea.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fm1ea.png"" alt=""ls from filesystem"" /></a></p>
",https://stackoverflow.com/questions/70065128/local-spark-config,"['python', 'apache-spark', 'pyspark', 'apache-spark-sql']",420,True,1,1
Mock asserting into callbacks,"<p>I'm having the following problem when unit testing (working code <a href=""https://play.golang.org/p/ZTF5ZoAV9sY"" rel=""nofollow noreferrer"">here</a>]</p>
<p>Assuming we have this:</p>
<pre><code>var (
    userDomain UserInterface
    Tx         TxInterface
)

type UserInterface interface {
    Get() (*User, error)
}

type TxInterface interface {
    Exec(fn func() error) error
}

type User struct {
    ID int64
}

func (u *User) Get() (*User, error) {
    return &amp;User{
        ID: 1,
    }, nil
}

type WithTx struct{}

func (t *WithTx) Exec(fn func() error) error {
    /* more logic here */
    return fn()
}

</code></pre>
<p>Assuming we have the following 2 services:</p>
<pre><code>func GetByID() (*User, error) {
    user, err := userDomain.Get()
    return user, err

}

func GetByIDWithTx() (*User, error) {
    u := &amp;User{}
    /** Notice this implementation **/
    if err := Tx.Exec(func() error {
        user, _ := userDomain.Get()
        u = user
        return nil

    }); err != nil {
        log.Print(&quot;Tx err&quot;, err)
    }

    return u, nil
}

</code></pre>
<p>They are the same but once goes directly to the Get method, the other one runs into a callback fn. So far so go, both works like a charm. Again code is <a href=""https://play.golang.org/p/ZTF5ZoAV9sY"" rel=""nofollow noreferrer"">here</a></p>
<p>I'm trying to mock the userDomain and Tx for unit tests, so my mocks look like this:</p>
<pre><code>var (
    getUserFromMock func() (*User, error)
    getFromMock     func() error
)

type userMock struct{}

func (u *userMock) Get() (*User, error) {
    return getUserFromMock()
}

type txMock struct{}

func (t *txMock) Exec(fn func() error) error {
    return getFromMock()
}

</code></pre>
<p>When testing <code>GetByID</code> I have no problem whatsoever.</p>
<pre><code>func TestGetByID(t *testing.T) {
    userDomain = &amp;userMock{}
    Tx = &amp;txMock{}

    getUserFromMock = func() (*User, error) {
        return &amp;User{ID: 3}, nil
    }

    user, err := GetByID()

    if user.ID != 3 {
        t.Fatalf(&quot;error&quot;)
    }

    if err != nil {
        t.Fatalf(&quot;error&quot;)
    }
}

</code></pre>
<p>However, When I try to testing <code>GetByIDWithTx</code>, I cannot assert the mock values:</p>
<pre><code>func TestGetByIDWithTx(t *testing.T) {
    userDomain = &amp;userMock{}
    Tx = &amp;txMock{}

    getUserFromMock = func() (*User, error) {
        return &amp;User{ID: 4}, nil
    }
    /**** Mocking callback response ****/
    getFromMock = func() error {
        return nil
    }

    user, err := GetByIDWithTx()

    if user.ID != 4 {
        t.Fatalf(&quot;error&quot;) /** It fails here **/
    }

    if err != nil {
        t.Fatalf(&quot;error&quot;)
    }
}

</code></pre>
<p>I assume, at the moment I'm trying to assert the callback is still running in another routine but I'm just speculating, I don't have any idea what is going on here. I rather not use any library for a spy, I just want to understand how to solve this. Thoughts?</p>
<p><a href=""https://play.golang.org/p/ZTF5ZoAV9sY"" rel=""nofollow noreferrer"">Go PlayGround HERE</a></p>
",https://stackoverflow.com/questions/65796815/mock-asserting-into-callbacks,"['unit-testing', 'go']",51,True,0,1
Make long header files compile once?,"<p>Alright so I'm using the &quot;Catch2&quot; framework for C++ Unit Testing and in my &quot;testMain.cpp&quot; (Doesn't matter) I include the single header version of it <code>#include &quot;Catch.hpp&quot;</code>.</p>
<p>The problem is every time I write just a small test, I have to compile the program in order to see the outputs again. But the single header is something like 70000 lines and it takes FOREVER.</p>
<p>I understand that with source files you can simply compile them into object files and after that link them. So if you are using the same source file for just linking there is no really a need to recompile it over again.</p>
<p>So the point of this question is, Is it possible to somehow compile the <strong>Catch.hpp</strong> file and just use it as a link after words? Or in order to slow it down do I have to get the multi-header version of the framework?</p>
<p>Thanks in Advance!</p>
",https://stackoverflow.com/questions/69001979/make-long-header-files-compile-once,"['g++', 'catch2']",56,True,0,1
What should be the best approach to test iOS SDK public functions with number of real devices and iOS version?,"<p>I am looking into the approaches for testing the iOS SDK public functions without explicitly developing an dedicated app to test the SDK public function.</p>
<p><strong>Approach which did not worked:</strong> We can develop an app and include button's and on clicking that button- SDK public function can be called and verified but cons of this approach is more development time and maintenance of the test App.</p>
<p><strong>Unit Testing Approach but looks it wont work:</strong> We can write unit test but it wont cover a full flow scenario Functionality hence we can not take this approach also If we write integrated test then we can not run on real devices.</p>
<p><strong>Can we somehow test the iOS SDK public functions using some white-box technique and can also catch the environmental (iOS versions/devices) issues. I want to build a complete automation suite on top of it.</strong></p>
<p>Please share your thought on this.</p>
",https://stackoverflow.com/questions/67204864/what-should-be-the-best-approach-to-test-ios-sdk-public-functions-with-number-of,"['ios', 'swift', 'sdk', 'facebook-ios-sdk', 'xctest']",137,False,0,0
What should be the best approach to test iOS SDK public functions with number of real devices and iOS version?,"<p>I am looking into the approaches for testing the iOS SDK public functions without explicitly developing an dedicated app to test the SDK public function.</p>
<p><strong>Approach which did not worked:</strong> We can develop an app and include button's and on clicking that button- SDK public function can be called and verified but cons of this approach is more development time and maintenance of the test App.</p>
<p><strong>Unit Testing Approach but looks it wont work:</strong> We can write unit test but it wont cover a full flow scenario Functionality hence we can not take this approach also If we write integrated test then we can not run on real devices.</p>
<p><strong>Can we somehow test the iOS SDK public functions using some white-box technique and can also catch the environmental (iOS versions/devices) issues. I want to build a complete automation suite on top of it.</strong></p>
<p>Please share your thought on this.</p>
",https://stackoverflow.com/questions/67204864/what-should-be-the-best-approach-to-test-ios-sdk-public-functions-with-number-of,"['ios', 'swift', 'sdk', 'facebook-ios-sdk', 'xctest']",137,False,0,0
Mock asserting into callbacks,"<p>I'm having the following problem when unit testing (working code <a href=""https://play.golang.org/p/ZTF5ZoAV9sY"" rel=""nofollow noreferrer"">here</a>]</p>
<p>Assuming we have this:</p>
<pre><code>var (
    userDomain UserInterface
    Tx         TxInterface
)

type UserInterface interface {
    Get() (*User, error)
}

type TxInterface interface {
    Exec(fn func() error) error
}

type User struct {
    ID int64
}

func (u *User) Get() (*User, error) {
    return &amp;User{
        ID: 1,
    }, nil
}

type WithTx struct{}

func (t *WithTx) Exec(fn func() error) error {
    /* more logic here */
    return fn()
}

</code></pre>
<p>Assuming we have the following 2 services:</p>
<pre><code>func GetByID() (*User, error) {
    user, err := userDomain.Get()
    return user, err

}

func GetByIDWithTx() (*User, error) {
    u := &amp;User{}
    /** Notice this implementation **/
    if err := Tx.Exec(func() error {
        user, _ := userDomain.Get()
        u = user
        return nil

    }); err != nil {
        log.Print(&quot;Tx err&quot;, err)
    }

    return u, nil
}

</code></pre>
<p>They are the same but once goes directly to the Get method, the other one runs into a callback fn. So far so go, both works like a charm. Again code is <a href=""https://play.golang.org/p/ZTF5ZoAV9sY"" rel=""nofollow noreferrer"">here</a></p>
<p>I'm trying to mock the userDomain and Tx for unit tests, so my mocks look like this:</p>
<pre><code>var (
    getUserFromMock func() (*User, error)
    getFromMock     func() error
)

type userMock struct{}

func (u *userMock) Get() (*User, error) {
    return getUserFromMock()
}

type txMock struct{}

func (t *txMock) Exec(fn func() error) error {
    return getFromMock()
}

</code></pre>
<p>When testing <code>GetByID</code> I have no problem whatsoever.</p>
<pre><code>func TestGetByID(t *testing.T) {
    userDomain = &amp;userMock{}
    Tx = &amp;txMock{}

    getUserFromMock = func() (*User, error) {
        return &amp;User{ID: 3}, nil
    }

    user, err := GetByID()

    if user.ID != 3 {
        t.Fatalf(&quot;error&quot;)
    }

    if err != nil {
        t.Fatalf(&quot;error&quot;)
    }
}

</code></pre>
<p>However, When I try to testing <code>GetByIDWithTx</code>, I cannot assert the mock values:</p>
<pre><code>func TestGetByIDWithTx(t *testing.T) {
    userDomain = &amp;userMock{}
    Tx = &amp;txMock{}

    getUserFromMock = func() (*User, error) {
        return &amp;User{ID: 4}, nil
    }
    /**** Mocking callback response ****/
    getFromMock = func() error {
        return nil
    }

    user, err := GetByIDWithTx()

    if user.ID != 4 {
        t.Fatalf(&quot;error&quot;) /** It fails here **/
    }

    if err != nil {
        t.Fatalf(&quot;error&quot;)
    }
}

</code></pre>
<p>I assume, at the moment I'm trying to assert the callback is still running in another routine but I'm just speculating, I don't have any idea what is going on here. I rather not use any library for a spy, I just want to understand how to solve this. Thoughts?</p>
<p><a href=""https://play.golang.org/p/ZTF5ZoAV9sY"" rel=""nofollow noreferrer"">Go PlayGround HERE</a></p>
",https://stackoverflow.com/questions/65796815/mock-asserting-into-callbacks,"['unit-testing', 'go']",51,True,0,1
How to bypass (custom) MessageBoxes when unit testing with Moq?,"<p><strong>Update:</strong></p>
<p>Added requested table drawing code, where the MessageBoxService.Show() called.</p>
<pre><code>/// &lt;summary&gt;
    /// Draws the classic sudoku table with the given size.
    /// &lt;/summary&gt;
    protected override void Draw(object o)
    {
        if (GetCurrentTableViewModel() != null &amp;&amp; GetCurrentTableViewModel().AreAnyCellsFilled())
        {
            var messageBoxResult = MessageBoxService.Show(
               Resources.MessageBox_DrawIfNumbersArePresented,
               Resources.MessageBox_Question_Title, MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (messageBoxResult == MessageBoxResult.No || messageBoxResult == MessageBoxResult.Cancel)
            {
                return;
            }
        }

        SudokuBoardSize sudokuBoardSize = (SudokuBoardSize)o;

        bool oldDiagonalRulesStatus = AreDiagonalRulesApplied;
        if (sudokuBoardSize.Height == 9 &amp;&amp; sudokuBoardSize.Width == 9)
        {
            SudokuBoardControl = new UcClassicSudoku9x9Table();
            _actualSudokuBoard = CreateBoard(sudokuBoardSize, (BaseSudokuTableViewModel)SudokuBoardControl.DataContext, false);
        }
        else if (sudokuBoardSize.Height == 6 &amp;&amp; sudokuBoardSize.Width == 6)
        {
            SudokuBoardControl = new UcClassicSudoku6x6Table();
            _actualSudokuBoard = CreateBoard(sudokuBoardSize, (BaseSudokuTableViewModel)SudokuBoardControl.DataContext, false);
        }
        else
        {
            SudokuBoardControl = new UcClassicSudoku4x4Table();
            _actualSudokuBoard = CreateBoard(sudokuBoardSize, (BaseSudokuTableViewModel)SudokuBoardControl.DataContext, false);
        }

        ((BaseClassicSudokuTableViewModel)SudokuBoardControl.DataContext).AreDiagonalRulesApplied = oldDiagonalRulesStatus;
        SolutionCounter = string.Empty;
        IsSolutionCounterVisible = false;
        _solutions.Clear();
    }
</code></pre>
<p>I am new on Stackoverflow, so sorry for any mistakes.</p>
<p>I am developed a Sudoku solver hobby project and I would like to add Unit tests to it. It is fully MVVM. (<a href=""https://github.com/denesdavid/Solvedoku"" rel=""nofollow noreferrer"">https://github.com/denesdavid/Solvedoku</a>)</p>
<p>I wanted to test 'the drawing of a new empty table' feature when there is at least one filled cell in the current Sudoku. The software asks you in this case if you really want to draw a new one. I would like to bypass this question, I mean...simulating to press on the Yes button. I read that Moq is perfect for this, but it is not working for me currently. The question pops up during unit testing, but I have to click on Yes manually.</p>
<p>Here is my test:</p>
<pre><code>[TestMethod]
    public void Draw9x9TableWithAlreadyFilledCellsTest()
    {
        Mock&lt;IMessageBoxService&gt; messageBoxMock = new Mock&lt;IMessageBoxService&gt;(MockBehavior.Strict);
        messageBoxMock.Setup(m =&gt;
            m.Show(It.IsAny&lt;string&gt;(), It.IsAny&lt;string&gt;(), It.IsAny&lt;MessageBoxButton&gt;(),
            It.IsAny&lt;MessageBoxImage&gt;()));
        messageBoxMock.SetReturnsDefault(MessageBoxResult.OK);
        
        ClassicSudokuViewModel classicSudokuViewModel = new ClassicSudokuViewModel(messageBoxMock.Object);
        SudokuBoardSize sudokuBoardSize = new SudokuBoardSize();
        sudokuBoardSize.Height = 9;
        sudokuBoardSize.Width = 9;
        sudokuBoardSize.BoxCountX = 3;
        sudokuBoardSize.BoxCountY = 3;

        
        BaseSudokuTableViewModel tableViewModel = classicSudokuViewModel.GetCurrentTableViewModel();
        tableViewModel.Cells[0][0] = &quot;1&quot;;
        classicSudokuViewModel.DrawSudokuCommand.Execute(sudokuBoardSize);
        object actualBoard = classicSudokuViewModel.SudokuBoardControl;
        tableViewModel = classicSudokuViewModel.GetCurrentTableViewModel();

        Assert.AreEqual(typeof(UcClassicSudoku9x9Table), actualBoard.GetType());
        Assert.AreEqual(string.Empty, tableViewModel.Cells[0][0]);
        Assert.AreEqual(false, classicSudokuViewModel.AreDiagonalRulesApplied);
        Assert.AreEqual(string.Empty, classicSudokuViewModel.SolutionCounter);
        Assert.AreEqual(false, classicSudokuViewModel.IsSolutionCounterVisible);
        Assert.AreEqual(0, classicSudokuViewModel.Solutions.Count);
    }
</code></pre>
<p>IMessageBoxService:</p>
<pre><code>public interface IMessageBoxService
{
    /// &lt;summary&gt;
    /// Shows a MessageBox with the given text, title, button(s) and image.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;messageText&quot;&gt;Text of the MessageBox.&lt;/param&gt;
    /// &lt;param name=&quot;title&quot;&gt;Title of the MessageBox&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxButton&quot;&gt;Button(s) of the MessageBox&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxImage&quot;&gt;Image of the MessageBox&lt;/param&gt;
    /// &lt;returns&gt;MessageBoxResult&lt;/returns&gt;
    MessageBoxResult Show(string messageText, string title, MessageBoxButton messageBoxButton,
        MessageBoxImage messageBoxImage);

    /// &lt;summary&gt;
    /// Shows a MessageBox with the given text, title, button(s), image and style.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;messageText&quot;&gt;Text of the MessageBox.&lt;/param&gt;
    /// &lt;param name=&quot;title&quot;&gt;Title of the MessageBox&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxButton&quot;&gt;Button(s) of the MessageBox&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxImage&quot;&gt;Image of the MessageBox&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxStyle&quot;&gt;Style of the MessageBox&lt;/param&gt;
    /// &lt;returns&gt;MessageBoxResult&lt;/returns&gt;
    MessageBoxResult Show(string messageText, string title, MessageBoxButton messageBoxButton,
        MessageBoxImage messageBoxImage, Style messageBoxStyle);
}
</code></pre>
<p>}</p>
<p>MessageBoxService:</p>
<pre><code>class MessageBoxService : DependencyObject, IMessageBoxService
{
    private Style _messageBoxStyle = (Style)Application.Current?.Resources[&quot;MessageBoxStyle&quot;];

    /// &lt;summary&gt;
    /// Displays a messagebox with the given parameters.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;messageText&quot;&gt;Text of the messagebox.&lt;/param&gt;
    /// &lt;param name=&quot;title&quot;&gt;Title of the messagebox.&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxButton&quot;&gt;Displayed button(s) in the messagebox. (Choose from the MessageBoxButton enum.).&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxImage&quot;&gt;Displayed icon in the messagebox. (Choose from the MessageBoxImage enum.).&lt;/param&gt;
    /// &lt;returns&gt;MessageBoxResult&lt;/returns&gt;
    public MessageBoxResult Show(string messageText, string title, MessageBoxButton messageBoxButton, MessageBoxImage messageBoxImage)
    {
        return Xceed.Wpf.Toolkit.MessageBox.Show(Application.Current?.MainWindow, messageText, title, messageBoxButton, messageBoxImage, _messageBoxStyle);
    }

    /// &lt;summary&gt;
    /// Displays a messagebox with the given parameters.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;messageText&quot;&gt;Text of the messagebox.&lt;/param&gt;
    /// &lt;param name=&quot;title&quot;&gt;Title of the messagebox.&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxButton&quot;&gt;Displayed button(s) in the messagebox. (Choose from the MessageBoxButton enum.).&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxImage&quot;&gt;Displayed icon in the messagebox. (Choose from the MessageBoxImage enum.).&lt;/param&gt;
    /// &lt;param name=&quot;messageBoxStyle&quot;&gt;Style what is applied on the MessageBox.&lt;/param&gt;
    /// &lt;returns&gt;MessageBoxResult&lt;/returns&gt;
    public MessageBoxResult Show(string messageText, string title, MessageBoxButton messageBoxButton, MessageBoxImage messageBoxImage, Style messageBoxStyle)
    {
        return Xceed.Wpf.Toolkit.MessageBox.Show(Application.Current?.MainWindow, messageText, title, messageBoxButton, messageBoxImage, messageBoxStyle);
    }
}
</code></pre>
<p>}</p>
<p>Thank you for your help!</p>
",https://stackoverflow.com/questions/68909377/how-to-bypass-custom-messageboxes-when-unit-testing-with-moq,"['c#', 'unit-testing', 'mocking', 'moq', 'messagebox']",80,True,0,1
Error when unit testing cloud function: no document found to update,"<p>I am following the firebase <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">documentation</a> for unit testing. I created a simple cloud function that is triggered when a firestore document is created. It turns the value in that document to uppercase. I tried the function by creating a document and it worked as expected.</p>
<p>I use jest for the test. When I run the test I get the following error:</p>
<pre><code>NOT_FOUND: No document to update: projects/myproject/databases/(default)/documents/test/testId

  10 |   return admin.firestore().doc(`test/` + snap.id)
&gt; 11 |               .update({ input: input });
     |                ^
  12 | });
</code></pre>
<p>I added a console.log to my function to see what data was passed by the unit-test. It passes the right data (meaning the right document id and the right value for &quot;input&quot;.</p>
<p>I'm not sure what I'm missing here. It's a simple function and a simple test. I don't understand how the function could receive the right data but not found the document, or how the document is not created in firestore when the test is run.</p>
<p>The function:</p>
<pre><code>import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

export const makeUpperCase = functions.firestore
.document('test/{id}')
.onCreate((snap, context) =&gt; {
  const data = snap.data();
  const input = data.input.toUpperCase();
  console.log('new data: ' + input + ', id: ' + snap.id);
  return admin.firestore().doc('test/' + snap.id)
              .update({ input: input });
});
</code></pre>
<p>index.ts:</p>
<pre><code>import * as admin from 'firebase-admin';
admin.initializeApp();

export { makeUpperCase } from './makeUpperCase';
</code></pre>
<p>the test (basicTest.test.ts):</p>
<pre><code>import * as functions from 'firebase-functions-test';
import * as admin from 'firebase-admin';
import 'jest';

const testEnv = functions({
  databaseURL: &quot;https://mydb.firebaseio.com&quot;,
  projectId: &quot;myproject&quot;,
}, './service-account.json');

testEnv.mockConfig({});

import { makeUpperCase } from '../src/index';

describe('basicTest', () =&gt; {
  let wrapped: any;

  beforeAll(() =&gt; {
    wrapped = testEnv.wrap(makeUpperCase);
  });

  test('converts input to upper case', async () =&gt; {
    const path = 'test/testId';
    const data = { input: 'a simple test' };
    const snap = await testEnv.firestore.makeDocumentSnapshot(data, path);
    await wrapped(snap);
    const after = await admin.firestore().doc(path).get();
    expect(after.data()!.input).toBe('A SIMPLE TEST');
  });
});
</code></pre>
",https://stackoverflow.com/questions/66604714/error-when-unit-testing-cloud-function-no-document-found-to-update,"['firebase', 'unit-testing']",340,False,0,1
c++ unit testing with dependency and file writing,"<p>I am a student and new for unit testing. I'm confused with testing problems when writing my project.</p>
<p>I have three functions <code>A()</code>, <code>B(string file)</code> and <code>C()</code>. <code>A()</code> is used for initialization and it creates a directory <code>temp</code> to store files. <code>B(string file)</code> writes file in <code>temp</code>. <code>C()</code> transfer the current files in <code>temp</code> to another place and mark these files. They are usually called in the following order:</p>
<pre><code>         | - - - - - - - - - - - - -
        \ /                        |
A - - -&gt; B (multiple times) - - -&gt; C
</code></pre>
<p>(the three functions are kind of like the commands <code>init</code>, <code>add</code> and <code>commit</code> in the version control system <em>git</em>)</p>
<p>Here is the thing:</p>
<ol>
<li>I've written the test and implementation of <code>A()</code>. In <code>testB()</code> I need the initialization, so I call <code>A()</code>. Though it is tested, it seems that it's a bad choice. What should I do? Should I just create the directory <code>temp</code> on my own in <code>testB()</code>?</li>
<li>If a file has been marked by <code>C()</code>, <code>B(string file)</code> should do nothing if  then we forward the file to <code>B(string file)</code>. How can I test this situation?</li>
</ol>
<p>I'll aappreciate it if you can give detailed instructions.</p>
",https://stackoverflow.com/questions/66407215/c-unit-testing-with-dependency-and-file-writing,"['c++', 'unit-testing']",369,True,0,1
Why it is better to have independent test cases in unit testing?,"<p>In a lot of unit testing frameworks, test cases are independent. For example, GoogleTest says:</p>
<blockquote>
<p>Tests should be <em>independent</em> and <em>repeatable</em>. It’s a pain to debug a test that succeeds or fails as a result of other tests. googletest isolates the tests by running each of them on a different object.</p>
</blockquote>
<p>I don't understand why it is good that test cases are independent. For example, assume an composite object <code>A</code> which uses objects <code>B</code> and <code>C</code>. It is obvious that if <code>B</code> and <code>C</code> are buggy, what <code>A</code> does will be incorrect too, whether it is implemented correctly or not. So I somehow like to see an output like this:</p>
<pre><code>Testing B [SUCCEED]
Testing C [FAILED]
Testing A [FAILED] because dependent test C failed. 
</code></pre>
<p>Do these framework assume that rather than depending these to each other, it is better to test <code>A</code> by mocking <code>B</code> and <code>C</code>? Because sometimes writing correct mocker for your classes can be complex (and buggy itself), so I still think depending tests is better.</p>
",https://stackoverflow.com/questions/70409849/why-it-is-better-to-have-independent-test-cases-in-unit-testing,"['unit-testing', 'testing']",144,True,0,1
How to write a service class to return any implementation class object which implements interface,"<p>I have a requirement to update number of records into a table in a single call from Java program. Simply it is JDBC batch update.</p>
<p>For this, I have this following code snippet at interface and implementation which is perfectly working.</p>
<pre><code>interface TableABatchUpdater extends Logic&lt;TableADTO&gt; {
   void updateBatch(List&lt;TableADTO&gt; list)
}

class TableABatchUpdaterImpl extends AbstractLogic&lt;TableADTO&gt; implements TableABatchUpdater {
   @Autowired DAOClass dao;

   TableABatchUpdaterImpl(){
     super(&quot;TableA&quot;);
   }

   @Override
    void updateBatch(List&lt;TableADTO&gt; list) {
        dao.updateBatch(list)
    }

}
interface TableBBatchUpdater extends Logic&lt;TableBDTO&gt; {
   void updateBatch(List&lt;TableBDTO&gt; list)
}

class TableBBatchUpdaterImpl extends AbstractLogic&lt;TableBDTO&gt; implements TableBBatchUpdater {
   @Autowired DAOClass dao;

   TableBBatchUpdaterImpl(){
     super(&quot;TableB&quot;);
   }

   @Override
    void updateBatch(List&lt;TableBDTO&gt; list) {
        dao.updateBatch(list)
    }

}

interface TableCBatchUpdater extends Logic&lt;TableCDTO&gt; {
   void updateBatch(List&lt;TableCDTO&gt; list)
}

class TableACatchUpdaterImpl extends AbstractLogic&lt;TableCDTO&gt; implements TableABatchUpdater {
   @Autowired DAOClass dao;

   TableCBatchUpdaterImpl(){
     super(&quot;TableC&quot;);
   }

   @Override
    void updateBatch(List&lt;TableCDTO&gt; list) {
        dao.updateBatch(list)
    }

}


public class MyServiceClass {

  @Autowired TableABatchUpdater tableA;
  @Autowired TableBBatchUpdater tableB;
  @Autowired TableCBatchUpdater tableC;

  public void updateTables() {
     tableA.updateBatch(tableAList);
     tableB.updateBatch(tableBList);
     tableC.updateBatch(tableCList);
   }

}
</code></pre>
<p>The problem here is, when I would like to add batch update statements for another table called <code>&quot;TableD&quot;</code>, MyServiceClass class dependencies are increasing and the complexity is very high interms of unit testing..etc. So, I tried to use one interface instead of independent interface for each table as follows. But, still I have to write many implementation classes for each table which I don't want.</p>
<pre><code>interface BatchUpdater extends Logic&lt;?&gt; {
       void updateBatch(List&lt;?&gt; list)
}
</code></pre>
<p>I tried to write the implementations by using factory and composite patterns. But, none of them worked out.</p>
<p>Is there any other way in Spring to write a separate service class which will return as the following.</p>
<pre><code>public class MyServiceClass {

    @Autowired BatchUpdaterService batchUpdaterService;

    public void updateTables() {
        batchUpdaterService.getTableUpdater(&quot;TableA&quot;).updateBatch(tableAList);
        batchUpdaterService.getTableUpdater(&quot;TableB&quot;).updateBatch(tableBList);
        batchUpdaterService.getTableUpdater(&quot;TableC&quot;).updateBatch(tableCList);
    }

}
</code></pre>
<p>Any response is highly appreciated</p>
",https://stackoverflow.com/questions/69409137/how-to-write-a-service-class-to-return-any-implementation-class-object-which-imp,"['java', 'spring']",45,False,0,1
How to check that the code/test-coverage of cobertura.xml files is above a specified threshold?,"<p>I have a .Net 5 solution with multiple projects and multiple test projects. I want to make sure either <strong>everything</strong> or a specified percentage value (e.g. 80%) got covered by tests. I'm using xUnit for my tests and created the following Powershell script based on the docs</p>
<p><a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports</a></p>

<pre class=""lang-sh prettyprint-override""><code>dotnet test --collect:&quot;XPlat Code Coverage&quot;;

reportgenerator -reports:'**/coverage.cobertura.xml' -targetdir:'CoverageReports' -reporttypes:'Cobertura';

[XML]$report = Get-Content CoverageReports/Cobertura.xml

if($report.coverage.'line-rate' -ge 20)
{
    Write-Host &quot;greater or equal than 20&quot;
}
else
{
    Write-Host &quot;less than 20&quot;
}

Read-Host -Prompt 'done'
</code></pre>
<p>which does the following</p>
<ul>
<li>it runs the tests and creates one <em>cobertura</em> file per test project</li>
<li>it merges every <em>cobertura</em> file into one and puts it into the <em>CoverageReports</em> directory</li>
<li>it parses the .xml file</li>
</ul>
<p>now I have access to the coverage info, e.g. the line-rate. Instead of the dummy if statement, how can I achieve the following sample?</p>
<pre class=""lang-sh prettyprint-override""><code>if($report.coverage.percentage -lt 80)
{
    Write-Host &quot;Coverage is less than 80 percent&quot;
}
</code></pre>
<p>and as a bonus I could write down a list of things that are not covered yet.</p>
<hr />
<p>This is the content of a generated Cobertura.xml file from a dummy project</p>
<pre class=""lang-xml prettyprint-override""><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;!DOCTYPE coverage SYSTEM &quot;http://cobertura.sourceforge.net/xml/coverage-04.dtd&quot;&gt;
&lt;coverage line-rate=&quot;1&quot; branch-rate=&quot;1&quot; lines-covered=&quot;4&quot; lines-valid=&quot;4&quot; branches-covered=&quot;0&quot; branches-valid=&quot;0&quot; complexity=&quot;4&quot; version=&quot;0&quot; timestamp=&quot;1627911309&quot;&gt;
  &lt;sources&gt;
    &lt;source&gt;C:\&lt;/source&gt;
  &lt;/sources&gt;
  &lt;packages&gt;
    &lt;package name=&quot;ClassLibrary1&quot; line-rate=&quot;1&quot; branch-rate=&quot;1&quot; complexity=&quot;3&quot;&gt;
      &lt;classes&gt;
        &lt;class name=&quot;ClassLibrary1.BoolReturner&quot; filename=&quot;C:\...\ClassLibrary1\BoolReturner.cs&quot; line-rate=&quot;1&quot; branch-rate=&quot;1&quot; complexity=&quot;3&quot;&gt;
          &lt;methods&gt;
            &lt;method name=&quot;Get&quot; signature=&quot;(...)&quot; line-rate=&quot;1&quot; branch-rate=&quot;1&quot; complexity=&quot;1&quot;&gt;
              &lt;lines&gt;
                &lt;line number=&quot;5&quot; hits=&quot;3&quot; branch=&quot;false&quot; /&gt;
              &lt;/lines&gt;
            &lt;/method&gt;
            &lt;method name=&quot;GetFalse&quot; signature=&quot;()&quot; line-rate=&quot;1&quot; branch-rate=&quot;1&quot; complexity=&quot;1&quot;&gt;
              &lt;lines&gt;
                &lt;line number=&quot;6&quot; hits=&quot;1&quot; branch=&quot;false&quot; /&gt;
              &lt;/lines&gt;
            &lt;/method&gt;
            &lt;method name=&quot;X&quot; signature=&quot;()&quot; line-rate=&quot;1&quot; branch-rate=&quot;1&quot; complexity=&quot;1&quot;&gt;
              &lt;lines&gt;
                &lt;line number=&quot;7&quot; hits=&quot;1&quot; branch=&quot;false&quot; /&gt;
              &lt;/lines&gt;
            &lt;/method&gt;
          &lt;/methods&gt;
          &lt;lines&gt;
            &lt;line number=&quot;5&quot; hits=&quot;3&quot; branch=&quot;false&quot; /&gt;
            &lt;line number=&quot;6&quot; hits=&quot;1&quot; branch=&quot;false&quot; /&gt;
            &lt;line number=&quot;7&quot; hits=&quot;1&quot; branch=&quot;false&quot; /&gt;
          &lt;/lines&gt;
        &lt;/class&gt;
      &lt;/classes&gt;
    &lt;/package&gt;
    &lt;package name=&quot;ClassLibrary2&quot; line-rate=&quot;1&quot; branch-rate=&quot;1&quot; complexity=&quot;1&quot;&gt;
      &lt;classes&gt;
        &lt;class name=&quot;ClassLibrary2.StringCombiner&quot; filename=&quot;C:\...\StringCombiner.cs&quot; line-rate=&quot;1&quot; branch-rate=&quot;1&quot; complexity=&quot;1&quot;&gt;
          &lt;methods&gt;
            &lt;method name=&quot;Combine&quot; signature=&quot;(...)&quot; line-rate=&quot;1&quot; branch-rate=&quot;1&quot; complexity=&quot;1&quot;&gt;
              &lt;lines&gt;
                &lt;line number=&quot;7&quot; hits=&quot;2&quot; branch=&quot;false&quot; /&gt;
              &lt;/lines&gt;
            &lt;/method&gt;
          &lt;/methods&gt;
          &lt;lines&gt;
            &lt;line number=&quot;7&quot; hits=&quot;2&quot; branch=&quot;false&quot; /&gt;
          &lt;/lines&gt;
        &lt;/class&gt;
      &lt;/classes&gt;
    &lt;/package&gt;
  &lt;/packages&gt;
&lt;/coverage&gt;
</code></pre>
",https://stackoverflow.com/questions/68588986/how-to-check-that-the-code-test-coverage-of-cobertura-xml-files-is-above-a-speci,"['c#', 'powershell', 'code-coverage', 'xunit', 'cobertura']",4206,True,4,1
Jest/Enzyme with create-react-app Unexpected token,"<p>I'm having an issue when trying to run tests on components inside a CRA app. I'm new to Jest/Enzyme and have run very similar tests in one CRA app which I created specifically to learn unit testing, but when I try to integrate it into an existing project, I get this error:</p>
<pre><code>SyntaxError: /Users/dave/Teacher_App/client_teacher/App.test.js: Unexpected token (12:20)

  10 | 
  11 |   beforeEach(() =&gt; {
&gt; 12 |     wrapper = mount(&lt;App /&gt;)
     |                     ^
  13 |     console.log(wrapper.debug()) 
  14 |   })
  15 | 
</code></pre>
<p>I have tried the suggestions provided in the terminal and have read a bunch of answers to other posts on here with the same issue, but nothing seems to be working!</p>
<p>Here are the contents of my ./setupTests.js</p>
<pre><code>import '@testing-library/jest-dom';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });

</code></pre>
<p>and ./App.test.js</p>
<pre><code>import App from './App';
import React from 'react';

import { mount } from 'enzyme';


describe('counter testing', () =&gt; {

  let wrapper ;

  beforeEach(() =&gt; {
    wrapper = mount(&lt;App /&gt;)
    console.log(wrapper.debug())
  })

  test('renders the title of the dash', () =&gt; {
    
    expect(wrapper.find('h1').text()).toContain(&quot;Dashboard&quot;)

  });

})

</code></pre>
<p>and also my package.json (it's a pretty big app!)</p>
<pre><code>{
  &quot;name&quot;: &quot;app-schools&quot;,
  &quot;version&quot;: &quot;0.1.0&quot;,
  &quot;private&quot;: true,
  &quot;dependencies&quot;: {
    &quot;@babel/preset-env&quot;: &quot;^7.15.8&quot;,
    &quot;@babel/preset-react&quot;: &quot;^7.14.5&quot;,
    &quot;@fortawesome/fontawesome-svg-core&quot;: &quot;^1.2.30&quot;,
    &quot;@fortawesome/free-brands-svg-icons&quot;: &quot;^5.14.0&quot;,
    &quot;@fortawesome/free-regular-svg-icons&quot;: &quot;^5.14.0&quot;,
    &quot;@fortawesome/free-solid-svg-icons&quot;: &quot;^5.14.0&quot;,
    &quot;@fortawesome/react-fontawesome&quot;: &quot;^0.1.11&quot;,
    &quot;@fullcalendar/daygrid&quot;: &quot;^5.3.2&quot;,
    &quot;@fullcalendar/react&quot;: &quot;^5.3.1&quot;,
    &quot;@rails/actioncable&quot;: &quot;^6.0.3-4&quot;,
    &quot;@react-pdf/renderer&quot;: &quot;^1.6.14&quot;,
    &quot;@stripe/react-stripe-js&quot;: &quot;^1.1.2&quot;,
    &quot;@stripe/stripe-js&quot;: &quot;^1.9.0&quot;,
    &quot;@testing-library/jest-dom&quot;: &quot;^4.2.4&quot;,
    &quot;@testing-library/react&quot;: &quot;^9.5.0&quot;,
    &quot;@testing-library/user-event&quot;: &quot;^7.2.1&quot;,
    &quot;@use-hooks/image-size&quot;: &quot;^1.0.5&quot;,
    &quot;axios&quot;: &quot;^0.19.2&quot;,
    &quot;babel-jest&quot;: &quot;^27.2.5&quot;,
    &quot;crossfilter2&quot;: &quot;^1.4.7&quot;,
    &quot;d3&quot;: &quot;^5.16.0&quot;,
    &quot;date-fns&quot;: &quot;^2.23.0&quot;,
    &quot;dc&quot;: &quot;^3.2.1&quot;,
    &quot;dompurify&quot;: &quot;^2.3.3&quot;,
    &quot;downloadjs&quot;: &quot;^1.4.7&quot;,
    &quot;enzyme&quot;: &quot;^3.11.0&quot;,
    &quot;enzyme-adapter-react-16&quot;: &quot;^1.15.6&quot;,
    &quot;glamor&quot;: &quot;^2.20.40&quot;,
    &quot;google-classroom-share&quot;: &quot;^0.5.4&quot;,
    &quot;googleapis&quot;: &quot;^39.2.0&quot;,
    &quot;jest&quot;: &quot;^27.2.5&quot;,
    &quot;jwt-decode&quot;: &quot;^3.1.2&quot;,
    &quot;loadash&quot;: &quot;^1.0.0&quot;,
    &quot;node-sass&quot;: &quot;^4.14.1&quot;,
    &quot;query-string&quot;: &quot;^7.0.0&quot;,
    &quot;react&quot;: &quot;^16.13.1&quot;,
    &quot;react-country-region-selector&quot;: &quot;^3.0.2&quot;,
    &quot;react-countup&quot;: &quot;^4.3.3&quot;,
    &quot;react-datepicker&quot;: &quot;^3.0.0&quot;,
    &quot;react-dom&quot;: &quot;^16.13.1&quot;,
    &quot;react-draggable&quot;: &quot;^4.4.3&quot;,
    &quot;react-elastic-carousel&quot;: &quot;^0.7.4&quot;,
    &quot;react-flexbox-grid&quot;: &quot;^2.1.2&quot;,
    &quot;react-flip-page&quot;: &quot;^1.6.4&quot;,
    &quot;react-ga&quot;: &quot;^3.3.0&quot;,
    &quot;react-google-picker&quot;: &quot;^0.1.0&quot;,
    &quot;react-helmet&quot;: &quot;^6.1.0&quot;,
    &quot;react-load-script&quot;: &quot;0.0.6&quot;,
    &quot;react-masonry-css&quot;: &quot;^1.0.14&quot;,
    &quot;react-modern-calendar-datepicker&quot;: &quot;^3.1.6&quot;,
    &quot;react-player&quot;: &quot;^2.7.0&quot;,
    &quot;react-quill&quot;: &quot;^1.3.5&quot;,
    &quot;react-redux&quot;: &quot;^7.2.0&quot;,
    &quot;react-router-dom&quot;: &quot;^5.2.0&quot;,
    &quot;react-router-redux&quot;: &quot;^4.0.8&quot;,
    &quot;react-script-tag&quot;: &quot;^1.1.2&quot;,
    &quot;react-scripts&quot;: &quot;3.4.1&quot;,
    &quot;react-select&quot;: &quot;^3.1.0&quot;,
    &quot;react-share&quot;: &quot;^4.2.1&quot;,
    &quot;react-swipeable&quot;: &quot;^5.5.1&quot;,
    &quot;react-test-renderer&quot;: &quot;^17.0.2&quot;,
    &quot;redux&quot;: &quot;^4.0.5&quot;,
    &quot;redux-persist&quot;: &quot;^6.0.0&quot;,
    &quot;redux-thunk&quot;: &quot;^2.3.0&quot;,
    &quot;styled-components&quot;: &quot;^5.1.1&quot;,
    &quot;typography&quot;: &quot;^0.16.19&quot;,
    &quot;typography-theme-funston&quot;: &quot;^0.16.19&quot;
  },
  &quot;scripts&quot;: {
    &quot;start&quot;: &quot;react-scripts start&quot;,
    &quot;build&quot;: &quot;react-scripts build&quot;,
    &quot;test&quot;: &quot;jest&quot;,
    &quot;eject&quot;: &quot;react-scripts eject&quot;
  },
  &quot;eslintConfig&quot;: {
    &quot;extends&quot;: &quot;react-app&quot;
  },
  &quot;browserslist&quot;: {
    &quot;production&quot;: [
      &quot;&gt;0.2%&quot;,
      &quot;not dead&quot;,
      &quot;not op_mini all&quot;
    ],
    &quot;development&quot;: [
      &quot;last 1 chrome version&quot;,
      &quot;last 1 firefox version&quot;,
      &quot;last 1 safari version&quot;
    ]
  }
}

</code></pre>
<p>Here is the contents of the App.jsx component, stripped down whilst trying to debug:</p>
<pre><code>import React from 'react';


const App = () =&gt; {

  return (
    &lt;div&gt;
      &lt;h1&gt;Dashboard&lt;/h1&gt;
    &lt;/div&gt;
  )

}

export default App;
</code></pre>
<p>I assume I am missing some setting somewhere. This is a non-ejected CRA app, so I cannot modify the babel config file.</p>
<p>Any help would be greatly appreciated!</p>
",https://stackoverflow.com/questions/69554958/jest-enzyme-with-create-react-app-unexpected-token,"['reactjs', 'unit-testing', 'jestjs', 'create-react-app', 'enzyme']",66,False,0,1
CppUTest - no test is running,"<p>i'm trying to setup CppUTest project with CMake.
I'm new to CMake so i started with this example: <a href=""https://github.com/davisford/cmake-cpputest"" rel=""nofollow noreferrer"">link</a></p>
<p>It works fine. Project compiles and i see tests ran.</p>
<p>Then i tried to create my own project based on this example.
My project also compiles without error but i always get following output:
<code>OK (0 tests, 0 ran, 0 checks, 0 ignored, 0 filtered out, 0 ms)</code></p>
<p>I've no idea why CppUTest framework 'doesn't see' tests that i've created.</p>
<p>What i've done is:
Created project structure like this:</p>
<pre><code>.unit_tests_prj
|--project
|--code
|    |-CMakeLists.txt
|    |-Tests
|    |    |-CMakeLists.txt
|    |    |-RunAllTests.cpp
|    |    |-leds_tests
|    |    |      |-leds_tests.cpp
</code></pre>
<p>The CMakeLists.txt file in code directory contains following code:</p>
<pre><code>cmake_minimum_required(VERSION 2.8.7)
project(rgb_lamp_unit_tests)

# Check if env variable for CppUTest dir is valid
if(DEFINED ENV{CPP_UTEST_HOME})
    message(&quot;Found CppUTest home dir at: $ENV{CPP_UTEST_HOME}&quot;)
else()
    message(&quot;Not found CppUTest directory... Finish build!&quot;)
    return()
endif()

include_directories($ENV{CPP_UTEST_HOME}/include)
# set c &amp; cpp lang
enable_language(C)
enable_language(CXX)

# version number
set(rgb_lamp_unit_tests_VER_MAJOR 1)
set(rgb_lamp_unit_tests_VER_MINOR 0)

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/lib)

# add sources subdirectories for cmake
add_subdirectory(Tests)

</code></pre>
<p>CMakeLists.txt in code/Tests dir contains:</p>
<pre><code>project(rgb_lamp_unit_tests)

# add include dirs for CppUTestHome
include_directories($ENV{CPP_UTEST_HOME}/include)

# add cpputest framework library
add_library(cpputest_lib STATIC IMPORTED)
set_property(TARGET cpputest_lib PROPERTY IMPORTED_LOCATION $ENV{CPP_UTEST_HOME}/lib/libCppUTest.a)

# build static library from tests modules
add_library(LedDriverTest ./leds_tests/leds_tests.cpp)

# build executable and link all necessary libs
add_executable(RunAllTests RunAllTests.cpp)
target_link_libraries(RunAllTests cpputest_lib LedDriverTest)

</code></pre>
<p>leds_tests.cpp contains:</p>
<pre><code>#include &quot;CppUTest/TestHarness.h&quot;   // include cppUtest framework

TEST_GROUP(LedDriver)
{

  uint16_t virtualLeds;
 
  void setup()
  {
    virtualLeds = 0;
  }

  void teardown() 
  {
  }
};

TEST(LedDriver, LedsAreOffAfterCreate)
{
    FAIL(&quot;This should fail!&quot;);
} 
</code></pre>
<p>I also noticed that when i changed content of leds_test.cpp to:</p>
<pre><code>#include &lt;iostream&gt;
void print_something(){
  std::cout &lt;&lt; &quot;some text&quot; &lt;&lt; std::endl;
}
</code></pre>
<p>and in RunAllTests.cpp did:</p>
<pre><code>extern void print_something();
int main(int argc, char** argv){
  print_something();
  //CommandLineTestRunner::RunAllTests(argc, argv);
}
</code></pre>
<p>Then i got &quot;some text&quot; on console output. So the LedDriverTest.a is correctly linked to RunAllTests executable.</p>
<p>I'll be grateful if someone could help me with that, as i want introduce unit testing and tdd in my work.</p>
<p>regards,
mf</p>
",https://stackoverflow.com/questions/66250691/cpputest-no-test-is-running,"['c++', 'unit-testing', 'cmake', 'cpputest']",488,False,0,0
How to unit test a void function in C++,"<p>I am working on a hobby project mainly to learn cpp unit testing and database programming. However I am a little bit lost &amp; confused about how should I write my code for proper testing. I tend to write a lot of <strong>void</strong> functions for my cpp projects. But now I can not figure out how should I test those functions. I have been succeeded in testing non-void functions cause they return something which can be easily tested against a value.</p>
<p>Ami I doing things in an unprofessional way? Should I avoid void functions as much as possible so that I can test those functions ? Or I am missing something ? For example how would I be able to test this function -</p>
<p><code>database.cpp</code></p>
<pre class=""lang-cpp prettyprint-override""><code>#include &quot;database.hpp&quot;

#include &lt;sqlite3.h&gt;

#include &lt;iostream&gt;

#include &quot;spdlog/sinks/basic_file_sink.h&quot;

// Creating the logging object
auto logger = spdlog::basic_logger_mt(&quot;appnotex&quot;, &quot;../data/appnotexlog&quot;);

void Database::createDb(const char *dbname) {
  // Creating the database file
  sqlite3 *datadb;
  int status = sqlite3_open(dbname, &amp;datadb);

  //    checking for errors
  if (status == SQLITE_OK) {
    logger-&gt;info(&quot;------------ New Session ----------&quot;);
    logger-&gt;info(&quot;Connected to Database Successfully&quot;);
  } else {
    std::string errorMessage = sqlite3_errmsg(datadb);
    logger-&gt;info(&quot;Error: &quot; + errorMessage);
  }
</code></pre>
<h3>If Needed</h3>
<ul>
<li>I am using <strong>Google Test</strong> framework</li>
<li>My whole project code hosted - <a href=""https://github.com/Abir-Tx/AppNotEx"" rel=""nofollow noreferrer"">here</a></li>
</ul>
<h3>Update</h3>
<p>I have tried this one is this approach of testing the above method correct ?</p>
<p><code>databaseTest.cpp</code></p>
<pre class=""lang-cpp prettyprint-override""><code>TEST(DatabaseTest, createDbTest) {
  const char *dbfilename = &quot;../data/test/data.db&quot;;
  const char *tbname = &quot;DataTest&quot;;
  Database *db = new Database();

  std::ifstream dbfile(&quot;../data/test/data.db&quot;);
  bool ok = false;
  if (!dbfile.is_open())
    ok = false;
  else
    ok = true;

  EXPECT_TRUE(ok);
}
</code></pre>
",https://stackoverflow.com/questions/67500353/how-to-unit-test-a-void-function-in-c,"['c++', 'unit-testing', 'testing', 'googletest', 'void']",1882,True,0,1
How do you specify the code behind the mocked AWS Lambda,"<p>I'm currently in the phase of unit-testing my lambdas and this is the first time I'm doing this, so please bear with me.</p>
<p>I've done my researches about this, and I think I managed to pinpoint down to which package I should use and which method.</p>
<p>As far as I know, <code>aws-sdk-mock</code> is the way to go. It seems complete and well-documented, so there's no problem in that direction. The only issue I have with it is the lack of documentation for AWS Lambda Invoke mockings.</p>
<p>The main issue I have is with mocking a specific function whose code is stored in the same project as the test.</p>
<p>i.e: I have a <code>lambda.ts</code>:</p>
<pre><code>export const handler: APIGatewayProxyHandlerV2 = async (event: any) =&gt; {
    const body = event.body;
    //do things with body
    return {
      statusCode:200,
      body: &quot;OK&quot;
    }
}
</code></pre>
<p>How do I correctly mock this?
I started a <code>lambda.test.ts</code> that looks like this :</p>
<pre><code>import AWSMock from &quot;aws-sdk-mock&quot;
import AWS from &quot;aws-sdk&quot;

beforeAll(async (done) =&gt; {
  //get requires env vars
  done()
})

describe(&quot;Calling lambda&quot;, () =&gt; {
  it(&quot;should reject API call because of missing arguments&quot;, async () =&gt; {
    AWSMock.setSDKInstance(AWS)
    AWSMock.mock(&quot;Lambda&quot;, &quot;invoke&quot;, async (params, callback) =&gt; {
        const lambda = new AWS.Lambda()
        await lambda.invoke({
            FunctionName: 'lambda',
            ...?
        }).promise()
    })
  })
})

</code></pre>
<p>I don't know how to indicate that the code that's behind this mocked lambda is available somewhere.</p>
<p>Thanks in advance for your help!</p>
",https://stackoverflow.com/questions/69839759/how-do-you-specify-the-code-behind-the-mocked-aws-lambda,"['node.js', 'amazon-web-services', 'unit-testing', 'aws-lambda', 'aws-sdk-mock']",247,False,0,1
Flutter integration tests - multiple tests,"<p>So I recently wanted to add some integration testing to the my app, and followed the official guidelines from the flutter.dev on the integration testing. I managed to run a single test, so I wanted to add another one, and this is where the problems started.</p>
<p>I don't know how to add another test suite in the same run, so something like</p>
<p>TEST 1:</p>
<ol>
<li>click button</li>
<li>check if counter incremented</li>
</ol>
<p>TEST2:</p>
<ol>
<li>click the button again</li>
<li>check if counter incremented again</li>
</ol>
<pre><code>void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();

  group('Integration test', () {
    testWidgets('test 1', (WidgetTester tester) async {
      app.main();
      await tester.pumpAndSettle();

      // doing stuff here works
    });
  });
}
</code></pre>
<p>This is what I have working right now. I expected that moving the <code>app.main()</code> call before the <code>group</code> and simply adding another testWidgets call will work (similar to unit testing) but it doesn't:</p>
<pre><code>void main() {
  IntegrationTestWidgetsFlutterBinding.ensureInitialized();
  // app.main(); &lt;&lt;--- moving here...
  group('Integration test', () {
    // app.main(); &lt;&lt;--- ... or here didn't help
    testWidgets('test 1', (WidgetTester tester) async {
      // do stuff
    });
    testWidgets('test 2', (WidgetTester tester) async {
      // how to add this? And do stuff with the same app session
    });
  });
}
</code></pre>
<p>EDIT:
For better clarity of what I'm trying to achieve. The following are some current flutter driver tests that I have. I just want to migrate to the new api of integration_test package, without losing the names &quot;test 1&quot;, &quot;test 2&quot; etc</p>
<pre><code>void main() {
  group(&quot;group name&quot;, () {
    FlutterDriver driver;
    setUpAll(() async {
      driver = await FlutterDriver.connect();
    });

    tearDownAll(() async {
      if (driver != null) {
        await driver.close();
      }
    });

    test('test 1', () async {
      // do stuff with the driver
    });
    test('test 2', () async {
      // do other stuff with the driver with the same seesion
    });
    test('test 3', () async {
      // etc
    });
  });
}
</code></pre>
",https://stackoverflow.com/questions/68480678/flutter-integration-tests-multiple-tests,"['flutter', 'testing']",2564,True,3,3
Next.js router error while testing using React-testing-library,"<p>I was just trying to do a preliminary test of rendering a component that is redirecting the user on the basis of the login status and thus using <code>router</code> from <code>next/router</code> in <code>componentDidMount</code> but getting the following error:</p>
<blockquote>
<p>No router instance found.
You should only use &quot;next/router&quot; inside the client side of your app.</p>
</blockquote>
<p>It appears to me that from <em>client side</em> it means using the <em>router</em> or <em>Link</em> has to be used inside of the render method as that is what makes the DOM and other methods like lifecycle, hooks, and server-side doesn't so in those cases it would throw an error.</p>
<p>I know that testing the entire component beats the purpose of unit testing but I wanted to do this anyway. Therefore, I followed this <a href=""https://github.com/vercel/next.js/issues/7479"" rel=""nofollow noreferrer"">discussion</a> and it appears that the router has to be mocked in order to be used by the <em>React-Testing-Library</em> but none of the solutions work for me.</p>
<p>Here is the code that I tried:</p>
<pre class=""lang-js prettyprint-override""><code>describe('Home Page', () =&gt; {
  it('renders without crashing', async () =&gt; {
    render(&lt;Home /&gt;)
  })
})
</code></pre>
",https://stackoverflow.com/questions/68398929/next-js-router-error-while-testing-using-react-testing-library,"['jestjs', 'next.js', 'react-testing-library']",2494,True,3,2
Cypress React Unit Tests - How to mock/stub Components,"<p>I am using the <code>@cypress/react</code> package to perform unit-testing on react components.</p>
<p>In my case, these react components contain external influence such as services or redux state management.</p>
<p>I tried to stub these external components with <code>cy.stub()</code> but I get an error that I don't know how to work around.</p>
<p>Example:</p>
<p>I have a component that invokes <code>useSelector</code> from redux in order to get the current state <code>currentState</code>. It looks like the following:</p>
<pre><code>import { currentStateSelector } from 'store/current-state/selectors';

export default function MyComponent() {
const currentState = useSelector(currentStateSelector);
return (
    currentState !== null ?
            &lt;div data-testid='my-component'&gt;
                 { currentState.name }
            &lt;/div&gt;
    :
    &lt;&gt;&lt;/&gt;
);
}
</code></pre>
<p>In order to test this I created the following spec file:</p>
<pre><code>import React from 'react';
import mount from '@cypress/react/dist';
import MyComponent from './my-component';
import * as reactRedux from 'react-redux';
import { store } from '../../store';

describe('MyComponent',() =&gt; {
        it('renders', () =&gt; {
        const useSelectorMock = cy.stub(reactRedux, 'useSelector');
        const currentState = {
            name: 'test',
        };
        useSelectorMock.returns(currentState);
        mount(
            &lt;reactRedux.Provider store={store}&gt;
                &lt;MyComponent/&gt;
            &lt;/reactRedux.Provider&gt;
        );
        cy.get('[data-testid=my-component]').should('exist');
    });
});
</code></pre>
<p>Running the test with <code>npx cypress open</code> it gives me an AssertionError:</p>
<pre><code>Timed out retrying after 4000ms: Expected to find element: [data-testid=my-component], but never found it.
</code></pre>
<p>Apparently, the element that I tried to stub returns a null value, which is why this AssertionError occured. But how do I resolve this?</p>
<p>Maybe I have not understood the stubbing functionality fully yet, but after days of research I haven't found anything helpful. Any help would be much appreciated.</p>
<p><strong>UPDATE</strong></p>
<p>I switched to the test framework jest and the mocking works by writing the following before <code>describe(...)</code>:</p>
<pre><code>jest.mock('react-redux', () =&gt; ({
    useSelector: jest.fn( () =&gt; { return 'desired return-object' })
}));
</code></pre>
",https://stackoverflow.com/questions/65994100/cypress-react-unit-tests-how-to-mock-stub-components,"['reactjs', 'unit-testing', 'redux', 'cypress', 'stub']",3605,False,2,0
Work around for Docker layer caching not working in Azure Pipeline,"<p>I'm hoping to cache a specific stage in my multi-stage Dockerfile that my test stages use in an effort speed the build process up. Otherwise, it builds for unit testing and then for integration testing.</p>
<p>Here is a bare bones example of one of the <code>Dockerfile</code>:</p>
<pre><code># creating a node base
FROM node:16-slim as node-base
ENV CI=true


# builder-base is used to build dependencies
FROM node-base as builder-base
COPY ./package-lock.json ./package.json ./
RUN npm ci --production


# 'development' stage installs all dev deps and can be used to develop code.
FROM builder-base as development
WORKDIR /app
COPY . . 
RUN npm ci
EXPOSE 4001
CMD [&quot;npm&quot;, &quot;start&quot;]


# 'unit-tests' stage 
FROM development AS unit-tests
RUN npm test -- --coverage --testNamePattern=UT: 


# 'integration-tests' stage 
FROM development AS integration-tests
RUN npm test -- --coverage --testNamePattern=IT:
</code></pre>
<p>I'd like to cache the <code>development</code> stage, <code>pull</code> it and just run the <code>unit-tests</code> and <code>integration-tests</code> stages without out building <code>development</code> twice.</p>
<p>I found this question which I'm trying to implement:</p>
<p><a href=""https://stackoverflow.com/questions/59266670/how-to-enable-docker-layer-caching-in-azure-devops"">How to Enable Docker layer caching in Azure DevOps</a></p>
<p>The top answer there is this:</p>
<pre><code>- task: Docker@2
  inputs:
    containerRegistry: '$(ContainerRegistryName)'
    command: 'login'

- script: &quot;docker pull $(ACR_ADDRESS)/$(REPOSITORY):latest&quot;
  displayName: Pull latest for layer caching
  continueOnError: true # for first build, no cache

- task: Docker@2
  displayName: build
  inputs:
    containerRegistry: '$(ContainerRegistryName)'
    repository: '$(REPOSITORY)'
    command: 'build'
    Dockerfile: './dockerfile '
    buildContext: '$(BUILDCONTEXT)'
    arguments: '--cache-from=$(ACR_ADDRESS)/$(REPOSITORY):latest' 
    tags: |
      $(Build.BuildNumber)
      latest

- task: Docker@2
  displayName: &quot;push&quot;
  inputs:
    command: push
    containerRegistry: &quot;$(ContainerRegistryName)&quot;
    repository: $(REPOSITORY) 
    tags: |
      $(Build.BuildNumber)
      latest
</code></pre>
<p>I've repurposed it for my pipeline like so:</p>
<pre><code># pr.yaml
# # This is triggered by the PR and branch policies
trigger: none

# Specify this to run on the app repo
resources:
  repositories:
  - repository:app
    type: git
    name: app

# Read in the base variable template
variables:
- template: templates/variables.yaml

# Use the ubuntu-latest image
pool:
  vmIMage: $(vmImageName)

# Stages and their templates for the PR pipeline
stages:
# Checks to see what services in the mono repo have changed by comparing
# the PR code to trunk
- template: templates/changed.yaml
  parameters:
    comparedTo: origin/trunk

# Run unit tests for each changed service
- template: templates/services.yaml
  parameters:
    stageName: BuildDev
    stageDisplayName: Build dev stage for services...
    dockerCommand: build
    phrase: build dev
    target: development
    tag: latest

# Run unit tests for each changed service
- template: templates/services.yaml
  parameters:
    stageName: UnitTests
    stageDisplayName: Run unit tests for services...
    dockerCommand: build
    phrase: unit test
    target: unit-tests
    tag: ut-$(Build.BuildNumber)

# Run integration tests for each changed service
- template: templates/services.yaml
  parameters:
    stageName: IntegrationTests
    stageDisplayName: Run integration tests for services...
    dockerCommand: build
    phrase: integration test
    target: integration-tests
    tag: it-$(Build.BuildNumber)
</code></pre>
<pre><code># services.yaml
parameters:
- name: stageName
  default: ''
- name: stageDisplayName
  default: ''
- name: phrase
  default: ''
- name: dockerCommand
  default: ''
- name: target
  default: ''
- name: tag
  default: ''
- name: services
  type: object
  default:
  - admin-v2
  - api
  - portal

stages:
- stage: ${{ parameters.stageName }}
  displayName: ${{ parameters.stageDisplayName }}
  # Run if detectChanges ran successfully
  dependsOn: 
  - Changed  
  - ${{ if eq(parameters.stageName, 'UnitTests') }}:
    - BuildDev
  - ${{ if eq(parameters.stageName, 'IntegrationTests') }}:
    - BuildDev
    - UnitTests
  condition: succeeded()
  jobs:
  # Runs for all other stages

  - ${{ each service in parameters.services }}:
    - template: docker.yaml
      parameters:
        service: ${{ service }}
        stageName: ${{ parameters.stageName }}
        jobName: ${{ service }}${{ parameters.stageName }}
        jobDisplayName: Run ${{ parameters.phrase }} for ${{ service }} service...
        taskDisplayName: Run ${{ service }} ${{ parameters.phrase }} tasks...
        dockerCommand: ${{ parameters.dockerCommand }}
        target: ${{ parameters.target }}
        tag: ${{ parameters.tag }}
</code></pre>
<pre><code># docker.yaml
parameters:
- name: stageName
  default: ''
- name: service
  default: ''
- name: jobName
  default: ''
- name: jobDisplayName
  default: ''
- name: taskDisplayName
  default: ''
- name: dockerCommand
  default: ''
- name: target
  default: ''
- name: tag
  default: ''

jobs:
- job: 
  displayName: ${{ parameters.jobDisplayName }}
  # Handle whether to run for service or not
  variables:
    servicesChanged: $[ stageDependencies.Changed.Changes.outputs['detectChanges.servicesChanged'] ]
  condition: or(contains(variables['servicesChanged'], '${{ parameters.service }}'), eq(variables['Build.Reason'], 'Manual'))
  steps: 
  # Set to app repo
  - checkout: app

  # Create mysecrets.txt primarily for Django system check
  - bash: |
      printenv &gt;&gt; $(dockerFilePath)/${{ parameters.service }}/mysecrets.txt
    displayName: Create mysecrets.txt for ${{ parameters.service }}
    env:
      DJANGO_SECRET_KEY: $(DJANGO_SECRET_KEY)

  - ${{ if not(eq(parameters.stageName, 'BuildDev')) }}:
    # Run the Docker task
    - task: Docker@2
      inputs:
        containerRegistry: $(dockerRegistryServiceConnection)
        command: login

    - script: docker pull $(containerRegistry)/$(imageRepository)-${{ parameters.service }}:latest
      displayName: Pull latest for layer caching
      continueOnError: true # for first build, no cache

    - task: Docker@2
      # Run if there have been changes
      displayName: ${{ parameters.taskDisplayName }}
      inputs:
        command: ${{ parameters.dockerCommand }}
        repository: $(imageRepository)-${{ parameters.service }}
        dockerfile: $(dockerFilePath)/${{ parameters.service }}/docker/Dockerfile
        buildContext: $(dockerFilePath)/${{ parameters.service }}
        containerRegistry: $(dockerRegistryServiceConnection)
        arguments: |
          --target ${{ parameters.target }} 
          --cache-from=$(containerRegistry)/$(imageRepository)-${{ parameters.service }}:latest
        tags: |
          ${{ parameters.tag }}-$(Build.BuildNumber)
      env:
        DOCKER_BUILDKIT: 1

  - ${{ if eq(parameters.stageName, 'BuildDev') }}:
    - task: Docker@2
      # Run if there have been changes
      displayName: ${{ parameters.taskDisplayName }}
      inputs:
        command: ${{ parameters.dockerCommand }}
        repository: $(imageRepository)-${{ parameters.service }}
        dockerfile: $(dockerFilePath)/${{ parameters.service }}/docker/Dockerfile
        buildContext: $(dockerFilePath)/${{ parameters.service }}
        containerRegistry: $(dockerRegistryServiceConnection)
        arguments: --target ${{ parameters.target }}
        tags: |
          ${{ parameters.tag }}
      env:
        DOCKER_BUILDKIT: 1
    - task: Docker@2
      displayName: Pushing ${{ parameters.service }} ${{ parameters.tag }} to ACR
      inputs:
        command: push
        repository: $(imageRepository)-${{ parameters.service }}      
        containerRegistry: $(dockerRegistryServiceConnection)
        tags: |
          ${{ parameters.tag }}
</code></pre>
<p>The <code>stageName</code> <code>BuildDev</code> is where the <code>development</code> stage would be built.</p>
<p>Everything runs successfully. The task where the image is pulled shows it being pulled, then task where <code>--target unit-tests</code> runs shows <code>importing cache manifest from ***/app-admin:dev-20211030.11</code>, but it still builds the <code>development</code> and preceeding stages. It pulls it, sees it's there, and decides to build it anyways.</p>
<p>Here are those logs:</p>
<pre><code># Pull Job
2021-11-02T23:29:33.0494768Z ##[section]Starting: Pull latest for layer caching
2021-11-02T23:29:33.0502467Z ==============================================================================
2021-11-02T23:29:33.0502844Z Task         : Command line
2021-11-02T23:29:33.0503204Z Description  : Run a command line script using Bash on Linux and macOS and cmd.exe on Windows
2021-11-02T23:29:33.0503544Z Version      : 2.182.0
2021-11-02T23:29:33.0504030Z Author       : Microsoft Corporation
2021-11-02T23:29:33.0504416Z Help         : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/command-line
2021-11-02T23:29:33.0504832Z ==============================================================================
2021-11-02T23:29:33.2083789Z Generating script.
2021-11-02T23:29:33.2098563Z Script contents:
2021-11-02T23:29:33.2099499Z docker pull ***/app-admin-v2:latest
2021-11-02T23:29:33.2100315Z ========================== Starting Command Output ===========================
2021-11-02T23:29:33.2155259Z [command]/usr/bin/bash --noprofile --norc /home/vsts/work/_temp/5e7263fa-2853-4e6d-b303-62fe80cfacdc.sh
2021-11-02T23:29:34.5925241Z latest: Pulling from app-admin-v2
2021-11-02T23:29:34.5933140Z b380bbd43752: Pulling fs layer
2021-11-02T23:29:34.5933539Z 8d36a6ce056a: Pulling fs layer
2021-11-02T23:29:34.5933881Z f54546b42be1: Pulling fs layer
2021-11-02T23:29:34.5934203Z f5bd69d20a35: Pulling fs layer
2021-11-02T23:29:34.5934568Z 21494383f180: Pulling fs layer
2021-11-02T23:29:34.5934902Z 87500a3a7192: Pulling fs layer
2021-11-02T23:29:34.5935238Z debc4a9f3725: Pulling fs layer
2021-11-02T23:29:34.5935558Z 1b67e176d924: Pulling fs layer
2021-11-02T23:29:34.5935890Z d603a960b591: Pulling fs layer
2021-11-02T23:29:34.5936223Z 9e85221572ee: Pulling fs layer
2021-11-02T23:29:34.5943277Z f5bd69d20a35: Waiting
2021-11-02T23:29:34.5943992Z 21494383f180: Waiting
2021-11-02T23:29:34.5944321Z 87500a3a7192: Waiting
2021-11-02T23:29:34.5944642Z debc4a9f3725: Waiting
2021-11-02T23:29:34.5944958Z 1b67e176d924: Waiting
2021-11-02T23:29:34.5945246Z d603a960b591: Waiting
2021-11-02T23:29:34.5945573Z 9e85221572ee: Waiting
2021-11-02T23:29:34.9794967Z 8d36a6ce056a: Verifying Checksum
2021-11-02T23:29:34.9799329Z 8d36a6ce056a: Download complete
2021-11-02T23:29:35.6335949Z f5bd69d20a35: Verifying Checksum
2021-11-02T23:29:35.6337075Z f5bd69d20a35: Download complete
2021-11-02T23:29:35.8084539Z b380bbd43752: Verifying Checksum
2021-11-02T23:29:35.8120185Z b380bbd43752: Download complete
2021-11-02T23:29:35.9459756Z 21494383f180: Verifying Checksum
2021-11-02T23:29:35.9460303Z 21494383f180: Download complete
2021-11-02T23:29:35.9926957Z f54546b42be1: Verifying Checksum
2021-11-02T23:29:35.9927391Z f54546b42be1: Download complete
2021-11-02T23:29:36.1820048Z 87500a3a7192: Verifying Checksum
2021-11-02T23:29:36.1820481Z 87500a3a7192: Download complete
2021-11-02T23:29:36.4513965Z 1b67e176d924: Verifying Checksum
2021-11-02T23:29:36.4514451Z 1b67e176d924: Download complete
2021-11-02T23:29:37.1143768Z d603a960b591: Verifying Checksum
2021-11-02T23:29:37.1144264Z d603a960b591: Download complete
2021-11-02T23:29:37.3920871Z b380bbd43752: Pull complete
2021-11-02T23:29:38.0559222Z 9e85221572ee: Verifying Checksum
2021-11-02T23:29:38.0559774Z 9e85221572ee: Download complete
2021-11-02T23:29:38.5139277Z debc4a9f3725: Verifying Checksum
2021-11-02T23:29:38.5140203Z debc4a9f3725: Download complete
2021-11-02T23:29:39.0212051Z 8d36a6ce056a: Pull complete
2021-11-02T23:29:40.9828384Z f54546b42be1: Pull complete
2021-11-02T23:29:41.1410341Z f5bd69d20a35: Pull complete
2021-11-02T23:29:41.2067833Z 21494383f180: Pull complete
2021-11-02T23:29:41.2833611Z 87500a3a7192: Pull complete
2021-11-02T23:29:54.5480084Z debc4a9f3725: Pull complete
2021-11-02T23:29:54.6097840Z 1b67e176d924: Pull complete
2021-11-02T23:29:54.6823771Z d603a960b591: Pull complete
2021-11-02T23:30:04.3756447Z 9e85221572ee: Pull complete
2021-11-02T23:30:04.3801963Z Digest: sha256:64308db1d461a2aff0deaf31b5bb5694becfb2298f0c474366d1d9b695b0a441
2021-11-02T23:30:04.3836112Z Status: Downloaded newer image for ***/app-admin-v2:latest
2021-11-02T23:30:04.3874744Z ***/app-admin-v2:latest
2021-11-02T23:30:04.4026099Z ##[section]Finishing: Pull latest for layer caching
</code></pre>
<pre><code># Build Job
2021-11-02T23:30:08.6626317Z [command]/usr/bin/docker build -f /home/vsts/work/1/s/admin-v2/docker/Dockerfile --label com.azure.dev.image.system.teamfoundationcollectionuri=https://dev.azure.com/thecompany/ --label com.azure.dev.image.system.teamproject=-dev --label com.azure.dev.image.build.repository.name=production-resources --label com.azure.dev.image.build.sourceversion=809969a7bb0880a135c935c5d66ea0e2bba2c65e --label com.azure.dev.image.build.repository.uri=https://thecompany@dev.azure.com/thecompany/-dev/_git/production-resources --label com.azure.dev.image.build.sourcebranchname=main --label com.azure.dev.image.build.definitionname= App PR --label com.azure.dev.image.build.buildnumber=20211102.3 --label com.azure.dev.image.build.builduri=vstfs:///Build/Build/1322 --label image.base.ref.name=nginx --label image.base.digest=sha256:644a70516a26004c97d0d85c7fe1d0c3a67ea8ab7ddf4aff193d9f301670cf36 --target unit-tests --cache-from=***/app-admin-v2:latest -t ***/app-admin-v2:ut-20211102.3-20211102.3 /home/vsts/work/1/s/admin-v2
2021-11-02T23:30:08.9603622Z #1 [internal] load build definition from Dockerfile
2021-11-02T23:30:08.9604133Z #1 sha256:7818e7e1291667e1af9ce6f8a463d74e3df7b64001596dd00b927ccc12c37515
2021-11-02T23:30:08.9604573Z #1 transferring dockerfile: 1.05kB done
2021-11-02T23:30:08.9604904Z #1 DONE 0.0s
2021-11-02T23:30:08.9605027Z 
2021-11-02T23:30:08.9605303Z #2 [internal] load .dockerignore
2021-11-02T23:30:08.9605713Z #2 sha256:1c18692a923cc3e70a98431aefc897940bf0c36edf7ae0f3b0b525b4d753b7fb
2021-11-02T23:30:08.9606117Z #2 transferring context: 329B done
2021-11-02T23:30:08.9607436Z #2 DONE 0.0s
2021-11-02T23:30:08.9607554Z 
2021-11-02T23:30:08.9608532Z #3 [internal] load metadata for docker.io/library/node:16-slim
2021-11-02T23:30:08.9609018Z #3 sha256:faa605aa367b596b57bbdc1bdcccade69c92d97d03d44e595a34c7e28b8d594e
2021-11-02T23:30:10.1243750Z #3 DONE 1.2s
2021-11-02T23:30:10.1243963Z 
2021-11-02T23:30:10.1245311Z #12 importing cache manifest from ***/app-admin-v2:latest
2021-11-02T23:30:10.1245833Z #12 sha256:91a404777043fddf396dcad59a4fd8b976e0224c77d860e00947ec3630b83eaf
2021-11-02T23:30:10.1246215Z #12 DONE 0.0s
2021-11-02T23:30:10.1246341Z 
2021-11-02T23:30:10.1246618Z #4 [internal] load build context
2021-11-02T23:30:10.1247014Z #4 sha256:e1bc60dd1feb9ca2db3a89f6b76ec616e7b56215986652ad691e1fc4c108a5aa
2021-11-02T23:30:10.1247447Z #4 transferring context: 713.43kB 0.0s done
2021-11-02T23:30:10.1247777Z #4 DONE 0.0s
2021-11-02T23:30:10.1247897Z 
2021-11-02T23:30:10.1254657Z #11 [node-base 1/1] FROM docker.io/library/node:16-slim@sha256:9ec1ff69c844f2de3a6a2180cd49ca75797d9f2a0fc52bb33c8a672fd0fe7e18
2021-11-02T23:30:10.1255382Z #11 sha256:af5e5b9d07d96a94506820483ad64d714f1bf9a0e5ae75b7b4e7265902c9f941
2021-11-02T23:30:10.1256263Z #11 resolve docker.io/library/node:16-slim@sha256:9ec1ff69c844f2de3a6a2180cd49ca75797d9f2a0fc52bb33c8a672fd0fe7e18 done
2021-11-02T23:30:10.1256894Z #11 sha256:9ec1ff69c844f2de3a6a2180cd49ca75797d9f2a0fc52bb33c8a672fd0fe7e18 1.21kB / 1.21kB done
2021-11-02T23:30:10.1257454Z #11 sha256:ed230d53c9d9820caa9b1bea418c1f835d15ec4d1253160e908ff31fe074ac35 1.37kB / 1.37kB done
2021-11-02T23:30:10.1258009Z #11 sha256:dd74f260f56dccc771f512ef5b2a81345e3bcefcac34c248459da36169be36b2 6.89kB / 6.89kB done
2021-11-02T23:30:10.1258404Z #11 DONE 0.1s
2021-11-02T23:30:10.2748114Z 
2021-11-02T23:30:10.2749533Z #5 [builder-base 1/2] COPY ./package-lock.json ./package.json ./
2021-11-02T23:30:10.2774757Z #5 sha256:e5803272aeaf38a29bf5ca34e14cc0c613c673044fdab9a2c27d837bb2de837c
2021-11-02T23:30:10.2775425Z #5 DONE 0.0s
2021-11-02T23:30:10.2775692Z 
2021-11-02T23:30:10.2776552Z #6 [builder-base 2/2] RUN npm ci --production
2021-11-02T23:30:10.2777798Z #6 sha256:30a22a0c38f1eebba7d10ab9f4cd8f24ce6a4599827350e6b42f38836af226ab
2021-11-02T23:30:12.6879927Z #6 2.477 npm WARN old lockfile 
2021-11-02T23:30:12.6881199Z #6 2.478 npm WARN old lockfile The package-lock.json file was created with an old version of npm,
2021-11-02T23:30:12.6881732Z #6 2.478 npm WARN old lockfile so supplemental metadata must be fetched from the registry.
2021-11-02T23:30:12.6882137Z #6 2.478 npm WARN old lockfile 
2021-11-02T23:30:12.6883737Z #6 2.479 npm WARN old lockfile This is a one-time fix-up, please be patient...
2021-11-02T23:30:12.6884195Z #6 2.479 npm WARN old lockfile 
...
</code></pre>
<p><strong>Any ideas why this might be happening and how to prevent it?</strong> Really is slowing things down.</p>
",https://stackoverflow.com/questions/69782647/work-around-for-docker-layer-caching-not-working-in-azure-pipeline,"['docker', 'azure-devops', 'azure-pipelines', 'azure-pipelines-yaml', 'azure-pipelines-tasks']",1533,True,2,3
How to pass arguments from github actions to unit tests in rust,"<p>I would like to use <em>github secrets</em> to inject a secret API key into my unit testing functions to prevent having ay API key within the source:</p>
<p>My (simplfied) test is defining the APIKEY as string constant.</p>
<pre class=""lang-rust prettyprint-override""><code>const APIKEY: &amp;str = &quot;ddbe2befdeadbeefa2d20f09b4a694&quot;;

#[test]
fn test_apikey() {
    assert!( usekey(APIKEY).is_ok() );
}
</code></pre>
<p>Now I would like to get the API-key from the arguments which the test executable gets when I run:</p>
<pre><code>&gt; cargo test -- ddbe2befdeadbeefa2d20f09b4a694&quot;;
</code></pre>
<p>But while I tried to use the following code to get the first argument with:</p>
<pre class=""lang-rust prettyprint-override""><code>let args: Vec&lt;String&gt; = env::args().collect();
let apikey = &amp;args[1];
</code></pre>
<p>I realized that my tests won't be processed any more whenever I give an argument to <code>cargo test --</code>.</p>
<p>Here is the call without giving arguments:</p>
<pre><code>▶ cargo test -v --                                 
[..]
    Finished test [unoptimized + debuginfo] target(s) in 0.05s
     Running `/home/pat/git/myprg/target/debug/deps/myrg-7e0bdeadbeef95ff`

running 7 tests
test tests::test_cityid ... ok
test tests::test_coordinate ... ok
test tests::test_apikey ... ok
test tests::test_city ... ok
test tests::test_language ... ok
test tests::test_units ... ok
test tests::test_cities ... ok

test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
</code></pre>
<p>But no test will be processed when I try to give the apikey in an argument to the tests:</p>
<pre><code>▶ cargo test -v -- ddbe2befdeadbeefa2d20f09b4a694                                 
[..]
    Finished test [unoptimized + debuginfo] target(s) in 0.05s
     Running `/home/pat/git/myprg/target/debug/deps/myprg-7e0bdeadbeef95ff ddbe2befdeadbeefa2d20f09b4a694&quot;;`

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 7 filtered out
</code></pre>
<p>One can see that the test was correctly called with the apikey attached.</p>
<p>I do not understand why this happens and diving into rust tests documentation did not lead me to something useful.</p>
<p>Do you have any tips?</p>
",https://stackoverflow.com/questions/67593012/how-to-pass-arguments-from-github-actions-to-unit-tests-in-rust,"['testing', 'rust', 'arguments', 'github-actions', 'github-secret']",305,True,2,1
How to Mock calls to boost.asio library?,"<p>I need to develop a c++ class that will act as a client for a TCP Server, lets call it myManager, this class will espose a few methods:</p>
<ul>
<li>connect()</li>
<li>disconnect()</li>
<li>send_command(std::string msg)</li>
<li>getStatus()</li>
<li>ecc.</li>
</ul>
<p>All this methods will perform some operations, like for example set some internal variables, call boost::asio::ip::tcp functions to perform the real work, finally the method will check the return value from the boost::asio::ip::tcp calls, update some more internal variables based on the result of the call to boost::asio and complete.
How can I mock this function calls in order to perform unit testing in the most efficient way?
Writing a mock implementation of the boost.asio library seems a bit overkill.</p>
<p>Notice that:</p>
<ul>
<li>I'm using turtle as a mocking framework but it does not seem to support this functionality, since it only supports mock_objects.</li>
<li>I do not want to add an internal object to myManager in order to wrap the calls to boost.asio.</li>
</ul>
",https://stackoverflow.com/questions/69269690/how-to-mock-calls-to-boost-asio-library,"['c++', 'boost', 'mocking', 'turtle-mock']",704,False,2,1
How to correctly mock mongoDb with XUnit in C#?,"<p><strong>Problem:</strong></p>
<p>I am new to writing unit testing in c# using xunit. So I am trying to mock the MongoDB connection. In my project I have use repository pattern there I have used unit of work class like this. so I am accessing every repository via it. so the unit of work class code is here.</p>
<pre><code>namespace QuestionBank.API.Repositories
{
    public class UnitOfWork : IUnitOfWork
    {
        public readonly IQuestionsBankDBContext _context;

        private readonly ILogger&lt;UnitOfWork&gt; _logger;

        private Dictionary&lt;Type, object&gt; repositories;

        private IQuestionsRepository _questionsRepository;

        private ICampaignQuestionsRepository _campaignQuestionsRepository;

        private ICandidateAnswerRepository _candidateAnswerRepository;

        private IIntergrationEventLogRepository _integrationEventLogRepository;

        private IControlRepository _controlRepository;


        public UnitOfWork(IQuestionsBankDBContext context, ILogger&lt;UnitOfWork&gt; logger)
        {
            _context = context;
            _logger = logger;
        }

        public IQuestionsRepository QuestionsRepository
        {
            get
            {
                this._questionsRepository = new QuestionsRepository(_context as IQuestionsBankDBContext, this, _logger);
                return this._questionsRepository;
            }
        }

        public ICandidateAnswerRepository CandidateAnswerRepository
        {
            get
            {
                this._candidateAnswerRepository = new CandidateAnswerRepository(_context as IQuestionsBankDBContext, this, _logger);
                return this._candidateAnswerRepository;
            }
        }

        public ICampaignQuestionsRepository CampaignQuestionsRepository
        {
            get
            {
                this._campaignQuestionsRepository = new CampaignQuestionsRepository(_context as IQuestionsBankDBContext, this, _logger);
                return this._campaignQuestionsRepository;
            }
        }

        public IIntergrationEventLogRepository IntegrationEventLogRepository
        {
            get
            {
                this._integrationEventLogRepository = new IntergrationEventLogRepository(_context as IQuestionsBankDBContext, this, _logger);
                return this._integrationEventLogRepository;
            }
        }

        public IControlRepository ControlRepository
        {
            get
            {
                this._controlRepository = new ControlRepository(_context as IQuestionsBankDBContext, this, _logger);
                return this._controlRepository;
            }
        }

        public IGenericRepository&lt;TDocument&gt; GetRepository&lt;TDocument&gt;() where TDocument : IDocument
        {
            if (this.repositories == null)
            {
                this.repositories = new Dictionary&lt;Type, object&gt;();
            }

            var type = typeof(TDocument);
            if (!this.repositories.ContainsKey(type))
            {
                this.repositories[type] = new GenericRepository&lt;TDocument&gt;(_context);
            }

            return (IGenericRepository&lt;TDocument&gt;)this.repositories[type];
        }
    }
}
</code></pre>
<p>So in the unit test to mock services and repositories, I need to pass database context to unitofwork. I tried it this way.</p>
<pre><code>var mockDbContext = new Mock&lt;QuestionsBankDBContext&gt;();
var dbContext = mockDbContext.Object;
var mock = new Mock&lt;ILogger&lt;UnitOfWork&gt;&gt;();
_logger = mock.Object;
unitOfWork = new UnitOfWork(dbContext, _logger);

questionsService = new QuestionsService(unitOfWork);
campaignQuestionsService = new CampaignQuestionsService(unitOfWork);
tokenService = new TokenService();

stringLocalizer = new Mock&lt;IStringLocalizer&lt;SharedResource&gt;&gt;();

questionBankIntergrationEventService = new Mock&lt;IQuestionBankIntergrationEventService&gt;();

questionsController = new QuestionsController(questionsService, campaignQuestionsService, stringLocalizer.Object, tokenService, questionBankIntergrationEventService.Object);

contextMock = new Mock&lt;HttpContext&gt;();
</code></pre>
<p>And this is my DB context class.</p>
<pre><code>using MongoDB.Driver;
using QuestionBank.API.Models;

namespace QuestionBank.API.Data
{
    public class QuestionsBankDBContext : IQuestionsBankDBContext
    {
        public IMongoClient Client { get; set; }
        public IMongoDatabase Database { get; set; }


        public QuestionsBankDBContext(IQuestionBankDatabaseSettings settings)
        {
            Client = new MongoClient(settings.ConnectionString);
            Database = Client.GetDatabase(settings.DatabaseName);
        }
    }
}
</code></pre>
<p>Then I wrote a unit test like this.</p>
<pre><code>[Theory]
[InlineData(&quot;61879e54e86be1fa5e41831f&quot;)]
[InlineData(&quot;61879e54e86be1fa5e41831e&quot;)]
public async Task GetQuestionById(string questionId)
{
    var actionResult = await questionsController.GetQuestionById(questionId);
    var result = actionResult as ObjectResult;
    Assert.NotNull(result.Value);
    if (result.StatusCode == (int)System.Net.HttpStatusCode.OK)
    {
        Assert.IsType&lt;Questions&gt;(result.Value);
    }
    else if (result.StatusCode == (int)System.Net.HttpStatusCode.NotFound)
    {
        Assert.Contains(&quot;ErrorCode&quot;, result.Value.ToString());
    }
    else if (result.StatusCode == (int)System.Net.HttpStatusCode.InternalServerError)
    {
        var code = (int)ErroCodes.InternalServerError;
        Assert.Contains(code.ToString(), result.Value.ToString());
    }
}
</code></pre>
<p>Then when running this it gives
<a href=""https://i.stack.imgur.com/5oLEp.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/5oLEp.png"" alt=""enter image description here"" /></a></p>
<p>And my question controller GetQuestionById is like this.</p>
<pre><code>[HttpGet]
//[Authorize(Roles = &quot;SuperAdmin,Admin&quot;)]
[Route(&quot;getquestionbyidfrombank&quot;)]
[ProducesResponseType(typeof(Questions), 200)]
[ProducesResponseType(typeof(string), 404)]
[ProducesResponseType(typeof(string), 500)]
public async Task&lt;IActionResult&gt; GetQuestionById([FromQuery] string questionId)
{
    try
    {
        string errorText;
        if (!string.IsNullOrEmpty(questionId))
        {
            var question = await 
            questionsService.GetQuestionById(questionId);
            return Ok(question);
        }
        else
        {
            errorText = string.Format(stringLocalizer[Constants.ErrorCodeString],
        (int)ErroCodes.SpecifiedItemNotFound,
        stringLocalizer[Helper.ToEnumString(ErroCodes.SpecifiedItemNotFound)]);

            return StatusCode(404, errorText);
        }
    }
    catch (Exception ex)
    {
        string exceptionData =
        $&quot;Exception occured while getiing question by id. &quot; +
        $&quot;\nException Data: Message- {ex.Message}; &quot; +
        $&quot;InnerException- {ex.InnerException}; StackTrace- {ex.StackTrace}&quot;;

        string errorText = string.Format(stringLocalizer[Constants.ErrorCodeString],
            (int)ErroCodes.InternalServerError,
            stringLocalizer[Helper.ToEnumString(ErroCodes.InternalServerError)]);

        return StatusCode(500, errorText);
    }
}
</code></pre>
<p>this is how I do the service instantiation.</p>
<pre><code>    public QuestionsService(IUnitOfWork unitOfWork)
    {
       _unitOfWork = unitOfWork;
    }
</code></pre>
<p>Get question by id function</p>
<pre><code>public async Task&lt;Questions&gt; GetQuestionById(string id)
{
    var question = await _unitOfWork.QuestionsRepository.FindByIdAsync(id);
    return question;
}
</code></pre>
<p>Can someone help me to write this unit test correctly and solve this issue. I tried a lot to find out a way to do this but I could not able to do it. Thank you</p>
",https://stackoverflow.com/questions/69960520/how-to-correctly-mock-mongodb-with-xunit-in-c,"['c#', 'mongodb', 'unit-testing']",1345,True,2,2
JUnit test for a method that contains SQL queries,"<p>I have an old Java project (no frameworks/build tools used) that has a class full of SQL methods and corresponding Bean-classes. The SQL methods mostly use SELECT, INSERT and UPDATE queries like this:</p>
<pre class=""lang-java prettyprint-override""><code>public static void sqlUpdateAge(Connection dbConnection, int age, int id) {

    PreparedStatement s = null;
    ResultSet r = null;

    String sql = &quot;UPDATE person SET age = ? WHERE id = ?&quot;;

    try {
        s = dbConnection.prepareStatement(sql);
        s.setInt(1, age);
        s.setInt(2, id);
        s.addBatch();
        s.executeBatch();

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (r != null)
                r.close();
            if (s != null)
                s.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
</code></pre>
<p>What is the best practice in unit testing when it comes to SQL queries?</p>
<p>The easiest way I can think of, would be to use my development database; just call the sqlUpdateAge() in the test class, query the database for a result set and assertTrue that the set age is in the result set. However, this would fill up the development database with unnecessary data, and I would like to avoid that.</p>
<p>Is the solution to create a so-called in-memory database or somehow rollback the changes I made?</p>
<p>If I need an in-memory database:</p>
<ol>
<li>Where and how would I create it? Straight to the test class, or perhaps to a config file?</li>
<li>How do I pass it to the updateAge() method?</li>
</ol>
",https://stackoverflow.com/questions/69916590/junit-test-for-a-method-that-contains-sql-queries,"['java', 'sql', 'unit-testing', 'junit', 'h2']",1457,True,1,2
"Unit Testing Events in Laravel 8 throw EventFake::__construct() must implement interface Illuminate\Contracts\Events\Dispatcher, null given","<p>I'm trying to fake an event using Unit Testing, so no DB, no Application, just pure classes.</p>
<p>I'm following the documentation for Laravel 8, my current version, but I'm still getting the error</p>
<pre><code>1) Tests\Unit\HandShake\ConfirmApplicationHandShakeActionTest::BasedOnAnExistentAppIConfirmTheHandShake
TypeError: Argument 1 passed to Illuminate\Support\Testing\Fakes\EventFake::__construct() must implement interface Illuminate\Contracts\Events\Dispatcher, null given, called in /Users/pablo/Workspace/xxxx/vendor/laravel/framework/src/Illuminate/Support/Facades/Event.php on line 38
</code></pre>
<p>As you can see is asking for an object implementing the interface Dispatch, my Event has the trait dispatch, but anyways here it says that I'm passing <code>null</code></p>
<p>My Test code is the one as follow</p>
<pre><code>&lt;?php

namespace Tests\Unit\HandShake;

use App\Actions\ConfirmApplicationHandShakeAction;
use App\Events\HandShakeReceivedEvent;
use App\Exceptions\NotFoundApplicationException;
use App\Models\Application;
use Illuminate\Support\Facades\Event;
use Mockery\MockInterface;
use Mockery;

use PHPUnit\Framework\TestCase;

class ConfirmApplicationHandShakeActionTest extends TestCase
{

    /**
     *
     * @test
     * @throws NotFoundApplicationException
     */
    public function BasedOnAnExistentAppIConfirmTheHandShake()
    {

        $appName = 'testDummy';

        Event::fake([HandShakeReceivedEvent::class]);

        $applicationModel = Mockery::mock(Application::class, function (MockInterface $mock) {
            $mock-&gt;shouldReceive('exists')
                -&gt;andReturn(true)
                -&gt;once();
        });
        $confirmation = new ConfirmApplicationHandShakeAction($applicationModel);
        $confirmation-&gt;execute($appName);
</code></pre>
<p>The Class that I'm testing is</p>
<pre><code>    &lt;?php
declare(strict_types=1);

namespace App\Actions;

use App\Events\HandShakeReceivedEvent;

use App\Exceptions\NotFoundApplicationException;
use App\Models\Application;


/**
 * Class ConfirmApplicationHandShakeAction
 * @package App\Actions
 */
class ConfirmApplicationHandShakeAction
{
    /**
     * @var Application
     */
    private $application;

    /**
     * ConfirmApplicationHandShakeAction constructor.
     * @param Application $application
     */
    public function __construct(Application $application)
    {
        $this-&gt;application = $application;
    }

    /**
     * @param string $appName
     * @throws NotFoundApplicationException
     */
    public function execute(string $appName)
    {

        if ( ! $this-&gt;application-&gt;exists($appName)) {
            throw new NotFoundApplicationException('The Application do not exists or is not active');
        }

        HandShakeReceivedEvent::dispatch($appName);
    }
}
</code></pre>
<p>Lastly the event is</p>
<pre><code>    &lt;?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class HandShakeReceivedEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}
</code></pre>
<p>Probably is one of those moments where I'm missing a stupid character, but I went through this error, and I cannot find the right solution.</p>
<p><strong>UPDATE</strong></p>
<p>I keep digging and I found that the getFacadeRoot() is returning null, so I'm assuming that something is not properly initialized, still not clue</p>
<p>static::swap($fake = new EventFake(static::getFacadeRoot(), $eventsToFake));</p>
<p>Thank you in advance if you find the issue or can point me in the right direction. I also tried FakeFor and Fake without sending the event as a parameter</p>
",https://stackoverflow.com/questions/66105051/unit-testing-events-in-laravel-8-throw-eventfake-construct-must-implement-i,['laravel'],1049,True,1,1
de.flapdoodle.embed.mongo fails on GitLab CI,"<p>I have a Spring Boot 2 application running some unit testing using Embendded Mongo (de.flapdoodle.embed.mongo).</p>
<p>The tests when I run locally using
<code>/gradlew clean build</code>
It runs normally.</p>
<p>However, when the same application is built on GitLab CI/CD I find the following error:</p>
<blockquote>
<p>WafiraApplicationTests &gt; contextLoads() FAILED
java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at
ConstructorResolver.java:800
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at
ConstructorResolver.java:800
Caused by: org.springframework.beans.factory.BeanCreationException at
BeanDefinitionValueResolver.java:342
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at
ConstructorResolver.java:800
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException at
ConstructorResolver.java:800
Caused by: org.springframework.beans.factory.BeanCreationException at
AbstractAutowireCapableBeanFactory.java:1786
Caused by: java.io.IOException at ProcessBuilder.java:1142
Caused by: java.io.IOException at ProcessImpl.java:-2 DepositRepositoryTest &gt; save() FAILED
java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
Caused by: org.springframework.beans.factory.BeanCreationException at
AbstractAutowireCapableBeanFactory.java:1786
Caused by: java.io.IOException at ProcessBuilder.java:1142
Caused by: java.io.IOException at ProcessImpl.java:-2 TransferRepositoryTest &gt; save() FAILED
java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:132
Caused by: org.springframework.beans.factory.BeanCreationException at
AbstractAutowireCapableBeanFactory.java:1786
Caused by: java.io.IOException at ProcessBuilder.java:1142
Caused by: java.io.IOException at ProcessImpl.java:-2 ClientRepositoryTest &gt; findByClientEmail() FAILED</p>
</blockquote>
<p>This is an example of one test case below:</p>
<pre><code>@DataMongoTest
public class DepositRepositoryTest {

@Autowired
private DepositRepository depositRepository;

@Test
void save(){
    var deposit = DataGenerator.getDeposityEntityWithFixedValues();

    depositRepository.save(deposit);

    AtomicInteger atomicInteger = new AtomicInteger(0);
    depositRepository.findAll().forEach(it -&gt; atomicInteger.addAndGet(1));

    assertThat(atomicInteger.get()).isEqualTo(1);

}
</code></pre>
<p>Any ideas?</p>
",https://stackoverflow.com/questions/69746321/de-flapdoodle-embed-mongo-fails-on-gitlab-ci,"['mongodb', 'spring-boot', 'gitlab-ci']",191,False,1,0
Angular unit testing doesn&#39;t recognise an extension method when used in a very specific place,"<p>While using an already existing project as a POC for unit testing, I encountered a problem at compilation time only when running tests.</p>
<p>I have a couple of <code>string</code> extension functions with custom title case and whatnot, but one of these which is meant for removing characters from a string is used in a <code>string</code> utilities class, in a method for cleaning up separator characters from document IDs (such as dots and dashes).</p>
<p>This works perfectly when running Angular application, but the Testing API seems to not be able to find it at that point. If the extension method is used directly in the component, it works as expected, so I know it's not a coding issue.</p>
<p>What could I be doing wrong?</p>
<p>The error (which doesn't happen when running the project. Only when running tests):</p>
<p><a href=""https://i.stack.imgur.com/LeaJn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/LeaJn.png"" alt=""Error message"" /></a></p>
<p><code>string-extensions.ts</code> (only relevant code):</p>
<pre class=""lang-js prettyprint-override""><code>export {};

declare global {
  interface String {
    /**
     * Remove a/s string/s passada/s por parâmetro desta string
     * @param text string/s a ser/em removida/s
     */
    emRemove(...text: string[]): string;
  }
}

String.prototype.emRemove = function(...text: string[]) {
  let retorno = this;
  if (text &amp;&amp; text.length &gt; 0) {
    text.forEach(t =&gt; {
      retorno = retorno.split(t).join('');
    });
  }
  return retorno;
};
</code></pre>
<p><code>string-utils.ts</code> (only relevant code):</p>
<pre class=""lang-js prettyprint-override""><code>export default class StringUtils {
  /**
   * Remove caracteres separadores de documentos e retorna somente o código
   * @param documento valor a ser limpo
   */
  static getDocumentoLimpo(documento: string): string {
    if (this.isNotEmpty(documento)) { // this tests undefined, null only whitespace and actual empty string without using the sometimes misleading falsy
      return documento.emRemove('-', '/', '.');
    }
    return '';
  }
}
</code></pre>
<p>Project structure:</p>
<p><a href=""https://i.stack.imgur.com/I92YU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/I92YU.png"" alt=""Project structure"" /></a></p>
<p>Edit:</p>
<p><code>angular.json</code> (only the projects.architect.test part. If more parts are needed, please ask):</p>
<pre class=""lang-json prettyprint-override""><code>        &quot;test&quot;: {
          &quot;builder&quot;: &quot;@angular-devkit/build-angular:karma&quot;,
          &quot;options&quot;: {
            &quot;main&quot;: &quot;src/test.ts&quot;,
            &quot;polyfills&quot;: &quot;src/polyfills.ts&quot;,
            &quot;tsConfig&quot;: &quot;tsconfig.spec.json&quot;,
            &quot;karmaConfig&quot;: &quot;karma.conf.js&quot;,
            &quot;assets&quot;: [
              &quot;src/favicon.ico&quot;,
              &quot;src/assets&quot;
            ],
            &quot;styles&quot;: [
              &quot;src/styles.scss&quot;
            ],
            &quot;scripts&quot;: []
          }
        },
</code></pre>
",https://stackoverflow.com/questions/66673293/angular-unit-testing-doesnt-recognise-an-extension-method-when-used-in-a-very-s,"['angular', 'unit-testing', 'compilation', 'karma-jasmine', 'extension-methods']",571,True,1,1
Enzyme mount does not re-render the updated components on props change,"<p>I have one parent component people_form.js with three input fields
a. first_name
b. last_name
c. date_of_birth</p>
<pre><code>// people_form.js

import { fetch } from &quot;request&quot;;

fetchDuplicateRecords() {
    const {
      first_name,
      last_name,
      date_of_birth,
    } = this.state;

    if (first_name &amp;&amp; last_name &amp;&amp; date_of_birth) {
      const searchParams = {
        first_name: first_name,
        last_name: last_name,
        date_of_birth: date_of_birth,
      };

      // url is fetched in other code.
      fetch(url, searchParams)
        .then(
          (response) =&gt; {
            this.setState({
              duplicateRecords: response,
            });
          },
          (err) =&gt; {
            this.setState({
              duplicateRecords: [],
            });
          }
        )
    } else {
      this.setState({
        duplicateRecords: [],
      });
    }
}

// few more functions in this file

render(){
    const {
      duplicateRecords,
    } = this.state;

    console.log('check',!_.isEmpty(duplicateRecords));

    return (
      &lt;React.Fragment&gt;
        &lt;form&gt;
          // other child components which are rendered.
          
          {!_.isEmpty(duplicateRecords) &amp;&amp;
            &lt;DuplicateRecordsFinder
              duplicateRecords={duplicateRecords}
              onInputChange={this.handleInputChange}
              closeDuplicateRecordList={this.handleDuplicateRecordsCloseEvent}
            /&gt;}
        &lt;/form&gt;
      &lt;/React.Fragment&gt;  
    )
}
</code></pre>
<p>In the above code fetchDuplicateRecords is executed when the above three mentioned fields
are added. Below is the request.js file code.</p>
<pre><code>// request.js
export function fetch(url, data = {}) {
  return $.ajax({
    url: url,
    method: &quot;GET&quot;,
    dataType: &quot;json&quot;,
    contentType: &quot;application/json&quot;,
    data,
  });
}

// duplicate_records_finder.js

export class DuplicateRecordsFinder extends Component {
  initialState() {
      return {
        duplicateRecordsChunk: _.chunk(
          this.props.duplicateRecords,
          3
        )
      }
  }  

  componentDidUpdate(props) {
    if (this.props.duplicateRecords !== props.duplicateRecords) {
      this.setState(this.initialState());
    }
  }

  render() {
      const { duplicateRecordsChunk } = this.state;
      console.log(&quot;i am here&quot;);
      console.log(&quot;duplicateRecordsChunk&quot;, duplicateRecordsChunk);

      return (
        &lt;div
            className=&quot;card card-profiles mb-4&quot;
        &gt;
      )
  }
}
</code></pre>
<p>I am using Jest and Enzyme for unit testing.</p>
<ol>
<li>When we enter the first_name, last_name and date_of_birth, the
fetchDuplicateRecords function is triggered.</li>
<li>This makes an ajax call to the backend and set the state.</li>
<li>This state change triggers people_form.js and DuplicateRecordsFinder component is displayed on UI.</li>
<li>Using Jest and Enzyme, I am trying to create this scenario. Below is my unit test.</li>
</ol>
<pre><code>// people_form.test.js

import * as request from &quot;request&quot;;

beforeEach(() =&gt; {
    wrapper = mount(&lt;PeopleForm/&gt;)
  });

test(&quot;it should display duplicate records when person already exists&quot;, () =&gt; {
    // mock fetch (ajax)
    request.fetch = jest.fn().mockReturnValueOnce(new Promise((resolve, reject) =&gt; { resolve(duplicateRecords); }))
    
    const firstNameInput = wrapper.find(&quot;input[name='first_name']&quot;);
    firstNameInput.simulate(&quot;change&quot;, { target: { value: &quot;First&quot;, name: &quot;first_name&quot; } });

    const lastNameInput = wrapper.find(&quot;input[name='last_name']&quot;);
    lastNameInput.simulate(&quot;change&quot;, { target: { value: &quot;Last&quot;, name: &quot;last_name&quot; } });

    // enter date of birth value.
    const dobInput = wrapper.find(&quot;input[name='date_of_birth']&quot;);
    dobInput.simulate(&quot;change&quot;, { target: { value: &quot;08-13-1990&quot;, name: &quot;date_of_birth&quot; } });

    // wrapper.setState({ first_name: 'First', last_name: &quot;Last&quot;, date_of_birth: &quot;08-13-1990&quot;, showDuplicateRecords: true,
    // duplicateRecords: duplicateRecords });

    expect(wrapper.containsMatchingElement(&lt;DuplicatePatientRecordsFinder /&gt;)).toEqual(true);
  })
</code></pre>
<p>When I execute the above test this is the output</p>
<pre><code>expect(received).toEqual(expected) // deep equality

Expected: true
Received: false

expect(wrapper.find(DuplicateRecordsFinder).length).toEqual(true);

console.log
    check false

      at PeopleForm.render (form/people_form.js:311:13)

  console.log
    check false

      at PeopleForm.render (form/people_form.js:311:13)

  console.log
    check true

    at PeopleForm.render (form/people_form.js:311:13)

  console.log
    i am here

      at DuplicateRecordsFinder.render (form/duplicate_records_finder.js:75:13)

  console.log
    duplicateRecordsChunk [  
        // data here
    ]

</code></pre>
<p>As per the output the control reaches the render of <code>DuplicateRecordsFinder</code> component,  but the expect DuplicateRecordsFinder component render is false which means the component tree is not updated.
However, if I explicitly set first_name, last_name, date_of_birth in state, it gives the expected result.</p>
<p>I found a related <a href=""https://github.com/enzymejs/enzyme/issues/1229#issuecomment-350392054"" rel=""nofollow noreferrer"">issue</a> on github.</p>
<p>Any help or suggestion would be highly appreciated</p>
",https://stackoverflow.com/questions/69163187/enzyme-mount-does-not-re-render-the-updated-components-on-props-change,"['reactjs', 'unit-testing', 'jestjs', 'enzyme', 'mount']",485,False,1,0
"How to set a Sinon spy for a dependency defined in a class, rather than a Sinon stub?","<p>I am unit testing a method defined in a module, which itself calls a dependency defined in a second module.  I want to set a spy for the method-under-test's call to the dependency, using the Sinon package. How do I do that? I've seen Sinon's page on mocking the dependency of a module (<a href=""https://sinonjs.org/how-to/stub-dependency/"" rel=""nofollow noreferrer"">see here</a>), and have been able to use it successfully in the past.  But in this case, my test code (see below) is still calling the original method, not the spy.</p>
<p>FYI in my code, if I assign a Sinon <em>stub</em> to the method, instead of Sinon <em>spy</em>, then the stubbed method is indeed called, as expected. I'm not sure why I can stub, but not spy in this case.</p>
<p>In this case, using <code>stub</code> is fine for my purposes.  But I'm curious as to why I cannot use <code>spy</code> here as I've done in the past.</p>
<p>Thanks.</p>
<hr />
<p><strong>My Code</strong></p>
<p><em>combo-test.js (test file)</em></p>
<pre><code>  const { tape } = require('tape')
  const sinon = require('sinon')
  const { myCombo } = require('./lib/ow/combo')
  const { ComboDropdown } = require('../../../lib/ow/combo-dropdown')

  const comboObject = myCombo(props)// Instantiate object to expose method-under-test.

  sinon.spy(ComboDropdown.prototype, 'extMethod')// Mock call to external method with a spy.
  // sinon.stub(ComboDropdown.prototype, 'extMethod')

  comboObj.myMethod()// Prints to console:  555
</code></pre>
<p><em>combo.js (defines method-under-test)</em></p>
<pre><code>const { ComboDropdown } = require('./combo-dropdown')

class Combo extends myClass {
  constructor(props) {
  }
  myMethod() {// method-under-test
    this.dropdown = new ComboDropdown({
    })
    this.dropdown.extMethod()//Calls external method.
  }
}
const myCombo = props =&gt; new Combo(props)
module.exports = { myCombo }
</code></pre>
<p><em>combo-dropdown.js (defines external method)</em></p>
<pre><code>class ComboDropdown extends Dropdown {
  constructor(props) {
    super(props)
  }
  extMethod() {
    console.log(555)
  }
}
module.exports = {
  ComboDropdown
}
</code></pre>
",https://stackoverflow.com/questions/68067898/how-to-set-a-sinon-spy-for-a-dependency-defined-in-a-class-rather-than-a-sinon,"['javascript', 'unit-testing', 'sinon', 'stub']",519,True,1,1
Mocking a trait with static method,"<p>I have a trait with a helper that looks like this</p>
<pre class=""lang-php prettyprint-override""><code>trait CliHelpers
{
    public static function cliError(string $errorMessage): void
    {
        try {
            \WP_CLI::error($errorMessage);
        } catch (ExitException $exception) {
            self::terminate($exception);
        }
    }

    public static function terminate(ExitException $exception)
    {
        exit(&quot;{$exception-&gt;getCode()}: {$exception-&gt;getMessage()}&quot;);
    }
}
</code></pre>
<p>I've added a public static method <code>terminate</code> so that I can test this part of the branch, without the test killing my PHP execution (because of the <code>exit</code>). The <code>WP_CLI</code> part will be mocked to throw the exception (this part works).</p>
<p>I'm using <a href=""https://pestphp.com/"" rel=""nofollow noreferrer"">Pest</a> for my unit testing framework.</p>
<p>My test looks like this</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php

namespace Tests\Unit\Cli;

use EightshiftLibs\Cli\CliHelpers;

use WP_CLI\ExitException;

/**
 * Mock before tests.
 */
beforeEach(function () {
    $wpCliMock = \Mockery::mock('alias:WP_CLI');

    $wpCliMock
        -&gt;shouldReceive('error')
        -&gt;andReturnUsing(function ($message) {
            throw new ExitException($message);
        });
});

/**
 * Cleanup after tests.
 */
afterEach(function () {
    \Mockery::close();
});


test('CliError helper will catch the exit', function() {

    $this-&gt;expectException(\Exception::class);

    $mock = \Mockery::mock(CliHelpers::class)
        -&gt;shouldAllowMockingProtectedMethods()
        -&gt;makePartial();

    $mock-&gt;shouldReceive('terminate')
        -&gt;andThrow(new \Exception);

    $mock::cliError('Error message');
});
</code></pre>
<p>So first I mock the <code>WP_CLI</code> so that I throw the exception (I'm testing this part of the branch).</p>
<p>Then I am trying to override the <code>terminate</code> method, but for some reason, when I run the single test inside PHPStorm, I get</p>
<pre class=""lang-sh prettyprint-override""><code>...
Testing started at 10:51 ...
PHPUnit 9.5.2 by Sebastian Bergmann and contributors.


Process finished with exit code 0
0: Error message
</code></pre>
<p>It actually goes to the exit method. And when I run the tests in the terminal, this test is never run 🤷🏼‍♂️</p>
<p>Is there a way to test this exiting part of the helper? I'm trying to avoid throwing another exception because then I'll have to put a bunch of throw/catch blocks through the entire codebase.</p>
",https://stackoverflow.com/questions/66730977/mocking-a-trait-with-static-method,"['php', 'unit-testing', 'mockery']",148,False,1,0
What is the cause of LazyInitializationException when testing Spring Boot web app with MockMvc and AutoConfigureMockMvc,"<p>I am trying out a few examples of unit testing Spring Boot MVC from this tutorial - <a href=""https://spring.io/guides/gs/testing-web/"" rel=""nofollow noreferrer"">https://spring.io/guides/gs/testing-web/</a>. My project has Spring Boot MVC and JPA (<a href=""https://github.com/shankarps/SfgUdemyRecipes"" rel=""nofollow noreferrer"">https://github.com/shankarps/SfgUdemyRecipes</a>)</p>
<p>The Controller that is tested retrieves a list of Recipe entities which have many-to-many mapping with Category entities.</p>
<pre><code>@RequestMapping({&quot;&quot;, &quot;/&quot;, &quot;/index&quot;})
public String getIndexPage(Model model){
    log.info(&quot;Getting all recipes&quot;);
    model.addAttribute(&quot;recipes&quot;, recipeService.getAllRecipes());
    return &quot;index&quot;;
}
</code></pre>
<p>This Controller works when the Spring Boot app is launched. The list of recipes are shown in the browser.</p>
<p>This <a href=""https://github.com/shankarps/SfgUdemyRecipes/blob/master/src/test/java/com/shankar/sfg/recipes/recipes/controllers/IndexControllerHttpTest.java"" rel=""nofollow noreferrer"">test case</a> with SpringBootTest and TestRestTemplate works as expected.</p>
<pre><code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class IndexControllerHttpTest {
    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void testIndexUrl(){
        String response = this.restTemplate.getForObject(&quot;http://localhost:&quot;+port+&quot;/&quot;, String.class);
    }
}
</code></pre>
<p>However, when I run a <a href=""https://github.com/shankarps/SfgUdemyRecipes/blob/master/src/test/java/com/shankar/sfg/recipes/recipes/controllers/IndexControllerMockMVCTest.java"" rel=""nofollow noreferrer"">test case with MockMVC</a> to test the Controller as a MVC object (with @AutoConfigureMockMvc), without the Http server, I get <code>org.hibernate.LazyInitializationException</code> Exception.</p>
<pre><code>@SpringBootTest
@AutoConfigureMockMvc
public class IndexControllerMockMVCTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void testIndexControllerView() throws Exception {
        this.mockMvc.perform(MockMvcRequestBuilders.get(&quot;/&quot;)).andExpect(status().isOk());
    }
}
</code></pre>
<p>Here is the exception stack trace in full:</p>
<pre><code>org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.shankar.sfg.recipes.recipes.domain.Category.recipes, could not initialize proxy - no Session    
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:606)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:218)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:585)
    at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:149)
    at org.hibernate.collection.internal.PersistentSet.toString(PersistentSet.java:327)
    at java.lang.String.valueOf(String.java:2994)
</code></pre>
<p>This looks like an issue with transaction scope. Can anyone help find the root cause? What additional configuration is needed to test the Spring application context when tested as a complete Web application (with @SpringBootTest), versus testing at the MVC layer (@SpringBootTest and @AutoConfigureMockMvc)?</p>
",https://stackoverflow.com/questions/65930196/what-is-the-cause-of-lazyinitializationexception-when-testing-spring-boot-web-ap,"['java', 'spring-boot', 'unit-testing', 'spring-boot-test', 'mockmvc']",468,True,1,1
"Only unit test observable behavior, not system requirements?","<p>I'm reading a book on unit testing, below is the code example:</p>
<pre><code>public class User {
   private string _name;
   public string Name {
      get =&gt; _name;
      set =&gt; _name = NormalizeName(value);
   }

   private string NormalizeName(string name) {
      /* Trim name down to 50 characters */
   }
}

public class UserController {
   public void RenameUser(int userId, string newName) {
      User user = GetUserFromDatabase(userId);
      user.Name = newName;
      SaveUserToDatabase(user);
   }
}
</code></pre>
<p>The author says</p>
<blockquote>
<p>UserController in this example is an application service. Assuming that the external client doesn't have a specific goal of normalizing user names, and all names are normalized solely due to restrictions from the application itself, the NormalizeName method in the User class can't be traced to the client's needs. Therefore, it's an implementation detail and should be made private. Moreover, tests shouldn't check this method directly. They should verify it only as part of the class's observable behavior-the Name property's setter in this example.</p>
</blockquote>
<p>So the author means we shouldn't write a test to test <code>NormalizeName</code> method, instead, we should write a test to test Name property. But image if the developer didn't write <code>NormalizeName</code> method properly and names more than 50 characters are allowed to be input, which will cause an exception thrown later, shouldn't we write a <code>NormalizeName</code> method test to guard this?</p>
",https://stackoverflow.com/questions/68173229/only-unit-test-observable-behavior-not-system-requirements,"['c#', 'unit-testing']",184,True,1,2
Visual Studio New project wont run tests,"<p>Visual Studio 2019 is not detecting or discovering NUNit nor MSTest unit tests at all. I installed it fresh just a week ago. The MS guide here <a href=""https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2019&amp;tabs=mstest"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2019&amp;tabs=mstest</a> does not work.</p>
<p>A few threads hold possible solutions, but none that I've tried helped have helped. I'm new to C# so much of the steps have taken a long time to figure out, but while my application is progressing nicely I really want to work and learn in a TDD style.
Even if a create a new blank MSTest project, with no application code or libs in the solution at all, the example/template project does not work, so I'm missing something big someplace. (I have .NET Core SDKs installed - my intent is to target macOS and linux at a future point.)</p>
<pre><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;
  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;netcoreapp3.1&lt;/TargetFramework&gt;
    &lt;IsPackable&gt;false&lt;/IsPackable&gt;
    &lt;LangVersion&gt;latest&lt;/LangVersion&gt;
  &lt;/PropertyGroup&gt;
  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;nunit&quot; Version=&quot;3.13.0&quot; /&gt;
    &lt;PackageReference Include=&quot;NUnit3TestAdapter&quot; Version=&quot;3.17.0&quot; /&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;
</code></pre>
<p>Threads I have tried: <a href=""https://stackoverflow.com/questions/23363073/tests-not-running-in-test-explorer"">Tests not running in Test Explorer</a> <a href=""https://stackoverflow.com/questions/61150776/why-will-visual-studio-2019-will-not-run-my-unit-tests"">Why will Visual Studio 2019 will not run my unit tests?</a> <a href=""https://stackoverflow.com/questions/59350689/visual-studio-2019-test-explorer-puts-all-tests-under-not-run-tests"">Visual Studio 2019 Test Explorer puts all tests under &quot;Not Run Tests&quot;</a>
If I create a project targeting .NET 4.7 all is good, it's when I want to target Core that I'm unstuck, if that helps.</p>
<p><strong>Stuck again</strong>
I had to install a component called &quot;NUnit 3&quot;, <a href=""https://marketplace.visualstudio.com/items?itemName=NUnitDevelopers.NUnitTemplatesforVisualStudio"" rel=""nofollow noreferrer"">https://marketplace.visualstudio.com/items?itemName=NUnitDevelopers.NUnitTemplatesforVisualStudio</a> worked for a moment... but when I added a testcase, it all broke again.</p>
<p>Did the nuget package updates, still not working.</p>
<p>I cloned. from git this project <a href=""https://github.com/dotnet/samples/tree/master/core/getting-started/unit-testing-using-nunit"" rel=""nofollow noreferrer"">https://github.com/dotnet/samples/tree/master/core/getting-started/unit-testing-using-nunit</a>
And it does not work either.</p>
<p>I then re-installed 2019, and emailed my project to a friend, who merely removed the nunit nuget modules, added them back and then it worked for him, but the project he sent me back did not work. Module versions unchanged</p>
<p>I opened the same project in the Microsoft developer VM/iso image and the project works just fine. so it's my environment that is incompatible with nunit somehow. Is there a way to see some traces?</p>
<p>Changed the installation drive from D: to C: I get this error now</p>
<pre><code>Testhost process exited with error: A fatal error occurred, the required library hostfxr.dll could not be found.
If this is a self-contained application, that library should exist in [C:\Users\zapho\src\c#\tutorials\working\ConsoleApp1\ConsoleApp1\NUnit.Tests2\bin\Debug\netcoreapp3.1\].
If this is a framework-dependent application, install the runtime in the default location [C:\Program Files\dotnet] or use the DOTNET_ROOT environment variable to specify the runtime location.
. Please check the diagnostic logs for more information.
Testhost process exited with error: A fatal error occurred, the required library hostfxr.dll could not be found.
If this is a self-contained application, that library should exist in [C:\Users\zapho\src\c#\tutorials\working\ConsoleApp1\ConsoleApp1\NUnit.Tests2\bin\Debug\netcoreapp3.1\].
If this is a framework-dependent application, install the runtime in the default location [C:\Program Files\dotnet] or use the DOTNET_ROOT environment variable to specify the runtime location.
. Please check the diagnostic logs for more information.
</code></pre>
",https://stackoverflow.com/questions/65569956/visual-studio-new-project-wont-run-tests,"['visual-studio', 'unit-testing', 'nunit']",3217,True,1,2
Hibernate Search / Lucene based Sorting Issue,"<p>I am having an issue in sorting, which specify below.</p>
<p>Previously, the code is writtern as</p>
<pre class=""lang-java prettyprint-override""><code>Sort sort = new Sort(new SortField[] {
   SortField.FIELD_SCORE,
   new SortField(&quot;field_1&quot;, SortField.STRING),
   new SortField(&quot;field_2&quot;, SortField.STRING),
   new SortField(&quot;field_2&quot;, SortField.LONG)
});
</code></pre>
<p>and this is an example pasted by the a stackoverflow answer here for custom sorting,
<a href=""https://stackoverflow.com/questions/21965778/sorting-search-result-in-lucene-based-on-a-numeric-field#answer-21965849"">Sorting search result in Lucene based on a numeric field</a>.</p>
<p>Though he does not suggest this is the correct way to do the sorting, this is also the code where my company has been used for years.</p>
<p>But when I create a new function, that needs to do sorting on lots of fields, and by performing unit testing, I found that it does not actually work as intended.</p>
<p>I need to remove <code>SortField.FIELD_SCORE</code> in order to make it works great. And I think this is suggested by the example described here if I did understand correctly, <a href=""https://docs.jboss.org/hibernate/search/4.1/reference/en-US/html_single/#d0e5317"" rel=""nofollow noreferrer"">https://docs.jboss.org/hibernate/search/4.1/reference/en-US/html_single/#d0e5317</a>.</p>
<p>i.e. the main code will convert to</p>
<pre class=""lang-java prettyprint-override""><code>Sort sort = new Sort(new SortField[] {
   new SortField(&quot;field_1&quot;, SortField.STRING),
   new SortField(&quot;field_2&quot;, SortField.STRING),
   new SortField(&quot;field_2&quot;, SortField.LONG)
});
</code></pre>
<p>So my question is</p>
<ol>
<li>what is the usage of <code>SortField.FIELD_SCORE</code>? How does the field score be calculated?</li>
<li>Why presenting <code>SortField.FIELD_SCORE</code> sometimes return correct value, sometimes don't?</li>
</ol>
",https://stackoverflow.com/questions/69216301/hibernate-search-lucene-based-sorting-issue,"['java', 'hibernate', 'lucene', 'hibernate-search']",159,True,0,1
Mock require/import modules using cypress,"<p>I'm using sequelize with graphql to connect my postgresql in my react nodejs project. And I'm using Cypress for unit testing. While doing that, I got stuck on how to mock the module import.</p>
<pre><code>describe('db config using sequelize', { tags: ['@unit'] }, () =&gt; {
  before(() =&gt; {
    const SequelizeStub = {
      authenticate: new Cypress.Promise((resolve) =&gt; { resolve(true) }),
      DataTypes: cy.stub().returns({}),
    }
    cy.stub('sequelize').returns(SequelizeStub)
  })

  it('db config authenticate', async () =&gt; {
    const { connect } = require('@db/common/dbconfig')
    assert.isBoolean(connect.authenticate())
  })
})
</code></pre>
<p>The <code>@db/common/dbconfig</code> file calls the <code>require('sequelize')</code> and creating the object for sequelize and using the Sequelize object I'm connecting to Postgresql.</p>
<p>So while writing the unit test case coverage for dbconfig file, I would like to mock the <code>require('sequelize')</code> itself instead of the module gets loaded for testing.</p>
<p>So I wrote a stub and replacing it with <code>'sequelize'</code> assuming that it will mock. But not sure this is the right approach. While running it, I'm getting the following error.</p>
<blockquote>
<p>TypeError: Cannot read properties of undefined (reading 'value')</p>
</blockquote>
<blockquote>
<p>Because this error occurred during a <code>before all</code> hook we are skipping the remaining tests in the current suite: <code>db config using sequelize</code></p>
</blockquote>
<blockquote>
<p>Although you have test retries enabled, we do not retry tests when <code>before all</code> or <code>after all</code> hooks fail</p>
</blockquote>
<p>Can someone help me with this stub mocking?</p>
",https://stackoverflow.com/questions/70343034/mock-require-import-modules-using-cypress,"['node.js', 'unit-testing', 'mocking', 'sequelize.js', 'cypress']",1331,False,0,1
HttpClient pattern with dynamic username and password,"<p>We have one single endpoint that dispatches requests to many endpoints with varying credentials and auth type (basic and digest auth; and username/password combinations). The credentials are given in the incoming request. How can I wire up HttpClient in such a way that it is reused as much as possible? In particular I am worried about socket exhaustion which is frequently mentioned when not reusing HttpClient instances properly. Additionally, I would prefer to have good inversion of control and factories for proper unit testing.</p>
<p>Naively one could do the following per request:</p>
<pre class=""lang-cs prettyprint-override""><code>using var messageHandler = new HttpClientHandler() {
    Credentials = new NetworkCredential(username, password)
};
using var client = new HttpClient(messageHandler);
</code></pre>
<p>Using .NET Core 3.1.</p>
<p><code>IHttpClientFactory</code> does not have means to inject <code>HttpMessageHandler</code> implementations dynamically. It picks the ones that you configure in the IOC wiring, or just the default <code>HttpClientHandler</code>.</p>
<p>I have moved above code to a factory:</p>
<pre class=""lang-cs prettyprint-override""><code>public class AuthenticatedHttpClientFactory : IAuthenticatedHttpClientFactory
{
    public HttpClient GetClient(string username, string password)
    {
        var messageHandler = new HttpClientHandler()
        {
            Credentials = new NetworkCredential(username, password)
        };
        var client = new HttpClient(messageHandler);
        return client;
    }
}
</code></pre>
<p>In the consumer code I dispose the provided <code>HttpClient</code>, but do I need to explicitly dispose the <code>HttpMessageHandler</code>? Is it automatically done when disposing the HttpClient? Or how do I do that?</p>
",https://stackoverflow.com/questions/67588449/httpclient-pattern-with-dynamic-username-and-password,"['c#', '.net', 'dotnet-httpclient']",422,False,0,0
How to test the config of PHPMailer and find out the TSL version,"<p>Since i want to test the config of our PHPMailer i searched a whole day for a possibility to get something like a log with the config listed. I found <a href=""https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting#testing-ssl-outside-php"" rel=""nofollow noreferrer"">Troubleshooting</a> on the github page of PHPMailer where exactly that topic is described.</p>
<p>That is the part of the response that is interesting for me is:</p>
<pre><code>New, TLSv1/SSLv3, Cipher is AES128-SHA
Server public key is 2048 bit
Secure Renegotiation IS supported
Compression: NONE
Expansion: NONE
SSL-Session:
    Protocol  : TLSv1
</code></pre>
<p>Unfortunately there is just described what command to use but not how:</p>
<blockquote>
<p>In order to eliminate PHP config or your code from encryption issues, you can use your local openssl installation to test the config directly using its built-in SMTP client, for example to test an explicit SMTP+STARTTLS config:</p>
<p><code>echo QUIT | openssl s_client -starttls smtp -crlf -connect smtp.gmail.com:587</code></p>
</blockquote>
<p>Because i have no experiences in something like unit testing and since there is nothing to find on google or on stackoverflow how to use that command i'm totally lost.</p>
<p>So please give me a hint. For example: should it be typed in a console on the server or should it be part of a test script or something else?</p>
",https://stackoverflow.com/questions/67191602/how-to-test-the-config-of-phpmailer-and-find-out-the-tsl-version,"['phpmailer', 'tls1.2']",149,False,0,0
how to mock calls to boost::posix_time::microsec_time::local_time()?,"<p>I'm having some issue trying to test some fuctionalities of a cpp class.
I'm testing my class, let's call it myManager, which has a public method called generateActionCommand that uses boost posix_time function local_time() to return a ptime structure in order to generate a command with the format &quot;timestamp,id,CMD_TYPE&quot; where:</p>
<ul>
<li>timestamp is a string representing the time of the machine as hh:mm:ss.ms;</li>
<li>id is an integer</li>
<li>CMD_TYPE, is a string, e.g., &quot;START&quot;</li>
</ul>
<p>Now, I'm testing myManager using boost.test and turtle-mock and I have wrote already some unit testing and used mocking in order to emulate other classes, but how can I test that the timestamp is generated correctly?(Ican test that the function respects the format, by using regex but I have no guarantees on the time returned. I would like to mock the function using MOCK_FUNCTION, but it does not seem to work.</p>
<p>Below, the code for the method I'm trying to test:</p>
<pre><code>std::string OEManager::generateActionCommand(const char* cmd_type) {
    std::string ret_msg;
    pt::ptime current_time = pt::microsec_clock::local_time();
    char timestamp[13];
    //NOTE: NO us(microseconds) support on windows machine time in format (hh:mm:ss.ms)
    snprintf(timestamp, 13, &quot;%02d:%02d:%02d.%03d&quot;, 
                    current_time.time_of_day().hours(), current_time.time_of_day().minutes(), 
                    current_time.time_of_day().seconds(), current_time.time_of_day().fractional_seconds());
    ret_msg = timestamp;
    ret_msg.append (&quot;,&quot; + std::to_string(sequence_id) + &quot;,&quot; + cmd_type);
    return ret_msg;
</code></pre>
",https://stackoverflow.com/questions/69847082/how-to-mock-calls-to-boostposix-timemicrosec-timelocal-time,"['c++', 'boost', 'turtle-mock']",75,False,0,0
Different outcomes for a single stub,"<p>I'm using <a href=""https://sinonjs.org"" rel=""nofollow noreferrer"">Sinon</a> for stubbing some data retrieval methods during unit testing. Most of these data methods are async, so the <code>resolves</code> syntax has been handy so far for this. What I'm trying to achieve is to dynamically generate different test data based on <code>Math.random()</code> to cover different branches on my code automatically, without having actually to provide hardcoded sample input data for each case. Still, I've realized that the stub just is actually called once upon initialization and, not the return value of it gets fixed/constant during the execution of the testing process (<a href=""https://mochajs.org"" rel=""nofollow noreferrer"">Mocha</a> based). Is there any way to actually provide different outcomes for a single stub using? I've checked the onCall syntax, but it also provides fixed output, just selectable based on current iteration index, but not actual dynamic output, which could even be args/params based, perhaps.</p>
<p>All ideas are welcome!</p>
<p>Current stubbing using Sinon:</p>
<pre><code>sinon.stub(dynamodb, 'get').resolves(stubGet())
</code></pre>
<p>The stub itself:</p>
<pre><code>function stubGet () {
  // Choose random repo
  const i = Math.round(Math.random() * sampleData.length)
  const repo = sampleData[i]

  // Should it have &quot;new code/push date&quot;?
  const isNew = Math.round(Math.random()) === 1
  if (isNew) {
    repo.pushed_at = { S: '1970-01-01T00:00:00Z' }
  }

  console.log('repo', repo)
  const item = { Item: repo }
  console.log(item)
  return item
}
</code></pre>
<p>The goal would be to hopefully get the random <code>repo</code> or the <code>isNew</code> value.</p>
",https://stackoverflow.com/questions/67154686/different-outcomes-for-a-single-stub,"['javascript', 'unit-testing', 'tdd', 'sinon', 'stub']",32,False,0,1
How do I test a python function using Robot Framework?,"<p>I'm trying to do a simple test with Robot Framework where I test python functions and see if they give me the desired results, but I cannot find any good examples documented. I'm giving input and want the test to pass if it meets the expected output that I designate. It would be nice if it could test the return statement of the function. I know that Robot Framework is usually geared more toward acceptance testing and what I'm doing is more aligned with unit testing but it seems like something that should still work with Robot Framework.</p>
<p>Here is an example of some code:</p>
<pre><code>def init(logger_module):

        retVal = 0 # Assuming all goes well.
        #print(&quot;module_init - I am in logging module&quot;)

        global logging
        logging = logger_module

        initialize_alert_logging()

        #print(&quot;The current retVal = {}&quot;.format(retVal))
        print(retVal)

        return retVal
</code></pre>
<p>I want it to show success if retVal equals 0. Right now I'm able to run a test, but it isn't really testing the output. I think it's just showing that the function actually ran.</p>
<p>Here is my robot file:</p>
<pre><code>*** Settings ***
Library         String
Library         Collections
Library         duplicate_module_simple_logging.py

*** Variables ***
${robotVar}             FooBarBaz
${MY_DATA_TABLE_VALUES_TEMP}            {&quot;foo&quot;: &quot;this is foo&quot;, &quot;bar&quot;: &quot;this is bar&quot;}

*** Test Cases ***
Case1
    init    logger_module
</code></pre>
<p>Here is my log file showing a successful test:
<a href=""https://i.stack.imgur.com/uDmWv.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/uDmWv.png"" alt="""" /></a></p>
",https://stackoverflow.com/questions/65711183/how-do-i-test-a-python-function-using-robot-framework,"['python', 'unit-testing', 'testing', 'robotframework', 'acceptance-testing']",650,True,0,1
How to test custom angular HTML input with Jasmine,"<p>I am having problems unit testing an angular component. Normally angular components are placed on the page like so: <code>&lt;custom-input/&gt;</code> and you have an HTML template: <code>template: '&lt;input/&gt;'</code> but for my purposes I am placing the selector in brackets: <code>selector:'[custom-input]'</code> and using the component on the page like this: <code>&lt;input custom-input/&gt;</code> . The problem I am having is when testing in Jasmine the rendered component is a <code>&lt;div&gt;</code> and not an <code>&lt;input/&gt;</code> . Is there a way to have Jasmine compile the component as an HTML input and not a div?</p>
<p>UPDATE:</p>
<p>component.ts</p>
<pre><code>@Component({
  selector: '[prps-text]',
  template:`
  `,
})
export class PrpsTextComponent implements OnInit {

  @Input() size: string = '';
  @Input() maxlength: string = '';
  @Input() property: string = '';
  @Input() readonly: string = '';
  @Input() styleClass: string = '';

  @HostBinding('attr.type') inputType: string = 'text'
  @HostBinding('attr.name') inputName: string = ''
  @HostBinding('attr.maxlength') inputMaxLength: string = ''
  @HostBinding('attr.size') inputSize: string = ''
  @HostBinding('attr.value') inputValue: string = ''
  @HostBinding('attr.readonly') isReadOnly: string | null = null;
  @HostBinding('attr.class') class: string = '';
  
  
  constructor() { }

  ngOnInit(): void {
    if(this.property != ''){
      this.inputName = this.property
    }
    if(this.maxlength != ''){
      this.inputMaxLength = this.maxlength
    }
    if(this.size != ''){
      this.inputSize = this.size
    }
    if (this.readonly === 'true') {
      this.isReadOnly = ''
    }
    if(this.styleClass != ''){
      this.class = this.styleClass
    }
  }

}
</code></pre>
<p>app-component.html</p>
<pre><code>&lt;input prps-text type=&quot;text&quot;/&gt;
</code></pre>
<p>spec.ts</p>
<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing';

import { PrpsTextComponent } from './prps-text.component';

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

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [ PrpsTextComponent ]
    })
    .compileComponents();
  });

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

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

  it('should create with type attribute text', () =&gt; {
    expect(compiled.getAttribute('type')).toEqual('text')
  })

  it('should set name attribute when property has value', () =&gt; {
    component.property = &quot;organization&quot;

    component.ngOnInit()
    fixture.detectChanges()

    expect(component.property).toBe('organization')
    expect(component.inputName).toBe('organization')
    expect(compiled.getAttribute('name')).toEqual('organization');
  })

  it('should set maxlength attribute', () =&gt; {
    component.maxlength = '3'
    
    component.ngOnInit()
    fixture.detectChanges()

    expect(component.maxlength).toBe('3')
    expect(component.inputMaxLength).toBe('3');
    expect(compiled.getAttribute('maxlength')).toBe('3')
  })

  it('should set size attribute', () =&gt; {
    component.size = '3'

    component.ngOnInit()
    fixture.detectChanges()

    expect(component.size).toBe('3')
    expect(component.inputSize).toBe('3')
    expect(compiled.getAttribute('size')).toBe('3')
  })

  it('should set to readonly', () =&gt; {
    component.readonly = 'true'

    component.ngOnInit()
    fixture.detectChanges()

    expect(component.readonly).toBe('true')
    expect(component.isReadOnly).toBeTrue
    expect(compiled.getAttribute('readonly')).toBeTrue
  })

  it('should set styleClass', () =&gt; {
    component.styleClass = 'input_disabled'

    component.ngOnInit()
    fixture.detectChanges()

    expect(component.styleClass).toBe('input_disabled')
    expect(component.class).toBe('input_disabled')
    expect(compiled.getAttribute('class')).toBe('input_disabled')
  })
});

</code></pre>
<p>My component has no template since the component isn't technically a component but an element with customized behavioral attributes so when the component is compiled by the test it renders like this: <code>&lt;div id=&quot;root66&quot; ng-version=&quot;11.0.9&quot;&gt;&lt;/div&gt;</code> instead of like this: <code>&lt;input id=&quot;root66&quot; ng-version=&quot;11.0.9&quot;/&gt;</code>. I can't test a div like an input and that is the problem I am trying to solve. The question would be: is there any way to mock the component as an input rather than a div so I can test the functionality correctly?</p>
",https://stackoverflow.com/questions/67198215/how-to-test-custom-angular-html-input-with-jasmine,"['angular', 'unit-testing', 'jasmine']",1304,False,0,1
Unable to connect to the remote server when using localhost to sent http request in unit test,"<p>I have a basic unit test that checks if a header for an http request is set or not:</p>
<pre><code>    public async Task HeaderNotFound()
    {
        var request = new HttpRequestMessage(HttpMethod.Get, &quot;http://localhost&quot;);
        // ...set the operation context
        await client.SendAsync(request, CancellationToken.None);
        // ...assert that the needed header are added
    }
</code></pre>
<p>The client is set with a custom handler in the test class ctor:</p>
<pre><code>client = HttpClientFactory.Create(new SomeHandlerThatAddHeader());
</code></pre>
<p>The above test used to run with out any issue, but start failing permanently after we updated the build agent pool used in the build pipeline. Running the test result in the following exception:</p>
<blockquote>
<p>No connection could be made because the target machine actively
refused it 127.0.0.1:80</p>
</blockquote>
<p>I could simply switch the uri to a valid one like google.com (since it seems like nothing is starting on localhost) but I would like to keep localhost (I know also that making active connection while unit testing would make it more like an int test). Finally mocking the Httpclient client will override the added <code>DelegatingHandler</code>, and it seems like an overkill for such simple test!</p>
<p>How can I fix that please?
Any help is appreciated.</p>
",https://stackoverflow.com/questions/68557820/unable-to-connect-to-the-remote-server-when-using-localhost-to-sent-http-request,"['c#', 'asp.net', 'asp.net-mvc', 'asp.net-core', 'httpclient']",349,False,0,1
Query regarding unit testing of camel multiple routes within the same class,"<p>I'm having issues unit testing multiple camel routes within the same class.I have a class which contains several route definitions. e.g. as below:</p>
<pre><code>public class A extends RouteBuilder{
    @Override
    public void configure() throws Exception {
        method1();
        method2();
        method3();
        ...
    }
    private void method1() {
        // contains route definitions
        final RouteDefinition route = from(&quot;direcct:&quot;);
        route.id(&quot;ID1&quot;);
        route.setHeader(&quot;&quot;,simple(&quot;&quot;));
        route.to(&quot;direct:B&quot;);
        route.end();
    }
// similarly other methods
}
</code></pre>
<p>i want to unit test each method. so have extended CamelTestSupport. can't override the methods in configure when creating routebuilder since the method are private.
this is what i am doing currently</p>
<pre><code>public class A extends CamelTestSupport {
    private A route;
    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        route = new A();
//can't use below configure since methods are private
    //@Override public void configure() throws Exception {
    //  method1();
    //}

        //logic for mocking and setting endpoints using mockito
        
        return route;
    }
@Test
public void method1_test() throws Exception {
}
}
</code></pre>
<p>I can test one method while commenting others(camelcontext loads and starts all the routes in a class).If i don't comment the test fails.
Also for testing other methods within the same test class i cant use the same createRoutebuilder.So below are the questions:</p>
<ol>
<li>How will i test other methods within the same test class</li>
<li>Is there a way to start and stop routeid so i can test only those routes(tries startroute method but since all the routes are already started it doesn't do anything)</li>
<li>Is there any workaround so that individual methods can be tested
Using camel 3.6, spring boot2 and junit 5</li>
</ol>
",https://stackoverflow.com/questions/67918282/query-regarding-unit-testing-of-camel-multiple-routes-within-the-same-class,"['java', 'unit-testing', 'apache-camel']",295,False,0,0
Loose Coupling with ServiceProvider and DependencyInjection creates connection problems with SQL Database,"<p>I have two interfaces IDatabaseManager and ICRUDManager with the respective classes DatabaseManager and CRUDManager, configured in main class with configurationService, with DatabaseManager being singleton added with AddSingleton, and CRUDManager with AddTransient. The services are then accessed with service provider. I configure in main class the <code>DatabaseManger.SetConnection()</code> with the connection string and the <code>GetConnection</code> is accessed from CRUDManagerService. But the connection breaks when i access the GetConnection from one function to another.</p>
<pre><code>public class Program
    {
        private static IServiceProvider serviceProvider;

        static void Main(string[] args)
        {
            ConfigureServices();
            var databaseService = serviceProvider.GetService&lt;IDatabaseManager&gt;();
            var crudService = serviceProvider.GetService&lt;ICRUDManager&gt;();

            databaseService.SetConnection(connectionString);
            crudService.Read();
            crudService.Update();
            crudService.Read();


        }
        private static void ConfigureServices()
        {
            var services = new ServiceCollection();
            services.AddTransient&lt;ICRUDManager, CRUDManager&gt;();
            services.AddSingleton&lt;IDatabaseManager, DatabaseManager&gt;(); 
            serviceProvider = services.BuildServiceProvider();
        }
    }

</code></pre>
<pre><code>public class DatabaseMananger: IDatabaseManager
{
    static SqlConnection connection;

    public SetConnection(connectionString)
    {
        connection = new SqlConnection(connectionString);
    }
    public GetConnection()
    {
        return connection;
    }

}
</code></pre>
<pre><code>public class CRUDMananger: ICRUDManager
{
    IDatabaseManager databaseManager;

    public CRUDMananger(IDatabaseManager _databaseManager)
    {
        databaseManager = _databaseManager;
    }
    public string Read()
    {
        using(databaseManager.GetConnection()
        {
        //reads table
        }
    }
    public void Update()
    {
        using(databaseManager.GetConnection()
        {
        //updates table
        }
    }

}
</code></pre>
<p>All functions in CRUDManager runs good when unit testing,as the databaseManager is passed by tight coupling. But due to design fault, or some other problem I do not realize, after setting the connection, only the first read works in the main and the next update or read stops working due to empty conneciton string, or sql connection error. What I want to know is, if its the fault with the code architecture, whether its the fault of using singletons, or with dependencyInjection with ServiceProvider that connection resets and how can I make it better?</p>
",https://stackoverflow.com/questions/69725887/loose-coupling-with-serviceprovider-and-dependencyinjection-creates-connection-p,"['c#', 'dependency-injection', 'service-provider']",105,False,0,0
Need help tracking down an access error violation,"<p>I'm fairly new to C++ but am working on a program where I'm using unit testing to do the development.  The specific unit test in question deals with saving and loading from a binary file, and seems to be throwing an access violation exception code during deallocation at the end of the unit test.  If I comment out the line of code that loads from the file, the problem goes away however, which I've assumed means there's something in my load function creating the issue but I can't seem to figure out what's going on.  When I step through the unit test, it seems to be saving and loading the file information correctly into the playbook objects.</p>
<p>Can anyone help point me in the right direction?</p>
<p>Unit Test Code:</p>
<pre><code>Playbook testPlays;
        Playbook testPlaysLoad;

        string playName = &quot;Play1&quot;;
        int numDLine = 4;
        int numLB = 3;
        vector&lt;int&gt; playerPos = { 0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 19 };
        vector&lt;int&gt; playerStance = { 2, 1, 0, 0, 1, 2, 2, 3, 2, 3, 3 };
        vector&lt;int&gt; playerBlitzGaps = { 0, 3, 0, 0, 3, 0, 0, 0, 0, 0, 0 };


        testPlays.setName(&quot;testPlays&quot;);
        testPlays.addPlay(playName, numDLine, numLB, playerPos, playerStance, playerBlitzGaps);
        testPlays.save();

        testPlaysLoad.load(testPlays.getName());

        
        Assert::IsTrue(testPlays == testPlaysLoad);
</code></pre>
<p>Load Function Code:</p>
<pre><code>void Playbook::load(string fileName)

std::ifstream loadFile;

//create file path to load file from
string filePath = &quot;./Playbooks/&quot; + fileName + &quot;.playbk&quot;;

//open the file
loadFile.open(filePath, std::ios::binary);

//end if file doesn't open correctly
if (loadFile.bad())
{
    return;
}

//read the individual pieces of the play
while (!loadFile.eof())
{
    //create a variable to store each play in one at a time before storing into the vector
    Play curPlay;
    
    loadFile.read((char*)&amp;curPlay.playName, sizeof(curPlay.playName));
    loadFile.read((char*)&amp;curPlay.numDLine, sizeof(curPlay.numDLine));
    loadFile.read((char*)&amp;curPlay.numLB, sizeof(curPlay.numLB));
    
    //temp int variable
    int curInt = 0;
    
    //loop through each element and read it in
    for (int i = 0; i &lt; 11; i++)
    {
        loadFile.read((char*)&amp;curInt, sizeof(int));
        curPlay.playerPos.push_back(curInt);
    }

    //loop through each element and read it in
    for (int i = 0; i &lt; 11; i++)
    {
        loadFile.read((char*)&amp;curInt, sizeof(int));
        curPlay.playerStance.push_back(curInt);
    }
    
    //loop through each element and read it in
    for (int i = 0; i &lt; 11; i++)
    {
        loadFile.read((char*)&amp;curInt, sizeof(int));
        curPlay.playerBlitzGaps.push_back(curInt);
    }
    
    plays.push_back(curPlay);
} 

//close the file
loadFile.close();

//set name of playbook as the file name
setName(fileName);

//set play num to vector size
numPlays = plays.size();
</code></pre>
<p>Play definition:</p>
<pre><code>Play(string name, int numLine, int LB, vector&lt;int&gt; pos, vector&lt;int&gt; stance, vector&lt;int&gt; blitzGaps) { playName = name; numDLine = numLine; numLB = LB; playerPos = pos; playerStance = stance; playerBlitzGaps = blitzGaps; }
Play() {
    playName = &quot;&quot;; numDLine = 0; numLB = 0; playerPos = { 0,0,0,0,0,0,0,0,0,0,0 }; playerStance = { 0,0,0,0,0,0,0,0,0,0,0 }; playerBlitzGaps = { 0,0,0,0,0,0,0,0,0,0,0 };
}
~Play() {}

string playName = &quot;&quot;;
int numDLine = 0;
int numLB = 0;
vector&lt;int&gt; playerPos = { 0,0,0,0,0,0,0,0,0,0,0 };
vector&lt;int&gt; playerStance = { 0,0,0,0,0,0,0,0,0,0,0 };
vector&lt;int&gt; playerBlitzGaps = { 0,0,0,0,0,0,0,0,0,0,0 };
</code></pre>
<p>Playbook definition:</p>
<pre><code>friend bool operator== (Playbook&amp; book1, Playbook&amp; book2);
</code></pre>
<p>public:
Playbook();
~Playbook();</p>
<pre><code>void setName(string name);
void setCurrentPlay(int playNum);

string getName();
int getNumPlays();

void addPlay(string name, int numDLine, int numLB, vector&lt;int&gt; playerPos, vector&lt;int&gt; playerStance, vector&lt;int&gt; playerBlitzGaps);
void save();
void load(string fileName);

Play currentPlay;
</code></pre>
<p>private:
string playbookName = &quot;&quot;;
int numPlays = 0;</p>
<pre><code>vector&lt;Play&gt; plays;
</code></pre>
<p>Oh, I almost forgot the stack trace:</p>
<pre><code>Stack Trace: 
    _Container_base12::_Orphan_all_unlocked() line 1222
    _Container_base12::_Orphan_all_locked() line 1098
    _Container_base12::_Orphan_all() line 1240
    allocator&lt;char&gt; &gt;::_Tidy_deallocate() line 4618
    char_traits&lt;char&gt;,std::allocator&lt;char&gt; &gt;() line 3005
    Playbook::load() line 168
    PlaybookIO::saveAndLoadPlayblook() line 66
</code></pre>
",https://stackoverflow.com/questions/69631050/need-help-tracking-down-an-access-error-violation,"['c++', 'visual-studio-2019']",57,False,0,0
How to run NUnit tests without Visual Studio and Source code?,"<p>I am very new to Unit-Testing.</p>
<p>I have a solution with C# project. I added to it a new NUnit project and added some tests.</p>
<p>I can run my tests using Test Explorer of Visual Studio, and even using Command-Line in the developing platform:</p>
<pre><code>D:\Project\GuiTests\bin\Debug\netcoreapp2.1&gt;dotnet test GuiTests.dll
</code></pre>
<p>I want to do a similar thing, but on a <strong>testing</strong> platform, which does not have Visual Studio and the source code.</p>
<p>I want to copy there only the tests folder (i.e. D:\Project\GuiTests\bin\Debug\netcoreapp2.1) and run the tests using Command-Line.</p>
<p>Is it possible? How can I do that?</p>
<p>Currently, I tried it out and got:</p>
<p><a href=""https://i.stack.imgur.com/IqwMa.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/IqwMa.png"" alt=""enter image description here"" /></a></p>
<p>===</p>
<p>I tried using nunit-console and got this error:</p>
<blockquote>
<p>Could not load file or assembly 'nunit.framework, Version=3.10.1.0,
Culture=neutral, PublicKeyToken=2638cd05610744eb' or one of its
dependencies.</p>
</blockquote>
<p><a href=""https://i.stack.imgur.com/D1Etw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/D1Etw.png"" alt="""" /></a></p>
<p>Googling it, seems nunit-console does not support .Net Core.</p>
<p>So I think I should go on with the <code>dotnet test</code></p>
",https://stackoverflow.com/questions/66423404/how-to-run-nunit-tests-without-visual-studio-and-source-code,"['c#', '.net', 'command-line', 'nunit']",1166,False,0,1
how to test code (private methods ) without a unit framework in .net?,"<p>i have taken over an application which was developed over many years from many developers and is written in vb.net. this application will be only used in-house and is running on an isolated environment.</p>
<p>i would like to include some tests to this application for safety-reason
to have some verification when i am changing something in the code -
and later on maybe trying to refactor it.</p>
<p>unfortunately i cant use any of the unit testing frameworks,
because almost all of the methods are private.
i guess &quot;spaghetti-code&quot; could fit here very well.</p>
<p><strong>what would be a way to include some tests into this application?</strong></p>
<p>the app is written in vb.net, but c# would also fit.</p>
<p>of course, i could change the methods f.e. to public.
but that's what i don't want to do here in a first step.</p>
<p><strong>and i am curious how to run tests on private or internal code parts?</strong></p>
<p>thank you in advance.</p>
<p>br
lakk</p>
",https://stackoverflow.com/questions/67195682/how-to-test-code-private-methods-without-a-unit-framework-in-net,"['.net', 'vb.net', 'testing', 'methods', 'private']",45,False,0,0
Long import times for some modules in VS Code,"<p>When I run a Python script in VS Code, it delays execution by more than a second if, for example, Pandas or Numpy are part of the script's import statement.</p>
<p>If only libraries from the Python Standard Library are used in the imports, the script will start immediately.</p>
<p>A second doesn't sound like a lot, but it is to me because I've used Spyder so far, where the same script starts immediately without spending any noticeable time on imports. I was wondering if this is normal in VS Code or if there are configuration parameters to speed up import time.</p>
<p><strong>Edit</strong></p>
<p>A minimal example would be a script with content</p>
<pre><code>import collections
import pandas

print(&quot;a string&quot;)
</code></pre>
<p>which in my opinion should only take a few milliseconds (not noticeable) for complete processing after clicking the &quot;run&quot; button. Without the <em>pandas</em> import, it actually does.
I think this is an important aspect, because slow &quot;import speeds&quot; hinder the unit-testing workflow.</p>
",https://stackoverflow.com/questions/66413965/long-import-times-for-some-modules-in-vs-code,"['python', 'visual-studio-code']",841,False,0,1
Include/exclude files for remote coverage in Codeception,"<p>I've just been given a legacy project to maintain, and I started by putting it in a test harness (Codeception) and running coverage on it. However, it currently only runs via PHPBrowser (unit testing is currently not possible due to its complexity and legacy nature), so it needs remote coverage. I've tried specifying which files should and shouldn't be covered, but it looks like it's completely ignoring that and including all files, including non-PHP files.</p>
<p>I'm running the tests with <code>codecept run acceptance --no-colors --coverage-html coverage</code>.</p>
<p>This is my <code>codeception.yml</code> file:</p>
<pre class=""lang-yaml prettyprint-override""><code>paths:
    tests: tests
    output: tests/_output
    data: tests/_data
    support: tests/_support
    envs: tests/_envs
actor_suffix: Tester
extensions:
    enabled:
        - Codeception\Extension\RunFailed
settings:
    lint: false
coverage:
    enabled: true
    include:
        - api_base/api/web/*
    exclude:
        - api_base/system/config.php
</code></pre>
<p>And this is <code>acceptance.yml</code>:</p>
<pre class=""lang-yaml prettyprint-override""><code># Codeception Test Suite Configuration
#
# Suite for acceptance tests.
# Perform tests in browser using the WebDriver or PhpBrowser.
# If you need both WebDriver and PHPBrowser tests - create a separate suite.

actor: AcceptanceTester
modules:
    enabled:
        - PhpBrowser:
            url: http://new-project.local/api/web
        - \Helper\Acceptance
</code></pre>
<p>The <code>c3.php</code> file is in the root of the project. Here's a rough idea of the directory structure:</p>
<pre><code>+- api_base/
|   +- api/
|   |   +- web/
|   |   |   \- *.php
|   |   \- *
|   +- README.md
|   +- system/
|   |   +- config.php
|   |   \- *
|   \- *
+- bin/
|   \- *
+- c3.php
+- codeception.yml
+- composer.json
+- composer.lock
+- tests/
|   +- acceptance/
|   |   \- AcceptanceCest.php
|   \- *
\- vendor/
    \- *
</code></pre>
<p>The files that are in the report have the correct coverage but there are files I don't want included. All files are currently being included, even if I specify <code>exclude: [ ./*.* ]</code>. I want most of the PHP files and none of the non-PHP files included in the remote coverage report. Is this possible? How?</p>
",https://stackoverflow.com/questions/69443881/include-exclude-files-for-remote-coverage-in-codeception,"['code-coverage', 'codeception']",622,False,0,1
Unit Testing without a main static method?,"<p>I am starting to go through a tutorial on Unit Testing. I am using Visual Studio 2019 and I am trying to run the projects/ tests but keep getting these errors,</p>
<p>CS5001  Program does not contain a static 'Main' method suitable for an entry point</p>
<p>CS006   Metadata file 'C:(filepath)... .exe' could not be found</p>
<p>I know neither class has a main static method but the tutorial I am following along with doesn't either so I am not sure what the issue is. I have searched Stack Overflow and Google but can only find answers going over my head, any idea what how to fix this?</p>
<p>It is pretty simple code as I am just at the beginning so I think the problem is something else but am not sure (obviously)</p>
<p>UPDATE:
Here is a screen shot of the structure of my solution:
<a href=""https://i.stack.imgur.com/wRlrK.png"" rel=""nofollow noreferrer"">structure of solution</a>
The original project was a Console application, the I added a Test project to the solution.</p>
",https://stackoverflow.com/questions/66879462/unit-testing-without-a-main-static-method,"['c#', 'visual-studio', 'unit-testing']",637,True,0,2
Atomic operation with consistent data in laravel,"<p>I have a booking process for tours that looks like this:</p>
<pre><code>booking_process:
    if_date_time_exists_in_bookings_table and there are still spaces available
        make_payment
        update_table
        send_confirmation_email_to_user
        ## no need to update google calendar here
    else if date_time hasn't been booked yet
        make_payment  
        make_closed_event_in_google_calendar
        insert_record_in_db
        send_confirmation_email_to_user
</code></pre>
<p>In this project I would like to integrate Google Calendar api for events, and as a central place for all of my tours. I have following requirements:</p>
<ol>
<li><p>I want each block code to either completely succeed or fail. ( for exampleI  don't want to make a payment and then fail to update table and vice versa).</p>
</li>
<li><p>I want to make this operation ( if/else block code ) atomic. So no overbooking should happen.</p>
</li>
</ol>
<p>And finally how do I test that? I guess unit testing is not meant for this.
In block code 2 (else is part) I don't have update, so does that mean I can't be using database locks? That doesn't seem like an operation suitable for cache and consequently cache locks either. Also is it possible mixing non atomic services ( I believe Google Calendar is not atomic ) in atomic operations?</p>
<p>I am using Laravel and absolutely have no idea how to do this.</p>
",https://stackoverflow.com/questions/65678097/atomic-operation-with-consistent-data-in-laravel,"['laravel', 'atomic']",518,False,0,0
How can I trigger a method after a variable in a dependency is updated?,"<p>How can I trigger a method after a variable in a dependency is updated in Swift?</p>
<p>My groupViewModel initializes a user repository that gets the list of users in the group, using the following flow:</p>
<pre><code>init(groupRepository: GroupStoreType, groupUserRepository: GroupUserStoreType, group accountabilityGroup: AccountabilityGroup) {
    self.groupRepository = groupRepository
    self.groupUserRepository = groupUserRepository
    self.group = accountabilityGroup
    
    // Setting this in the repository triggers the loadUsers 
    // method in the repository
    self.groupUserRepository.groupId = self.group.id
    
    // I want to run a method that does a sanity check on all the users
    // that verifies their data matches the group after the repository completes
    // it's method, but before I run loadActiveMembers() and loadPendingMembers() below.

    loadActiveMembers()
    loadPendingMembers()
}
</code></pre>
<p>Then in my user repository, setting the groupId to something other than nil will trigger the function that loads users matching that group:</p>
<pre><code>var groupId: String? {
    didSet {
        if groupId != nil &amp;&amp; groupId != oldValue {
            self.loadByGroupId()
        }
    }
}
</code></pre>
<p>That loading function will either listen to a cloud Firestore collection or subscribe to a static list of users (for my mocked version for unit testing).</p>
<p>I want to run a <code>verifyUsersMatchGroup</code> method in the ViewModel after the repository loads the users, but before the ViewModel runs the <code>loadActiveMembers</code> and <code>loadPendingMembers</code> methods. Any ideas on good ways to accomplish this?</p>
<p>I thought about having a <code>usersLoaded</code> Bool var in the repository, and having that published to a similar variable in the ViewModel, then triggering my method in the didSet of that, but I'm wondering if there are simpler ways to accomplish this. (This app is currently not yet set for iOS 15.)</p>
",https://stackoverflow.com/questions/68693009/how-can-i-trigger-a-method-after-a-variable-in-a-dependency-is-updated,"['swift', 'asynchronous']",45,True,-1,1
CakePHP 3.10 -&gt; 4.x Upgrade - Rector won&#39;t start,"<p>I am in the process of upgrading a site from CakePHP 3.10.0 to CakePHP 4.x using the <a href=""https://book.cakephp.org/4/en/appendices/4-0-upgrade-guide.html"" rel=""noreferrer"">4.x Upgrade Guide</a>. I have been successful up until the point where you need to run the following commands:</p>
<pre><code>bin/cake upgrade rector --rules phpunit80 &lt;path/to/app/tests&gt;
bin/cake upgrade rector --rules cakephp40 &lt;path/to/app/src&gt;
</code></pre>
<p>I skipped the first command as I do not do unit testing (<em>yet!</em>). When I run the second command, it just hangs. There is no output at all from this command. I have let it sit for hours but it does nothing. I added <code>-v</code> to the command and finally got some output but it still hangs:</p>
<pre><code>$ bin/cake upgrade rector --rules cakephp40 ../vintage-lib/src -v
Detecting autoload file for /mnt/d/Programming/PHP/vintage-lib/src
-&gt; Checking /mnt/d/Programming/PHP/vintage-lib/src/vendor/autoload.php
-&gt; Checking /mnt/d/Programming/PHP/vintage-lib/vendor/autoload.php
-&gt; Found /mnt/d/Programming/PHP/vintage-lib/vendor/autoload.php
Running /mnt/d/Programming/PHP/upgrade/vendor/bin/rector process  --autoload-file='/mnt/d/Programming/PHP/vintage-lib/vendor/autoload.php' --config='/mnt/d/Programming/PHP/upgrade/config/rector/cakephp40.php' --working-dir='/mnt/d/Programming/PHP/vintage-lib/src' '/mnt/d/Programming/PHP/vintage-lib/src'
</code></pre>
<p>I have tried running this in Windows, WSL and even in a Linux VM - the result remains the same which makes me believe it is something with my code or a config file. I tried to run the command on each of my plugins but I get the same result.</p>
<p>I have also run and fixed all errors and warnings from codesniffer but it makes no difference.</p>
<p>I am at a loss as I don't know where to check next. Any assistance would be greatly appreciated.</p>
",https://stackoverflow.com/questions/68464416/cakephp-3-10-4-x-upgrade-rector-wont-start,"['php', 'cakephp', 'rector']",519,False,5,1
How to locally unit-test Chainlink&#39;s Verifiable Random Function?,"<h2>Context</h2>
<p>While trying to set up a basic self-hosted unit testing environment (and CI) that tests <a href=""https://ethereum.stackexchange.com/a/83617/55344"">this Chainlink VRF random number contract</a>, I am experiencing slight difficulties in how to simulate any relevant blockchains/testnets locally.</p>
<p>For example, I found <a href=""https://github.com/smartcontractkit/hardhat-starter-kit"" rel=""noreferrer"">this repository that tests Chainlinks VRF</a>. However, for default deployment it suggests/requires a free <code>KOVAN_RPC_URL</code> e.g. from Infura's site and even for &quot;local deployment&quot; it suggests/requires a free <code>MAINNET_RPC_URL</code> from e.g. Alchemy's site.</p>
<h2>Attempt/baseline</h2>
<p>I adopted a unit test environment from the waffle framework which is described as:</p>
<h3>Filestructure</h3>
<pre><code>src____AmIRichAlready.sol
   |____RandomNumberConsumer.sol
   |
test____AmIRichAlready.test.ts
   |____mocha.opts
package.json
tsconfig.json
waffle.json
yarn.lock
</code></pre>
<h3>Filecontents</h3>
<p>AmIRichAlready.sol</p>
<pre><code>pragma solidity ^0.6.2;

interface IERC20 {
    function balanceOf(address account) external view returns (uint256);
}

contract AmIRichAlready {
    IERC20 private tokenContract;
    uint public richness = 1000000 * 10 ** 18;

    constructor (IERC20 _tokenContract) public {
        tokenContract = _tokenContract;
    }

    function check() public view returns (bool) {
        uint balance = tokenContract.balanceOf(msg.sender);
        return balance &gt; richness;
    }

    // IS THIS NEEDED???
    function setRichness(uint256 _richness) public {
      richness = _richness;
    }
}
</code></pre>
<p>The <code>RandomNumberConsumer.sol</code> filecontent is already on stackexange <a href=""https://ethereum.stackexchange.com/a/83617/55344"">over here</a>.</p>
<p>AmIRichAlready.test.ts</p>
<pre><code>import {expect, use} from 'chai';
import {Contract, utils, Wallet} from 'ethers';
import {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';

import IERC20 from '../build/IERC20.json';
import AmIRichAlready from '../build/AmIRichAlready.json';

use(solidity);

describe('Am I Rich Already', () =&gt; {
  let mockERC20: Contract;
  let contract: Contract;
  let vrfContract: Contract;
  let wallet: Wallet;

  beforeEach(async () =&gt; {
    [wallet] = new MockProvider().getWallets();
    mockERC20 = await deployMockContract(wallet, IERC20.abi);
    contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address]);
    vrfContract = await deployContract(wallet, RandomNumberConsumer);
  });

  it('checks if contract called balanceOf with certain wallet on the ERC20 token', async () =&gt; {
    await mockERC20.mock.balanceOf
      .withArgs(wallet.address)
      .returns(utils.parseEther('999999'));
    await contract.check();
    expect('balanceOf').to.be.calledOnContractWith(mockERC20, [wallet.address]);
  });

  it('returns false if the wallet has less than 1000000 coins', async () =&gt; {
    await mockERC20.mock.balanceOf
      .withArgs(wallet.address)
      .returns(utils.parseEther('999999'));
    expect(await contract.check()).to.be.equal(false);
  });

  it('returns true if the wallet has at least 1000000 coins', async () =&gt; {
    await mockERC20.mock.balanceOf
      .withArgs(wallet.address)
      .returns(utils.parseEther('1000000'));
    expect(await contract.check()).to.be.equal(false);
  });
});
</code></pre>
<p>mocha.opts</p>
<pre><code>-r ts-node/register/transpile-only
--timeout 50000
--no-warnings
test/**/*.test.{js,ts}
</code></pre>
<p>package.json</p>
<pre><code>{
  &quot;name&quot;: &quot;example-dynamic-mocking-and-testing-calls&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;main&quot;: &quot;index.js&quot;,
  &quot;license&quot;: &quot;MIT&quot;,
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;export NODE_ENV=test &amp;&amp; mocha&quot;,
    &quot;build&quot;: &quot;waffle&quot;,
    &quot;lint&quot;: &quot;eslint '{src,test}/**/*.ts'&quot;,
    &quot;lint:fix&quot;: &quot;eslint --fix '{src,test}/**/*.ts'&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@openzeppelin/contracts&quot;: &quot;^4.3.1&quot;,
    &quot;@types/chai&quot;: &quot;^4.2.3&quot;,
    &quot;@types/mocha&quot;: &quot;^5.2.7&quot;,
    &quot;@typescript-eslint/eslint-plugin&quot;: &quot;^2.30.0&quot;,
    &quot;@typescript-eslint/parser&quot;: &quot;^2.30.0&quot;,
    &quot;chai&quot;: &quot;^4.3.4&quot;,
    &quot;eslint&quot;: &quot;^6.8.0&quot;,
    &quot;eslint-plugin-import&quot;: &quot;^2.20.2&quot;,
    &quot;ethereum-waffle&quot;: &quot;^3.4.0&quot;,
    &quot;ethers&quot;: &quot;^5.0.17&quot;,
    &quot;mocha&quot;: &quot;^7.2.0&quot;,
    &quot;ts-node&quot;: &quot;^8.9.1&quot;,
    &quot;typescript&quot;: &quot;^3.8.3&quot;
  }
}
</code></pre>
<p>tsconfig.json</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;declaration&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;lib&quot;: [
      &quot;ES2018&quot;
    ],
    &quot;module&quot;: &quot;CommonJS&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;outDir&quot;: &quot;dist&quot;,
    &quot;resolveJsonModule&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;strict&quot;: true,
    &quot;target&quot;: &quot;ES2018&quot;
  }

  // custom test in vrfContract
  it('Tests if a random number is returned', async () =&gt; {
    expect(await vrfContract.getRandomNumber()).to.be.equal(7);
  });
}
</code></pre>
<p>waffle.json</p>
<pre><code>{
  &quot;compilerType&quot;: &quot;solcjs&quot;,
  &quot;compilerVersion&quot;: &quot;0.6.2&quot;,
  &quot;sourceDirectory&quot;: &quot;./src&quot;,
  &quot;outputDirectory&quot;: &quot;./build&quot;
}
</code></pre>
<p>The <code>yarn.lock</code> file content is a bit large, and it's auto-generated, so you can find it <a href=""https://github.com/EthWorks/Waffle/blob/master/yarn.lock"" rel=""noreferrer"">on the Waffle framework repository</a>. Similarly, the <code>package.json</code> can be found <a href=""https://github.com/EthWorks/Waffle/blob/master/package.json"" rel=""noreferrer"">here</a>, in the same repository.</p>
<h3>Commands</h3>
<p>One can also simply clone the repo with the specified filestructure <a href=""https://github.com/a-t-2/test_vrf3"" rel=""noreferrer"">here</a>, and run the tests with the following commands:</p>
<pre><code>git clone git@github.com:a-t-2/chainlink.git
git clone git@github.com:a-t-2/test_vrf3.git
cd test_vrf3
sudo apt install npm
npm install
npm audit fix
npm install --save-dev ethereum-waffle
npm install @openzeppelin/contracts -D
npm i chai -D
npm i mocha -D
rm -r build
npx waffle
npx mocha
npm test
</code></pre>
<h2>Test Output</h2>
<p>This will test the <code>AmIRichAlready.sol</code> file and output:</p>
<pre><code>  Am I Rich Already
    ✓ checks if contract called balanceOf with certain wallet on the ERC20 token (249ms)
    ✓ returns false if the wallet has less than 1000000 coins (190ms)
    ✓ returns true if the wallet has at least 1000000 coins (159ms)
    Tests if a random number is returned:
     Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={&quot;name&quot;:&quot;RuntimeError&quot;,&quot;results&quot;:{&quot;0x0a0b028de6cf6e8446853a300061305501136cefa5f5eb3e96afd95dbd73dd92&quot;:{&quot;error&quot;:&quot;revert&quot;,&quot;program_counter&quot;:609,&quot;return&quot;:&quot;0x&quot;}},&quot;hashes&quot;:[&quot;0x0a0b028de6cf6e8446853a300061305501136cefa5f5eb3e96afd95dbd73dd92&quot;],&quot;message&quot;:&quot;VM Exception while processing transaction: revert&quot;}, tx={&quot;data&quot;:&quot;0xdbdff2c1&quot;,&quot;to&quot;:{},&quot;from&quot;:&quot;0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff&quot;,&quot;gasPrice&quot;:{&quot;type&quot;:&quot;BigNumber&quot;,&quot;hex&quot;:&quot;0x77359400&quot;},&quot;type&quot;:0,&quot;nonce&quot;:{},&quot;gasLimit&quot;:{},&quot;chainId&quot;:{}}, code=UNPREDICTABLE_GAS_LIMIT, version=abstract-signer/5.4.1)
      at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:225:28)
      at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:237:20)
      at /home/name/git/trucol/tested/new_test/test_vrf3/node_modules/@ethersproject/abstract-signer/src.ts/index.ts:301:31
      at process._tickCallback (internal/process/next_tick.js:68:7)



  3 passing (4s)
</code></pre>
<h2>Question</h2>
<p>Which set of files, file structure and commands do I need to automatically test whether the <code>getRandomNumber()</code> contract returns an integer if sufficient &quot;gas&quot; is provided, and an error otherwise?</p>
",https://stackoverflow.com/questions/69089799/how-to-locally-unit-test-chainlinks-verifiable-random-function,"['unit-testing', 'random', 'solidity', 'chainlink']",2754,True,11,2
How to copy target&#39;s all runtime dependencies after build process in CMake?,"<p>I'm trying to organize auto-copying runtime dependencies of executable targets to its built directories.</p>
<p>As case I use <strong>GTest</strong> for unit-testing that is linking as shared libraries. After building if I try to launch unit-tests there will be an error like &quot;<em>gtest.dll isn't found</em>&quot;. With other external dependencies the same problem (as with local where target is shared library).</p>
<p>I can just add every external library to install process after linking and run tests in that directory but it isn't a practical way as launching <strong>CTest</strong>.</p>
<p>I wanted to use <code>file(GET_RUNTIME_DEPENDENCIES)</code> but it must be called after build and I didn't find <code>INSTALL(CODE)</code> analog for <em>POST_BUILD</em> stage.</p>
<p>Just coping <code>DLLs</code> with <code>add_custom_command</code> don't work too because of possible dependency inheritance.
For example, <strong>A</strong> depends on <strong>B</strong> that depends on <strong>C</strong>. If I try to make dependency copying by this approach then only <strong>B</strong> will be copied in <em>POST_BUILD</em> process of <strong>A</strong>.</p>
<p>I don't like to store all built artifacts in one directory because it creates a mess and could create collisions in the future.</p>
",https://stackoverflow.com/questions/68579934/how-to-copy-targets-all-runtime-dependencies-after-build-process-in-cmake,"['cmake', 'dependencies', 'post-build']",3551,True,3,1
How can I test commits on Kafka MockConsumer?,"<p>When I started to investigate more into Unit testing my Kafka consuming methods, I could not believe just how painfully hard testing with a MockConsumer could be.</p>
<p>I have a piece of code that uses (a.k.a. try with resources) a <code>Consumer&lt;K,V&gt;</code>.</p>
<p>In a unit test, I provide a <code>MockConsumer&lt;K,V&gt;</code> instance and simulate records. (even that was <em>much</em> harder than I anticipated...)</p>
<p>Once the test has run, I need to assert certain things - e.g. did my code commit the right messages?</p>
<p>I tried it all - but apparently <em>all</em> calls to <em>any</em> methods hinting at this give me an Exception
<code>java.lang.IllegalStateException: This consumer has already been closed.</code></p>
<p>Yes - of course - my resource has been closed after my method. Because I am doing it the clean way to use a resource, a.k.a. automatically closing it after using it. But how on earth am I to check what has been committed after the fact? Isn't that what a Mock is all about?</p>
<p>Please enlighten me...</p>
<p>For those of you, who have never heard about MockConsumer -&gt; <a href=""https://kafka.apache.org/23/javadoc/org/apache/kafka/clients/consumer/MockConsumer.html"" rel=""nofollow noreferrer"">https://kafka.apache.org/23/javadoc/org/apache/kafka/clients/consumer/MockConsumer.html</a></p>
",https://stackoverflow.com/questions/66868839/how-can-i-test-commits-on-kafka-mockconsumer,"['java', 'unit-testing', 'apache-kafka']",231,False,2,0
How can I add Mockito to the test classpath in Tycho&#39;s unit-tests with eclipse-plugin packaging,"<p>Recently, it has become possible to <a href=""https://bugs.eclipse.org/bugs/show_bug.cgi?id=572420"" rel=""nofollow noreferrer"">Execute unit-tests with eclipse-plugin packaging</a>. And, in addition there is <a href=""https://bugs.eclipse.org/bugs/show_bug.cgi?id=572602"" rel=""nofollow noreferrer"">support for resolving JUnit Classpath Containers</a>.</p>
<p>I would like to execute unit-tests with eclipse-plugin packaging, but would like to use the <em>mockito</em> library in addition to JUnit. I have a <a href=""https://wiki.eclipse.org/Tycho/pomless"" rel=""nofollow noreferrer"">pomless build</a> and would like to keep it that way. I do not want to add non-PDE files to the build, unless this is unavoidable.</p>
<p><strong>Question</strong>: What is the idiomatic/intended/correct way to add this dependency, or any other test-time dependencies?</p>
<p>Note: I am aware of the use of <code>fragments</code> for unit testing. This is not what I am after. I actually want to use the new mechanism, if possible, or hear that this is currently impossible.</p>
<p>For my initial purposes, and given these are intended to be Unit-tests, running non-OSGI would be ok. If there is a means for OSGI as well, that would be great, but I cannot imagine where the platform configuration could be stored.</p>
",https://stackoverflow.com/questions/69611036/how-can-i-add-mockito-to-the-test-classpath-in-tychos-unit-tests-with-eclipse-p,"['eclipse', 'unit-testing', 'junit', 'mockito', 'tycho']",308,True,2,1
How to evaluate the impact of change for a single line of code or a variable?,"<p>During unit testing it is possible to estimate the code coverage to see which share of the code base is covered by the tests.</p>
<p>For one part (the simple calculatable one) of a risk estimation we need to estimate the impact when a single line or a variable changes on the code base.</p>
<p>E.g. if a variable changes and a pointer to that variable is passed around or used in several places that would result in a rather &quot;impactful&quot; change.</p>
<p>The approach I am looking for is some mixture of introspection and code coverage, but I could not find anything useful so far.</p>
<p>Sure, small changes can completely break the code while large changes might not have an important impact.
But this is only supposed to be one part of the impact analysis, the other one is done by a reviewer.</p>
<p>If such a software or approach does not exist, how is this handled in rather large projects? Is is useful at all or would you recommend a different approach?</p>
",https://stackoverflow.com/questions/68021941/how-to-evaluate-the-impact-of-change-for-a-single-line-of-code-or-a-variable,"['unit-testing', 'code-coverage', 'introspection', 'impact-analysis']",37,False,2,1
Auto increment primary key in mocked db context,"<p>Does anyone know how can I have auto increment primary keys in my mocked db context? I am unit testing a method and when I want to add two items to my mocked db context and I get an error saying &quot;An item with the same key has already been added&quot;. so I should find a way to setup my db context mock such that when every time an item is added, it will be added with different primary key.
this is my method in service class:</p>
<pre><code>public async Task&lt;ProductDTO&gt; CreateProduct(ProductDTO dto)
{
 foreach (var i in dto.Products)
            {
                if (i.ProductId == 0)
                {
                    // New product
                    var product = Product.CreateMyProductDto(i);
                    _db.Products.Add(product);
                }
            }

 // rest of the code …

}
</code></pre>
<p>so here we look at dto.products and if any product has productId equal to zero then we create our product by calling Product.CreateMyProductDto function and add it to Products table. In my unit test below I have two products with productId = 0 hence they should be added to the Products table but I get an error for adding the second product because of the primary key.</p>
<pre><code>[Fact]
public async Task TestForCreateProduct()
{
    //Arrange
     List&lt;Product&gt; products = new List&lt;Product&gt;();

     Product product1 = new Poduct()
     {
           ProductId = 0
     };

     Product product2 = new Poduct()
     {
          ProductId = 0
     };

     // add to the products list
      products.Add(product1);
      products.Add(product2);
      
      ProductDTo dto = new ProductDTO()
      {     
          Products = products
      };

     // create mock
     DbContextMock&lt;MyContext&gt; context_Moq = new DbContextMock&lt;MyContext&gt;(DummyOptions);
        
     // set up mock
     context_Moq.CreateDbSetMock(x =&gt; x.Products, new[]
     {
          new Product { EntityId = 1, Name = &quot;product1&quot;},
          new Product { EntityId = 2, Name = &quot;product2&quot;},
          new Product { EntityId = 3, Name = &quot;product3&quot;}
     });

     var service = new myService(context_Moq.Object);

     // Act
     var result = await service.CreateProduct(dto);
          
     // Assert
     Assert.Equal(5, context_Moq.Object.Products.Count());
}
</code></pre>
<p>I am using .NET core3 so can anyone help me to fix this error? I need to have auto increment primary keys in my mocked db context.</p>
",https://stackoverflow.com/questions/66189672/auto-increment-primary-key-in-mocked-db-context,"['c#', 'unit-testing', '.net-core', 'moq', 'xunit']",839,True,1,1
C++ Perfect Generic Abstract Factory with arbitrary Constructor Arguments,"<p>for unit testing, I'm trying to create a Factory which meets the following requirements:</p>
<ul>
<li>(1) It can create arbitrary objects (e.g. <code>Timer</code> and <code>TimerMock</code>)</li>
<li>(2) It returns <code>unique_ptr</code>s to a Base class to these objects (e.g. <code>unique_ptr&lt;TimerInterface&gt;</code>)</li>
<li>(3) The Factory itself can be passed around as a base class pointer too</li>
<li>(4) It shall be possible to call any constructor to create the Object [edit1]using the same factory object[/edit1]</li>
</ul>
<p>The purpose is to do dependency injection with this factories to be able to exchange objects that are not part of the test with mock objects.</p>
<p>Here's what I have so far:</p>
<pre><code>#include &lt;memory&gt;
#include &lt;iostream&gt;

//&quot;perfect factory method&quot;
//usage: std::unique_ptr&lt;Type&gt; pt(create&lt;Type&gt;(Type-constructor-arguments));
template &lt;typename Type, typename ... ConstructorArgs&gt;
auto create(ConstructorArgs&amp;&amp; ... args){
    return std::make_unique&lt;Type&gt;(std::forward&lt;ConstructorArgs&gt;(args)...);
}

//Abstract Factory Base class
template&lt;typename BaseType, typename ... ConstructorArgs&gt;
class IFactory {
    public:
        virtual ~IFactory() = default;
        virtual std::unique_ptr&lt;BaseType&gt; create(ConstructorArgs&amp;&amp; ... args) const = 0;
};

//Abstract Factory class
template &lt;typename BaseType, typename DerivedType, typename ... ConstructorArgs&gt;
class CFactory : public IFactory&lt;BaseType, ConstructorArgs...&gt;
{
    public:
        using Base = IFactory&lt;BaseType, ConstructorArgs...&gt;;
        std::unique_ptr&lt;BaseType&gt; create(ConstructorArgs&amp;&amp; ... args) const override
        {
            return ::create&lt;DerivedType&gt;(std::forward&lt;ConstructorArgs&gt;(args)...);
        }
};
</code></pre>
<p>How the real Factory classes are defined:</p>
<pre><code>class TimerInterface {
    public:
        TimerInterface() = default;
        TimerInterface (const char* name);
        virtual void whoami() const = 0;
        /*...*/
};

class Timer: public TimerInterface {
    public:
        Timer() = default;
        Timer(const char* name) : TimerInterface (name) {}
        void whoami() const override { std::cerr &lt;&lt; &quot;I'm real!&quot; &lt;&lt; std::endl; }
        /*...*/
};


class TimerMock : public TimerInterface {
    public:
        TimerMock () = default;
        TimerMock (const char* name) : TimerInterface (name) {}
        void whoami() const override { std::cerr &lt;&lt; &quot;I fake it!&quot; &lt;&lt; std::endl; }
        /*...*/
};

using TimerFactory = CFactory&lt;TimerInterface, Timer, const char*&gt;;
using TimerMockFactory = CFactory&lt;TimerInterface, TimerMock, const char*&gt;;

using TimerFactoryInterface = TimerFactory::Base;
</code></pre>
<p>And how they are intended to be used:</p>
<pre><code>class ClassUnderTest {
    public:
        std::unique_ptr&lt;TimerInterface&gt; timer {};
        std::unique_ptr&lt;TimerInterface&gt; timer2 {};
    
        ClassUnderTest(const TimerFactoryInterface&amp; factory)
        : timer(factory.create(&quot;I got a name!&quot;))
        //, timer2(factory.create())
        {}
};

class Production
{
    public:
        ClassUnderTest realUsage;
        
        Production() :
        realUsage(TimerFactory())
        {}
};

class Test
{
    public:
        ClassUnderTest tested;
        
        Test() :
        tested(TimerMockFactory())
        {}  
};

int main()
{
    Production p;
    p.realUsage.timer-&gt;whoami();
    
    Test t;
    t.tested.timer-&gt;whoami();
}
</code></pre>
<p>My big problem is requirement (4)
ClassUnderTest::timer2 can't be created with the same factory that's used for ClassUnderTest::timer, beause the constructor signatur already needs to be known when defining the CFactory class.</p>
<p>Anyone got an idea?</p>
<p>P.S.: &quot;It can't be done&quot; with an explanation is also an acceptable answer, but not my favourite ;)</p>
",https://stackoverflow.com/questions/66185643/c-perfect-generic-abstract-factory-with-arbitrary-constructor-arguments,"['c++', 'abstract-factory']",280,True,1,3
How to fix sporadic read timeout and service unavailable error in Azure Cosmos Emulator (Linux) running in docker?,"<p>I am running  Linux cosmos emulator with below configurations (as per official Microsoft documention) on Ubuntu 20.04.3 ( I tried 18.04 as well)</p>
<pre><code>ipaddr=&quot;`ifconfig | grep &quot;inet &quot; | grep -Fv 127.0.0.1 | awk '{print $2}' | head -n 1`&quot;
sudo docker pull mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator
sudo docker run -d -p 8081:8081 -p 10251:10251 -p 10252:10252 -p 10253:10253 -p 10254:10254  -m 4g --cpus=2.0 --name=test-linux-emulator -e AZURE_COSMOS_EMULATOR_PARTITION_COUNT=10 -e AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE=true -e AZURE_COSMOS_EMULATOR_IP_ADDRESS_OVERRIDE=$ipaddr mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator
</code></pre>
<p>Also adding the certificate to Java keystore as per the official document.</p>
<p><strong>what I am doing?</strong>
I am running Unit testing connecting to Emulator of simple CRUD operation with atmost 1 or 2 items.
Each test will create a container and delete the container.
My Machine configuration is 4 core and 16 GB memory.
I am running Junit in spring boot.</p>
<p><strong>Whats happening?</strong>
Sporadically unit test cases are failing with read timeout or service unavailable error. I have observed in the Emulator UI, that databases disappear sometime but emulator is always up and running.</p>
<p><strong>Note:</strong> The same is working fine when I run cosmos DB Emulator in windows 10 (both exe and as a docker container).</p>
<p><a href=""https://i.stack.imgur.com/Jds3O.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Jds3O.png"" alt=""enter image description here"" /></a></p>
<p><strong>Questions:</strong></p>
<ol>
<li>What could be the issue when running with Linux ?</li>
<li>Is it ok to delete cosmos container(table) and create again for each test cases?</li>
</ol>
<p>Any suggestion for the issue is much appreciated.</p>
",https://stackoverflow.com/questions/69126402/how-to-fix-sporadic-read-timeout-and-service-unavailable-error-in-azure-cosmos-e,"['java', 'linux', 'azure', 'docker', 'azure-cosmosdb']",515,False,1,1
Problem getting native code to work in a module in Android Studio,"<p>I'm trying to build an Android library that has a combo of native code and Java code calling the C++ code. The C++ is stictly limited to the library. I managed to get a project compiling, but when I launch the unit testing, I get an exception that it cannot find the library.<br />
I checked and the code does generate the .so files, but they just can't be found.</p>
<p>So, I created an empty activity project and created in it a module for an Android library.
In it, I placed my code in the <code>src/main/cpp</code> directory, along with a <code>CMakeLists.txt</code> file:<br />
<code>libnative.cpp</code>:</p>
<pre><code>#include &quot;libnativeJNI.h&quot;

#ifdef __cplusplus
extern &quot;C&quot; {
#endif

JNIEXPORT jint JNICALL GEN_FUNCNAME(TestFunction)(JNIEnv *jenv, jobject jobj)
{
    return 0;
}

#ifdef __cplusplus
}
#endif
</code></pre>
<p><code>libnative.h</code>:</p>
<pre><code>#ifndef NDKTROUBLESHOOT_LIBNATIVEJNI_H
#define NDKTROUBLESHOOT_LIBNATIVEJNI_H

#include &quot;jni.h&quot;
#define GEN_FUNCNAME(FUNCNAME) Java_com_java_libnative_libnative_##FUNCNAME

#endif //NDKTROUBLESHOOT_LIBNATIVEJNI_H
</code></pre>
<p><code>CMakeLists.txt</code>:</p>
<pre><code>cmake_minimum_required(VERSION 3.10.2)
project(&quot;LibNative&quot;)
add_library(LibNative SHARED libnativeJNI.cpp)
find_library(log-lib log)
target_link_libraries(LibNative ${log-lib})
</code></pre>
<p>I also updated gradle inside the module to compile the native code by adding the following lines in the <code>android</code> section:</p>
<pre><code>    externalNativeBuild {
        cmake {
            path file('src/main/cpp/CMakeLists.txt')
        }
    }
</code></pre>
<p>The native code is linked to the Java class in <code>src/main/java/com/java/libnative/</code>:<br />
<code>libnative.java</code>:</p>
<pre><code>package com.java.libnative;

public class libnative {
    static
    {
        System.loadLibrary(&quot;LibNative&quot;);
    }

    private native int TestFunction();

    public libnative()
    {
        TestFunction();
    }
}
</code></pre>
<p>I can also see the native code being compiled in a library as <code>libnative/build/intermediates/cmake/debug/obj/{Architecture}/libLibNative.so</code>.</p>
<p>Now, the IDE recognizes the native functions, but I created a unit test in the module to test if it actually works:</p>
<pre><code>package com.java.libnative;
import org.junit.Test;

public class UnitTest {
    @Test
    public void library_canLoad()
    {
        new libnative();
    }
}
</code></pre>
<p>However, doing so triggers an exception on run:</p>
<pre><code>java.lang.UnsatisfiedLinkError: no libnative in java.library.path
</code></pre>
<p>What am I missing to make this work?</p>
",https://stackoverflow.com/questions/65937243/problem-getting-native-code-to-work-in-a-module-in-android-studio,"['java', 'android', 'c++', 'java-native-interface']",128,True,1,1
No rule to make target for googletest,"<p>Scraping the rust off my C++ after many, many years. Lots of new things including CmakeLists.txt. I'm using CLION and googletest, both of which I'm also new to.</p>
<p>I followed the tutorial <a href=""https://raymii.org/s/tutorials/Cpp_project_setup_with_cmake_and_unit_tests.html"" rel=""nofollow noreferrer"">https://raymii.org/s/tutorials/Cpp_project_setup_with_cmake_and_unit_tests.html</a> to set up unit testing for a basic project. Now I'm trying to adapt that project to my test project.</p>
<p>I have changed the library structure. The src directory still contains my source and tst my test, but I have created a lib directory and a git submodule for googletest there.</p>
<p>Here is my root CmakeLists.txt</p>
<pre><code>cmake_minimum_required(VERSION 3.17)
project(processcontroller_test)

set(CMAKE_CXX_STANDARD 17)

include_directories(src)

add_subdirectory(src)
add_subdirectory(tst)
add_subdirectory(lib/googletest)
</code></pre>
<p>and here is the one for src</p>
<pre><code>set(BINARY ${CMAKE_PROJECT_NAME})

file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp)

set(SOURCES ${SOURCES})

add_executable(${BINARY}_run ${SOURCES})

add_library(${BINARY}_lib STATIC ${SOURCES})
</code></pre>
<p>and the one for tst</p>
<pre><code>set(BINARY ${CMAKE_PROJECT_NAME}_tst)

file(GLOB_RECURSE TEST_SOURCES LIST_DIRECTORIES false *.h *.cpp)

set(SOURCES ${TEST_SOURCES})

add_executable(${BINARY} ${TEST_SOURCES})

add_test(NAME ${BINARY} COMMAND ${BINARY})

target_link_libraries(${BINARY} PUBLIC ${CMAKE_PROJECT_NAME}_lib gtest)
</code></pre>
<p>Now when I run the tests using tst/main.cpp I get:</p>
<pre><code>====================[ Build | processcontroller_test_tst | Debug ]==============
/opt/clion/bin/cmake/linux/bin/cmake --build /home/thomas/CLionProjects/processcontroller-test/cmake-build-debug --target processcontroller_test_tst -- -j 12
gmake[3]: *** No rule to make target 'src/CMakeFiles/processcontroller_test_lib.dir/build'.  Stop.
gmake[2]: *** [CMakeFiles/Makefile2:227: src/CMakeFiles/processcontroller_test_lib.dir/all] Error 2
gmake[2]: *** Waiting for unfinished jobs....
[ 40%] Built target gtest
gmake[1]: *** [CMakeFiles/Makefile2:262: tst/CMakeFiles/processcontroller_test_tst.dir/rule] Error 2
gmake: *** [Makefile:210: processcontroller_test_tst] Error 2
</code></pre>
<p>I think the problem is in the last line of my tst/CMakeLists.txt file</p>
<pre><code>target_link_libraries(${BINARY} PUBLIC ${CMAKE_PROJECT_NAME}_lib gtest)
</code></pre>
<p>But I can't see how. Tried reading from the docs about this but can't seem to make heads or tails of it.</p>
<p>I added <code>message(STATUS &quot;Source list:&quot; ${SOURCES})</code> to the src make file and <code>message(STATUS &quot;Test source list:&quot; ${SOURCES})</code> to the tst make and got these results.</p>
<pre><code>-- Source list:/home/thomas/CLionProjects/processcontroller-test/src/water-dispenser.h
-- Test source list:/home/thomas/CLionProjects/processcontroller-test/tst/Arduino-mock.h/home/thomas/CLionProjects/processcontroller-test/tst/main.cpp/home/thomas/CLionProjects/processcontroller-test/tst/water-dispenser-test.cpp
</code></pre>
",https://stackoverflow.com/questions/66385454/no-rule-to-make-target-for-googletest,"['c++', 'cmake', 'googletest']",1290,False,1,1
Odd Subject behavior: why does it act like my subscription was late?,"<p>I have an Angular component that I'm testing via Karma/Jasmine.  On the component, I have an observable following an element's scrolling:</p>
<pre><code>const scroll$ = fromEvent(
      this.chatWindowElem!.nativeElement,
      'scroll'
    )
      .pipe(
        takeUntil(this.destroyed$),
      );
</code></pre>
<p>On that observable, I create a Subject that is going to emit values as to whether a button shows/hides:</p>
<pre><code>const showJumpSub = new ReplaySubject&lt;boolean&gt;();
    this.showJumpToLatestButton$ = showJumpSub
      .pipe(
        startWith(false),
        distinctUntilChanged()
      );

    console.log('sub');
    scroll$
      .subscribe(($event: Event) =&gt; {
        console.log('sub fired');
        const show = this._calculateScrollDistanceFromBottom($event) &gt; 50;
        showJumpSub.next(show);
      });
</code></pre>
<p><code>this.showJumpToLatestButton$</code> is a public property on the component:</p>
<pre><code>public showJumpToLatestButton$: Observable&lt;boolean&gt;;
</code></pre>
<p>This works perfectly fine when developing and playing with it, but once I get to unit testing it breaks.  I have this test:</p>
<pre><code>fit('should emit \'true\' from jump button visible observable', async () =&gt; {
      // Arrange      
      const chat: Chat = new Chat();
      component.chat = chat;
      const scrollTarget = fixtureHelper.getElement('#merc-chat-window');
      
      spyOnProperty(scrollTarget, 'offsetHeight').and.returnValue(100);
      spyOnProperty(scrollTarget, 'scrollHeight').and.returnValue(200);
      spyOnProperty(scrollTarget, 'scrollTop').and.returnValue(49);

      fixture.detectChanges();

      const scrollEvent = new UIEvent('scroll', Object.assign({
        target: scrollTarget
      }));
        
      // Act
      console.log('dispatch');
      scrollTarget.dispatchEvent(scrollEvent);
      console.log('change detect');
      await fixtureHelper.runOnPushChangeDetection();
      console.log('change detect done');
      
      // Assert
      expect(fixtureHelper.getElement('#merc-jump-to-latest').hidden).toBeFalse();
    });
</code></pre>
<p>That test fails as the element I'm testing is still hidden though it shouldn't be.  With my <code>console.log</code>s, I get this output:</p>
<pre><code>sub
dispatch
sub fired
change detect
change detect done
</code></pre>
<p>This shows that my subscription to the <code>Subject&lt;boolean&gt;</code> was created before I dispatched my test event which means my code <em>should</em> work.  However, I can only get this to work and pass if I change <code>Subject&lt;boolean&gt;</code> to <code>ReplaySubject&lt;boolean&gt;</code> which would seem to indicate there is a timing issue with my subscription.  But, the console logging with a <code>ReplaySubject</code> is exactly the same:</p>
<pre><code>sub
dispatch
sub fired
change detect
change detect done
</code></pre>
<p>Can anyone shed a light on why exactly seemingly correct observable usage is giving seemingly incorrect results?</p>
",https://stackoverflow.com/questions/67322697/odd-subject-behavior-why-does-it-act-like-my-subscription-was-late,"['angular', 'rxjs', 'karma-jasmine']",37,False,1,0
How can I create a method to get a string of an element and assert its changes,"<p>I'm quite new to unit testing and c#.</p>
<p>I have an area on a page with a url: <a href=""https://www.testurl.com"" rel=""nofollow noreferrer"">https://www.testurl.com</a> (example)</p>
<p>I have a couple of tick boxes that can change the displayed url on the page.</p>
<p>Example of tick boxes: Http, .net, testurl2</p>
<p>There boxes will change the value of the url and i need to check if the url does change when those boxes are ticked.</p>
<p>How can i create a method for the url so i can call it every  time a box is ticked and use an assert for the expected value?</p>
<p>I have created a Method for the test url as follows:</p>
<pre><code>void TestUrl()
            {
                string url = driver.FindElement(By.CssSelector(&quot;div[class='ui action input'] input[type='text']&quot;)).Text;
                
            }
</code></pre>
<p>And i tried to assert it this way (lets say, after clicking the http:// tick box, changing https:// to http://):</p>
<pre><code>string httpUrl = &quot;http://testurl.com&quot;;
Assert.AreEqual(httpUrl, TestUrl());
</code></pre>
<p>I get the following issue: Argument 2&gt; cannot convert from void to object.</p>
<p>I understand the issue, but i cannot think on a way to get to use the method <code>TestUrl()</code> as i want to.</p>
<p>Hopefully the question is clear, Using examples as i cannot use the urls i am working on as they are confidential.</p>
",https://stackoverflow.com/questions/67331549/how-can-i-create-a-method-to-get-a-string-of-an-element-and-assert-its-changes,"['c#', 'selenium', 'methods']",47,True,1,1
How to unit test async events in Go,"<p>I have some <code>Go</code> code which uses a <code>Ticker</code> to send a periodic signal. It's handled by a <code>select</code> block (code below)
But my unit test coverage report in VSCode is telling me that the block is untested.</p>
<p>My question is, what is the best practice technique for unit testing such code? As I understand it, the normal pattern is to use a mock interface for the function under test.
So would I have to pass in a mock <code>Ticker</code> object to this function? The real <code>Ticker</code> has an embedded channel, which is used to send the periodic events.
All the examples I've looked at are really simple and just involve creating a mock interface, with direct function calls. I've not seen an example which tests async events.</p>
<p>I'm coming from a Java background, which has really good mocking frameworks. Is there anything available for Go, or do people generally roll their own mocks for testing?</p>
<p>Any links to web resources, or example code to demonstrate how to construct a unit test for this appreciated.</p>
<pre><code>func SignalProcess(process string, interval int, wg *sync.WaitGroup) error {
  
  ticker := time.NewTicker(time.Duration(interval) * time.Hour)
  done := make(chan bool)

  defer func() {
    wg.Done()
    done &lt;- true
  }()

  for {
    select {
    case &lt;-done:
        zlog.Info().Msg(&quot;Done event received&quot;)
        return nil
    case &lt;-ticker.C:
        zlog.Info().Msg(&quot;Ticker event received&quot;)
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/67122042/how-to-unit-test-async-events-in-go,"['unit-testing', 'go', 'mocking']",711,False,1,0
Jest fails for same string,"<p>I'm trying unit testing for the first time with Jest on a personal project, and some of my tests failed even though the data received was the exact same as expected, here's an example:</p>
<pre><code>test(&quot;decrypt method works correctly&quot;, () =&gt;{
    const myAES = new rijndael(&quot;&quot;, &quot;0bdfa595235c307a105d593fb78fbb13&quot;, { key: &quot;SOME 128 BIT KEY&quot;, bits: 128, rounds: 9 })
    expect(myAES.decrypt()).toStrictEqual({
        &quot;c&quot;: &quot;0bdfa595235c307a105d593fb78fbb13&quot;,
        &quot;p&quot;: &quot;ATTACK AT DAWN!&quot;,
        &quot;errors&quot;: []
    })
}
</code></pre>
<p><a href=""https://i.stack.imgur.com/DFSar.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/DFSar.png"" alt=""Jest report"" /></a></p>
<p>So then I tried to check if it's a problem with Jest or my code:</p>
<pre><code>const r = myAES.decrypt()
console.log(typeof r.p) // string
console.log(r.p === &quot;ATTACK AT DAWN!&quot;) // false
</code></pre>
<p>Which just made me even more confused as the strings look the same. The code that I'm testing is an AES encryption function (Don't worry it's just a personal project for fun won't be used in production) that processes text as nodeJS <a href=""https://nodejs.org/api/buffer.html"" rel=""nofollow noreferrer"">Buffers</a>, and in the end uses the <a href=""https://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end"" rel=""nofollow noreferrer"">toString()</a> method to convert it back to a string. I'm thinking that may be why I'm having issues, but can't seem to find exactly why. Would love it if someone could point me in the right direction so I can get rid of this error. Thank you in advance.</p>
<p>P.S. I'll save everyone the pain of reading my AES implementation for now as I don't think it's a problem with the encryption but let me know if that's necessary</p>
",https://stackoverflow.com/questions/68224561/jest-fails-for-same-string,"['node.js', 'string', 'jestjs', 'buffer']",465,True,1,1
How to unit test a function that returns nothing (but assigns values to variables)?,"<p>How do you unit test functions that <strong>don't return</strong> anything, but <strong>do</strong> change variables' values?</p>
<p>I've looked through many S.O. questions to try and find an answer; here are a couple slightly-educated guesses:</p>
<ol>
<li>Inside Jest's test(), run the function and then check to see if <code>variable = expectedValue</code></li>
<li>This use-case doesn't require unit testing, it's a simple variable assignment</li>
<li>Rewrite the function specifically so that it returns something</li>
<li>Function shouldn't exist if it's not returning anything, just put the initialization code in parent function</li>
</ol>
<p>1 seems like the best answer; 2 could be right - I'm new and still figuring out <em>what exactly</em> needs to be tested; 3 feels like overkill for some use-cases; 4 can't always be right, sometimes you just need to split out functionality if only for readability.</p>
<hr />
<p><strong>My specific use-case:</strong></p>
<p><code>initializeGame</code> is called within the <code>playGame</code> function. It doesn't return anything; it just sets some variables to their start conditions (player X's turn, empty board, etc.) How can I test that <code>gameTracker</code> was set to <code>[]</code>, for example?</p>
<pre><code>let gameTracker = [], turn;
const turnX = 'X', turnO = 'O';

function playGame() {
  $(document).ready(function () {
    initializeGame();

    $('.square').click(function () {
      makeMove($(this));
      endTurn();
    });
  });
}
function initializeGame() {
  $('.start').css('display', 'none');
  $('.square').children('p').text('');
  gameTracker = [];
  turn = turnX;
  $('h1').text('Player ' + turn + ' Turn');
}
</code></pre>
<p><strong>And the test:</strong></p>
<pre><code>const tictactoe = require('./tictactoe');

test('gameTracker should equal [] after running initializeGame()', () =&gt; {
    tictactoe.initializeGame();
    expect(gameTracker).toBe([]);
})
</code></pre>
",https://stackoverflow.com/questions/66912625/how-to-unit-test-a-function-that-returns-nothing-but-assigns-values-to-variable,"['javascript', 'jquery', 'unit-testing', 'jestjs']",1784,False,0,1
Unit Testing: How to verify that the void method being tested called another method with the correct parameters?,"<p>I am trying to create a unit test for a message handler that utilizes a void method. The current setup is that once a message is published, another message is sent to an external service and that external service returns a success or failure code. Then depending on the whether the message was a success, a failure, or invalid, a method from another class in the component (Util.java) is called to create an event for logging purposes. Here is the basic set up:</p>
<pre><code>public class MessageHandler {

public void OnMessage {

try {

  doSeveralThings{

    code = codeMagicThatDoesntConcernUsCurrently;
  };

   if (code =! &quot;SUCCESS&quot;) {
      Util.createEvent(stringVariable, enumStatusObject.ERROR, mapPayload);
      log.info(&quot;oh no!&quot;)  
      throw new RuntimeException;
   } else {
       Util.createEvent(stringVariable, enumStatusObject.FATAL, mapPayload);
       log.info(&quot;It's invalid!&quot;)
   }

   catch {
       doStuff()
       Util.createEvent(stringVariable, enumStatusObject.EXCEPTION, mapPayload);
       log.info(&quot;Message will be retried.&quot;)
    }

   finally {
     Util.createEvent(stringVariable, enumStatusObject.SUCCESS, mapPayload);
       log.info(&quot;Yay!&quot;)

}

}
</code></pre>
<p>To test these outcomes, I want to verify that the message handler calls this method (Util.createEvent(stringVariable, enumStatusObject.SUCCESS, mapPayload))
with the correct enumStatusObject based on a mocked &quot;code result&quot;.</p>
<p>Things I have tried:</p>
<pre><code>@Mock
Util util

verify(util, times(1)).createEvent(anyString(), eq(enumStatusObject.SUCCESS), anyMap());

Mockito.verify(util, times(1)).createEvent(anyString(), eq(enumStatusObject.SUCCESS), anyMap());

Assert.assertTrue(util.createEvent(anyString(), any(enumStatusObject.class), anyMap()).getStatus().equals(enumStatusObject.SUCCESS))

</code></pre>
<p>I also made an attempt at using ArgumentCaptor from Mockito 2 and had no luck with that.</p>
<p>Is there any way to properly verify this once I call my handler in the test? I am very new to unit testing so I don't know if this is even possible.</p>
<p>the Util.createEvent() method is a static method if that matters. Please advise.</p>
",https://stackoverflow.com/questions/69950406/unit-testing-how-to-verify-that-the-void-method-being-tested-called-another-met,"['java', 'unit-testing', 'mocking', 'mockito', 'powermockito']",241,False,0,0
Golang stretchr testify mock calls to a function within same class,"<p>I am pretty new to Golang and writing unit test for a function (I am using stretchr testify for mocks). This function however calls another function in same class. But when unit testing the first function, I want to mock the call to second function because I do not want it to call the second function in real. This was easy in Java, but I am not finding any useful information for this in Go. Here is some code snippet for my functions:</p>
<pre><code>func (p *Prod) GetProducts(name string, request *prod.ProductRequest) (detail *prod.Department, err error) {
    ....
    ....
    if err = p.getDetails(ctx, detail.Id); err != nil {
        logger.Error(err)
        return
    }
    
    ...
    ...
}

func (p *Prod) GetDetails(name string, Id string) error {
    ....
    ....
}
</code></pre>
<p>As you can see here, <code>GetProducts</code> is the function that I am trying to unit test and this function calls <code>GetDetails</code>. I would like to mock the call to <code>GetDetails</code>. Is this possible in Go? Do we typically mock such function calls in Go. Is it recommended? If yes, whats the right way to do it?</p>
<p>In my test, I have:</p>
<pre><code>for _, tt := range tests {
    t.Run(tt.name, func(t *testing.T) {
    p := &amp;Prod{
        ...
        ds:     tt.fields.ds,

    }
    p.GetProducts(&quot;somestring&quot;, request)
    })
}
</code></pre>
<p>This calls the function GetProducts. But now I don't know what changes to make so the call to GetDetails can be mocked. I would appreciate any help on this</p>
",https://stackoverflow.com/questions/66819860/golang-stretchr-testify-mock-calls-to-a-function-within-same-class,"['unit-testing', 'go', 'testify']",704,False,0,0
Is there a way to make equals (==) check on kotlin.js.Date object work?,"<p>I would like to ask for some help/suggestions on an issue we're facing when trying to unit test platform specific <code>Date</code> classes in our Kotlin Multiplatform project.</p>
<p>Our Kotlin Multiplatform library targets; <strong>JVM</strong>, <strong>Native</strong> &amp; <strong>JavaScript</strong> and is using the platform specific Date classes:</p>
<ul>
<li>java.util.Date (JVM)</li>
<li>platform.Foundation.NSDate (Native)</li>
<li>kotlin.js.Date (JS)</li>
</ul>
<p>Which are exposed via an expected/actual <code>Date</code> class and used in public domain classes in the common package. For example:</p>
<pre><code>public data class Event {
    val id: String,
    val start: Date
}
</code></pre>
<p>Long story short; when unit testing we found that assertEquals works for JVM &amp; Native, but fails for JavaScript. For example:</p>
<pre><code>import kotlin.js.Date
import kotlin.test.Test
import kotlin.test.assertEquals

class DateEqualsTest {

    @Test
    // Fails!
    fun dateEquals() {
        val first = Date(1_630_399_506_000)
        val second = Date(1_630_399_506_000)
        assertEquals(first, second)
    }

    @Test
    // Succeeds
    fun timestampEquals() {
        val first = Date(1_630_399_506_000)
        val second = Date(1_630_399_506_000)
        assertEquals(first.getTime(), second.getTime())
    }
}
</code></pre>
<p>The <code>assertEquals</code> fails for JS due to (I guess) a missing equals() operator in the kotlin.js.Date class.</p>
<p>Any suggestions on how to make the <code>assertEquals</code> work on all platforms given our use case? I can imagine a workaround could be to introduce a <code>DateWrapper</code> class that wraps the <code>Date</code> class and implement the equals() manually... but that would require use to refactor our public API and not sure if that is the best way to go. So any help/ suggestion is super welcome. Many thanks!</p>
",https://stackoverflow.com/questions/68996185/is-there-a-way-to-make-equals-check-on-kotlin-js-date-object-work,"['unit-testing', 'kotlin', 'assertion', 'kotlin-multiplatform', 'kotlin-js']",220,True,0,1
C# undefine project wide preprocessor,"<p>I have a C# project that has some solution wide defines in <em>Conditional compilation symbols</em>, see here
<a href=""https://i.stack.imgur.com/LQseI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/LQseI.png"" alt=""enter image description here"" /></a></p>
<p>I now want to unit test that code and I need to undefine some of those variables.
For Unit testing I have a xUnit project that references the solution with the defines.</p>
<p>Is it possible in VS2019 to disable those defines?</p>
<p><strong>Edit</strong>
In my specific case I have a Unity project added to my solution. Unity has Unity-specific code that cannot be executed in unit tests such like xUnit.</p>
<p>In order to cope with that, I wrap Unity-specific code (like Logging via <code>Debug.Log</code>) into a define <code>UNITY_2020</code> that is automatically defined by the Unity project-file.</p>
<p>Now on the unit test side I want to undefine said preprocessor <code>UNITY_2020</code>. As I have the source code (no DLL or nuget), I hope that there is a way to compile and run my unit tests without having troubles with Unity-specific code.</p>
<p>So far, putting <code>#undef UNTIY_2020</code> at the top of my test files does not help.</p>
",https://stackoverflow.com/questions/67744615/c-undefine-project-wide-preprocessor,"['c#', 'unit-testing']",360,True,-1,1
"Lit Element, unit testing - Nested Elements - Child element does not render","<p>I am very new to lit-element and unit testing and am not sure if the question is even framed correctly. Please correct me if I am wrong anywhere.</p>
<p>So, I have 1 lit component created such that it fetches the json from the uri
<code>&lt;abc infoJsonLink=&quot;../data/data.json&quot;&gt;&lt;/abc&gt;</code></p>
<p>data.json</p>
<pre><code>[
 {&quot;id&quot;:1, &quot;name&quot;:&quot;one&quot;, &quot;img&quot;:&quot;one.jpg&quot;},
{&quot;id&quot;:1, &quot;name&quot;:&quot;two&quot;, &quot;img&quot;:&quot;two.jpg&quot;}, 
...]
</code></pre>
<p>Within abc's render() method, we loop through the json data and create a array with html markup corresponding to each item, <code>itemsMarkupList</code></p>
<pre><code> *0* &lt;div &quot;item-data&quot;&gt;&lt;span&gt;one&lt;/span&gt;&lt;img src=&quot;one.jpg&quot;/&gt;&lt;/div&gt; 
 *1* &lt;div &quot;item-data&quot;&gt;&lt;span&gt;two&lt;/span&gt;&lt;img src=&quot;two.jpg&quot;/&gt;&lt;/div&gt;  
 *2* ...
</code></pre>
<p>Each one of these markups, has to be rendered in a bootstrap carousel. <a href=""https://mdbootstrap.com/snippets/jquery/ascensus/135508"" rel=""nofollow noreferrer"">https://mdbootstrap.com/snippets/jquery/ascensus/135508</a></p>
<p>For this we have created another component, <code>&lt;carousel-helper&gt;</code>, which has the code to accept an array of markups and render it as a carousel using bootstrap libraries.</p>
<p>Below is the <code>render()</code> method of <code>&lt;abc&gt;</code> component</p>
<pre><code>render(){... 
let ch = document.createElement(&quot;carousel-helper&quot;); 
ch.itemsMarkupList = this.itemsMarkupList;
return html`... &lt;div class=&quot;parent_wrapper&quot;&gt; ${ch} &lt;/div&gt;`;
}
</code></pre>
<p>This whole renders perfectly when I <code>npm run</code> it.</p>
<p>But when I am writing the test cases for this,  the shadowroot of child elements seems to be not rendering.</p>
<pre><code>  it(&quot;test1&quot;, async () =&gt; {
   const el = /** @type {Abc} */ (await fixture(
    html`&lt;abc infoJsonLink=&quot;/data/data.json&quot;&gt;&lt;/abc&gt;
    `));

  await el.loadJsonData();

  /*statement 1*/
  console.log(el.shadowRoot.querySelector(&quot;carousel-helper&quot;)); 

  /*statement 2*/
  console.log(el.shadowRoot.querySelector(&quot;carousel-helper&quot;).
    shadowRoot.querySelectorAll(&quot;.item-data&quot;));

  }); 
</code></pre>
<p><em>statement-1</em> works and returns <code>&lt;carousel-helper&gt;&lt;/carousel-helper&gt; </code><br />
<em>statement-2</em> return and empty array, <code>NodeList {}</code></p>
<p>Can anyone tell me what I need to do to get a filled array from <em>statement-2</em>?</p>
",https://stackoverflow.com/questions/67979324/lit-element-unit-testing-nested-elements-child-element-does-not-render,"['unit-testing', 'web-component', 'web-testing', 'lit-element', 'react-testing']",913,False,0,0
Best practice for integration testing in React Redux app?,"<p>I'm trying to set up tests for a React-Redux application. Most resources including <a href=""https://redux.js.org/usage/writing-tests"" rel=""nofollow noreferrer"">Redux Docs</a>, and <a href=""https://kentcdodds.com/blog/testing-implementation-details"" rel=""nofollow noreferrer"">the main contributor to react-testing-library</a> argues for a focus on integration tests and that the Redux code as far as possible should be considered an implementation detail. That's cool and all, but I'm struggling to do this in practice.</p>
<p>Most examples I've found on integration testing sets up a component where you can observe the effect in the immediate unit. But several places in my app, I have components that send dispatches to my store which causes a re-render in another part of the app. To illustrate my question, I've made a simplified component tree below where I want to click the <code>AddToListButton</code> to cause <code>Element1</code> to be added to the <code>List</code>.</p>
<p>If Redux is an implementation detail, how do I actually test that clicking the button causes the update without rendering (more or less) the whole app? I understand how to do unit-testing and end-to-end testing, but not sure how I would implement integration testing.</p>
<pre><code>&lt;App&gt;
  &lt;Search&gt;
    &lt;SearchResult&gt;
      &lt;Element1&gt;
        &lt;AddToListButton /&gt; //I WANT TO TEST THIS BUTTON
      &lt;/Element1&gt;
      &lt;Element2&gt;
        &lt;AddToListButton /&gt;
      &lt;/Element2&gt; 
    &lt;/SearchResult&gt;
  &lt;/Search&gt;
  &lt;List&gt;
    &lt;Element1 /&gt; // WHEN THE BUTTON IS PRESSED THE ELEMENT SHOULD GO HERE
  &lt;/List&gt;
&lt;/App&gt;

</code></pre>
",https://stackoverflow.com/questions/68939827/best-practice-for-integration-testing-in-react-redux-app,"['reactjs', 'redux', 'react-testing-library']",128,True,0,1
unit test for django models containing &quot;User&quot; as ManyToManyField,"<p>So, I have a model 'Page' that has the already provided with django model, &quot;User&quot; as the manyToManyField like this</p>
<p>I think to unit test, I first create an instance of Page then assign what? err... a user to the favorite field? For this , I would have to create an instance of User ,right ? Or can I also it the other way around, create user then attach a page to pages ?</p>
<p>Also, my feature to test requires the user be logged in . How do I simulate or fake login in for the purpose of a unit test ?</p>
<p>Can you suggest how to go on about what should go in this favorite field to create an object of this kind successfully and how to have P be related to favorite to be able to conduct unit test.
Also, what unit test can I do for this ManyToManyField?</p>
<p>Another different question, are all foreign keys necessary to be be there for creating an object of a table for unit testing ?</p>
",https://stackoverflow.com/questions/68669040/unit-test-for-django-models-containing-user-as-manytomanyfield,"['django', 'unit-testing', 'django-models', 'manytomanyfield']",104,True,0,1
Why does Jacoco report show different coverages on consecutive test runs?,"<p>I just added JaCoCo code coverage with <code>jacoco-maven-plugin</code> to a Quarkus application using <code>quarkus-junit5</code> and <code>maven-surefire-plugin</code> for unit testing.</p>
<p>JaCoco reports are there when I run <code>mvn clean verify</code> but I noticed that when I run them again <strong>I get another coverage</strong>. Most of the time the coverage report <strong>doesn't include lines which are definetly covered by the unit tests</strong>.</p>
<p>I know that the line coverage actually is at <strong>84%</strong>. IntelliJ IDEA coverage runner shows this one and also JaCoCo runner one time managed to show that one.</p>
<p>But most of the time JaCoCo report shows a much lower line coverage at <strong>20%</strong> or <strong>30%</strong>.</p>
<p>I am running JaCoCo in instrumentation offline mode as on-the-fly mode interfered with Quarkus.</p>
<p>This is my set up:</p>
<p>JaCoCo Agent dependency:</p>
<pre><code>&lt;dependency&gt;
  &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
  &lt;artifactId&gt;org.jacoco.agent&lt;/artifactId&gt;
  &lt;classifier&gt;runtime&lt;/classifier&gt;
  &lt;scope&gt;test&lt;/scope&gt;
  &lt;version&gt;${jacoco.version}&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<p>JaCoCo plugin:</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.version}&lt;/version&gt;
    &lt;executions&gt;
        &lt;execution&gt;
            &lt;goals&gt;
                &lt;goal&gt;instrument&lt;/goal&gt;
                &lt;goal&gt;restore-instrumented-classes&lt;/goal&gt;
                &lt;goal&gt;report&lt;/goal&gt;
            &lt;/goals&gt;
        &lt;/execution&gt;
    &lt;/executions&gt;
&lt;/plugin&gt;

</code></pre>
<p>Surefire plugin:</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;3.0.0-M5&lt;/version&gt;
    &lt;configuration&gt;
        &lt;systemPropertyVariables&gt;
            &lt;jacoco-agent.destfile&gt;${project.build.directory}/jacoco.exec&lt;/jacoco-agent.destfile&gt;
            &lt;java.util.logging.manager&gt;org.jboss.logmanager.LogManager&lt;/java.util.logging.manager&gt;
            &lt;maven.home&gt;${maven.home}&lt;/maven.home&gt;
            &lt;hibernate.search.backend.directory.type&gt;local-heap&lt;/hibernate.search.backend.directory.type&gt;
        &lt;/systemPropertyVariables&gt;
    &lt;/configuration&gt;
&lt;/plugin&gt;

</code></pre>
<p>In case you need to know more, the pom.xml:</p>
<pre><code>&lt;?xml version=&quot;1.0&quot;?&gt;
    &lt;project
        xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
        xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 
        https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;
        xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot;&gt;
    &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt;
    &lt;artifactId&gt;backend&lt;/artifactId&gt;
    &lt;properties&gt;
        &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
        &lt;project.reporting.outputEncoding&gt;UTF-8&lt;/project.reporting.outputEncoding&gt;

        &lt;org.mapstruct.version&gt;1.4.2.Final&lt;/org.mapstruct.version&gt;
        &lt;jacoco.version&gt;0.8.7&lt;/jacoco.version&gt;
    &lt;/properties&gt;
    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-resteasy&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-smallrye-health&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-junit5&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.assertj&lt;/groupId&gt;
            &lt;artifactId&gt;assertj-core&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.exparity&lt;/groupId&gt;
            &lt;artifactId&gt;hamcrest-date&lt;/artifactId&gt;
            &lt;version&gt;2.0.7&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.rest-assured&lt;/groupId&gt;
            &lt;artifactId&gt;rest-assured&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-container-image-docker&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-hibernate-validator&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-hibernate-orm-panache&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-flyway&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-resteasy-jackson&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-jdbc-postgresql&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-micrometer&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.micrometer&lt;/groupId&gt;
            &lt;artifactId&gt;micrometer-registry-prometheus&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;io.quarkus&lt;/groupId&gt;
            &lt;artifactId&gt;quarkus-jdbc-h2&lt;/artifactId&gt;
            &lt;scope&gt;test&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;version&gt;1.18.16&lt;/version&gt;
            &lt;scope&gt;provided&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
            &lt;artifactId&gt;commons-lang3&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
            &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hibernate.search&lt;/groupId&gt;
            &lt;artifactId&gt;hibernate-search-mapper-orm&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.hibernate.search&lt;/groupId&gt;
            &lt;artifactId&gt;hibernate-search-backend-lucene&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mapstruct&lt;/groupId&gt;
            &lt;artifactId&gt;mapstruct&lt;/artifactId&gt;
            &lt;version&gt;${org.mapstruct.version}&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mapstruct&lt;/groupId&gt;
            &lt;artifactId&gt;mapstruct-processor&lt;/artifactId&gt;
            &lt;version&gt;${org.mapstruct.version}&lt;/version&gt;
            &lt;scope&gt;provided&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
            &lt;artifactId&gt;org.jacoco.agent&lt;/artifactId&gt;
            &lt;classifier&gt;runtime&lt;/classifier&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;version&gt;${jacoco.version}&lt;/version&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;
    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.jacoco&lt;/groupId&gt;
                &lt;artifactId&gt;jacoco-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;${jacoco.version}&lt;/version&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;instrument&lt;/goal&gt;
                            &lt;goal&gt;restore-instrumented-classes&lt;/goal&gt;
                            &lt;goal&gt;report&lt;/goal&gt;
                        &lt;/goals&gt;
                    &lt;/execution&gt;
                &lt;/executions&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.jboss.jandex&lt;/groupId&gt;
                &lt;artifactId&gt;jandex-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;1.0.8&lt;/version&gt;
                &lt;executions&gt;
                    &lt;execution&gt;
                        &lt;id&gt;make-index&lt;/id&gt;
                        &lt;goals&gt;
                            &lt;goal&gt;jandex&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.8.1&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;parameters&gt;true&lt;/parameters&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt;
                &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt;
                &lt;version&gt;3.0.0-M5&lt;/version&gt;
                &lt;configuration&gt;
                    &lt;systemPropertyVariables&gt;
                        &lt;jacoco-agent.destfile&gt;${project.build.directory}/jacoco.exec&lt;/jacoco-agent.destfile&gt;
                        &lt;java.util.logging.manager&gt;org.jboss.logmanager.LogManager&lt;/java.util.logging.manager&gt;
                        &lt;maven.home&gt;${maven.home}&lt;/maven.home&gt;
                        &lt;hibernate.search.backend.directory.type&gt;local-heap&lt;/hibernate.search.backend.directory.type&gt;
                    &lt;/systemPropertyVariables&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
    &lt;/build&gt;
&lt;/project&gt;
</code></pre>
<p>I would appreciate if someone has an idea what is the reason for this behaviour and could help me.</p>
<p>In case you advise me to use the <code>quarkus-jacoco</code> extension. I tried this one by removing <code>jacoco-maven-plugin</code> and adding the <code>quarkus-jacoco</code> extension, but then I run into another problem after executing <code>mvn clean verify</code>:</p>
<pre><code>Caused by: io.quarkus.builder.BuildException:
Build failure: Build failed due to errors
        [error]: Build step io.quarkus.jacoco.deployment.JacocoProcessor#transformerBuildItem threw an exception: java.lang.NoClassDefFoundError: io/quarkus/deployment/builditem/BytecodeTransformerBuildItem$Builder
        at io.quarkus.jacoco.deployment.JacocoProcessor.transformerBuildItem(JacocoProcessor.java:71)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:972)
        at io.quarkus.builder.BuildContext.run(BuildContext.java:277)
        at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
        at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:2046)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1578)
        at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1452)
        at java.base/java.lang.Thread.run(Thread.java:834)
        at org.jboss.threads.JBossThread.run(JBossThread.java:479)
Caused by: java.lang.ClassNotFoundException: io.quarkus.deployment.builditem.BytecodeTransformerBuildItem$Builder
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
        at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:412)
        at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:365)
        ... 13 more
</code></pre>
",https://stackoverflow.com/questions/68209879/why-does-jacoco-report-show-different-coverages-on-consecutive-test-runs,"['code-coverage', 'junit5', 'quarkus', 'maven-surefire-plugin', 'jacoco-maven-plugin']",1359,False,0,1
"How to set KOFAX KTM Server global variable value which will be initialized in Batch open, updated in SeparateCurrentPage &amp; used in BatchClose?","<p>I am trying to count a specific barcode value from Project.Document_SeparateCurrentPage and use it in BatchClose to compare if the count is greater than 1 and if it is &gt;1 then send the batch to a specific queue with specific priority. I used a global variable in KTM Project Script to hold the count value which was initialized to 0 in Batch open. It worked fine until unit testing. But our automation team found that out of 20 similar batches, few batches were sent to the queue where the batch should go only if the count satisfies the greater than one condition, though they used only one barcode.</p>
<p>I googled and found that KTM Server script events do not allow to use shared information in different processes(<a href=""https://docshield.kofax.com/KTM/en_US/6.4.0-uuxag78yhr/help/SCRIPT/ScriptDocumentation/c_ServerScriptEvents.html"" rel=""nofollow noreferrer"">https://docshield.kofax.com/KTM/en_US/6.4.0-uuxag78yhr/help/SCRIPT/ScriptDocumentation/c_ServerScriptEvents.html</a>). Then I tried to use a batch field to hold the barcode count but unable to update its value from Project.Document_SeparateCurrentPage function using <code>pXRootFolder.Fields.ItemByName(&quot;BatchFieldName&quot;).Text = &quot;GreaterThanOne&quot;</code>. The logs show that the batch reads the first page three times and then errors out.</p>
<p>Any links would help. Thanks in advance.</p>
",https://stackoverflow.com/questions/68528013/how-to-set-kofax-ktm-server-global-variable-value-which-will-be-initialized-in-b,"['scripting', 'kofax']",117,True,0,1
"Is it possible to spy on an object in which I have no control over it&#39;s creation, using mockk?","<p>I have a Kotlin project using <a href=""https://kotest.io/"" rel=""nofollow noreferrer"">kotest</a> as my unit testing framework and <a href=""https://mockk.io/"" rel=""nofollow noreferrer"">mockk</a> to take care of my mocking requirements. I am new to all aspects of the Kotlin language and chosen testing libraries/frameworks.</p>
<p>I have a simple class in which a function creates an object which I want to spy on.</p>
<pre class=""lang-kotlin prettyprint-override""><code>import java.net.URI

class MyClass {
    public fun doStuff() {
        val uri = URI(&quot;https://some-random-endpoint.com/get/some/stuff&quot;)
        // ...
        // ...use URI object to get some stuff
        // ...
    }
}
</code></pre>
<p>I would like to spy on the creation of the URI object to ensure it's passed the correct endpoint. Based off of <a href=""https://mockk.io/#spy"" rel=""nofollow noreferrer"">the documentation</a> I initially thought I could achieve my goal like this:</p>
<pre class=""lang-kotlin prettyprint-override""><code>import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import io.mockk.spyk
import java.net.URI

class MyClassTest : FunSpec({
    test(&quot;doStuff should be targeting the correct endpoint&quot;) {
        val urlSpy = spyk&lt;URI&gt;()
        val myClass: MyClass = MyClass()
        myClass.doStuff()
        urlSpy.host shouldBe &quot;some-random-endpoint.com&quot;
        urlSpy.path shouldBe &quot;/get/some/stuff&quot;
    }
})
</code></pre>
<p>However, this fails as both <code>urlSpy.host</code> and <code>urlSpy.path</code> are <code>null</code>.</p>
<p>I've clearly misunderstood something. I suspect the under-the-hood magic I was hoping for is not associating my spy with the creation of the URI object in <code>MyClass.doStuff()</code></p>
<p>If I replace my spy with a <code>mockk</code> then the creation of the URI object is mocked, as I would expect. However, a mock doesn't seem the correct object for me in this case... I don't want to mock the behaviour, I just want to verify the behaviour as it's coded.</p>
<p>Where am I going wrong?</p>
",https://stackoverflow.com/questions/67708110/is-it-possible-to-spy-on-an-object-in-which-i-have-no-control-over-its-creation,"['unit-testing', 'kotlin', 'spy', 'mockk', 'kotest']",944,False,0,0
org.mockito.exceptions.misusing.MissingMethodInvocationException - cannot test exception when method calls other protected methods,"<p>I cannot mock the private methods using mockito, but the method access specifier can be package or protected so i did that. but even after that i cannot achieve unit testing an exception throwing when the actual method contains several other protected method calls.</p>
<p><strong>source:</strong></p>
<pre><code>public class ConsumeService {
    
      private DataProcessService dataProcessService;
    
    @JmsListener
      public void getMessage(final Message message) throws InterruptedException {
    
        if (message instanceof TextMessage) {
          TextMessage textMessage = getTextMessage(message);
          try {
            
            Map&lt;String, String&gt; attributes = prepareInfo(textMessage);
            dataProcessService.processRequestData(
                message.getText(), attributes);
            
    
          } catch (JMSException e) {
            log.error(&quot;JMSException in message&quot;);
          } catch (ResourceAccessException e) {
            log.error(&quot;IOException in message&quot;);
          }
        } else {
          log.error(&quot;message convertion failed!&quot;);
        }
      }
     }
     
     TextMessage getTextMessage(final Message message) {
        return (TextMessage) message;
    }
    
    Map&lt;String, String&gt; prepareInfo(TextMessage message) throws JMSException {

    ..
    ..
    
    return result;
  }
</code></pre>
<p><strong>Test method:</strong></p>
<pre><code>    @ExtendWith(MockitoExtension.class)
public class ConsumeServiceTest {

  
     
    @InjectMocks ConsumeService consumeService;
    
    @Mock DataProcessService dataProcessService;
    
    @Test
  public void receiveMessageException() throws ResourceAccessException, JMSException{
    
    TextMessage message = mock(TextMessage.class);
    TextMessage textMessage = mock(TextMessage.class);
    Map&lt;String, String&gt; mockMap = mock(HashMap.class);
    
    when(consumeService.getTextMessage(message)).thenReturn(textMessage); //67 line
    when(consumeService.prepareInfo(textMessage)).thenReturn(mockMap);
    
    Mockito.lenient().
    when(
        dataProcessService.processRequestData(
                textMessage.getText(), mockMap))
    .thenThrow(ResourceAccessException.class);
    
    assertThrows(
            ResourceAccessException.class,
            () -&gt; this.consumeService.getMessage(message));
    }   
            
}
</code></pre>
<p><strong>Error:</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.sample.rest.listner.service.ConsumeServiceTest.receiveMessageException(ConsumeServiceTest.java:67)
</code></pre>
<p>I absolutely have no clue how to resolve this. I am understanding the error is in stubing but i am not understanding how to fix this.
Secondly, an util method specifically useful for a class can be declared as private and in the same file. I do not see why mockito discourage private/static method mocking or testing in that way? Is it possible at all? i am using mockito with junit5</p>
<hr />
<p><strong>Update</strong></p>
<p>Modified the test method</p>
<p><strong>Updated test method:</strong></p>
<pre><code>@Test
  public void receiveMessageException() throws ResourceAccessException, JMSException{

    
    TextMessage message = mock(TextMessage.class);
    
    Mockito.lenient().
    when(
        dataProcessService.processRequestData(
                Mockito.anyString(), Mockito.any(Map.class)))
    .thenThrow(ResourceAccessException.class);
    
    assertThrows(
            ResourceAccessException.class,
            () -&gt; this.consumeService.getMessage(message));
  }
</code></pre>
<p>and now the <strong>error</strong> is</p>
<pre><code>org.opentest4j.AssertionFailedError: Expected org.springframework.web.client.ResourceAccessException to be thrown, but nothing was thrown.
</code></pre>
<p>My assumption is it is failing in this line Map&lt;String, String&gt; attributes = prepareInfo(textMessage);
I am not sure. when i run the test in debug mode, i see attributes is an empty object.
How to throw this ResourceAccessException</p>
",https://stackoverflow.com/questions/68513813/org-mockito-exceptions-misusing-missingmethodinvocationexception-cannot-test-e,"['unit-testing', 'junit', 'mockito', 'junit5', 'spring-jms']",3606,False,0,1
linking with wrap directive for unit testing can be used to redefine a subroutine?,"<p>I'm using Cmocka to write a unit testing suite for a shared object written in C, but I'm having some issue. Since I cannot share the source code, I have written a minimum &quot;not-working&quot; example to show what is the issue:</p>
<p>my program is composed 5 files: foo.c, foo.h bar.c bar.h main.c.</p>
<ul>
<li>bar.* files define a bar() function, which simply returns the argument multiplied by 2</li>
<li>foo.* files declare a foo() function that uses the bar() function defined by bar.h</li>
<li>main.c contains a simple cmocka test and a <em><strong>__wrap_bar()</strong></em></li>
</ul>
<p>function, returning the argument multiplied by 3.</p>
<p>I compile the program by producing a libfootest.so object (foo+bar) and then I link this object with main.o passing the -Wl,--wrap=bar flag to the compiler.  In this configuration <strong>libfootest</strong> is the module under test and main is the tester program. I expect the __wrap__bar to be called (failing the test), but the standard bar() is called(test is passed). How can I solve this problem? Below you find all the code I'm using.</p>
<p>bar.c:</p>
<pre><code>#include &quot;bar.h&quot;
int bar(int val) {
    return val*2;
}
</code></pre>
<p>bar.h:</p>
<pre><code>int bar(int val);
</code></pre>
<p>foo.h:</p>
<pre><code>#include &lt;stdio.h&gt;

int foo(int val);
</code></pre>
<p>foo.c:</p>
<pre><code>#include &quot;foo.h&quot;
#include &quot;bar.h&quot;
int foo(int val) {
    int ret;
    ret = bar(val);
    printf(&quot;RET: %d&quot;, ret);
    return ret;
}
</code></pre>
<p>main.c:</p>
<pre><code>#include &lt;stdio.h&gt;
//required include for CMOCKA
#include &lt;stdarg.h&gt;
#include &lt;stddef.h&gt;
#include &lt;stdint.h&gt;
#include &lt;setjmp.h&gt;
#include &lt;cmocka.h&gt;


//library under test
#include &quot;foo.h&quot;
int __wrap_bar(int val) {
        return 3*val;
}


static void test_foo(void **state) {
    int ret = foo(5);
    assert_int_equal(ret, 10);
    

}

int main (int argc, char** argv) {
    const struct CMUnitTest tests[] = {
        cmocka_unit_test(test_foo),
    };

    return cmocka_run_group_tests(tests, NULL, NULL);
}
</code></pre>
<p>Makefile:</p>
<pre><code>CMOCKA_LIB_DIR=../../cmocka-1.1.5/build/src
CXXFLAGS+=-g -Og  -fPIC
CFLAGS+=-g  -Og  -std=c99 -fPIC
CC=gcc
CXX=g++

all: main.o ./libfootest.so
    gcc -o linux-test -g -L. -L$(CMOCKA_LIB_DIR) $(filter %.o, $^) -lcmocka -lfootest -Wl,-rpath=. -Wall -Wl,--wrap=bar -Wl,-rpath=$(CMOCKA_LIB_DIR)

./libfootest.so: foo.o bar.o
    $(CC) -shared -o $@ -g $^  -pedantic -Wall

clean: 
    rm -f *.o
    rm -f *.so
</code></pre>
",https://stackoverflow.com/questions/68257570/linking-with-wrap-directive-for-unit-testing-can-be-used-to-redefine-a-subroutin,"['c', 'unit-testing', 'gcc', 'ld', 'cmocka']",170,True,0,1
Conditional Django settings import based on the value of a command line argument,"<p>I have the following code at the end of my Django settings:</p>
<pre><code>if not TESTING:
    # Don't use local settings for tests, so that tests are always reproducible.
    try:
        from .local_settings import *
    except ImportError:
        pass
</code></pre>
<p>local_settings.py contains all the external dependencies URLs used by my Django application, such as database server URL, email server URL and external APIs URLs. Currently the only external dependency my test suite uses is a local test database; everything else is mocked.</p>
<p>However, now I'd like to add some tests that validate responses from the external APIs I use, so that I can detect quickly when an external API changes without prior notice. I'd like to add a --external-deps command line argument to &quot;./manage.py test&quot; and only run tests that depend on external APIs if this flag is enabled.</p>
<p>I know that I can process arguments passed to that command by overriding the add_arguments() method of the DiscoverRunner class, as described in <a href=""https://stackoverflow.com/questions/28229864/django-manage-py-is-it-possible-to-pass-command-line-argument-for-unit-testin/51901026#51901026"">Django manage.py : Is it possible to pass command line argument (for unit testing)</a> , but my conditional Django settings loading are run before that, so the following won't work:</p>
<pre><code>if not TESTING or TEST_EXTERNAL_DEPS:
    # Don't use local settings for tests, so that tests are always reproducible.
    try:
        from .local_settings import *
    except ImportError:
        pass
</code></pre>
<p>Is there a way to achieve what I want?</p>
",https://stackoverflow.com/questions/67663423/conditional-django-settings-import-based-on-the-value-of-a-command-line-argument,"['python', 'django']",137,False,0,0
Tap operator inside NGXS state is not called during test,"<p>I'm working on a Angular 6 application with NGXS and I'm struggling with some tests...</p>
<p>One of our asynchronous action was returning a subscription, something like :</p>
<pre><code>@Action(MyActions.MyAction, {cancelUncompleted: true})
myAction(ctx: StateContext&lt;MyModel&gt;) {
   return this.someHttpCall().subscribe(xxx =&gt; ctx.patchState({value: xxx}));
}
</code></pre>
<p>It was working well but the cancellation mechanism was not working because NGXS want us to return an observable and not a subscription so I fixed it following the guidelines (<a href=""https://www.ngxs.io/advanced/actions-life-cycle#asynchronous-actions"" rel=""nofollow noreferrer"">https://www.ngxs.io/advanced/actions-life-cycle#asynchronous-actions</a>)</p>
<pre><code>@Action(MyActions.MyAction, {cancelUncompleted: true})
myAction(ctx: StateContext&lt;MyModel&gt;) {
   return this.someHttpCall().pipe(tap(xxx =&gt; ctx.patchState({value: xxx})));
}
</code></pre>
<p>Now the cancellation mechanism is working but some tests failed because it seems the state is never patched.</p>
<p>I checked those links :</p>
<p><a href=""https://www.ngxs.io/recipes/unit-testing#testing-asynchronous-actions"" rel=""nofollow noreferrer"">https://www.ngxs.io/recipes/unit-testing#testing-asynchronous-actions</a></p>
<p><a href=""https://stackoverflow.com/questions/50415966/pipe-and-tap-vs-subscribe-with-ngxs"">Pipe and Tap VS subscribe with ngxs</a></p>
<p>And it seems I have to subscribe to the returned observable if I want the tap to be triggered so in my test I did something like this :</p>
<pre><code>store.dispatch(new MyAction()).subscribe()
</code></pre>
<p>The subscribe in the test (last code) is called, the state is also called but the &quot;tap&quot; still never called...</p>
<p>I also try to change the state code to :</p>
<pre><code>@Action(MyActions.MyAction, {cancelUncompleted: true})
myAction(ctx: StateContext&lt;MyModel&gt;) {
   return this.someHttpCall().pipe(tap(xxx =&gt; ctx.patchState({value: xxx}))).subscribe()
}
</code></pre>
<p>It works (the &quot;tap&quot; is called and the state is patched) but obviously the cancel mechanism is not working anymore...</p>
<p>Thanks in advance :-)</p>
",https://stackoverflow.com/questions/66015283/tap-operator-inside-ngxs-state-is-not-called-during-test,"['angular', 'testing', 'tap', 'ngxs']",247,False,0,1
How to test class using Read/WriteConsoleW,"<p>I have a custom <code>std::ostream</code> that uses <code>WriteConsoleW</code> and similar <code>std::istream</code> using <code>ReadConsoleW</code>.
The code is pretty simple and boils down to:</p>
<pre><code>HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
DWORD dummy;
if(GetConsoleMode(h, &amp;dummy) != FALSE)
  ReadConsoleW(h, ...)
</code></pre>
<p>I would like to (unit/integration) test this. The issue:</p>
<ul>
<li>If I redirect input to the program (<code>echo foo | test.exe</code>) it is no longer a console so I can't use <code>ReadConsoleW</code> so making it a full-blown integration test testing a sample program from the outside seems impossible</li>
<li>Similar for pretty much any unit testing framework which gathers stdout/stderr so <code>WriteConsoleW</code> cannot be used anymore making testing inside any framework hard</li>
</ul>
<p>How can I still test this?</p>
<p>I imagine either faking <code>STD_INPUT_HANDLE</code> so the above <code>GetConsoleMode</code> returns true and then putting (somehow?) some input there / getting the output checking for the expected stuff.</p>
<p>OR:</p>
<p>Somehow run the program via some WindowsAPI in a way that <code>STD_INPUT_HANDLE</code>/<code>STD_OUTPUT_HANDLE</code> are detected as consoles but in fact being able to fill stdin from the parent program and read stdout, then check that for the expected values.</p>
<p>However I can't find any resources on that. Any ideas/hints? Has anyone ever done this?</p>
<p>PS: Code is for Boost, i.e. OpenSource if that matters.</p>
",https://stackoverflow.com/questions/70323798/how-to-test-class-using-read-writeconsolew,"['c++', 'windows', 'testing', 'winapi', 'console']",63,False,0,0
userform multicolumn listbox not showing records unless form is closed and re-opened,"<p>I have 4 user input forms where user inputs/edits records via fields on the form and the records display below in a multi-column listbox. (There are also Save and Delete buttons on the forms.) They have all worked fine for weeks of unit testing. Now that I have coded and debugged the calculations part of the project, I have started a final round of system testing where I am starting with blank data sheets. And the listboxes are showing a strange (new) behavior.</p>
<p>When I open a form with no records, enter the first record and save it, the record is not displayed. The record does get saved properly on the data sheets. The first column of the listbox displays the record number and the rest of the columns are blank. However, I am not including (displaying) the record number (column A) on the forms. I only display values from columns 2 the 7 (B thru H) of the data sheet. It will only show the record number for every record I enter thereafter, as long as I am in the same &quot;session&quot; of the open form when I entered the first record.</p>
<p>However, if I close the form and re-open it, the records displays as they should. And any subsequent records I enter after I re-open the form, the new records also display properly. Even if I delete all the records on the form and ad new ones, they display fine as long as I have not closed the form. This behavior is the same for all 4 of the forms. The forms all worked properly when I created them, and for literally a couple of months of unit testing after that. Admittedly, I have made a lot of code changes to correct errors I have found in the calculations part of my project. But I cannot conceive of any that would globally affect listboxes on all the forms.</p>
<p>Example code for one of the forms Initialize event:</p>
<pre><code>        If Not iAcctLastRow = 1 Then 'there are no records to load into listbox
            Set rAcctDB = wsAcctInput.Range(&quot;A2:J&quot; &amp; iAcctLastRow)
            With Me.lstAcct 'Populate listbox
                .Font.Name = &quot;Tahoma&quot;
                .Font.Size = 10
                .ColumnCount = 10
                .ColumnWidths = &quot;0,120,80,90,60,60,80,60,0,0&quot;
                .List = rAcctDB.Cells.Value
            End With
        End If
</code></pre>
<p>And in the Save procedure I refresh the listbox as follows:</p>
<pre><code>        iAcctLastRow = wsAcctInput.Range(&quot;B22&quot;).End(xlUp).row
        DelayThis 50 'added this delay but no change
        Set rAcctDB = wsAcctInput.Range(&quot;A2:J&quot; &amp; iAcctLastRow)
        Me.lstAcct.List = rAcctDB.Cells.Value 'Refresh listbox
</code></pre>
<p>The above code is the same on all 4 forms, varying in which data sheet and columns being used. I can repeat the above behaviors at will. Has anyone seen this before, or have any ideas?</p>
",https://stackoverflow.com/questions/69123138/userform-multicolumn-listbox-not-showing-records-unless-form-is-closed-and-re-op,"['excel', 'vba', 'listbox', 'userform']",237,True,0,2
Is it possible to update React context via Cypress?,"<p>I am using Cypress for integration testing (not for unit testing / component testing) and working with application that has authentication logic depending on the presence of a security token in the application state - in one of the context used (created with <a href=""https://www.npmjs.com/package/react-tracked"" rel=""noreferrer""><code>react-tracked</code></a> library). Without it - it is impossible to interact with the application. From what I could see Cypress is not suitable for testing of a remote authentication process (like via Azure AD), that's why I need to &quot;pre-authenticate&quot; the application in the beginning of each test by injecting the security token into the context. I saw examples of how to gain direct access to the Redux store:</p>
<pre><code>const store = createStore(reducer)

render(
  &lt;Provider store={store}&gt;
    &lt;App /&gt;
  &lt;/Provider&gt;,
  document.getElementById('root')
)

// expose store when run in Cypress
if (window.Cypress) {
  window.store = store
}
</code></pre>
<p>(<a href=""https://www.cypress.io/blog/2018/11/14/testing-redux-store/"" rel=""noreferrer"">https://www.cypress.io/blog/2018/11/14/testing-redux-store/</a> — actually I'm not too sure if it would be even possible to update the store)</p>
<p>I couldn't find a similar solution for react context. Storing token in a cookie or local storage seems to be too risky. Changing a testing framework (Playwright seems to be a good candidate for us) would be a pain. Another option would be to create a special, hidden input in the application, to enter the token — but isn't there any better way?</p>
",https://stackoverflow.com/questions/67688450/is-it-possible-to-update-react-context-via-cypress,"['reactjs', 'security', 'cypress', 'react-context']",1250,False,6,1
How do you mock urllib.requests.urlopen?,"<p>I'm making a screen-scraper that collects schedule data from a TV channel website. To do that, I have to fetch the website's raw HTML. I'm trying my hand at unit-testing for the first time and I have some knowledge about mocking, but I'm not too confident about it yet. (If someone could provide some good learning resources on this, I'd be more than grateful.)</p>
<p>The way I'm going about this is I'm trying to return a schedule class that will parse the DOM from the HTML data and strip the schedule data, like so:</p>
<pre><code>from urllib.request import urlopen

def fetch_html():
    url = &quot;https://example.com&quot;
    response = urlopen(url)
    dom = response.read()
    return SomeScheduleClass(dom)
</code></pre>
<p>My point is I have no idea how to test if it actually returns <code>SomeScheduleClass</code> as expected. Do I mock the <code>http.client.HTTPResponse</code> object I get from the <code>urlopen</code>? Do I somehow find a way to mock the <code>response.read()</code>? Or do I not have to test this at all and I'm just wasting my time? If so, what should I test here?</p>
<p>On an unrelated note, I'm still very much rusty since everything I know about Python is self-learnt, so if this is incredibly basic and I'm wasting everyone's time, I'd be more than happy to delete this question and forget it ever existed. Thanks in advance!</p>
",https://stackoverflow.com/questions/66544105/how-do-you-mock-urllib-requests-urlopen,"['python', 'unit-testing', 'mocking', 'pytest', 'urllib']",1197,False,3,1
Laravel user hierarchy w/ relationship unit testing gone wrong,"<p>Scenario:
So, I've got a users table that contains a ForeignKey named <code>parent_id</code> that references the id of the users table. This allows for one User to belongs to another User, and a User having Many &quot;children&quot; Users (one-to-many).</p>
<p>Now, the question itself is due to the unit testing. When I use records from a database it works as expected but mocking the relationship values doesn't seem it work. Also note that having this test being run against a database doesn't make sense as because the structure has a lot of dependencies.</p>
<p>The Goal: test the rule without hitting the database</p>
<p>The rule:</p>
<pre><code>&lt;?php

namespace App\Rules;

use App\Repositories\UserRepository;
use Illuminate\Contracts\Validation\Rule;

class UserHierarchy implements Rule
{
    /**
     * User related repository
     *
     * @var \App\Repositories\UserRepository $userRepository
     */
    private $userRepository;

    /**
     * User to affected
     *
     * @var null|int $userId 
     */
    private $userId;

    /**
     * Automatic dependency injection
     *
     * @param \App\Repositories\UserRepository $userRepository
     * @param integer|null $userId
     */
    public function __construct(UserRepository $userRepository, ?int $userId)
    {
        $this-&gt;userRepository = $userRepository;
        $this-&gt;userId = $userId;
    }

    /**
     * Determine if the validation rule passes.
     * Uses recursivity in order to validate if there is it causes an infinite loop
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value): bool
    {
        if (is_null($value)) {
            return true;
        }

        $childrenOfUserToBeUpdated = $this-&gt;userRepository-&gt;show($this-&gt;userId);
    //pluck_key_recursive is a customized function but its not posted because the issue can be traced on the dd below
        $notAllowedUserIds = pluck_key_recursive($childrenOfUserToBeUpdated-&gt;childrenTree-&gt;toArray(), 'children_tree', 'id');
         dd($childrenOfUserToBeUpdated-&gt;childrenTree-&gt;toArray());
        return in_array($value, $notAllowedUserIds) ? false : true;
    }
}
</code></pre>
<p>The User relationships are as it follows:</p>
<pre><code>/**
     * An User can have multiple children User
     *
     * @return EloquentRelationship
     */
    public function children(): HasMany
    {
        return $this-&gt;hasMany(self::class, 'parent_id', 'id');
    }

    /**
     * An User can have a hierarchal of children
     *
     * @return EloquentRelationship
     */
    public function childrenTree(): HasMany
    {
        return $this-&gt;children()-&gt;with('childrenTree');
    }
</code></pre>
<p>This is the test:</p>
<pre><code>&lt;?php

namespace Tests\Unit\Rules;

use App\Repositories\UserRepository;
use App\Rules\UserHierarchy;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Mockery;
use Tests\TestCase;

class UserHierarchyTest extends TestCase
{
    /**
     * Setting up Mockery
     *
     * @return void
     */
    protected function setUp(): void
    {
        parent::setUp();
           $this-&gt;parent = new User(['id' =&gt; 1]);
        $this-&gt;sonOne = new User(['id' =&gt; 2, 'parent_id' =&gt; $this-&gt;parent-&gt;id]);
        $this-&gt;sonTwo = new User(['id' =&gt; 3, 'parent_id' =&gt; $this-&gt;parent-&gt;id]);
        $this-&gt;sonThree = new User(['id' =&gt; 4, 'parent_id' =&gt; $this-&gt;parent-&gt;id]);
        $this-&gt;grandSonOne = new User(['id' =&gt; 5, 'parent_id' =&gt; $this-&gt;sonOne-&gt;id]);
        $this-&gt;grandSonTwo = new User(['id' =&gt; 6, 'parent_id' =&gt; $this-&gt;sonOne-&gt;id]);

 //$this-&gt;sonOne-&gt;children = new Collection([$this-&gt;grandSonOne, $this-&gt;grandSonTwo]);
        //$this-&gt;parent-&gt;children = new Collection([$this-&gt;sonOne, $this-&gt;sonTwo, $this-&gt;sonThree]);
        $this-&gt;sonOne-&gt;childrenTree = new Collection([$this-&gt;grandSonOne, $this-&gt;grandSonTwo]);
        $this-&gt;parent-&gt;childrenTree = new Collection([$this-&gt;sonOne, $this-&gt;sonTwo, $this-&gt;sonThree]);


        $this-&gt;userRepositoryMock = Mockery::mock(UserRepository::class);
        $this-&gt;app-&gt;instance(UserRepository::class, $this-&gt;userRepositoryMock);
    }

    /**
     * The rule should pass if the user to be updated will have not a child as a parent (infinite loop)
     *
     * @return void
     */
    public function test_true_if_the_user_id_isnt_in_the_hierarchy()
    {
        //Arrange
        $this-&gt;userRepositoryMock-&gt;shouldReceive('show')-&gt;once()-&gt;with($this-&gt;parent-&gt;id)-&gt;andReturn($this-&gt;parent);
        //Act
        $validator = validator(['parent_id' =&gt; $this-&gt;randomUserSon-&gt;id], ['parent_id' =&gt; resolve(UserHierarchy::class, ['userId' =&gt; $this-&gt;parent-&gt;id])]);
        //Assert
        $this-&gt;assertTrue($validator-&gt;passes());
    }

    /**
     * The rule shouldnt pass if the user to be updated will have a child as a parent (infinite loop)
     *
     * @return void
     */
    public function test_fail_if_the_user_id_is_his_son_or_below()
    {
        //Arrange
        $this-&gt;userRepositoryMock-&gt;shouldReceive('show')-&gt;once()-&gt;with($this-&gt;parent-&gt;id)-&gt;andReturn($this-&gt;parent);
        //Act
        $validator = validator(['parent_id' =&gt; $this-&gt;grandSonOne-&gt;id], ['parent_id' =&gt; resolve(UserHierarchy::class, ['userId' =&gt; $this-&gt;parent-&gt;id])]);
        //Assert
        $this-&gt;assertFalse($validator-&gt;passes());
    }

    /**
     * Tear down Mockery
     *
     * @return void
     */
    public function tearDown(): void
    {
        parent::tearDown();
        Mockery::close();
    }
}

</code></pre>
<p>I've tried a lot of combinations but I can't seem to get it to work. I've even tried mocking the user model all the way but it results in the same end: the children of a user are converted to an array but the grandchildren remain as item objects of a collection.</p>
<p>This is the sample output on this test:</p>
<pre><code>array:3 [
  0 =&gt; array:6 [
    &quot;name&quot; =&gt; &quot;asd&quot;
    &quot;email&quot; =&gt; &quot;asdasdasd&quot;
    &quot;id&quot; =&gt; 2
    &quot;parent_id&quot; =&gt; 1
    &quot;childrenTree&quot; =&gt; Illuminate\Database\Eloquent\Collection^ {#898
      #items: array:2 [
        0 =&gt; App\Models\User^ {#915
          #fillable: array:8 [...
</code></pre>
<p>Why does -&gt;toArray() convert everything to an array with real database objects but not when you set the expected outcome?</p>
",https://stackoverflow.com/questions/67710450/laravel-user-hierarchy-w-relationship-unit-testing-gone-wrong,"['laravel', 'eloquent', 'phpunit', 'laravel-8', 'eloquent-relationship']",314,True,3,1
Use c# `Index` and `Range` with jagged arrays,"<p>I am trying to use <code>Index</code> and <code>Range</code> objects to slice a jagged array. But in the example below I cannot extract columns, only rows.</p>
<pre><code>var A =  new float[3][];
A[0] = new float[] { 1.1f, 1.2f, 1.3f };
A[1] = new float[] { 2.1f, 2.2f, 2.3f };
A[2] = new float[] { 3.1f, 3.2f, 3.3f };

// This works as intended to extract rows
var A_row1 = A[0][..];      // { 1.1, 1.2, 1.3 } 
var A_row3 = A[^1][..];     // { 3.1, 3.2, 3.3 } 
var A_row23 = A[1..^0][..]; // { { 2.1, 2.2, 2.3}, { 3.1, 3.2, 3.3 } } 

// This does not work as intended to extract columns
var A_col1 = A[..][0];      // { 1.1, 1.2, 1.3 } ** WRONG
var A_col3 = A[..][^1];     // { 3.1, 3.2, 3.3 } ** WRONG
var A_col23 = A[..][1..^0]; // { { 2.1, 2.2, 2.3}, { 3.1, 3.2, 3.3 } } ** WRONG

var A_sub22 = A[0..2][0..2];
// { { 1.1, 1.2, 1.3 }, { 2.1, 2.2, 2.3 } } ** WRONG
// { { 1.1, 1.2 }, { 2.1, 2.2 } } &lt;= WHAT I AM EXPECTING
</code></pre>
<p>Why is it that <code>A[..][0]</code> returns the exact same result as <code>A[0][..]</code>? And why doesn't the last statement contain 2 columns per row, but 3?</p>
<p>The bigger picture here is that I am building a <code>Matrix</code> object that stores the numeric data in a jagged array of <code>double</code> and I want to implement slicing using <code>Index</code> and <code>Range</code>. I thought I could have it support slicing with the following methods</p>
<pre><code>public class Matrix 
{
    readonly double[][] Elements;

    ///&lt;summary&gt;Reference a single element&lt;/summary&gt;
    public ref double this[Index row, Index column] 
        =&gt; ref Elements[row][column];

    ///&lt;summary&gt;Extract a sub-matrix&lt;/summary&gt;
    public double[][] this[Range rows, Range columns]
        =&gt; Elements[rows][columns];

    ///&lt;summary&gt;Extract a row sub-vector&lt;/summary&gt;
    public double[] this[Index row, Range columns]
        =&gt; Elements[row][columns];

    ///&lt;summary&gt;Extract a column sub-vector&lt;/summary&gt;
    public double[] this[Range rows, Index column] 
        =&gt; Elements[rows][column];
}
</code></pre>
<p>But this failed spectacularly in my unit testing. It seems that even if C# supports the syntax, the results are unexpected.</p>
<p>Is there a way to implement the functionality I want to have using the existing framework for slicing that C# is <em>trying</em> to implement?</p>
<hr />
<p>Sorry, I come from a Fortran background where slicing is natural.</p>
<p>Also, am I the only one that finds it very confusing that the last element in an array is indexed as <code>[^1]</code> but the range to the last element is <code>[..^0]</code>. It seems very inconsistent on the part of Microsoft to have <code>^0</code> mean different things for <code>Index</code> as it does for <code>Range</code>.</p>
",https://stackoverflow.com/questions/69768012/use-c-index-and-range-with-jagged-arrays,"['c#', 'indexing', 'jagged-arrays']",445,True,3,2
Cartesian product of std::tuple,"<p>For unit testing a <strong>C++17</strong> framework that relies heavily on templates I tried to write helper <strong><code>template</code> classes</strong> which generate a <strong>Cartesian product of two sets of data types</strong> given by two tuples:</p>
<blockquote>
<pre><code>**Input**: std::tuple &lt;A, B&gt; std::tuple&lt;C,D,E&gt;

**Expected output**: Cartesian product of the two tuples: 
std::tuple&lt;std::tuple&lt;A,C&gt;, std::tuple&lt;A,D&gt;, std::tuple&lt;A,E&gt;,
std::tuple&lt;B,C&gt;, std::tuple&lt;B,D&gt;, std::tuple&lt;B,E&gt;&gt;
</code></pre>
</blockquote>
<p>I am aware that <a href=""https://stackoverflow.com/a/67899346/9938686"">Boost MP11 offers such features</a> but I would not like to include a dependency on yet another library just for testing purposes. So far I came up with a pretty straight forward solution which though <strong>requires the class to be default-constructible</strong> (<a href=""https://wandbox.org/permlink/Okc8H0ApFegZZhcy"" rel=""nofollow noreferrer"">Try it here!</a>):</p>
<pre><code>template &lt;typename T1, typename T2,
          typename std::enable_if_t&lt;is_tuple_v&lt;T1&gt;&gt;* = nullptr,
          typename std::enable_if_t&lt;is_tuple_v&lt;T2&gt;&gt;* = nullptr&gt;
class CartesianProduct {
  protected:
    CartesianProduct() = delete;
    CartesianProduct(CartesianProduct const&amp;) = delete;
    CartesianProduct(CartesianProduct&amp;&amp;) = delete;
    CartesianProduct&amp; operator=(CartesianProduct const&amp;) = delete;
    CartesianProduct&amp; operator=(CartesianProduct&amp;&amp;) = delete;
    
    template &lt;typename T, typename... Ts,
              typename std::enable_if_t&lt;std::is_default_constructible_v&lt;T&gt;&gt;* = nullptr,
              typename std::enable_if_t&lt;(std::is_default_constructible_v&lt;Ts&gt; &amp;&amp; ...)&gt;* = nullptr&gt;
    static constexpr auto innerHelper(T, std::tuple&lt;Ts...&gt;) noexcept {
      return std::make_tuple(std::make_tuple(T{}, Ts{}) ...);
    }
    template &lt;typename... Ts, typename T,
              typename std::enable_if_t&lt;std::is_default_constructible_v&lt;T&gt;&gt;* = nullptr,
              typename std::enable_if_t&lt;(std::is_default_constructible_v&lt;Ts&gt; &amp;&amp; ...)&gt;* = nullptr&gt;
    static constexpr auto outerHelper(std::tuple&lt;Ts...&gt;, T) noexcept {
      return std::tuple_cat(innerHelper(Ts{}, T{}) ...);
    }
  public:
    using type = std::decay_t&lt;decltype(outerHelper(std::declval&lt;T1&gt;(), std::declval&lt;T2&gt;()))&gt;;
};
template &lt;typename T1, typename T2&gt;
using CartesianProduct_t = typename CartesianProduct&lt;T1, T2&gt;::type;
</code></pre>
<p>Also when trying to instantiate a list of template classes in a similar way (<a href=""https://wandbox.org/permlink/Yao1nvISDO5yTtX5"" rel=""nofollow noreferrer"">try it here</a>) I have to make the same assumption: I can't apply it to classes which have a <code>protected</code>/<code>private</code> constructor (without a <code>friend</code> declaration) and are not-default-constructible.</p>
<p>Is it possible to <strong>lift the restriction of default constructability</strong> without turning to an <a href=""https://en.cppreference.com/w/cpp/utility/integer_sequence"" rel=""nofollow noreferrer""><code>std::integer_sequence</code></a> and an additional helper class? From what I understand it is not possible to use <a href=""https://en.cppreference.com/w/cpp/utility/declval"" rel=""nofollow noreferrer""><code>std::declval&lt;T&gt;()</code></a> directly in the methods <code>innerHelper</code> and <code>outerHelper</code> (which would solve my issue), as it seems to not be an <a href=""https://en.cppreference.com/w/cpp/language/expressions#Unevaluated_expressions"" rel=""nofollow noreferrer"">unevaluated expression</a> anymore. At least <a href=""https://wandbox.org/permlink/w5QzFqaQyAyFcHXE"" rel=""nofollow noreferrer"">GCC complains then about <code>static assertion failed: declval() must not be used!</code></a> while it <a href=""https://wandbox.org/permlink/zzm1Or32eO7S8aBK"" rel=""nofollow noreferrer"">seems to compile fine with Clang</a>.</p>
<p><strong>Thank you in advance!</strong></p>
",https://stackoverflow.com/questions/70404549/cartesian-product-of-stdtuple,"['c++', 'templates', 'tuples', 'c++17', 'variadic-templates']",371,True,2,3
How to mock / unit test HTTP Client - restease,"<p>tl;dr: I'm having trouble mocking restease**</p>
<p>Also, I realize I may be totally on the wrong track, so any suggestions / nudges in the right direction would be of great help. I am quite new to this.</p>
<p>I'm making a small HTTP Client library, built around <a href=""https://github.com/canton7/RestEase"" rel=""nofollow noreferrer"">RestEase</a>. RestEase is nice and easy to use, but I'm having trouble mocking the calls for the purpose of unit testing.</p>
<p>I want to use moq and NUnit, but I can't properly mock the RestClient. Example (shortened for brevity):</p>
<p><strong>IBrandFolderApi - interface needed by restease to send calls</strong></p>
<pre><code>public interface IBrandFolderApi
{
    [Post(&quot;services/apilogin&quot;)]
    Task&lt;LoginResponse&gt; Login([Query] string username, [Query] string password);
}
</code></pre>
<p><strong>BrandfolderClient.cs - the main class</strong></p>
<pre><code>public class BrandfolderClient : IBrandfolderClient
{
    private IBrandFolderApi _brandFolderApi { get; set; } 

    public BrandfolderClient(string url)
    {
        _brandFolderApi = RestClient.For&lt;IBrandFolderApi &gt;(url);
    }

    public async Task&lt;string&gt; Login(string username, string password)
    {
        LoginResponse loginResponse = await _brandFolderApi .Login(username, password);
        if (loginResponse.LoginSuccess)
        {
            ....
        }
        ....            
        return loginResponse.LoginSuccess.ToString();
    }
}
</code></pre>
<p><strong>The unit tests</strong></p>
<pre><code>public class BrandFolderTests
{
    BrandfolderClient  _brandfolderClient 
    Mock&lt;IBrandFolderApi&gt; _mockBrandFolderApii;
    
    
    [SetUp]
    public void Setup()
    {
         //The test will fail here, as I'm passing a real URL and it will try and contact it.
        //If I try and send any string, I receive an Invalid URL Format exception.
         string url = &quot;https://brandfolder.companyname.io&quot;;
        _brandfolderClient = new BrandfolderClient  (url);
        _mockBrandFolderApii= new Mock&lt;IBrandFolderApi&gt;();
    }

    ....
}
</code></pre>
<p>So, I don't know how to properly mock the Restclient so it doesn't send an actual request to an actual URL.</p>
<p>The test is failing at the constructor - if I send a valid URL string, then it will send a call to the actual URL. If I send any other string, I get an invalid URL format exception.</p>
<p>I believe I haven't properly implemented something around the rest client, but I'm not sure where. I'm very stuck on this, I've been googling and reading like crazy, but I'm missing something and I don't know what.</p>
",https://stackoverflow.com/questions/68238847/how-to-mock-unit-test-http-client-restease,"['c#', 'unit-testing', '.net-core', 'httpclient', 'moq']",1325,True,2,3
Is it a good practice to include some data for doing a test?,"<p>I have never did unit testing or integration testing and would like to learn the good way (but keeping things simple since I am a newcomer).
Here is my problem: I want to offer a test for a function that manipulates and exports some files (that unzip: imbricated zip file). Should I provide a minimal data example with the test (as I explain after)? If not what would you do?</p>
<p>I created:</p>
<ul>
<li>a &quot;tests&quot; directory inside my utilities subpackage</li>
<li>a &quot;data&quot; directory in my tests subpackage</li>
<li>a dummy  (almost empty for test purpose) zip file called zip_root.zip and structured as follow: {zip_root.zip:{zip_child1:{zip_child1_grandchild1:file_child1_grandchild.txt},zip_child2:file_child2.txt} in &quot;tests/data/input/zip&quot; directory</li>
<li>a &quot;tests/data/output/unzip&quot; empty directory</li>
<li>a test file &quot;test_extract.py&quot; in tests subpackage</li>
<li>the target module &quot;extract_zip.py&quot;</li>
</ul>
<p>Below are the target module &quot;extract_zip.py&quot; and test file code (if needed and allowed by SO I can provide the whole package).</p>
<p><strong>extract_zip.py:</strong></p>
<pre><code>'''
walk a file tree from specified starting point, unzip any zip files encountered in the
directory where zip file was found, and then delete the zip file after succesfully
unzipping
'''
import zipfile, os, glob
import shutil
 
def extract_zip(zippedfilepath,toFolder):
    with zipfile.ZipFile(zippedfilepath, 'r') as zfile:
        #print(&quot;Extracting {}&quot;.format(zippedfilepath))
        zfile.extractall(path=toFolder)
 
def extract_nested_zip(zipped_file, toFolder):
    &quot;&quot;&quot; Extract a zip file including any nested zip files
        Delete the zip file(s) after extraction
    &quot;&quot;&quot;
    extract_zip(zipped_file,toFolder)
    basename = os.path.basename(zipped_file).split('.zip')[0]
    path = list(glob.iglob(os.path.join(toFolder,basename,'**/*.zip'), recursive=True))
    for filepath in path:
        extract_nested_zip(filepath, os.path.dirname(filepath))
        os.remove(filepath)
 
if __name__ == &quot;__main__&quot;:
    rootpath = r&quot;datalib/utilities/tests/data&quot;
    zippedFile = os.path.join(rootpath,r'input/zip/zip_root.zip')
    toFolder= os.path.join(rootpath,r'output/unzip')
    extract_nested_zip(zippedFile, toFolder)
</code></pre>
<p><strong>test_extract_zip.py</strong></p>
<pre><code>from ..extract_zip import extract_zip
import os
import tempfile
 
def test_extract_zip():
    rootpath = r&quot;datalib\utilities\tests\data&quot;
    zippedfilepath = os.path.join(rootpath,r&quot;input\zip\zip_root.zip&quot;)
    with tempfile.TemporaryDirectory() as tmpdir:
        toFolder =tmpdir
        extract_zip(zippedfilepath,toFolder)
        #import pdb;pdb.set_trace()
        assert os.listdir(toFolder)==['zip_root']
</code></pre>
<p>Here is an image of the hierarchy to clear the organization:
<a href=""https://i.stack.imgur.com/IUDdo.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/IUDdo.png"" alt=""enter image description here"" /></a></p>
<p>Remark: I am not familiar with simple test practice. I used to make my test inside the targeted module below the <code>if __name__ = &quot;__main__&quot;</code> but I am not sure it is really good practice.</p>
",https://stackoverflow.com/questions/66011629/is-it-a-good-practice-to-include-some-data-for-doing-a-test,"['python', 'unit-testing', 'testing']",193,False,2,0
Pytest Cov Report Missing Mock Exception Returns,"<p>I'm a Network Engineer who is trying to write some Python, so very much still learning each day. I have an issue with Unit Testing and Pytest coverage reports. I think I understand the concept of unit tests and pytest.</p>
<p>I have a function that does a DNS lookup using socket</p>
<pre><code>def get_ip(d):
    &quot;&quot;&quot;Returns the first IPv4 address that resolves from 'd'

    Args:
        d (string): string that needs to be resolved in DNS.

    Returns:
        string: IPv4 address if found
    &quot;&quot;&quot;
    logger.info(&quot;Returns IP address from hostname: &quot; + d)
    try:
        data = socket.gethostbyname(d)
        ip_addr = repr(data).strip(&quot;'&quot;)
        logger.debug(&quot;IP Address Resolved to: &quot; + ip_addr)
        return ip_addr
    except socket.gaierror:
        return False
</code></pre>
<p>I have written a unit test which passes fine. I'm using pytest-mock to handle the mocking of the socket for the DNS lookup. Side Effect seems to be mocking the Exception and I've set a return_value as False and I assuming I have asserted that False is returned, the test passes ok which is why I'm assuming that my test is ok.</p>
<pre><code>import pytest
import pytest_mock
import socket
from utils import network_utils

@pytest.fixture
def test_setup_network_utils():
    return network_utils

def test_get_ip__unhappy(mocker, test_setup_network_utils):
    mocker.patch.object(network_utils, 'socket')
    test_setup_network_utils.socket.gethostbyname.side_effect = socket.gaierror
    with pytest.raises(Exception):
        d = 'xxxxxx'
        test_setup_network_utils.socket.gethostbyname.return_value = False
        test_setup_network_utils.get_ip(d)
    assert not test_setup_network_utils.socket.gethostbyname.return_value
    test_setup_network_utils.socket.gethostbyname.assert_called_once()
    test_setup_network_utils.socket.gethostbyname.assert_called_with(d)
</code></pre>
<p>The pytest-cov report shows the return False line as not being covered.</p>
<pre><code>pytest --cov-report term-missing:skip-covered --cov=utils unit_tests

network_utils.py     126      7    94%   69
</code></pre>
<p>Line 69 is the below line of code in function</p>
<pre><code>except socket.gaierror:
    return False &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; This is missing from the report
</code></pre>
<p>Any pointers would be appreciated as to why the return of False isn't being declared as covered. Like I said above I'm pretty new to Python and coding and this is my 1st question on Stackoverflow. Hopefully I've explained what my issue and have provided enough information for some guidance.</p>
",https://stackoverflow.com/questions/67272174/pytest-cov-report-missing-mock-exception-returns,"['python-3.x', 'unit-testing', 'pytest', 'pytest-mock', 'pytest-cov']",809,True,2,1
how to mock implementation details that doesn&#39;t lead to a fragile test,"<p>I'm reading a book on Unit Testing, below is the quote and the code (not full code since it is easy to understand what the code does)</p>
<p><a href=""https://i.stack.imgur.com/43u5G.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/43u5G.png"" alt=""enter image description here"" /></a></p>
<p>First, the author shows a mocking that doesn't lead to fragile tests:</p>
<pre><code>[Fact]
public void Successful_purchase() {
   var mock = new Mock&lt;IEmailGateway&gt;();
   var sut = new CustomerController(mock.Object);

   bool isSuccess = sut.Purchase(customerId: 1, productId: 2, quantity: 5);

   Assert.True(isSuccess);
   mock.Verify(x =&gt; x.SendReceipt(&quot;customer@email.com&quot;, &quot;Shampoo&quot;, 5), Times.Once);
}
</code></pre>
<p>the author says:</p>
<blockquote>
<p>The call to the SMTP service is a legitimate reason to do mocking. It doesn’t lead
to test fragility because you want to make sure this type of communication stays in
place even after refactoring. The use of mocks helps you do exactly that.</p>
</blockquote>
<p>Then the author shows another example that leads to fragile tests:</p>
<pre><code>[Fact]
public void Purchase_succeeds_when_enough_inventory() {
   var storeMock = new Mock&lt;IStore&gt;();
   storeMock.Setup(x =&gt; x.HasEnoughInventory(Product.Shampoo, 5)).Returns(true);
   var customer = new Customer();

   bool success = customer.Purchase(storeMock.Object, Product.Shampoo, 5);

   Assert.True(success);
   storeMock.Verify(x =&gt; x.RemoveInventory(Product.Shampoo, 5), Times.Once);
}
</code></pre>
<p>and the author says:</p>
<blockquote>
<p>Unlike the communication between CustomerController and the SMTP service, the RemoveInventory() method call from Customer to Store doesn't cross the application boundary: both the caller and the recipient reside inside the application. Also, this method is neither an operation nor a state that helps the client achieve its goals.</p>
</blockquote>
<p>I'm a little bit confused here, so we shouldn't test whether <code>RemoveInventory</code> is called? what happen the developer doesn't write the Purchase method correctly, which causes <code>RemoveInventory</code> method not being called on the IStore object, so the purchase will still success but the internal state is corrupted?</p>
",https://stackoverflow.com/questions/68204867/how-to-mock-implementation-details-that-doesnt-lead-to-a-fragile-test,"['c#', 'unit-testing']",274,True,2,1
Mockito shipped within Spring Boot fails to attach to JVM (OpenJDK 11),"<p>I have a bunch of Spring Boot 2.5.6 applications that use Mockito for unit testing. The version of Mockito that is used is the one that comes shipped within SB itself (3.9.0). The JDK is OpenJDK 11.0.12+0. Everything was working fine until yesterday, this morning I suddenly cannot run any Mockito-based tests, all of them fail with the following:</p>
<pre><code>Caused by: java.lang.IllegalStateException: Failed to load interface org.mockito.plugins.MockMaker implementation declared in java.lang.CompoundEnumeration@7c51f34b
Caused by: java.lang.reflect.InvocationTargetException
Caused by: org.mockito.exceptions.base.MockitoInitializationException: 

Could not initialize inline Byte Buddy mock maker.

It appears as if your JDK does not supply a working agent attachment mechanism.
Java               : 11
JVM vendor name    : Homebrew
JVM vendor version : 11.0.12+0
JVM name           : OpenJDK 64-Bit Server VM
JVM version        : 11.0.12+0
JVM info           : mixed mode
OS name            : Mac OS X
OS version         : 12.0.1

Caused by: java.lang.IllegalStateException: Could not self-attach to current VM using external process
</code></pre>
<p>I cannot identify anything that has changed between yesterday and today.</p>
<p>Things I have tried with no success:</p>
<ul>
<li>Re-run with Java 17.</li>
<li>Re-install Java 11.</li>
<li>Install a JDK 11 from a different vendor (Microsoft OpenJDK)</li>
<li>Add <code>-Djdk.attach.allowAttachSelf=true</code>, both to command line and to <code>&lt;argLine&gt;</code> parameter within surefire configuration, as suggested <a href=""https://stackoverflow.com/questions/55504785/how-to-get-rid-of-could-not-initialize-plugin-interface-org-mockito-plugins-mo"">here</a></li>
<li>Add <code>-XX:+StartAttachListener</code> as suggested <a href=""https://stackoverflow.com/a/25439003/6166627"">here</a></li>
<li>Restart the computer</li>
<li>Ensure the firewall allows the <code>java</code> process to receive incoming connections as per <a href=""https://support.apple.com/en-us/HT201642"" rel=""nofollow noreferrer"">here</a></li>
<li>(Temporarily) stop any security software that may prevent connections from happening</li>
<li>Review <code>JAVA_HOME</code> and the different Java installations on my machine in case the process was trying to attach to the wrong Java as per <a href=""https://githubmemory.com/repo/raphw/byte-buddy/issues/1118"" rel=""nofollow noreferrer"">here</a></li>
</ul>
<p>In case it matters, this is on an MBP M1. Other members of the team are able to build with no problem.</p>
",https://stackoverflow.com/questions/69929229/mockito-shipped-within-spring-boot-fails-to-attach-to-jvm-openjdk-11,"['java', 'spring-boot', 'macos', 'mockito', 'sidecar']",2090,True,2,3
"Unit test Laravel query builder class, mock problem","<p>I'm trying to mock out the actual database operations in my Laravel application for the purposes of effective unit testing.  But I am having difficulty in getting the mocked method to be called, rather than the real method.</p>
<p>I have about 200 Models in <code>app/Models</code> which were generated using <code>artisan make:model</code>.  I'm in the process of creating query builder classes which extend <code>Illuminate\Database\Eloquent\Builder</code> for each of the models.  Likewise, there will be a PHPUnit test class for each of these query builders.</p>
<p>I've spent the last 2 days with the Laravel docs, the Mockery docs, Stack Overflow, Google and lots of debugging trying to get my unit test to work correctly, to no avail.  What's the trick to making this work with Laravel's intricate internals?</p>
<p>Example Model, stripped down:</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php
namespace App\Models;
use App\Domain\Example\QueryBuilders\ExampleQueryBuilder;
use Illuminate\Database\Eloquent\Model;
/**
 * @property int $id
 * @property string $foo
 * @property string $bar
 * @property string $baz
 */
class Example extends Model
{
    public $timestamps = false;
    protected $table = 'my_table';
    protected $fillable = ['foo', 'bar', 'baz',];
    protected $dateFormat = 'U';
    protected $connection = 'mysql';
    public function newEloquentBuilder($query): ExampleQueryBuilder {
        return new ExampleQueryBuilder($query);
    }
}
</code></pre>
<p>Example query builder, stripped down:</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php
namespace App\Domain\Example\QueryBuilders;
use App\Models\Example;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
final class ExampleQueryBuilder extends Builder
{
    protected $model;
    protected $onDelete;
    protected $query;

    public function findActive(string $foo): ?Model {
        $conditions = ['foo' =&gt; &quot;$foo&quot;, 'bar' =&gt; 1,];
        $example = Example::firstWhere($conditions);
        if ($example instanceof Example) {return $example;}
        return null;
    }
</code></pre>
<p>Example unit test:</p>
<pre class=""lang-php prettyprint-override""><code>&lt;?php
namespace Tests\Domain\Example\QueryBuilders;
use App\Models\Example;
use Tests\TestCase;

class ExampleQueryBuilderTest extends TestCase
{
    /** @test */
    public function it_handles_missing_example_correctly(): void {
        // I've tried endless variations on this, mocking the Model &quot;Example&quot;,
        // mocking &quot;Model&quot;, even &quot;Process&quot; at one crazy point.  Debugging proves
        // without a doubt that the `Builder::firstWhere` method IS being called
        // instead of my mocked method.
        $mock = $this-&gt;partialMock(Builder::class, function (MockInterface $mock) {
            $mock-&gt;shouldReceive('firstWhere')-&gt;once();
        });
        $this-&gt;app-&gt;instance(Builder::class, $mock);

        $example = Example::findActive('');
        self::assertNull($example);
    }
}
</code></pre>
<p>When this test is run, I get this output:</p>
<blockquote>
<p>Method firstWhere() from Mockery_0_Illuminate_Database_Eloquent_Builder should be called
exactly 1 times but called 0 times.</p>
</blockquote>
<p>So clearly the method I need to mock out is not getting mocked somehow.  What am I overlooking or missing?</p>
<p>My environment:  Laravel 8, Mockery 1.4, PHPUnit 9, PHP 7.4/8.0, macOS/Linux</p>
",https://stackoverflow.com/questions/66294828/unit-test-laravel-query-builder-class-mock-problem,"['laravel', 'unit-testing', 'eloquent', 'phpunit', 'mockery']",1437,False,2,0
Rust: Attribute #[cfg(test)] in crates with lib and binary targets,"<p>I'm currently working on a <a href=""https://github.com/christiankuhl/titanium"" rel=""nofollow noreferrer"">Rust project</a> that has a library target as well as a binary target.</p>
<p>The library defines two panic handlers, one for production use and one for testing, which are conditionally compiled using the #[cfg(test)] attribute. This works fine for unit testing src/lib.rs, but as soon as integration tests in tests/ (or src/main.rs for that matter), the &quot;production&quot; panic handler is linked in, i.e. in those circumstances, lib.rs gets compiled with test=false.</p>
<p>Is there some way to prevent/configure that?</p>
<p>This is pretty minimally reproducible with the following directory structure:</p>
<pre><code>Cargo.toml
src/lib.rs
src/main.rs
</code></pre>
<p>The manifest looks like this:</p>
<pre><code># Cargo.toml
...
[lib]
name = &quot;kernel&quot;

[[bin]]
path = &quot;src/main.rs&quot;
name = &quot;titanium&quot;
</code></pre>
<p>Code for the binary:</p>
<pre><code>// main.rs

fn main() {
    println!(&quot;Hello, world!&quot;);
}

#[test]
fn it_works() {
    assert_eq!(kernel::hello(), &quot;Hello!&quot;.to_string());
}
</code></pre>
<p>... and for the library:</p>
<pre><code>// lib.rs

#[cfg(test)]
pub fn hello() -&gt; String {
    &quot;Hello!&quot;.to_string()
}

#[cfg(not(test))]
pub fn hello() -&gt; String {
    &quot;Goodbye!&quot;.to_string()
}

#[test]
fn it_works() {
    assert_eq!(hello(), &quot;Hello!&quot;.to_string())
}
</code></pre>
<p><strong>Answer</strong>
Above behaviour is in fact desirable for probably 99% of use cases, however, mine isn't one of them.</p>
<p>For my use case (testsuite for toy OS running in a VM &quot;headless&quot;, i.e. with output only to stdout of the host machine) I ended up defining a feature to switch panic handlers. Adapted to above example it now looks like this:</p>
<pre><code># Cargo.toml
...
[features]
test_qemu_headless = []
</code></pre>
<p>The binary then remains unchanged, and in the library I do</p>
<pre><code>// lib.rs

#[cfg(feature = &quot;test_qemu_headless&quot;)]
pub fn hello() -&gt; String {
    &quot;Hello!&quot;.to_string()
}

#[cfg(not(feature = &quot;test_qemu_headless&quot;))]
pub fn hello() -&gt; String {
    &quot;Goodbye!&quot;.to_string()
}

#[test]
fn it_works() {
    assert_eq!(hello(), &quot;Hello!&quot;.to_string())
}
</code></pre>
<p>The tests are then run with</p>
<pre><code>cargo test --features test_qemu_headless
</code></pre>
",https://stackoverflow.com/questions/68876553/rust-attribute-cfgtest-in-crates-with-lib-and-binary-targets,"['testing', 'rust', 'rust-cargo', 'conditional-compilation']",1174,True,2,1
"With unittest.mock, How to mock a class property with return_value depending on instance attribute?","<p>I have two classes <code>A</code> and <code>B</code>. I want to test function <code>foo_a</code> of <code>A</code>. Using some business logic, <code>foo_a</code> creates two possible instances of <code>B</code> (with different arguments) and calls function <code>foo_b</code> of <code>B</code>:</p>
<pre class=""lang-py prettyprint-override""><code>class A:
  def foo_a(self, *args, **kwargs):
    # some code above
    if condition_1:
      foo_b_result = B(**arguments_1).foo_b()
    else:
      foo_b_result = B(**arguments_2).foo_b()
    # some code below that returns foo_b_result + other objects independent of foo_b_result

</code></pre>
<p>The problem comes from the fact that <code>foo_b</code> is a complexe function that calls APIs and other stuff. I don't want to mock APIs here in this unit test so that <code>foo_b</code> returns the appropriate output, indeed, <code>foo_b</code> is already tested elsewhere in my set of unit tests for class <code>B</code>. Thus, in this context I care more about the correctness of <code>arguments_1</code> and <code>arguments_2</code> than the correctness of <code>foo_b_result</code>. Therefore, It would be nice if I could mock <code>foo_b</code> so that it returns outputs that could easily show if <code>foo_b</code> has been called with the right instance of <code>B</code>. For instance, <code>foo_b</code> could return <code>arguments_1</code> or <code>arguments_2</code>.</p>
<p>Maybe there is another better approach for unit testing <code>foo_a</code> in this case, any idea is welcome.</p>
<p><strong>UPDATE</strong>: Another way would be to create a new function that takes as input <code>condition_1</code> and returns either <code>arguments_1</code> or <code>arguments_2</code> (this function could be tested easily). Then I would mock <code>foo_b</code> so that it always return the same value (for instance 0). But still, it would be interesting to know if it's possible to mock <code>foo_b</code> so that it returns values according to <code>arguments_1</code> or <code>arguments_2</code>.</p>
",https://stackoverflow.com/questions/67824539/with-unittest-mock-how-to-mock-a-class-property-with-return-value-depending-on,"['python-3.x', 'mocking']",491,False,1,1
In Ruby on Rails unit testing update model against MySQL database gives error: ActiveRecord::ValueTooLong,"<p>I have an ENUM type for a column I recently added to a previous table in the a MySQL database.</p>
<p>I'm unit testing creating a db entry with a valid ENUM value for that column.</p>
<p>The migration for adding the column is:</p>
<pre><code>class AddStatusToMymodel &lt; ActiveRecord::Migration[5.2]
  def change
    add_column :my_model, :status,
               &quot;ENUM('have_issues','no_issues', 'checking', 'error')&quot;
  end
end
</code></pre>
<p>And the model:</p>
<pre><code>class MyModel &lt; ApplicationRecord
  # ...
  enum status: %w[have_issues no_issues checking error].map { |i| [i.to_sym, i] }.to_h
end
</code></pre>
<p>Now, running a unit test that calls the controller method to create a record with <code>status: 'have_issues'</code> gives MySQL error:</p>
<pre><code>ActiveRecord::ValueTooLong:
       Mysql2::Error: Data too long for column 'status' at row 1
</code></pre>
<p>But creating the model in rails console actually creates the entry in the database for that <code>'have_issues'</code> status.</p>
<p>On the other hand, when running the same test with <code>'checking'</code> status the entry is created in the test database.</p>
<p>What is the problem when using the test database with a valid ENUM type, and getting <code>ValueTooLong</code> error?</p>
<p><strong>UPDATE</strong>:</p>
<p>As asked in comments I generate the <code>SHOW CREATE TABLE</code> for dev and test databases and, in fact, they differ for the column <code>status</code>. For dev db it's ENUM, and for test db it's VARCHAR(8).</p>
<p>So, looks like the problem is when running the tests, and the statements to create the new column with type ENUM, the column is created with type VARCHAR. Is that a configuration to correctly create the column <code>status</code> with the type ENUM?</p>
",https://stackoverflow.com/questions/67977213/in-ruby-on-rails-unit-testing-update-model-against-mysql-database-gives-error-a,"['mysql', 'ruby-on-rails', 'ruby', 'testing', 'rspec']",104,False,1,0
Angular 12 setting up Unit test with JEST when running no tests found,"<p><strong>Edit: My Jest was not setup on my Angular project properly. so if you are experience this then your Jest was not setup properly, if anyone has a good guide on setting up jest please provide a link thanks</strong></p>
<p>Trying to setup unit tests for an Angular 12 project with Jest unit testing framework</p>
<p>I have followed a handful of tutorials and I am currently stuck.
I am able to run the test pack via the command line with using jest,
however no tests are found. I get the following message from the command line.</p>
<p><a href=""https://i.stack.imgur.com/OvuWT.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/OvuWT.png"" alt=""enter image description here"" /></a></p>
<p>From the blogs I found on how to set Jest up have suggested that I place part of my jest config in the package.json file</p>
<pre><code>  &quot;name&quot;: &quot;ramp-weather&quot;,
  &quot;version&quot;: &quot;0.0.0&quot;,
  &quot;scripts&quot;: {
    &quot;postinstall&quot;: &quot;ngcc&quot;,
    &quot;ng&quot;: &quot;ng&quot;,
    &quot;start&quot;: &quot;webpack serve &quot;,
    &quot;build&quot;: &quot;ng build&quot;,
    &quot;watch&quot;: &quot;ng build --watch --configuration development&quot;,
    &quot;test&quot;: &quot;jest --runInBand --coverage color&quot;
  },
  &quot;private&quot;: true,
  &quot;dependencies&quot;: {
    &quot;@angular/animations&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/common&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/compiler&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/core&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/forms&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/platform-browser&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/platform-browser-dynamic&quot;: &quot;~12.2.0&quot;,
    &quot;@angular/router&quot;: &quot;~12.2.0&quot;,
    &quot;material-design-icons&quot;: &quot;^3.0.1&quot;,
    &quot;rxjs&quot;: &quot;6.6.0&quot;,
    &quot;ts-jest&quot;: &quot;^27.0.7&quot;,
    &quot;tslib&quot;: &quot;^2.3.0&quot;,
    &quot;zone.js&quot;: &quot;~0.11.4&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@angular-devkit/build-angular&quot;: &quot;~12.2.8&quot;,
    &quot;@angular/cli&quot;: &quot;~12.2.8&quot;,
    &quot;@angular/compiler-cli&quot;: &quot;~12.2.0&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.16.0&quot;,
    &quot;@babel/preset-typescript&quot;: &quot;^7.16.0&quot;,
    &quot;@types/jest&quot;: &quot;^27.0.2&quot;,
    &quot;@types/node&quot;: &quot;^12.11.1&quot;,
    &quot;angular2-template-loader&quot;: &quot;^0.6.2&quot;,
    &quot;awesome-typescript-loader&quot;: &quot;^5.2.1&quot;,
    &quot;css-loader&quot;: &quot;^6.5.1&quot;,
    &quot;exports-loader&quot;: &quot;^3.0.0&quot;,
    &quot;file-loader&quot;: &quot;^6.2.0&quot;,
    &quot;html-loader&quot;: &quot;^2.1.2&quot;,
    &quot;html-webpack-plugin&quot;: &quot;^5.3.2&quot;,
    &quot;image-webpack-loader&quot;: &quot;^8.0.1&quot;,
    &quot;jest&quot;: &quot;^27.3.1&quot;,
    &quot;jest-preset-angular&quot;: &quot;^10.1.0&quot;,
    &quot;null-loader&quot;: &quot;^4.0.1&quot;,
    &quot;raw-loader&quot;: &quot;^4.0.2&quot;,
    &quot;source-map-loader&quot;: &quot;^1.0.0&quot;,
    &quot;style-loader&quot;: &quot;^3.3.1&quot;,
    &quot;to-string-loader&quot;: &quot;^1.2.0&quot;,
    &quot;ts-loader&quot;: &quot;^9.2.6&quot;,
    &quot;ts-node&quot;: &quot;^10.4.0&quot;,
    &quot;typescript&quot;: &quot;4.2.3&quot;,
    &quot;webpack&quot;: &quot;^5.63.0&quot;,
    &quot;webpack-cli&quot;: &quot;^4.8.0&quot;,
    &quot;webpack-dev-server&quot;: &quot;^4.3.1&quot;
  },
  &quot;jest&quot;: {
    &quot;preset&quot;: &quot;ts-jest&quot;,
    &quot;setupFilesAfterEnv&quot;: [
      &quot;&lt;rootDir&gt;/src/setup-jest.ts&quot;
    ],
    &quot;testPathIgnorePatterns&quot;: [
      &quot;&lt;rootDir&gt;/node_modules/&quot;,
      &quot;&lt;rootDir&gt;/dist/&quot;
    ],
    &quot;moduleDirectories&quot;: [ &quot;node_modules&quot;, &quot;src&quot; ],
    &quot;globals&quot;: {
      &quot;ts-jest&quot;: {
        &quot;tsConfig&quot;: &quot;&lt;rootDir&gt;/tsconfig.spec.json&quot;,
        &quot;stringifyContentPathRegex&quot;: &quot;\\.html$&quot;
      }
    }
  }
}
</code></pre>
<p>My Jest setup only has the following import
//setup-jest file
import 'jest-preset-angular/setup-jest';</p>
<p>Below is my configts.json file</p>
<pre><code>  &quot;compileOnSave&quot;: false,
  &quot;compilerOptions&quot;: {
    &quot;baseUrl&quot;: &quot;.&quot;,
    &quot;outDir&quot;: &quot;./dist/out-tsc&quot;,
    &quot;rootDir&quot;: &quot;.&quot;,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;strict&quot;: true,
    &quot;noImplicitReturns&quot;: true,
    &quot;noFallthroughCasesInSwitch&quot;: true,
    &quot;sourceMap&quot;: true,
    &quot;declaration&quot;: false,
    &quot;downlevelIteration&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;experimentalDecorators&quot;: true,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;importHelpers&quot;: true,
    &quot;target&quot;: &quot;es2017&quot;,
    &quot;module&quot;: &quot;es2020&quot;,
    &quot;lib&quot;: [&quot;es2018&quot;, &quot;dom&quot;]
  },
  &quot;angularCompilerOptions&quot;: {
    &quot;enableI18nLegacyMessageIdFormat&quot;: false,
    &quot;strictInjectionParameters&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;strictInputAccessModifiers&quot;: true,
    &quot;strictTemplates&quot;: true
  },
  &quot;include&quot;: [&quot;src/**/*&quot;]
}
</code></pre>
<p>I have been trying a number of combinations to get the tests to be picked up. but no luck. Any suggestions would be amazingly helpful. I thought it had to do with my baseUrl and rootDir as seen in the tsconfig.json file above, however I haven't been successful with my attempts.</p>
",https://stackoverflow.com/questions/69984002/angular-12-setting-up-unit-test-with-jest-when-running-no-tests-found,"['angular', 'unit-testing', 'installation', 'jestjs', 'angular12']",1002,False,1,1
How to make es6 module imports resolve correctly both for compiling via tsc and executing unit tests with Mocha without compiling using ts-node,"<p>I have an npm based project using typescript and es6 module imports.</p>
<p>To execute unit testing without having to compile the typescript, Mocha with ts-node is used.</p>
<p>For the typescript to compile correctly, the <code>.js</code> file extension needs to be included in the import statements in the source code. So:</p>
<pre class=""lang-js prettyprint-override""><code>import module from &quot;./module&quot;
// Results in runtime error, can't find module

import module from &quot;./module.js&quot;;
// executes correctly during runtime
</code></pre>
<p>However, when running unit tests via a script that calls Mocha combined with <code>ts-node/register</code>, the file extensions need to be omitted in the source code import statements:</p>
<pre class=""lang-js prettyprint-override""><code>import module from &quot;./module.js&quot;
// error thrown, can't find module

import module from &quot;./module&quot;;
// unit test executes correctly
</code></pre>
<p>I'm fairly certain it's an issue with how <code>ts-node</code> resolves the module imports vs how <code>tsc</code> does it, but am not certain on how to work around/solve the issue without compiling the source code first which I want to avoid if possible.</p>
<p>My <code>package.json</code> contains (with some properties omitted to make it a bit less verbose):</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;type&quot;: &quot;module&quot;,
  &quot;main&quot;: &quot;./npm-fs.js&quot;,
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;env TS_NODE_PROJECT='src/test/ts/tsconfig.json' mocha -r ts-node/register --extension ts --recursive true src/test/ts&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@types/chai&quot;: &quot;^4.2.14&quot;,
    &quot;@types/mocha&quot;: &quot;^8.0.4&quot;,
    &quot;@types/node&quot;: &quot;^14.14.9&quot;,
    &quot;chai&quot;: &quot;^4.2.0&quot;,
    &quot;mocha&quot;: &quot;^8.2.1&quot;,
    &quot;ts-node&quot;: &quot;^9.0.0&quot;,
    &quot;tslib&quot;: &quot;^1.14.1&quot;,
    &quot;typedoc&quot;: &quot;^0.19.2&quot;,
    &quot;typescript&quot;: &quot;^4.1.2&quot;
  }
}
</code></pre>
<p>The <code>tsconfig.json</code> for my unit tests are:</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;include&quot;: [&quot;./**/*.ts&quot;, &quot;../../main/ts/**/*.ts&quot;],
  &quot;compilerOptions&quot;: {
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;inlineSourceMap&quot;: true,
    &quot;lib&quot;: [&quot;ES2020&quot;],
    &quot;module&quot;: &quot;commonjs&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;noEmitOnError&quot;: false,
    &quot;removeComments&quot;: true,
    &quot;target&quot;: &quot;ES2020&quot;
  }
}
</code></pre>
<p>Switching the <code>module</code> property from <code>commonjs</code> to <code>es2020</code> results in <code>SyntaxError: Cannot use import statement outside a module</code> to be thrown instead of being unable to find the imported modules.</p>
<p>I've tried researching and looking up similar issues to find solutions and the answers I've found haven't worked or are for a different environment (i.e. not using ts-node).</p>
",https://stackoverflow.com/questions/65972485/how-to-make-es6-module-imports-resolve-correctly-both-for-compiling-via-tsc-and,"['typescript', 'mocha.js', 'es6-modules', 'ts-node']",1413,True,1,1
Test classes doesn&#39;t work correctly on android?,"<p>I'm a newbie in unit testing in android and I follow <a href=""https://github.com/fevziomurtekin/DeezerClone"" rel=""nofollow noreferrer"">this repository</a> on implementing it  but when I done it and run it my test it passes always even if I make a different clear assertion
like that</p>
<pre><code>MatcherAssert.assertThat(25, CoreMatchers.`is`(20))
</code></pre>
<p>so I thought I made something wrong and I tried to clone the repository and try it and found the repository also passed in all cases , I tried to change the MainCoroutineRule from <a href=""https://github.com/fevziomurtekin/DeezerClone/blob/master/app/src/sharedTest/MainCoroutineRule.kt"" rel=""nofollow noreferrer"">this</a> to <a href=""https://github.com/Pavneet-Sing/mvvm-flow-coroutine-testing/blob/master/app/src/test/java/com/pavneet_singh/mvvm_flow_coroutine_testing/MainCoroutineScopeRule.kt"" rel=""nofollow noreferrer"">this</a> and now the tests work but not passed</p>
<p>for example in Repository test it gives me this error</p>
<pre><code>junit.framework.AssertionFailedError: 
Expected :com.fevziomurtekin.deezer.core.data.ApiResult$Loading@5c7933ad
Actual   :Success(data=[AlbumData(diskNumber=1, duration=320, explicitContentCover=0, explicitContentLyrics=0,.......
</code></pre>
<p>and the method for that test case</p>
<pre><code>  @ExperimentalTime
  @Test
  fun fetchAlbumTracksFromNetworkTest() = runBlocking {
    val mockData = AlbumDetailsResponse(data = listOf(MockUtil.album), total = 12)
    val returnData = Response.success(mockData)
    whenever(service.fetchAlbumDetails(MockUtil.albumID)).thenReturn(returnData)

    repository.fetchAlbumTracks(MockUtil.albumID).test {
      val result = expectItem()
      assertEquals(result, ApiResult.Success(listOf(MockUtil.album)))
      Assert.assertEquals((result as ApiResult.Success&lt;List&lt;AlbumData&gt;&gt;).data[0].title, &quot;Alo&quot;)
      Assert.assertEquals(result.data[0].id, &quot;425605922&quot;)
      Assert.assertEquals(result.data[1].title, &quot;Geceler&quot;)
      Assert.assertEquals(result.data[1].id, &quot;425605932&quot;)
      expectComplete()
    }

    verify(service, atLeastOnce()).fetchAlbumDetails(MockUtil.albumID)
    verifyNoMoreInteractions(service)
  }
</code></pre>
<p>and for Viewmodel it gives me this error</p>
<pre><code>Argument(s) are different! Wanted:
observer.onChanged(
    Success(data=[ArtistAlbumData(cover=https://api.deezer.com/album/51174732/image, cov
</code></pre>
<p>for this test case</p>
<pre><code> @Test
    fun fetchAlbumListTest() = runBlocking {
        val mockList = listOf(MockUtil.album)

        val observer : Observer&lt;ApiResult&lt;List&lt;AlbumData&gt;&gt;&gt; = mock()
        val fetchedData : LiveData&lt;ApiResult&lt;List&lt;AlbumData&gt;&gt;&gt; = repository.fetchAlbumTracks(&quot;302127&quot;).asLiveData()
        fetchedData.observeForever(observer)

        viewModel.fetchingAlbumDatas(MockUtil.albumID)
        delay(500L)

        verify(observer).onChanged(ApiResult.Success(mockList))
        fetchedData.removeObserver(observer)


    }
</code></pre>
<p>and for Api test <a href=""https://github.com/fevziomurtekin/DeezerClone/blob/master/app/src/test/java/com/fevziomurtekin/deezer/domain/network/DeezerServiceTest.kt"" rel=""nofollow noreferrer"">here</a> it also fails to read input stream from input json files</p>
<p>Did I setup anything wrong on test configuration which makes the tests fails or the tests itself is wrong,the weird is the repository which I used there are many test classes for the whole project and I wonder if it didn't work it won't be pushed!</p>
<p>update: I open an issue on the repository and it has more details of what happens <a href=""https://github.com/fevziomurtekin/DeezerClone/issues/30"" rel=""nofollow noreferrer"">here</a></p>
<p>hope anyone can help with that?</p>
",https://stackoverflow.com/questions/67845727/test-classes-doesnt-work-correctly-on-android,"['android', 'unit-testing', 'kotlin', 'mockito', 'kotlin-coroutines']",202,False,1,0
Is there a way to run server with a session-persisted database connection in Django?,"<p>As I develop the backend side, I also develop the frontend. As you have probably guessed, I have to do some REST requests on my server.</p>
<p>Well, there are a couple of solutions for that. I can use mocks on the frontend, or <a href=""https://github.com/typicode/json-server"" rel=""nofollow noreferrer"">a fake JSON server</a>. However, there are some cons to this approach:</p>
<ul>
<li>I have to remodel what I have on an already existing backend server.</li>
<li>Dealing with authentication on a fake JSON server is not really comfortable.</li>
<li>I have to write a lot of boilerplate if I want to go on mocking and unit testing approach.</li>
</ul>
<p>Again, all the logic I want already exists in my Django project, so what I want is:</p>
<ol>
<li>Run a dev server.</li>
<li>Set up a fresh new database.</li>
<li><strong>Provide some initial data.</strong> Some fake users, posts, whatever.</li>
<li>Do my testing on my frontend project while the server runs.</li>
<li>Hit the kill signal. (CTRL+C)</li>
<li>Gracefully drop the database that I have created on step 2.</li>
<li>Shutdown the program.</li>
</ol>
<p>I use <code>pytest</code> and <code>pytest-django</code>. They do exactly these when they set up a test environment, I was wondering if I can manually do that.</p>
<p>Thanks in advance.</p>
<hr />
<h1>Environment</h1>
<ul>
<li>Python 3.9</li>
<li>Django 2.2</li>
</ul>
",https://stackoverflow.com/questions/69987275/is-there-a-way-to-run-server-with-a-session-persisted-database-connection-in-dja,['django'],69,True,1,1
How can I unit test a MongoDB query filter?,"<p>I have a scenario similar to the following (simplified for clarity):</p>
<pre><code>public class ExampleRepository
{
    private readonly IMongoDatabase _db;

    public ExampleRepository(IMongoClient mongoClient)
    {
        this._db = mongoClient.GetDatabase(&quot;database&quot;);
    }

    public async Task&lt;IEnumerable&lt;Item&gt;&gt; GetItemsUsingFilter(Guid ownerId, DateTimeOffset createdSince, IEnumerable&lt;ItemType&gt; typesToIgnore)
    {
        var cursor = await this._db.GetCollection&lt;Item&gt;(&quot;Items&quot;)
            .FindAsync(item =&gt;
                item.OwnerId == ownerId
                &amp;&amp;
                item.CreatedDate &gt;= createdSince
                &amp;&amp;
                !typesToIgnore.Contains(item.Type)
            .SortByDescending(item =&gt; item.UserRating)
            .Limit(10);

        return await cursor.ToListAsync();
    }
}
</code></pre>
<p>I want to write unit tests to verify the correctness of my query filter (as well as the sort and limit calls), but I can't figure out how to set up the test data to do so.</p>
<p>I've tried mocking the IMongoDatabase and setting up the GetCollection call to return a mock IMongoCollection, but this isn't the right approach, since I need to invoke the FindAsync call on a real MongoCollection.</p>
<p>I looked into changing the repository by splitting out the GetCollection call then applying the filtering using standard LINQ, but I don't want to have to return my entire collection from the DB and then query it in the repository layer.</p>
<p>I've found several examples of people unit testing MongoDB, but these all involved mocking the FindAsync call, which is not what I need to do.</p>
<p>I also considered declaring my filter as an Expression&lt;Func&lt;Item, Boolean&gt;&gt; in a separate class, so I could test that in isolation, but I'd like to explore other options before going down that route, as it adds complexity to the repository layer.</p>
",https://stackoverflow.com/questions/66012591/how-can-i-unit-test-a-mongodb-query-filter,"['c#', '.net', 'mongodb', 'unit-testing', 'mongodb-query']",758,False,1,1
How to generate Code Coverage for entire c++ codebase coverage w/ gcov/lcov,"<p>We have a large body of C/C++ code that is cross-compiled for an embedded Linux target. We've recently begun implementing unit tests (using gmock/gtest) that are run on our development server (which is Linux as well). The unit tests are executed automatically when check-ins are detected (we're using Microsoft Azure pipeline).</p>
<p>We're using gcov and lcov to analyze &amp; report code coverage during those unit tests, which has worked out fairly well. However, given that we didn't start out unit testing, a large portion of our codebase is not covered by unit tests. An interesting metric beyond &quot;what is the unit test coverage for those files being unit tested&quot; is &quot;how much of our entire codebase is being covered by unit tests&quot;, which includes those files not currently being unit tested. With gcov, you need to actually compile &amp; link a given source file and then execute the resulting program to get the possible coverage data for that file.</p>
<p>I have used the following script but it generates report for the classes that has unit test.:</p>
<pre><code># Get the path to the current folder
SCRIPT_DIR=$(pwd)

# SRC_DIR is the directory containing the .gcno files (%{buildDir} in Qt Creator)
SRC_DIR=&quot;$SCRIPT_DIR/../../build-KEBPLCComService-Desktop-Debug/&quot;

# COV_DIR is the directory where the coverage results will be stored
COV_DIR=&quot;$SCRIPT_DIR/../coverage&quot;

############################################################################################################

# Path where the HTML files should be saved
HTML_RESULTS=&quot;${COV_DIR}&quot;&quot;/html&quot;

# Create the html folder if it does not exists
mkdir -p ${HTML_RESULTS}

# Generate our initial info
lcov -d &quot;${SRC_DIR}&quot; -c -o &quot;${COV_DIR}/coverage.info&quot;

# Remove some paths/files which we don't want to calculate the code coverage (e.g. third party libraries) and generate a new coverage file filtered (feel free to edit it when necessary)
lcov -r &quot;${COV_DIR}/coverage.info&quot; &quot;*Qt*.framework*&quot; &quot;*.h&quot; &quot;*/tests/*&quot; &quot;*Xcode.app*&quot; &quot;*.moc&quot; &quot;*moc_*.cpp&quot; &quot;*/test/*&quot; &quot;*/build*/*&quot; -o &quot;${COV_DIR}/coverage-filtered.info&quot;

# Generate the HTML files
genhtml -o &quot;${HTML_RESULTS}&quot; &quot;${COV_DIR}/coverage-filtered.info&quot;

# Reset our counts
lcov -d &quot;${COV_DIR}&quot; -z

# Open the index.html
firefox &quot;${HTML_RESULTS}/index.html&quot;
</code></pre>
<p>How can i get code coverage for entire codebase?</p>
",https://stackoverflow.com/questions/69032981/how-to-generate-code-coverage-for-entire-c-codebase-coverage-w-gcov-lcov,"['c++', 'unit-testing', 'code-coverage', 'gcov', 'lcov']",510,False,1,0
"With unittest.mock, How to mock a class property with return_value depending on instance attribute?","<p>I have two classes <code>A</code> and <code>B</code>. I want to test function <code>foo_a</code> of <code>A</code>. Using some business logic, <code>foo_a</code> creates two possible instances of <code>B</code> (with different arguments) and calls function <code>foo_b</code> of <code>B</code>:</p>
<pre class=""lang-py prettyprint-override""><code>class A:
  def foo_a(self, *args, **kwargs):
    # some code above
    if condition_1:
      foo_b_result = B(**arguments_1).foo_b()
    else:
      foo_b_result = B(**arguments_2).foo_b()
    # some code below that returns foo_b_result + other objects independent of foo_b_result

</code></pre>
<p>The problem comes from the fact that <code>foo_b</code> is a complexe function that calls APIs and other stuff. I don't want to mock APIs here in this unit test so that <code>foo_b</code> returns the appropriate output, indeed, <code>foo_b</code> is already tested elsewhere in my set of unit tests for class <code>B</code>. Thus, in this context I care more about the correctness of <code>arguments_1</code> and <code>arguments_2</code> than the correctness of <code>foo_b_result</code>. Therefore, It would be nice if I could mock <code>foo_b</code> so that it returns outputs that could easily show if <code>foo_b</code> has been called with the right instance of <code>B</code>. For instance, <code>foo_b</code> could return <code>arguments_1</code> or <code>arguments_2</code>.</p>
<p>Maybe there is another better approach for unit testing <code>foo_a</code> in this case, any idea is welcome.</p>
<p><strong>UPDATE</strong>: Another way would be to create a new function that takes as input <code>condition_1</code> and returns either <code>arguments_1</code> or <code>arguments_2</code> (this function could be tested easily). Then I would mock <code>foo_b</code> so that it always return the same value (for instance 0). But still, it would be interesting to know if it's possible to mock <code>foo_b</code> so that it returns values according to <code>arguments_1</code> or <code>arguments_2</code>.</p>
",https://stackoverflow.com/questions/67824539/with-unittest-mock-how-to-mock-a-class-property-with-return-value-depending-on,"['python-3.x', 'mocking']",491,False,1,1
Test classes doesn&#39;t work correctly on android?,"<p>I'm a newbie in unit testing in android and I follow <a href=""https://github.com/fevziomurtekin/DeezerClone"" rel=""nofollow noreferrer"">this repository</a> on implementing it  but when I done it and run it my test it passes always even if I make a different clear assertion
like that</p>
<pre><code>MatcherAssert.assertThat(25, CoreMatchers.`is`(20))
</code></pre>
<p>so I thought I made something wrong and I tried to clone the repository and try it and found the repository also passed in all cases , I tried to change the MainCoroutineRule from <a href=""https://github.com/fevziomurtekin/DeezerClone/blob/master/app/src/sharedTest/MainCoroutineRule.kt"" rel=""nofollow noreferrer"">this</a> to <a href=""https://github.com/Pavneet-Sing/mvvm-flow-coroutine-testing/blob/master/app/src/test/java/com/pavneet_singh/mvvm_flow_coroutine_testing/MainCoroutineScopeRule.kt"" rel=""nofollow noreferrer"">this</a> and now the tests work but not passed</p>
<p>for example in Repository test it gives me this error</p>
<pre><code>junit.framework.AssertionFailedError: 
Expected :com.fevziomurtekin.deezer.core.data.ApiResult$Loading@5c7933ad
Actual   :Success(data=[AlbumData(diskNumber=1, duration=320, explicitContentCover=0, explicitContentLyrics=0,.......
</code></pre>
<p>and the method for that test case</p>
<pre><code>  @ExperimentalTime
  @Test
  fun fetchAlbumTracksFromNetworkTest() = runBlocking {
    val mockData = AlbumDetailsResponse(data = listOf(MockUtil.album), total = 12)
    val returnData = Response.success(mockData)
    whenever(service.fetchAlbumDetails(MockUtil.albumID)).thenReturn(returnData)

    repository.fetchAlbumTracks(MockUtil.albumID).test {
      val result = expectItem()
      assertEquals(result, ApiResult.Success(listOf(MockUtil.album)))
      Assert.assertEquals((result as ApiResult.Success&lt;List&lt;AlbumData&gt;&gt;).data[0].title, &quot;Alo&quot;)
      Assert.assertEquals(result.data[0].id, &quot;425605922&quot;)
      Assert.assertEquals(result.data[1].title, &quot;Geceler&quot;)
      Assert.assertEquals(result.data[1].id, &quot;425605932&quot;)
      expectComplete()
    }

    verify(service, atLeastOnce()).fetchAlbumDetails(MockUtil.albumID)
    verifyNoMoreInteractions(service)
  }
</code></pre>
<p>and for Viewmodel it gives me this error</p>
<pre><code>Argument(s) are different! Wanted:
observer.onChanged(
    Success(data=[ArtistAlbumData(cover=https://api.deezer.com/album/51174732/image, cov
</code></pre>
<p>for this test case</p>
<pre><code> @Test
    fun fetchAlbumListTest() = runBlocking {
        val mockList = listOf(MockUtil.album)

        val observer : Observer&lt;ApiResult&lt;List&lt;AlbumData&gt;&gt;&gt; = mock()
        val fetchedData : LiveData&lt;ApiResult&lt;List&lt;AlbumData&gt;&gt;&gt; = repository.fetchAlbumTracks(&quot;302127&quot;).asLiveData()
        fetchedData.observeForever(observer)

        viewModel.fetchingAlbumDatas(MockUtil.albumID)
        delay(500L)

        verify(observer).onChanged(ApiResult.Success(mockList))
        fetchedData.removeObserver(observer)


    }
</code></pre>
<p>and for Api test <a href=""https://github.com/fevziomurtekin/DeezerClone/blob/master/app/src/test/java/com/fevziomurtekin/deezer/domain/network/DeezerServiceTest.kt"" rel=""nofollow noreferrer"">here</a> it also fails to read input stream from input json files</p>
<p>Did I setup anything wrong on test configuration which makes the tests fails or the tests itself is wrong,the weird is the repository which I used there are many test classes for the whole project and I wonder if it didn't work it won't be pushed!</p>
<p>update: I open an issue on the repository and it has more details of what happens <a href=""https://github.com/fevziomurtekin/DeezerClone/issues/30"" rel=""nofollow noreferrer"">here</a></p>
<p>hope anyone can help with that?</p>
",https://stackoverflow.com/questions/67845727/test-classes-doesnt-work-correctly-on-android,"['android', 'unit-testing', 'kotlin', 'mockito', 'kotlin-coroutines']",202,False,1,0
How to make es6 module imports resolve correctly both for compiling via tsc and executing unit tests with Mocha without compiling using ts-node,"<p>I have an npm based project using typescript and es6 module imports.</p>
<p>To execute unit testing without having to compile the typescript, Mocha with ts-node is used.</p>
<p>For the typescript to compile correctly, the <code>.js</code> file extension needs to be included in the import statements in the source code. So:</p>
<pre class=""lang-js prettyprint-override""><code>import module from &quot;./module&quot;
// Results in runtime error, can't find module

import module from &quot;./module.js&quot;;
// executes correctly during runtime
</code></pre>
<p>However, when running unit tests via a script that calls Mocha combined with <code>ts-node/register</code>, the file extensions need to be omitted in the source code import statements:</p>
<pre class=""lang-js prettyprint-override""><code>import module from &quot;./module.js&quot;
// error thrown, can't find module

import module from &quot;./module&quot;;
// unit test executes correctly
</code></pre>
<p>I'm fairly certain it's an issue with how <code>ts-node</code> resolves the module imports vs how <code>tsc</code> does it, but am not certain on how to work around/solve the issue without compiling the source code first which I want to avoid if possible.</p>
<p>My <code>package.json</code> contains (with some properties omitted to make it a bit less verbose):</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;type&quot;: &quot;module&quot;,
  &quot;main&quot;: &quot;./npm-fs.js&quot;,
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;env TS_NODE_PROJECT='src/test/ts/tsconfig.json' mocha -r ts-node/register --extension ts --recursive true src/test/ts&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@types/chai&quot;: &quot;^4.2.14&quot;,
    &quot;@types/mocha&quot;: &quot;^8.0.4&quot;,
    &quot;@types/node&quot;: &quot;^14.14.9&quot;,
    &quot;chai&quot;: &quot;^4.2.0&quot;,
    &quot;mocha&quot;: &quot;^8.2.1&quot;,
    &quot;ts-node&quot;: &quot;^9.0.0&quot;,
    &quot;tslib&quot;: &quot;^1.14.1&quot;,
    &quot;typedoc&quot;: &quot;^0.19.2&quot;,
    &quot;typescript&quot;: &quot;^4.1.2&quot;
  }
}
</code></pre>
<p>The <code>tsconfig.json</code> for my unit tests are:</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;include&quot;: [&quot;./**/*.ts&quot;, &quot;../../main/ts/**/*.ts&quot;],
  &quot;compilerOptions&quot;: {
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;inlineSourceMap&quot;: true,
    &quot;lib&quot;: [&quot;ES2020&quot;],
    &quot;module&quot;: &quot;commonjs&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;noEmitOnError&quot;: false,
    &quot;removeComments&quot;: true,
    &quot;target&quot;: &quot;ES2020&quot;
  }
}
</code></pre>
<p>Switching the <code>module</code> property from <code>commonjs</code> to <code>es2020</code> results in <code>SyntaxError: Cannot use import statement outside a module</code> to be thrown instead of being unable to find the imported modules.</p>
<p>I've tried researching and looking up similar issues to find solutions and the answers I've found haven't worked or are for a different environment (i.e. not using ts-node).</p>
",https://stackoverflow.com/questions/65972485/how-to-make-es6-module-imports-resolve-correctly-both-for-compiling-via-tsc-and,"['typescript', 'mocha.js', 'es6-modules', 'ts-node']",1413,True,1,1
Abstract wrapper for fundamental types,"<p>I have created this interface as part of my c++ learning path. I was especially inspired by <a href=""https://stackoverflow.com/questions/17793298/c-class-wrapper-around-fundamental-types"">this post</a>.</p>
<p>The idea is to use the concrete implementations to perform some actions before and after any change of the wrapped variable.</p>
<p>For instance an implementation may notify an observer when the underlying variable changes, another one could be used as a mock for unit testing and so on.</p>
<pre><code>#pragma once

#define CREATE_MEMORY_CELL_IMPLEMENTATION(NAME)                             \
    template&lt;class T&gt;                                                       \
    class NAME : public MemorySystem::IMemoryCell&lt;T&gt;                        \
    {                                                                       \
    public:                                                                 \
        using MemorySystem::IMemoryCell&lt;T&gt;::operator=;                      \
        using MemorySystem::IMemoryCell&lt;T&gt;::value;                          \
        NAME(T v) : IMemoryCell&lt;T&gt;(v) {}                                    \
    protected:                                                              \
        void beforeSetting() override;                                      \
        void afterSetting()  override;                                      \
    };                                                                      


namespace MemorySystem {

    template&lt;class T&gt;
    class IMemoryCell {
    public:
        IMemoryCell(T v): value(v) {}
        operator T() const { return value; }

        // modifiers
        IMemoryCell&amp; operator=(T v)         { setValue(v); return *this;          }
        IMemoryCell&amp; operator+=(T v)        { setValue(value + v); return *this;  }
        IMemoryCell&amp; operator-=(T v)        { setValue(value - v); return *this;  }
        IMemoryCell&amp; operator*=(T v)        { setValue(value * v); return *this;  }
        IMemoryCell&amp; operator/=(T v)        { setValue(value / v); return *this;  }
        IMemoryCell&amp; operator%=(T v)        { setValue(value % v); return *this;  }
        IMemoryCell&amp; operator&amp;=(T v)        { setValue(value &amp; v); return *this;  }
        IMemoryCell&amp; operator|=(T v)        { setValue(value | v); return *this;  }
        IMemoryCell&amp; operator^=(T v)        { setValue(value ^ v); return *this;  }
        IMemoryCell&amp; operator&lt;&lt;=(T v)       { setValue(value &lt;&lt; v); return *this; }
        IMemoryCell&amp; operator&gt;&gt;=(T v)       { setValue(value &gt;&gt; v); return *this; }

        // increment &amp; decrement
        IMemoryCell&amp; operator++()           { setValue(value + 1); return *this; }                  // prefix increment
        IMemoryCell&amp; operator--()           { setValue(value - 1); return *this; }                  // prefix decrement
        T operator++(int)                   { T old = value; setValue(value + 1); return old; }     // postfix increment 
        T operator--(int)                   { T old = value; setValue(value - 1); return old; }     // postfix decrement            


    protected:
        T value;
        virtual void beforeSetting() = 0;
        virtual void afterSetting()  = 0;

    private:
        void setValue(const T&amp; val) {
            beforeSetting();
            value = val;
            afterSetting();
        };
    };
}
</code></pre>
<p>Here an example of its usage:</p>
<pre><code>#include &quot;memory.h&quot;

CREATE_MEMORY_CELL_IMPLEMENTATION(testMemory)

template &lt;class T&gt; void testMemory&lt;T&gt;::beforeSetting() {
    std::cout &lt;&lt; &quot;Old value: &quot; &lt;&lt; value &lt;&lt; std::endl;
};

template &lt;class T&gt; void testMemory&lt;T&gt;::afterSetting() {
    std::cout &lt;&lt; &quot;New value: &quot; &lt;&lt; value &lt;&lt; std::endl;
};
</code></pre>
<p>What I don't like is that the derived class must explicitly declare the use of the base class assignment operator and &quot;value&quot;member. As you can see my first idea was to use a macro to create a skeleton for the implementation.</p>
<p>This approach has two major drawbacks:</p>
<ol>
<li>It limits the possibilities in terms of concrete implementation class. For instance a new member cannot be defined inside the skeleton.</li>
<li>The definition of the overridden methods is cumbersome.</li>
</ol>
<p>What do you think?</p>
<p>An alternative could be to define it as a concrete class and to pass the pre-processing and post-processing functions as pointers to the constructor. Do you think that it can be a better approach?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/68959752/abstract-wrapper-for-fundamental-types,['c++'],47,False,1,0
Mocking FromSqlInterpolated,"<p>I'm attempting to build out some unit tests for a repository built around stored procs, so we have quite a few instances of FromSqlInterpolated() that casts the result into a EF friendly model.  While this works well, unit testing it is proving to be a nightmare  When using EF, and testing anything dependent on the context, I typically use an in Memory DB as it is the most painless way of unit tests (after a couple years of stupidly mocking out most of the functionality of EF).  I imagine that in order to get FromSqlInterpolated tested, I'm going to have to mock the db context, as well as some of the support methods, but no matter how I tweak it, I continue to get exceptions like arg1 is null.
while I won't share all the code, the gist of what I have that does not work it is:</p>
<pre><code>var dataSet = new List&lt;efDBModel&gt;();

var mockProvider = new Mock&lt;IQueryProvider&gt;();
mockProvider.Setup(x =&gt; x.CreateQuery(It.IsAny&lt;MethodCallExpression&gt;())).Returns(dataSet.AsQueryable());

var mockedDbSet = new Mock&lt;DbSet&lt;efDBModel&gt;();
mockedDbSet.As&lt;IQueryable&lt;efDBModel&gt;&gt;().Setup(x =&gt; x.Provider).Returns(mockProvider.Object);

var dbOptions = new DbContextOptions&lt;dbContext&gt;();
var context = new Mock&lt;dbContext(dbOptions):
context.Setup(x =&gt; x.SprocReturnedData).Returns(mockedDbSet.Object);

var repo = new testRepository(context.Object);

var result = repo.DoUnitOfWork();
</code></pre>
<p>The last time I mocked out EF Contexts, I had to mock out a lot more than just the provider, but I'm not sure anymore what needs to be mocked.  As an example, the code that is throwing the exception looks something like:</p>
<pre><code>var result = context.SprocReturnedData.FromSqlInterpolated($&quot;Exec dbo.someprocname {someValue}&quot;).ToList();
</code></pre>
<p>The full error message is:</p>
<pre><code>System.AggregateException: one or more errors occurred.  (Value cannot be null. (Parameter 'arg0'))
---- System.ArgumentNullException: Value cannot be null. (Parameter 'arg0')

Stack Trace: (snippingout the testing method stuff):
Expression.Call(Expression instance, MethodInfo method, Expression arg0, Expression arg1, Expression arg2)
RelationshipQueryableExtensions.FromSqlInterpolated[TEntity](DbSet`1 source, FormattableString sql)

</code></pre>
<p>Any Advice?</p>
",https://stackoverflow.com/questions/67061424/mocking-fromsqlinterpolated,"['c#', 'unit-testing', 'entity-framework-core', 'mocking', 'asp.net-core-3.1']",275,False,0,0
Not understanding the benefits of using dependency injection frameworks,"<p>This is an honest question as I've started acquainting myself with Dagger for a java project I'm working on. I currently have this setup: I have a manager class that accepts requests, utilizes dao's to perform transactions and then responds back to the caller. This is the skeleton code that I've implemented:</p>
<pre><code>public class MyManager {
   public Response start(Request req){
      return getDao().save(req);
   }

   public MyDao getDao() {
      return new MyDao();
   }
}

// Clients would then invoke:
// new MyManager().start(req)
</code></pre>
<p>Now if I understand correctly, I would have to introduce a new interface and module to transition to dagger. The component would look like:</p>
<pre><code>@Component(module = MyManagerModule.class)
public interface MyManagerComponent {
   MyManger getMyManager();
}
</code></pre>
<p>and the module would look like:</p>
<pre><code>@Module
public class MyManagerModule {
   @Provides
   public MyDao provideMyDao() {
      return new MyDao();
   }
}
</code></pre>
<p>and finally I would modify my original class to have constructor injection:</p>
<pre><code>public class MyManager {
   @Getter
   private MyDao dao;

   @Inject
   public MyManager(MyDao dao) {
      this.dao = dao;
   }

   public Resonse start(Request req) {
      return getDao().save(req);
   }
}

// Clients now have to do:
// MyManagerComponent component = DaggerMyManagerComponent.create();
// component.getMyManager().start(req);
</code></pre>
<p>With DI, this seems much more complex. Not only do I have to create the module and interface but my client has to make a strange component and then invoke my manager from it. I'm failing to see the benefit of this. I keep hearing that this helps with unit testing but I don't understand. Before, I could easily unit test my code by simply mocking the <code>getDao()</code> method; something like</p>
<pre><code>manager = Spy(MyManager)
manager.getDao() &gt;&gt; { return Mock(MyDao); }
</code></pre>
<p>I didn't really need DI to do this. Is this example to small to fully appreciate the benefits of DI?</p>
",https://stackoverflow.com/questions/67452582/not-understanding-the-benefits-of-using-dependency-injection-frameworks,"['java', 'dependency-injection', 'dagger-2']",105,False,0,0
Running SonarQube analysis via jenkins throwing StackOverFlow error for Spark Scala code,"<p>I have a spark scala application which runs fine without any issues in the jenkins build as well as local build. For one of the method we are using 160 withColumn for adding columns to the dataframe. We have a request for adding two more additional columns. When I added it, everything runs fine from local as well as from EMR, but sonar analysis is throwing stackoverflow error when added those two columns. If I remove it there is no issues. Not sure if the jenkins container has enough resources or not. Tried with different sonar-scanner versions, all are failing, but unit testing, code coverage works fine from local and jenkins, only sonar-scanner is failing. <a href=""https://i.stack.imgur.com/bWMiX.png"" rel=""nofollow noreferrer"">Jenkins error 1</a>
<a href=""https://i.stack.imgur.com/si5IJ.png"" rel=""nofollow noreferrer"">Jenkins error 2</a></p>
<p>Do I need to rewrite the code to not use withcolumns multiple times ?
Or is this something to fix at Sonar-scanner or jenkins level ?</p>
<p>Is there a better way of adding columns other than using 160 times withcolumn ?</p>
<ul>
<li>SonarScanner - 4.6.1.2450</li>
<li>Scala - 2.12</li>
<li>sbt  - 1.4.6</li>
</ul>
<pre><code>     val tempDf = slimDf.withColumn(&quot;AAA&quot;, concat($&quot;post_visid&quot;, $&quot;post_visid&quot;)).drop(&quot;post_visid&quot;).drop(&quot;post_visid&quot;)
          .withColumnRenamed(&quot;aaa&quot;, &quot;VST_SEQ_NUM&quot;)
          .withColumnRenamed(&quot;bbb&quot;, &quot;PGVW_SEQ_NUM&quot;)
          .withColumn(&quot;ddd&quot;, to_date($&quot;date_time&quot;))
          .withColumn(&quot;ccc&quot;, date_format($&quot;date_time&quot;, &quot;HH:mm:ss&quot;))
          .withColumn(&quot;eee&quot;, truncateStringUDF($&quot;evar60&quot;, lit(255)))
          .withColumnRenamed(&quot;fff&quot;, &quot;PAGE_EVT_ID&quot;)
          .withColumn(&quot;ggg&quot;, when($&quot;hhh&quot; === 0 || $&quot;hhh&quot; === 70, true).otherwise(false))
          .withColumn(&quot;iii&quot;, truncateStringUDF($&quot;page_event_var1&quot;, lit(1000)))
          .withColumn(&quot;jjj&quot;, truncateStringUDF($&quot;page_event_var2&quot;, lit(1000)))
          .withColumn(&quot;kkk&quot;, truncateStringUDF($&quot;post_prop11&quot;, lit(255)))
          .withColumn(&quot;lll&quot;, truncateStringUDF($&quot;exclude_hit&quot;, lit(255)))
          .withColumn(&quot;mmm&quot;, truncateStringUDF($&quot;post_prop9&quot;, lit(1000)))
          .withColumn(&quot;FRST4&quot;, when($&quot;daily_visitor&quot; === 0, &quot;N&quot;).otherwise(&quot;Y&quot;)).drop(&quot;daily_visitor&quot;)
          .withColumn(&quot;FRST3&quot;, when($&quot;hourly_visitor&quot; === 0, &quot;N&quot;).otherwise(&quot;Y&quot;)).drop(&quot;hourly_visitor&quot;)
          .withColumn(&quot;FRST1&quot;, when($&quot;weekly_visitor&quot; === 0, &quot;N&quot;).otherwise(&quot;Y&quot;)).drop(&quot;weekly_visitor&quot;)
          .withColumn(&quot;FRST2&quot;, when($&quot;monthly_visitor&quot; === 0, &quot;N&quot;).otherwise(&quot;Y&quot;)).drop(&quot;monthly_visitor&quot;)
          .withColumn(&quot;FRST_QTRLY_VST_IND&quot;, when($&quot;quarterly_visitor&quot; === 0, &quot;N&quot;).otherwise(&quot;Y&quot;)).drop(&quot;quarterly_visitor&quot;)
</code></pre>
<p>Similar to this, there are total of 160 withcolumn's that adds total of 160 columns to the dataframe</p>
",https://stackoverflow.com/questions/69754177/running-sonarqube-analysis-via-jenkins-throwing-stackoverflow-error-for-spark-sc,"['scala', 'apache-spark', 'jenkins', 'sonarqube', 'stack-overflow']",179,False,0,1
How to mock helper functions in Firebase Cloud Functions?,"<p>I am currently exploring unit-testing in Firebase Cloud Functions and ran into a use-case that seems like it would be quite frequent but isn't covered by the official documentation.</p>
<p>When writing Cloud Functions for various processes and triggers, we usually use separate helper functions to help us write more reusable code. For example:</p>
<pre><code>// index.ts
import * as functions from &quot;firebase-functions&quot;;

function add(num1: number, num2: number) {
    return num1 + num2;
}

exports.getSum = functions.https.onCall((data, context) =&gt; {
    return {
        result: add(data.num1, data.num2)
    }
})
</code></pre>
<p>When I now want to test <code>getSum</code>, I would have to import it into my test file and make an assertion. However this is where I encounter the issue:</p>
<p>How do I assert that <code>add</code> has been called in <code>getSum</code>? Or better: how do I mock <code>add</code>?</p>
<p>The only workaround I have found so far is exporting <code>add</code> as well and then modifying the code to call <code>this.add</code> instead of just <code>add</code> like so:</p>
<pre><code>// index.ts
import * as functions from &quot;firebase-functions&quot;;

export function add(num1: number, num2: number) {
    return num1 + num2;
}

exports.getSum = functions.https.onCall((data, context) =&gt; {
    return {
        // @ts-ignore
        result: this.add(data.num1, data.num2)
    }
})
</code></pre>
<p>However this solution is not ideal as I 1. can't guarantee that <code>this</code> isn't undefined (which is also why I need to <code>// @ts-ignore</code> it) and 2. need to modify the original code to make testing work.</p>
<p>Is there any way to make this work without modifying the functions code? Any best practice for testing these kind of helper functions? Thank you in advance!</p>
<p>Here is the full unit test code I have used for the workaround:</p>
<pre><code>// index.unit.test.ts
const testEnvironment = require(&quot;firebase-functions-test&quot;)(
  {
    databaseURL: &quot;&quot;,
        storageBucket: &quot;&quot;,
        projectId: &quot;&quot;,
    },
    &quot;credentials.json&quot;
  );
  const myFunctions = require(&quot;../src/index&quot;);


describe(&quot;getSum&quot;, () =&gt; {
    let wrapper: any, group: any;

    beforeAll(() =&gt; {
        group = myFunctions.addition
        wrapper = testEnvironment.wrap(group.getSum);
    });

    it(&quot;adds two numbers&quot;, () =&gt; {    
        group.add = jest.fn()
    
        wrapper({ num1: 2, num2: 2})

        expect(group.add).toHaveBeenCalled()
    });
});

</code></pre>
",https://stackoverflow.com/questions/65763396/how-to-mock-helper-functions-in-firebase-cloud-functions,"['typescript', 'firebase', 'unit-testing', 'jestjs', 'google-cloud-functions']",547,True,0,1
Is there a way to limit stack trace information in Flutter,"<p>I'm trying to find a way to make the Flutter unit test failures messages more useful to me.</p>
<p>Right now on a simple test that doesn't do anything it useful will produce a stack trace of 50+ lines of things that are all useless to me.  I don't care what the Flutter framework is doing to get my test to run, I care about what I can control, in this example the top 2 lines.</p>
<p>Currently it does something like this:</p>
<pre><code>══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
  Expected: &lt;true&gt;
  Actual: &lt;false&gt;

When the exception was thrown, this was the stack:
#4      main.&lt;anonymous closure&gt; (file:///D:/disclaimer_screen_test.dart:57:5)
&lt;asynchronous suspension&gt;
#5      main.&lt;anonymous closure&gt; (file:///D:/disclaimer_screen_test.dart)
#6      testWidgets.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (package:flutter_test/src/widget_tester.dart:146:29)
&lt;asynchronous suspension&gt;
#7      testWidgets.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (package:flutter_test/src/widget_tester.dart)
#8      TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:784:19)
&lt;asynchronous suspension&gt;
#11     TestWidgetsFlutterBinding._runTest (package:flutter_test/src/binding.dart:764:14)
#12     AutomatedTestWidgetsFlutterBinding.runTest.&lt;anonymous closure&gt; (package:flutter_test/src/binding.dart:1173:24)
#13     FakeAsync.run.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (package:fake_async/fake_async.dart:178:54)
#18     withClock (package:clock/src/default.dart:48:10)
#19     FakeAsync.run.&lt;anonymous closure&gt; (package:fake_async/fake_async.dart:178:22)
#24     FakeAsync.run (package:fake_async/fake_async.dart:178:7)
#25     AutomatedTestWidgetsFlutterBinding.runTest (package:flutter_test/src/binding.dart:1170:15)
#26     testWidgets.&lt;anonymous closure&gt; (package:flutter_test/src/widget_tester.dart:138:24)
#27     Declarer.test.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (package:test_api/src/backend/declarer.dart:175:19)
&lt;asynchronous suspension&gt;
#28     Declarer.test.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (package:test_api/src/backend/declarer.dart)
#33     Declarer.test.&lt;anonymous closure&gt; (package:test_api/src/backend/declarer.dart:173:13)
#34     Invoker.waitForOutstandingCallbacks.&lt;anonymous closure&gt; (package:test_api/src/backend/invoker.dart:231:15)
#39     Invoker.waitForOutstandingCallbacks (package:test_api/src/backend/invoker.dart:228:5)
#40     Invoker._onRun.&lt;anonymous closure&gt;.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (package:test_api/src/backend/invoker.dart:383:17)
&lt;asynchronous suspension&gt;
#41     Invoker._onRun.&lt;anonymous closure&gt;.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (package:test_api/src/backend/invoker.dart)
#46     Invoker._onRun.&lt;anonymous closure&gt;.&lt;anonymous closure&gt; (package:test_api/src/backend/invoker.dart:370:9)
#47     Invoker._guardIfGuarded (package:test_api/src/backend/invoker.dart:415:15)
#48     Invoker._onRun.&lt;anonymous closure&gt; (package:test_api/src/backend/invoker.dart:369:7)
#55     Invoker._onRun (package:test_api/src/backend/invoker.dart:368:11)
#56     LiveTestController.run (package:test_api/src/backend/live_test_controller.dart:153:11)
#57     RemoteListener._runLiveTest.&lt;anonymous closure&gt; (package:test_api/src/remote_listener.dart:256:16)
#62     RemoteListener._runLiveTest (package:test_api/src/remote_listener.dart:255:5)
#63     RemoteListener._serializeTest.&lt;anonymous closure&gt; (package:test_api/src/remote_listener.dart:208:7)
#81     _GuaranteeSink.add (package:stream_channel/src/guarantee_channel.dart:125:12)
#82     new _MultiChannel.&lt;anonymous closure&gt; (package:stream_channel/src/multi_channel.dart:159:31)
#86     CastStreamSubscription._onData (dart:_internal/async_cast.dart:85:11)
#120    new _WebSocketImpl._fromSocket.&lt;anonymous closure&gt; (dart:_http/websocket_impl.dart:1145:21)
#128    _WebSocketProtocolTransformer._messageFrameEnd (dart:_http/websocket_impl.dart:338:23)
#129    _WebSocketProtocolTransformer.add (dart:_http/websocket_impl.dart:232:46)
#139    _Socket._onData (dart:io-patch/socket_patch.dart:2044:41)
#148    new _RawSocket.&lt;anonymous closure&gt; (dart:io-patch/socket_patch.dart:1580:33)
#149    _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1076:14)
(elided 111 frames from dart:async and package:stack_trace)

This was caught by the test expectation on the following line:
  file:///D:/disclaimer_screen_test.dart line 57
The test description was:
  someScreen Widget Test
════════════════════════════════════════════════════════════════════════════════════════════════════
Test failed. See exception logs above.
The test description was: someScreen Widget Test

✖ someScreen Widget Test
Exited (1)
</code></pre>
<p>Ideally I would like to limit or remove the stack trace altogether so that it looks something like this:</p>
<pre><code>══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
  Expected: &lt;true&gt;
  Actual: &lt;false&gt;

This was caught by the test expectation on the following line:
  file:///D:/disclaimer_screen_test.dart line 57
The test description was:
  someScreen Widget Test
════════════════════════════════════════════════════════════════════════════════════════════════════
Test failed. See exception logs above.
The test description was: someScreen Widget Test

✖ someScreen Widget Test
Exited (1)
</code></pre>
<p>This way I get all the relevant information to me without all the noise of things I cannot control and quite honestly are not broken.  I trust that the Framework and 3rd party packages are working as expected, if they aren't I'm doing a different investigation.</p>
<p>I found the <a href=""https://api.flutter.dev/flutter/foundation/FlutterError/defaultStackFilter.html"" rel=""nofollow noreferrer"">defaultStackFilter method</a> but that appears to be an internal Flutter method rather than something I can control, perhaps I just don't understand it.</p>
<p>Is there a way to change the stack output as a whole or perhaps a way to disable it in the unit testing environment?</p>
<p>Thank you in advance!</p>
",https://stackoverflow.com/questions/66127531/is-there-a-way-to-limit-stack-trace-information-in-flutter,"['flutter', 'dart', 'visual-studio-code']",538,True,4,2
Test suite failed to run with @react-navigation/stack,"<p>I started writing unit testing in React Native app. I created new project in Typescript using the following command.</p>
<blockquote>
<p>npx react-native init rn_jest --template
react-native-template-typescript</p>
</blockquote>
<p>When i executed npm test in root of project i got the below results</p>
<blockquote>
<p>PASS  <strong>tests</strong>/App-test.tsx (7.472s)   ✓ renders correctly (4329ms)
Test Suites: 1 passed, 1 total Tests:       1 passed, 1 total
Snapshots:   0 total Time:        7.64s Ran all test suites.</p>
</blockquote>
<p>Next i integrated <a href=""https://reactnavigation.org"" rel=""nofollow noreferrer"">React Navigation</a> in app and executed npm test again, but this time i got following error</p>
<blockquote>
<p>FAIL  <strong>tests</strong>/App-test.tsx   ● Test suite failed to run</p>
<pre><code>/Users/macbookpro/Documents/Manheium_Express/rn_jest/node_modules/@react-navigation/stack/lib/commonjs/views/assets/back-icon.png:1
�PNG

SyntaxError: Invalid or unexpected token

  at Runtime._execModule (node_modules/jest-runtime/build/index.js:1157:58)
</code></pre>
<p>console.error
react-native-gesture-handler module was not found. Make sure you're running your app on the native platform and your code is linked
properly (cd ios &amp;&amp; pod install &amp;&amp; cd ..).</p>
<pre><code>For installation instructions, please refer to https://docs.swmansion.com/react-native-gesture-handler/docs/#installation

  at Object.&lt;anonymous&gt; (node_modules/react-native-gesture-handler/lib/commonjs/RNGestureHandlerModule.ts:5:3)
</code></pre>
<p>Test Suites: 1 failed, 1 total Tests:       0 total Snapshots:   0
total Time:        3.229s Ran all test suites. npm ERR! Test failed.
See above for more details.</p>
</blockquote>
<p>I checked this <a href=""https://github.com/react-navigation/react-navigation/issues/8669"" rel=""nofollow noreferrer"">link</a> and not found any solution. here is code inside App-test.tsx file</p>
<pre><code>import 'react-native';
import React from 'react';
import App from '../App';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

it('renders correctly', () =&gt; {
  renderer.create(&lt;App /&gt;);
});
</code></pre>
<p>Below is the package.json</p>
<pre><code> &quot;dependencies&quot;: {
    &quot;@react-native-community/masked-view&quot;: &quot;^0.1.10&quot;,
    &quot;@react-navigation/native&quot;: &quot;^5.9.3&quot;,
    &quot;@react-navigation/stack&quot;: &quot;^5.14.3&quot;,
    &quot;react&quot;: &quot;16.13.1&quot;,
    &quot;react-native&quot;: &quot;0.63.4&quot;,
    &quot;react-native-gesture-handler&quot;: &quot;^1.10.3&quot;,
    &quot;react-native-reanimated&quot;: &quot;^2.0.0&quot;,
    &quot;react-native-safe-area-context&quot;: &quot;^3.1.9&quot;,
    &quot;react-native-screens&quot;: &quot;^2.18.1&quot;
  },
</code></pre>
<p>I followed this <a href=""https://reactnavigation.org/docs/testing/"" rel=""nofollow noreferrer"">link</a> also but no luck. if any one has solved this issue in unit test using jest please help me out</p>
",https://stackoverflow.com/questions/66514035/test-suite-failed-to-run-with-react-navigation-stack,"['react-native', 'jestjs', 'react-navigation-v5']",1816,True,2,1
How to test a command line application using junit,"<p>I understand that junit is specifically for unit testing, but please read about my situation below.</p>
<p>I have a command line application written in Java, but I use GraalVM to compile native binaries of my app for Windows, Linux, and Mac.
The issue is that sometimes the native binaries for my app will behave a little differently depending on what operating system is being used. Because of that, I want to automate the testing my command line application on all three operating systems, so that I can ensure that I easily take notice of when something is not working as expected.</p>
<p>To clarify, my hope is that I could use something like junit (or some other testing tool) to interact with my command line application by calling my app's native binary with some arguments, then watch for what text gets printed back out. If the text printed by my command line app matches what I expect, then the test passes.</p>
<p>Again, I know and understand that this is not junit's primary use case, but is this something that I can get junit to do? If so, how? If not, what other tool/framework would you recommend that I look at?</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/69914115/how-to-test-a-command-line-application-using-junit,"['java', 'testing', 'junit', 'automated-tests']",224,True,2,1
Wordpress plugin + phpunit + custom db tables and constants,"<p>I'm currently trying to set up testing for a WordPress plugin I'm developing. I've followed the guide at <a href=""https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests"" rel=""nofollow noreferrer"">https://make.wordpress.org/cli/handbook/misc/plugin-unit-tests</a>, installed dependencies, PHPUnit 7, and generated the test files via the bin/install-wp-tests.sh script. All is good so far.</p>
<p>I can get PHPUnit to run, but my plugin both installs custom database tables (upon activation, if they're not already installed) and also uses some custom constants loaded into the wp-config.php file. However it seems PHPUnit doesn't &quot;activate&quot; the plugin so this hook doesn't fire, thus the DB table installs are never performed and so MySQL necessarily spits out an error that the wp_xxxxx table doesn't exist. Additionally, I get errors saying Use of undefined constant XXXXX</p>
<p>I've been searching around for a while but can't find much regarding unit testing with this sort of custom plugin setup.</p>
<p>So, how can you run plugin activation upon bootstrapping PHPUnit, so that the custom plugin DB tables are installed into the testing database prior to running tests?</p>
<p>Also, how can you pull in custom constants/config (possibly in a separate file with test values for the constants), so that they're available to the plugin like they would be if included in wp-config.php</p>
",https://stackoverflow.com/questions/69980441/wordpress-plugin-phpunit-custom-db-tables-and-constants,"['php', 'wordpress', 'testing', 'phpunit']",226,False,1,0
from django.db.models.Value not including quotes when converting to query string,"<p>I am using the <code>django.db.models.Value</code> expression within a QuerySet function in Django 3.2.8. When passing a string value (<code>&quot;|&quot;</code> in my example below), the conversion to a query string fails to add the <code>'</code>, which makes the query to fail.</p>
<pre><code>from django.db import models
from django.db.models import F, Value
from django.db.models.functions import Concat

class PurchaseOrder(models.Model):
    id = models.AutoField(primary_key=True)
    customer_name = models.CharField(max_length=50)
    date = models.DateField()
    

qs = PurchaseOrder.objects.annotate(
    concat=Concat(
        F(&quot;customer_name&quot;),
        Value(&quot;~&quot;),
        F(&quot;date&quot;),
        output_field=models.CharField(),
    )
).values(&quot;concat&quot;)

</code></pre>
<pre><code>&gt;&gt;&gt; print(str(qs.query))
SELECT CONCAT(&quot;purchaseorder&quot;.&quot;customer_name&quot;, CONCAT(~, &quot;purchaseorder&quot;.&quot;date&quot;)) AS &quot;concat&quot; FROM &quot;purchaseorder&quot;
</code></pre>
<p>As it can be seen from the result above, the <code>~</code> character  is missing the two <code>'</code> it should be wrapped around: <code>CONCAT('~', &quot;purchaseorder&quot;.&quot;date&quot;)</code>.</p>
<p>Is this the expected functionality of expression <code>Value</code> or a bug that should be reported?
I am inclined to think it is a bug, because of the following:</p>
<p>I initially solved the problem above by writing it as <code>Value(&quot;'~'&quot;)</code>, with the two <code>'</code> inside my string. However, when running the query in a sqlite3 database during unit testing I got an error in the query. I realised that sqlite has a different syntax than Postgres (my production and local dev database) for function Contact:</p>
<ul>
<li>Postgres: <code>CONCAT([args])</code></li>
<li>Sqlite: <code>arg1 || arg2 ...</code></li>
</ul>
<p>In the sqlite case, Django also wraps every argument in the concatenation with <code>Coalesce</code>:</p>
<pre><code>COALESCE(arg1, '') || COALESCE(arg2, '')
</code></pre>
<p>The query that was resulting from this in sqlite looked like the one below:</p>
<pre><code>... COALESCE(&quot;purchaseorder&quot;.&quot;customer_name&quot;, ) || COALESCE('~', ) || COALESCE(&quot;purchaseorder&quot;.&quot;date&quot;,)
</code></pre>
<p>(Note that I passed <code>'</code> inside <code>Value(&quot;'~'&quot;)</code> this time)</p>
<p>The above query will give an error as the second argument inside <code>COALESCE</code> must not be empty (<code>''</code> is an acceptable input).</p>
<p>If the above problem is due to a bug, what would be the best workaround to make the sqlite query work?</p>
",https://stackoverflow.com/questions/70274642/from-django-db-models-value-not-including-quotes-when-converting-to-query-string,"['sqlite', 'django-models', 'concatenation', 'coalesce']",299,False,1,1
"Is there a way, in tests, to defend against &quot;correct&quot; results coming out of undefined behavior?","<h2>Foreword</h2>
<p><a href=""https://stackoverflow.com/questions/66816301/is-there-a-safe-version-of-c-without-undefined-behaviour/66816831#66816831"">I know what UB is</a>, so I'm not asking how to avoid it, but whether there's a way to make unit testing more resistent to it, even if it's a probabilistic approach, that just makes UB more likely to become apparent rather than silently passing tests successfully.</p>
<h2>The question</h2>
<p>Let's say I want to write a test for a function and I that I do it wrong, like this:</p>
<pre><code>#include &lt;gtest/gtest.h&gt;
#include &lt;vector&gt;

int main()
{
    std::vector&lt;int&gt; v{0};
    for (auto i = 0; i != 100; ++i) {
      v.push_back(3);     // push a 3
      v.pop_back();       // ops, popping the value I just pushed
      EXPECT_EQ(v[1], 3); // UB
    }
}
</code></pre>
<p>On my machine, it consistently passes; maybe the program is so simple that there's no reason for the 3 to be truly wiped away from the area of memory where it lives before <code>pop_back</code>.</p>
<p>Therefore the test clearly isn't reliable.</p>
<p>Is there any way to protect against such accidentally succesful tests, even on a statistical ground (&quot;calling <code>shuffleFreedMemory()</code> before the <code>EXPECT_EQ</code> you decrease the chances that UB will sting you&quot;)?</p>
<hr />
<p>The code above is just an example (I'm not willing to test the STL); I know of <code>std::vector&lt;T&gt;::at</code> as a bound-safe <code>std::vector&lt;T&gt;::operator[]</code>, but that's a way to prevent undefined behavior in the first place, whereas I'm wandering about how to defend against it.</p>
<p>For instance, leveraging UB itself by adding <code>*(&amp;v[0] + 1) = 10;</code> right after <code>v.pop_back();</code>, will make the incorrectness of the test apparent, at least on my machine.</p>
<p>So I'm kind of thinking of a tool/library/whatever which would, let's say, set the memory not hold by <code>v</code> to random values after every executable line.</p>
",https://stackoverflow.com/questions/68728928/is-there-a-way-in-tests-to-defend-against-correct-results-coming-out-of-unde,"['c++', 'unit-testing', 'googletest', 'undefined-behavior']",353,True,8,3
Differentiating between an imported package and one run at the CLI when using Entrypoints in Python,"<p>I have a python package that most commonly used as a CLI tool, but I sometimes run it as a library for my own purposes. (e.g. turning it into a web-app or for unit testing)</p>
<p>For example, I'd like to <code>sys.exit(1)</code> on error to give the end-user a nice error message on exception when used as a CLI command, but <code>raise</code> an Exception when it's used as an imported library.</p>
<p>I am using an <code>entry_points</code> in my <code>setup.py</code>:</p>
<pre><code>entry_points={
        'console_scripts': [
            'jello=jello.cli:main'
        ]
    }
</code></pre>
<p>This works great, but I can't easily differentiate when the package is run at the CLI or it was imported because <code>__name__</code> is always <code>jello.cli</code>. This is because the Entrypoint is basically importing the package as normal.</p>
<p>I tried creating a <code>__main__.py</code> file and pointing my Entrypoint there, but that did not seem to make a difference.</p>
<p>I'm considering checking <code>sys.argv[0]</code> to see if my program name exists there, but that seems to be a brittle hack. (in case the user aliases the command or something) Any other ideas or am I just doing it wrong? For now I have been passing an <code>as_lib</code> argument to my functions so they will behave differently based on whether they are loaded as a module or run from the CLI, but I'd like to get away from that.</p>
",https://stackoverflow.com/questions/67842411/differentiating-between-an-imported-package-and-one-run-at-the-cli-when-using-en,"['python', 'entry-point']",64,True,1,2
Selenium PageFactory lazy evaluation StaleElementException,"<p>I'm doing unit testing on a system using Selenium with a Page Object Model.</p>
<p>Usually I'm able to figure out a solution to such a problem in relatively short order, but this one is being rather tenacious, so I thought I should just get clarification on the root of the problem rather than write another workaround.</p>
<p>There is some PageObject class that has an <code>IWebElement</code> property with the necessary <code>FindsBy</code> attribute for locating a element on the page, and a method that uses said property:</p>
<pre><code>public class Foo : BasePage
{
    
    ...
    
    [FindsBy(How = How.XPath, Using = &quot;//a[@title='Edit']&quot;)]
    protected IWebElement LinkEdit { get; set; }
    
    ...
    
    public Bar ClickEdit()
    {
        WaitUntilInteractable(LinkEdit);
        LinkEdit.Click();
        
        return new Bar(driver);
    }
    
    ...
    
}
</code></pre>
<p><em>Note that this is the only reference to <code>LinkEdit</code></em></p>
<p>For clarity, <code>WaitUntilInteractable</code> is defined in <code>BasePage</code> as:</p>
<pre><code>    protected void WaitUntilInteractable(IWebElement webElement)
    {
        var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
        _ = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(webElement));
    }
</code></pre>
<p>My understanding of how the <code>PageFactory</code> works with <code>Selenium</code> is that whenever you reference a <code>IWebElement</code> property of a class, the <code>IWebDriver</code> will then find the element within the page.</p>
<p>This much is said on this page: <a href=""https://github.com/seleniumhq/selenium/wiki/pagefactory"" rel=""nofollow noreferrer"">https://github.com/seleniumhq/selenium/wiki/pagefactory</a></p>
<blockquote>
<p>... every time we call a method on the WebElement, the driver will go and find it on the current page again.</p>
</blockquote>
<p>Given that knowledge, I don't quite understand how I can run into <code>StaleElementReferenceException</code> when simply referencing one of these properties. Surely either the element cannot be found, in which case a <code>NoSuchElementException</code> will be thrown, or it can be found, in which case it is present on the document, and not &quot;stale&quot;.</p>
<p>Perhaps I've misunderstood staleness.</p>
",https://stackoverflow.com/questions/68854036/selenium-pagefactory-lazy-evaluation-staleelementexception,"['c#', 'selenium', 'pageobjects', 'page-factory', 'staleelementreferenceexception']",119,False,1,1
std::string::operator=(char): Which compiler is right? And how to test for this kind of bug?,"<p>I tripped upon this strange bug in my code.  The bug itself is quite common... Since I had a test case open, I decided to test for it...  I found it was quite hard to test for this condition.</p>
<p>Here is an overview of the code:</p>
<pre><code>#include &lt;string&gt;
#include &lt;cstring&gt;
#include &lt;iostream&gt;

// -------------------------------------------------------------------------
// simulating what is the C driver FYI, it's the alsa sound driver, 
// but that's not much relevant

char* some_text = nullptr;

void init_text()
{
    some_text = strdup(&quot;some text&quot;);
}

int get_card_name(int, char** x)
{
    *x = some_text;
    return 0;
}

//  end 'driver' code  
// -------------------------------------------------------------------------

int main()
{
    int i = 0;
    char* name;
    std::string s;

     // my original bug...  &amp;&quot;à! happens.
     s = get_card_name(i, &amp;name);

     // Should have read:
     // if (!get_card_name(i, &amp;name))
     //    s = name;

    // simulating EXPECT_FALSE(s.empty());
    std::cout &lt;&lt; &quot;s.empty()      : &quot; &lt;&lt; s.empty() &lt;&lt; '\n';

    // simulating EXPECT_NE(s.length(), 0);
    std::cout &lt;&lt; &quot;s.length()     : &quot; &lt;&lt; s.length() &lt;&lt; '\n';

    // simulating EXPECT_NE(s, &quot;&quot;);
    std::cout &lt;&lt; &quot;(s == \&quot;\&quot;)      : &quot; &lt;&lt; (s == &quot;&quot;) &lt;&lt; '\n';

    // a trace to check contents:
    std::cout &lt;&lt; &quot;s              : \&quot;&quot; &lt;&lt; s &lt;&lt; &quot;\&quot;\n&quot;;

    if (!s.empty())
        std::cout &lt;&lt; &quot;int(s.front()) : &quot; &lt;&lt; (int)s.front() &lt;&lt; '\n';

    free(some_text);
    return s.length();
}
</code></pre>
<p>It looks straightforward, but here is the output with gcc 10.2 -Wall, but no warnings :( :</p>
<pre><code>s.empty()      : 0
s.length()     : 1
(s == &quot;&quot;)      : 0
s              : &quot;&quot;
int(s.front()) : 0
</code></pre>
<p>With clang 11.0.1 -Wall, but no warnings :( :</p>
<pre><code>s.empty()      : 0
s.length()     : 1
(s == &quot;&quot;)      : 0
s              : &quot;&quot;
int(s.front()) : 0
</code></pre>
<p>And with msvc 19.28 -Wall, and over 100 lines of warnings :( :</p>
<pre><code>s.empty()      : 1
s.length()     : 0
(s == &quot;&quot;)      : 1
s              : &quot;&quot;
</code></pre>
<p>This rather trivial, bug of mine turns out to be quite difficult to test for, at least for gcc and clang.  Three questions come to mind...</p>
<ul>
<li>which compiler is right?</li>
<li>Detecton is not so obvious.  How can we protect against this kind of 'easy' bug?</li>
<li>Are the gcc and clang stl implementations to blame? Should I report a bug?</li>
</ul>
<p>You will find the code here as well: <a href=""https://godbolt.org/z/9WhaGzTz8"" rel=""nofollow noreferrer"">https://godbolt.org/z/9WhaGzTz8</a></p>
<p>[EDIT]  As food for thought...</p>
<p>Taking the string s from the code above... Since my main concern is corect unit testing for detecting bugs in production code.</p>
<p>gcc and clang report</p>
<pre><code> (s == s.c_str()) is false
</code></pre>
<p>This does catch the bug, but the inequality looks strange... Does this mean that something is broken with respect to the standard?</p>
",https://stackoverflow.com/questions/66819431/stdstringoperator-char-which-compiler-is-right-and-how-to-test-for-this,"['c++', 'unit-testing', 'std']",109,True,1,1
Get the name of the unit test class in the ios host application,"<p>I am using the standard <strong>XCTestCase</strong> class to implement and trigger the unit tests together with the host ios application.
Is it possible to pass a piece of information from the unit test (XCTestCase subclass) to the host application, and read this information in host's main.m?</p>
<p><code>XCUIApplication().launchArguments</code> does not work for me. Also putting a value in the build settings is not a solution.</p>
<p>I need to change the behaviour of the host application according to the <strong>XCTestCase</strong>'s subclasses.</p>
<p>The class under the test (subclass of XCTestCase) is affected by the host's App Delegate class. I would like to instantiate a special AppDelegateFake class (in main.m) that will not affect the class under test.</p>
<p>It is possible to detect if the host app is running with a unit test set and instantiate a special fake test app delegate class:
<a href=""https://marcosantadev.com/fake-appdelegate-unit-testing-swift/"" rel=""nofollow noreferrer"">https://marcosantadev.com/fake-appdelegate-unit-testing-swift/</a></p>
<p><strong>BUT</strong> in that way I have to use this fake app delegate for <strong>ALL</strong> tests (XCTestCase's).</p>
<p>Something like this if that would be nice to have in the host app:</p>
<pre><code>let isRunningTests = NSClassFromString(&quot;XCTestCaseSubclassXY&quot;) != nil
</code></pre>
<p>but unfortunately, this is not possible. I also tried to get somehow the instance of XCTestConfiguration, which contains the running XCTestCase name, but again it is not possible.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/67373320/get-the-name-of-the-unit-test-class-in-the-ios-host-application,"['unit-testing', 'xctestcase']",262,True,0,2
Require 100% code coverage for ASP.NET Core web application controllers in Azure DevOps build pipeline,"<p>In our project we have a requirement that all controller methods should have at least one test.</p>
<p>Our build fails if we have a test that fails but right now we are using this guide to check code coverage manually:</p>
<p><a href=""https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports</a></p>
<p>Basically this means running two commands:</p>
<pre><code>dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura /p:CoverletOutput=&quot;Path\To\TestProject\TestResults\coverage.cobertura.xml&quot;

reportgenerator &quot;-reports:Path\To\TestProject\TestResults\coverage.cobertura.xml&quot; &quot;-targetdir:coveragereport&quot; -reporttypes:Html
</code></pre>
<p>Note: If you run <code>dotnet test --collect:&quot;XPlat Code Coverage&quot;</code> you can get a <code>coverage.cobertura.xml</code> file but if you use msbuild with <code>/p:CollectCoverage=true</code> you will have to add the package <code>dotnet add package coverlet.msbuild</code> to the test project once.</p>
<p><a href=""https://github.com/coverlet-coverage/coverlet/issues/201"" rel=""nofollow noreferrer"">https://github.com/coverlet-coverage/coverlet/issues/201</a></p>
<p>We then get a report like this:</p>
<p><a href=""https://i.stack.imgur.com/9bNsw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/9bNsw.png"" alt=""enter image description here"" /></a></p>
<p>Our line coverage in this case is not great but our controllers have 100% line coverage. It would be OK to check that a specific namespace like <code>Project.Web.Controllers</code> has 100% line coverage.</p>
<p>We can not use the normal code coverage results to fail a build since we only want to fail a build if controllers are not tested.</p>
<p><a href=""https://learn.microsoft.com/en-us/azure/devops/pipelines/test/review-code-coverage-results?view=azure-devops"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/azure/devops/pipelines/test/review-code-coverage-results?view=azure-devops</a></p>
<p><a href=""https://gunnarpeipman.com/azure-devops-check-code-coverage/"" rel=""nofollow noreferrer"">https://gunnarpeipman.com/azure-devops-check-code-coverage/</a></p>
<p><a href=""https://stackoverflow.com/a/60894835/3850405"">https://stackoverflow.com/a/60894835/3850405</a></p>
<p>Is there any way to do this nicely or do we need to read the <code>coverage.cobertura.xml</code> file and look at <code>&lt;class name=&quot;Project.Web.Controllers</code> for example?</p>
",https://stackoverflow.com/questions/66109985/require-100-code-coverage-for-asp-net-core-web-application-controllers-in-azure,"['c#', 'azure-devops', 'code-coverage', 'xunit', 'coverlet']",1100,True,0,1
"How do I run unittests in an Azure pipeline, when I use x64 and .NET5?","<p>I have a small demo project, with unit tests.
using .net5, and 64 bit/any cpu.</p>
<p>I am having trouble with them running in my azure pipeline.</p>
<p>I have made a runsetting file, but cannot specify the 5.0 net framework</p>
<p>I've made a failing unit test, but it doenst get run.</p>
<p>when I 'debug' it I get this in my azure log..</p>
<p>2021-03-04T16:29:27.9652466Z /TestAdapterPath:&quot;C:\DevOps\Agent 2_work\3\s&quot;
2021-03-04T16:29:27.9652833Z /diag:&quot;C:\DevOps\Agent 2_work_temp\c9f3dc90-7d06-11eb-9f3e-ab7c238ad233.txt&quot;
2021-03-04T16:29:28.0475388Z <strong>Settings file provided does not conform to required format. An error occurred while loading the settings.  Error: Invalid setting 'RunConfiguration'. Invalid value 'AnyCPU' specified for 'TargetPlatform'..</strong>
2021-03-04T16:29:28.2479067Z ##[debug]Exit code 1 received from tool 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Extensions\TestPlatform\vstest.console.exe'
2021-03-04T16:29:28.2484150Z ##[debug]STDIO streams have closed for tool 'C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Extensions\TestPlatform\vstest.console.exe'
2021-03-04T16:29:28.2516774Z ##[warning]Vstest failed with error. Check logs for failures. There might be failed tests.</p>
<p>my .runsettings are:</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
 &lt;!-- File name extension must be .runsettings --&gt;
&lt;RunSettings&gt;
&lt;!-- Configurations that affect the Test Framework --&gt;
&lt;RunConfiguration&gt;
  &lt;!-- Path relative to directory that contains .runsettings file--&gt;
  &lt;ResultsDirectory&gt;.\bin\TestResults&lt;/ResultsDirectory&gt;
&lt;!-- x86 or x64 --&gt;
    &lt;!-- You can also change it from the Test menu; 
         choose &quot;Processor Architecture for AnyCPU Projects&quot; --&gt;
    &lt;TargetPlatform&gt;AnyCPU&lt;/TargetPlatform&gt;
    &lt;!-- Framework35 | [Framework40] | Framework45 ... todo Framework50 er ikke suporteret--&gt;
    &lt;TargetFrameworkVersion&gt;Framework45&lt;/TargetFrameworkVersion&gt;
    &lt;!-- true or false --&gt;
    &lt;!-- Value that specifies the exit code when no tests are discovered --&gt;
    &lt;TreatNoTestsAsError&gt;false&lt;/TreatNoTestsAsError&gt;
     &lt;/RunConfiguration&gt; 
&lt;/RunSettings&gt;
</code></pre>
<p>Does ms Azure not support .net50 for unit testing, with vs tests?</p>
<p>Thanks for you thoughts..
Kenneth</p>
",https://stackoverflow.com/questions/66479339/how-do-i-run-unittests-in-an-azure-pipeline-when-i-use-x64-and-net5,"['azure-devops', '64-bit', 'mstest', '.net-5', 'vs-unit-testing-framework']",669,False,0,1
"Java/JUnit testing: test compiles, but get &#39;cannot find symbol&#39; error on test Class at runtime","<p>I'm new to formal unit testing, so I'm trying to learn JUnit to get some practice. I have an existing project that runs, but am just now writing a unit test (for practice sake).</p>
<p>I'm working in Netbeans 11.3, which has Junit 4 and 5 out of the box. Netbeans allows me to right click my source packages folder &gt; New &gt; Test for existing class. Completing the 'wizard' yields a skeleton of the test cases that are needed for my desired class &quot;DBUtils&quot;(from the source package).</p>
<p>Netbeans places this new DBUtilsTest.java in a test packages folder of its own, but is still in the package 'scheduler', which is where the original source class DBUtils is as well.</p>
<p><a href=""https://i.stack.imgur.com/n7Xxb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/n7Xxb.png"" alt=""enter image description here"" /></a></p>
<p>Here is the test code:</p>
<pre><code>    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package scheduler;

import java.sql.PreparedStatement;
import java.time.LocalDateTime;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Dave
 */
public class DBUtilsTest {
    
    public DBUtilsTest() {
    }
    
    @BeforeClass
    public static void setUpClass() {
    }
    
    @AfterClass
    public static void tearDownClass() {
    }
    
    @Before
    public void setUp() {
    }
    
    @After
    public void tearDown() {
    }

    /**
     * Test of closeDBConnection method, of class DBUtils.
     */
    @Test
    public void testCloseDBConnection() {
        System.out.println(&quot;closeDBConnection&quot;);
        DBUtils.closeDBConnection();
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }

    /**
     * Test of openDB method, of class DBUtils.
     */
    @Test
    public void testOpenDB() {
        System.out.println(&quot;openDB&quot;);
        String connString = &quot;&quot;;
        String user = &quot;&quot;;
        String password = &quot;&quot;;
        DBUtils.openDB(connString, user, password);
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }

    /**
     * Test of addAutoIncrement method, of class DBUtils.
     */
    @Test
    public void testAddAutoIncrement() {
        System.out.println(&quot;addAutoIncrement&quot;);
        DBUtils.addAutoIncrement();
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }

    /**
     * Test of insertCountry method, of class DBUtils.
     */
    @Test
    public void testInsertCountry() {
        System.out.println(&quot;insertCountry&quot;);
        String country = &quot;&quot;;
        int expResult = 0;
        int result = DBUtils.insertCountry(country);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }

    /**
     * Test of insertCity method, of class DBUtils.
     */
    @Test
    public void testInsertCity() {
        System.out.println(&quot;insertCity&quot;);
        String city = &quot;&quot;;
        int countryId = 0;
        int expResult = 0;
        int result = DBUtils.insertCity(city, countryId);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }

    /**
     * Test of insertAddress method, of class DBUtils.
     */
    @Test
    public void testInsertAddress() {
        System.out.println(&quot;insertAddress&quot;);
        String address = &quot;&quot;;
        String address2 = &quot;&quot;;
        int cityId = 0;
        String postalCode = &quot;&quot;;
        String phone = &quot;&quot;;
        int expResult = 0;
        int result = DBUtils.insertAddress(address, address2, cityId, postalCode, phone);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }

    /**
     * Test of insertCustomer method, of class DBUtils.
     */
    @Test
    public void testInsertCustomer() {
        System.out.println(&quot;insertCustomer&quot;);
        String customerName = &quot;&quot;;
        int addressId = 0;
        boolean active = false;
        int expResult = 0;
        int result = DBUtils.insertCustomer(customerName, addressId, active);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }

    /**
     * Test of insertAppointment method, of class DBUtils.
     */
    @Test
    public void testInsertAppointment() {
        System.out.println(&quot;insertAppointment&quot;);
        int customerId = 0;
        int userId = 0;
        String title = &quot;&quot;;
        String description = &quot;&quot;;
        String location = &quot;&quot;;
        String contact = &quot;&quot;;
        String type = &quot;&quot;;
        String url = &quot;&quot;;
        LocalDateTime start = null;
        LocalDateTime end = null;
        int expResult = 0;
        int result = DBUtils.insertAppointment(customerId, userId, title, description, location, contact, type, url, start, end);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }

    /**
     * Test of insertUser method, of class DBUtils.
     */
    @Test
    public void testInsertUser() {
        System.out.println(&quot;insertUser&quot;);
        String userName = &quot;&quot;;
        String password = &quot;&quot;;
        Boolean active = null;
        int expResult = 0;
        int result = DBUtils.insertUser(userName, password, active);
        assertEquals(expResult, result);
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }

    /**
     * Test of deleteItem method, of class DBUtils.
     */
    @Test
    public void testDeleteItem() {
        System.out.println(&quot;deleteItem&quot;);
        String table = &quot;&quot;;
        int id = 0;
        DBUtils.deleteItem(table, id);
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }

    /**
     * Test of updateItem method, of class DBUtils.
     */
    @Test
    public void testUpdateItem() {
        System.out.println(&quot;updateItem&quot;);
        PreparedStatement stmt = null;
        int nextIndex = 0;
        DBUtils.updateItem(stmt, nextIndex);
        // TODO review the generated test code and remove the default call to fail.
        fail(&quot;The test case is a prototype.&quot;);
    }
    
}
</code></pre>
<p>The details of the test aren't important yet, and the DBUtilsTest.java file compiles. However, when I go to run the test, I get a bunch of these:</p>
<pre><code>C:\Users\Dave\Documents\NetBeansProjects\Scheduler\test\scheduler\DBUtilsTest.java:48: error: cannot find symbol
        DBUtils.closeDBConnection();
  symbol:   variable DBUtils
  location: class DBUtilsTest
</code></pre>
<p>I would think since DBUtilsTest has access to the 'scheduler' package, it should find DBUtils just fine. I'm also wondering why when I explicitly compile the DBUtilsTest.java file, these compiler-ish errors don't appear... only when I try to run it.</p>
<p>Any ideas on this? I've searched a little online, but haven't been able to find this answered, only asked.</p>
",https://stackoverflow.com/questions/67731520/java-junit-testing-test-compiles-but-get-cannot-find-symbol-error-on-test-cl,"['java', 'junit']",448,False,0,0
call javascript_include_tag within a rack middleware,"<p>I am building a rack middleware (to work within rails) that wants to use javascript_include_tag from within the rack middle ware.</p>
<p>How can I call javascript_include_tag outside of the controller/view context.</p>
<p>I guess even this title is a bit to detailed.  All I want to do is get the correct link to some asset from within a rack middleware.</p>
<p>To put it at the highest level I can:  Need to have rack middleware get the link to the sprockets generated asset for a given file.</p>
<p>Why?  Well I guess that is my business, but its for a gem I maintain that creates a test page that you can then use rspec/capybara to interact with assets on that page.   This allows unit testing of the assets without relying on the specific context on some layout or view.</p>
<p>Currently I provide this capability by having the gem dynamically create a controller, and then hacking around in the rails route.  All works fine, but it just seems like its calling out for a simple rack middle ware that will handle the test url.</p>
<p>Also this means I have separate code to deal with non-rails environments (i.e. Sinatra) .  It would be nice if the only dependency were sprockets and rack.</p>
",https://stackoverflow.com/questions/65919939/call-javascript-include-tag-within-a-rack-middleware,"['ruby-on-rails', 'rack']",41,False,0,0
Factorial Unit Test function returning wrong test runs,"<p>I am trying to create a unittest using the input value. I know that math.factorial function will give the correct number so I would like to pass the same value to my  factorial function that I created and the built in math.factorial function to compare the results and see if my function is working fine.</p>
<p>What I don't understand is that somehow the code below says RAN OK is 0.000s even when I enter a negative value. I believe in that case it should not work.[funny thing some times it say ran ok with negative and sometimes not]</p>
<p>Additionally, If I use the <strong>second code</strong> below it still says pass on a test when I enter a negative number. Even though I have removed the first IF statement</p>
<p>and the third thing that is not clear to me is about how does the class TestCalc accepts the input variable i.e &quot;n&quot;. I thought that I would need to create another parameter like (self , number). Somehow it is accepting n in the def_test_factorial(self)</p>
<p>I am new to this unit testing and classes and objects. I was hoping if someone can clear these doubts.</p>
<pre><code>from functools import reduce
import doctest
import time
import math
import numpy as np
import unittest

def calculate_factorial(number):
    if number &lt; 0:
        raise ValueError('number should be greater than 0')
    elif type(number) != int:
        raise  TypeError('number should be an integer type')
    else:
        data = []
        for i in range(number):
            data.append(number - i)
            # print(data)
        results = reduce((lambda x, y: x * y), data, 1)
        return results




run = True
while run:
    n = int(input('Enter an integer value: '))
    if n != -9999:
        unittest.main(argv=[''], verbosity=2, exit=False)  
    else:
        run = False


class TestCalc(unittest.TestCase):
    def test_factorial(self):
        result = calculate_factorial(n)
        self.assertEqual(result, math.factorial(n))

    def test_n(self):
        print(n)
</code></pre>
<p>second code:</p>
<pre><code>def calculate_factorial_(number):
    if type(number) != int:
        raise  TypeError('number should be an integer type')
    else:
        data = []
        for i in range(number):
            data.append(number - i)
            # print(data)
        results = reduce((lambda x, y: x * y), data, 1)
        return results
</code></pre>
<p>I have removed the negative number condition and it still shows the results</p>
<pre><code>run = True
while run:
    n = int(input('Enter an integer value: '))
    if n != -9999:
        unittest.main(argv=[''], verbosity=2, exit=False)
    else:
        run = False


class TestCalc(unittest.TestCase):
    def test_factorial(self):
        result = calculate_factorial_(n)
        self.assertEqual(result,math.factorial(n))
    
    def test_n(self):
        print(n)
</code></pre>
",https://stackoverflow.com/questions/68768188/factorial-unit-test-function-returning-wrong-test-runs,"['python', 'unit-testing', 'input', 'factorial']",629,False,0,1
How To Run A Successful Solidity Smart Contract Test Script?,"<p>I have been following this <a href=""https://www.youtube.com/watch?v=xlHldvMNK8Q"" rel=""nofollow noreferrer"">tutorial</a> by Gregory from <a href=""https://www.dappuniversity.com/"" rel=""nofollow noreferrer"">Dapp University</a> on how to create your own ERC20 token along with a crowd-sale smart contract. I have been successful so far, but I am stuck where I need to make the buytokens() function work so a transfer of tokens from the address of the crowd-sale contract to the buyer's can take place. The test I am about to show makes use of the async/await pattern, different from what is on the video tutorial. Below you can find the code of</p>
<ul>
<li>my ERC20 token contract</li>
<li>my crowd-sale contract and its test script (specifically the part that is failing)</li>
<li>the deployment script</li>
<li>and finally the error I am getting when I run my test</li>
</ul>
<p>Thanks for your help.</p>
<p><strong>Development Environment</strong></p>
<pre><code>Truffle v5.4.18 (core: 5.4.18)
Solidity - 0.8.9 (solc-js)
Node v16.1.0
Web3.js v1.5.3
</code></pre>
<p><strong>Crowd-sale Contract</strong></p>
<pre><code>// SPDX-License-Identifier: MIT
pragma solidity &gt;=0.7.0;

import &quot;./NzouaToken.sol&quot;;

contract NzouaTokenSale {

    address admin;
    NzouaToken public tokenContract;
    uint256 public tokenPrice;
    uint256 public tokensSold;

    event Sell(address _buyer, uint256 _amount);

    constructor(NzouaToken _tokenContract, uint256 _tokenPrice) {

        admin = msg.sender;
        tokenContract = _tokenContract;
        tokenPrice = _tokenPrice;
    }

    function multiply(uint x, uint y) internal pure returns(uint z){
        require(y == 0 || (z = x * y) / y == x);
    }

    function buyTokens(uint256 _numberOfTokens) public payable{
        require(msg.value == multiply(_numberOfTokens, tokenPrice));
        require(tokenContract.balanceOf(address(this)) &gt;= _numberOfTokens);
        require(tokenContract.transfer(msg.sender, _numberOfTokens));

        tokensSold += _numberOfTokens;

        emit Sell(msg.sender, _numberOfTokens);

    }

}
</code></pre>
<p><strong>ERC20 Token Contract</strong></p>
<pre><code>// SPDX-License-Identifier: MIT
pragma solidity &gt;=0.7.0;

contract NzouaToken {

    string public name = &quot;Nzouat Token&quot;;
    string public symbol = &quot;NZT&quot;;
    uint256 public totalSupply;

    event Transfer(
        address indexed _from,
        address indexed _to,
        uint256 _value
    );

    event Approval(
      address indexed _owner, 
      address indexed _spender,
      uint256 _value
    );

    mapping(address =&gt; uint256) public balanceOf;

    mapping(address =&gt; mapping(address =&gt; uint256)) public allowance;


    constructor(uint256 _initialSupply) {
        balanceOf[msg.sender] = _initialSupply;
        totalSupply = _initialSupply;
    }

    function transfer(address _to, uint256 _value) public returns(bool success){
        require(balanceOf[msg.sender] &gt;= _value, 'The account has low funds');

        balanceOf[msg.sender] -= _value;
        balanceOf[_to] += _value;

        emit Transfer(msg.sender, _to, _value);

        return true;
    }

    function approve(address _spender, uint256 _value) public returns(bool success) {

        allowance[msg.sender][_spender] = _value;

        emit Approval(msg.sender, _spender, _value);
        
        return true;
    }

    function transferFrom(address _from, address _to, uint256 _value) public returns (bool success){

        require(_value &lt;= balanceOf[_from]);
        require(_value &lt;= allowance[_from][msg.sender]);

        balanceOf[_from] -= _value;
        balanceOf[_to] += _value;

        allowance[_from][msg.sender] -= _value;

        emit Transfer(_from, _to, _value);

        return true;
    }
}
</code></pre>
<p><strong>Deployment Script</strong></p>
<pre><code>const NzouaToken = artifacts.require(&quot;NzouaToken&quot;);
const NzouaTokenSale = artifacts.require(&quot;NzouaTokenSale&quot;);

module.exports = async function (deployer, network, accounts) {

    await deployer.deploy(NzouaToken, 1000000); // 1000000 NZT tokens

    await deployer.deploy(NzouaTokenSale, NzouaToken.address, 1000000000000000);
};
</code></pre>
<p><strong>Unit Testing With Mocha (Part of the crowd-sale test that is failing)</strong></p>
<pre><code>var NzouaToken = artifacts.require('./NzouaToken');
var NzouaTokenSale = artifacts.require('./NzouaTokenSale');

contract('NzouaTokenSale', async (accounts) =&gt; {
    let tokenSale;
    let token;
    let tokenPrice = 1000000000000000; // in wei
    const adminAccount = accounts[0];
    const buyerAccount = accounts[1];

    describe('Facilitates Token Buying', async () =&gt; {
        it('Required a successful Transfer of Tokens', async () =&gt; {
            token = await NzouaToken.deployed();
            tokenSale = await NzouaTokenSale.deployed();
            let tokenSaleBalance;
            let buyerBalance;

            const numberOfTokens = 10;


            const tokensAvailable = 750000;

            // try {
            let receipt = await token.transfer.call(tokenSale.address, tokensAvailable, {
                from: adminAccount
            })

            tokenSaleBalance = await token.balanceOf(tokenSale.address);
            assert.equal(tokenSaleBalance.toNumber(), tokensAvailable, 'Contract received funds.')

            await tokenSale.buyTokens(numberOfTokens, {
                from: buyerAccount,
                value: numberOfTokens * tokenPrice
            });

            // Grab the new balance of the buyerAccount
            buyerBalance = await token.balanceOf(buyerAccount);
            buyerBalance = buyerBalance.toNumber()
            assert.equal(tokenSaleBalance, numberOfTokens, 'Buyer Balance updated');

            // Grab the new balance of the Token Sale Contract
            tokenSaleBalance = await token.balanceOf(tokenSale.address);
            tokenSaleBalance = tokenSaleBalance.toNumber()
            assert.equal(tokenSaleBalance, tokensAvailable - numberOfTokens, 'Token Sale Balance updated');

            // } catch (error) {
            //     // console.log(error.message)
            //     assert(error.message.indexOf('revert') &gt;= 0, 'Something went wrong while making the transfer');
            // }

        });
    });

});
</code></pre>
<p>If I uncomment the <strong>try{}catch{}</strong> section, the test will pass but it is not the behavior I am expecting.</p>
<p>When I run my test using truffle <code>truffle test</code> inside the truffle console, All my other tests pass but one, and I get this <strong>revert</strong> error</p>
<p><a href=""https://i.stack.imgur.com/ncbUM.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ncbUM.png"" alt=""Truffle console Error Message"" /></a></p>
<p>What am I doing wrong here?</p>
",https://stackoverflow.com/questions/69974761/how-to-run-a-successful-solidity-smart-contract-test-script,"['javascript', 'unit-testing', 'solidity', 'smartcontracts', 'erc20']",198,False,0,1
Serializing an object to a file via System.Text.Json.Serialization appears to break ReaderWriterLockSlim,"<p>I have a requirement for a simple List&lt;&gt; to be used in an async environment and be concurrent. The list does only has a hand full of methods and is not a full implementation of IList. I have used the ReaderWriterLockSlim class to enable a locking paradigm and it was working well.</p>
<p>Recently whilst unit testing I received a locking error: System.Threading.LockRecursionException: 'A read lock may not be acquired with the write lock held in this mode.' and the property IsWriteLockHeld was true at the point of the exception.  This was not expected at all and the code <em>appeared</em> to be fine.</p>
<p>So, I whipped up a small console test program and discovered that serializing my list to a file using System.Text.Json.Serialization namespace was causing an issue.  If I commented the call to serialize the list to file everything works as expected.</p>
<p>Stepping through the code the program appears to deadlock on the next read/write lock after Save() and does not return even though the properties IsReadLockHeld and IsWriteLockHeld are false.</p>
<p>No exceptions are thrown in the example code.</p>
<p>I would appreciate any comments or suggestions.  I'm at a loss.  Is this a defect in the semaphore  or serializer or have I royally messed up my code.</p>
<p>Sample code with comments follows.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;

namespace example {

    public static class Serialize {

        public static async Task ToFileAsync&lt;T&gt;(string path, object value) {
            var options = new JsonSerializerOptions(JsonSerializerDefaults.General) {
                WriteIndented = true,
                Converters = { new JsonStringEnumConverter() }
            };

            using (FileStream fs = File.Open(path, FileMode.Create)) {
                await JsonSerializer.SerializeAsync&lt;T&gt;(fs, (T)value, options);
            }
        }

        public static async Task&lt;T&gt; FromFileAsync&lt;T&gt;(string path) where T : new() {
            if (File.Exists(path)) {
                var options = new JsonSerializerOptions(JsonSerializerDefaults.General) {
                    ReadCommentHandling = JsonCommentHandling.Skip,
                    Converters = { new JsonStringEnumConverter() }
                };

                using (FileStream fs = File.Open(path, FileMode.Open)) {
                    return await JsonSerializer.DeserializeAsync&lt;T&gt;(fs, options);
                }
            }

            return new T();
        }
    }

    public class ListCollection&lt;T&gt; {

        private List&lt;T&gt; list;
        private readonly ReaderWriterLockSlim readerWriterLockSlim;
        private bool disposed;

        public ListCollection() {
            this.readerWriterLockSlim = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);
            this.list = new List&lt;T&gt;();
        }

        public bool Contains(T value) {
            bool result = false;

            try {
                Console.WriteLine($&quot;Contains, Before EnterReadLock&quot;);
                Console.WriteLine($&quot;Contains, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Contains, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);
                
                this.readerWriterLockSlim.EnterReadLock();

                // program appears to have hung (deadlock ?) up at the point of EnterReadLock()
                // even though both IsReadLockHeld and IsWriteLockHeld are false
                // Commenting the await Serialize.ToFileAsync(...) in Save() allows this to run as expected

                // using a TryEnterReadLock fails even though both IsReadLockHeld
                // and IsWriteLockHeld are false;
                // bool locked = this.readerWriterLockSlim.TryEnterReadLock(500);

                Console.WriteLine($&quot;Contains, After EnterReadLock&quot;);
                Console.WriteLine($&quot;Contains, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Contains, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);

                result = this.list.Contains(value);
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
            finally {
                Console.WriteLine($&quot;Contains, Finally&quot;);
                Console.WriteLine($&quot;Contains, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Contains, IsWriteLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);

                if (this.readerWriterLockSlim.IsReadLockHeld) {
                    this.readerWriterLockSlim.ExitReadLock();
                }
            }

            return result;
        }

        public bool Add(T value) {
            bool result = false;

            try {
                Console.WriteLine($&quot;Add, Before EnterWriteLock&quot;);
                Console.WriteLine($&quot;Add, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Add, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);

                this.readerWriterLockSlim.EnterWriteLock();

                Console.WriteLine($&quot;Add, After EnterWriteLock&quot;);
                Console.WriteLine($&quot;Add, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Add, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);

                if (value != null) {
                    if (!this.list.Contains(value)) {
                        this.list.Add(value);
                        result = true;
                    }
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
            finally {
                Console.WriteLine($&quot;Add, Finally&quot;);
                Console.WriteLine($&quot;Add, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Add, IsWriteLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);

                if (this.readerWriterLockSlim.IsWriteLockHeld) {
                    this.readerWriterLockSlim.ExitWriteLock();
                }
            }

            return result;
        }

        public bool Remove(T value) {
            bool result = false;

            try {
                Console.WriteLine($&quot;Remove, Before EnterWriteLock&quot;);
                Console.WriteLine($&quot;Remove, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Remove, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);

                this.readerWriterLockSlim.EnterWriteLock();

                Console.WriteLine($&quot;Remove, After EnterWriteLock&quot;);
                Console.WriteLine($&quot;Remove, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Remove, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);

                if (value != null) {
                    if (this.list.Contains(value)) {
                        this.list.Remove(value);
                        result = true;
                    }
                }
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
            finally {
                Console.WriteLine($&quot;Add, Finally&quot;);
                Console.WriteLine($&quot;Add, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Add, IsWriteLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);

                if (this.readerWriterLockSlim.IsWriteLockHeld) {
                    this.readerWriterLockSlim.ExitWriteLock();
                }
            }

            return result;
        }

        public async Task Save(string path) {
            try {
                Console.WriteLine($&quot;Save, Before EnterWriteLock&quot;);
                Console.WriteLine($&quot;Save, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Save, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);

                this.readerWriterLockSlim.EnterWriteLock();

                Console.WriteLine($&quot;Save, After EnterWriteLock&quot;);
                Console.WriteLine($&quot;Save, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Save, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);

                await Serialize.ToFileAsync&lt;List&lt;T&gt;&gt;(path, this.list).ConfigureAwait(false);

                Console.WriteLine($&quot;Save, After Serialization&quot;);
                Console.WriteLine($&quot;Save, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Save, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);

                // I expected the IsIsWriteLockHeld to be true however it's false!
                // Commenting the await Serialize.ToFileAsync(...) above leaves IsWriteLockHeld as true
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
            finally {
                Console.WriteLine($&quot;Save, Finally&quot;);
                Console.WriteLine($&quot;Save, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Save, IsWriteLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                
                if (this.readerWriterLockSlim.IsWriteLockHeld) {
                    this.readerWriterLockSlim.ExitWriteLock();
                }
            }

            // stop the warnings if no await's
            await Task.CompletedTask;
        }

        public async Task Load(string path) {
            try {
                Console.WriteLine($&quot;Load, Before EnterWriteLock&quot;);
                Console.WriteLine($&quot;Load, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Load, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);

                this.readerWriterLockSlim.EnterWriteLock();

                Console.WriteLine($&quot;Load, After EnterWriteLock&quot;);
                Console.WriteLine($&quot;Load, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Load, IsWriteLockHeld: {this.readerWriterLockSlim.IsWriteLockHeld}&quot;);

                this.list = await Serialize.FromFileAsync&lt;List&lt;T&gt;&gt;(path).ConfigureAwait(false);
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
            }
            finally {
                Console.WriteLine($&quot;Load, Finally&quot;);
                Console.WriteLine($&quot;Load, IsReadLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);
                Console.WriteLine($&quot;Load, IsWriteLockHeld: {this.readerWriterLockSlim.IsReadLockHeld}&quot;);

                if (this.readerWriterLockSlim.IsWriteLockHeld) {
                    this.readerWriterLockSlim.ExitWriteLock();
                }
            }
        }

        protected virtual void Dispose(bool disposing) {
            if (!this.disposed) {
                if (disposing) {
                    this.readerWriterLockSlim.Dispose();
                }
                this.disposed = true;
            }
        }

        public void Dispose() {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

    }

    public class Program {
        static async Task Main() {
            var lc = new ListCollection&lt;string&gt;();

            lc.Add(&quot;Item 1&quot;);

            await lc.Save(&quot;example.json&quot;);

            bool result = lc.Contains(&quot;Item 1&quot;);

            Console.WriteLine();
            Console.WriteLine(&quot;Finished, hit &lt;enter&gt; to quit&quot;);
            Console.WriteLine();
            Console.ReadLine();
        }

    }
}

/*
 Program output fom Save() method:

 Save, Before EnterWriteLock
 Save, IsReadLockHeld: False
 Save, IsWriteLockHeld: False
 Save, After EnterWriteLock
 Save, IsReadLockHeld: False
 Save, IsWriteLockHeld: True  &lt; expected result
 Save, After Serialization
 Save, IsReadLockHeld: False
 Save, IsWriteLockHeld: False &lt; unexpected result
 Save, Finally
 Save, IsReadLockHeld: False
 Save, IsWriteLockHeld: False
  
*/
</code></pre>
",https://stackoverflow.com/questions/69511267/serializing-an-object-to-a-file-via-system-text-json-serialization-appears-to-br,"['c#', 'list', 'asynchronous', 'concurrency', 'readerwriterlockslim']",33,False,0,0
dotnet test not loading resharper test adapter,"<p>We have an nunit3 test project that we're trying to run via command-line in dotnet core that is having problems being identified. In all our debugging we've not found an answer to fixing this.</p>
<p>Background: We build out these tests to test an API site after it's been deployed, alongside standard unit testing. So we package the test up as a DLL to run after we've built out the site, and configure it to run against the site. On our local machines, the tests can't be identified until we install Resharper on our Visual Studio.</p>
<p>After attempting a
<code>dotnet test &quot;path\to\bin\release\Test.dll&quot;</code></p>
<p>we get the error:</p>
<blockquote>
<p>No test is available in path\to\bin\release\Test.dll. Make sure that test discoverer &amp; executors are registered and platform &amp; framework version settings are appropriate and try again.</p>
</blockquote>
<blockquote>
<p>Additionally, path to test adapters can be specified using /TestAdapterPath command. Example  /TestAdapterPath:.</p>
</blockquote>
<p>According to Resharper site, the tools require the run: <code>dotnet tool install -g JetBrains.ReSharper.GlobalTools</code></p>
<p>doing so I've found the adapters at</p>
<blockquote>
<p>C:\Users\USER\.dotnet\tools\.store\jetbrains.resharper.globaltools\2020.3.2\jetbrains.resharper.globaltools\2020.3.2\tools\netcoreapp3.1\any\TestRunner\Adapters</p>
</blockquote>
<p>but when trying to load a given adapter dll using /TestAdapterPath, it says it can't find it. any idea how to get this test running?</p>
",https://stackoverflow.com/questions/65744960/dotnet-test-not-loading-resharper-test-adapter,"['.net-core', 'resharper', 'dotnet-test']",447,False,0,1
CodeIgniter 4: $this-&gt;post call failing,"<p>I am working through Lonnie Ezell's book on CodeIgniter 4, and am busy with project 4, dealing with unit testing. The code samples are here:</p>
<ul>
<li><a href=""https://github.com/lonnieezell/ci4-foundations/blob/master/project-04-part-ii/app/Controllers/PostController.php"" rel=""nofollow noreferrer"">https://github.com/lonnieezell/ci4-foundations/blob/master/project-04-part-ii/app/Controllers/PostController.php</a></li>
<li><a href=""https://github.com/lonnieezell/ci4-foundations/blob/master/project-04-part-ii/tests/PostCrudTest.php"" rel=""nofollow noreferrer"">https://github.com/lonnieezell/ci4-foundations/blob/master/project-04-part-ii/tests/PostCrudTest.php</a></li>
</ul>
<p>I have implemented my code exactly like this (copied and pasted code) and in particular the functions <code>testCanEditPost()</code> in the Test, which is the only test that is failing, and <code>save</code> in <code>PostController</code>.</p>
<p>First of all, the <code>if (! $this-&gt;validate...</code> call always fails - this is the primary issue - I have outputted the validation errors, and it keeps saying that &quot;The x field is required&quot;, even though the data is available. If I move the <code>$post = ($postID === null ? ...</code> code to the top, I can see my <code>title</code>, <code>body</code> and <code>publish_at</code>, which are retrieved from <code>new Post($this-&gt;request-&gt;getPost()</code>. I know this because further down, the $postId always remains null, for some reason (see below), but doing this does show the fields (title, body and publish_it) but postId is empty:</p>
<pre><code>$post = ($postId === null ? new Post($this-&gt;request-&gt;getPost()) : $this-&gt;posts-&gt;find($postId));
echo '&lt;pre&gt;';
print_r($postId);
print_r($post);
echo '&lt;/pre&gt;';
exit(); // I am removing this debug text after testing, so the exit() here is not why it does not complete correctly.
</code></pre>
<p>Secondly, the empty <code>$postId</code>. So - calling this:</p>
<pre><code>$response = $this-&gt;post(&quot;posts/{$post-&gt;id}&quot;, [
    'title' =&gt; 'Post A',
    'publish_at' =&gt; date('Y-m-d 00:00:00', strtotime('+1 week')),
    'body' =&gt; 'My Great Post'
]);
</code></pre>
<p>Does not pass the <code>$post-&gt;id</code> through to the <code>PostController</code> <code>save</code> function's <code>$postId</code> parameter. <code>$post-&gt;id</code> is populated, so I am not passing a null through to the <code>save</code> function. My route is also copied from the example:</p>
<pre><code>$routes-&gt;post('posts/(:num)', 'PostController::save/$1');
</code></pre>
<p>Any ideas?</p>
",https://stackoverflow.com/questions/68750197/codeigniter-4-this-post-call-failing,['codeigniter-4'],93,False,0,0
Testing through inherited class using protected members,"<p>Let us assume that you've got a class in C++, for example with an internal state machine that is hard to test. Assume that you have a proper architecture with mocks for all classes used by the class under test. The class under test has some public interface and some non-public internal implementation.</p>
<p>You want to properly unit test this class. In order to make sure that all parts of it work correctly you would like to create some example conditions that you would not allow through the public interface. However, you want to test whether, under these circumstances, the system reacts correctly or not.</p>
<p>One possibility would be to make your member variables protected, so that an inherited class, specifically created for unit testing, is able to extend the public interface to control those variables during testing. You could then, for example, set the system to a certain state, set some internal variables and make sure that e.g. the state transition is according to your requirements.</p>
<p>From a design point of view: Is it justifiable to make non-public members protected in order to be able to get them more testable? What are your opinions? Are there better alternative design decisions?</p>
",https://stackoverflow.com/questions/65664446/testing-through-inherited-class-using-protected-members,"['c++', 'unit-testing', 'tdd', 'protected']",70,False,0,1
How to correctly mock function in Jest tests when using Rollup.js,"<p>I'm writing a React library <code>MyLibrary</code> and bundling it with <a href=""https://rollupjs.org/guide/en/"" rel=""nofollow noreferrer"">Rollup.js</a> <code>2.58.3</code>. I use <a href=""https://jestjs.io/"" rel=""nofollow noreferrer""><code>jest</code></a> for unit testing.</p>
<h1>Quick summary of the issue</h1>
<p>I am unable to mock a module from my library using <code>jest</code>. This is due to the way rollup &quot;compiles&quot; my code.</p>
<p>Rollup uses its code splitting functionality to create many chunks. In one example, rollup splits <code>Alpha.js</code> into two chunks: <code>Alpha.js</code> and <code>Alpha-xxxxxx.js</code>. Some functionality from the original file is extracted to this &quot;intermediate&quot; chunk (<code>Alpha-xxxxxx.js</code>).</p>
<p>In my unit test, when mocking any method that was moved into the intermediate file <code>Alpha-xxxxxx.js</code>, <code>jest</code> seems to actually load the module from this &quot;intermediate&quot; module rather than the top level module.</p>
<p>This causes the test to fail.</p>
<p>e.g. <code>jest.mock('MyLibrary/dist/Alpha')</code> does not work since the modules are actually being loaded from <code>Alpha-xxxxxx.js</code> instead of <code>Alpha.js</code></p>
<h1>Detailed explanation with example</h1>
<p>I have a two modules <code>Alpha.js</code> and <code>Beta.js</code> in <code>MyLibrary</code>.</p>
<h2><code>MyLibrary/Alpha.js</code></h2>
<pre><code>export const Aaa = () =&gt; {
  ...
}
...
</code></pre>
<h3><code>MyLibrary/Beta.js</code></h3>
<pre><code>import { Aaa } from './Alpha';
...
export const Bbb = () =&gt; {
  ...
}
...
</code></pre>
<h2>Compiled output generated by rollup</h2>
<p>When bundled, rollup.js splits <code>Alpha.js</code> into 2 chunks <code>Alpha.js</code> and <code>Alpha-xxxxxx.js</code>. As a result of the code splitting, the compiled version of <code>Beta.js</code> now looks something like this:</p>
<h3><code>MyLibrary/dist/Beta.js</code></h3>
<pre><code>import { Aaa } from './Alpha-xxxxxx';
...
export const Bbb = () =&gt; {
  ...
}
...
</code></pre>
<p>This compiled module from <code>MyLibrary</code> is imported in <code>MyApp</code> and the app seems to import it correctly and works fine.</p>
<h3><code>MyApp/index.js</code></h3>
<pre><code>import { Bbb } from 'MyLibrary/dist/Beta'
...
</code></pre>
<h2>The problem</h2>
<p>The <code>jest</code> test below fails since it does not correctly mock the <code>Aaa</code> export.</p>
<h3><code>MyApp/index.test.js</code></h3>
<pre><code>import { Bbb } from 'MyLibrary/dist/Beta';

jest.mock('MyLibrary/dist/Alpha', () =&gt; ({
  Aaa: jest.fn(),
}));
</code></pre>
<p>However, if I mock the intermediate chunk generated by rollup, it works.</p>
<pre><code>import { stuff } from 'MyLibrary/dist/Beta';

jest.mock('MyLibrary/dist/Alpha-xxxxxx', () =&gt; ({
  Aaa: jest.fn(),
}));
</code></pre>
<p>How can I properly mock <code>Alpha</code> from my library in my jest test?</p>
",https://stackoverflow.com/questions/70177334/how-to-correctly-mock-function-in-jest-tests-when-using-rollup-js,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'rollupjs']",395,True,3,1
Testing Library functions in a flutter package with Native Functions using Dart::ffi,"<p>I am writing a Dart library to access a C shared object using Flutter.</p>
<p>So far, the example app I created is working (somewhat) as expected, but i want to include Unit testing too keep the library somewhat stable.</p>
<p>Details:</p>
<ul>
<li>Shared Objects are in APP/android/src/main/jniLibs/{abi}/liboqs.so</li>
<li>The example App in example/lib/main.dart and works as expected</li>
<li>Library is in APP/lib/liboqs_flutter.dart</li>
</ul>
<p>The library uses</p>
<pre><code>  static final ffi.DynamicLibrary _liboqs = Platform.isAndroid
      ? ffi.DynamicLibrary.open(&quot;liboqs.so&quot;)
      : ffi.DynamicLibrary.process();
</code></pre>
<p>To set up the library.</p>
<p>But when I attempt to access this library using flutter_test (e.g. to run the init function LiboqsFlutter.init() which runs a static final C native function OQS_init, I get:</p>
<pre><code>Failed to load &quot;/{HOME DIRECTOR}/liboqs_flutter/test/liboqs_flutter_test.dart&quot;: Invalid argument(s): Failed to lookup symbol (dlsym(RTLD_DEFAULT, OQS_init): symbol not found)
</code></pre>
<p>I understand that flutter test does not have access to the 'main' assets, but how can I force through that, so I can properly test my code?</p>
<p>This <a href=""https://github.com/dart-lang/ffi/issues/39"" rel=""nofollow noreferrer"">issue offers two solutions</a>:</p>
<ul>
<li>Use flutter_driver</li>
<li>Build the library using cmake with an opener function <a href=""https://github.com/dart-lang/ffi/issues/39#issuecomment-681758550"" rel=""nofollow noreferrer"">as per this example code</a>.</li>
</ul>
<p>but I do not fully understand exactly how to make these work for me. How does flutter driver help me here?  Should the #2 code be added to the test or the original library and called in the test? If I already have prebuilt shared objects in main/jniLibs folder, do I really need to rebuild the project when I test it? That seems like a lot of wasted time just to test the app.</p>
",https://stackoverflow.com/questions/66641396/testing-library-functions-in-a-flutter-package-with-native-functions-using-dart,"['flutter', 'integration-testing', 'dart-ffi']",1177,True,3,1
XCTMemoryMetric not recording memory in iOS Unit Testing bundle in Xcode 12.5 (XCTest),"<h3>Background</h3>
<p>I have implemented a <code>Swift</code> algorithm in which I want to consume low memory at runtime (Space Complexity). So, I wanted to write performance tests using <code>XCTMemoryMetric</code> as part of a &quot;Unit Testing Bundle&quot; for large input sizes. I need to track regressions and optimisations for this algorithm, so I wanted initially to track the baseline metrics and expected this to work out of the box for my iOS app. Unfortunately, even after reading the Apple documentation for <a href=""https://developer.apple.com/documentation/xctest/performance_tests?language=swift"" rel=""nofollow noreferrer"">Performance Tests</a>, I haven't found any potential fixes or information to help me resolve my particular issue.</p>
<p>I am using an iOS Base SDK for my main target (<code>UIKit</code> and <code>Storyboard</code>) and the same Base SDK for my &quot;Unit Testing Bundle&quot; in Xcode. In Xcode, I have left the default &quot;Build active architecture only&quot; setting to &quot;Yes&quot;, and the main target compiles as well, and the tests compile fine. However, when I finish running the <code>measure</code> block with an <code>XCTMemoryMetric()</code> and <code>XCTClockMetric()</code> added as the only parameters, the Memory metrics don't show up in the test report. The Clock metrics are also completely unreliable, and my test fails (almost) every time due to high standard deviations even with the same function! Anyway, this question is focused on the memory metric.</p>
<p><strong>Example of successful compilation:</strong>
<a href=""https://i.stack.imgur.com/XVUwI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/XVUwI.png"" alt=""example of successful compilation"" /></a></p>
<p><strong>Note:</strong> I have also tried other metrics like <code>XCTCPUMetric</code> for performance testing, which doesn't show results either.</p>
<p><strong>Example of missing memory metrics:</strong>
<a href=""https://i.stack.imgur.com/VFMUW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VFMUW.png"" alt=""example of missing memory metrics"" /></a></p>
<p>I don't get warning messages in the console or exceptions.</p>
<h3>What I've tried:</h3>
<ol>
<li>Moving the algorithm to a <code>Swift Package Target</code> and moving performance tests to a <code>Package Unit Testing Bundle</code> - the memory metric shows up in the test logs. Still, it is highly unreliable (sometimes showing even <strong>negative</strong> memory allocation 😂!). This solution is not ideal since I don't want to create a package just for a single algorithm.</li>
<li>Moving the algorithm to a <code>Mac-only Target</code> with correlated <code>Unit Testing Bundle</code> - works but again not appropriate for an iOS-only app.</li>
<li>Debugging using <code>metric.reportMeasurements()</code> shows a missing <code>_data</code> parameter in the metric and crashes at runtime:</li>
</ol>
<p><a href=""https://i.stack.imgur.com/Hkk3N.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Hkk3N.png"" alt=""example of runtime crash when reporting"" /></a></p>
<ol start=""4"">
<li>Running individual test cases instead of the whole suite didn't make a difference.</li>
<li>Testing even larger input array sizes didn't make a difference.</li>
</ol>
<p>Is there any clean way I can resolve my issue without changing my Base SDK? I am considering abandoning <code>XCTest</code> for performance testing since it doesn't seem to work very well, but ideally, I'd like to stick with Apple's recommended APIs.  You can also see the code seems to run completely on Stack Memory (no <code>static let</code>s or <code>var</code>s), so I don't think the confusion between Stack and Heap Memory is the root cause.</p>
<h3>Code:</h3>
<p>I've posted a <a href=""https://gist.github.com/LemonSpike/0e869a6df291190a34322a0bfbf19726"" rel=""nofollow noreferrer"">gist</a> of the algorithm I'm performance testing since the code is too many lines to include here. Even with other (less memory-intensive) code inside the <code>measure</code> block, the issue is reproducible for me.</p>
<p>The test code:</p>
<pre><code>func testPerformanceExample() {
    let metric = XCTMemoryMetric()
    measure(metrics: [metric],
            block: {
      var sums: [[[Int]]] = []
      (1...100).forEach { _ in
        sums.append(QOneSolutionOne().fourSum([1, 0, -1, 0, -2, 2, 3, -3, 0, 4,
                                               -2, 5, -4, 6, -6, 7, -8, 8, -7],
                                              target: 0))
      }
    })
  }
</code></pre>
<p>I think this may be an <code>XCTest</code> bug, but I wanted to see if I am missing something. Open to any advice, thanks.</p>
",https://stackoverflow.com/questions/67359955/xctmemorymetric-not-recording-memory-in-ios-unit-testing-bundle-in-xcode-12-5-x,"['ios', 'swift', 'xcode', 'unit-testing', 'xctest']",750,False,2,0
Unit Testing GetxController,"<p>I'm a beginner with tdd so please forgive me if it's a dumb question.</p>
<p>I'm having difficulty unit testing GetxControllers.  Does anyone know a simple way of doing this?
Whenever I do I get errors since Get is calling onStart and it doesn't like the result Mockito's giving it.  I've tried using Mockito 5.0.1's auto generated code as well as the older syntax, class MockController extends Mock implements Controller{}, as well as extends Fake.</p>
<p>The auto generated code has build errors, since Mockito is trying to use _InternalFinalCallback, but it's not being imported as it's private.  I tried just copy pasting that part of the code into my generated file (and switching off pub build watch) but first that's a short term solution with it's own issues, 2nd it still doesn't work since the onStart and onDelete functions now tell me they're not valid overrides.</p>
<p>Also, I can see the get_test package but it's documentation is basically 0, and in the examples the controller is just used directly -- there's never a mocked controller.</p>
<p>I tried setting Get.testMode = true; but again that doesn't seem to do anything.  And while I found that property in the docs, I didn't find how to use it correctly.</p>
<p>Any help would be appreciated,</p>
<p>Here's my code but the issue seems to be with the GetxControllers, so I don't think it's relevant much:</p>
<pre><code>class FakeAuthController extends Fake implements AuthController {}

@GenerateMocks([AuthController])
void main() {
  TestWidgetsFlutterBinding.ensureInitialized();
  late MockAuthController mockAuthController;
  late FakeAuthController fakeAuthController;
  late SessionController sessionController;

  setUp(() {
    Get.testMode = true;
    mockAuthController = MockAuthController();
    fakeAuthController = FakeAuthController();
    Get.put&lt;AuthController&gt;(mockAuthController);

    sessionController = SessionController();
  });

  tearDown(() {
    Get.delete&lt;AuthController&gt;();
  });

  group('getSessionInfo', () {
    test('Calls authFacade getSignedInUserId', () async {
      await sessionController.getSessionInfo();

      when(Get.find&lt;AuthController&gt;()).thenReturn(fakeAuthController);

      verify(mockAuthController.getSignedInUserId());
    });
  });
}
</code></pre>
<p>There really isn't anything in my AuthController and session controller, but code is as follows:</p>
<pre><code>import 'package:get/get.dart';

class AuthController extends GetxController {
  String getSignedInUserId() {
    // await Future.delayed(Duration(milliseconds: 1));
    return '1';
  }
}


import 'package:get/get.dart';

import '../../auth/controllers/auth_controller.dart';
import '../models/session_info.dart';

class SessionController extends GetxController {
  final AuthController authController = Get.find&lt;AuthController&gt;();

  Rx&lt;SessionInfo&gt; sessionInfo = Rx&lt;SessionInfo&gt;();

  Future&lt;void&gt; getSessionInfo() async {
    // authController.getSignedInUserId();

    // sessionInfo.value = SessionInfo(userId: userId);
  }
}

</code></pre>
<p>And the auto-generated, buggy mock controller:</p>
<pre><code>// Mocks generated by Mockito 5.0.1 from annotations
// in smart_locker_controller/test/shared/controllers/session_controller_test.dart.
// Do not manually edit this file.

import 'dart:ui' as _i4;

import 'package:get/get_instance/src/lifecycle.dart' as _i2;
import 'package:get/get_state_manager/src/simple/list_notifier.dart' as _i5;
import 'package:mockito/mockito.dart' as _i1;
import 'package:smart_locker_controller/auth/controllers/auth_controller.dart'
    as _i3;

// ignore_for_file: comment_references
// ignore_for_file: unnecessary_parenthesis

class _Fake_InternalFinalCallback&lt;T&gt; extends _i1.Fake
    implements _i2._InternalFinalCallback&lt;T&gt; {}

/// A class which mocks [AuthController].
///
/// See the documentation for Mockito's code generation for more information.
class MockAuthController extends _i1.Mock implements _i3.AuthController {
  MockAuthController() {
    _i1.throwOnMissingStub(this);
  }

  @override
  int get notifierVersion =&gt;
      (super.noSuchMethod(Invocation.getter(#notifierVersion), returnValue: 0)
          as int);
  @override
  int get notifierMicrotask =&gt;
      (super.noSuchMethod(Invocation.getter(#notifierMicrotask), returnValue: 0)
          as int);
  @override
  bool get hasListeners =&gt;
      (super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false)
          as bool);
  @override
  int get listeners =&gt;
      (super.noSuchMethod(Invocation.getter(#listeners), returnValue: 0)
          as int);
  @override
  _i2._InternalFinalCallback&lt;void&gt; get onStart =&gt;
      (super.noSuchMethod(Invocation.getter(#onStart),
              returnValue: _Fake_InternalFinalCallback&lt;void&gt;())
          as _i2._InternalFinalCallback&lt;void&gt;);
  @override
  _i2._InternalFinalCallback&lt;void&gt; get onDelete =&gt;
      (super.noSuchMethod(Invocation.getter(#onDelete),
              returnValue: _Fake_InternalFinalCallback&lt;void&gt;())
          as _i2._InternalFinalCallback&lt;void&gt;);
  @override
  bool get initialized =&gt;
      (super.noSuchMethod(Invocation.getter(#initialized), returnValue: false)
          as bool);
  @override
  bool get isClosed =&gt;
      (super.noSuchMethod(Invocation.getter(#isClosed), returnValue: false)
          as bool);
  @override
  String getSignedInUserId() =&gt;
      (super.noSuchMethod(Invocation.method(#getSignedInUserId, []),
          returnValue: '') as String);
  @override
  void update([List&lt;Object&gt;? ids, bool? condition = true]) =&gt;
      super.noSuchMethod(Invocation.method(#update, [ids, condition]),
          returnValueForMissingStub: null);
  @override
  void refreshGroup(Object? id) =&gt;
      super.noSuchMethod(Invocation.method(#refreshGroup, [id]),
          returnValueForMissingStub: null);
  @override
  void removeListener(_i4.VoidCallback? listener) =&gt;
      super.noSuchMethod(Invocation.method(#removeListener, [listener]),
          returnValueForMissingStub: null);
  @override
  void removeListenerId(Object? id, _i4.VoidCallback? listener) =&gt;
      super.noSuchMethod(Invocation.method(#removeListenerId, [id, listener]),
          returnValueForMissingStub: null);
  @override
  _i5.Disposer addListener(_i5.GetStateUpdate? listener) =&gt;
      (super.noSuchMethod(Invocation.method(#addListener, [listener]),
          returnValue: () {}) as _i5.Disposer);
  @override
  _i5.Disposer addListenerId(Object? key, _i5.GetStateUpdate? listener) =&gt;
      (super.noSuchMethod(Invocation.method(#addListenerId, [key, listener]),
          returnValue: () {}) as _i5.Disposer);
  @override
  void disposeId(Object? id) =&gt;
      super.noSuchMethod(Invocation.method(#disposeId, [id]),
          returnValueForMissingStub: null);
}
</code></pre>
",https://stackoverflow.com/questions/66685369/unit-testing-getxcontroller,"['flutter', 'unit-testing', 'flutter-getx']",8933,True,14,2
Android Studio unit testing with LibGDX test folder missing Arctic Fox,"<p>I've not used Android Studio in a while and have forgotten more things about it than I ever knew.</p>
<p>I am working with LibGDX and have some complicated class/methods I'd like to do unit testing on them outside of the graphic environment. On a normal android project, I'd have a structure that looks something like:
app
manifests
java
com.example.myApplication
MainActivity
ClassToTest
com.example.myApplication (test)
ClassToTestUnitTest</p>
<p>But when I generate a LibGDX my structure looks like:
Android
manifests
java
com.example.myApplication
MainActivity
ClassToTest</p>
<p>When I go to 'Generate...' 'Tests' by right clicking on the ClassToTest entry in the java file, I receive the message 'Create test in the same root?'</p>
<p><strong>No</strong>, I don't want that - I want to have a special folder for tests to be contained away from my main code.</p>
<p>How do I create that folder and have the test generator know where it is?? All the answers I could find looked like they were created for a much older version of Android Studio, since the folder hierarchy was different.</p>
<p>In further looking, it appeared I needed to make some changes to my code build.gradle. I tried the changes suggested, but there was no effect that I could see.</p>
<p>The gradle now looks like:</p>
<pre><code>sourceCompatibility = 1.7
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'

sourceSets.main.java.srcDirs = [ &quot;src/&quot; ]
sourceSets.test.java.srcDirs = [&quot;test/&quot;]

eclipse.project.name = appName + &quot;-core&quot;
</code></pre>
<p>Thanks for any insight you can provide. I am sure I am missing something fairly basic.</p>
",https://stackoverflow.com/questions/68667909/android-studio-unit-testing-with-libgdx-test-folder-missing-arctic-fox,"['java', 'android-studio', 'unit-testing']",126,False,1,0
Swift: Set protocol&#39;s associated type in argument / member variable,"<p>I'm trying to create a generic protocol that can be reused in various parts throughout my application. Previously I've hardcoded <code>KeyValueStore</code> to only use <code>String</code> and <code>Int</code> for <code>Key</code> and <code>Value</code> respectively. I ran into an issue where I want a different consumer, class <code>ConsumerB</code>, to use <code>KeyValueStore</code> with <code>Key</code>/<code>Value</code> being <code>Int</code>/<code>Int</code> respectively.</p>
<pre><code>protocol KeyValueStore {
    associatedtype Key
    associatedtype Value
    func get(key: Key) -&gt; Value
    func set(key: Key, value: Value)
}
</code></pre>
<p>For the original implementation, I had two classes the conform to the protocol. <code>UserDefaultsStore</code> was used to store data during runtime and <code>MemoryKeyValueStore</code> was used in unit testing.</p>
<pre><code>class UserDefaultsStore: KeyValueStore {
    func get(key: String) -&gt; Int { return 0
        // Implementation
    }
    
    func set(key: String, value: Int) {
        // Implementation
    }
}

class MemoryKeyValueStore: KeyValueStore {
    var values: [String: Int] = [:]
    func get(key: String) -&gt; Int { return values[key]! }
    func set(key: String, value: Int) { values[key] = value}
}
</code></pre>
<p>Since they both used <code>KeyValueStore</code> with hardcoded types I could provide a store implementation at runtime.</p>
<pre><code>class ConsumerA {
    var keyValueStore: KeyValueStore
    
    init(store: KeyValueStore) {
        keyValueStore = store
    }
  
    func example() {
        keyValueStore.set(key: &quot;Hello&quot;, value: 5)
    }
}
</code></pre>
<p>After adding the associated types, I get the error below. It makes sense that while compiling <code>ConsumerA </code>, there is no way to know what type <code>Key</code> and <code>Value</code> take on in the <code>KeyValueStore</code> argument and member variable. However after poking around, I could not seem to find a clear answer on <strong>how to properly declare what types <code>Key</code> and <code>Value</code> should be in the <code>ConsumerA</code> class.</strong></p>
<p>In the <code>example</code> function, it is clear it would use <code>String</code> and <code>Int</code>, but how do I set the argument/member variable to only allow classes that conform to <code>KeyValueStore</code> and have <code>Key</code>/<code>Value</code> set to <code>String</code>/<code>Int</code>?</p>
<pre><code>Protocol 'KeyValueStore' can only be used as a generic constraint because it has Self or associated type requirements
</code></pre>
<p><strong>Edit:</strong>
I ended up going a different route based on <a href=""https://betterprogramming.pub/swift-protocols-with-associated-types-and-generics-373b2927baed"" rel=""nofollow noreferrer"">this</a> medium article I found later in the evening.
While it seems like Swift should just natively provide a way to declare a protocol with associated types as a argument/variable type here is the work around.</p>
<pre><code>class AnyKeyValueStore&lt;Key, Value&gt;: KeyValueStore {
    private let _set: (Value?, Key) -&gt; Void
    private let _object: (Key) -&gt; Value?
    
    init&lt;U: KeyValueStore&gt;(_ keyValueStore: U) where U.Key == Key, U.Value == Value {
        _set = keyValueStore.set
        _object = keyValueStore.object
    }
    
    func set(value: Value?, forKey key: Key) {
        _set(value, key)
    }
    
    func object(forKey key: Key) -&gt; Value? {
        return _object(key)
    }
}
</code></pre>
",https://stackoverflow.com/questions/69330051/swift-set-protocols-associated-type-in-argument-member-variable,"['swift', 'swift5', 'swift-protocols', 'associated-types']",730,True,0,1
Adding LINQ Where &amp;&amp; condition in a foreach loop,"<p>To simplify my problem let's say I have the folowing database model:</p>
<pre><code>// database model, the list of not supported postcodes
var postcodeExclusionArray = new List&lt;PostcodeExclusion&gt;() {
    new PostcodeExclusion(){
        CustomerId = 2,
        Postocde = &quot;A11&quot;
    },
    new PostcodeExclusion(){
        CustomerId = 2,
        Postocde = &quot;A12&quot;
    },
    new PostcodeExclusion(){
        CustomerId = 2,
        Postocde = &quot;A12 4FR&quot;
    },
    new PostcodeExclusion(){
        CustomerId = 2,
        Postocde = &quot;AR&quot;
    },
    new PostcodeExclusion(){
        CustomerId = 2,
        Postocde = &quot;B11&quot;
    },
    new PostcodeExclusion(){
        CustomerId = 2,
        Postocde = &quot;B12&quot;
    },
        new PostcodeExclusion(){
        CustomerId = 2,
        Postocde = &quot;C11&quot;
    },
    new PostcodeExclusion(){
        CustomerId = 2,
        Postocde = &quot;C12&quot;
    },
    // many more records...
};
</code></pre>
<p>It describes unsupported UK postcodes. It's only a concept of a data source as normally we use EF Core 3.1.  Please bear in mind the format of each record can vary in gathering the whole area e.g. <code>EH</code> or a particular property only e.g. <code>AB25HZ</code>.</p>
<p>Now I want to check if the provided UK postcode is supported by my system.
My idea was to do it in the query using <code>Where</code> statement only but I'm not sure if it's possible at all.</p>
<p>The idea for the algorithm is to get the combinations of the provided postcode in a way such as</p>
<p><code>providedpostCode = &quot;A41666&quot;;</code></p>
<p>the combinations:</p>
<pre><code>A
A4
A41
A416
A4166
A41666
</code></pre>
<p>Then build db query such as</p>
<pre><code>bool isSupported = postcodeExclusionArray.Where(x =&gt; x.CustomerId == 2)
                      .Where(x=&gt; x.Postocde == &quot;A&quot; ||
                      x.Postocde == &quot;A&quot; ||
                      x.Postocde == &quot;A4&quot; ||
                      x.Postocde == &quot;A41&quot; ||
                      x.Postocde == &quot;A416&quot; ||
                      x.Postocde == &quot;A41666&quot;).First() == null;
                  
</code></pre>
<p><strong>Is there a way to achieve this using LINQ (not raw SQL) and if not what is the most optimal solution?</strong></p>
<p>I tried to play with the <code>foreach</code> loop but I didn't manage to find any solution.
If it's not possible then probably the easiest solution would be to generate the raw SQL query,
however, the minus of this approach would be that unit testing wouldn't be possible and this could only be tested by the integration test.
The other alternative would be to just query for all the postcodes from the db by customerId and do a simple iteration.
Any ideas?
Cheers</p>
",https://stackoverflow.com/questions/67676285/adding-linq-where-condition-in-a-foreach-loop,"['c#', 'linq', '.net-core', 'ef-core-3.1']",1050,True,0,2
How do I get H2 and SpringBoot to play nice together using the in memory database?,"<p>I'm working my way through a tutorial video on unit testing with JUnit and Mockito and have run across some issues where something isn't playing nice and I'm trying to figure out the problem.  The tutorial is creating an in memory database using H2 which is where I am having issues (the database has no data).  I have created a new project with the sole purpose of creating the same database which works to a point and then fails with no data.  After a couple days of research I'm hoping someone will see something glaringly obvious that I'm missing.  I'm using IntelliJ Idea 21.1.2 as my IDE, Linux Mint OS.  H2 is new to me.</p>
<p>pom.xml</p>
<pre><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 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;&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.5.2&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;com.example&lt;/groupId&gt;
    &lt;artifactId&gt;TestH2&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;TestH2&lt;/name&gt;
    &lt;description&gt;Demo project for Spring Boot&lt;/description&gt;
    &lt;properties&gt;
        &lt;java.version&gt;1.8&lt;/java.version&gt;
    &lt;/properties&gt;
    &lt;dependencies&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-devtools&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
            &lt;optional&gt;true&lt;/optional&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;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.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;/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>application.properties</p>
<pre><code>spring.datasource.url=jdbc:h2:mem:item;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1
spring.h2.console.enabled=true
</code></pre>
<p>schema.sql</p>
<pre><code>DROP TABLE IF EXISTS ITEM;

CREATE TABLE ITEM (
    id INT,
    name VARCHAR(255),
    price INT,
    quantity INT
);
</code></pre>
<p>data.sql</p>
<pre><code>INSERT INTO ITEM(id, name, price, quantity)
VALUES
       (10001,'Item1',10,20),
       (10002,'Item2',5,10),
       (10003,'Item3',15,2);
</code></pre>
<p>With the above and my application file the project builds and when I open the h2-console I get the expected result.
<a href=""https://i.stack.imgur.com/64v3i.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/64v3i.jpg"" alt=""H2 console works as expected"" /></a></p>
<p>However. . .</p>
<p>If I try to add an Item.java file like this (note if I comment out the @Entity line it works as shown above)</p>
<pre><code>package com.example.testh2.model;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Transient;

@Entity
public class Item {

    @Id
    private int id;
    private String name;
    private int price;
    private int quantity;

    @Transient
    private int value;

    public Item() {

    }

    public Item(int id, String name, int price, int quantity) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.quantity = quantity;

    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public int getValue() { return value; }
    public void setValue(int value) { this.value = value; }


    public String toString() {
        return String.format(&quot;Item[%d, %s, %d, %d]&quot;, id, name, price, quantity);
    }


}
</code></pre>
<p>Then there is no data</p>
<p><a href=""https://i.stack.imgur.com/YbBUC.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/YbBUC.jpg"" alt=""H2 fails"" /></a></p>
<p>I'm guessing that I'm missing something simple, I just haven't Google'd the right question yet.  I have tried the default as well as the current datasource.url, I've tried embedded H2 with a file (I see the items.mv.db file appear where it should but the console didn't find it nor did the IntelliJ database tools).  Any help would be greatly appreciated.</p>
",https://stackoverflow.com/questions/68230036/how-do-i-get-h2-and-springboot-to-play-nice-together-using-the-in-memory-databas,"['java', 'spring-boot', 'maven', 'intellij-idea', 'h2']",331,True,0,2
spring-integration: SplitterFactoryBean may only be referenced once,"<p>I have a Spring project (<em>not</em> using Spring Boot, if that's relevant) that I'm trying to connect to a local database using the Postgres JDBC driver. (The local database is actually Yugabyte, but that should be fully compatible with the Postgres driver.)</p>
<p>When starting the application, I get this error message:</p>
<pre><code>java.lang.IllegalArgumentException: An AbstractMessageProducingMessageHandler may only be referenced once (org.springframework.integration.config.SplitterFactoryBean#0) - use scope=&quot;prototype&quot;
    at org.springframework.util.Assert.isTrue(Assert.java:118)
    at org.springframework.integration.config.AbstractStandardMessageHandlerFactoryBean.checkReuse(AbstractStandardMessageHandlerFactoryBean.java:168)
    at org.springframework.integration.config.AbstractStandardMessageHandlerFactoryBean.createHandler(AbstractStandardMessageHandlerFactoryBean.java:137)
    at org.springframework.integration.config.AbstractSimpleMessageHandlerFactoryBean.createHandlerInternal(AbstractSimpleMessageHandlerFactoryBean.java:186)
    at org.springframework.integration.config.AbstractSimpleMessageHandlerFactoryBean.getObject(AbstractSimpleMessageHandlerFactoryBean.java:174)
    at org.springframework.integration.config.AbstractSimpleMessageHandlerFactoryBean.getObject(AbstractSimpleMessageHandlerFactoryBean.java:59)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:171)
    ... 52 more
</code></pre>
<p>I can't place this error at all. There is <a href=""https://stackoverflow.com/questions/50127547/spring-integration-messageproducer-may-only-be-referenced-once"">one similar question</a> on Stack Overflow, but there the asker seems to actually know what they're doing and how this is related to spring integration. I, however, am not aware at all that I'm trying to 'reuse' anything. The referenced question also doesn't seem to be related to database configuration.</p>
<p>My setup/configuration is a bit involved, so I'll try to quote the parts that seem relevant.</p>
<p>I have a dao layer project that has the following gradle dependencies (among others):</p>
<pre><code>implementation(&quot;org.springframework:spring-context:5.2.2.RELEASE&quot;)
implementation(&quot;org.springframework:spring-jdbc:5.2.2.RELEASE&quot;)
implementation(&quot;org.jooq:jooq-kotlin:3.14.11&quot;)
runtimeOnly(&quot;org.postgresql:postgresql:42.2.19.jre7&quot;)
</code></pre>
<p>In the same project, I have some configuration (in Kotlin):</p>
<pre><code>@Configuration
open class Config {
    @Bean
    open fun jdbcTemplate(dataSource: DataSource): JdbcTemplate = JdbcTemplate(dataSource)

    @Bean
    open fun dslContext(): DSLContext = DefaultDSLContext(SQLDialect.POSTGRES)

    @Configuration
    @Profile(&quot;!unittest&quot;)
    open inner class NonTestConfig {
        @Bean
        open fun dataSource(): DataSource {
            return DriverManagerDataSource().apply {
                // Hardcoded properties to be replaced by values from property file
                setDriverClassName(&quot;org.postgresql.Driver&quot;)
                url = &quot;jdbc:postgresql://localhost:5433/demo&quot;
                username = &quot;yugabyte&quot;
                password = &quot;yugabyte&quot;
            }
        }
    }
}
</code></pre>
<p>(Notes: the DSLContext bean is used for JOOQL, included for completeness' sake. The inner class config is there because there is also a separate unit testing config for an embedded database - that one works fine!)</p>
<p>Now, the above project is used in my top-level project that contains the actual application. It's a maven runtime dependency there. I import the config class in this project's XML configuration, using <a href=""https://stackoverflow.com/questions/13254779/how-to-import-java-config-class-into-xml-config-so-that-both-contexts-have-beans"">this method</a>:</p>
<pre><code>&lt;context:annotation-config /&gt;
&lt;bean class=&quot;my.package.Config&quot; /&gt;
</code></pre>
<p>Then trying to start the application produces the error message.</p>
",https://stackoverflow.com/questions/67973488/spring-integration-splitterfactorybean-may-only-be-referenced-once,"['spring', 'postgresql', 'jdbc', 'spring-integration']",56,True,0,1
Delay content of test of Cloud Functions with Mocha,"<p>I am trying to test a Cloud Function that interact with a Firestore database. I am following the documentation for testing my function using firebase-functions-test in online mode and mocha (<a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a>)</p>
<p>Since the function I want to test delete a document in a collection, I first created a fake document that I push to the db, inside my test.
Then I called with the wrap my function to test. It's asynchronous, so it takes a bit of time.</p>
<p>What I want to verify is that the document has been correctly removed. But the call to get the document and then the assert is sometimes faster than my actual function doing the delete. I would like to add a small delay before doing the verification.</p>
<p>I tried to add a settimeout, but the test returns 'passed' without waiting for the code inside the timeout to run and checking the assert.</p>
<p>Here is my test. Any help would be greatly appreciated!</p>
<pre><code>const myFunctions = require('../src/delete_notification.ts');

    it('delete notification of db more than 7 days old', async() =&gt; {

        // create test notification in db
        const notificationToDeleteId = 'TEST_1234567890';
        const notificationToDelete = {
            uid: notificationToDeleteId,
            createdOn: '2021-01-01T00:00:00.00000'
        };

        await admin.firestore().collection('notifications')
                 .doc(notificationToDeleteId)
                 .set(notificationToDelete);

        // call the cloud function
        const wrapped = test.wrap(myFunctions.deleteNotificationAfter7Days);
        await wrapped();

        //this code needs to be delayed by a few seconds

        return admin.firestore()
            .collection('notifications')
            .doc(notificationToDeleteId).get().then((deleteDoc) =&gt; {
                //console.log(deleteDoc.data());
                assert.equal(deleteDoc.data(), null);
        });
    }); 
</code></pre>
<p>Update :</p>
<p>I tried this code:</p>
<pre><code>return wrapped().then(() =&gt; {
            return setTimeout(() =&gt; {
              return admin.firestore().collection('notifications').doc(notificationToDeleteId)
                  .get().then((deleteDoc) =&gt; {
                      console.log(deleteDoc.data());
                      assert.equal(deleteDoc.data(), null);
                  });
            }, 5000)
        });
</code></pre>
<p>while making sure my function called does NOT delete the document. Like that I expect my test to failed. But with this code below (with the settimeout) the test passes all the time. It's the same with setInterval.</p>
<p><a href=""https://i.stack.imgur.com/fcQ6T.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fcQ6T.png"" alt=""enter image description here"" /></a></p>
<p>And here is the function I am trying to test:</p>
<pre><code> import * as functions from 'firebase-functions';
    import * as admin from 'firebase-admin';
    
    if (admin.apps.length === 0) admin.initializeApp();
    const db = admin.firestore();
    
    // run every  7 days
    export const deleteNotificationAfter7Days = functions
    .region('europe-west6')
    .pubsub
    .schedule('every 24 hours')
    .timeZone('Africa/Accra')
    .onRun(async context =&gt; {
    
        const currentDate = new Date();
        const currentDateMinus7Days = new Date(currentDate.getTime() - 604800000);
        const currentDateMinus7DaysString = currentDateMinus7Days.toISOString();
    
        //console.log(&quot;date minus 7 days &quot; + currentDateMinus7DaysString);
    
       try {
            const querySnapshot = await db.collection('notifications').where(&quot;createdOn&quot;, &quot;&lt;&quot;, currentDateMinus7DaysString).get();
            if(querySnapshot.empty) return;
    
            querySnapshot.forEach( async function(doc){
           

     const notificationId = doc.id;

            //console.log('notificationId id ' + notificationId);
            await deleteNotification(notificationId);
            return;
        });
    } catch (error) {
        console.log('Error deleting notifications ' + error);
    }
    return;
});

async function deleteNotification(notificationId : string) {

    //console.log('DELETE FROM NOTIFICATION');

    return db.collection('notifications')
        .doc(notificationId)
        .delete()
        .then(function() {
            console.log('Notification deleted');
        })
        .catch(function(error) {
            throw error;
        });
}
</code></pre>
",https://stackoverflow.com/questions/67742100/delay-content-of-test-of-cloud-functions-with-mocha,"['typescript', 'unit-testing', 'google-cloud-firestore', 'google-cloud-functions', 'mocha.js']",307,True,0,2
How to unit test a non-module with jasmine-node? (related to turning off node integration in Electron),"<p>I have a bit of a dilemma.</p>
<p>I turned on <code>contextIsolation</code> and turned off <code>nodeIntegration</code> for my <code>BrowserWindow</code> and loaded a local html page. (as is recommended by Electron).</p>
<p>This local html page requires a node module, which causes a crash, because Electron can't load a node module in the window since node is disabled:</p>
<p>main.ts:</p>
<pre><code>import { app, BrowserWindow } from &quot;electron&quot;;
import * as path from &quot;path&quot;;

function createWindow() {
  const mainWindow = new BrowserWindow({
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, &quot;preload.js&quot;),
    },
  });

  mainWindow.loadFile(path.join(__dirname, &quot;../index.html&quot;));
  mainWindow.webContents.openDevTools();
}

(async () =&gt; {
  await app.whenReady();
  createWindow();
})();

app.on(&quot;window-all-closed&quot;, () =&gt; {
  if (process.platform !== &quot;darwin&quot;) {
    app.quit();
  }
});
</code></pre>
<p>index.html:</p>
<pre><code>&lt;body&gt;
  &lt;h1&gt;Hello World!&lt;/h1&gt;
  &lt;script src=&quot;./renderer.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
</code></pre>
<p>renderer.js:</p>
<pre><code>export interface A { }
</code></pre>
<blockquote>
<p>Uncaught ReferenceError: exports is not defined
at renderer.js:2</p>
</blockquote>
<p>The specific line that crashes is this:</p>
<p><code>Object.defineProperty(exports, &quot;__esModule&quot;, { value: true });</code> which exists because of the <code>export</code> statement.</p>
<p>I can remove the export in this case (and just redefine the interface in the other module that needs it), but then I can't unit test my script.</p>
<p>I'm currently using <a href=""https://www.npmjs.com/package/jasmine-node"" rel=""nofollow noreferrer""><code>jasmine-node</code></a> for unit testing and I've been requiring the module that I want to test at the top:</p>
<pre><code>import * as Renderer from &quot;./renderer&quot;
</code></pre>
<p>This errors out in VSCode with something about how <code>Renderer</code> isn't a module.</p>
<p>It seems that requiring works (I guess Node can <code>require</code> non-modules?), but this causes the IIFE to run before my spies are set up.</p>
<p>If <code>Renderer</code> were a module, I would do:</p>
<pre><code>&lt;script&gt;
   require(&quot;renderer.js&quot;).main();
&lt;/script&gt;
</code></pre>
<p>And then my unit tests would set up the spies on the module before calling the main method. But since I can't <code>require</code> in my index.html since I've disabled Node, I have to load the script inline, and so I need some kind of IIFE to replace the main method:</p>
<pre><code>(async () =&gt; {
   await doSomething();
})();
</code></pre>
<p>How can I unit test this non-module then with Jasmine?</p>
",https://stackoverflow.com/questions/65568182/how-to-unit-test-a-non-module-with-jasmine-node-related-to-turning-off-node-in,"['node.js', 'unit-testing', 'jasmine', 'electron', 'jasmine-node']",214,True,0,1
Testing Methods that create objects inside the method with Junit and Mockito,"<p>Hello I am fairly new to unit testing with Junit as well as Mockito. I think I have a fairly reasonable understanding of the principles but I can't seem to find any explanations of what I am specifically trying to test online.</p>
<p>I want to test a method, that calls several other methods (void and non-void), which also instantiates objects in the method body. I unfortunately cannot share the code as it is not mine, but here is a general format:</p>
<pre><code>class classToTest {
     private final field_1;

     public void methodToTest( string id, List object_1, List object_2) {
          try {
               Map&lt;SomeObject_1, SomeObject_2&gt; sampleMap = new HashMap&lt;&gt;();
               method_1(object_1, object_2); //void function modifies object_2
               field_1.method_2(id, object_2);
               Map&lt;SomObeject_1, List&lt;object&gt;&gt; groupedList = groupList(object_2)
               //Then some stuff is added to the sampleMap
          }
          //catch would be here
}
</code></pre>
<p>At the moment I only care about testing method_1, and I cannot test directly as it is a private method so I must go through this parent method call. I wish I could change the code but I have been asked to keep it the same and to test in this manner with Mockito and Junit.</p>
<p>I know I need to Mock an object of the class to Test as well as its parameter:</p>
<pre><code>private classToTest classToTestObject;
@Mock private field_1 f1;

@Before
public void setup() {
     MockitoAnnotations.init.Mocks(this);
     classToTestObject = mock(classToTest.class, CALLS_REAL_METHODS);
}
</code></pre>
<p>but I don't know where to start my actual test, as in how I can essentially just execute that one method call and ignore all the rest. I can't just not ignore the other objects and method calls either as the main method will throw exceptions if they are not handled correctly.</p>
<p>Any help and guidance is much appreciated, sorry that I could not share the code. Thank You!</p>
",https://stackoverflow.com/questions/67923428/testing-methods-that-create-objects-inside-the-method-with-junit-and-mockito,"['java', 'unit-testing', 'junit', 'mockito']",436,False,0,1
Mocking API Call in Unit Testing Python 3,"<p>I have been given the task to write unit-tests for a function which eventually makes a requests.post API call. I have been asked to use mocking in Python. I am fairly new to it and have been reading lot of articles related to it. I have also written the unit test following the document. But, I do have a few questions which none of the documents I have come across answered-</p>
<ol>
<li><p>In unit test function too, I am making a call to the original function which is making the API call. And for now, I am mocking the response using mock.return_value. <em>So, eventually does this make an API call too from the unit-test function??</em>  If it does, then it fails my use-case where I am not supposed to make API calls regularly to third party server.</p>
</li>
<li><p>If it not making an API call, what exactly is it validating? I myself have fed the response and let's say status code of the API call. <em>So, without making the API call, how can these two be validated?</em></p>
</li>
</ol>
<pre><code>@patch('post.requests.get')
def test_api_function(self, mock_incident):
    mock_incident.return_value.json.return_value = [{'mock':'json'}]
    mock_incident.return_value.status_code = 200
    response = api_fucntion()

    assert response.status_code == 200
</code></pre>
<p>If you see, I am still making that call to the function(api_response). How does this serve my purpose of unit testing with mocking?? And, how does it verify 200 response without making an actual API call if it doesn't make one ??</p>
",https://stackoverflow.com/questions/65669782/mocking-api-call-in-unit-testing-python-3,"['python-3.x', 'api', 'unit-testing']",528,True,0,1
sandbox.restore() won&#39;t reset stub&#39;s called count,"<p>I'm completely new to Sinon/Jest and unit testing, so I'm kinda lost here. I tried to make a sandbox to declare all my stubs inside it but even after using sandbox.restore() the stub's call count is preserved, so my test fails in the next 'it'.</p>
<p>I wasn't able to stub TypeORM's objects directly, so I decided to create fake objects with only the methods I needed and made TypeORM's getRepository() use my created objects.</p>
<p>I'm not sure if this approach is even correct but looks like my tests are working, I can assert the number of calls and it's parameters, in the second 'it' I can expect that the error thrown equals 'Email já cadastrado' and if I change the expected message the test fails.</p>
<p>The issue is that the number of calls won't reset before the next 'it' block. So I always get an error on the line &quot;sandbox.assert.calledOnceWithExactly(fakeConnection.getRepository, Cidades)&quot; since it's being called twice (once on previous 'it' and a second time on the current block).</p>
<p>If I remove that line I get an error in the assert transaction section, since I expect commitTransaction to not have been called but it was called once (in the previous 'it' block).</p>
<p><a href=""https://i.stack.imgur.com/sS1re.jpg"" rel=""nofollow noreferrer"">Image of my Error</a></p>
<p>Here is my test:</p>
<pre><code>const sandbox = sinon.createSandbox();

// Simulating TypeORM's QueryRunner
const fakeQueryRunner = {
    connect: sandbox.stub().returnsThis(),      
    startTransaction: sandbox.stub().returnsThis(),
    rollbackTransaction: sandbox.stub().returnsThis(),
    commitTransaction: sandbox.stub().returnsThis(),
    release: sandbox.stub().returnsThis(),
    manager: { save: sandbox.stub().returnsThis() },
};

// Simulating TypeORM's Connection
const fakeConnection = {
    createQueryRunner: sandbox.stub().returns( fakeQueryRunner ),
    getRepository: sandbox.stub().returnsThis(),
    findOneOrFail: sandbox.stub().returnsThis(),
}

// I've hidden the mock of my parameters/entities (Usuarios, Senhas, Cidades) since I don't think it's needed to solve the problem.

describe('UserRepository', function () {
    let userRepository;

    beforeEach(async () =&gt; {
        const module = await Test.createTestingModule({
            providers: [
                UserRepository,
            ],
        }).compile();
        userRepository = module.get&lt;UserRepository&gt;(UserRepository);
    });

    describe('signUp', function () {
        beforeEach(function () {
            // typeORM.getConnection() returns my object simulating a Connection.
            sandbox.stub(typeorm, 'getConnection').returns( fakeConnection as unknown as typeorm.Connection )

            // Stubbing this.create()
            sandbox.stub(userRepository, 'create').returns( Usuarios )
        });
        
        afterEach(function () {
            sandbox.restore();
        });

        it('successfully signs up the user', async function () {
            // Simulating sucessful save transaction
            fakeQueryRunner.manager.save.onCall(0).resolves(Usuarios);
            fakeQueryRunner.manager.save.onCall(1).resolves(Senhas);
            
            // Calling my method
            await userRepository.signUp(mockCredentialsDto);
            
            // First interation, this line works
            sandbox.assert.calledOnceWithExactly(fakeConnection.getRepository, Cidades);

            // Asserting that transaction was commited
            sandbox.assert.calledOnce(fakeQueryRunner.commitTransaction);
            sandbox.assert.notCalled(fakeQueryRunner.rollbackTransaction);
        });

        it('throws a conflic exception as username already exists', async function () {
            // Simulating a reject from transaction
            fakeQueryRunner.manager.save.onCall(0).rejects({ code: '23505' });

            // Calling my method and catching error
            try {
                await userRepository.signUp(mockCredentialsDto)
            } catch (err) {
                expect(err).toEqual(new Error('Email já cadastrado'));
            }

            // Second interation, this line giver ERROR (method called twice)              
            sandbox.assert.calledOnceWithExactly(fakeConnection.getRepository, Cidades);

            // Asserting that transaction was rolled back, this also gives an error since commitTransaction was called once (in the first 'it' block)
            sandbox.assert.notCalled(fakeQueryRunner.commitTransaction);
            sandbox.assert.calledOnce(fakeQueryRunner.rollbackTransaction);
        });
    // I will make another describe block here eventually
});
</code></pre>
<p>Here is the method I'm testing:</p>
<pre><code>async signUp(authCredentialsDto: AuthCredentialsDto): Promise&lt;signUpMessage&gt; {
    const { nome, email, genero, dataNascimento, profissao, organizacao, atuacao, nomeCidade, uf, senha } = authCredentialsDto;
    const connection = getConnection();
    const user = this.create();
    const senhas = new Senhas;
    const cidade = await connection.getRepository(Cidades).findOneOrFail({where: { nome: nomeCidade, uf: uf } });

    // Set values
    user.nome = nome;
    user.email = email;
    user.genero = genero;
    user.dataNascimento = dataNascimento;
    user.profissao = profissao;
    user.organizacao = organizacao;
    user.atuacao = atuacao;
    user.idCidade = cidade;
    const salt = await bcrypt.genSalt();
    senhas.senha = await this.hashPassword(senha, salt)
    senhas.idUsuario2 = user;
    
    // Make a transaction to save the data
    const queryRunner = connection.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();
    
    try {
        await queryRunner.manager.save(user);
        await queryRunner.manager.save(senhas);
        await queryRunner.commitTransaction();
    } catch (error) {
        if ( error.code === '23505' ) { // Usuário repetido
            await queryRunner.rollbackTransaction();
            throw new ConflictException('Email já cadastrado')
        } else {
            await queryRunner.rollbackTransaction();
            throw new InternalServerErrorException;
        }
    } finally {
        await queryRunner.release();
    }

    let success: signUpMessage;
    return success;
}
</code></pre>
",https://stackoverflow.com/questions/66809607/sandbox-restore-wont-reset-stubs-called-count,"['unit-testing', 'testing', 'jestjs', 'sinon']",373,True,0,1
Unit Testing File with Space in the Name,"<p>I have a Python project where the main file has spaces in the name. I understand that this is not encouraged, but in this case, I think it's necessary. The file is being compiled into a stand alone executable using py2app--which uses the file name for the application name when building the executable (app name, menu references, etc.). This works fine because the base file is not imported anywhere within the project and py2app handles the spaces gracefully. Let's call the file <code>Application Name.py</code>.</p>
<p>In order to run unit tests against <code>Application Name.py</code>, however, I have to eliminate the spaces in order to import the file into <code>unittest</code>. I'm unable to use <code>importlib</code> or <code>__import__</code> because the file is not constructed as a package, so both approaches fail. My workflow has been to refactor the file name to <code>application_name.py</code>, run the unit tests, and then refactor the name to <code>Application Name.py</code> before compiling it into <code>Application Name.app</code>.</p>
<p>So the options appear to be:</p>
<ol>
<li>Keep doing what I'm doing (workable, but not ideal),</li>
<li>Create a wrapper called <code>Application Name.py</code> that imports <code>application_name.py</code> where the wrapper doesn't need to be unit tested (seems silly),</li>
<li>Convert <code>Application Name</code> into a package so I can use <code>importlib</code> (seems like overkill), or</li>
<li>Something else entirely.</li>
</ol>
<p>Is there some way to gracefully handle file names with spaces in unit testing that I'm not seeing or should I just suck it up?</p>
",https://stackoverflow.com/questions/66379066/unit-testing-file-with-space-in-the-name,"['python-3.x', 'python-unittest', 'py2app']",216,True,0,1
"If I am unit testing what happens inside an if-clause, should I mock everything up to the if-clause?","<h2>The scenario</h2>
<p>I am writing unit tests for a module similar to the one below</p>
<p><strong>service.js</strong></p>
<pre><code>const client = require(&quot;./../client&quot;);

let managedData = {};

function manageData(dataId) {
  let users = client.retrieveUsers(); //Will return an array of strings. For example: a list of user names
  let user = client.retrieveCurrentUser(); //Will return a string. For example: one user name
  let userIsPresentInList = users.includes(user); //Check if the user is present in a broader user list
  if(userIsPresentInList) {
    managedData[dataId] = client.retrieveDataWithId(dataId);
  }
}


function unmanageData(dataId) {
  client.doSomethingToTheDataWithId(dataId)
  delete managedData[dataId]
}

module.exports = { 
  manageData,
  unmanageData
}
</code></pre>
<p>Some of my unit tests target what happens when the user is present in the list of users, i.e., what happens inside the if-clause</p>
<p>The questions is: if I am unit testing an if-clause, should I mock everything up to the clause (option 1 below)? Or should I create an way of &quot;directly&quot; ending up in the if-clause (option 2 below)?</p>
<h2>The test</h2>
<p><strong>Option 1) Group the tests via describe blocks and mock in beforeEach/beforeAll:</strong>: Scenarios that concern what's inside the if-clause are grouped in a describe block and mocks are done for all statements up until the if-clause</p>
<p><strong>Option 2) Mock intermediate functions inside module</strong>: service.js is refactored. The code that checks whether the user is in the list of users is extracted in a new function inside the module. This function then is mocked. In this way anything before the if-clause does not really matter and the test only concerns what is inside the if-clause is working</p>
<p><strong>service.test.js</strong></p>
<pre><code>const service = require(&quot;./service&quot;);
const client = require(&quot;./../client&quot;);
jest.mock(&quot;./../client&quot;);

beforeEach(() =&gt; {
  jest.clearAllMocks();
});

describe('Sucesful management', () =&gt; {


    //OPTION 1
    beforeEach(() =&gt; {
        client.retrieveUsers = jest.fn(() =&gt; [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]);
        client.retrieveCurrentUser = jest.fn(() =&gt; &quot;a&quot;);
    })

    //OPTION 2
    beforeEach(() =&gt; {
        service.isUserPresentInUsersList = jest.fn(() =&gt; true);
    })

    afterEach(() =&gt; {
      service.isUserPresentInUsersList.mockRestore();
    })

    it(&quot;Given the user belongs to the user list, should retrieve the data calleing manageData&quot;, async () =&gt; {
        //Act
        service.manageData(&quot;D&quot;);
        //Assert
        expect(client.retrieveDataWithId).toHaveBeenCalledWith(&quot;D&quot;);
      });
    
      it(&quot;Given the user belongs to the user list, should do something with the data when calling unmanageData&quot;, async () =&gt; {
        //Act
        service.manageData(&quot;D&quot;);
        service.unmanageData(&quot;D&quot;);
        //Assert
        expect(client.doSomethingToTheDataWithId).toHaveBeenCalledWith(&quot;D&quot;);
      });
})
</code></pre>
<p>Is there preferable one in this case? Is any of those approaches terrible?</p>
<p>An extended question would be: what are open source projects that have good testing practices that I can get inspiration from?</p>
",https://stackoverflow.com/questions/66626062/if-i-am-unit-testing-what-happens-inside-an-if-clause-should-i-mock-everything,"['node.js', 'unit-testing', 'jestjs', 'mocking']",58,False,0,0
CPython and PyPy Decimal operation performance,"<p>I would like to run some 100k+ simulations with some millions of data points, which are represented as decimals. I choose decimals over floats for floating point accuracy and ease of unit testing my logic (since <code>0.1 + 0.1 + 0.1</code> does not equal 0.3 with floats...).</p>
<p>My hope was to speed up the simulations by using PyPy. But during my testing I encountered that PyPy does not handle <code>decimal.Decimal</code> or even <code>_pydecimal.Decimal</code> well at all - and gets dramatically slower than the CPython interpreter (which uses C for <code>decimal.Decimal</code> arithmetics). So I copy/pasted my whole codebase and replaced all <code>Decimal</code>s with <code>float</code>s and the performance increase was huge: x60-x70 times faster with PyPy than CPython - with the sacrifice of accuracy.</p>
<p>Are there any solutions to use Decimals precision in PyPy with the performance benefit? I &quot;could&quot; maintain two codebases: <code>float</code> for batch running the 100k simulations, <code>Decimal</code> for inspecting the interesting results later - but this bears the overhead of maintaining two codebases...</p>
<p>Here are some simple tests I ran on a <code>Raspberry Pi 4 (Ubuntu Server 20.10, 4 x 1.5GHZ ARM Cortex-A72, 8GB RAM)</code> for reproduction:</p>
<p><strong>test_decimal.py</strong></p>
<pre><code>import time
from decimal import Decimal

start = time.time()
val = Decimal('1.0')
mul = Decimal('1.000001')
for i in range(10 * 1000 * 1000):
    val *= mul
end = time.time()
print(f&quot;decimal.Decimal: {val:.8f} in {round(end-start,4)} sec&quot;)
</code></pre>
<p><strong>test_pydecimal.py</strong></p>
<pre><code>import time
from _pydecimal import Decimal

start = time.time()
val = Decimal('1.0')
mul = Decimal('1.000001')
for i in range(10 * 1000 * 1000):
    val *= mul
end = time.time()
print(f&quot;pydecimal.Decimal: {val:.8f} in {round(end-start,4)} sec&quot;)
</code></pre>
<p><strong>test_float.py</strong></p>
<pre><code>import time
from decimal import Decimal

start = time.time()
val = float('1.0')
mul = float('1.000001')
for i in range(10 * 1000 * 1000):
    val *= mul
end = time.time()
print(f&quot;float: {val:.8f} in {round(end-start,4)} sec&quot;)
</code></pre>
<p><strong>Results</strong></p>
<div class=""s-table-container"">
<table class=""s-table"">
<thead>
<tr>
<th style=""text-align: left;"">Test</th>
<th style=""text-align: right;"">Python 3.8.6 (GCC 10.2.0)</th>
<th style=""text-align: right;"">Python 3.6.9 -PyPy 7.3.1 with GCC 10.2.0</th>
</tr>
</thead>
<tbody>
<tr>
<td style=""text-align: left;"">test_decimal</td>
<td style=""text-align: right;"">5.1131 sec</td>
<td style=""text-align: right;"">55.0829 sec</td>
</tr>
<tr>
<td style=""text-align: left;"">test_pydecimal</td>
<td style=""text-align: right;"">315.4012 sec</td>
<td style=""text-align: right;"">40.1771 sec</td>
</tr>
<tr>
<td style=""text-align: left;"">test_float</td>
<td style=""text-align: right;"">2.5607 sec</td>
<td style=""text-align: right;"">0.1273 sec</td>
</tr>
</tbody>
</table>
</div>
<p><strong>Edit #1:</strong></p>
<ul>
<li>Updated the examples (use precomputed multiplicator, measure time outside of  <code>print</code>) and the results table: The overall comparison between PyPy and CPython performance on Decimals stays the same.</li>
<li>The simulation mostly consists of the basic math operations (add, subtract, multiply, divide) over time-series data with changing values.</li>
</ul>
",https://stackoverflow.com/questions/66646850/cpython-and-pypy-decimal-operation-performance,"['python', 'performance', 'math', 'floating-point', 'pypy']",1102,True,4,2
Best Practices for TDD in JavaScript/TypeScript,"<h1>Questions</h1>
<ul>
<li>What is the correct/acceptable way to access all JavaScript/TypeScript functions in a module for unit testing?</li>
<li>Is there a (good) reason why I shouldn't just export all my functions?</li>
</ul>
<h1>Context</h1>
<p>Please forgive my ignorance; I have spent the majority of my professional career writing Python code using the Test Driven Development (TDD) approach. Now, I am finding myself learning ReactJS/TypeScript and figuring out how to implement unit tests, but I quickly found out that functions are only accessible if you export them. As most of you know, Python is very permissive; there really is no concept of privacy, so it's just a matter of importing the module and being respectful of what you have access to. But JavaScript only imports the functions of a module that have been explicitly exported, thus providing a modest barrier.</p>
<p>I've been told that it's not a great idea to export all my functions for testing, but I'm not aware of another way to actually be able to test them.</p>
<h1>Examples</h1>
<h3>What I've been told is &quot;correct/better&quot;:</h3>
<p>Sample1.js:</p>
<pre class=""lang-js prettyprint-override""><code>const func1 = () =&gt; {
    //code that does stuff
    return &quot;stuff&quot;;
};

const func2 = () =&gt; {
   //code that does other stuff
   return &quot;otherStuff&quot;;
};

export { func1 };
</code></pre>
<p>Sample1.test.js:</p>
<pre class=""lang-js prettyprint-override""><code>// executed via Jest framework

import * as sample from &quot;./Sample1.js&quot;

describe(&quot;Unit Tests for Sample1&quot;, () =&gt; {
    test(&quot;Unit Test - func1&quot;, () =&gt; {
        // code that tests stuff
    };

    test(&quot;Unit Test - func2&quot;, () =&gt; {
        // can't test func2 because it's not exported
    };
};
</code></pre>
<h3>What I'm doing to be able to test all functions:</h3>
<p>Sample2.js:</p>
<pre class=""lang-js prettyprint-override""><code>const func1 = () =&gt; {
    //code that does stuff
    return &quot;stuff&quot;;
};

const func2 = () =&gt; {
   //code that does other stuff
   return &quot;otherStuff&quot;;
};

export { func1, func2 };
</code></pre>
<p>Sample2.test.js:</p>
<pre class=""lang-js prettyprint-override""><code>// executed via Jest framework

import * as sample from &quot;./Sample2.js&quot;

describe(&quot;Unit Tests for Sample2&quot;, () =&gt; {
    test(&quot;Unit Test - func1&quot;, () =&gt; {
        // code that tests stuff
    };

    test(&quot;Unit Test - func2&quot;, () =&gt; {
        // code that tests other stuff because it's exported
    };
};
</code></pre>
<h3>For the Record</h3>
<p>I've looked around on the internet and Stack Overflow specifically for standards and best practices, but I haven't found much that answers this specific question. The closest I found was <a href=""https://stackoverflow.com/questions/32228055/javascript-unit-testing-best-practices"">this SO question</a>, but it's not really what I'm after.</p>
",https://stackoverflow.com/questions/69140302/best-practices-for-tdd-in-javascript-typescript,"['javascript', 'typescript', 'tdd', 'standards']",774,True,2,1
Visual Studio unit tests not completing,"<p>A new colleague is unit testing using VS pro 2019#'s built-in unit test, as we all do.</p>
<p>With one solution (.sln) none of the unit tests complete when run from the Test Explorer, no matter whether Run or Debug is selected (on a side not, when the unit test file is open in the IDE, it is normally possible to right click within a  TEST_METHOD and either Run or Debug, but neither of these seem to work, although the status bar updates to say &quot;0 run, 0 passed, 0 failed&quot;.</p>
<p>If we breakpoint the final line of a unit test, and debug it from the Test Explorer, then the breakpoint is hit - no asserts fail and no exceptions are thrown. However, if we Continue, the test never ends and the status in the Test Explorer is never updated.</p>
<p>Worth noting:</p>
<ul>
<li>if just copy the code to my machine, the tests run as expected (and pass)</li>
<li>on my colleague's machine, a few new unit tests have been added, but even existing tests exhibit this behaviour</li>
<li>I Exported my Config &amp; Imported on me colleagues PC, which changed nothing</li>
<li>other Solutions' unit tests run as expected on my colleague's machine, including new tests added to those solutions</li>
</ul>
<p>any idea what is going wrong, and ow to fix it?</p>
<p>(I am loath to uninstall &amp; reinstall VS, as we work from home and the process takes hours over WiFi + VPN)</p>
",https://stackoverflow.com/questions/70378262/visual-studio-unit-tests-not-completing,['visual-studio'],92,True,2,1
Feature Branch Artifacts Workflow in CI with SemVer,"<p>I have a library (let's call it <code>my_lib</code>) and an application (<code>my_app</code>) structured in two Python packages where my tool <code>my_app</code> requires <code>my_lib</code> in the <code>requirements.txt</code>. In practice, I often develop a feature in <code>my_app</code> where the underlying added functionality is added to <code>my_lib</code> and then utilized in <code>my_app</code> (to re-use library <code>my_lib</code> in another setting).</p>
<p>I develop using <strong>Gitflow</strong> development principle and have a CI stage for both packages in a <code>feature</code> branch for both packages (let's call them <code>feature/my_feature_in_lib</code> and <code>feature/my_feature_in_app</code> for the argument's sake here). In CI, e.g., unit testing and package upload to a (private) PyPI is done.</p>
<p>Of course, I don't want to merge <code>feature/my_feature_in_lib</code> into the integration branch of <code>my_lib</code> before I properly tested it, which is often done in conjunction with <code>feature/my_feature_in_app</code> in CI.</p>
<p>Ideally, I would want <code>feature/my_feature_in_lib</code> to create an artifact / package that is then consumed by <code>my_app</code> in it's <code>requirements.txt</code>. I currently use <a href=""https://github.com/pypa/setuptools_scm/"" rel=""nofollow noreferrer"">setuptools_scm</a> for a SemVer-like auto-incrementation of the version number (such as <code>0.10.1.post1</code>). However, this scheme can lead to version duplications if working with multiple feature branches in parallel (which is why I currently only create artifacts on the integration branch).</p>
<p>Tools such as <a href=""https://gitversion.net/docs/learn/branching-strategies/gitflow/"" rel=""nofollow noreferrer"">GitVersion</a> in the C# world allow for version identifiers that contain feature branch specific identifiers, such as <code>1.2.3-alpha.feature-a682956d</code>. However, <a href=""https://www.python.org/dev/peps/pep-0440/"" rel=""nofollow noreferrer"">PEP-440</a> forbids the use of such versioning schemes and twine even rejects such uploads.</p>
<p>What is the optimal way to solve these dependency issues over package-boundaries while maintaining a SemVer-like automatic version incrementation?</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/69300811/feature-branch-artifacts-workflow-in-ci-with-semver,"['python', 'git-flow', 'semantic-versioning', 'twine', 'setuptools-scm']",142,False,1,0
why I am still getting firestore data from production when performing testing using emulator?,"<p>I am using</p>
<ul>
<li>Node 14</li>
<li>firebase functions-test: 0.2.3</li>
<li>firebase-admin: 9.6.0</li>
<li>firebase-functions: 3.13.2</li>
<li>firebase tools: 9.10.0</li>
</ul>
<p>I am trying to perform unit testing of my scheduled cloud function. my cloud functions is like this</p>
<pre><code>export const deleteExpiredEvents = functions
.pubsub.schedule(&quot;0 0 * * *&quot;) 
.timeZone(&quot;Asia/Jakarta&quot;)
.onRun(async (context) =&gt; {

    // delete expired events


});
</code></pre>
<p>I test the function above like this</p>
<pre><code>import * as admin from &quot;firebase-admin&quot;;
import * as firebase from &quot;firebase-functions-test&quot;;

const test = firebase({
  databaseURL: &quot;https://xxxx.firebaseio.com&quot;,
  projectId: projectID,
}, &quot;./service-account.json&quot;);

const db = admin.initializeApp().firestore();

beforeEach( async () =&gt; {
    // create dummy expired event
   
    await db.doc(`events/${event1.eventID}`).set(event1);
    await db.doc(`events/${event2.eventID}`).set(event2);
    await db.doc(`events/${event3.eventID}`).set(event3);
});

it(&quot;should not delete events that not expired&quot;, async () =&gt; {
 
     const wrap = test.wrap(myFunctions.deleteExpiredEvents);

     const context = {};  
     wrap(context); // execute function
        
     const querySnapshot = await db.collection(&quot;events&quot;).get();
     querySnapshot.docs.forEach((snapshot) =&gt; console.log(snapshot.data().eventID));
        
     // the rest of my code test ....
});
</code></pre>
<p>as you can see from the code above, in <code>before</code> block, I try to create dummy event data, so I expect my firestore emulator will be populated with these 3 dummy event data.</p>
<p>and then in the <code>it</code> block, I try to get all events and then <code>console.log</code> all the <code>eventID</code>s</p>
<p>I expect I will get 3 events from firestore emulator that previously created in the <code>before</code> block, but I don't know why I get 74 events (instead of just 3), and it comes from firestore production data, not from firestore emulator</p>
<p>I believe I already run <code>firebase emulators:start</code> , firestore, functions and pubsub emulators was running when I executed the test.
<a href=""https://i.stack.imgur.com/T6dx2.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/T6dx2.png"" alt=""enter image description here"" /></a></p>
<p>so why I am still getting firestore data from production when emulators has been started?</p>
<p>I try to read the documentation from here: <a href=""https://firebase.google.com/docs/emulator-suite/connect_firestore"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/emulator-suite/connect_firestore</a></p>
<p>it is said:</p>
<blockquote>
<p>The Firebase Admin SDKs automatically connect to the Cloud Firestore
emulator when the FIRESTORE_EMULATOR_HOST environment variable is set:</p>
<p>export FIRESTORE_EMULATOR_HOST=&quot;localhost:8080&quot;</p>
</blockquote>
<p>so I run</p>
<pre><code>export FIRESTORE_EMULATOR_HOST=&quot;localhost:8080&quot;
</code></pre>
<p>and then</p>
<pre><code>firebase emulators:start
</code></pre>
<p>it still get the data from production. in fact, if I disconnect from the internet, the test will not run!</p>
<p>I don't know why if check</p>
<pre><code>console.log(process.env.FIRESTORE_EMULATOR_HOST); // I expect, it will be will be &quot;localhost:8080&quot;
console.log(process.env.FUNCTIONS_EMULATOR); // I expect, it will be &quot;true&quot;
</code></pre>
<p>but I will get <code>undefined</code> for both values, like this</p>
<p><a href=""https://i.stack.imgur.com/Tbewy.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Tbewy.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/67033084/why-i-am-still-getting-firestore-data-from-production-when-performing-testing-us,"['node.js', 'google-cloud-firestore', 'google-cloud-functions', 'firebase-tools']",576,True,1,2
Why does .NET Core scope affect how db context updates are visible?,"<p>I've discovered some interesting behaviour with .NET dbContext and scoping in a unit test, and I haven't been able to figure out why this is happening. Hopefully someone will know why this is.</p>
<p>This is from a test method. Here are the steps. I've tried to edit it down for clarity.</p>
<ol>
<li>Test class Setup adds the required services for dependency injection, and creates the database as an InMemory db, and seeds the test data.</li>
</ol>
<pre><code>... add services ...
 services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt; options.UseInMemoryDatabase(&quot;ApplicationDb&quot;));
_serviceProvider = services.BuildServiceProvider();
_serviceScopeFactory = _serviceProvider.GetRequiredService&lt;IServiceScopeFactory&gt;();
_dbContext = _serviceProvider.GetRequiredService&lt;MyDbContext&gt;();
... seed data ...
</code></pre>
<ol start=""2"">
<li>Test Method modifies some data, then calls the target method being tested.</li>
</ol>
<pre><code>//signature: public async Task TargetMethod(SomeTaskDto taskDto, IServiceScopeFactory serviceScopeFactory)
... modify some data using _dbContext created in Setup ...
var _myClass =_serviceProvider.GetRequiredService&lt;MyClass&gt;();
await _myClass.TargetMethod( taskDto, _serviceScopeFactory );
</code></pre>
<ol start=""3"">
<li>Target method then uses <code>_serviceScopeFactory</code> to get a db context and modify some data.</li>
</ol>
<pre><code> using (var scope = serviceScopeFactory.CreateScope())
            {
                var _db = scope.ServiceProvider.GetService&lt;MyDbContext&gt;();
... changes made by calling test method are visible here.
... modify some data ...
                await _db.SaveChangesAsync();
... other stuff ...
          } //end scope
</code></pre>
<ol start=""4"">
<li>Back in the test method, after calling the target method, the changes are not visible in the original db context:</li>
</ol>
<pre><code>  var entityShouldBeModified = _dbContext.Products.Where( x =&gt; x.Id = idOfModifiedEntity ).FirstOrDefault();
  //this fails:
  Assert.AreEqual( expectedUpdatedValue, entityShouldBeModified.PropertyWhichShouldBeModified );
</code></pre>
<ol start=""5"">
<li>If I modify the test method to instead create a new scope after calling the target method, and get a new db context, the updated data from the target method is now visible:</li>
</ol>
<pre><code>   using(var scope = _serviceScopeFactory.CreateScope())
            {
                var db = scope.ServiceProvider.GetService&lt;MyDbContext&gt;();
                db.SetAuthenticatedUser(_user); 
                var entityShouldBeModified = db.Products.Where( x =&gt; x.Id = idOfModifiedEntity ).FirstOrDefault();
               //this works:
               Assert.AreEqual( expectedUpdatedValue, entityShouldBeModified.PropertyWhichShouldBeModified );
          }
</code></pre>
<p>Is this only something that happens with InMemory dbs in unit testing? (I guess I should really try it out on a Sql Server db.)
Even if it's only on InMemory dbs, why are the changes made by the test method visible to the target method, but the changes made by the target method are NOT visible to the calling test method?</p>
<p>Why did I have to create a new scope and new db context to see the changes made by the target method?</p>
<p>Thanks, any explanations appreciated.</p>
",https://stackoverflow.com/questions/67310184/why-does-net-core-scope-affect-how-db-context-updates-are-visible,"['c#', '.net-core', 'dependency-injection', 'scope']",190,True,1,1
C++ Makefile with source in multiple directories and multiple executables,"<p>I have a small project for school and I want to write a decent Makefile, I have seen some examples of using Makefile with multiple source directories and multiple executables but still could not implement it properly to my Makefile.</p>
<p>Here is the directory structure:</p>
<pre><code>.
├── bin (this is where i want the executables)
├── build (this is where i want the .o)
├── extern
│   └── doctest.h
├── include
│   ├── file1.hpp
│   └── file2.hpp
├── src
│   ├── file1.cpp
│   └── file2.cpp
├── tests
│   ├── file1-test.cpp
│   └── file2-test.cpp
└──  Makefile
</code></pre>
<p>PS: I'm using doctest for the unit testing (and i can't change).</p>
<p>Here is my Makefile for the moment:</p>
<pre><code>BIN_DIR = ./bin/
BUILD_DIR = ./build/
EXTERN_DIR = ./extern/
INCLUDE_DIR = ./include/
SOURCE_DIR = ./src/
TESTS_DIR = ./tests/

CXX = clang++-7
CXXFLAGS = -Wall -std=c++11 -g -O3 -I$(INCLUDE_DIR)

EXEC_FILES = file1 file2
BIN = $(addprefix $(BIN_DIR), $(EXEC_FILES))

all: $(BIN)

$(BIN_DIR) $(BUILD_DIR):
    mkdir -p $@

$(BUILD_DIR)%.o: $(SOURCE_DIR)%.cpp | $(BUILD_DIR)
    $(CXX) $(CXXFLAGS) -c -o $@ $^

$(BUILD_DIR)%.o: $(TESTS_DIR)%.cpp | $(BUILD_DIR)
    $(CXX) $(CXXFLAGS) -I$(EXTERN_DIR) -c -o $@ $^

$(BIN_DIR)file1-test: $(BUILD_DIR)file1.o $(BUILD_DIR)file1-test.o | $(BIN_DIR)
    $(CXX) -o $@ $^

$(BIN_DIR)file2-test: $(BUILD_DIR)file1.o $(BUILD_DIR)file2.o $(BUILD_DIR)file2-test.o | $(BIN_DIR)
    $(CXX) -o $@ $^

clean:
    rm -f $(BIN_DIR)* $(BUILD_DIR)*
</code></pre>
<p>It's working well but I feel like it's doing useless stuff that i could avoid with more knownledge in the Makefile art, sadly I don't have much time.</p>
<p>My goal:</p>
<ul>
<li><p>I want to run <code>make</code> and compile all the units tests (all the <code>.cpp</code> in the <code>tests/</code> directory) and the main program (see PS below).</p>
</li>
<li><p>I want all the executables in the <code>bin/</code> directory and all the binary files in the <code>build/</code> directory.</p>
</li>
</ul>
<p>PS: I don't have my main executable yet but it should be stored in the <code>src/</code> directory at the very end (and be compiled as well while running <code>make</code>).</p>
<p><strong>EDIT 1:</strong></p>
<p>Basically, my question is: How can I write generic rules to prevent copying this (see below) for every new executable in my project ?</p>
<pre><code>$(BIN_DIR)file2-test: $(BUILD_DIR)file1.o $(BUILD_DIR)file2.o $(BUILD_DIR)file2 test.o | $(BIN_DIR)
    $(CXX) -o $@ $^
</code></pre>
<p><strong>EDIT 2:</strong></p>
<p>After some changes, I ended up with this:</p>
<pre><code>BIN_DIR = ./bin/
BUILD_DIR = ./build/
EXTERN_DIR = ./extern/
INCLUDE_DIR = ./include/
SOURCE_DIR = ./src/
TESTS_DIR = ./tests/

vpath %.cpp $(SOURCE_DIR) $(TESTS_DIR)

CXX = clang++-7
CXXFLAGS = -Wall -std=c++11 -g -O3 -I$(INCLUDE_DIR) -I$(EXTERN_DIR)

EXEC_FILES = file1-test file2-test
BIN = $(addprefix $(BIN_DIR), $(EXEC_FILES))

all: $(BIN) | $(BIN_DIR)

$(BUILD_DIR)%.o: %.cpp | $(BUILD_DIR)
    @$(CXX) $(CXXFLAGS) -c -o $@ $^

# The problem is here
$(BIN_DIR)%: $(BUILD_DIR)%.o
    @$(CXX) -o $@ $^

$(BIN_DIR) $(BUILD_DIR):
    @mkdir -p $@

clean:
    -@rm -f $(BIN_DIR)* $(BUILD_DIR)*
</code></pre>
<p>I understand this rule (see below) like this: Compile every target in <code>EXEC_FILES</code> to the <code>bin/</code> directory, from <strong>his equivalent <code>.o</code> (obj) in the <code>build/</code> directory</strong>.</p>
<pre><code>$(BIN_DIR)%: $(BUILD_DIR)%.o
    @$(CXX) -o $@ $^
</code></pre>
<p>But in fact I need a rule that will: Compile every target in <code>EXEC_FILES</code> to the <code>bin/</code> directory, from <strong>all their related <code>.o</code> (obj) in the <code>build/</code> directory</strong>.</p>
",https://stackoverflow.com/questions/67347388/c-makefile-with-source-in-multiple-directories-and-multiple-executables,"['c++', 'makefile', 'project-structure']",147,False,1,0
How to mock dbSet.AddAsync(obj).Entity,"<p>I have a project with unit and integration test. Unfortunately, I cannot use any integration test for some reasons so I am obliged to use unit tests.</p>
<p>I have have the code bellow in my project.</p>
<pre><code>var associationEntity = (await _context.UsersAssociations.AddAsync(association)).Entity;
await _context.Entry(associationEntity.Guest).Collection(g =&gt; g.Accounts).LoadAsync();
</code></pre>
<p>_context is an Entity Framework DbContext. I am using AddAsync for better performances so I cannot use .Add(association) method.</p>
<p>I am using mocks with Moq and I am mocking the DbContext.</p>
<p>My objective is to get the .Entity object for my unit tests. Unfortunately, all my tries and what the internet offers couldn't make it work. await _context.UsersAssociations.AddAsync(association) is always returning null and not an EntityEntry as it should.</p>
<p>Here is my latest try:</p>
<pre><code>var dbContextMock = UnitTestHelper.GetDbContextMock();
var usersAssociationsSetMock = UnitTestHelper.GetDbSetMock(new List&lt;UsersAssociation&gt;());

var usersAssociationEntryMock = new Mock&lt;EntityEntry&lt;UsersAssociation&gt;&gt;();
usersAssociationEntryMock.Setup(x =&gt; x.Entity)
    .Returns(userAssociationMock); // It should returns an object defined before this part.

usersAssociationsSetMock.Setup(x =&gt; x.AddAsync(It.IsAny&lt;UsersAssociation&gt;(), It.IsAny&lt;CancellationToken&gt;()))
    .Returns((UsersAssociation model, CancellationToken token) =&gt; new ValueTask&lt;EntityEntry&lt;UsersAssociation&gt;&gt;(usersAssociationEntryMock.Object));

</code></pre>
<p>I was thinking that the entryMock.Entity could give me the usersAssociationMock. However, usersAssociationEntryMock.Object is not working. An error appears: &quot;Could not find a parameterless constructor&quot;.</p>
<p>And here's what I've tried and why it didn't succeed:</p>
<ul>
<li><a href=""https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/mocking-entity-framework-when-unit-testing-aspnet-web-api-2"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/mocking-entity-framework-when-unit-testing-aspnet-web-api-2</a> - The official doc but it's outdated.</li>
<li>The two answers of this topic <a href=""https://stackoverflow.com/questions/49142556/how-do-i-mock-addasync"">How do I mock AddAsync?</a> - It's either not working or returning null, so it's not what I want.</li>
</ul>
<p>If by any chance you have an idea, or need more code, don't hesitate :) I found very little help on the dbSet.AddAsync() mocking so even less help on what I want.</p>
<p>Thank you by advance and have a nice day even if you didn't help me :D</p>
",https://stackoverflow.com/questions/68801418/how-to-mock-dbset-addasyncobj-entity,"['c#', 'entity-framework', 'moq', 'dbset']",1297,True,0,2
Junit Testing in Netbeans with Maven - What is wrong with my setup?,"<p>UPDATE: Solution &amp; Lessons</p>
<ul>
<li>Corrected naming convention to be detected by Maven/JUnit: IngredientTest, not Ingredient_Test.</li>
<li>Deleted runner class (not required for tests).  Struggled with how exactly to run tests to see results (without any main method).</li>
<li>Solution: in netbeans, ran the test file from original class (Ingredient), NOT the test class (IngredientTest).  Right-click in body of original class (Ingredient), click 'Test file'.  Upon completion, an output and and test result window should open.</li>
</ul>
<p><a href=""https://i.stack.imgur.com/0t35g.png"" rel=""nofollow noreferrer"">netbeansSnapSolution</a></p>
<p>Thanks Chrylis, it appears I was mixing JUnit 4 &amp; 5.</p>
<p><a href=""https://learn.vogella.com/courses/details/java-software-testing"" rel=""nofollow noreferrer"">https://learn.vogella.com/courses/details/java-software-testing</a></p>
<p><a href=""https://junit.org/junit5/docs/current/user-guide/"" rel=""nofollow noreferrer"">https://junit.org/junit5/docs/current/user-guide/</a></p>
<hr />
<p>What I'm trying to do: write and run JUnit on existing classes in netbeans.</p>
<p>What's wrong</p>
<ul>
<li>@Before in Ingredient_Test: &quot;Cannot find symbol&quot;</li>
<li>imports in Ingredient_TestRunner: &quot;Package &lt;&gt; does not exist.&quot;</li>
</ul>
<p>Environment</p>
<ul>
<li>Product Version: Apache NetBeans IDE 12.4</li>
<li>Java: 16; Java HotSpot(TM) 64-Bit Server VM 16+36-2231</li>
<li>Runtime: Java(TM) SE Runtime Environment 16+36-2231</li>
<li>Project built with Maven as default, though I haven't modified the Maven XML file in any manner, saving that as the next tutorial item after unit testing.</li>
</ul>
<p>Background:  I wrote my own quick ad hoc test classes (mixed in with src files), meaning to do proper Junit testing &quot;later&quot;.  I'm several classes in, and I should have started with proper testing!  Now I'm in the process of rewriting ad hoc test classes properly.</p>
<p><a href=""https://i.stack.imgur.com/YhdQz.png"" rel=""nofollow noreferrer"">NetbeansSnap</a></p>
<p>Thanks in advance.</p>
<hr />
<pre><code>package com.riverrat.recipebook;

public class Ingredient{

    String name;
    String amount;
    String unit;
    String form;
    
    // do stuff
}  
</code></pre>
<hr />
<pre><code>package com.riverrat.recipebook;

import com.riverrat.recipebook.Ingredient;
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;

public class Ingredient_Test {
    
    @Before
    public void buildIngredients(){
        Ingredient beans = new Ingredient(&quot;beans&quot;);
        Ingredient onions = new Ingredient(&quot;onions&quot;, &quot;2&quot;, &quot;cups&quot;, &quot;chopped coarsley&quot;);
        Ingredient water = new Ingredient(&quot;water&quot;, &quot;3&quot;, &quot;oz&quot;);
        Ingredient bacon = new Ingredient(&quot;bacon&quot;, &quot;&quot;, &quot;slab&quot;);
    }
 
    @Test
    public void testNames(){
        assertEquals(&quot;beans&quot;, beans.name);
    }
}  
</code></pre>
<hr />
<pre><code>package com.riverrat.recipebook;
import org.JUnit.runner.JUnitCore;      
import org.JUnit.runner.Result;     
import org.JUnit.runner.notification.Failure;

public class Ingredient_TestRunner {
    
    public static void main(String[] args){
        Result result = JUnitCore.runclasses(IngredientTest);
        for (Failure failure : result.getFailure()){
            System.out.println(failure.toString());
        }
        System.out.println(&quot;Result &quot; + result.wasSuccessful());
    }
}  
</code></pre>
<hr />
",https://stackoverflow.com/questions/69060292/junit-testing-in-netbeans-with-maven-what-is-wrong-with-my-setup,"['java', 'junit', 'netbeans']",343,False,0,0
Istanbul Code Coverage tool incredibly slow after updating from version 12 to version 14,"<p>We use the Istanbul code coverage tool with Mocha to execute our Javascript unit tests.  This has been working fairly well for quite some time.  But, we were using version 12.0 with Node 11.  We are trying to update our build system to Node 14, and this caused the 'nyc' command line tool to break.</p>
<p>Updating our nyc package to 14.1.0 fixes the problem, but when used with Node 14, it has become <em>incredibly</em> slow - our unit tests/code coverage was executing in a few minutes in the build system and locally, and now takes upwards of 30 minutes to execute now.</p>
<p>Our command line looks like this:</p>
<pre><code>&gt; nyc --all true mocha --exclude test/browserBootStrap/index.js --require ignore-styles --exit --no-colors --timeout=20000 --require test/helper/bootstrap.js --recursive -R min
</code></pre>
<p>Our bootstrap mainly sets up a bunch of path variables for require and node, as well as some stub modules for unit testing &quot;dependency injection&quot;.  Our NYC configuration looks like this:</p>
<pre><code>  &quot;nyc&quot;: {
&quot;reporter&quot;: [
  &quot;cobertura&quot;
],
&quot;all&quot;: false,
&quot;include&quot;: [
  &quot;Content/**&quot;
],
&quot;exclude&quot;: [
  &quot;node_modules/**&quot;,
  &quot;Content/@types/**&quot;,
  &quot;Content/bower_components/**&quot;,
  &quot;Content/diagnostics/**&quot;,
  &quot;Content/events/**&quot;,
  &quot;Content/extenders/**&quot;,
  &quot;Content/hosts/**&quot;,
  &quot;Content/lib/**&quot;,
  &quot;Content/nls/**&quot;,
  &quot;Content/polyfills/**&quot;,
  &quot;Content/remove/**&quot;,
  &quot;Content/requirePlugins/**&quot;,
  &quot;Content/security/**&quot;,
  &quot;Content/storage/**&quot;,
  &quot;Content/tutorials/**&quot;,
  &quot;Content/tests/**&quot;,
  &quot;test/**&quot;
],
&quot;extension&quot;: [
  &quot;.ts&quot;
],
&quot;check-coverage&quot;: false,
&quot;sourceMap&quot;: false,
&quot;statements&quot;: 100,
&quot;lines&quot;: 100,
&quot;branches&quot;: 100,
&quot;functions&quot;: 100
},
</code></pre>
<p>I attached the chrome debugger to this and it runs quickly, but it differed by command line when I did that, it excluded the &quot;--all true&quot; switch.</p>
<p>I looked into the &quot;nyc&quot; initialization code and it had a line that I changed to add some console logging</p>
<pre><code>if (argv.all) { console.log(&quot;adding all files&quot;); nyc.addAllFiles(); console.log(&quot;adding all files - done&quot;); }
</code></pre>
<p>This is apparently the step that was taking so much time. The first log statement came out immediately, and the second one took forever to reach.</p>
<p>Does anyone know what sort of configuration I could change to get this to work better or what issue might be taking place here?</p>
",https://stackoverflow.com/questions/70397077/istanbul-code-coverage-tool-incredibly-slow-after-updating-from-version-12-to-ve,"['node.js', 'mocha.js', 'nyc']",491,False,0,1
"Static Utility Class, Unit Testing and Java.Time","<p>Due to our client still using Java.Date.Util, we've had to deal with various converting methods and a large bloated Date Utility class. My goal is to simplify the Utility class and write unit tests for it.</p>
<p>I've managed to simplify it, but I'm running into issues with test cases because:</p>
<ol>
<li>As an Utility class, the methods are static, thus no dependency
injection using Java.Time.Clock.</li>
<li>Several of our helper methods use instant.now() before converting it to the format requested. Obviously this makes writing unit tests... problematic.</li>
</ol>
<p>Here are some examples of the methods I need to write test cases for:</p>
<pre><code>     /**
     * Get the current time in any format.
     * @param outFormat
     * @return
     */
    public static Object getNow(TimeFormat outFormat){
        Instant dateObject = Instant.now();
        
        return new InstantConverter().convertTo(dateObject, outFormat);

    }
    
    /**
     * @param value - unit of time 
     * @param unit  - hours, days, etc. Anything higher than days is not supported. 
     * @param format - format returned. 
     */
    public static Object calculateFutureDate(int value, ChronoUnit unit, TimeFormat outFormat) {
        Instant time = Instant.now().plus(value, unit);
        
        return new InstantConverter().convertTo(time, outFormat);
    }
</code></pre>
<p><strong>InstantConverter</strong> is a protected class that converts Instant to various time outputs (localdate, string, epoch, java.util.date, etc) while <strong>TimeFormat</strong> is an enum that contains all the formats we can convert to.</p>
<p>I know it's best practice to move away from static methods when it comes to unit testing... but i'm afraid that is not an option.</p>
<p>In my research, it seems my only options are using powermock or one of the later versions of mockito to mock my static instant.now() method (similar to: <a href=""https://rieckpil.de/mocking-static-methods-with-mockito-java-kotlin/"" rel=""nofollow noreferrer"">https://rieckpil.de/mocking-static-methods-with-mockito-java-kotlin/</a>).</p>
<p>I just want to make sure I'm not missing anything obvious as I don't want to refactor <em>again</em> as I made a mistake.</p>
<p>Thank you anyone who took the time to read this! Let me know if  you have any questions.</p>
",https://stackoverflow.com/questions/66554775/static-utility-class-unit-testing-and-java-time,"['java', 'unit-testing', 'time', 'static']",745,True,0,1
Configuring Axon in Spring for integration testing,"<p>Still new to java and axon, having troubles to setup integration test suite using spring and axon.</p>
<p>Basically, I have some process, which:</p>
<ul>
<li>starts with command1</li>
<li>goes to command handler on aggregate and event1 is dispatched</li>
<li>event1 is processed by some policy (event listener) and command2 is generated</li>
<li>command2 is processed by command handler service (thus has no aggregate id) because I need to process something with third party</li>
<li>event2 is dispatched and processed by another event listener, so command3 is dispatched</li>
<li>command3 is processed by aggregate and event3 is dispatched</li>
</ul>
<p>I use <a href=""https://docs.axoniq.io/reference-guide/v/4.4/axon-framework/testing/commands-events"" rel=""nofollow noreferrer"">axon tests</a> for unit testing aggregates and it works great.</p>
<p>But I would like to add &quot;integration&quot; tests to:</p>
<ol>
<li>check the whole flow, like: when command1 dispatched then event1, event2, event3 is recorded (actually don't care about fields, just to have confidence the whole thing is glued as expected)</li>
<li>check the service command handler work as expected in manner &quot;when command2 dispatched, then event2 is recorded&quot;</li>
</ol>
<p>I was partly succesful with 1) by doing:</p>
<pre class=""lang-java prettyprint-override""><code>package com.example.integration;

import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore;
import org.junit.Assert;
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.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Arrays;
import java.util.UUID;

@RunWith(SpringRunner.class)
@SpringBootTest
@Import(IntegrationTestConfig.class)
public class ExampleIntegrationTest
{

    @Autowired
    private CommandGateway commandGateway;

    @Autowired
    private EmbeddedEventStore eventStore;

    @Test
    public void itShouldStoreCorrectEvents() {
        var aggregateId = UUID.randomUUID().toString();
        var exampleCommand = new ExampleCommand(aggregateId);

        whenCommandIsDispatched(exampleCommand);

        thenExpectedEventsRecorded(
                Arrays.asList(
                        Event1.class,
                        Event3.class
                ),
                aggregateId
        );
    }

    private void whenCommandIsDispatched(Command command)
    {
        commandGateway.sendAndWait(command);
    }

    private void thenExpectedEventsDispatched(java.util.List&lt;Class&lt;?&gt;&gt; expectedEventTypes, String id)
    {
        var events = eventStore.readEvents(id);
        while (events.hasNext()) {
            Assert.assertEquals(
                    expectedEventTypes.get(Math.toIntExact(events.getLastSequenceNumber())),
                    events.next().getPayloadType()
            );
        }
    }
}

</code></pre>
<p>And having IntegrationConfigTest:</p>
<pre class=""lang-java prettyprint-override""><code>package com.example.library.test;

import org.axonframework.eventhandling.EventBus;
import org.axonframework.eventsourcing.eventstore.EmbeddedEventStore;
import org.axonframework.eventsourcing.eventstore.EventStorageEngine;
import org.axonframework.eventsourcing.eventstore.inmemory.InMemoryEventStorageEngine;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

@TestConfiguration
public class IntegrationTestConfig {

    @Bean
    @Primary
    public static EventBus createSpyEventBus() {
        return new EmbeddedEventStore.Builder().storageEngine(new InMemoryEventStorageEngine()).build();
    }
}
</code></pre>
<p>Which is nice and test passes, but I didn't find a way how to test events dispatched from the service command handler (Event2 in my example) - id of aggregate is needed here: <code>eventStore.readEvents(id)</code>. EDIT: But I dont want to put aggregate id in, since event was not recorded on any aggregate - it was dispatched right into event gateway in service/singleton command handler.</p>
<p>Any ideas how can I get all dispatched events so I can also assert Event2 was dispatched?</p>
<p>Or am I missing something here? :)</p>
",https://stackoverflow.com/questions/69004824/configuring-axon-in-spring-for-integration-testing,"['spring', 'spring-test', 'axon']",638,True,3,2
Unit Testing regex to check for False Positives,"<p>so I have a Regex expression that I'm matching against a single string provided to check and match certain information. If it's matched, only the captured group is returned. I have made my function so that it removes any null strings from the returned array and finally, just gives the captured string as the output. This works great in unit testing for True Positives.</p>
<p>Now, I want to check for False Positives using the same expression, except I can't seem to figure out how to demonstrate it in a unit test. I have a few test strings in a file for which the Regex shouldn't match, and it does not. So my code works. But when I try to actually show that in a test case, as in check if a null string is returned, I can't.</p>
<p>I essentially want to check that if a match is not found, then it should return a null string. This is my code</p>
<pre><code>match = re.findall(combined, narration)
    result = list(filter(None, match[0]))
    if match:
        return result[0]
    else:
        result[0] = &quot;&quot;
        return result[0]
</code></pre>
<p>The first clause works fine for matched strings and returns a single string as output. In the second clause, I want to output a null string so I can check with the test case <code>.assertEqual</code> if the string is unmatched. But the function returns <code>list index out of range</code> error.</p>
<p>Can anybody tell me if there's a better way to check for an unmatched string with Regex and Unit Tests?</p>
<p><strong>Edit 1:</strong> Adding Expected Input and Output as requested</p>
<p>Input 1 - BRN CLG-CI IQ PAID ROHIT SINGH</p>
<p>Output 1 - ROHIT SINGH</p>
<p>Input 2 - BRN-TO CASH SELF</p>
<p>Output 2 - ''  //null string</p>
",https://stackoverflow.com/questions/67824633/unit-testing-regex-to-check-for-false-positives,"['python', 'regex', 'unit-testing', 'false-positive']",280,True,1,1
functional phpunit tests with elsticsearch,"<p>I'm trying to find a best way to setup elasticsearch for a tests in php.</p>
<p>I found such a <code>https://github.com/zumba/elasticsearchunit</code> library which can make my life a bit easier, but I'm not sure how to make test instance of elasticsearch server/database, should I use same instance but separate indexes for tests (maybe with a <code>test_</code> prefix), not a best idea, as I in the actual code I'm using <code>https://github.com/jolicode/elastically</code> which has mapping in <code>.yaml</code> files where index name hardcoded, and that's mean I'll need to make separate mapping files for test env.</p>
<p>Is there other ways of doing it, maybe I can use separate elasticsearch node on the same instance (like a SQL database) for testing? Or maybe there are some other solutions you can share with me, I'm a bit new to elasticsearch...</p>
<p>For unit tests all seems to be clear, we have mock handler <a href=""https://github.com/elastic/elasticsearch-php#unit-testing-using-mock-a-elastic-client"" rel=""nofollow noreferrer"">https://github.com/elastic/elasticsearch-php#unit-testing-using-mock-a-elastic-client</a>, but what to do with functional/integration tests?</p>
<p>Thanks in advice!</p>
<p>Note: my env is under docker, and I'm using <a href=""https://hub.docker.com/_/elasticsearch"" rel=""nofollow noreferrer"">https://hub.docker.com/_/elasticsearch</a> image.</p>
<p><strong>Updates</strong></p>
<p>I see I can create separate nodes,
<a href=""https://www.elastic.co/guide/en/elasticsearch/reference/7.5/docker.html#docker-compose-file"" rel=""nofollow noreferrer"">https://www.elastic.co/guide/en/elasticsearch/reference/7.5/docker.html#docker-compose-file</a> but it's not clear for me how to specify which node I want to connect???</p>
<p>Currently I have it like this:</p>
<pre><code>  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.10.1
    container_name: my-app-elasticsearch
    ports:
      - 9200:9200
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - elasticsearch-data:/usr/share/elasticsearch/data
    environment:
      - bootstrap.memory_lock=true
      - discovery.type=single-node
      - &quot;ES_JAVA_OPTS=-Xms512m -Xmx512m&quot;
</code></pre>
<p>on docker side, and in PHP I have such env params:</p>
<pre><code>ELASTICSEARCH_HOST=my-app-elasticsearch
ELASTICSEARCH_PORT=9200
</code></pre>
<p>I'm using to connect, but what should I specify as a host in case of multiple nodes, should each I simply specify separate <code>container_name</code> and use it as env variable???</p>
",https://stackoverflow.com/questions/68653466/functional-phpunit-tests-with-elsticsearch,"['php', 'symfony', 'elasticsearch']",304,False,1,0
Swift - Floating-point values as keys in a Dictionary?,"<p>Yes, I've done my research, and the closest page I could find to my question is:
<a href=""https://stackoverflow.com/questions/23721230/float-values-as-dictionary-key"">this page</a> and it is not in the least helpful.</p>
<p>That said, <strong>is it safe (reliable) to use floating-point values as keys in a <em><strong>Swift</strong></em> Dictionary</strong> ? Specifically, <strong>CGFloat</strong>, which the Apple docs say is actually a Double on 64-bit systems.</p>
<p><strong>P.S. (This is important) - My CGFloat values will <em>always</em> end with .0 or .5 as fractional parts. Examples - 13, 13.5, 14, 14.5, etc. Will this make a difference to the reliability of such Dictionary lookups ?</strong></p>
<pre class=""lang-swift prettyprint-override""><code>var dictionary: [CGFloat: MyObject] = [:]

...

// Could this type of lookup fail ?
if let mappedObject = dictionary[13.5] {
   ...
}
</code></pre>
<p>I have a unique use case that requires mapping certain objects to these CGFloat values for quick lookups later.</p>
<p>I know from my experience in unit testing, that <strong>XCTAssertEqual</strong> sometimes fails when comparing two floating-point types, without the use of an &quot;<em>accuracy</em>&quot; parameter. So, I'm afraid that using CGFloats as keys will cause failed subsequent lookups as the keys passed in may be off by 0.0000000001 or something like that, because of the underlying representation of floating-point types.</p>
<p>Thank you.</p>
<hr />
<p><strong>EDIT</strong> - (Thanks @Sweeper) Yes, I did think of using Int keys by converting the CGFloat to Int using the following conversion:</p>
<pre class=""lang-swift prettyprint-override""><code>intKey = Int(lroundf(Float(cgFloatKey * 2.0))
</code></pre>
<p>But then, I'm concerned about this ^ conversion (which has to be done on each lookup) requiring enough overhead to make it not worth it.</p>
<p>I might be totally wrong here and maybe these operations are lightning-fast. Can anyone comment on the efficiency of such an operation every single time a lookup is performed ?</p>
",https://stackoverflow.com/questions/68435629/swift-floating-point-values-as-keys-in-a-dictionary,"['swift', 'dictionary', 'floating-point']",281,True,1,2
Potiential data loss with using InMemoryMessageDataRepository in production with MassTransit?,"<p>We are hoping to convert to mass transit, but due to the size of the data we need to store in the message data repository, we are needing to keep it in memory. The data is sometimes over 15GB, and the SQL query to fetch it takes up to 300 seconds. We don't want to have to fetch the data potentially 100s of times (which is how the consumers would be logically broken up). We need to continue to fetch it from sql once and keep it in memory, or performance will be crippled. We would ultimately like to stop needing to have so much data in memory, but it is not something we could feasibly fix in the short term. We are hoping to convert to mass transit now though, as we see significant benefits in doing so, and the InMemoryMessageDataRepository seems like the only path that would allow us to do this right now. However, the documentation says only to use that for unit testing.</p>
<p>I am trying to find out if this is something we can use in production code. What are the pitfalls in using the InMemoryMessageDataRepository in production? I can't find much about this, other than this blog post, <a href=""https://kevsoft.net/2017/05/18/transferring-big-payloads-with-masstransit-and-azure-blob-storage.html"" rel=""nofollow noreferrer"">https://kevsoft.net/2017/05/18/transferring-big-payloads-with-masstransit-and-azure-blob-storage.html</a>,  which says</p>
<blockquote>
<p>It is however advised not to use in-memory storage due to potential data loss.</p>
</blockquote>
<p>Why would there be potential data loss? What is mass transit doing with the InMemoryMessageDataRepository that would make using it in production risky?</p>
",https://stackoverflow.com/questions/68182147/potiential-data-loss-with-using-inmemorymessagedatarepository-in-production-with,['masstransit'],31,False,0,0
How to add Google Mock to a project that already has Google Test?,"<p>I'm unit testing a Visual Studio project which has already been fully developed by the client. It came to us set up with Google test; it has many tests and we're adding more. I want to use Google Mock, which I know is part of Google Test, but I don't know how to get it to build correctly. Simply adding <code>#include &quot;gmock/gmock.h&quot;</code> doesn't work, so it's not simply actually included with gtest.</p>
<p>Currently, the project has a <code>dependencies</code> folder with a <code>vendor_google_test_release</code> folder, which as two subfolders: (the snippets are from the <code>vsproj</code> file)</p>
<ul>
<li><code>vendor_google_test_release\h</code> has what appears to be the contents of the GTest repo's <code>googletest\include</code> folder. The folder is included in the add'l include directories:</li>
</ul>
<pre class=""lang-xml prettyprint-override""><code>&lt;AdditionalIncludeDirectories&gt; ... $(ProjectDir)\..\..\dependencies\vendor_google_test_release\h\; ... &lt;/AdditionalIncludeDirectories&gt;
</code></pre>
<ul>
<li><code>vendor_google_test_release\lib\</code> has <code>GoogleTestLib.lib</code> &amp;&amp; <code>GoogleTestLib.pdb</code>, which I think they built themselves. The lib file is included in the project:</li>
</ul>
<pre class=""lang-xml prettyprint-override""><code> &lt;Link&gt;
  &lt;SubSystem&gt;Console&lt;/SubSystem&gt;
  &lt;GenerateDebugInformation&gt;true&lt;/GenerateDebugInformation&gt;
  &lt;AdditionalLibraryDirectories&gt;$(ProjectDir)..\..\dependencies\vendor_google_test_release\lib;$(ProjectDir)..\..\dependencies\vendor_google_mock_release\lib&lt;/AdditionalLibraryDirectories&gt;
  &lt;AdditionalDependencies&gt;kernel32.lib;user32.lib;gdi32.lib;winspool.lib;comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib;uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies);GoogleTestLib.lib;WS2_32.lib&lt;/AdditionalDependencies&gt;
&lt;/Link&gt;
</code></pre>
<p>I've added a similar <code>vendor_google_mock_release</code> folder with a similar <code>h</code> folder (containing the contents of <code>googlemock\include</code>) and I've added that folder to the &quot;additional include&quot; folders which is where the gtest folders are included in the project.</p>
<p>When I add <code>#include &quot;gmock/gmock.h&quot;</code> to my code, I get a zillion errors coming from the gmock files.</p>
<p>I imagine what I need to do is build the google mock library, but I don't know how to do that. I'm pretty new to C++ and VS. I've followed a tutorial to build Google Test in a static library project, and added Google Mock to that as well, but it's not finding files it's looking for.</p>
<p>This is from the <code>vsproj</code> file of the attempted mock/test project:</p>
<pre class=""lang-xml prettyprint-override""><code>  &lt;PropertyGroup Condition=&quot;'$(Configuration)|$(Platform)'=='Debug|Win32'&quot;&gt;
    &lt;LinkIncremental&gt;true&lt;/LinkIncremental&gt;
    &lt;IncludePath&gt;C:\Users\jtuzman\source\googletest-release-1.10.0\googletest\include;C:\Users\jtuzman\source\googletest-release-1.10.0\googlemock\include;$(IncludePath)&lt;/IncludePath&gt;
  &lt;/PropertyGroup&gt;
...
...
...
  &lt;ItemGroup&gt;
    &lt;ClCompile Include=&quot;..\..\..\googletest-release-1.10.0\googlemock\src\gmock-all.cc&quot; /&gt;
    &lt;ClCompile Include=&quot;..\..\..\googletest-release-1.10.0\googlemock\src\gmock-cardinalities.cc&quot; /&gt;
    &lt;ClCompile Include=&quot;..\..\..\googletest-release-1.10.0\googlemock\src\gmock-internal-utils.cc&quot; /&gt;
    &lt;ClCompile Include=&quot;..\..\..\googletest-release-1.10.0\googlemock\src\gmock-matchers.cc&quot; /&gt;
    &lt;ClCompile Include=&quot;..\..\..\googletest-release-1.10.0\googlemock\src\gmock-spec-builders.cc&quot; /&gt;
    &lt;ClCompile Include=&quot;..\..\..\googletest-release-1.10.0\googlemock\src\gmock.cc&quot; /&gt;
    &lt;ClCompile Include=&quot;..\..\..\googletest-release-1.10.0\googlemock\src\gmock_main.cc&quot; /&gt;
  &lt;/ItemGroup&gt;
</code></pre>
<p>It's probably a relatively simple answer, I imagine. Thanks for help.</p>
",https://stackoverflow.com/questions/65906001/how-to-add-google-mock-to-a-project-that-already-has-google-test,"['c++', 'visual-studio', 'googlemock']",389,False,0,0
mocha test with redis sinon stub throwing uncaught error outside suite,"<p>I'm having trouble getting Sinon to mock redis correctly for unit testing. The test cases are passing but Mocha is still crashing with a redis connection error every time, and I can't get to the bottom of it. After several days of working on this and combing through Stackoverflow I still haven't been able to solve it, so it's time to ask better minds than mine.</p>
<p>I started with a <code>server.ts</code> file that will export the app, so it can be loaded for final runtime configuration externally or loaded into a test suite:</p>
<pre><code>import express, { Application } from &quot;express&quot;;
import bodyParser from &quot;body-parser&quot;;
import auth from &quot;./routes/authRoutes&quot;;

const createServer = () =&gt; {
  const app: Application = express();

  app.use(bodyParser.json());

  app.get(&quot;/&quot;, (_req, res: Response, _next) =&gt; {
    res.json({
      message: &quot;Hello World&quot;,
    });
  });

  app.use(&quot;/auth&quot;, auth);

  return app;
};

export default createServer;
</code></pre>
<p>The authRoutes.ts file is fairly simple and I merged the validation middleware and endpoint logic for brevity:</p>
<pre><code>import { Router, Request, Response, NextFunction } from &quot;express&quot;;
import { check, validationResult } from &quot;express-validator&quot;;
import redisCache from &quot;../data/redis-cache&quot;;

const router = Router();

const postAuth = async (req: Request, res: Response, _next: NextFunction) =&gt; {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json(errors.array());
  }
  const sessionId = Math.random().toString();
  await redisCache.setAsync(sessionId, &quot;session1&quot;);
  return res.status(200).json({ sessionId: sessionId });
};

router.post(
  &quot;/login&quot;,
  [
    check(&quot;body&quot;).exists().withMessage(&quot;No Post Body&quot;),
  ],
  postAuth
);

export default router;
</code></pre>
<p>I also set up a <code>redis-cache.ts</code> file to promisify and export just the redis functions that I need:</p>
<pre><code>import redis from &quot;redis&quot;;

import { promisify } from &quot;util&quot;;

const client = redis.createClient({
  host: process.env.REDIS_HOST || &quot;localhost&quot;,
  port: process.env.REDIS_PORT ? +process.env.REDIS_PORT : 6379,
});

const getAsync = promisify(client.get).bind(client);
const setAsync = promisify(client.set).bind(client);

export default {
  getAsync,
  setAsync,
};
</code></pre>
<p>The test suite <code>index.spec.ts</code> is simple and sets up 3 tests:</p>
<pre><code>import chai, { expect } from &quot;chai&quot;;
import chaiHttp from &quot;chai-http&quot;;
import * as sinon from &quot;sinon&quot;;
import createServer from &quot;../src/server&quot;;
import redis from &quot;redis&quot;;

chai.use(chaiHttp);
chai.should();

describe(&quot;auth routes&quot;, function () {
  const mock = sinon.createSandbox();

  before(function () {
    mock.stub(redis, &quot;createClient&quot;).returns({
      set: (key: string, value: string, cb: (e: Error | null) =&gt; void) =&gt; {
        console.log(`mocked set, request: ${key} -&gt; ${value}`);
        return cb(null);
      },
      get: (key: string, cb: (e: Error | null) =&gt; void) =&gt; {
        console.log(`mocked get, request: ${key} `);
        return cb(null);
      },
      quit: (_cb: () =&gt; void) =&gt; {
        console.log(`mocked quit method`);
      },
    } as any);
  });

  after(function () {
    mock.restore();
  });

  describe(&quot;#GET/login&quot;, function () {
    it(&quot;responds with 404&quot;, function (done) {
      const app = createServer();
      chai
        .request(app)
        .get(&quot;/auth/login&quot;)
        .end((err: any, res: any) =&gt; {
          expect(err).to.be.null;
          expect(res.status).to.equal(404);
          done();
        });
    });
  });

  describe(&quot;#POST/login&quot;, function () {
    const app = createServer();
    function requestSend() {
      return chai.request(app).post(&quot;/auth/login&quot;);
    }

    describe(&quot;without body&quot;, function () {
      it(&quot;responds with 422&quot;, function (done) {
        requestSend().end(function (err: any, res: any) {
          if (err) return done(err);
          expect(res.status).to.equal(422);
          done();
        });
      });

      it(&quot;returns error when no post body sent&quot;, function (done) {
        requestSend().end(function (err: any, res: any) {
          if (err) return done(err);
          expect(res.body).to.be.a(&quot;array&quot;);
          const body = res.body as { msg: string }[];
          const messageIndex = body.findIndex(
            (el) =&gt; el.msg === &quot;No Post Body&quot;
          );
          expect(messageIndex).to.not.equal(-1);
          done();
        });
      });
    });
  });
});
</code></pre>
<p>Now I run the tests with Mocha and get the following:</p>
<pre><code>auth routes
    Uncaught error outside test suite
    #GET/login
      ✔ responds with 404
    #POST/login
      without body
        ✔ responds with 422 (45ms)
        ✔ returns error when no post body sent


  3 passing (217ms)
  1 failing

  1) auth routes
       Uncaught error outside test suite:
     Uncaught Redis connection to localhost:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
  Error: connect ECONNREFUSED 127.0.0.1:6379
</code></pre>
<p>As you can see, all the tests are passing but redis is still trying to connect outside of the test suite, and I can't figure out how to get around it. If I comment out the call to <code>await redisCache.setAsync</code> in my <code>authRoutes.ts</code> file and run the tests, all green and no errors.</p>
<p>I've spent hours googling and trying things with no luck and I'm pretty sure I'm missing something but I can't find it. Any help would be appreciated.</p>
<p>I followed <a href=""https://stnight99.hashnode.dev/stubbing-redis-with-sinonjs-cjyux7ch0000pj7s1i2s4g4ll"" rel=""nofollow noreferrer"">this blog post</a> to create a similar setup and it works, which leads me to believe this can be done and the error is on my part.</p>
",https://stackoverflow.com/questions/68309423/mocha-test-with-redis-sinon-stub-throwing-uncaught-error-outside-suite,"['typescript', 'express', 'redis', 'mocha.js', 'sinon']",663,True,0,1
Running Xunit tests on UI in appveyor,"<p>I am attempting to write <a href=""https://github.com/Fr33dan/NLog.Windows.Forms/blob/master/NLog.Windows.Forms.Tests/ToolStripItemTargetTests.cs"" rel=""nofollow noreferrer"">unit tests</a> for a library that invokes WinForms interface.</p>
<p>The library codes uses BeginInvoke using a Form handle thread safety. This means in my unit testing I need to wait for the for the invoked method to run before checking to see if it worked. After doing some research I thought I could accomplish this by calling Application.DoEvents() after my library call but before I check the result:</p>
<pre><code>logger.Fatal(&quot;Test&quot;);   // Send log
Application.DoEvents(); // Process events for BeginInvoke to run
Assert.Equal(&quot;Fatal NLog.UnitTests.Targets.ToolStripItemTargetTests Test&quot;, getText(testForm, testItem)); // Test if method worked.
</code></pre>
<p>That worked for the test of my first method call, but if I do a second test that one does not work. For some reason if I do TWO Application.DoEvents() calls then the second will work:</p>
<pre><code>logger.Error(&quot;Foo&quot;);
Application.DoEvents();
Application.DoEvents();
Assert.Equal(&quot;Error NLog.UnitTests.Targets.ToolStripItemTargetTests Foo&quot;, getText(testForm, testItem));
</code></pre>
<p>This already doesn't make sense to me because Application.DoEvents() documentation states &quot;Processes <em>all</em> Windows messages currently in the message queue&quot; . Unless I'm reading this wrong it shouldn't return the first call until all events have been processed meaning a second call should never be necessary. This shows there is something going on I don't understand. That said I would accept it as a workaround, but putting two calls in does not work for the 3rd-6th tests.</p>
<p>I've tried several other whacky ideas that were not provide enough information to be worth outlining here. You can see them looking at the commits in the above link.</p>
<p>I figure there has to be something about how unit tests are processed by appveyor is causing the WinForms thread/events to not process. How can I wait for BeginInvoke to process in such a context?</p>
",https://stackoverflow.com/questions/69363384/running-xunit-tests-on-ui-in-appveyor,"['c#', 'winforms', 'xunit', 'appveyor']",74,False,0,1
Consume OpenApi client .NET Core with Interface,"<p>Someone out there must have run into this already...</p>
<p>I created a WebApi solution with swagger implemented, full documentation, the whole 9 yards!</p>
<ul>
<li>When I run my web api solution, see the swagger output (and I've tested the endpoints, all working fine)</li>
<li>I can see the swagger definition: https://localhost:5001/swagger/v1/swagger.json</li>
</ul>
<p>Now, I want to consume this Api as a connected service on my web app.
So following every single tutorial online:</p>
<ul>
<li>I go to my webapp</li>
<li>right click on Connected Services</li>
<li>Add Connected Service</li>
<li>Add Service Reference &gt; OpenApi &gt; add Url, namespace &amp; class name
<a href=""https://i.stack.imgur.com/VxWxi.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/VxWxi.png"" alt=""enter image description here"" /></a></li>
</ul>
<p>That generates a partial class in my solution (MyTestApiClient)</p>
<pre><code>public parial class MyTestApiClient
{
   // auto generated code
}
</code></pre>
<p>Next step, inject the service in Startup.cs</p>
<pre><code>services.AddTransient(x =&gt;
{
   var client = new MyTestApiClient(&quot;https://localhost:5001&quot;, new HttpClient());
   return client;
});
</code></pre>
<p>Then, inject the class into some class where it's consumed and this all works</p>
<pre><code>public class TestService
{
    private readonly MyTestApiClient _client; // this is class, not an interface -&gt; my problem
    public TestService(MyTestApiClient client)
    {
        _client = client;
    }

    public async Task&lt;int&gt; GetCountAsync()
    {
        return _client.GetCountAsync();
    }
}
</code></pre>
<p>So everything up to here works. BUT, this generated OpenApi client doesn't have an interface which sucks for the purposes of DI and Unit Testing.</p>
<p>I got around this by creating a local interface IMyTestApiClient, added to the generated class (MyTestApiClient). I only have 1 endpoint in my WebApi so have to declare that on my interface.</p>
<pre><code>public parial class MyTestApiClient : IMyTestApiClient
{
   // auto generated code
}
</code></pre>
<pre><code>public interface IMyTestApiClient
{
   // implemented in generated MyTestApiClient class
   Task&lt;int&gt; GetCountAsync();
}
</code></pre>
<pre><code>services.AddTransient&lt;IMyTestApiClient, MyTestApiClient&gt;(x =&gt;
{
   IMyTestApiClient client = new MyTestApiClient(&quot;https://localhost:5001&quot;, new HttpClient());
   return client;
});
</code></pre>
<pre><code>public class TestService
{
    private readonly IMyTestApiClient _client; // now injecting local interface instead of the generated class - great success
    public TestService(IMyTestApiClient client)
    {
        _client = client;
    }

    public async Task&lt;int&gt; GetCountAsync()
    {
        return _client.GetCountAsync();
    }
}
</code></pre>
<p>But this is a bad approach because it makes me manually create an interface and explicitly declare the methods I want to consume. Furthermore, every time my Api gets updated, I will have to tweak my local interface.</p>
<p><strong>So question time:</strong>
How can I add an OpenApi Service Reference that automagically also generates an interface as well?
Thanks in advance for any help getting to a viable solution.</p>
",https://stackoverflow.com/questions/67235046/consume-openapi-client-net-core-with-interface,"['.net-core', 'dependency-injection', 'swagger', 'openapi', 'openapi-generator']",1282,True,0,1
how to properly initialize firebase functions test using cloud function?,"<p>I am using</p>
<ul>
<li>Node 14</li>
<li>firebase-functions-test: 0.2.3</li>
<li>firebase-admin: 9.6.0</li>
<li>firebase-functions: 3.13.2</li>
<li>firebase tools: 9.8.0</li>
</ul>
<p>so I want to perform unit testing for my firestore trigger function using firebase cloud function, I read the steps from <a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">the documentation in here</a>.</p>
<p>I want to perform unit test using <code>Firebase Emulator</code>. so I assume I will initialize the SDK in offline mode. <a href=""https://firebase.google.com/docs/functions/unit-testing#offline-mode"" rel=""nofollow noreferrer"">the documentation</a> said that</p>
<blockquote>
<p>If you would like to write completely offline tests, you can
initialize the SDK without any parameters:</p>
</blockquote>
<p>so I initialize it like this</p>
<pre><code>import * as firebase from &quot;firebase-functions-test&quot;;

const test = firebase();
const wrapped = test.wrap(myFunctions.onCreate);

// rest of my test code
</code></pre>
<p>but when I run the test, I have this error:</p>
<blockquote>
<p>Error: Could not load the default credentials. Browse to
<a href=""https://cloud.google.com/docs/authentication/getting-started"" rel=""nofollow noreferrer"">https://cloud.google.com/docs/authentication/getting-started</a> for more
information.</p>
</blockquote>
<p>so even though I will use Firebase emulator (offline), it seems I need to provide the credential, which is the step if online mode is used, like explained from <a href=""https://firebase.google.com/docs/functions/unit-testing#online-mode"" rel=""nofollow noreferrer"">documentation in here</a></p>
<p>so I initialize the SDK like this</p>
<pre><code>import * as firebase from &quot;firebase-functions-test&quot;;

const test = firebase({
    databaseURL: &quot;https://xxx-b843e.firebaseio.com&quot;,
    projectId: &quot;xxx-b843e&quot;,
}, &quot;../../../service-account.json&quot;);

const wrapped = test.wrap(myFunctions.onCreate);

// rest of my test code
</code></pre>
<p>but when I run the test, I have another error</p>
<blockquote>
<p>{&quot;severity&quot;:&quot;WARNING&quot;,&quot;message&quot;:&quot;Warning, FIREBASE_CONFIG and
GCLOUD_PROJECT environment variables are missing. Initializing
firebase-admin will fail&quot;}</p>
<p>Error: The file at ../../../service-account.json does not exist, or it
is not a file. ENOENT: no such file or directory, lstat
'/Users/xxx/Documents/service-account.json'</p>
</blockquote>
<p>the service account json file doesn't exist? I believe I have set the path correctly like this</p>
<p><a href=""https://i.stack.imgur.com/elqET.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/elqET.png"" alt=""enter image description here"" /></a></p>
<p>in fact, I use intellisense to guide me to service-account.json path
<a href=""https://i.stack.imgur.com/Vju5G.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Vju5G.png"" alt=""enter image description here"" /></a></p>
<p>the service-account.json file is like the image below, i get it from firebase project overview --&gt; project settings --&gt; service accounts --&gt; generate new private key</p>
<p><a href=""https://i.stack.imgur.com/Q3n75.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Q3n75.png"" alt=""enter image description here"" /></a></p>
<p>what should I do if I want to initialize firebase functions test SDK in Firebase emulator?</p>
",https://stackoverflow.com/questions/66964566/how-to-properly-initialize-firebase-functions-test-using-cloud-function,"['node.js', 'firebase', 'google-cloud-firestore', 'google-cloud-functions']",1772,True,5,3
Why does my Theory unit test say &quot;test has multiple result outcomes&quot; in the test explorer summary?,"<p>Normally, when I decorate an XUnit test method with <code>[Theory]</code> and use attributes like <code>[InlineData]</code> or <code>[ClassData]</code> to pass multiple sets of parameters into the test, the Visual Studio test explorer window lets me expand the test method to see each set of parameters as a test in its own right.</p>
<p>However, I have one test which is behaving differently - it shows as a single test in the tree view of projects, namespaces, classes, test methods etc, however in the test detail summary pane it says &quot;Test has multiple result outcomes&quot;, which can be a mixture of passes and fails. This makes it more difficult to see exactly what has passed or failed, and also prevents me from debugging a test with just one set of parameters.</p>
<p>Here is my unit test:</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using Xunit;

public class MyTestClass
{
    [Theory]
    [ClassData(typeof(MyTestData1))]
    public void MyTestMethod1(Color col, int red, int green, int blue)
    {
        Assert.Equal(red, col.R);
        Assert.Equal(green, col.G);
        Assert.Equal(blue, col.B);
    }
}
</code></pre>
<p>The class supplying my test data:</p>
<pre><code>public class MyTestData1 : IEnumerable&lt;object[]&gt;
{
    public MyTestData1()
    {
        this.Data = new List&lt;object[]&gt;();
        this.Data.Add(new object[] { Color.FromArgb(255, 0, 0), 255, 0, 0 });
        this.Data.Add(new object[] { Color.FromArgb(0, 255, 0), 0, 255, 0 });
        this.Data.Add(new object[] { Color.FromArgb(0, 0, 255), 0, 0, 255 });
    }

    public List&lt;object[]&gt; Data { get; }
    public IEnumerator&lt;object[]&gt; GetEnumerator() =&gt; this.Data.GetEnumerator();
    IEnumerator IEnumerable.GetEnumerator() =&gt; this.GetEnumerator();
}
</code></pre>
<p>Yes, it's a unit test for <code>System.Drawing.Color</code>, and I shouldn't need to write my own unit tests for that because it's maintained by Microsoft and so they're responsible for unit testing it. However it works nicely as a minimum reproducible example, as the fact that I'm using that particular struct in the parameters for my test seems to be the only difference between tests which behave as I'd expect in the test explorer and tests which don't. In the actual project where I hit this issue I'm using arrays of <code>Color</code> as parameters, but the issue seems to be the same.</p>
<p>What do I need to do to allow me to expand this test in the test explorer, so that I can run/debug it with just one of the sets of parameters?</p>
",https://stackoverflow.com/questions/69106145/why-does-my-theory-unit-test-say-test-has-multiple-result-outcomes-in-the-test,"['c#', 'unit-testing', 'xunit.net']",935,True,2,1
Correct way to retry HttpClient requests with Polly,"<p>I have an Azure function that makes a http call to a webapi endpoint. I'm following this example <a href=""https://github.com/stevejgordon/PollyLoggingContextSample"" rel=""nofollow noreferrer"">GitHub Polly RetryPolicy</a> so my code has a similar structure. So in Startup.cs i have:</p>
<pre><code>builder.Services.AddPollyPolicies(config); // extension methods setting up Polly retry policies
builder.Services.AddHttpClient(&quot;MySender&quot;, client =&gt;
{
    client.BaseAddress = config.SenderUrl;
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));
});
</code></pre>
<p>My retry policy looks like this:</p>
<pre><code>public static class PollyRegistryExtensions
{
    public static IPolicyRegistry&lt;string&gt; AddBasicRetryPolicy(this IPolicyRegistry&lt;string&gt; policyRegistry, IMyConfig config)
    {
        var retryPolicy = Policy
            .Handle&lt;Exception&gt;()
            .OrResult&lt;HttpResponseMessage&gt;(r =&gt; !r.IsSuccessStatusCode)
            .WaitAndRetryAsync(config.ServiceRetryAttempts, retryCount =&gt; TimeSpan.FromMilliseconds(config.ServiceRetryBackOffMilliSeconds), (result, timeSpan, retryCount, context) =&gt;
            {
                if (!context.TryGetLogger(out var logger)) return;

                logger.LogWarning(
                    $&quot;Service delivery attempt {retryCount} failed, next attempt in {timeSpan.TotalMilliseconds} ms.&quot;);

            })
            .WithPolicyKey(PolicyNames.BasicRetry);

        policyRegistry.Add(PolicyNames.BasicRetry, retryPolicy);

        return policyRegistry;
    }
}
</code></pre>
<p>My client sender service receives <code>IReadOnlyPolicyRegistry&lt;string&gt; policyRegistry</code> and <code>IHttpClientFactory clientFactory</code> in its constructor. My code calling the client is the following:</p>
<pre><code>var jsonContent =  new StringContent(JsonSerializer.Serialize(contentObj),
    Encoding.UTF8,
    &quot;application/json&quot;);

HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, &quot;SendEndpoint&quot;)
{
    Content = jsonContent
};

requestMessage.Headers.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, authToken);
requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));

var retryPolicy = _policyRegistry.Get&lt;IAsyncPolicy&lt;HttpResponseMessage&gt;&gt;(PolicyNames.BasicRetry)
                  ?? Policy.NoOpAsync&lt;HttpResponseMessage&gt;();

var context = new Context($&quot;GetSomeData-{Guid.NewGuid()}&quot;, new Dictionary&lt;string, object&gt;
{
    { PolicyContextItems.Logger, _logger }
});

var httpClient = _clientFactory.CreateClient(&quot;MySender&quot;);

var response = await retryPolicy.ExecuteAsync(ctx =&gt;
    httpClient.SendAsync(requestMessage), context);
</code></pre>
<p>When I attempt to test this with no endpoint service running then for the first retry attempt, the retry handler is fired and my logger records this first attempt. However, on the second retry attempt i get a error message saying:</p>
<blockquote>
<p>The request message was already sent. Cannot send the same request
message multiple times</p>
</blockquote>
<p>I know that other people have encountered a similar problem (see <a href=""https://stackoverflow.com/questions/19260060/retrying-httpclient-unsuccessful-requests"">Retrying HttpClient Unsuccessful Requests</a> and the solution seems to be do what i'm doing (i.e. use <code>HttpClientFactory</code>). However, i DON'T get this problem if i define my retry policy as part of the configuration in Startup as so:</p>
<pre><code>builder.Services.AddHttpClient(&quot;MyService&quot;, client =&gt;
    {
        client.BaseAddress = config.SenderUrl;
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));
    }).AddPolicyHandler(GetRetryPolicy());

static IAsyncPolicy&lt;HttpResponseMessage&gt; GetRetryPolicy()
{
    return HttpPolicyExtensions
        .HandleTransientHttpError()
        .OrResult(msg =&gt; msg.StatusCode == System.Net.HttpStatusCode.NotFound)
        .WaitAndRetryAsync(3, retryAttempt =&gt; TimeSpan.FromMilliseconds(1000));
}
</code></pre>
<p>and simply call my service as so:</p>
<pre><code>var response = await httpClient.SendAsync(requestMessage);
</code></pre>
<p>BUT doing it this way i lose the ability to pass my logger in the retry policy context (which is the whole reason i'm injecting in <code>IReadOnlyPolicyRegistry&lt;string&gt; policyRegistry</code> - I <strong>can not</strong> do this at startup). Another benefit is for unit testing - i can simply inject in the same collection with the same policy without copying and pasting a whole bunch of code and making the unit test redundant since i'm no longer testing my service. Having the policy defined in the startup makes this impossible. So my question is, is there a way to not get this duplicate request error using this approach ?</p>
",https://stackoverflow.com/questions/66553465/correct-way-to-retry-httpclient-requests-with-polly,"['c#', '.net-core', 'azure-functions', 'polly']",17903,True,2,2
"C++ Makefile, is it possible to factorize it even more?","<p>I have a project for school and I want to write a Makefile, I have seen some examples of using Makefile with multiple source directories and multiple executables but still could not implement it properly to my Makefile.</p>
<p><strong>PS: I'm using doctest for the unit testing (and I can't change it).</strong></p>
<p>Here is the project structure (and I can't change it):</p>
<pre><code>.
├── bin
├── build
├── extern
│   └── doctest.h
├── include
│   ├── file1.hpp
│   └── file2.hpp
├── src
│   ├── file1.cpp
│   └── file2.cpp
├── tests
│   ├── file1-test.cpp
│   └── file2-test.cpp
└──  Makefile
</code></pre>
<p>I have the following directories:</p>
<ul>
<li><p><code>bin</code>: for all the executables.</p>
</li>
<li><p><code>build</code>: for all the objects (<code>.o</code>).</p>
</li>
<li><p><code>extern</code>: for the doctest header (this is where I would have stored any other library)</p>
</li>
<li><p><code>include</code>: for all the headers (<code>.hpp</code>).</p>
</li>
<li><p><code>src</code>: for all the classes (<code>.cpp</code>).</p>
</li>
<li><p><code>tests</code>: for all the unit tests (also <code>.cpp</code>)</p>
</li>
</ul>
<p>You can see <code>file1.cpp</code> as a class, <code>file1.hpp</code> as the class header and <code>file1-test.cpp</code> as the unit tests for the class.</p>
<p>Here is my Makefile:</p>
<pre><code>BIN_DIR := bin/
BUILD_DIR := build/
EXTERN_DIR := extern/
INCLUDE_DIR := include/
SOURCE_DIR := src/
TESTS_DIR := tests/
DEP_DIR := .dep/

DEPENDS := $(patsubst %.o, $(BUILD_DIR)$(DEP_DIR)%.d, $(notdir $(wildcard $(BUILD_DIR)*.o)))

EXE := $(addprefix $(BIN_DIR), file1-test file2-test)

OBJS_1 := $(addprefix $(BUILD_DIR), file1.o)
OBJS_2 := $(addprefix $(BUILD_DIR), file1.o file2.o)

CXX := clang++
CXXFLAGS := -Wall -std=c++11 -g -O3 -I$(INCLUDE_DIR) -I$(EXTERN_DIR)

vpath %.cpp $(SOURCE_DIR) $(TESTS_DIR)

.PHONY: all clean

all: $(EXE)

$(BUILD_DIR) $(BIN_DIR) $(BUILD_DIR)$(DEP_DIR):
    @mkdir -p $@

$(BUILD_DIR)%.o: %.cpp | $(BUILD_DIR) $(BUILD_DIR)$(DEP_DIR)
    @$(CXX) $(CXXFLAGS) -MMD -MP -MF $(BUILD_DIR)$(DEP_DIR)$(notdir $(basename $@).d) -c $&lt; -o $@

$(BIN_DIR)%: $(BUILD_DIR)%.o | $(BIN_DIR)
    @$(CXX) -o $@ $^

$(BIN_DIR)file1-test: $(OBJS_1)
$(BIN_DIR)file2-test: $(OBJS_2)

.PRECIOUS: $(BUILD_DIR)%.o

-include $(DEPENDS)

clean:
    -rm -rf $(BIN_DIR) $(BUILD_DIR)
</code></pre>
<p><strong>So my questions are:</strong></p>
<ul>
<li><p>Is my Makefile following good practices ?</p>
</li>
<li><p>Is it optimized ? If no, how can I make it even better ?</p>
</li>
<li><p>For every new executable I've to add a <code>OBJS_X</code> variable and a target <code>$(BIN_DIR)fileX-test: $(OBJS_X)</code>, can i get rid of it ? If yes can someone write me some generic rule, so I don't have to specify a variable and a target every time I want a new executable.</p>
</li>
<li><p>If I want to compile only one executable I have to use <code>make bin/fileX-test</code>. Is it possible to run only <code>make fileX-test</code> instead of <code>make bin/fileX-test</code> (but still building it in the <code>bin</code> directory) ? I tried to implement a rule like this: <code>fileX-test: $(BIN_DIR)fileX-test</code> but it's not working as I want, at the very end of the compilation it starts executing builtin rules and I don't know why. Can someone explain ?</p>
</li>
</ul>
<p><strong>Final answer:</strong></p>
<p>This is what I considere a good answer, if it can help someone later:</p>
<pre><code>BIN_DIR := bin/
BUILD_DIR := build/
EXTERN_DIR := extern/
INCLUDE_DIR := include/
SOURCE_DIR := src/
TESTS_DIR := tests/
DEP_DIR := $(BUILD_DIR).dep/

CXX := g++
CXXFLAGS := -Wall -std=c++11 -g -O3 -I$(INCLUDE_DIR) -I$(EXTERN_DIR)
DEPFLAGS := -MMD -MP -MF $(DEP_DIR)

vpath %.cpp $(SOURCE_DIR) $(TESTS_DIR)

file1-test_OBJECTS := $(addprefix $(BUILD_DIR), file1.o)
file2-test_OBJECTS := $(addprefix $(BUILD_DIR), file1.o file2.o)

EXE := $(patsubst %_OBJECTS, %, $(filter %_OBJECTS, $(.VARIABLES)))

.PHONY: all keep help check clean $(EXE)

all: $(EXE:%=$(BIN_DIR)%)

$(foreach E, $(EXE), $(eval $(BIN_DIR)$E: $($E_OBJECTS)))
$(foreach E, $(EXE), $(eval $E: $(BIN_DIR)$E ;))

$(BUILD_DIR) $(BIN_DIR) $(DEP_DIR):
    @mkdir -p $@

$(BUILD_DIR)%.o: %.cpp | $(BUILD_DIR) $(DEP_DIR) $(BIN_DIR)
    @$(CXX) $(CXXFLAGS) $(DEPFLAGS)$(@F:.o=.d) -c $&lt; -o $@

$(BIN_DIR)%: $(BUILD_DIR)%.o
    @$(CXX) -o $@ $^

-include $(wildcard $(DEP_DIR)*.d)

keep: $(EXE:%=$(BUILD_DIR)%.o)

clean:
    -@rm -rf $(BIN_DIR)* $(BUILD_DIR)* $(DEP_DIR)*
</code></pre>
",https://stackoverflow.com/questions/67375725/c-makefile-is-it-possible-to-factorize-it-even-more,"['c++', 'makefile', 'project-structure']",278,True,1,2
Unit test fails in debug without reaching first statement,"<p>I've been working on a personal project as of late, and to save time on testing, I wrote some unit tests. Now I've finished some methods I wanted to test, so I decided to run the test.</p>
<p>All tests with body fail, even before reaching the first statement. This happens for the simple reason that Visual Studio can't find file or assembly System.Runtime or one of it's dependensies. For some reason, the tests without body all succeded, but after implementing their bodies, same error message.</p>
<p>So I went to have a look in the references. Of course it was nowhere to be found. I tried to add it, but I can't add System.Runtime itself, only System.Runtime.SomeDeeperLevel.</p>
<p>Then I went to find it on learn.microsoft.com, but I can only download .NET there, not this package itself. Now I'm wondering, did something go wrong during the installation of VS and do I need to reinstall Visual Studio to solve this? Or is there some easier method to resolve this issue.</p>
<p>Obviously I could also chose to copy the test into something like Program.cs and test it via that method, but I think that looks disguisting.</p>
<p>Thanks in advance for any help.</p>
<p>PS. I just noticed that the unit tests have references, where my .NET 5.0 code has dependensies. I don't expect this to be the issue, but if this means I can't use the .NET 4.7.2 framework for unit testing (which is the most recent version I could find installed), then please refer to what kind of unit test system I could install to get it compatible.</p>
",https://stackoverflow.com/questions/68770610/unit-test-fails-in-debug-without-reaching-first-statement,"['.net', 'unit-testing']",78,False,1,0
Dependent unit tests and returning Task&lt;T&gt; from a unit test,"<p>How does MSTest framework handle unit tests that are dependent upon other unit tests? I'm testing a REST API and have spent quite some time trying to understand the big picture. The following questions came up during this journey:</p>
<ol>
<li>Should we write test methods that call other test methods? Is it somehow against the idea of <em>unit</em> testing? Or should unit tests be completely isolated from each other?</li>
<li>If isolated, what do we do when certain api endpoint requires input that can only be fetched by calling another API endpoint (for which a test already exists)? For example, the endpoint <code>GetMembers</code> endpoint requires authentication token which can only be obtained by calling <code>Login</code> endpoint. A separate test exists for each endpoint. Is it fair to call <code>TestLogin</code> method from <code>TestGetMembers</code>, or should I repeat the entire code of <code>TestLogin</code> inside <code>TestGetMembers</code> (or write a function to share code for that matter)?</li>
<li>Where should I keep the login token since it will be required by all subsequent tests. It looks like MSTest creates a new instance of the test class for each test method, so my global variables get lost. Is it okay to declare <code>static</code> variables to hold such values?</li>
<li>What about <code>async</code> tests? My research shows that an <code>async</code> test can return <code>Task</code> but not <code>Task&lt;T&gt;</code>. Visual Studio Test Explorer does not list any test methods that return <code>Task&lt;T&gt;</code> and trying to run them manually (e.g. by right-clicking inside the method and choosing <code>Run Test</code>) finishes without actually running the test method. Is there such a limitation? If yes, how can I return value from a async test method that will be consumed by another test method?</li>
</ol>
",https://stackoverflow.com/questions/69053143/dependent-unit-tests-and-returning-taskt-from-a-unit-test,"['c#', 'unit-testing', 'mstest']",253,False,1,1
Testing ARM-Templates with ARM-TTK,"<p>I am trying to use ARM-TTK for doing unit testing for my ARM templates and ensuring that the templates follow uniformity. I am only running few tests.
We are using Azure Repos as our VCS</p>
<p>I have incorporated this in my AZDO pipeline as a pre PR merge task which is in the form of a branch policy, so that before a PR is merged, these tests will run and validate all the templates that are pushed to the main branch.
But the problem is, the tests are returning false positives even though there are no issues with the JSON files.
According to this link <a href=""https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/test-toolkit"" rel=""nofollow noreferrer"">ARM-TTK</a> it seems there has to be one azuredeploy.json or maintemplate.json and all the other files are tested as linked templates.
I have JSON files with other names pertaining to the function of the template like win_vm_deploy.json, function_app-deploy.json etc etc.
It is not possible for me to have all the files as linked templates to the azuredeploy.json or maintemplate.json as mentioned in the URL.</p>
<p>I would also like to run the selected tests against the files loaded in the repo automatically and not specify a particular file to run the tests against.</p>
<p>So does that mean that in my situation i won't be able to use the ARM-TTK and utilize the unit tests?</p>
<p>What is the best way to check my templates in my particular folder and utilize some of the unit tests that i choose from ARM-TTK, but then i don't have to have a main template and the other templates as linked templates.</p>
<p>Appreciate any help</p>
",https://stackoverflow.com/questions/69336107/testing-arm-templates-with-arm-ttk,"['azure', 'azure-devops', 'azure-pipelines', 'azure-powershell', 'azure-rm-template']",241,False,1,1
how to create a hierarchy on the page object model classes?,"<p>This might be a very strange question, but I am not even sure how to title this question. I am quite new to C# and Selenium. I have done some coding on it and I'm quite comfortable creating a (quitemessy) test that runs how I want to. I would like to organize my tests a bit better.</p>
<p>I will use this as an example to what I want to achieve:</p>
<p>On a login page lets say I have a button &quot;Log In&quot; and that button opens a page that let's me put my credentials &quot;Username&quot; and &quot;Password&quot;.</p>
<p>Lets say i would like to program it like this: have the landing page with the login with all the elements of that page, and one only for the elements of the login page.</p>
<p>And the test would be something like this:</p>
<pre><code>LandingPage.Login.Click();
LandingPage.Login.Username(&quot;username&quot;);
LandingPage.Login.Password(&quot;password&quot;;
LandingPage.Login.LoginBtn.Click();
</code></pre>
<p>and then after the Log In is completed i could have something like:</p>
<pre><code>Database. (everything in the database page). (actions or areas i can navigate to)
</code></pre>
<p>There would be some hierarchy on this classes. Username belongs to login, login belongs to LandingPage, and so on.
I have seen this type of coding being used. I'm starting to create a &quot;page object model&quot; for my test and would like to separate it so then i can use the way I showed above. The &quot;<code>LandinPage.cs</code>&quot; would have the login link as well as other elements and the &quot;<code>Login.cs</code>&quot; would have the username field and the password and the login button, along side other elements not relevant now.</p>
<p>I also understand that this is not really for unit testing but more integration testing.</p>
<p>My question is, is there a name for this kind of formatting? I am struggling to find such so I can start my studying there.</p>
",https://stackoverflow.com/questions/67403636/how-to-create-a-hierarchy-on-the-page-object-model-classes,"['c#', 'selenium', 'pageobjects']",553,False,1,3
Unit Testing WeakReference,"<p>It seems the following code to unit test <code>WeakReference</code> does not work correctly/reliably:</p>
<pre><code>object realObject = new object();
WeakReference weakReference = new WeakReference(realObject);
Assert.NotNull(weakReference.Target);
realObject = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Assert.Null(weakReference.Target);
</code></pre>
<p>The testing is run targeting both net461 and net5.0, for both DEBUG and RELEASE mode. The best result:</p>
<ul>
<li><p>Targeting net461: the above code runs successfully, for both DEBUG and RELEASE mode.</p>
</li>
<li><p>Targeting net5.0: the above code fails for both DEBUG and RELEASE mode at first. After reading this post (<a href=""https://stackoverflow.com/questions/69616548/garbage-collection-behaviour-difference-between-netframework-4-8-and-net-5"">Garbage collection behaviour difference between .NetFramework 4.8 and .Net 5</a>) it works running in RELEASE mode by adding <code>&lt;TieredCompilation&gt;false&lt;/TieredCompilation&gt;</code> to <code>.csproj</code>.</p>
</li>
</ul>
<p>So the problem narrows down to <strong>targeting net5.0 DEBUG mode</strong>.</p>
<p>I also came across the following posts but it seems they're not very helpful mostly because they're out-of-date:</p>
<ul>
<li><a href=""https://stackoverflow.com/questions/15062308/unit-testing-code-with-weakreference"">Unit Testing Code with WeakReference</a></li>
<li><a href=""https://stackoverflow.com/questions/5912797/testing-verifying-a-weakreference"">Testing/Verifying a WeakReference</a></li>
</ul>
<p>Worth to mention the answer from @Eric Lippert for <a href=""https://stackoverflow.com/questions/37462378/why-c-sharp-garbage-collection-behavior-differs-for-release-and-debug-executable"">Why C# Garbage Collection behavior differs for Release and Debug executables?</a> says: You <strong>absolutely cannot</strong> rely on the garbage collector having <strong>any particular behaviour whatsoever</strong> with respect to the lifetime of a local, which suggests testing a WeakReference cannot be done reliably.</p>
<p>Edit: More information about the context of why using a <code>WeakReference</code>:</p>
<p>I'm developing a framework providing class <code>Entity&lt;T&gt;</code> and <code>Record&lt;T&gt;</code> similar to <code>System.Data.DataRow</code> and <code>System.Data.DataRowView</code>, with the most significance that the prior one is strongly typed. Entity is the model provides its own event to notify changes, <code>Record&lt;T&gt;</code> is a viewmodel that wraps <code>Entity&lt;T&gt;</code> to translate the change event into <code>INotifyPropertyChanged</code> plus other things such as databinding, validations, etc. <code>Entity&lt;T&gt;</code> should not aware the existence of <code>Record&lt;T&gt;</code>. To avoid memory leak, <code>Record&lt;T&gt;</code> should be GC reclaimed when only Entity is still referenced.</p>
<p>The example code for the event hookup:</p>
<p><code>IEntityListener</code> Implemented by <code>Record&lt;T&gt;</code> class:</p>
<pre><code>internal interface IEntityListener
{
    void OnFieldUpdated(FieldUpdatedEventArgs e);
}
</code></pre>
<p><code>WeakEntityListner</code> to do the event hookup:</p>
<pre><code>internal sealed class WeakEntityListener
{
    private readonly WeakReference&lt;IEntityListener&gt; _weakListener;
    private readonly Entity _entity;

    internal WeakEntityListener(Entity entity, IEntityListener listener)
    {
        _entity = entity;
        _weakListener = new (listener);
        _entity.FieldUpdated += OnFieldUpdated;
    }

    private void OnFieldUpdated(object? sender, FieldUpdatedEventArgs e)
    {
        if (_weakListener.TryGetTarget(out var listener))
            listener.OnFieldUpdated(e);
        else
            CleanUp();
    }

    private void CleanUp()
    {
        _entity.FieldUpdated -= OnFieldUpdated;
    }
}
</code></pre>
<p>I would like to have method <code>OnFieldUpdated</code> and <code>CleanUp</code> fully covered by unit test.</p>
",https://stackoverflow.com/questions/70060061/unit-testing-weakreference,"['c#', '.net', '.net-core', 'garbage-collection', 'weak-references']",291,True,1,3
Unit Testing firebase_auth and firestore,"<p>I am trying to setup flutter scripts for testing my classes that interface with my firestore database.</p>
<p>My current struggles are:</p>
<ul>
<li>It seems that in order to use firebase_auth, I have to have a widget tree. I'm new to both flutter and firebase I am slowly building up my expertise by building classes one at a time, writing tests for them and then moving to the next class. Requiring the widget tree means I can't test the authorization logic independent of the GUI (e.g. What happens if I call signOut twice in my code even though the GUI logic only lets you press the button once?).</li>
<li>Mocking is insufficient. In order to mock, you need to know the expected behaviour for the tests to be representative. I've spent a lot of time trying to troubleshoot issues with futures, changing signed in states, and incorrect data formats. If I had written mocks, they wouldn't have matched how the real functions actually behave.</li>
<li>Mocking doesn't help me as I am also learning about the security rules for the database. I've definitely got code that works with lax security rules but there's something wrong with the current security rules.</li>
</ul>
<p>Is there any way to write unit/integration tests for firebase_auth or firestore without mocking? I'm even happy using a local emulator/export of my database if that's a thing that's even possible.</p>
<p>Here are a number of the articles I have reviewed that are not what I am looking for:</p>
<ul>
<li><a href=""https://bendyworks.com/blog/a-month-of-flutter-mocking-firebase-auth-in-tests"" rel=""noreferrer"">A month of Flutter: mocking Firebase Auth in tests</a></li>
<li><a href=""https://stackoverflow.com/questions/64476408/setup-unit-test-for-firebase-user-authentication-with-mockito"">Setup Unit test for Firebase User authentication with Mockito</a></li>
<li><a href=""https://stackoverflow.com/questions/56612501/how-to-create-integration-test-for-app-with-firebase-auth"">How to create integration test for app with Firebase Auth?</a></li>
<li><a href=""https://www.youtube.com/watch?v=225MFHjQokw"" rel=""noreferrer"">Flutter Testing [4] - Firebase Auth App - Unit Testing</a></li>
<li><a href=""http://Mocking%20In%20Integration%20Tests%20with%20Flutter"" rel=""noreferrer"">Mocking In Integration Tests with Flutter</a></li>
<li><a href=""https://utkarshkore.medium.com/writing-unit-tests-in-flutter-with-firebase-firestore-72f99be85737"" rel=""noreferrer"">Writing Unit Tests in Flutter with Firebase Firestore</a></li>
<li><a href=""https://github.com/flutter/flutter/issues/15245"" rel=""noreferrer"">Tutorial how to test with firebase #15245</a></li>
</ul>
",https://stackoverflow.com/questions/68745007/unit-testing-firebase-auth-and-firestore,"['firebase', 'flutter', 'unit-testing', 'firebase-authentication', 'flutter-test']",610,False,6,1
How to setup Gitlab CI E2E tests using Multiple dockers,"<p>I am a bit lost with the automated testing using Gitlab CI. I hope I can explain my problem so somebody can help me. I'll try to explain the situation first, after which I'll try to ask a question (which is harder than it sounds)</p>
<h1>Situation</h1>
<h3>Architecture</h3>
<ol>
<li>React frontend with Jest unit tests and Cypress e2e tests</li>
<li>Django API server 1 including a Postgres database and tests</li>
<li>Django API server 2 with a MongoDB database (which communicates with the other API</li>
</ol>
<h3>Gitlab</h3>
<p>For the 2 API's, there is a <code>Docker</code> and a <code>docker-compose</code> file. These work fine and are set up correctly.</p>
<p>We are using GitLab for the CI/CD, there we have the following stages in this order:</p>
<ol>
<li><em>build:</em> where dockers for 1, 2 &amp; 3 are build separate and pushed to private-registry</li>
<li><em>Test:</em> Where the unit testing and e2e test (should) run</li>
<li><em>Release:</em> where the docker images are released</li>
<li><em>Deploy:</em> Where the docker images are deployed</li>
</ol>
<h1>Goal</h1>
<p>I want to set up the GitLab CI such that it runs the cypress tests. But for this, all build dockers are needed. Currently, I am not able to use all dockers together when performing the end-to-end tests.</p>
<h1>Problem</h1>
<p>I don't really get how I would achieve this.</p>
<ul>
<li>Can I use the dockers that are built in the build stage for my e2e tests and can somebody give me an example of how this would be achieved? (By running the build docker containers as a service?)</li>
<li>Do I need one Docker-compose file including all dockers and databases?</li>
<li>Do I even need a <code>dind</code>?</li>
</ul>
<p>I hope somebody can give me some advice on how to achieve this. An example would be even better but I don't know if somebody would want to do that.</p>
<p>Thanks for taking the time to read!</p>
<h3><em>(if needed)</em> Example of the API server 1</h3>
<pre><code>build-api:
  image: docker:19
  stage: build
  services:
    - docker:19-dind
  script:
    cd api
    docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    docker pull $IMAGE_TAG_API:latest || true
    docker build -f ./Dockerfile --cache-from $IMAGE_TAG_API:latest --tag $IMAGE_TAG_API:$CI_COMMIT_SHA .
    docker push $IMAGE_TAG_API:$CI_COMMIT_SHA

test-api:
  image: docker:19
  stage: test
  services:
    - postgres:12.2-alpine
    - docker:19-dind
  variables:
    DB_NAME: project_ci_test
    POSTGRES_HOST_AUTH_METHOD: trust
  script:
    - docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
    - docker pull $IMAGE_TAG_API:$CI_COMMIT_SHA
    - docker run $IMAGE_TAG_API:$CI_COMMIT_SHA sh -c &quot;python manage.py test&quot;
  after_script:
    - echo &quot;Pytest tests complete&quot;
  coverage: &quot;/TOTAL.+ ([0-9]{1,3}%)/&quot;

release-api-staging:
  image: docker:19
  stage: release
  services:
    - docker:19-dind
  only:
    refs: [ master ]
    changes: [ &quot;.gitlab-ci.yml&quot;, &quot;api/**/*&quot; ]
  environment:
    name: staging
  script:
    - docker pull $IMAGE_TAG_API:$CI_COMMIT_SHA
    - docker tag $IMAGE_TAG_API:$CI_COMMIT_SHA $IMAGE_TAG_API:latest
    - docker push $IMAGE_TAG_API:latest
</code></pre>
",https://stackoverflow.com/questions/66071016/how-to-setup-gitlab-ci-e2e-tests-using-multiple-dockers,"['docker', 'docker-compose', 'continuous-integration', 'gitlab']",2970,True,6,2
Testing an a observable subject from a backend service,"<p>I decided that I needed to improve my Angular app by actually testing the code before it got deployed. I have a C#/.Net background and I know my way around unit testing in that context.</p>
<p>Most of the unit tests I've written so far for my Angular app have been relatively straightforward, but testing an observable subject has become a stumbling block.</p>
<p>The code I'm writing tests for, consists of the following:</p>
<ul>
<li>A service that fetches news items (JSON) from a .Net App running in Azure</li>
<li>A component that uses the above</li>
</ul>
<p>The service retrieves news items using an HTTP GET request and updates an observable subject, the component subscribes to the subject and processes the JSON as it is offered by the subject.</p>
<p>The issue that I run into is testing the function that subscribes to the subject from the service and hands off the processing to another function.</p>
<p>Here's the code for the service:</p>
<pre><code>export class NewsService {

  userObject!: UserSettings;
  localeId = 'da';
  data: any;

  public newsFeed!: News[];
  public newsFeedSubject = new Subject&lt;any&gt;();
  public newsFeedTimer = new Subscription();

  constructor(private http: HttpClient) {

    this.newsFeedTimer = this.timerSubscription();
    console.log('constructor called');
  }

  public timerSubscription(): Subscription {
    return timer(globalConstants.interval10Secs, globalConstants.interval2Hours).subscribe(() =&gt; {
      this.updateNewsFeedsSubject();
    });
  }

  public updateNewsFeedsSubject(): void {
    console.log(`Calling newsfeed service`);

    this.getNewsFeed(this.localeId).subscribe(newsFeed =&gt; {
      this.newsFeedSubject.next(newsFeed);

      console.log('NewsFeedTimer updated, newsfeed updated');
    });
  }

  public getNewsFeed(locale: string): Observable&lt;News[]&gt; {
    return this.http.get&lt;News[]&gt;(`${environment.baseURL}/${environment.newsServiceUrl}?locale=${this.localeId}`).pipe(
      tap(data =&gt; console.log('NewsFeed Items retrieved: ', data)),
      tap(() =&gt; console.log('getNewsFeed: HTTP Request executed'))
    );
  }
}
</code></pre>
<p>and here's the code for the component:</p>
<pre><code>export class HomeComponent implements OnInit {

  // Newsfeed service
  public newsFeed!: News[];

  constructor(private newsFeedService: NewsService) { }

  ngOnInit(): void {

    this.newsFeedServiceSubscribe();
  }

  public newsFeedServiceSubscribe(): void {
    this.newsFeedService.newsFeedSubject.subscribe(newsFeed =&gt; {
      this.updateNewsFeed(newsFeed);
      console.log('newsFeedServiceSubscribe function has been called');
    });
  }

  public updateNewsFeed(newsFeed: any): void {
    this.newsFeed = newsFeed;
    console.log('updateNewsFeed function has been called');
    console.log(newsFeed);
  }
}
</code></pre>
<p>And finally my (probably botched) attempt to test the newsFeedServiceSubscribe function:</p>
<pre><code>  it('#newsFeedServiceSubscribe should call on the subscribe function on the updateNewsFeed subject', fakeAsync(() =&gt; {
    const spyNewsFeedSubjectSubj = spyOn(newsService.newsFeedSubject, 'subscribe');    
    spyOn(component, 'updateNewsFeed');
    
    expect(spyNewsFeedSubjectSubj.calls.any()).toBe(false,'subject should not have been called');
    expect(component.updateNewsFeed).toHaveBeenCalledTimes(0);

    component.newsFeedServiceSubscribe();
    fixture.detectChanges();
    
    newsService.newsFeedSubject.next(mockNewsfeedTestData);
    fixture.detectChanges();

    expect(spyNewsFeedSubjectSubj.calls.any()).toBe(true,'subject should have been called');
    expect(component.updateNewsFeed).toHaveBeenCalledTimes(1);
  }));
</code></pre>
<p>The actual code runs just fine the news items are &quot;returned&quot; from the subject and processed just fine, but I just can't seem to get the test right. I would be expecting that the subject (in the service) is updated when I call the &quot;next&quot; method on the subject and I would then expect the subscription in the newsFeedServiceSubscribe function to actually call the updateNewsFeed function in the component.</p>
<p>Unfortunately, that doesn't seem to work. How do I actually test that the subscription on the subject returns data and the updateNewsFeed is called?</p>
<p>Thanks,
Bjarne</p>
",https://stackoverflow.com/questions/66408615/testing-an-a-observable-subject-from-a-backend-service,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'rxjs-observables']",768,True,0,2
Static Context Configuration for Logback Appenders,"<p>I've found a few examples (even on Stack Overflow) of some programmatic configuration of Logback logging appenders, but as much as I've incorporated into my own setup hasn't worked for me so far. Some examples produce an actual <code>Logger</code> instance, but considering I've already got a <code>Logger</code> being statically instantiated within my class, I want to be able to programmatically enable an <code>Appender</code> that I've defined for unit testing purposes.</p>
<p>Here is my custom appender:</p>
<pre class=""lang-java prettyprint-override""><code>package org.example.logging;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;

import java.util.ArrayList;
import java.util.List;

// Credit to https://stackoverflow.com/a/29077499/5476186
public class TestAppender extends AppenderBase&lt;ILoggingEvent&gt; {
    private static List&lt;ILoggingEvent&gt; events = new ArrayList&lt;&gt;();

    @Override
    protected void append(ILoggingEvent e) {
        events.add(e);
    }

    public static List&lt;ILoggingEvent&gt; events() {
        return List.copyOf(events);
    }

    public static void clear() {
        events.clear();
    }
}
</code></pre>
<p>And in my testing code, I'm trying to configure my <code>TestAppender</code> to &quot;kick in&quot; so that, after invoking this method in my test setup, I can capture the logs and validate them:</p>
<pre class=""lang-java prettyprint-override""><code>package org.example.logging;

import ch.qos.logback.classic.LoggerContext;
import org.slf4j.LoggerFactory;

    // ...

    // Mostly modeled after https://stackoverflow.com/a/7825548/5476186
    private static void startAppender() {
        LoggerContext logCtx = (LoggerContext) LoggerFactory.getILoggerFactory();

        TestAppender appender = new TestAppender();
        appender.setContext(logCtx);
        appender.setName(&quot;TEST&quot;);
        // I was hoping this would statically allow the appender to kick in,
        // but all of the examples then attach this appender to a Logger instance.
        appender.start();
    }
</code></pre>
<p>Obviously, this isn't working for me. So I guess I have two contingent questions.</p>
<ol>
<li>Is this possible and, if so, how can I make it work?</li>
<li>If this is not possible, what's the cleanest way to accomplish what I'm trying to do? (Enable/disable appenders during testing without having to manually mess with a config file.)</li>
</ol>
<p>In one of the threads linked above, I found this answer which looks like <a href=""https://stackoverflow.com/a/3810936/5476186"">one possible solution</a> is to modify the text in the configuration file and to force a reload, but that doesn't seem super clean to me. Another option would be to create my own wrapper <code>Logger</code> factory which I could use to provide loggers with my <code>TestAppender</code> during test execution with dependency injection. I'll probably be creating a wrapper anyway, even though I'm using SLF4J.</p>
<p>Side note: I know that my test code as currently written is pretty tightly coupled with Logback instead of SLF4J, so I'm open to criticism/advice on that issue, too.</p>
",https://stackoverflow.com/questions/67049027/static-context-configuration-for-logback-appenders,"['java', 'junit', 'logback', 'slf4j', 'junit5']",303,True,0,1
Creating a single factory for unrelated objects,"<p>I have several classes that are not related to each other.</p>
<pre><code>public class Apple
{
    
}

public class Giraffe
{
    
}
</code></pre>
<p>I can create a separate factory for each but I want to get a structure like below.</p>
<pre><code>Factory&lt;Apple&gt;.CreateSingle();
</code></pre>
<p>I want to produce a single apple with the code above. Also with the following code;</p>
<pre><code>Factory&lt;Giraffe&gt;.CreateCollection(20);
</code></pre>
<p>I want to get 20 giraffes.</p>
<p>To do this, I created an IFactory generic interface.</p>
<pre><code>public interface IFactory&lt;out T&gt;
{
    T CreateSingle();
    IEnumerable&lt;T&gt; CreateCollection(int count);
}
</code></pre>
<p>And a factory for each type;</p>
<pre><code>public class AppleFactory : IFactory&lt;Apple&gt;
{
    public Apple CreateSingle() =&gt;
        new()
        {
           //some code
        };

    public IEnumerable&lt;Apple&gt; CreateCollection(int count)
    {
          // CreateSingle X count times, add to collection and return
    }
}

public class GiraffeFactory: IFactory&lt;Giraffe&gt;
{
    public Giraffe CreateSingle() =&gt;
        new()
        {
           //some code
        };

    public IEnumerable&lt;Giraffe&gt; CreateCollection(int count)
    {
          // CreateSingle X count times, add to collection and return
    }
}
</code></pre>
<p>The main factory looks like this;</p>
<pre><code>public static class Factory&lt;T&gt;
{
    private static IFactory&lt;T&gt; GetFactory()
    {
        if (typeof(T) == typeof(Apple)) return (IFactory&lt;T&gt;) new AppleFactory();
        if (typeof(T) == typeof(Giraffe)) return (IFactory&lt;T&gt;) new GiraffeFactory();
        return null;
    }
    public static T CreateSingle() =&gt; GetFactory().CreateSingle();
    public static IEnumerable&lt;T&gt; CreateCollection(int count) =&gt; GetFactory().CreateCollection(count);


}
</code></pre>
<p>The if structure here looks pretty ugly. Is there a way I can do what I want to do in a cleaner way? These days, I am trying to learn design patterns and I force myself to use design patterns. The code may seem unnecessarily cluttered for this reason. It's totally experimental.</p>
<p><strong>[UPDATE]</strong></p>
<p>Actually I made up apples and giraffes to represent database objects (Orders, Customers etc). During unit testing, I sometimes needed mocks of these objects. For this reason, I coded a factory for each object type. Afterwards, I thought if I could gather these factories in a single factory. I also checked the Abstract factory method, but it didn't quite fit.</p>
<p>I made some changes to the code. Generating objects singularly has a separate structure for each object (because its properties are different). But after making a single production, producing a collection is the same for all of them. For this reason, I moved the collection production method to the main factory.</p>
<p>Also, I used reflection to select the appropriate factory to produce within the main factory.</p>
<p>Again, I did all this for experimental purposes only. I didn't get any useful results. I think it's best to use separate factories anyway.</p>
<pre><code>public static class Factory&lt;T&gt;
{
    private static IFactory&lt;T&gt; _factory;
    private static IFactory&lt;T&gt; SetFactory()
    {
        var type = typeof(IFactory&lt;T&gt;);
        var desiredFactory = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s =&gt; s.GetTypes())
            .First(p =&gt; type.IsAssignableFrom(p));
        if (_factory == null || desiredFactory != _factory.GetType())
        {
            _factory=(IFactory&lt;T&gt;)Activator.CreateInstance(desiredFactory);
        }
        return _factory;
    }
    public static T CreateSingle() =&gt; SetFactory().CreateSingle();

    public static IEnumerable&lt;T&gt; CreateEnumerable(int count)
    {
       // I removed creating collection method from each factory to here
    }
</code></pre>
",https://stackoverflow.com/questions/68598332/creating-a-single-factory-for-unrelated-objects,['design-patterns'],189,False,0,1
Pycharm not recognizing project packages after copying from old version of project,"<p>I'm trying to set up a unit testing framework for a repo using pytest, and I was working in an old branch. I cloned the new branch and copied the files over to the new branch. When invoking pytest, the tests would run fine, but they were referencing files in the old project (even though they were imported as a package in the current project and not through a direct file path).</p>
<p>This is the line/command used to run pytest:</p>
<p><code>(venv) C:\Program Files\Python-3.8.2\pycharm_projects\fnma-erm01-devl-edl-hao-repo_21.3&gt;python -m pytest</code></p>
<p>To attempt to remedy that issue, I deleted the old branch locally, and now none of the tests will work, and it doesn't recognize any of the project directories as valid modules.</p>
<p>Stacktrace:</p>
<pre><code>========================================================================================================================================================================= test session starts =========================================================================================================================================================================
platform win32 -- Python 3.8.2, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: C:\Program Files\Python-3.8.2\pycharm_projects\ERM_EDL_HAO_21.3_Branch, configfile: pytest.ini
plugins: mock-3.5.1
collecting ... sys path ['
C:\\Program Files\\Python-3.8.2\\pycharm_projects\\ERM_EDL_HAO_21.3_Branch\\SourceCode\\application\\deploy\\app\\hao',
'C:\\Program Files\\Python-3.8.2\\pycharm_projects\\ERM_EDL_HAO_21.3_Branch',
'C:\\Progra~1\\Python-3.8.2\\pycharm_projects\\fnma-erm01-devl-edl-hao-repo\\SourceCode\\application\\deploy\\app\\hao\\lambda',
'C:\\Progra~1\\Python-3.8.2\\pycharm_projects\\fnma-erm01-devl-edl-hao-repo\\SourceCode\\application\\deploy\\app\\hao\\lambda\\tests',
'C:\\Progra~1\\Python-3.8.2\\pycharm_projects\\fnma-erm01-devl-edl-hao-repo\\SourceCode\\application\\deploy\\app\\hao\\lambda\\utils',
'C:\\Program Files\\Python-3.8.2\\pycharm_projects\\ERM_EDL_HAO_21.3_Branch',
'C:\\Program Files\\Python-3.8.2\\python38.zip',
'C:\\Program Files\\Python-3.8.2\\DLLs',
'C:\\Program Files\\Python-3.8.2\\lib',
'C:\\Program Files\\Python-3.8.2',
'C:\\Program Files\\Python-3.8.2\\pycharm_projects\\ERM_EDL_HAO_21.3_Branch\\venv',
'C:\\Program Files\\Python-3.8.2\\pycharm_projects\\ERM_EDL_HAO_21.3_Branch\\venv\\lib\\site-packages',
'C:\\Users\\g3uj2m\\AppData\\Roaming\\Python\\Python38\\site-packages',
'C:\\Users\\g3uj2m\\AppData\\Roaming\\Python\\Python38\\site-packages\\win32',
'C:\\Users\\g3uj2m\\AppData\\Roaming\\Python\\Python38\\site-packages\\win32\\lib',
'C:\\Users\\g3uj2m\\AppData\\Roaming\\Python\\Python38\\site-packages\\Pythonwin',
'C:\\Program Files\\Python-3.8.2\\lib\\site-packages']
collected 0 items / 16 errors  
=============================================================================================================================================================================== ERRORS ================================================================================================================================================================================
_______________________________________________________________________________________________________________________ ERROR collecting SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_amtm_upstream_notification.py _______________________________________________________________________________________________________________________
ImportError while importing test module 'C:\Program Files\Python-3.8.2\pycharm_projects\ERM_EDL_HAO_21.3_Branch\SourceCode\application\deploy\app\hao\lambda\tests\handlers\unittest_hao_amtm_upstream_notification.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
..\..\lib\importlib\__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
SourceCode\application\deploy\app\hao\lambda\tests\handlers\unittest_hao_amtm_upstream_notification.py:8: in &lt;module&gt;
    from hao_amtm_upstream_notification import lambda_function
E   ModuleNotFoundError: No module named 'hao_amtm_upstream_notification'

# ... ^ that part more or less repeated 15 more times ...

======================================================================================================================================================================= short test summary info =======================================================================================================================================================================
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_amtm_upstream_notification.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_batchjob_status_check.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_batchjob_submit.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_capture_hedge_status.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_ccfa_upstream_notification.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_dynamodb_status_check.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_glue_function.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_irdb_upstream_notification.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_krd_upstream_notification.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_ln_pool_max.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_s3_data_availability_check.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_stepfn_execution_status.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_swap_upstream_notification.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_trigger_sns_msg.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_verify_upstream_data_availability.py
ERROR SourceCode/application/deploy/app/hao/lambda/tests/handlers/unittest_hao_workflow_trigger.py
</code></pre>
<p>File tree:</p>
<pre><code>pytest.ini

SOURCECODE
├───application
│   └───deploy
│       └───app
│           └───hao
│               ├───lambda
│               │   ├───hao_amtm_upstream_notification
│               │   │       lambda_function.py
│               │   │
│               │   ├───hao_batchjob_status_check
│               │   │       lambda_function.py
│               │   │
│               │   ├───hao_batchjob_submit
│               │   │       lambda_function.py
│               │   │
                  ... etc ...
│               │   │
│               │   ├───tests
│               │   │   conftest.py
│               │   │
│               │   │   ├───handlers
│               │   │   │       unittest_hao_amtm_upstream_notification.py
│               │   │   │       unittest_hao_batchjob_status_check.py
│               │   │   │       unittest_hao_batchjob_submit.py
│               │   │   │     ... etc ...
</code></pre>
<p>pytest.ini file:</p>
<pre><code># pytest.ini
[pytest]
python_files = unittest_*.py
</code></pre>
<p>Here's what I've already tried/checked:</p>
<ol>
<li>All of the necessary folders are already marked as &quot;Sources Root&quot;.</li>
<li>I've added <code>__init__.py</code> to all of the necessary folders.</li>
<li>I've checked to make sure <code>__init__.py</code> is not recognized as a text file.</li>
<li>I've run the &quot;Invalidate Caches / Restart...&quot; option under File.</li>
<li>I've ensured that the project's interpreter is aligned with the current project and directory.</li>
</ol>
<p>It won't let me include screenshots, but the project structure should not be an issue as it worked perfectly fine in the old branch. (The old branch structure is identical to the new one, so there should be no reference issues when copying from one to the other)</p>
<p>EDIT 1:
I'm using the <code>pytest.ini</code> configuration file, and the only thing specified in it is the custom prefix to identify test files. I created a new venv for the new project, and I'm invoking pytest from the built-in terminal in PyCharm, so the venv is active.</p>
<p>EDIT 2:
Shortened the stack trace so it's easier to read, and adding the relevant parts of the file tree and the <code>pytest.ini</code> file.</p>
",https://stackoverflow.com/questions/68170195/pycharm-not-recognizing-project-packages-after-copying-from-old-version-of-proje,"['python', 'pycharm', 'pytest']",121,True,1,1
how to mock s3.Object for an AWS lambda function in AWS,"<p>I have a simple lambda function, and because I am new to Python, I am not able to write test cases for that function. So, the task is very simple, I uploading an xml document to s3, and returning the url. Below is the code in the main python file:</p>
<p>Edit 2: the purpose of below code is to make a xml out of a JSON payload, which is passed in as an argument root, and upload it to s3. s3 already has a bucket s3-encora-task, and I have to upload output.xml. I have to write unit test for that condition.</p>
<pre><code>def uploaddata(root):
    xmlstr = minidom.parseString(ET.tostring(root)).toprettyxml(indent=&quot;   &quot;)
    string_out = io.StringIO()
    string_out.write(xmlstr)
    s3.Object('s3-encora-task', 'output.xml').put(Body=string_out.getvalue())
    location = boto3.client('s3').get_bucket_location(Bucket=bucket_name)['LocationConstraint']
    url = &quot;https://s3-%s.amazonaws.com/%s/%s&quot; % (location, bucket_name, 'output.xml')
    return url
</code></pre>
<p>I get error in the line:</p>
<pre><code>s3.Object('s3-encora-task', 'output.xml').put(Body=string_out.getvalue())
</code></pre>
<p>Below is the error:</p>
<p>raise NoCredentialsError()
botocore.exceptions.NoCredentialsError: Unable to locate credentials</p>
<p>I have experience in writing Junit test classes but I am having trouble in making a comparison(in the way of writing) of Junit and unittest, and so not able to articulate my question. So, I have below questions:</p>
<ol>
<li>In my python file, I don't have a class.I am instantiating s3 like this outside of methods: s3 = boto3.resource('s3'). So , how can I mock this s3 object and pass to the method, so that mock object is used.</li>
<li>In my test class, i am importing the main python as : import jsontoxmlconverter as converter
and then using converter.&lt;&gt; for unit testing, but the method doesn't take s3 as an argument, so again, how can I pass s3 mock object.</li>
<li>I have read few things about using moto to mock s3, but not able to figure out, how the object is getting passed, so any more info on that would help.</li>
</ol>
<p>Thanks in Advance!!</p>
<p>Edit 1:
Below is the current code in my test class:</p>
<pre><code>     import jsontoxmlconverter as converter
    def test_jsontoxml_happyflow(self):
        with open('jsonData.txt') as json_file:
            data = json.load(json_file)
        mock = Mock()
        mock.patch('converter.s3')
        result = converter.jsontoxml(data, context={})
</code></pre>
",https://stackoverflow.com/questions/67409287/how-to-mock-s3-object-for-an-aws-lambda-function-in-aws,"['python', 'amazon-s3', 'python-unittest']",1127,True,-1,1
CsvHelper delimeter character same as end of line character,"<p>I've run into an issue while parsing some csv-like files that I know how to fix, but like to confirm if that's the appropriate way to do.</p>
<hr />
<h3>The file structure</h3>
<p>The file I'm trying to parse has a structure <strong>similar</strong> to <code>.csv</code> in that it's values are separated with a delimeter (in my case it's <code>|</code>), but different to the ones I've previously seen is that it also has a delimeter at the end of the line, e.g:</p>
<pre><code>Column1|Column2|Column3|
Row1Val1|Row1Val2|Row1Val3|
Row2Val1|Row2Val2|Row2Val3|
</code></pre>
<hr />
<h3>The issue</h3>
<p>The problem arose when I wrote some unit tests to cover my service that wraps over the CsvHelper library. Apparently there is some issue when I provide the following configuration:</p>
<pre class=""lang-cs prettyprint-override""><code>var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    Delimiter = &quot;|&quot;,
    HasHeaderRecord = true,
    NewLine = &quot;|\r\n&quot;
};
</code></pre>
<p>With the above configuration, <code>csvReader.GetRecords()</code> returns no results. I believe that's because the order of operations for the parser is to first look for columns, then end of line - and it tries to parse empty column without realizing it's actually part of the delimeter.</p>
<p>(I can paste the code for the getRecords call as well, but it's basically generic code taken from examples - the only difference is I'm using <code>System.IO.Abstractions</code> library for easier unit testing)</p>
<hr />
<h3>The attempts to solve the problem</h3>
<p>If I remove the <code>NewLine</code> configuration value, parser works fine when reading the file (even if it has end-of-line delimeter character at the end). Then, however, my &quot;write CSV&quot; tests break, since CsvHelper no longer is adding proper line endings to the file.</p>
<hr />
<h3>The question(s)</h3>
<p>Is there any way I can configure CsvHelper to cover both cases with one configuration, or should I basically use two different configurations, depending on whether I'm writing to CSV or reading from it? This seems a little bit counter-intuitive for me, since it's basically the same format I'm trying to follow, but different configurations are expected?</p>
",https://stackoverflow.com/questions/66971793/csvhelper-delimeter-character-same-as-end-of-line-character,"['c#', 'csv', 'csvhelper']",693,False,0,1
Typescript: Is it possible to stub a declared function for a unit test?,"<p>For context, I'm writing typescript that gets compiled into javascript, is bundled with rollup, then called by a framework. This framework provides a library for me in the global scope. It's a function that looks like this:</p>
<pre><code>    fun({
      prop1: number,
      ...
    });
</code></pre>
<p>I don't want to include this library into my bundled JavaScript because it's already provided by the framework. I think that could introduce lots of weird bugs if the version of the library in my code is different from the framework's. In theory, I think it would be less error-prone and simpler to just use the library that's provided by the framework.</p>
<p>I've done a <em>little</em> research, and I think the <code>declare</code> keyword is just for this purpose. So I put this in the same file I call <code>fun</code>:</p>
<pre><code>export declare function fun(input: unknown): void;
</code></pre>
<p>Now my code compiles, but I haven't figured out a way of unit testing my production code. If I call the code that calls <code>fun</code>, jasmine complains that the function doesn't exist: <code>ReferenceError: fun is not defined</code></p>
<p>I understand why this error is happening, but I have no idea how to work around it. I tried using sinon to stub <code>fun</code>, but it had a similar complaint about <code>fun</code> not existing when I ran my test in Jasmine.</p>
<p>I've come up with a workaround that I hate: I wrapped the call to <code>fun</code> in an <code>if</code> statement so the test skips the call to <code>fun</code>.</p>
<p>I want to know if there is some way to stub <code>fun</code> so I can execute code that calls it and confirm that the correct properties are being passed in. <em>Alternatively, is there a way I can write a fake version of <code>fun</code> and exclude it from the transpiled javascript, so it's <code>stub</code>able for testing, but doesn't exist in production? Given the way modules work, I don't think this is an option. But I'm open to all sorts of ideas, which is why I bring it up.</em></p>
",https://stackoverflow.com/questions/66296773/typescript-is-it-possible-to-stub-a-declared-function-for-a-unit-test,"['typescript', 'unit-testing', 'jasmine', 'sinon', 'rollupjs']",216,False,0,1
Load Spring Boot component before Lombok instantation in unit test,"<p>I developed a kind of <em>wrapper</em> to make it work as a custom logger. I'm instantiating this class using <code>@CustomLog</code> Lombok annotation just to make it easier and cleaner. The tricky thing comes next: the idea behind this wrapper is to use a common logger (as <code>org.slf4j.Logger</code>) along with a custom monitor class that each time I call <code>log.error()</code>, the proper message gets logged in the terminal and the event is sent to my monitoring tool (Prometheus in this case).</p>
<p>To achieve this I did the following classes:</p>
<ol>
<li><code>CustomLoggerFactory</code> the factory called by Lombok to instantiate my custom logger.</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>public final class CustomLoggerFactory {

     public static CustomLogger getLogger(String className) {

        return new CustomLogger(className);
     }
}
</code></pre>
<ol start=""2"">
<li><code>CustomLogger</code> will receive the class name just to then call <code>org.slf4j.LoggerFactory</code>.</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>public class CustomLogger {

    private org.slf4j.Logger logger;
    private PrometheusMonitor prometheusMonitor;
    private String className;

    public CustomLogger(String className) {

        this.logger = org.slf4j.LoggerFactory.getLogger(className);
        this.className = className;
        this.monitor = SpringContext.getBean(PrometheusMonitor.class);
    }
}
</code></pre>
<ol start=""3"">
<li><code>PrometheusMonitor</code> class is the one in charge of creating the metrics and that kind of things. The most important thing here is that <strong>it's being managed by Spring Boot</strong>.</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>@Component
public class PrometheusMonitor {

    private MeterRegistry meterRegistry;

    public PrometheusMonitor(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }
}
</code></pre>
<ol start=""4"">
<li>As you may noticed, to access <code>PrometheusMonitor</code> from <code>CustomLogger</code> I need an additional class in order to get the Bean / access the context from a non Spring managed class. This is the <code>SpringContext</code> class which has an <code>static</code> method to get the bean by the class supplied.</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>@Component
public class SpringContext implements ApplicationContextAware {

    private static ApplicationContext context;

    public static &lt;T extends Object&gt; T getBean(Class&lt;T&gt; beanClass) {
        return context.getBean(beanClass);
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        SpringContext.context = context;
    }
}
</code></pre>
<p>So all this works just fine when running the application. I ensure to load <code>SpringContext</code> class before anything else, so once each <code>CustomLogger</code> gets instantiated it just works.</p>
<p>But the <strong>BIG</strong> issue comes here: this is not working while unit testing my app. I tried many things and I saw some solutions that may help me but that I'm trying to avoid (e.g. using PowerMockito). Lombok is processing <code>@CustomLog</code> annotation before any <code>@Before</code> method I add to my test class. Once <code>getBean()</code> method is called I get an exception cause <code>context</code> is <code>null</code>.</p>
<p>My guesses are that I could solve it if I can <em>force</em> the <code>SpringContext</code> to be loaded before Lombok does its magic, but I'm not sure that's even possible. Many thanks for taking your time to read this. Any more info I can provide just let me know.</p>
",https://stackoverflow.com/questions/65833567/load-spring-boot-component-before-lombok-instantation-in-unit-test,"['java', 'spring', 'spring-boot', 'junit4', 'lombok']",318,True,0,2
GMock - Mock class from third party libary,"<p>I'm looking at GMock and trying to decide if it is going to be feasible for some unit testing I want to do.</p>
<p>If I understand correctly, any class you Mock has to have an interface that the mock can be created from, and any class you want to test, has to be able to accept the mock via injection.</p>
<p>Am I correct so far?</p>
<p>If I am correct, so far, I do not see how it is going to help me in testing classes that use a class from a third party.</p>
<p>For example:</p>
<p>Suppose I wrote a <code>ChatClient</code> class, and when implementing it I use <code>QWebSocket</code> from the Qt Library. <code>ChatClient</code> has a member <code>ChatClient::m_socket</code> of type <code>QWebSocket</code>.</p>
<p>Now, there is no interface for GMock to create a mock websocket from, and my chat client doesn't take an interface via dependency injection in production code. How a the <code>QWebSocket</code> works is so specific, that I'd never be able to use a different concrete implementation.</p>
<p>However, I do want to test that my <code>ChatClient</code>, calls connect when its supposed to, passes the correct bytes to its calls to <code>QWebSocket::sendBinaryMessage</code>, reacts to incoming message correctly, etc., and it seems a mock framework would be useful to test my <code>ChatClient</code> in that way so I don't have to actually connect to a network.</p>
<p>What do I do, or is this just not doable in C++ like it is in other languages because we don't have reflection?</p>
<p>Do I just create my own interface for the third party class, with every call I make to it, forward it to the third party class, and then have my <code>ChatClient</code> take that interface, even though I will never ever use another concrete implementation, just to enable testing?</p>
",https://stackoverflow.com/questions/67614313/gmock-mock-class-from-third-party-libary,"['c++', 'unit-testing', 'googlemock']",649,False,0,1
"From a pandas DataFrame, how can I create copy-and-pasteable text that will re-create the same DataFrame, including the index?","<h3>Motivation:</h3>
<p>I have a CSV with some data, which is then loaded into a pandas DataFrame <code>raw_data</code>. While unit testing I want to do some aggregation or other process on <code>raw_data</code>, to create a new DataFrame, <code>df</code>, and then confirm that the results (i.e. <code>df</code>) are what I expect.</p>
<p>This means I need to specify, in the unit test, what the results should look like, including the index. Since I have to do this a lot, it's tedious to manually create the exemplars to test against. What I want to do is, in an interactive session, construct the correct result dataframe and then convert it into something I can paste into my test module.</p>
<p>In other words, I want some function <code>f</code> with inverse function <code>F</code>, such that <code>f(df)</code> is something I can copy and paste, and <code>F(f(df)) == df</code></p>
<h3>Example</h3>
<pre class=""lang-py prettyprint-override""><code>df = pd.DataFrame({
    'foo': [1, 2, 3],
    'bar': ['a', 'b', 'c'],
    'baz': ['d', 'e', 'f'],
    'qux': ['z', 'y', 'x']
}).set_index(['baz', 'qux'])
</code></pre>
<p>What I want to do is to take <code>df</code>, get something I can copy and paste into my test module, and create an exact copy of <code>df</code>.</p>
<p>I have tried <code>to_dict</code> and <code>to_json</code>, but for all values of <code>orient</code> either there's an exception or the index is not recreated correctly (often, the <em>names</em> of the index are left out).</p>
<p>Here's code to confirm this:</p>
<h4><code>to_dict</code></h4>
<pre class=""lang-py prettyprint-override""><code>orientations = ['dict', 'split', 'series', 'records', 'list', 'index']

print('\t'.join(['orient', 'eqval', 'valexc', 'eqidx', 'idxexc']))

for orient in orientations:
    try:
        # Convert df to a dict, which I can __repr__ and then copy and paste
        serialized_df = df.to_dict(orient=orient)
        # Then, in theory I should be able to recreate the original df from
        # the dictionary object
        ser_de_df = pd.DataFrame.from_dict(serialized_df, orient=orient)
        
        equal_values = df.equals(ser_de_df)
        values_exception = False
    except:
        equal_values = False
        values_exception = True
        
    try:
        equal_index = df.index.equals(ser_de_df.index) and df.index.names == ser_de_df.index.names
        index_exception = False
    except:
        equal_index = False
        index_exception = True
        
    print('\t'.join(map(str, [orient, equal_values, values_exception, equal_index, index_exception])))
</code></pre>
<p>This produces:</p>
<pre><code>orient  eqval   valexc  eqidx   idxexc
dict    False   True    False   False
split   False   True    False   False
series  False   True    False   False
records False   True    False   False
list    False   True    False   False
index   True    False   False   False
</code></pre>
<p>So, <code>orient='index'</code> creates an equal-value DataFrame, but the index loses the names.</p>
<h4>JSON</h4>
<p>Here's code to confirm no value of <code>orient</code> works for JSON:</p>
<pre class=""lang-py prettyprint-override""><code>orientations = {'split', 'records', 'index', 'columns', 'values', 'table'}

print('\t'.join(['orient', 'eqval', 'valexc', 'eqidx', 'idxexc']))

for orient in orientations:
    try:
        # Convert to JSON, which I could just copy and paste as a string
        serialized_df = df.to_json(orient=orient)
        # Load back into a DataFrame
        ser_de_df = pd.read_json(serialized_df, orient=orient)
        
        equal_values = df.equals(ser_de_df)
        values_exception = False
    except:
        equal_values = False
        values_exception = True
        
    try:
        equal_index = df.index.equals(ser_de_df.index) and df.index.names == ser_de_df.index.names
        index_exception = False
    except:
        equal_index = False
        index_exception = True
        
    print('\t'.join(map(str, [orient, equal_values, values_exception, equal_index, index_exception])))
</code></pre>
<p>Produces:</p>
<pre><code>orient  eqval   valexc  eqidx   idxexc
columns False   False   False   False
table   True    False   True    False
index   False   False   False   False
split   False   True    False   False
records False   False   False   False
values  False   False   False   False
</code></pre>
<p>So <code>table</code> creates equal values, but not equal index.</p>
<p>I could, of course, manually add code to set the index names correctly again, but it seems odd that there would not be a way to consistently serialize a DataFrame including the complete index (other than to a file like with <code>to_pickle</code>, etc.).</p>
<p>Is there a better way?</p>
<p><strong>Note: Edited to fix a typo in the code, which prevented me from discovering the answer (which I've added below). Keeping this question here in case others might have same question</strong></p>
",https://stackoverflow.com/questions/68106870/from-a-pandas-dataframe-how-can-i-create-copy-and-pasteable-text-that-will-re-c,"['python', 'pandas', 'dataframe']",126,True,0,2
Guidance for C++ / Python developer to understand the web dev world,"<p>I am programming since quite some years now.
Until now I was mainly focused on writing &quot;normal&quot; applications which run inside a console or with a GUI, sometimes also applications which interact with hardware components such as sensors / actors / ...
During this time I got to know a lot of cool programming principles and tools such as object orientation, modularization, unit-testing, test-driven-development, desing-patterns, code-analysis, ..</p>
<p>Also I have some first experience with hosting a wordpress blog, running static web-sites on a nginx webserver, and writing some small php-forms. But I feel like there is still too much magic in all these web-development topics. And I would like to fill this gap and learn a bit more about all these connected scripting / programming languages and technologies. (Because I hate, when I don't understand how things are working :D :D )
I started with some online &quot;Web-development bootcamp&quot; course at udemy to get a rough overview. This took quite some days now and I think HTML, CSS and Javascript for DOM manipulation / animations are clear to me now. Also I heard a lot about NodeJS and all it's derivate languages and databases like Mongo-DB. But still I feel like there is a lot of things unclear to me.</p>
<p>To get to a better understanding I wanted to development some small web-application. Nothing very special, just some website where you have to login to, are able to generate some data and this data is then persisted into a database and once you login again you are able to see the data again.
I first started with developing some classes in Javascript to represent the data in the browser while you are logged in. But I very soon realized that the Javascript which can run inside the browser is very limited and already for unit-testing and modularization into separate files that include each other I actually needed to do some crazy work-arounds or use other server-side languages like nodejs / php / ... .
After some time coding I decided to take one step back, trying to understand the basic design patterns of web-applications and not running for a long time into the wrong direction.</p>
<p>My questions are:</p>
<ul>
<li>Is there some typical way to go / best practice while developing web-applications?</li>
<li>What are the typical key players? I know there is the difference between front-end, back-end and databases.</li>
<li>But are there some do's and don't's that good WebDev's follow?
For example:
<ul>
<li>which code is usually written in back-end / server-side languages?</li>
<li>What is usually done in the front-end? (Only desing and animations?)</li>
<li>Do I have to move all business logic into the back-end, also for security reasons or is this maybe also a bad idea because of peformance reasons?</li>
<li>What programming languages are more or less dead and not to be used in the future?</li>
<li>What things are typically reused from frameworks, for example authentication and session handling?</li>
</ul>
</li>
</ul>
<p>Also I felt like some things I know from other programming languages are not so easy in languages like javascript / nodejs. I am willing to spend time and effort into learning all these things but I would also like to keep the quality standards that I know from C++ /
Python. On the other side I also wondered if these patterns that I have in my head are maybe just boundaries that are completely useless in modern web-development? (e.g. typing, object orientation, modularization / splitting the code to be very reusable )</p>
<p>What do you think am I on the wrong track here, or do I maybe simply use the wrong languages?</p>
<p>I hope the long text is not knocking everyone down / keeping everyone from answering me :o
I would really appreciate your help and guidance to understand everything a bit better and to not repeat the things already a lot of others have done wrong ;)</p>
<p>BR, mezorian</p>
",https://stackoverflow.com/questions/65643564/guidance-for-c-python-developer-to-understand-the-web-dev-world,"['frontend', 'backend', 'web-development-server']",470,True,0,1
How should Poetry scripts used in the build process be stored in the project?,"<p>Let's say that you're using Poetry to manage a Python PyPI package. As it stands, your project has a <code>Makefile</code> that contains procedures for managing the installation, unit testing, and linting of your project. However, since this goes against the spirit of Poetry where you ideally have one configuration file to rule them all (<code>pyproject.toml</code>), and because said <code>Makefile</code> can be annoying on Windows builds, you would like to instead move the <code>Makefile</code> functionality to be managed by Poetry directly by making use of <a href=""https://python-poetry.org/docs/pyproject/#scripts"" rel=""noreferrer"">Poetry's support for <code>setuptools</code> scripts</a>.</p>
<p>Here's an example of such a <code>Makefile</code>:</p>
<pre><code>PYMODULE := awesome_sauce
TESTS := tests
INSTALL_STAMP := .install.stamp
POETRY := $(shell command -v poetry 2&gt; /dev/null)
MYPY := $(shell command -v mypy 2&gt; /dev/null)

.DEFAULT_GOAL := help

.PHONY: all
all: install lint test

.PHONY: help
help:
    @echo &quot;Please use 'make &lt;target&gt;', where &lt;target&gt; is one of&quot;
    @echo &quot;&quot;
    @echo &quot;  install     install packages and prepare environment&quot;
    @echo &quot;  lint        run the code linters&quot;
    @echo &quot;  test        run all the tests&quot;
    @echo &quot;  all         install, lint, and test the project&quot;
    @echo &quot;  clean       remove all temporary files listed in .gitignore&quot;
    @echo &quot;&quot;
    @echo &quot;Check the Makefile to know exactly what each target is doing.&quot;
    @echo &quot;Most actions are configured in 'pyproject.toml'.&quot;

install: $(INSTALL_STAMP)
$(INSTALL_STAMP): pyproject.toml
    @if [ -z $(POETRY) ]; then echo &quot;Poetry could not be found. See https://python-poetry.org/docs/&quot;; exit 2; fi
    $(POETRY) run pip install --upgrade pip setuptools
    $(POETRY) install
    touch $(INSTALL_STAMP)

.PHONY: lint
lint: $(INSTALL_STAMP)
    # Configured in pyproject.toml
    # Skips mypy if not installed
    @if [ -z $(MYPY) ]; then echo &quot;Mypy not found, skipping...&quot;; else echo &quot;Running Mypy...&quot;; $(POETRY) run mypy $(PYMODULE) $(TESTS); fi
    @echo &quot;Running Flake8...&quot;; $(POETRY) run pflake8 # This is not a typo
    @echo &quot;Running Pylint...&quot;; $(POETRY) run pylint $(PYMODULE)

.PHONY: test
test: $(INSTALL_STAMP)
    # Configured in pyproject.toml
    $(POETRY) run pytest

.PHONY: clean
clean:
    # Delete all files in .gitignore
    git clean -Xdf
</code></pre>
<p>But then, you face another problem; due to how these scripts operate, they're expected to be in a package or module of their own, so the first idea would be to simply include the scripts as part of the project package itself:</p>
<pre><code>📦awesome_sauce
 ┣ 📂awesome_sauce
 ┃ ┣ 📂poetry_scripts
 ┃ ┃ ┣ 📜__init__.py
 ┃ ┃ ┣ 📜run_unit_tests.py
 ┃ ┃ ┗ 📜run_linters.py
 ┃ ┣ 📜__init__.py
 ┃ ┗ 📜sauce.py
 ┣ 📂docs
 ┣ 📂tests
 ┣ 📜.gitignore
 ┣ 📜poetry.lock
 ┗ 📜pyproject.toml
</code></pre>
<p>In this case, you could add the following to <code>pyproject.toml</code></p>
<pre><code>[tool.poetry.scripts]
tests = 'awesome_sauce.poetry_scripts.run_unit_tests:main'
linters = 'awesome_sauce.poetry_scripts.run_linters:main'
</code></pre>
<p>and they could be run as</p>
<pre class=""lang-sh prettyprint-override""><code>poetry run tests
poetry run linters
</code></pre>
<p>But this isn't ideal; now your build configuration is part of the package and presumably goes straight into production, unless you pull off something fancy during the CI/CD process. It's dead weight to the end-users, and needlessly adds stuff to the package namespace.</p>
<p>Then, another idea would be to have everything in a top-level script:</p>
<pre><code>📦awesome_sauce
 ┣ 📂awesome_sauce
 ┃ ┣ 📜__init__.py
 ┃ ┗ 📜sauce.py
 ┣ 📂docs
 ┣ 📂tests
 ┣ 📜.gitignore
 ┣ 📜poetry.lock
 ┣ 📜poetry_scripts.py
 ┗ 📜pyproject.toml
</code></pre>
<p>which would change the lines in <code>pyproject.toml</code> to</p>
<pre><code>[tool.poetry.scripts]
tests = 'poetry_scripts:run_unit_tests'
linters = 'poetry_scripts:run_linters'
</code></pre>
<p>but this isn't necessarily ideal either, because now you potentially have a relatively lengthy script sitting at the project root, and it can be subjectively ugly. Though at least now it shouldn't be part of the production package, which is a net gain.</p>
<p>These two approaches could be combined, and the script package in the first version would simply be moved to the root, meaning the project now consists of two different packages.</p>
<pre><code>📦awesome_sauce
 ┣ 📂awesome_sauce
 ┃ ┣ 📜__init__.py
 ┃ ┗ 📜sauce.py
 ┣ 📂docs
 ┣ 📂poetry_scripts
 ┃ ┣ 📜__init__.py
 ┃ ┣ 📜run_unit_tests.py
 ┃ ┗ 📜run_linters.py
 ┣ 📂tests
 ┣ 📜.gitignore
 ┣ 📜poetry.lock
 ┗ 📜pyproject.toml
</code></pre>
<pre><code>[tool.poetry.scripts]
tests = 'poetry_scripts.run_unit_tests:main'
linters = 'poetry_scripts.run_linters:main'
</code></pre>
<p>but it isn't clear whether this is a better approach.</p>
<p>Does a consensus exist for handling the Poetry/<code>setuptools</code> scripts within a given project? If so, I don't believe that has been previously documented in public.</p>
",https://stackoverflow.com/questions/70386944/how-should-poetry-scripts-used-in-the-build-process-be-stored-in-the-project,"['python', 'package', 'directory-structure', 'python-poetry', 'build-script']",4506,True,7,1
&quot;istanbul ignore next&quot; command seems to be ignored,"<p>I'm trying to use Jest to test my code. It was working quite fine until I tried to exclude a class method from the tests.</p>
<p>The querySelector() call is the reason why I want to skip this method from being tested (&quot;document&quot; is obviously null unless I run the script in the browser)</p>
<p>I tried this solution, which seems to be the most suggested one:</p>
<pre><code>  /* istanbul ignore next */
  appendNewInputFields() {

    const howMany = Number(document.querySelector('#items-to-add').value);
    
    [...Array(howMany)].forEach( i =&gt; {
      const newInputField = this.createNewItemInputField();
      this.inputItemsContainerNode.append(newInputField);
    });
  }
</code></pre>
<p>But the test keeps failing and the line <code>/* istanbul ignore next */ </code> seems to be ignored.</p>
<p>I've also tried putting the comment between the function signature and its body (as was suggested somewhere here on SO), but no luck:</p>
<pre><code> FAIL  js/DOMManager.test.js
  ● Test suite failed to run

    TypeError: Cannot read property 'value' of null

      135 |   appendNewInputFields() /* istanbul ignore next */ {
      136 |
    &gt; 137 |     const howMany = Number(document.querySelector('#items-to-add').value);
          |                            ^
      138 |     
</code></pre>
<p>I've read around that this might be related to <code>babel-plugin-istanbul</code>. I've tried</p>
<p><code>npm --save-dev uninstall babel-plugin-istanbul</code></p>
<p>which in the terminal returned:</p>
<pre><code>npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {&quot;os&quot;:&quot;darwin&quot;,&quot;arch&quot;:&quot;any&quot;} (current: {&quot;os&quot;:&quot;linux&quot;,&quot;arch&quot;:&quot;x64&quot;})

removed 18 packages and audited 521 packages in 2.178s
</code></pre>
<p>but the folder <code>babel-plugin-istanbul</code> is still present in <code>/node_modules/</code> inside my working folder and the test keeps failing as if nothing changed.</p>
<p>If I comment out the body of the function, the other test suites work perfectly. If I try to apply the ignore next command to any other part of the code, the tests pass just fine and the line is completely ignored.</p>
<p>If I try to manually delete the <code>/babel-plugin-istanbul/</code> folder (from the /node_modules/ in my working folder), Jest stops working.</p>
<p>(This is the first time I installed Node.js, and I did it only because I wanted to start unit testing with Jest. I'm pointing this out because these are my first steps venturing out of the vanilla world. I don't know how to deal with Node.js nor npm, I just launched a couple commands to install it, I wrote a few tests for Jest and they all immediately worked fine. I'm not using any other framework, I'm trying to stick to vanilla JS as much as possible.)</p>
<p>----------------------- Edit:</p>
<p>I tried changing the code to this:</p>
<pre><code>
  appendNewInputFields() {
    // TODO solve the istanbul ignore issue
    
    let howMany;

    /* istanbul ignore if */
    if(document != null) {
      howMany = Number(document.querySelector('#items-to-add').value);
    
      [...Array(howMany)].forEach( i =&gt; {
        const newInputField = this.createNewItemInputField();
        this.inputItemsContainerNode.append(newInputField);
      });

      console.log(&quot;added &quot; + howMany + &quot; input fields&quot;);
    }
  }
</code></pre>
<p>I keep getting</p>
<pre><code> FAIL  js/DOMManager.test.js
  ● Test suite failed to run

    TypeError: Cannot read property 'value' of null

      139 |     /* istanbul ignore if */
      140 |     if(document != null) {
    &gt; 141 |       howMany = Number(document.querySelector('#items-to-add').value);
          |                        ^
      142 |     
      143 |       [...Array(howMany)].forEach( i =&gt; {
      144 |         const newInputField = this.createNewItemInputField();
</code></pre>
<p>I'm totally clueless at this point. Given the conditional, &quot;document&quot; should be null and that block entirely skipped, but it keeps failing the test.</p>
<p>The same code works exactly as intended when run in the browser.</p>
",https://stackoverflow.com/questions/66532331/istanbul-ignore-next-command-seems-to-be-ignored,"['javascript', 'node.js', 'jestjs', 'istanbul']",16706,True,3,3
Angular/Jest Unit Testing with NGXS State/Router,"<p>I'm unit testing a handful of Angular components that can be navigated between using NGXS Store/Routing with Jest as my test framework.</p>
<ul>
<li>Angular v9.1.1</li>
<li>Jest v9.2.2</li>
<li>NGXS Router v3.7.1</li>
<li>NGXS Store v3.6.2</li>
</ul>
<p>Here's one of the tests in question:</p>
<pre><code>it('should move to page 2 by clicking the next button then go back to page 1 by clicking the back icon', async () =&gt; {
    let url = store.selectSnapshot(RouterState.url);
    expect(url).toEqual(page1Url);

    const nextButton = fixture.nativeElement.querySelector('.right-action-button');
    nextButton.click();
    fixture.detectChanges();
    await fixture.whenStable();
    url = store.selectSnapshot(RouterState.url);
    expect(url).toEqual(page2Url);

    const backButton = fixture.nativeElement.querySelector('.mat-icon-back');
    backButton.click();
    fixture.detectChanges();
    await fixture.whenStable();
    url = store.selectSnapshot(RouterState.url);
    expect(url).toEqual(page1Url);
  });
</code></pre>
<p>This fails at <code>expect(url).toEqual(page2Url);</code> so I know that <code>nextButton</code> is defined, however, clicking on it clearly isn't dispatching the new Store event which contains <code>page2Url</code>.</p>
<p><strong>[EDIT]</strong> - While the button was defined, it was also disabled so the click did nothing. I adjusted the test case to ensure the button would be enabled by the time it was clicked and the value of <code>RouterState.url</code> is now being updated, but not to the correct value. You can see from the last code snippet that the store dispatch should cause navigation to the &quot;side&quot; outlet followed by &quot;add/targets&quot;, &quot;add/details&quot;, etc. However, in reality the result is:</p>
<pre><code>Expected: &quot;/view/(list//side:add/targets)&quot;
Received: &quot;/view/list&quot;
</code></pre>
<p>Logging <code>RouterState.state</code> produces the following:</p>
<pre><code>    {
      root: {
        url: [],
        params: {},
        queryParams: {},
        fragment: undefined,
        data: {},
        outlet: 'primary',
        component: null,
        routeConfig: null,
        root: null,
        parent: null,
        firstChild: {
          url: [],
          params: {},
          queryParams: {},
          fragment: undefined,
          data: {},
          outlet: 'primary',
          component: null,
          routeConfig: null,
          root: null,
          parent: null,
          firstChild: [Object],
          children: [Array],
          pathFromRoot: null,
          paramMap: [ParamsAsMap],
          queryParamMap: [ParamsAsMap],
          toString: [Function]
        },
        children: [ [Object] ],
        pathFromRoot: null,
        paramMap: ParamsAsMap { params: {} },
        queryParamMap: ParamsAsMap { params: {} },
        toString: [Function]
      },
      url: '/view/list'
    }
</code></pre>
<p>Notice how the &quot;outlet&quot; field is &quot;primary&quot; in the &quot;firstChild&quot; object. I'd expect this to be &quot;side&quot; instead based on the code shown below.</p>
<p>[END EDIT]</p>
<p>I've got some set-up in the <code>beforeEach()</code> that resets the value of <code>RouterState.url</code> in the Store back to <code>page1Url</code> and you can see that that's working in the first expect. Here's  the set-up (imports, declarations, providers, etc. are in another <code>beforeEach()</code>):</p>
<pre><code>  beforeEach(() =&gt; {
    store = TestBed.inject(Store);
    store.reset({
      activityView: {
        creationData: {
          info: {},
          earthworks: {}
        }
      },
      router: {
        navigationId: 1,
        state: {
          root: {},
          url: page1Url
        },
        trigger: 'none'
      }
    });
    fixture = TestBed.createComponent(ActivityEditComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });
</code></pre>
<p>In terms of the code being tested, it works as intended, but there seems to be some subtleties around testing a combination of NGXS Router/Store that I haven't quite got tied up. There also doesn't seem to be much about this sort of test either on the Angular/NGXS docs or anywhere else on Stack Overflow.</p>
<p>As some background on how the actual code is handling this navigation, I have a few methods in the Component that handle the various UI actions that can be taken, see below:</p>
<pre><code>  onCancel() {
    this.store.dispatch(new SetActivityCreationData(null));
    this.onClose();
  }

  onClose() {
    this.store.dispatch(new Navigate([{ outlets: { side: null } }], null, { relativeTo: this.route.parent }));
  }

  onNext() {
    this.page = 2;
    this.store.dispatch(new Navigate([{ outlets: { side: 'add/targets' } }], null, { relativeTo: this.route.parent }));
  }

  onBack() {
    this.page = 1;
    this.store.dispatch(new Navigate([{ outlets: { side: 'add/details' } }], null, { relativeTo: this.route.parent }));
  }
</code></pre>
<p>And again, this is working as intended but the test set-up seems to cause the relevant methods to not be called when one of the buttons is clicked.</p>
<p>This is getting pretty frustrating now so any guidance/suggestions would be much appreciated!</p>
",https://stackoverflow.com/questions/68744896/angular-jest-unit-testing-with-ngxs-state-router,"['angular', 'typescript', 'unit-testing', 'jestjs', 'ngxs']",458,False,2,0
How to get valid appcheck token when running on Firebase test lab devices?,"<p>I am running robo tests on a variety of devices in the Firebase Test Lab (e.g. Pixel 3, Api Level 28). The test devices cannot load data from the Firebase real-time database, because of an invalid app check token.</p>
<p>Relevant logs include:</p>
<blockquote>
<p>09-17 21:33:30.327: D/WebSocket(1870): ws_0 - websocket opened</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.327: D/WebSocket(1870): ws_0 - Reset keepAlive</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.327: D/WebSocket(1870): ws_0 - ws message: {&quot;t&quot;:&quot;c&quot;,&quot;d&quot;:{&quot;t&quot;:&quot;s&quot;,&quot;d&quot;:&quot;Invalid appcheck token&quot;}}</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.328: D/WebSocket(1870): ws_0 - Reset keepAlive. Remaining: 44999</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.328: D/WebSocket(1870): ws_0 - HandleNewFrameCount: 1</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.328: D/WebSocket(1870): ws_0 - handleIncomingFrame complete frame: {t=c, d={t=s, d=Invalid appcheck token}}</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.328: D/Connection(1870): conn_0 - Got control message: {t=s, d=Invalid appcheck token}</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.328: D/Connection(1870): conn_0 - Connection shutdown command received. Shutting down...</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.328: W/PersistentConnection(1870): pc_0 - Firebase Database connection was forcefully killed by the server. Will not attempt reconnect. Reason: Invalid appcheck token</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.328: D/PersistentConnection(1870): pc_0 - Connection interrupted for: server_kill</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.329: D/Connection(1870): conn_0 - closing realtime connection</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.329: D/WebSocket(1870): ws_0 - websocket is being closed</p>
</blockquote>
<blockquote>
<p>09-17 21:33:30.329: D/PersistentConnection(1870): pc_0 - Got on disconnect due to OTHER</p>
</blockquote>
<p>The same build runs on my phone (Pixel 3) and loads all data successfully.</p>
<p>I wondered if I needed to do something similar to what is described in &quot;Use the debug provider for unit testing in a CI environment&quot; (<a href=""https://firebase.google.com/docs/app-check/android/debug-provider"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/app-check/android/debug-provider</a>), but that doesn't make sense to me-- these are physical devices, right? (Furthermore, it's completely unclear to me how I'd go about following those steps from the Firebase console).</p>
<p>I'd greatly appreciate any hints or advice! Thank you.</p>
",https://stackoverflow.com/questions/69231753/how-to-get-valid-appcheck-token-when-running-on-firebase-test-lab-devices,"['android', 'firebase', 'firebase-realtime-database', 'firebase-test-lab', 'firebase-app-check']",385,False,1,0
Does Inversion of Control lead to Side Effects?,"<p>A question I've been struggling a lot with lately is how, in my opinion, Inversion of Control
breaks Encapsulation and can easily lead to side effects in a program. However, at the same time, some of the
big advatages of IoC is loose coupling/modularity as well as Test Driven Design making Unit testing a class much easier (I think TDD is really pushing IoC in the industry).</p>
<p>Here is my argument againt IoC.</p>
<p>If the injected types are Immutable and Pure then IoC is acceptable, for example primitive types. However, if they are impure
and can modify the state of the program or hold their own state then side effects can easily
occur.</p>
<p>Take the following example C#/Pseudo:</p>
<pre class=""lang-cs prettyprint-override""><code>public class FileSearcher: IFileSearcher
{
    private readonly string searchPath;

    public void SetSearchPath(string path)
    {
        searchPath = path;
    }

    public List&lt;string&gt; FindFiles(string searchPattern)
    {
        //...Search for files with searchPattern starting at searchPath
    }
}

public class PlayListViewer
{
    public PlayListViewer(string playlistName, IFileSearcher searcher)
    {
        searcher.SetSearchPath($&quot;playlists/{playlistName}&quot;)
    }


    public List&lt;string&gt; FindSongNames()
    {
        return searcher.FindFiles(
            &quot;*.mp3|*.wav|*.flac&quot;).Select(f =&gt; Path.GetFileName(f))
    }

//....other methods
}
</code></pre>
<pre class=""lang-cs prettyprint-override""><code>public class Program
{
    public static void Main()
    {
        var searcher = FileSearcher();
        var viewer = PlayListViewer(&quot;Hits 2021&quot;, searcher);

        searcher.SetSearchPath(&quot;C:/Users&quot;) //Messes up search path
        var pictures = searcher.FindFiles(&quot;*.jpg&quot;) //Using searcher for something else

        viewer
            .FindSongNames()
            .ForEach(s =&gt; Console.WriteLine(s)) //WRONG SONGS
    }
}
</code></pre>
<p>In the (very uncreative) example above, The PlaylistViewer has a method for finding songs within a playlist. It
attempts to set the correct search path for the playlist on the injected IFileSearcher, but the User of the class
overwrote the path. Now when they try to find the songs in the playlist, the results are incorrect.
The Users of a class do not always know the implementation of the class they're using and don't know the side
effects they're causing by mutating the objects they passed in.</p>
<p>Some other simple examples of this:</p>
<p>The Date Class in Java is not immutable and has a setDate (deprecated now) method. The following could occur:</p>
<pre class=""lang-cs prettyprint-override""><code>date = new Date(2021, 10, 1)
a = new A(date)
a.SomethingInteresting() //Adds 1 year to the Date using setDate
b = new B(date) //No longer the correct date
</code></pre>
<p>I/O abstractions such as streams:</p>
<pre class=""lang-cs prettyprint-override""><code>audioInput = new MemoryStream()
gainStage = new DSPGain(audioInput)
audioInput.write(....)
audioInput.close()
gainStage.run() //Error because memory stream is already closed
</code></pre>
<p>etc...</p>
<p>Other issues can come up too if the Object gets passed to multiple classes that use it across different threads concurrently. In these cases
a User might not know/realize that class X internally is launching/processing on a different thread.</p>
<p>I think the simple, and functional, answer would be to only write pure functions and immutable classes but that isn't always practical in the real world.</p>
<p>So when should IoC really be used? Maybe only when the injected types are immutable and pure and anything else should be composed and encapsulated? If that's the answer, then what does that mean for TDD?</p>
",https://stackoverflow.com/questions/69400440/does-inversion-of-control-lead-to-side-effects,"['oop', 'dependency-injection', 'inversion-of-control', 'encapsulation']",110,True,1,1
Why use service container instead of new class,"<p>In what scenario should we use a service container instead of calling a new class directly?
I read from Laravel official docs that it is mainly used for managing class dependency and performing dependency injection, however I am not sure if I understand it correctly.</p>
<p>For example payroll applications, we would have a Payroll class, Employee Class, Leave Class, Timesheet Class.
So to process a monthly payroll, Payroll class would depends on</p>
<ul>
<li>Employee Class (getBasicSalary)</li>
<li>Leave Class (getUnpaidLeaveCount)</li>
<li>Timesheet Class (getLateHoursCount)</li>
</ul>
<p>Below is what I normally writes (without any design pattern)</p>
<pre><code>Class PayrollProcessController 
{
    public function index(){
         $payrollObj = new Payroll();
         $payroll-&gt;setPayrollMonth('202106');
         $payroll-&gt;process();
    }
}

Class Payroll 
{
    private $payrollMonth;

    public function process()
    {
        // loop employee from database
        foreach ($employees as $employee_id){
             $salary = $this-&gt;calculateNetSalary($employee_id); 
             // save into db
        }
    }

    public function calculateNetSalary($employee_id)
    {
         $employee = Employee::find($employee_id);
         $basicSalary = $employee-&gt;getBasicSalary();
         $basicSalaryPerDay = $basicSalary / date('t');         
         $basicSalaryPerHour = $basicSalaryPerDay / 8;
         $leaveTakenDay = Leave::getUnpaidLeaveCount( $employee-&gt;getId(), $this-&gt;payrollMonth);
         $leaveDeductionAmount = $basicSalaryPerDay * $leaveTakenDay;
         $timesheetLateHours = Timesheet::getLateHoursCount($employee-&gt;getId(), $this-&gt;payrollMonth);
         $lateDeductionAmount = $basicSalaryPerHour * $timesheetLateHours;
         $netSalary = $basicSalary - $leaveDeductionAmount - $lateDeductionAmount;
         return $netSalary;
    }
}
</code></pre>
<p>If apply with service container concept,</p>
<pre><code>Class PayrollProcessController 
{
    public function index(Payroll $payroll){  
          $payroll-&gt;setPayrollMonth('202106');        
          $payroll-&gt;process();
    }
}

Class Payroll 
{
    public function process()
    {
        // loop employee from database
        foreach ($employees as $employee_id){

            $employee = app(Employee::class);
            $employee = $employee-&gt;find($employee_id);
            $leave = app(Leave::class);
            $timesheet = app(Timesheet::class);

            $salary = $this-&gt;calculateNetSalary($employee, $leave, $timesheet); 
             // save into db
        }
    }

    public function calculateNetSalary(Employee $employee, Leave $leave, Timesheet $timesheet)
    {
         $basicSalary = $employee-&gt;getBasicSalary();
         $basicSalaryPerDay = $basicSalary / date('t');         
         $basicSalaryPerHour = $basicSalaryPerDay / 8;
         $leaveTakenDay = $leave-&gt;getUnpaidLeaveCount( $employee-&gt;getId(), $this-&gt;payrollMonth);
         $leaveDeductionAmount = $basicSalaryPerDay * $leaveTakenDay;
         $timesheetLateHours = $timesheet-&gt;getLateHoursCount($employee-&gt;getId(), $this-&gt;payrollMonth);
         $lateDeductionAmount = $basicSalaryPerHour * $timesheetLateHours;
         $netSalary = $basicSalary - $leaveDeductionAmount - $lateDeductionAmount;
         return $netSalary;
    }
}

</code></pre>
<p>Questions:</p>
<ol>
<li><p>Is the above concept correct? I can see with service container it allows me to move the payroll, employee, timesheet, leave class into a laravel package so I can install in another laravel application (and the main benefits is I can re-use the code and also overrides the class if needed by specify the class path in service provider)</p>
</li>
<li><p>I checked again on the service container documentation
<a href=""https://laravel.com/docs/8.x/container#when-to-use-the-container"" rel=""nofollow noreferrer"">https://laravel.com/docs/8.x/container#when-to-use-the-container</a>, it is written:</p>
<blockquote>
<p>First, if you write a class that implements an interface and you wish to type-hint that interface on a route or class constructor, you must tell the container how to resolve that interface. Secondly, if you are writing a Laravel package that you plan to share with other Laravel developers, you may need to bind your package's services into the container.</p>
</blockquote>
<p>So can I say that unless we are publishing the payroll modules as a laravel package for others to use or to write unit testing, there is no point in using a service container?</p>
</li>
<li><p>If we look at opencart's registry class, is that is similar to Laravel's service container?
<a href=""https://github.com/opencart/opencart/blob/e22ddfb060752cd8134abbfb104202172ab45c86/upload/system/framework.php#L9"" rel=""nofollow noreferrer"">https://github.com/opencart/opencart/blob/e22ddfb060752cd8134abbfb104202172ab45c86/upload/system/framework.php#L9</a></p>
</li>
<li><p>Take an example from opencart, so Language class is singleton design pattern, while registry is container design pattern?</p>
<pre><code>$language = new \Opencart\System\Library\Language($config-&gt;get('language_code'));
$language-&gt;addPath(DIR_LANGUAGE);
$language-&gt;load($config-&gt;get('language_code'));
$registry-&gt;set('language', $language);
</code></pre>
</li>
</ol>
",https://stackoverflow.com/questions/68120707/why-use-service-container-instead-of-new-class,"['php', 'laravel', 'design-patterns', 'containers']",574,True,1,1
Cannot satisfy wrapper parameter for react testing library render function using TypeScript,"<p>I'm trying to build a convenience function that allows me to pass a react component and have it render the component with all of the options and route specifications that I want that I pass it wrapped around a <code>&lt;BrowserRouter&gt;</code> for unit testing.</p>
<p>The problem is when I try to pass <code>Wrapper</code> function into react testing library's <code>render()</code> (see <code>rtlRender()</code> below), I'm getting an error from TypeScript stating the following</p>
<blockquote>
<p>No overload matches this call.
Overload 1 of 2, '(ui: ReactElement&lt;any, string | JSXElementConstructor&gt;, options: RenderOptions&lt;Queries, HTMLElement&gt;): RenderResult&lt;...&gt;', gave the following error.
Type '({ children }: Props) =&gt; JSX.Element' is not assignable to type 'ComponentType&lt;{}&gt; | undefined'.
Type '({ children }: Props) =&gt; JSX.Element' is not assignable to type 'FunctionComponent&lt;{}&gt;'.
Types of parameters '__0' and 'props' are incompatible.
Type '{ children?: ReactNode; }' is not assignable to type 'Props'.
Types of property 'children' are incompatible.
Type 'ReactNode' is not assignable to type 'ReactChildren'.
Type 'undefined' is not assignable to type 'ReactChildren'.
Overload 2 of 2, '(ui: ReactElement&lt;any, string | JSXElementConstructor&gt;, options?: Omit&lt;RenderOptions&lt;typeof import(&quot;/Users/myuser/dev/myapp/container/node_modules/@testing-library/dom/types/queries&quot;), HTMLElement&gt;, &quot;queries&quot;&gt; | undefined): RenderResult&lt;...&gt;', gave the following error.
Type '({ children }: Props) =&gt; JSX.Element' is not assignable to type 'ComponentType&lt;{}&gt; | undefined'.
Type '({ children }: Props) =&gt; JSX.Element' is not assignable to type 'FunctionComponent&lt;{}&gt;'.ts(2769)
index.d.ts(41, 3): The expected type comes from property 'wrapper' which is declared here on type 'RenderOptions&lt;Queries, HTMLElement&gt;'
(property) RenderOptions&lt;Queries, HTMLElement&gt;.wrapper?: React.ComponentType&lt;{}&gt; | undefined</p>
</blockquote>
<p>Here's my code</p>
<pre><code>import React from 'react';
import { Queries, render as rtlRender } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
import { RenderResult } from '@testing-library/react/types';

/* Type Definitions */
type Route = {
  state: Record&lt;string, unknown&gt;;
  title: string;
  location: string;
};
type Props = {
  children: React.ReactChildren;
};

/* Helper Functions */
export function render(ui: JSX.Element, options: { route: Route }): RenderResult&lt;Queries, HTMLElement&gt; {
  const { route } = options;
  window.history.pushState(route?.state ?? null, route?.title ?? 'Root', route?.location ?? '/');

  const Wrapper = ({ children }: Props) =&gt; {
    return &lt;BrowserRouter&gt;{children}&lt;/BrowserRouter&gt;;
  };

  return rtlRender(ui, { wrapper: Wrapper, ...options });
}
</code></pre>
<p>From what I understand, it's telling me that whatever <code>Wrapper()</code> returns doesn't fit the description of a React class component or functional component. This seems weird to me because you can tell from the code, <code>Wrapper()</code> should return a functional component.</p>
<p>I tried to assign <code>Wrapper()</code> to type <code>React.FC&lt;Props&gt;</code>, but TypeScript states that <code>React.FC&lt;Props&gt;</code> is not of type <code>React.ComponentType</code> which made me even more confused.</p>
<p>I'm still new to TypeScript so throwing in all these React types is confusing me even more. I'm hoping for some guidance on this.</p>
",https://stackoverflow.com/questions/68809613/cannot-satisfy-wrapper-parameter-for-react-testing-library-render-function-using,"['reactjs', 'typescript', 'react-router-dom', 'react-testing-library', 'react-typescript']",2480,True,1,1
Udacity - Flask Python,"<p>I've been working on a Udacity course on unit testing flask application.</p>
<p>All the files needed are in this <a href=""https://github.com/udacity/nd0044-c2-API-Development-and-Documentation-exercises/tree/master/3_Testing_Review"" rel=""nofollow noreferrer"">Github link</a>, and we will just focus on the &quot;backend&quot; directory.  This directory contains the flaskr directory and two files - one of which  is the <code>test_flaskr.py</code>, where there is this <a href=""https://github.com/udacity/nd0044-c2-API-Development-and-Documentation-exercises/blob/master/3_Testing_Review/backend/test_flaskr.py#L82-L93"" rel=""nofollow noreferrer"">test_delete_book</a> method that i am trying to fix.</p>
<p>The way this <code>test_delete_book</code> test method is coded currently it will only pass the FIRST test (and will fail in succeeding tests).  So what I am trying to do is to get the value of the 'id' key of the last Book entry, and pass it to the <code>delete book</code> API .  There is another <a href=""https://github.com/udacity/nd0044-c2-API-Development-and-Documentation-exercises/blob/master/3_Testing_Review/backend/test_flaskr.py#L64-L71"" rel=""nofollow noreferrer"">test_create_new_book</a> method in the same test file <code>test_flaskr.py</code> that ensures the Book table will never run out of data (thus the <code>test_delete_book</code> will never fail after my code change.</p>
<p>By the way, here is the <a href=""https://github.com/udacity/nd0044-c2-API-Development-and-Documentation-exercises/blob/master/3_Testing_Review/backend/models.py#L26-L32"" rel=""nofollow noreferrer"">link</a> to the Book table structure.</p>
<p>Here is my code for the test_delete_book (emphasis on just two lines - lines 03 and 04):</p>
<pre><code>01    # Delete a different book in each attempt
02    def test_delete_book(self):
03        book = Book.query.order_by(Book.id.desc()).first()
04        book_id_to_delete = book.id
05        # res = self.client().delete('/books/&lt;book_id_to_delete')
06        res = self.client().delete('/books/' + str(book_id_to_delete))
07        data = json.loads(res.data)
80
09        book = Book.query.filter(Book.id == book_id_to_delete).one_or_none()
10
11        self.assertEqual(res.status_code, 200)
12        self.assertEqual(data['success'], True)
13        self.assertEqual(data['deleted'], book_id_to_delete)
14        self.assertTrue(data['total_books'])
15        self.assertTrue(len(data['books']))
16        self.assertEqual(book, None)
</code></pre>
<p>On line 03 I coded the SQLAlchemy query to get the book.id value of the last Book table entry, and save off the last book id value in the <code>book_id_to_delete</code> variable.  BTW this test actually interfaces with a database (not mocked).  Before I run the test, I noted the &quot;id&quot; key of the last Book table entry.  When i ran the test, <em><strong>all tests passed</strong></em>, but the last table entry was still in the table.  Also, I did not see a new record that's supposed to be created by the <code>test_create_new_book</code> method I mentioned earlier.</p>
<p>Here is where it gets weird (at least for me):</p>
<p>When I modified line #04 by replacing the &quot;book.id&quot; with the actual book id value of the last entry in the Book table THEN ran the tests, not only did the last entry gets DELETED from the Book table, but I can also see the new book table record that's created by the <code>test_create_new_book</code> method.</p>
<p>Any helpful input would be very much appreciated.</p>
",https://stackoverflow.com/questions/68414200/udacity-flask-python,"['python', 'api', 'flask', 'python-unittest']",63,True,0,1
check whether a directory contains all (and only) the listed files,"<p>I'm writing unit-tests to test file-IO functions.
There's no formalized test-framework in my target language, so my idea is to run a little test program that somehow manipulates files in a test-directory, and after that checks the results in a little shell script.</p>
<p>To evaluate the output, I want to check a given directory whether all expected files are there and no other files have been created during the test.</p>
<p>My first attempt goes like this:</p>
<pre class=""lang-sh prettyprint-override""><code>set -e

test -e &quot;${test_dir}/a.txt&quot;
test -e &quot;${test_dir}/b.txt&quot;
test -d &quot;${test_dir}/dir&quot;
find &quot;${test_dir}&quot; -mindepth 1 \
     -not -wholename &quot;${test_dir}/a.txt&quot; \
     -not -wholename &quot;${test_dir}/b.txt&quot; \
     -not -wholename &quot;${test_dir}/dir&quot; \
    | grep . &amp;&amp; exit 1 || true
</code></pre>
<p>This properly detects whether there are two files <code>a.txt</code> and <code>b.txt</code>, and a subdirectory <code>dir/</code> in the <code>${test_dir}</code>.
If there happens to be a file <code>c.txt</code>, the test should and will fail.</p>
<p>However, this doesn't scale well.
There are dozens of unit-tests and each has a different set of files/directories, so I find myself repeating lines very similar to the above again and again.</p>
<p>So I'd rather wrap the above into a function call like so:</p>
<pre class=""lang-sh prettyprint-override""><code>if checkdirectory &quot;${test_dir}&quot; a.txt b.txt dir/ dir/subdir/ dir/.hidden.txt; then
  echo &quot;ok&quot;
else
  echo &quot;ko&quot;
fi
</code></pre>
<p>Unfortunately I have no clue how to implement <code>checkdirectory</code> (esp. the <code>find</code> invocation with multiple <code>-not -wholename ...</code> stanzas gives me headache).</p>
<p>To add a bit of fun, the constraints are:</p>
<ul>
<li>support both (and differentiate between) files and directories</li>
<li><em>must</em> (EDITed from <em>should</em>) run on Linux, macOS &amp; MSYS2/MinGW, therefore:</li>
<li><em>POSIX</em> if possible (in reality it will be <code>bash</code>, but probably bash&lt;&lt;4! so no fancy features)</li>
</ul>
<h3>EDIT</h3>
<p>some more constraints (these didn't make it into original my late-night question; so just consider them &quot;extra constraints for bonus points&quot;)</p>
<ul>
<li>the test-directory may contain subdirectories and files in  subdirectories (up to an arbitrary depth), so any check needs to operate on more than just the top-level directory</li>
<li>ideally, the paths may contain weirdo characters like spaces, linebreaks,... (this is really unit-testing. we do want to test for such cases)</li>
<li>the <code>testdir</code> is more often than not some randomly generated directory using <code>mktemp -d</code>, so it would be nice if we could avoid hardcoding it in the tests</li>
<li>no assumptions about the underlying filesystem can be made.</li>
</ul>
",https://stackoverflow.com/questions/67494824/check-whether-a-directory-contains-all-and-only-the-listed-files,"['bash', 'shell', 'unit-testing', 'filesystems', 'sh']",236,True,-1,4
PyTest and controlled test failure for GitHub Workflow/Automation,"<p>Although I've been using Python for a number of years now, I realised that working predominantly on personal projects, I never needed to do Unit testing before, so apologies for the obvious questions or wrong assumptions I might make.
My goal is to understand how I can make tests and possibly combine everything with the GitHub workflow to create some automation.
I've seen Failures/Errors (which are conceptually different) thrown locally are not treated differently once online. But before I go, I have some doubts that I want to clarify.</p>
<p>From reading online, my initial understanding seems to be that a test should always SUCCEED, even if it contains errors or failure.
But if it succeeds, how can then I record a failure or an error? So I'm tempted to say I'm capturing this in the wrong way?
I appreciate that in an Agile environment, some would like to say it's a controlled process, and errors can be intercepted while looking into the code. But I'm not sure this is the best approach.<br>And this leads me to the second question.</p>
<p>Say I have a function accepting dates, and I know that it cannot accept anything else than that.</p>
<ol>
<li>Would it make sense to do a test to say pass in strings (and get
a failure)?</li>
<li>Or should I test only for the expected circumstances?</li>
</ol>
<p>Say case 1) is a best practice; what should I do in the context of running these tests? Should I let the test fail and get a long list of errors? Or should I decorate functions with a <code>@pytest.mark.xfail()</code> (a sort of Soft fail, where I can use a try ... catch)?</p>
<p>And last question (for now): would an xfail decorator let the workflow automation consider the test as &quot;passed&quot;. Probably not, but at this stage, I've so much confusion in my head that any clarity from experienced users could help.</p>
<p>Thanks for your patience in reading.</p>
",https://stackoverflow.com/questions/69681830/pytest-and-controlled-test-failure-for-github-workflow-automation,"['python', 'unit-testing', 'pytest']",165,True,0,1
"Django database routers - how do you test them, especially for migrations?","<p>I've read the <a href=""https://docs.djangoproject.com/en/2.2/topics/db/multi-db/#database-routers"" rel=""nofollow noreferrer"">documentation</a> on database routers in Django 2.2.  I more or less understand the concept - including keeping certain tables together - except that it seems somewhat tricky to do in practice.</p>
<p>My instincts when things are complicated and interdependent is to use unit tests to gradually get my code to return expected results.  Except that I don't know how to write tests in this case.</p>
<h3>Databases in settings:</h3>
<pre><code>DATABASES = {
    &quot;default&quot;: {
        &quot;ENGINE&quot;: constants.POSTGRES_ENGINE,
        &quot;NAME&quot;: constants.SYSDBNAME,
        ...
    },
    &quot;userdb&quot;: {
        &quot;ENGINE&quot;: constants.POSTGRES_ENGINE,
        &quot;NAME&quot;: constants.USERDBNAME,

}

</code></pre>
<h3>Routers in settings:</h3>
<pre><code>
DATABASE_ROUTERS = [
    #the user database - userdb - which gets the auths and user-related stuff
    &quot;bme.websec.database_routers.UserdbRouter&quot;,

    #the default database - sysdb - gets most of the other models
    &quot;bme.websec.database_routers.SysdbMigrateRouter&quot;,
]

</code></pre>
<p>Ideally I would use unit tests to submit all my models one by one to the routers' <code>allow_migrate</code>, <code>db_for_read</code>, <code>db_for_write</code> methods, and for each call, verify that I got the expected results.</p>
<p>But is there a way to do that?  I suppose I can use</p>
<pre><code>models = django.apps.apps.get_models(
        include_auto_created=True, include_swapped=True
    )
</code></pre>
<p>and then drive those methods calls from unittests.</p>
<p>But to take just</p>
<pre><code>def allow_migrate(self, db, app_label, model_name=None, **hints):

</code></pre>
<ul>
<li><p>How do I know when to have <code>**hints</code> and whether <code>model_name</code> is always provided or not?</p>
</li>
<li><p>And most importantly, how do I simulate what the master router ultimately decides as stated in the doc (my emphasis)?  Among other things, it doesn't rely on just one router, it calls both in succession and then &quot;does things&quot; if my custom routers return None, so unit testing my routers by calling them individually doesn't really replicate the master router's behavior.</p>
</li>
</ul>
<blockquote>
<p>The master router is used by Django’s database operations to allocate database usage. Whenever a query needs to know which database to use, it calls the master router, providing a model and a hint (if available). Django then tries each router in turn until a database suggestion can be found. <strong>If no suggestion can be found, it tries the current _state.db of the hint instance. If a hint instance wasn’t provided, or the instance doesn’t currently have database state, the master router will allocate the default database.</strong></p>
</blockquote>
<p>I've gotten <code>db_for_read</code> and <code>db_for_write</code> mostly to behave, but I am struggling to get migrations working correctly : most models end up in <code>userdb</code> rather than <code>default</code>.</p>
<p>So far, what I am doing is running migrations against 2 empty databases and using postgresql to check where tables were created.  Drop databases, adjust routers, re-run.  Is there a better way to <strong>unit test</strong> the actual decision-making of which database gets what model tables for migrations (write and read are nice-to-have, not the primary reason for this question)?</p>
",https://stackoverflow.com/questions/68233451/django-database-routers-how-do-you-test-them-especially-for-migrations,"['django', 'unit-testing', 'django-migrations', 'multi-database']",828,True,1,1
"How to effectively run .net core unit test with selenium, from published web app","<p>I have a .NET Core v2.2 application. I am trying to start Selenium UI tests, built on top of unit testing project (tried using NUnit, xUnit).</p>
<p>The tests can be started locally from VS(using TestExplorer), or from started locally .NET Core 2.2 app.</p>
<p>The goal is to be able to start test, once the app is deployed in IIS, using button in a view.</p>
<p>I've tried both starting the test using reflection, and instantiating the class, or starting it as process (by running nunit3-console.exe, dotnet test or vstest.console.exe) in command line.</p>
<p>When using</p>
<pre><code>dotnet test {PathToTestDll} --filter &quot;Name ~{testName}&quot; --logger trx --results-directory {resultDir}
</code></pre>
<p>command, I can start the test from cmd, but when trying to open the published site, I get error for missing dll</p>
<blockquote>
<p>Could not load file or assembly 'Microsoft.VisualStudio.Coverage.CoreLib.Net, Version=16.9.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.<br />
System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types.), which is part of VS Enterprise, I am currently using VS Professional 2019 Version 16.9.1.</p>
</blockquote>
<p>If I try and use</p>
<pre><code>nunit3-console.exe --test={testFullyQualifiedName} {PathToTestDll}
</code></pre>
<p>I get another error for missing nunit.framework package:</p>
<blockquote>
<p>NUnit.Engine.NUnitEngineException : An exception occurred in the driver while loading tests.<br />
System.IO.FileNotFoundException : Could not load file or assembly 'nunit.framework, Version=3.12.0.0, Culture=neutral, PublicKeyToken=2638cd05610744eb' or one of its dependencies. The system cannot find the file specified.<br />
--NUnitEngineException<br />
An exception occurred in the driver while loading tests.) regardless if I execute it in the dir, where the nunit.framework file is located (C:\Users{user}.nuget\packages\nunit{version}), or the published project's dir (somewhere in C:\inetpub\wwwroot{projectName}).</p>
</blockquote>
<p>Now when using reflection, after the app is published, the test fail, with the same error (javascript error: Failed to execute 'elementsFromPoint' on 'Document': The provided double value is non-finite. (Session info: chrome=88.0.4324.190)), which is a Selenium error, for using not unique way to locate element, if I am not mistaken. For each test. I've checked them and can assure  you, it is not the case.</p>
<p>By this time, I have accepted that I am doing something, or everything wrong, but cannot pin-point what.</p>
<p>I have to say, that I currently use NUnit3, chromedriver v88.0.4324.96, Selenium.WebDriver 3.141.0</p>
",https://stackoverflow.com/questions/66624980/how-to-effectively-run-net-core-unit-test-with-selenium-from-published-web-app,"['c#', 'selenium', 'asp.net-core', 'xunit', 'nunit-3.0']",312,False,1,0
Making python COM client testable,"<p>I have read about unit testing in python, but all examples I found are based on trivial examples of mocking objects. I have no idea how to really implement tests for the project in a way it can be tested without accessing COM port. project is mainly used for control of another application via COM API plus evaluating data produced by app and making reports, so let's say it is higher abstraction level api made as python library. COM interface is non-trivial, with main object that is exposing some managers, the managers exposing containers of objects, that are having references to another objects, so a web of conencted objects responsible for different things controlled application. Architecture of python library somehow follows the COM structure. During library import main COM object is dispatched and stored in central module, manager-level modules on import are getting references to COM manager objects from central module and then manager-level methods are using this COM manager objects in their methods. Examples for better understanding</p>
<pre><code>#__init__
from managera import ManagerA
from centralobject import CentralObject
central_object = CentralObject()
manager_a = ManagerA()  #here all initialisation to make everything work,
manager_b = ManagerB()  #so full com object needed to import the package
...

#centalobject
class CentalObject():
    def __init__():
        self.com = Dispatch(&quot;application&quot;)
...

#managera
from project import central_object
class ManagerA():
    def __init__():
        self.com = central_object.com.manager_a
def manager_a_method1(x):
    foo = self.com.somecontainer[x].somemethod()
    foo.configure(3)
    return foo
...
</code></pre>
<p>In current state it is hard to test. It is even not possible import without connection to the COM app. Dispatch could be moved into some init function that is executed after the import, but I don't see how it would make the testing possible. One solution would be to make test double that have structutre similar to the original application, but for my unexperienced in testing mind it seems a bit overkill to do this in each method test. Maybe it is not and that's how it should be done, I am asking somebody's more experience advice.
Second solutuon that came to my mind is to dispatch COM object every time any COM call is made, and then mock it but it seems a lot of dispatches and I don't see how it makes the code better.
Tried also with managers not being defined as classes, but modules, however it seemed even more hard to test as then COM managers was refrerenced during module import, not object instantiation.</p>
<p>What should be done to make testing posible and nice without accessing COM? Interested in everything: solution, advice or just topic that I should read more about.</p>
",https://stackoverflow.com/questions/65692086/making-python-com-client-testable,"['python', 'unit-testing', 'mocking']",34,False,1,0
C# - Menu Implementation - Help writing it in a testable way,"<p><strong>The Question:</strong></p>
<p>I'm developing an app in C# and am currently designing a menu which contains submenus and needs to be different depending on the category of the user.</p>
<p>I've written the code but am struggling to structure it so that it is testable.</p>
<p>I've read a lot about unit testing and testable code but still find it tough to write it well - I was hoping people could give me some pointers on re-structuring so that it's testable and so I'm not setting myself up for trouble down the road.</p>
<p><strong>The Code:</strong></p>
<p><strong>A menu item:</strong></p>
<pre><code>public struct Item
{
    public string HRef { get; set; }
    public string Title { get; set; }

    public Item(string hRef, string title)
    {
        HRef = hRef;
        Title = title;
    }
}
</code></pre>
<p><strong>A menu:</strong></p>
<p>It has a list of items and a list of submenus (I took inspiration from how a directory tree is structured with files and folders)</p>
<pre><code>public class Menu
{
    public string Name { get; set; }
    public List&lt;Item&gt; Items { get; set; }
    public List&lt;Menu&gt; SubMenus { get; set; }

    public Menu(string name, List&lt;Item&gt; items, List&lt;Menu&gt; subMenus)
    {
        Name = name;
        Items = items;
        SubMenus = subMenus;
    }
}
</code></pre>
<p><strong>The Menu Manager: - The thing under test</strong></p>
<p>The menu manager contains a repository where I get the category of a user from</p>
<p>It has a GetMenu() method which accepts the user name and returns the correct menu depending on the user's category.</p>
<p>It has two private methods which build the menu for each category (currently just Admin and Default but will eventually be more).</p>
<pre><code>public class Manager
    {
        WorkflowPlusApp.Database.IInfoStaffRepository repository;

        public Manager(IInfoStaffRepository repository)
        {
            this.repository = repository;
        }

        public Menu GetMenu(string userName)
        {
            var userCategory = repository.GetStaffCategory(userName);

            switch(userCategory)
            {
                case &quot;Admin&quot;: return GetAdminMenu();
                
                default: return GetDefaultMenu();
            }
        }




        private Menu GetAdminMenu()
        {
            return new Menu(
                name: &quot;/&quot;,
                items: new List&lt;Item&gt;()
                {
                    new Item(hRef: &quot;&quot;, title: &quot;Request Form&quot;),
                    new Item(hRef: &quot;&quot;, title: &quot;Tasks&quot;),
                    new Item(hRef: &quot;&quot;, title: &quot;Project&quot;),
                },
                subMenus: new List&lt;Menu&gt;()
                {
                    new Menu(
                        name: &quot;/Config&quot;,
                        items: new List&lt;Item&gt;()
                        {
                            new Item(hRef: &quot;&quot;, title: &quot;Area&quot;)
                        },
                        subMenus: new List&lt;Menu&gt;())
                });
        }




        private Menu GetDefaultMenu()
        {
            return new Menu(
                name: &quot;/&quot;,
                items: new List&lt;Item&gt;()
                {
                    new Item(hRef: &quot;&quot;, title: &quot;Request Form&quot;),                    
                },
                subMenus: new List&lt;Menu&gt;());
        }
    }
</code></pre>
<p><strong>The Unit Test</strong></p>
<p>I've written a unit test using MSTest and Moq</p>
<pre><code>[TestMethod()]
        public void GetMenu_Staff_Admin_Returns_Admin_Menu()
        {
            var userName = &quot;TestUser&quot;;

            //Setup Mock
            var mockRepository = new Mock&lt;WorkflowPlusApp.Database.IInfoStaffRepository&gt;();
            mockRepository.Setup(x =&gt; x.GetStaffCategory(userName)).Returns(&quot;Admin&quot;);
            
            //Setup
            var manager = new Menus.Manager(mockRepository.Object);
            var menu = manager.GetMenu(userName);

            //Test - Does it return the Admin menu?
            Assert.IsTrue(menu.Items.Count == 3);
            Assert.IsTrue(menu.Items[0].Title == &quot;Request Form&quot;);
            Assert.IsTrue(menu.Items[0].Title == &quot;Tasks&quot;);
            Assert.IsTrue(menu.Items[0].Title == &quot;Project&quot;);
            Assert.IsTrue(menu.SubMenus.Where(x =&gt; x.Name == &quot;Config&quot;).ToList()[0].Items.Count == 1);
            Assert.IsTrue(menu.SubMenus.Where(x =&gt; x.Name == &quot;Config&quot;).ToList()[0].Items[0].Title == &quot;Area&quot;);
        }
</code></pre>
<p>The Admin menu should be returned in a particular order and have particular entries so I thought by using the Titles I'm testing a behaviour - if the menu changes it should fail and alert me that the menu isn't right for Admin staff.</p>
<p>I can't help feeling like this test is tied to much to the implementation and is bad code though.</p>
<p>In setting up the Mock I have to know two things:</p>
<p>That the Manager's GetMenu() function calls the repository's GetStaffCategory() function</p>
<p>That the category the repository returns is Admin</p>
<p>So I'm tying myself to two of the Manager's implementation details - if they change I'll have to change the test code</p>
<p>I would love to be able to write code well and while the books and articles I've read are helpful I still find it difficult to do in practice, any help or suggestions - even if it's scrap the whole thing and use a simple Dictionary -  would be helpful towards me learning to write testable decent code.</p>
<p>Many Thanks</p>
<p>Nick</p>
",https://stackoverflow.com/questions/65818433/c-menu-implementation-help-writing-it-in-a-testable-way,"['c#', 'unit-testing', 'testing', 'refactoring']",129,False,1,0
