title,body,link,tags,view_count,is_answered,score,answer_count
unit testing callbackFlow,"<p>I have a callback based API like this:</p>
<pre><code>  class CallbackApi {
    fun addListener(callback: Callback) {
      // todo
    }

    fun removeListener(callback: Callback) {
      // todo
    }

    interface Callback {
      fun onResult(result: Int)
    }
  }
</code></pre>
<p>and an extension function which converts the API into a <strike>hot</strike> cold flow:</p>
<pre><code>  fun CallbackApi.toFlow() = callbackFlow&lt;Int&gt; {
    val callback = object : CallbackApi.Callback {
      override fun onResult(result: Int) {
        trySendBlocking(result)
      }
    }
    addListener(callback)
    awaitClose { removeListener(callback) }
  }
</code></pre>
<p>Would you mind suggesting how to write a unit test which ensures that the API is correctly converted to a hot flow?</p>
<p>Here is my attempt. By trial and error, I came up with this solution.</p>
<pre><code>  @Test
  fun callbackFlowTest() = runBlocking {
    val callbackApi = mockk&lt;CallbackApi&gt;()
    val callbackSlot = slot&lt;CallbackApi.Callback&gt;()
    every { callbackApi.addListener(capture(callbackSlot)) } just Runs
    every { callbackApi.removeListener(any()) } just Runs
    val list = mutableListOf&lt;Int&gt;()
    val flow: Flow&lt;Int&gt; = callbackApi.toFlow().onEach { list.add(it) }
    val coroutineScope = CoroutineScope(this.coroutineContext + SupervisorJob())
    flow.launchIn(coroutineScope)
    yield()
    launch {
      callbackSlot.captured.onResult(10)
      callbackApi.removeListener(mockk()) // this was a misunderstanding
    }.join()
    assert(list.single() == 10)
  }
</code></pre>
<p>But I don't understand two pieces of this solution.</p>
<p>1- In the absence of that <code>SupervisorJob()</code>, it appears that test will never end. Maybe collecting the flow never ends for some reason, which I don't understand. I'm feeding captured callback in a separate coroutine.</p>
<p>2- If I remove the <code>launch</code> body which <code>callbackSlot.captured.onResult(10)</code> is inside it, test will fail with this error <code>UninitializedPropertyAccessException: lateinit property captured has not been initialized</code>. I would think that <code>yield</code> should start the flow.</p>
",https://stackoverflow.com/questions/70576533/unit-testing-callbackflow,"['unit-testing', 'kotlin', 'kotlin-coroutines']",1374,True,6,3
Unit Testing Combine,"<p>I'm having difficulties testing Combine. I'm following:</p>
<ul>
<li><a href=""https://www.swiftbysundell.com/articles/unit-testing-combine-based-swift-code/"" rel=""nofollow noreferrer"">https://www.swiftbysundell.com/articles/unit-testing-combine-based-swift-code/</a></li>
</ul>
<p>Which tests:</p>
<pre class=""lang-swift prettyprint-override""><code>final class ViewModel {
    @Published private(set) var tokens = [String]()
    @Published var string = &quot;&quot;
 
    private let tokenizer = Tokenizer()

    init () {
        $string
            .flatMap(tokenizer.tokenize)
            .replaceError(with: [])
            .assign(to: &amp;$tokens)
    }
}

struct Tokenizer {
    func tokenize(_ string: String) -&gt; AnyPublisher&lt;[String], Error&gt; {
        let strs = string.components(separatedBy: &quot; &quot;)
        return Just(strs)
            .setFailureType(to: Error.self)
            .eraseToAnyPublisher()
    }
}
</code></pre>
<p>with the following:</p>
<pre><code>func testTokenizingMultipleStrings() throws {
    let viewModel = ViewModel()
    let tokenPublisher = viewModel.$tokens
        .dropFirst()
        .collect(2)
        .first()
    viewModel.string = &quot;Hello @john&quot;
    viewModel.string = &quot;Check out #swift&quot;
    let tokenArrays = try awaitPublisher(tokenPublisher)
    XCTAssertEqual(tokenArrays.count, 2)
    XCTAssertEqual(tokenArrays.first, [&quot;Hello&quot;, &quot;john&quot;])
    XCTAssertEqual(tokenArrays.last, [&quot;Check out&quot;, &quot;swift&quot;])
}
</code></pre>
<p>And the following helper function:</p>
<pre class=""lang-swift prettyprint-override""><code>extension XCTestCase {
    func awaitPublisher&lt;T: Publisher&gt;(
        _ publisher: T,
        timeout: TimeInterval = 10,
        file: StaticString = #file,
        line: UInt = #line
    ) throws -&gt; T.Output {
        var result: Result&lt;T.Output, Error&gt;?
        let expectation = self.expectation(description: &quot;Awaiting publisher&quot;)
        let cancellable = publisher.sink(
            receiveCompletion: { completion in
                switch completion {
                case .failure(let error):
                    result = .failure(error)
                case .finished:
                    break
                }
                expectation.fulfill()
            },
            receiveValue: { value in
                result = .success(value)
            }
        )
        waitForExpectations(timeout: timeout)
        cancellable.cancel()
        let unwrappedResult = try XCTUnwrap(
            result,
            &quot;Awaited publisher did not produce any output&quot;,
            file: file,
            line: line
        )
        return try unwrappedResult.get()
    }
}
</code></pre>
<p>Here <code>receiveValue</code> is never called so the test doesn't complete.
How can I get this test to pass?</p>
",https://stackoverflow.com/questions/71276105/unit-testing-combine,"['swift', 'xctest', 'combine']",2440,True,3,2
Unit testing AmazonS3ClientBuilder,"<p>How do we unit test this line of code
AmazonS3 s3Client = AmazonS3ClientBuilder.standard().withRegion(Regions.EU_WEST_1).build();</p>
",https://stackoverflow.com/questions/72936180/unit-testing-amazons3clientbuilder,"['unit-testing', 'junit', 'mockito', 'powermockito']",40,False,0,0
Unit testing. java.lang.NullPointerException,"<p>everyone! I am writing unit tests for the mobile app. But I have an error that I don't know how to solve. The error has the following form:</p>
<pre><code>java.lang.NullPointerException
    at androidx.appcompat.app.AppCompatDelegateImpl.createSubDecor(AppCompatDelegateImpl.java:841)
    at androidx.appcompat.app.AppCompatDelegateImpl.ensureSubDecor(AppCompatDelegateImpl.java:806)
    at androidx.appcompat.app.AppCompatDelegateImpl.findViewById(AppCompatDelegateImpl.java:630)
    at androidx.appcompat.app.AppCompatActivity.findViewById(AppCompatActivity.java:223)
    at com.example.projectMP3.SplashScreenActivityTest.testLaunchOfNewActivity(SplashScreenActivityTest.java:14)
    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 com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
</code></pre>
<p><strong>Program code &quot;SplashScreenActivity.java&quot;</strong>:</p>
<pre><code>public class SplashScreenActivity extends AppCompatActivity {
    LinearLayout linearLayout;
    /** Toolbar */
    androidx.appcompat.widget.Toolbar toolbar;

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

        toolbar = findViewById(R.id.toolBar);
        setSupportActionBar(toolbar);

        linearLayout = findViewById(R.id.Splash_Activity);
        linearLayout.setOnClickListener(v -&gt; {
            Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
            startActivity(intent);
            finish();
        });

        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
        );

        Objects.requireNonNull(getSupportActionBar()).hide();

        Thread thread = new Thread() {
            public void run() {
                try {
                    sleep(3000);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    Intent intent = new Intent(SplashScreenActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        };
        thread.start();
    }
}
</code></pre>
<p><strong>Program code &quot;SplashScreenActivityTest.java&quot;</strong>:</p>
<pre><code>import android.widget.TextView;

import org.junit.Test;

import static org.junit.Assert.assertNotNull;

public class SplashScreenActivityTest {

    @Test
    public void testLaunchOfNewActivity() {
        SplashScreenActivity activity = new SplashScreenActivity();
        TextView nameApplication =  activity.findViewById(R.id.textView3);
        assertNotNull(nameApplication.getText());
    }
}
</code></pre>
<p><strong>Program code &quot;activity_splash_screen.xml&quot;</strong>:</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:id=&quot;@+id/Splash_Activity&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:background=&quot;@color/colorPrimaryDark&quot;
    android:orientation=&quot;vertical&quot;
    tools:context=&quot;.SplashScreenActivity&quot;&gt;
    &lt;androidx.appcompat.widget.Toolbar

        android:id=&quot;@+id/toolBar&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;?actionBarSize&quot;
        android:background=&quot;@drawable/tab_indicater&quot;
        android:theme=&quot;@style/ThemeOverlay.AppCompat.Dark.ActionBar&quot; /&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:gravity=&quot;center&quot;
        android:orientation=&quot;vertical&quot;&gt;

        &lt;ImageView
            android:id=&quot;@+id/imageView2&quot;
            android:layout_width=&quot;320dp&quot;
            android:layout_height=&quot;320dp&quot;
            android:layout_gravity=&quot;center_horizontal&quot;
            app:srcCompat=&quot;@drawable/splash_screen_logo&quot;
            android:layout_marginTop=&quot;100dp&quot;
            app:tint=&quot;#120a8f&quot;
            android:contentDescription=&quot;@string/startSplashScreen&quot; /&gt;
    &lt;/LinearLayout&gt;

    &lt;TextView
        android:id=&quot;@+id/textView3&quot;
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:fontFamily=&quot;cursive&quot;
        android:gravity=&quot;center&quot;
        android:text=&quot;@string/appName&quot;
        android:textColor=&quot;#FFAB00&quot;
        android:textSize=&quot;50sp&quot;
        android:paddingLeft=&quot;30dp&quot;
        android:paddingRight=&quot;30dp&quot;
        android:layout_marginTop=&quot;2dp&quot;
        android:textStyle=&quot;bold&quot; /&gt;

    &lt;LinearLayout
        android:layout_width=&quot;match_parent&quot;
        android:layout_height=&quot;match_parent&quot;
        android:gravity=&quot;bottom&quot;
        android:orientation=&quot;vertical&quot;&gt;

        &lt;TextView
            android:id=&quot;@+id/textView&quot;
            android:layout_width=&quot;match_parent&quot;
            android:layout_height=&quot;wrap_content&quot;
            android:gravity=&quot;center&quot;
            android:text=&quot;@string/all_rights_are_reserved&quot;
            android:textColor=&quot;@color/white&quot;
            android:textSize=&quot;15sp&quot; /&gt;
    &lt;/LinearLayout&gt;
&lt;/LinearLayout&gt;
</code></pre>
<p>This is my first time writing unit tests. I hope for your help! Thank you in advance.</p>
",https://stackoverflow.com/questions/72395146/unit-testing-java-lang-nullpointerexception,"['android-studio', 'unit-testing', 'nullpointerexception', 'junit4', 'assertion']",512,False,0,2
Pega Unit Testing,"<p>Which two conditions do you test with a unit test? (Choose Two)</p>
<pre><code>A . A data page populates without any errors.

B . A property value is set correctly by a data transform.

C . An application displays user views for 20 users within three
seconds.

D . An application is successfully migrated to a test system.
</code></pre>
<p>My answer is A and C. Can someone confirm it, and If different please explain.</p>
",https://stackoverflow.com/questions/73804321/pega-unit-testing,['pega'],133,False,-1,1
Unit testing asp.net6,"<p>My unit test is getting passed but in debugging it gives <strong>object reference not set to an instance</strong><br />
I used NUnit testing method.<br />
How can I cross check whether both contents are same</p>
<p>controller:</p>
<pre class=""lang-cs prettyprint-override""><code>[HttpGet(&quot;MerchantId&quot;)]
public async Task&lt;ActionResult&lt;List&lt;Product&gt;&gt;&gt; GetProductByMerchantId(int MerchantId)
{
    return await _repository.GetProductByMerchantId(MerchantId);
}
</code></pre>
<p>unit test code:</p>
<pre class=""lang-cs prettyprint-override""><code>using Amazon.Controllers;
using Amazon.Models;
using Amazon.Repository;
using Microsoft.AspNetCore.Mvc;
    
namespace AmazonAPI_UnitTest
{
    public class Tests
    {
        private readonly IMerchantRepository _repository;
        MerchantController m;
        Merchant TestMerchant;
        Merchant TestMethod;
    
        [SetUp]
        public void Setup()
        {
            m = new MerchantController(_repository);
            TestMerchant = new Merchant();
            TestMerchant.MerchantId = 40006;
            TestMerchant.MerchantName = &quot;akhil&quot;;
            TestMerchant.MerchantEmail = &quot;akhil@outlook.com&quot;;
            TestMerchant.MerchantPhoneNumber = &quot;9876543210&quot;;
            TestMerchant.MerchantPassword = &quot;12345&quot;;
            TestMerchant.ConfirmPassword = &quot;12345&quot;;
        }
    
        [Test]
        public void Test1()
        {
            var result = m.GetMerchant(4006);
            Assert.IsNotNull(result);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/73566049/unit-testing-asp-net6,"['asp.net', 'unit-testing', 'nunit']",93,False,0,0
Flutter unit testing firestore,"<p>I'm new to unit testing in general. I'm trying to test simple method from my DataRepository.</p>
<p>Following this link but seems deprecated: <a href=""https://utkarshkore.medium.com/writing-unit-tests-in-flutter-with-firebase-firestore-72f99be85737"" rel=""nofollow noreferrer"">https://utkarshkore.medium.com/writing-unit-tests-in-flutter-with-firebase-firestore-72f99be85737</a></p>
<pre><code>class DataRepository {
  final CollectionReference collection =
      FirebaseFirestore.instance.collection('notes');

  //Retour de models a la place de snapshots
  Stream&lt;QuerySnapshot&gt; getStream() {
    return collection.snapshots();
  }

  Stream&lt;QuerySnapshot&gt; getStreamDetail(String id) {
    return collection.doc(id).collection('tasks').snapshots();
  }

  Stream&lt;List&lt;Note&gt;&gt; noteStream() {
    final CollectionReference collection =
        FirebaseFirestore.instance.collection('notes');

    try {
      return collection.snapshots().map((notes) {
        final List&lt;Note&gt; notesFromFirestore = &lt;Note&gt;[];
        for (var doc in notes.docs) {
          notesFromFirestore.add(Note.fromSnapshot(doc));
        }
        return notesFromFirestore;
      });
    } catch (e) {
      rethrow;
    }
  }
</code></pre>
<p>So far this is what my test file look like:</p>
<pre><code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';

class MockFirestore extends Mock implements FirebaseFirestore {}
class MockCollectionReference extends Mock implements CollectionReference {}

void main() {
  MockFirestore instance = MockFirestore();
  MockCollectionReference mockCollectionReference = MockCollectionReference();

  test('should return data when the call to remote source is succesful.',
      () async {
    when(instance.collection('notes')).thenReturn(mockCollectionReference);
  });
}
</code></pre>
<p>First instance throw me this error</p>
<pre><code>The argument type 'MockCollectionReference' can't be assigned to the parameter type 'CollectionReference&lt;Map&lt;String, dynamic&gt;&gt;'
</code></pre>
<p>I would really appreciate the help for testing the method.</p>
<p>new edit:</p>
<pre><code>void main() {
  test('should return data when the call to remote source is succesful.',
      () async {
    final FakeFirebaseFirestore fakeFirebaseFirestore = FakeFirebaseFirestore();
    final DataRepository dataRepository = DataRepository();
    final CollectionReference mockCollectionReference =
        fakeFirebaseFirestore.collection(dataRepository.collection.path);

    final List&lt;Note&gt; mockNoteList = &lt;Note&gt;[];

    for (Note mockNote in mockNoteList) {
      await mockCollectionReference.add(mockNote.toJson());
    }

    final Stream&lt;List&lt;Note&gt;&gt; noteStreamFromRepository =
        dataRepository.noteStream();

    final List&lt;Note&gt; actualNoteList = await noteStreamFromRepository.first;
    final List&lt;Note&gt; expectedNoteList = mockNoteList;

    expect(actualNoteList, expectedNoteList);
  });
}
</code></pre>
",https://stackoverflow.com/questions/71370219/flutter-unit-testing-firestore,"['firebase', 'flutter', 'unit-testing', 'google-cloud-firestore', 'mockito']",2261,True,4,2
Flutter FirebaseAuth unit testing,"<p>I'm trying to test my whole AuthManager class which use FirebaseAuth to signin, login. Here my file:</p>
<pre><code>    class AuthManager extends ChangeNotifier {
      final FirebaseAuth auth;
    
      Stream&lt;User?&gt; get user =&gt; auth.authStateChanges();
    
      static Future&lt;FirebaseApp&gt; initializeFirebase({
        required BuildContext context,
      }) async {
        FirebaseApp firebaseApp = await Firebase.initializeApp();
    
        return firebaseApp;
      }
    
      AuthManager({required this.auth});
    
      Future&lt;String&gt; signup(String email, String password) async {
        try {
          final credential = await auth.createUserWithEmailAndPassword(
            email: email,
            password: password,
          );
          return &quot;Success&quot;;
        } on FirebaseAuthException catch (e) {
          rethrow;
        }
      }
    
      Future&lt;String&gt; signInWithEmailAndPassword(
          String email, String password) async {
        try {
          final userCredential = await auth.signInWithEmailAndPassword(
              email: email, password: password);
          return &quot;Success&quot;;
        } on FirebaseAuthException catch (e) {
          return &quot;Failed&quot;;
        } catch (e) {
          rethrow;
        }
      }
    
      static Future&lt;String&gt; signOut() async {
        try {
          await FirebaseAuth.instance.signOut();
          return &quot;Success&quot;;
        } catch (e) {
          rethrow;
        }
      }
    }
</code></pre>
<p>I used to return the usercredential but wanted to try test a simple string return for the test, following this tutorial: <a href=""https://www.youtube.com/watch?v=4d6hEaUVvuU"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=4d6hEaUVvuU</a>, here is my test file</p>
<pre><code>import 'package:firebase_auth/firebase_auth.dart';
import 'package:notes_firebase_app/data/models/auth_manager.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';

class MockFirebaseAuth extends Mock implements FirebaseAuth {
  @override
  Stream&lt;User&gt; authStateChanges() {
    return Stream.fromIterable([
      _mockUser,
    ]);
  }
}

class MockUser extends Mock implements User {}

final MockUser _mockUser = MockUser();

class MockUserCredential extends Mock implements Future&lt;UserCredential&gt; {}

void main() {
  final MockFirebaseAuth mockFirebaseAuth = MockFirebaseAuth();
  final AuthManager authManager = AuthManager(auth: mockFirebaseAuth);
  final MockUserCredential mockUserCredential = MockUserCredential();
  setUp(() {});
  test(&quot;emit occurs&quot;, () async {
    expectLater(authManager.user, emitsInOrder([_mockUser]));
  });

  test(&quot;create account&quot;, () async {
    when(mockFirebaseAuth.createUserWithEmailAndPassword(
            email: &quot;tadas@gmail.com&quot;, password: &quot;123456&quot;))
        .thenAnswer((realInvocation) =&gt; null);

    expect(
        await authManager.signInWithEmailAndPassword(
            &quot;tadas@gmail.com&quot;, &quot;123456&quot;),
        &quot;Success&quot;);
  });
}
</code></pre>
<p>I face two problems here, cannot pass null because we need to handle it now or this throw this error</p>
<pre><code>The return type 'Null' isn't a 'Future&lt;UserCredential&gt;', as required by the closure's context
</code></pre>
<p>Then I tried to mock UserCredential like this.</p>
<pre><code>  final MockUserCredential mockUserCredential = MockUserCredential();

    when(mockFirebaseAuth.createUserWithEmailAndPassword(
            email: &quot;tadas@gmail.com&quot;, password: &quot;123456&quot;))
        .thenAnswer((realInvocation) =&gt; mockUserCredential);
</code></pre>
<p>but I'm getting this error:</p>
<pre><code>type 'Null' is not a subtype of type 'Future&lt;UserCredential&gt;'
</code></pre>
<p>What am I doing wrong ? Help will be much appreciated.</p>
",https://stackoverflow.com/questions/71392970/flutter-firebaseauth-unit-testing,"['flutter', 'unit-testing', 'firebase-authentication', 'mockito']",1448,True,4,1
Unit testing with gorm,"<p>I have found a lot of questions regarding gorm mocking related to the old V1 package: <a href=""https://github.com/jinzhu/gorm"" rel=""nofollow noreferrer"">github.com/jinzhu/gorm</a>. with the usage of <a href=""https://github.com/DATA-DOG/go-sqlmock"" rel=""nofollow noreferrer"">github.com/DATA-DOG/go-sqlmock</a>.</p>
<p>I didn't find much with the v2.
My simple question is:</p>
<p>Suppose I have this storage package code:</p>
<pre><code>...
type Storage struct {
    GormDB       *gorm.DB
    SqlDB        *sql.DB
    mutex        sync.Mutex
    ReadTimeout  int
    WriteTimeout int
}

func (ps *Storage) Open(settings *Settings) error {
    if err := settings.Validate(); err != nil {
        return err
    }

    ps.mutex.Lock()
    defer ps.mutex.Unlock()

    if ps.GormDB != nil {
        return nil
    }

    gormDB, err := gorm.Open(postgres.New(postgres.Config{
        DSN: settings.GetDSN(),
    }), &amp;gorm.Config{
        SkipDefaultTransaction: true,
    })
    if err != nil {
        return fmt.Errorf(&quot;%s: %v&quot;, DBConnectError, err)
    }

    ps.GormDB = gormDB

    sqlDB, err := ps.GormDB.DB()
    if err != nil {
        return fmt.Errorf(&quot;%s: %v&quot;, DBRetrievalError, err)
    }

    ps.SqlDB = sqlDB
    ps.SqlDB.SetMaxIdleConns(settings.MaxIdleConnections)
    ps.SqlDB.SetMaxOpenConns(settings.MaxOpenConnections)

    ps.ReadTimeout = settings.ReadTimeout
    ps.WriteTimeout = settings.WriteTimeout

    return nil
}
</code></pre>
<p>How can I unit-test this function with a simple check that <code>gorm.Open</code> received the expected config?</p>
<p>I don't see any other way than passing the ORM interface to this method... It would be a tough solution to write a gorm interface and mock it myself...</p>
<p>Can anyone please provide a simple example of mocking such a function?</p>
<p>P.S.
I don't want to run the docker with Postgres for this test. It is a simple unit test, not integration.</p>
<p><strong>EDIT</strong>:
Suppose I just want to mock the connection to make <code>gorm.Open</code> to not return an error. How can I do it?
<code>sqlmock.NewWithDSN(settings.GetDSN())</code> does not help</p>
",https://stackoverflow.com/questions/74770045/unit-testing-with-gorm,"['unit-testing', 'go', 'go-gorm']",170,False,4,1
React Form Unit Testing,"<p><em>I'm new to react js and was trying to unit test my react form but i'm getting an error saying &quot;Unable to find an element by: [data-testid=&quot;input-first-name&quot;].
It would be of great help if someone can suggest something</em></p>
<p><strong>AddUser.js</strong></p>
<ul>
<li>Here,i'm posting a small part of my code</li>
</ul>
<pre><code>return (
    &lt;&gt;
      {isLoggedIn === &quot;true&quot; ? (
        &lt;div data-testid=&quot;user&quot;&gt;
          &lt;NavbarAdmin /&gt;
          &lt;div className={styles.body}&gt;
            &lt;h2 className={styles.h2}&gt;Add User&lt;/h2&gt;
            &lt;form className={styles.form}
            data-testid=&quot;filter-input-form&quot;&gt;
              &lt;div className={styles.formField}&gt;
                &lt;label
                  htmlFor=&quot;validationServer01&quot;
                  style={{ marginLeft: &quot;-131px&quot;, marginBottom: &quot;0px&quot; }}
                  className=&quot;form-label&quot;
                &gt;
                  First Name &lt;span style={{ color: &quot;#D22B2B&quot; }}&gt;*&lt;/span&gt;
                &lt;/label&gt;
                &lt;input
                  style={inputStyle}
                  className=&quot;Form control lg is-invalid&quot;
                  type=&quot;text&quot;
                  name=&quot;FirstName&quot;
                  placeholder=&quot;Enter your First-Name&quot;
                  value={fname}
                  onBlur={() =&gt; fieldValidation(&quot;fname&quot;)}
                  onChange={(e) =&gt; {
                    setFName(e.target.value);
                  }}
                  data-testid=&quot;input-first-name&quot;
                  required
                /&gt;
                &lt;br /&gt;
                {fNameEmpty === true ? (
                  &lt;div
                    className=&quot;invalid-feedback&quot;
                    style={{
                      marginBottom: &quot;15px&quot;,
                      marginTop: &quot;-25px&quot;,
                      marginLeft: &quot;-30px&quot;,
                    }}
                  &gt;
                    Please Enter First Name!
                  &lt;/div&gt;
                ) : (
                  &quot;&quot;
                )}
              &lt;/div&gt;
              &lt;button
                className={styles.btn}
                type=&quot;submit&quot;
                onClick={handleClick}
                disabled={isDisabled}
                data-testid=&quot;add-users-button&quot;
              &gt;
                Add User
              &lt;/button&gt;
            &lt;/form&gt;
          &lt;/div&gt;
        &lt;/div&gt;
      ) : (
        &quot;&quot;
      )}
    &lt;/&gt;
  );
</code></pre>
<p><strong>AddUser.test.js</strong></p>
<ul>
<li>This is the test case</li>
</ul>
<pre><code>import React from &quot;react&quot;;
import AddUsers from &quot;../Containers/User/AddUsers&quot;;
import {
  render,
  waitFor,
  screen,
  fireEvent,
  act,
  getByTestId

} from &quot;@testing-library/react&quot;;
import { BrowserRouter } from &quot;react-router-dom&quot;;
import userEvent from '@testing-library/user-event';

describe('AddUser component', () =&gt; {

    it('should render the component onto the screen', () =&gt; {
        render(&lt;BrowserRouter&gt;&lt;AddUsers show={true}/&gt; &lt;/BrowserRouter&gt;);
        expect(screen.getByTestId('input-first-name')).toBe(&quot;&quot;);
    });
</code></pre>
<p><strong>Error</strong>
<a href=""https://i.stack.imgur.com/wTTjM.png"" rel=""nofollow noreferrer"">Click here to see the error</a>
[I guess,this error is occuring because of the ternary operator]</p>
",https://stackoverflow.com/questions/72573890/react-form-unit-testing,"['javascript', 'reactjs', 'react-bootstrap']",177,False,2,0
Unit testing custom validator,"<p>My validator looks like:</p>
<pre><code>&lt;?php

declare(strict_types=1);

namespace App\Infrastructure\Domain\Model\Company\Validator;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;
use Symfony\Contracts\Translation\TranslatorInterface;

final class ContainsUnsupportedSymbolsValidator extends ConstraintValidator
{
    public function __construct(
        private TranslatorInterface $translator
    )
    {
    }

    public function validate($value, Constraint $constraint): void
    {
        if (!$constraint instanceof ContainsUnsupportedSymbols) {
            throw new UnexpectedTypeException($constraint, ContainsUnsupportedSymbols::class);
        }

        // custom constraints should ignore null and empty values to allow
        // other constraints (NotBlank, NotNull, etc.) to take care of that
        if (null === $value || '' === $value) {
            return;
        }

        if (!is_string($value)) {
            // throw this exception if your validator cannot handle the passed type so that it can be marked as invalid
            throw new UnexpectedValueException($value, 'string');
        }

        if (!preg_match('/^\+?[0-9]{3}-?[0-9]{6,12}$/', $value, $matches)) {
            // the argument must be a string or an object implementing __toString()
            $this-&gt;context-&gt;buildViolation(
                $this-&gt;translator-&gt;trans($constraint-&gt;message, ['{phone}' =&gt; $value])
            )-&gt;addViolation();
        }
    }
}
</code></pre>
<p>The test I wrote for valid case is:</p>
<pre><code>&lt;?php

declare(strict_types=1);

namespace App\Tests\Unit\Infrastructure\Domain\Model\Company\Validator;

use App\Infrastructure\Domain\Model\Company\Validator\ContainsUnsupportedSymbols;
use App\Infrastructure\Domain\Model\Company\Validator\ContainsUnsupportedSymbolsValidator;
use App\Tests\Unit\UnitTestCase;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

final class ContainsUnsupportedSymbolsValidatorTest extends UnitTestCase
{
    public function testValidatorWithValidPhone():void
    {
        $phone = &quot;+359883202020&quot;;

        $translationMock = $this-&gt;createMock(TranslatorInterface::class);

        $constraint = new ContainsUnsupportedSymbols();

        $constraintValidator = new ContainsUnsupportedSymbolsValidator($translationMock);

        $this-&gt;assertEmpty($constraintValidator-&gt;validate($phone, $constraint));
    }
}
</code></pre>
<p>Is it correct to test with <code>assertEmpty</code> when the <code>validate</code> method return type is <code>void</code>?
And how to test with incorrect data? Tried to mock the <code>context</code> and both <code>buildViolation</code> and <code>addViolation</code> methods but got error:</p>
<blockquote>
<p>Error: Call to a member function buildViolation() on null</p>
</blockquote>
<p>This is what I tried with incorrect phone</p>
<pre><code>public function testValidatorWithInvalidPhone():void
    {
        $phone = &quot;+359()883202020&quot;;

        $translationMock = $this-&gt;createMock(TranslatorInterface::class);

        $contextMock = $this-&gt;createMock(ExecutionContextInterface::class);
        $contextMock-&gt;expects($this-&gt;once())
            -&gt;method('buildViolation')
            -&gt;with('message');
        $contextMock-&gt;expects($this-&gt;once())
            -&gt;method('addViolation');

        $constraint = new ContainsUnsupportedSymbols();

        $constraintValidator = new ContainsUnsupportedSymbolsValidator($translationMock);

        $this-&gt;assertEmpty($constraintValidator-&gt;validate($phone, $constraint));
    }
</code></pre>
",https://stackoverflow.com/questions/72692784/unit-testing-custom-validator,"['symfony', 'phpunit']",259,True,1,1
Unit testing mbed application,"<p>I'm working on an mbed application and I want to be able to unit test some of the functionality. I created a test app so I could try out unit testing and I can't seem to get it to build. The TLDR of it is when I go to build the app the build fails with errors like:</p>
<pre><code>C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/CMSIS_5/CMSIS/RTOS2/RTX/Source/rtx_core_c.h:42:2: error: #error &quot;Unknown Arm Architecture!&quot;
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2015:40: error: 'fileno' was not declared in this scope; did you mean 'file'?
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2021:47: error: 'strdup' was not declared in this scope; did you mean 'StrDup'?
</code></pre>
<p>The more detailed version of it, on Windows I created a new app by:</p>
<pre><code>1. mbed-tools new
2. mbed-tools configure -m K64F -t GCC_ARM
</code></pre>
<p>Then I created a simple class to be tested <code>MyClass.h</code> and <code>MyClass.cpp</code></p>
<pre><code>#include &quot;MyClass.h&quot;

MyClass::MyClass() { }

bool MyClass::IsTwo(int number) {
    return number == 2;
}
</code></pre>
<p>And then also a simple test file <code>UNITTESTS\test_MyClass.cc</code></p>
<pre><code>#include &quot;gtest/gtest.h&quot;
#include &quot;../MyClass.h&quot;

class TestMyClass : public testing::Test {
protected:
    MyClass *cls;

    void SetUp(){
        cls = new MyClass();
    }

    void TearDown(){
        delete cls;
    }
};

TEST_F(TestMyClass, test_isTwo){
    EXPECT_TRUE(cls-&gt;IsTwo(2));
    EXPECT_FALSE(cls-&gt;IsTwo(23));
}
</code></pre>
<p>Then following the instructions from Google found <a href=""https://google.github.io/googletest/quickstart-cmake.html"" rel=""nofollow noreferrer"">here</a> I edited my root <code>CMakeList.txt</code> to be</p>
<pre><code># Copyright (c) 2022 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.19.0)

# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)

set(MBED_PATH ${CMAKE_CURRENT_SOURCE_DIR}/mbed-os CACHE INTERNAL &quot;&quot;)
set(MBED_CONFIG_PATH ${CMAKE_CURRENT_BINARY_DIR} CACHE INTERNAL &quot;&quot;)
set(APP_TARGET gtest_example)

include(${MBED_PATH}/tools/cmake/app.cmake)

project(${APP_TARGET})

# Disable tests as default configuration, use -DBUILD_TESTING to enable
option(BUILD_TESTING &quot;Run mbed os UNITTESTS&quot; ON)

add_subdirectory(${MBED_PATH})

if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING)
    add_subdirectory(${MBED_PATH}/UNITTESTS) # add mbed os stubs and fakes
    add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/UNITTESTS)
endif()

include(FetchContent)
FetchContent_Declare(
        googletest
        GIT_REPOSITORY https://github.com/google/googletest.git
        GIT_TAG release-1.12.1
)
# For Windows: Prevent overriding the parent projects compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL &quot;&quot; FORCE)
FetchContent_MakeAvailable(googletest)

add_executable(${APP_TARGET}
    main.cpp
    MyClass.cpp MyClass.h
)

target_link_libraries(${APP_TARGET} mbed-os)

mbed_set_post_build(${APP_TARGET})

option(VERBOSE_BUILD &quot;Have a verbose build process&quot;)
if(VERBOSE_BUILD)
    set(CMAKE_VERBOSE_MAKEFILE ON)
endif()
</code></pre>
<p>and the <code>UNITTESTS\CMakeLists.txt</code> file to be</p>
<pre><code>set(TEST_NAME example-unittest)

enable_testing()

add_executable(${TEST_NAME}
        test_MyClass.cc
        )

target_link_libraries(${TEST_NAME}
        GTest::gtest_main
        )
include(GoogleTest)
gtest_discover_tests(${TEST_NAME})
</code></pre>
<p>Then I ran</p>
<pre><code>cmake -S . -B cmake_build\K64F\develop\GCC_ARM -GNinja -DBUILD_TESTING=ON -DCMAKE_CXX_FLAGS=-std=c++14
</code></pre>
<p>resulting in</p>
<pre><code>-- The C compiler identification is GNU 10.3.1
-- The CXX compiler identification is GNU 10.3.1
-- The ASM compiler identification is GNU
-- Found assembler: C:/Program Files (x86)/GNU Arm Embedded Toolchain/10 2021.10/bin/arm-none-eabi-gcc.exe
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: C:/Program Files (x86)/GNU Arm Embedded Toolchain/10 2021.10/bin/arm-none-eabi-gcc.exe - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files (x86)/GNU Arm Embedded Toolchain/10 2021.10/bin/arm-none-eabi-g++.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found Python3: C:/Python39/python.exe (found version &quot;3.9.7&quot;) found components: Interpreter
-- Checking for Python package prettytable -- found
-- Checking for Python package future -- found
-- Checking for Python package jinja2 -- found
-- Checking for Python package intelhex -- found
-- Found Python: C:/Python39/python.exe (found version &quot;3.9.7&quot;) found components: Interpreter
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - not found
-- Check if compiler accepts -pthread
-- Check if compiler accepts -pthread - no
-- Could NOT find Threads (missing: Threads_FOUND)
-- Could NOT find Threads (missing: Threads_FOUND)
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM
</code></pre>
<p>and then finally I ran</p>
<pre><code>cmake --build cmake_build\K64F\develop\GCC_ARM
</code></pre>
<p>which fails with a bunch of errors</p>
<pre><code>[75/208] Building CXX object _deps/googletest-build/googletest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.obj
FAILED: _deps/googletest-build/googletest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @_deps\googletest-build\googletest\CMakeFiles\gtest_main.dir\src\gtest_main.cc.obj.rsp -MD -MT _deps/googletest-build/googletest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.obj -MF _deps\googletest-build\googletest\CMakeFiles\gtest_main.dir\src\gtest_main.cc.obj.d -o _deps/googletest-build/googletest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.obj -c C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/src/gtest_main.cc
In file included from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/gtest-message.h:55,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/gtest-assertion-result.h:46,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/gtest.h:59,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/src/gtest_main.cc:32:
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'int testing::internal::posix::FileNo(FILE*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2015:40: error: 'fileno' was not declared in this scope; did you mean 'file'?
 2015 | inline int FileNo(FILE* file) { return fileno(file); }
      |                                        ^~~~~~
      |                                        file
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'char* testing::internal::posix::StrDup(const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2021:47: error: 'strdup' was not declared in this scope; did you mean 'StrDup'?
 2021 | inline char* StrDup(const char* src) { return strdup(src); }
      |                                               ^~~~~~
      |                                               StrDup
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'FILE* testing::internal::posix::FDOpen(int, const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2065:56: error: 'fdopen' was not declared in this scope; did you mean 'fopen'?
 2065 | inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
      |                                                        ^~~~~~
      |                                                        fopen
[77/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\cmsis\device\rtos\source\mbed_rtx_idle.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\cmsis\device\rtos\source\mbed_rtx_idle.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/internal/SysTimer.h:21,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/internal/mbed_os_timer.h:21,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp:27:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/CMSIS_5/CMSIS/RTOS2/RTX/Source/rtx_lib.h:31,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/internal/mbed_os_timer.h:25,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp:27:
C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/CMSIS_5/CMSIS/RTOS2/RTX/Source/rtx_core_c.h:42:2: error: #error &quot;Unknown Arm Architecture!&quot;
   42 | #error &quot;Unknown Arm Architecture!&quot;
      |  ^~~~~
[78/208] Building CXX object _deps/googletest-build/googlemock/CMakeFiles/gmock_main.dir/src/gmock_main.cc.obj
FAILED: _deps/googletest-build/googlemock/CMakeFiles/gmock_main.dir/src/gmock_main.cc.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @_deps\googletest-build\googlemock\CMakeFiles\gmock_main.dir\src\gmock_main.cc.obj.rsp -MD -MT _deps/googletest-build/googlemock/CMakeFiles/gmock_main.dir/src/gmock_main.cc.obj -MF _deps\googletest-build\googlemock\CMakeFiles\gmock_main.dir\src\gmock_main.cc.obj.d -o _deps/googletest-build/googlemock/CMakeFiles/gmock_main.dir/src/gmock_main.cc.obj -c C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/src/gmock_main.cc
In file included from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/internal/gmock-port.h:57,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/internal/gmock-internal-utils.h:49,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/gmock-actions.h:145,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/gmock.h:56,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/src/gmock_main.cc:32:
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'int testing::internal::posix::FileNo(FILE*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2015:40: error: 'fileno' was not declared in this scope; did you mean 'file'?
 2015 | inline int FileNo(FILE* file) { return fileno(file); }
      |                                        ^~~~~~
      |                                        file
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'char* testing::internal::posix::StrDup(const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2021:47: error: 'strdup' was not declared in this scope; did you mean 'StrDup'?
 2021 | inline char* StrDup(const char* src) { return strdup(src); }
      |                                               ^~~~~~
      |                                               StrDup
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'FILE* testing::internal::posix::FDOpen(int, const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2065:56: error: 'fdopen' was not declared in this scope; did you mean 'fopen'?
 2065 | inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
      |                                                        ^~~~~~
      |                                                        fopen
[79/208] Building CXX object CMakeFiles/gtest_example.dir/main.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/main.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\main.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/main.cpp.obj -MF CMakeFiles\gtest_example.dir\main.cpp.obj.d -o CMakeFiles/gtest_example.dir/main.cpp.obj -c C:/Users/chris/Desktop/gtest_example/main.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\analogin.h:25,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/mbed.h:63,
                 from C:/Users/chris/Desktop/gtest_example/main.cpp:6:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/mbed.h:75,
                 from C:/Users/chris/Desktop/gtest_example/main.cpp:6:
c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\mbedcrc.h:658:2: error: #error &quot;Unknown ARM architecture for CRC optimization&quot;
  658 | #error &quot;Unknown ARM architecture for CRC optimization&quot;
      |  ^~~~~
[80/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/AnalogIn.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/AnalogIn.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\AnalogIn.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/AnalogIn.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\AnalogIn.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/AnalogIn.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/AnalogIn.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\analogin.h:25,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/AnalogIn.cpp:18:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[81/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SerialBase.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SerialBase.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\SerialBase.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SerialBase.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\SerialBase.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SerialBase.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/SerialBase.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_wait_api.h:21,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/SerialBase.cpp:18:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[82/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/FlashIAP.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/FlashIAP.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\FlashIAP.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/FlashIAP.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\FlashIAP.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/FlashIAP.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/FlashIAP.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\flashiap.h:30,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/FlashIAP.cpp:28:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[83/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/platform/cxxsupport/mstd_mutex.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/platform/cxxsupport/mstd_mutex.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\platform\cxxsupport\mstd_mutex.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/platform/cxxsupport/mstd_mutex.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\platform\cxxsupport\mstd_mutex.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/platform/cxxsupport/mstd_mutex.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/platform/cxxsupport/mstd_mutex.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\platform\cxxsupport\mstd_mutex:43,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/cxxsupport/mstd_mutex.cpp:18:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[84/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/I2C.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/I2C.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\I2C.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/I2C.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\I2C.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/I2C.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/I2C.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\i2c.h:26,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/I2C.cpp:18:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[85/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/MbedCRC.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/MbedCRC.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\MbedCRC.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/MbedCRC.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\MbedCRC.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/MbedCRC.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/MbedCRC.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\mbedcrc.h:29,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/MbedCRC.cpp:19:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/MbedCRC.cpp:19:
c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\mbedcrc.h:658:2: error: #error &quot;Unknown ARM architecture for CRC optimization&quot;
  658 | #error &quot;Unknown ARM architecture for CRC optimization&quot;
      |  ^~~~~
[86/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/platform/source/DeepSleepLock.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/platform/source/DeepSleepLock.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\platform\source\DeepSleepLock.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/platform/source/DeepSleepLock.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\platform\source\DeepSleepLock.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/platform/source/DeepSleepLock.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/platform/source/DeepSleepLock.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/source/DeepSleepLock.cpp:20:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[87/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SPI.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SPI.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\SPI.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SPI.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\SPI.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SPI.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/SPI.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\spi.h:27,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/SPI.cpp:17:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[88/208] Building CXX object _deps/googletest-build/googlemock/CMakeFiles/gmock.dir/src/gmock-all.cc.obj
FAILED: _deps/googletest-build/googlemock/CMakeFiles/gmock.dir/src/gmock-all.cc.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @_deps\googletest-build\googlemock\CMakeFiles\gmock.dir\src\gmock-all.cc.obj.rsp -MD -MT _deps/googletest-build/googlemock/CMakeFiles/gmock.dir/src/gmock-all.cc.obj -MF _deps\googletest-build\googlemock\CMakeFiles\gmock.dir\src\gmock-all.cc.obj.d -o _deps/googletest-build/googlemock/CMakeFiles/gmock.dir/src/gmock-all.cc.obj -c C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/src/gmock-all.cc
In file included from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/internal/gmock-port.h:57,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/internal/gmock-internal-utils.h:49,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/gmock-actions.h:145,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/gmock.h:56,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/src/gmock-all.cc:39:
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'int testing::internal::posix::FileNo(FILE*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2015:40: error: 'fileno' was not declared in this scope; did you mean 'file'?
 2015 | inline int FileNo(FILE* file) { return fileno(file); }
      |                                        ^~~~~~
      |                                        file
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'char* testing::internal::posix::StrDup(const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2021:47: error: 'strdup' was not declared in this scope; did you mean 'StrDup'?
 2021 | inline char* StrDup(const char* src) { return strdup(src); }
      |                                               ^~~~~~
      |                                               StrDup
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'FILE* testing::internal::posix::FDOpen(int, const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2065:56: error: 'fdopen' was not declared in this scope; did you mean 'fopen'?
 2065 | inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
      |                                                        ^~~~~~
      |                                                        fopen

...

ninja: build stopped: subcommand failed.
</code></pre>
",https://stackoverflow.com/questions/73241424/unit-testing-mbed-application,"['c++', 'unit-testing', 'cmake', 'googletest', 'mbed']",204,True,1,1
System.NullReferenceException when unit testing,"<p>I am new to unit testing,</p>
<p>I am working on a minimal API project. and I am testing an endpoint with xunit, moq</p>
<p>endpoint class - ParticipantsGetAll.cs</p>
<pre><code>public class ParticipantsGetAll : IEndpoint&lt;IResult, GetAllParticipantsRequest&gt;
{
    const string uri = &quot;api/participants-all&quot;;
    private ParticipantService? participantService;

    public void AddRoute(IEndpointRouteBuilder app)
    {
        app.MapPost(uri, async ( ParticipantService participantService, [FromBody] GetAllParticipantsRequest query) =&gt; 
        {
            this.participantService = participantService;
            return await HandleAsync(query);
        })
        .Produces&lt;List&lt;ParticipantSummaryModel&gt;&gt;()
        .WithTags(&quot;Participants&quot;)
        .WithName(&quot;GetAllParticipants&quot;);
    }

    public async Task&lt;IResult&gt; HandleAsync( GetAllParticipantsRequest query)
    {
        var participants = await participantService!.ListAllAsync(query);
        return Results.Ok(participants);
    }
</code></pre>
<p>I tried to write a unit test test above endpoint class.</p>
<p>CreateParticipantApiTest.cs</p>
<pre><code>    [Fact]
    public async void ListAllAsyncShouldReturn200Status()
    {
        var query = new GetAllParticipantsRequest()
        {
           Name= &quot;&quot;,
            KeyCordinator=&quot;&quot;,
            RelatedConnection=&quot;&quot;,
            Statuses = null

        };
        var participant = ParticipantMockData.NewParticipantModel(); // a static class

        var sut = new ParticipantsGetAll();
        var result = (OkObjectResult)await sut.HandleAsync(query);

        result.StatusCode.Should().Be(200);

    }
</code></pre>
<p>I got below error</p>
<blockquote>
<p>Message: 
System.NullReferenceException : Object reference not set to an instance of an object.<br />
Stack Trace: 
ParticipantsGetAll.HandleAsync(GetAllParticipantsRequest query) line 36
CreateParticipantApiTest.ListAllAsyncShouldReturn200Status() line 67</p>
</blockquote>
<p>I have no idea why the object tis null.</p>
<p>Please anyone help me to find the problem.
I am facing this issue for a long time</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/74866807/system-nullreferenceexception-when-unit-testing,"['c#', 'unit-testing', 'moq', '.net-6.0', 'minimal-apis']",228,True,1,1
Json based unit testing,"<p>We have huge Data Objects which are a little too difficult to manage while creating test cases. In order to test the entire flow we have to create this big object and then assert on it. Sometimes setting up this object takes more effort than the actual testing part. Mock or Spying is also not feasible because that again requires writing more code and becomes difficult to manage with the increase in the number of fields to manage.</p>
<p>I am thinking of keeping the data objects in json files and then load them into memory. This keeps things manageable on our end and also speeds up our development process.</p>
<p>Does any one sees any flaws with this approach or have any suggestions ? We are using Java 8.</p>
",https://stackoverflow.com/questions/72190116/json-based-unit-testing,"['java', 'json', 'junit', 'mockito']",150,False,1,0
Unit Testing in Android,"<p>I am trying to unit test my repository . In that i want to write test for function which makes api calls.(function name :- searchImage)
The function calls datasource for actual api calls.
I am using a fake data source which extends from the shopping data source interface.
How can i provide different responses from fake data source for the api calls like no internet , Null body or Success response.</p>
<p><strong>ShoppingRepositoryInterface</strong></p>
<pre><code>interface ShoppingRepository {

    suspend fun insertShoppingItem(shoppingItem: ShoppingItem)

    suspend fun deleteShoppingItem(shoppingItem: ShoppingItem)

    fun getAllShoppingItems() : LiveData&lt;List&lt;ShoppingItem&gt;&gt;

    fun getTotalPrice() : LiveData&lt;Float&gt;

    suspend fun searchImage(q:String) : Resource&lt;ImageResponse&gt;
}
</code></pre>
<p><strong>ShoppingRepositoryImpl</strong></p>
<pre><code>@ViewModelScoped
class ShoppingRepositoryImpl @Inject constructor(
    private val dataSource: ShoppingDataSource
) : ShoppingRepository{

    override suspend fun insertShoppingItem(shoppingItem: ShoppingItem) = dataSource.insertShoppingItem(shoppingItem)

    override suspend fun deleteShoppingItem(shoppingItem: ShoppingItem) = dataSource.deleteShoppingItem(shoppingItem)

    override fun getAllShoppingItems() = dataSource.getAllShoppingItems()

    override fun getTotalPrice() = dataSource.getTotalPrice()

    override suspend fun searchImage(q: String) : Resource&lt;ImageResponse&gt; {
        return try {
            val response = dataSource.searchImage(q)
            if(response.isSuccessful){
                response.body()?.let {
                    Resource.Success(it)
                }?:Resource.Error(&quot;Some Error Occurred&quot;)
            }else{
                Resource.Error(&quot;Some Error Occurred&quot;)
            }
        }catch (e:Exception){
            Resource.Error(&quot;Couldn't connect to the server.Please try later&quot;)
        }
    }

}
</code></pre>
<p><strong>ShoppingReposositoryTest</strong></p>
<pre><code>class ShoppingRepositoryTest{

    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()


    private lateinit var repository: ShoppingRepository
    private lateinit var dataSource: ShoppingDataSource
    private val shoppingItem1 = ShoppingItem(&quot;name1&quot;,1,price=1f,&quot;url1&quot;,1)
    private val shoppingItem2 = ShoppingItem(&quot;name2&quot;,2,price=2f,&quot;url2&quot;,2)
    private val shoppingItem3 = ShoppingItem(&quot;name3&quot;,3,price=3f,&quot;url3&quot;,3)

    @Before
    fun setup(){
        dataSource = FakeDataSource(mutableListOf(
            shoppingItem1
        ))
        repository = ShoppingRepositoryImpl(dataSource)
    }

    @Test
    @ExperimentalCoroutinesApi
    fun insertShoppingItem_returnsWhetherItemInserted() = runTest{
        //Given

        //When
       repository.insertShoppingItem(shoppingItem2)
        val shoppingList = repository.getAllShoppingItems().getOrAwaitValue()

        //Then
        assertThat(shoppingList).contains(shoppingItem1)
    }

    @Test
    @ExperimentalCoroutinesApi
    fun deleteShoppingItem_returnsWhetherItemDeleted() = runTest{
        //Given


        //When
        repository.deleteShoppingItem(shoppingItem1)
        val shoppingList = repository.getAllShoppingItems().getOrAwaitValue()

        //Then
        assertThat(shoppingList.contains(shoppingItem1)).isFalse()
    }

    @Test
    @ExperimentalCoroutinesApi
    fun observeTotalPrice_returnsTotalPrice() = runTest {
        //Given


        //When
        repository.insertShoppingItem(shoppingItem2)
        repository.insertShoppingItem(shoppingItem3)
        val actual = repository.getTotalPrice().getOrAwaitValue()
        val expected = 14f

        //Then
        assertThat(expected).isEqualTo(actual)
    }

    @Test
    @ExperimentalCoroutinesApi
    fun observesSearchImage_returnsNoInternetError() = runTest {
        //Given

        //When

    }
</code></pre>
<p><strong>ShoppingDataSourceInterface</strong></p>
<pre><code>interface ShoppingDataSource {

    suspend fun insertShoppingItem(shoppingItem:ShoppingItem)

    suspend fun deleteShoppingItem(shoppingItem: ShoppingItem)

    fun getAllShoppingItems() : LiveData&lt;List&lt;ShoppingItem&gt;&gt;

    fun getTotalPrice() : LiveData&lt;Float&gt;

    suspend fun searchImage(q:String) : Response&lt;ImageResponse&gt;
}
</code></pre>
<p><strong>FakeDataDource</strong></p>
<pre><code>class FakeDataSource(private val list: MutableList&lt;ShoppingItem&gt; = mutableListOf()) : ShoppingDataSource {

    private val shoppingList  = MutableLiveData&lt;List&lt;ShoppingItem&gt;&gt;()
    get() {
        field.value=list
        return field
    }

    private val totalPrice = MutableLiveData&lt;Float&gt;()
    get(){
        var value=0f
        for(item in shoppingList.value!!){
            value+=(item.price*item.amount)
        }
        field.value=value
        return field
    }

    override suspend fun insertShoppingItem(shoppingItem: ShoppingItem) {
        list.add(shoppingItem)
    }

    override suspend fun deleteShoppingItem(shoppingItem: ShoppingItem) {
        list.remove(shoppingItem)
    }

    override fun getAllShoppingItems(): LiveData&lt;List&lt;ShoppingItem&gt;&gt; = shoppingList

    override fun getTotalPrice(): LiveData&lt;Float&gt; {
        return totalPrice
    }

    override suspend fun searchImage(q: String): Response&lt;ImageResponse&gt; {
        TODO(&quot;&quot;)
    }
</code></pre>
<p>I cannot use some booleans etc since it extends ShoppingDataSource Interface .
I tried mocking as well but that didn't work . What should be done now?</p>
",https://stackoverflow.com/questions/74284160/unit-testing-in-android,"['android', 'unit-testing', 'kotlin', 'repository-pattern', 'test-double']",110,False,0,0
Unit testing Nest JS,"<p>I have a little problem with my services dependencies for my unit test:</p>
<ul>
<li>I would test my UsersService who have three dependencies.
<a href=""https://i.stack.imgur.com/VZjK8.png"" rel=""nofollow noreferrer"">UsersService</a></li>
<li>the  KeycloakUsersService itself has one dependency
but if I try to mock the KeycloakUsersService as showed in the picture but I get this error :</li>
</ul>
<p><a href=""https://i.stack.imgur.com/A8JKP.png"" rel=""nofollow noreferrer"">KeycloakUsersService</a>
<a href=""https://i.stack.imgur.com/ISi8W.png"" rel=""nofollow noreferrer"">KeycloakAdminClientService</a></p>
<pre><code>Nest can't resolve dependencies of the KeycloakUsersService (?). Please make sure that the argument KeycloakAdminClientService at index [0] is available in the RootTestModule context.
</code></pre>
<p><a href=""https://i.stack.imgur.com/MRU2F.png"" rel=""nofollow noreferrer"">Testing Module</a></p>
",https://stackoverflow.com/questions/74429678/unit-testing-nest-js,['nestjs'],58,False,0,0
Unit testing mocking interactions,"<p>I'm trying to implement unit testing for a large enterprise app that has multiple layers and interactions between classes.
Reading about this type of test, I see that it is not recommended to verify interaction, you should test &quot;observable results&quot;. For example:</p>
<pre><code>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>In this case, verifying that RemoveInventory is called it's wrong (according to the theory), because it is an implementation detail.
Now, how should I test that the product has been removed from the inventory, given that the database or dao classes are mocked? There's no way to know, other than check that the function that does remove the product is called and hope for the best.</p>
<p>What am I missing here? Should I implement this in a different manner?</p>
",https://stackoverflow.com/questions/73474498/unit-testing-mocking-interactions,"['java', 'unit-testing', 'junit', 'mocking']",27,False,0,0
Java - Constructor Unit testing,"<p>I have following Java configuration class which I need to unit test using JUnit:</p>
<pre><code>public class Config {

private static final String AMQ_CONNECTION_URL_TEMPLATE = &quot;failover:(%s)&quot;;
private final String awsAmqUrl;

public Config(String url, Optional&lt;String&gt; amqConnectionOptions, PropertiesManager propertiesManager) {
    String urlParameter = propertiesManager.getStringParameter(url);
    this.awsAmqUrl = constructAmqConnectionString(urlParameter, amqConnectionOptions);
}

private String constructAmqConnectionString(String urlParameter, Optional&lt;String&gt; connectionOptions) {
    if (connectionOptions.isPresent()) {
        urlParameter = Stream.of(urlParameter.split(&quot;,&quot;))
                .map(url -&gt; url + &quot;?&quot; + connectionOptions.get())
                .collect(Collectors.joining(&quot;,&quot;));
    }
    return String.format(AMQ_CONNECTION_URL_TEMPLATE, urlParameter);
}

public ConnectionFactory getConnectionFactory() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(awsAmqUrl);
    return connectionFactory;
}
}
</code></pre>
<p>I am struggling to find an optimal solution for <code>constructAmqConnectionString</code> method unit testing as it's marked as private.
There are 3 scenarios I am trying to cover:</p>
<ul>
<li><code>urlParameter</code> - comprises comma separated URLs (url1,url2),
<code>connectionOptions</code> is not empty;</li>
<li><code>urlParameter</code> - comprises comma
separated URLs (url1,url2), <code>connectionOptions</code> is empty;</li>
<li><code>urlParameter</code> - comprises single URL (url1), <code>connectionOptions</code> is
not empty.</li>
</ul>
<p>Current solution is to add a getter into Config class for <code>awsAmqUrl</code> field so that logic of constructor's call can be verified/tested:</p>
<pre><code>public String getAwsAmqUrl() {
    return this.awsAmqUrl;
}
</code></pre>
<p>Tests itself have following logic:</p>
<pre><code>@Test
public void verifyConstructorWithoutMqOptionsMultiBroker() {
    when(propertiesManager.getStringParameter(any())).thenReturn(&quot;url1,url2&quot;);
    Optional&lt;String&gt; amqConnectionOptions = Optional.empty();
    config = new Config(&quot;url1,url2&quot;, amqConnectionOptions, propertiesManager);
    assertEquals(String.format(&quot;failover:(url1,url2)&quot;),config.getAwsAmqUrl());
}

@Test
public void verifyConstructorWithMqOptionsMultiBroker() {
    when(propertiesManager.getStringParameter(any())).thenReturn(&quot;url1,url2&quot;);
    Optional&lt;String&gt; amqConnectionOptions = Optional.of(&quot;optionTest=1&quot;);
    config = new Config(&quot;url1,url2&quot;, amqConnectionOptions, propertiesManager);        
    assertEquals(String.format(&quot;failover:(url1?%1$s,url2?%1$s)&quot;,amqConnectionOptions.get()),config.getAwsAmqUrl());
}

@Test
public void verifyConstructorWithMqOptionsSingleBroker() {
    when(propertiesManager.getStringParameter(any())).thenReturn(&quot;url1&quot;);
    Optional&lt;String&gt; amqConnectionOptions = Optional.of(&quot;optionTest=1&quot;);
    config = new Config(&quot;url1&quot;, amqConnectionOptions, propertiesManager);                
    assertEquals(String.format(&quot;failover:(url1?%1$s)&quot;,amqConnectionOptions.get()),config.getAwsAmqUrl());
}
</code></pre>
<p>Adding a getter just for Unit testing purposes doesn't feel the right thing to do as it's breaking encapsulation.
Is there a better way to approach testing in such scenario?</p>
",https://stackoverflow.com/questions/72454451/java-constructor-unit-testing,"['java', 'unit-testing', 'junit']",62,True,0,1
Unit testing if condition,"<p>0</p>
<p>I am writing unit tests and I am a bit stuck on this method. I have onClickCheck method that takes name from formGroup (this part I cover in the test) and then checks if the data.action equals NEW and if name exists and then does something.</p>
<p>onClickCheck() {
const name = this.formGroup.get('name').value;</p>
<pre><code>if (this.data.action === 'NEW' &amp;&amp; name) {
    this.service
        .doSomething(name)
        .pipe(take(1))
        .subscribe((result: any) =&gt; {
            this.someVar = result.data.attributes;

            if (this.someVar.isDeleted) {
                this.confirmationDialog(dialogData);
            }
        });
}
</code></pre>
<p>}
In my test I tried to do it like this but I get Error: expect(spy).toHaveBeenCalled() but the number of calls is 0.</p>
<p>const doSomethingSpy = spyOn(
service,
'doSomething'
).and.callThrough();</p>
<pre><code>    component.formGroup.setValue({
        name: 'Test',
        lastName: 'TT2'
    });

    component.data= {
        action: 'NEW',
        item: null
    };

    const name = component.formGroup.get('name').value;

    component.onClickCheck();
    fixture.detectChanges();
    expect(doSomethingSpy ).toHaveBeenCalled();
</code></pre>
<p>How can I test the code inside this double condition IF?</p>
",https://stackoverflow.com/questions/70892435/unit-testing-if-condition,"['angular', 'unit-testing', 'if-statement', 'karma-jasmine', 'karma-runner']",571,True,0,1
unit testing vue component,"<p>In my vue component I am have a some methods firing off in the mounted lifecycle,</p>
<pre><code>mounted() {
    this.GET_WORKFLOW_TYPES()
      .then(() =&gt; {
        this.GET_WORKFLOW_EVENTS_BY_TYPE({workflow_type: this.audit.selectedWorkflowType})
      });
  },
</code></pre>
<p>The above are actions in my store and they are mapped into my component like the following,</p>
<pre><code>methods: {
   ...mapActions([ACTION_TYPES.GET_WORKFLOW_TYPES, ACTION_TYPES.GET_WORKFLOW_EVENTS_BY_TYPE]);
}
</code></pre>
<p>I am wanting to test that both these functions get called in my unit test so I have tried,</p>
<pre><code>it('Should render the audit component and it\'s children', async () =&gt; {
        wrapper = mount(AdminAudit, { store, localVue});
        //Does it retrieve the data we need
        expect(actions.GET_WORKFLOW_TYPES).toHaveBeenCalled();
        await wrapper.vm.$nextTick(() =&gt; {  
            expect(actions.GET_WORKFLOW_EVENTS_BY_TYPE).toHaveBeenCalled();
        });
})
</code></pre>
<p>but i get the following response,</p>
<blockquote>
<p>console.error ../../node_modules/vue/dist/vue.runtime.common.dev.js:1893
JestAssertionError: expect(jest.fn()).toHaveBeenCalled()</p>
</blockquote>
<pre><code>Expected number of calls: &gt;= 1
Received number of calls:    0
</code></pre>
<p>How do I go about testing chained async calls?</p>
<p>For reference we are using vue version 2.6.14</p>
",https://stackoverflow.com/questions/72000011/unit-testing-vue-component,"['javascript', 'vue.js', 'jestjs', 'tdd']",65,False,0,1
Firebase React Unit Testing,"<p>I am trying to do unit testing on my React Web app which is using firebase auth, firestore and storage. I am pretty new to this and there aren't much resources I can find online.</p>
<p>I just tried to do a simple true test case but I keep getting a auth-api error. Anyone knows how to solve this? Are there any videos I could see to help me?</p>
<p>Code</p>
<pre><code>import * as firebase from &quot;@firebase/rules-unit-testing&quot;

describe(&quot;Login Component&quot;, () =&gt; {
    it(&quot;rendered input&quot; , () =&gt; {
        expect(true).toBeTruthy();
    })
});
</code></pre>
<p>Error</p>
<pre><code>Test suite failed to run

    FirebaseError: Firebase: Error (auth/invalid-api-key).

      26 | };
      27 | export const storage = app.storage(&quot;gs://sftc-development.appspot.com&quot;);
    &gt; 28 | export const auth = app.auth();
         |                         ^
      29 | export default app;

      at createErrorInternal (node_modules/@firebase/auth/src/core/util/assert.ts:128:44)
      at _assert (node_modules/@firebase/auth/src/core/util/assert.ts:153:30)
</code></pre>
<p>firebase.js</p>
<pre><code>import firebase from &quot;firebase/compat/app&quot;;
import &quot;firebase/compat/auth&quot;
import &quot;firebase/compat/firestore&quot;
import &quot;firebase/compat/storage&quot;

const app = firebase.initializeApp({
    apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
    authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
    databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
    projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
    storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.REACT_APP_FIREBASE_APP_ID
})

const firestore = app.firestore();
export const database = {
    usersRef: firestore.collection('user'),
    portfolioRef: firestore.collection('portfolio'),
    projectTitleRef: firestore.collection('projectTitle'),
    audioRef: firestore.collection('audio'),
    videoRef: firestore.collection('video'),
    imageRef: firestore.collection('image'),
    ascensionRef: firestore.collection('ascensionNumber'),
    regEmailRef: firestore.collection('regEmail')
};
export const storage = app.storage(&quot;gs://sftc-development.appspot.com&quot;);
export const auth = app.auth();
export default app;
</code></pre>
",https://stackoverflow.com/questions/73019848/firebase-react-unit-testing,"['reactjs', 'firebase', 'unit-testing']",84,False,0,0
unit testing computed properties,"<p>I'm currently trying to unit test a computed properties.</p>
<p>I have a fileOne.ts file :</p>
<pre><code>export const fileOne = () =&gt; {
   
   const fx1 = computed ( () =&gt; { ... } );
   const fx2 = computed ( () =&gt; { ... } );
   const fx3 = computed ( () =&gt; { ... } );

}

</code></pre>
<p>this 'fileOne' is used in a Vue.vue aswell :</p>
<pre><code>&lt;template&gt;
   ...
&lt;/template&gt;

&lt;script lang=&quot;ts&quot;&gt;
   import { fileOne } from './fileOne';
   
   const fileOneState = fileOne( ... );

   ...
&lt;/script&gt;
</code></pre>
<p>I want to unit test my computed properties of fileOne. At the moment i have a file named : 'fileOne.spec.ts' with :</p>
<pre><code>describe('testing computed properties', () =&gt; {
  it('should return the right value', () =&gt; {
    expect().toBe();
  })
});
</code></pre>
<p>The problem is : I don't know what I need to import either how to get a instance with my computed properties to test.</p>
<p>I believe this is not clear but if someone understood, i'll be happy to have some helps.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/72435412/unit-testing-computed-properties,"['javascript', 'typescript', 'unit-testing', 'testing']",33,False,0,1
django unit testing timezone,"<p>In my settings.py I have implemented timezone as</p>
<pre><code>TIME_ZONE = os.environ.get(&quot;TIMEZONE&quot;, &quot;Europe/London&quot;)
</code></pre>
<p>I've tried something like</p>
<pre><code>    assert timezone.localtime() == timezone.get_current_timezone()

    print(timezone.localtime())
    print(timezone.get_current_timezone())
</code></pre>
<p>How would I change get_current_timezone so that it could be compared to localtime</p>
",https://stackoverflow.com/questions/73725915/django-unit-testing-timezone,"['python', 'django', 'unit-testing']",36,False,0,0
Angular unit testing .subscribe(),"<p>Can't unit test subscribe(). No result returned for portfolioType</p>
<p>component.ts</p>
<pre><code> getPortfolioType() {
    this.dataService.getPortfolioTypeList()
      .subscribe((response: any) =&gt; {
        this.portfolioType = response.payload.portfolioList;
      })
  }
</code></pre>
<p>data.service.ts</p>
<pre><code>public getPortfolioTypeList(): any {
    return this.http.getData('/portfolio/portfolioTypeList');
  }
</code></pre>
<p>http.service.ts</p>
<pre><code>getData(action: any, data: any = {}): any {
    const url = environment.API_URL + action;
    const params = Object.keys(data);
    let httpParams = new HttpParams();

    if (params.length) {
      params.forEach((key: string) =&gt; {
        httpParams = httpParams.append(key, data[key]);
      });
    }

    return this.http.get(url, {params: httpParams});
  }
</code></pre>
<p>Case for service (pass)</p>
<pre><code>it('should pass service getPortfolioTypeList', () =&gt; {
    const test = {
      &quot;test&quot;: &quot;test&quot;
    }
    let result: any;
    dataService.getPortfolioTypeList().subscribe(t =&gt; {
      result = t;
    });
    const req = httpMock.expectOne({
      method: &quot;GET&quot;,
      url: environment.API_URL + '/portfolio/portfolioTypeList'
    });

    req.flush([test]);

    expect(result[0]).toEqual(test);
  });
</code></pre>
<p>Added a simple function call</p>
<pre><code>it('Get data from getPortfolioType', () =&gt; {
    component.getPortfolioType();
    console.log(component.portfolioType); // &lt;&lt;&lt; is empty
  });
</code></pre>
<p>Why component.portfolioType is empty?</p>
",https://stackoverflow.com/questions/74536719/angular-unit-testing-subscribe,"['angular', 'unit-testing', 'subscribe']",58,True,0,1
Unit Testing GetByIdAsync method,"<p>As part of validation for my site there is a method for checking whether an Id already exists with the following method:</p>
<pre><code>        private async Task&lt;bool&gt; IdExistsAsync(Guid id)
        {
            var model = await repository.GetByIdAsync(id);
            return model != null;
        }
</code></pre>
<p>and in the constructor of the class the rule is set that states that the new id cannot match an existing one:</p>
<pre><code>       public ValidatorBase(IHttpContextAccessor httpContextAccessor, IAsyncRepository&lt;T&gt; repository)
        {
            this.repository = repository;

            if (httpContextAccessor.HttpContext.Request.Method == HttpMethods.Post)
            {
                RuleFor(model =&gt; model.Id).MustAsync(async (Id, cancellation) =&gt; !await IdExistsAsync(Id))
                    .WithMessage(string.Format(&quot;{0} Id already exists.&quot;, typeof(T).Name));
            }
        }
</code></pre>
<p>What I am trying to do now is unit test this method, this is based off a file called DisciplineValidator which extends the validatorBase class.</p>
<p>I have created some mock disciplines:</p>
<pre><code>        private static List&lt;Discipline&gt; testDisciplines = new List&lt;Discipline&gt;()
        {
            new Discipline
            {
                Id = new Guid(&quot;00000000-0000-0000-0000-000000000001&quot;),
                Code = &quot;001&quot;
            },
            new Discipline
            {
                Id = new Guid(&quot;00000000-0000-0000-0000-000000000002&quot;),
                Code = &quot;002&quot;

            },

            new Discipline
            {
                Id = new Guid(&quot;00000000-0000-0000-0000-000000000003&quot;),
                Code = &quot;003&quot;

            }

        };
</code></pre>
<p>I have created a test like so:</p>
<pre><code>        public void UniqueIdCheckTest() 
        {

            Discipline disciplineToTest = new Discipline()
            {
                Id = new Guid(&quot;00000000-0000-0000-0000-000000000001&quot;)
            };

            var httpContextAccessorMock = new Mock&lt;IHttpContextAccessor&gt;();
            httpContextAccessorMock.Setup(h =&gt; h.HttpContext.Request.Method).Returns(HttpMethods.Post);


            var disciplineRepositoryMock = new Mock&lt;IAsyncRepository&lt;Discipline&gt;&gt;();
            disciplineRepositoryMock.Setup(t =&gt; t.GetByIdAsync(disciplineToTest.Id, default));

            var disciplineValidator = new DisciplineValidator(httpContextAccessorMock.Object, disciplineRepositoryMock.Object);

            // Act
            var result = disciplineValidator.TestValidate(disciplineToTest);

            // Assert
            result.ShouldHaveValidationErrorFor(discipline =&gt; discipline.Id)
                .WithErrorMessage(&quot;Discipline id already exists.&quot;);

        }
</code></pre>
<p>The issue I am having is, I am not sure how setup my disciplineRepositoryMock properly I know that:</p>
<pre><code>            disciplineRepositoryMock.Setup(t =&gt; t.GetByIdAsync(disciplineToTest.Id, default));

</code></pre>
<p>is not correct and there should be more to it, I thought it should be something along the lines of:</p>
<pre><code>            disciplineRepositoryMock.Setup(t =&gt; t.GetByIdAsync(disciplineToTest.Id, default))
                .ReturnsAsync(testDisciplines
                .Where(d =&gt; d.Id == disciplineToTest.Id).ToList());
</code></pre>
<p>But I then get the following error:</p>
<p>&quot;Isetup&lt;IAsyncRepository, Task&gt; does not contain a definition for 'ReturnsAsync'....&quot;</p>
<p>So my question is, how do I set this up properly so that it it testing the GetByIdAsync method? Where is is that I'm going wrong?</p>
<p>Edit:</p>
<p>I have now updated my disciplineRespositoryMock like so:</p>
<pre><code>    disciplineRepositoryMock.Setup(t =&gt; t.GetByIdAsync(It.IsAny&lt;ISpecification&lt;Discipline&gt;&gt;(), default))
        .ReturnsAsync(testDisciplines
        .Single(d =&gt; d.Id == disciplineToTest.Id));
</code></pre>
<p>There are no compiling errors but when I run the test, it fails with the message:</p>
<p>Message: 
System.ArgumentNullException : Value cannot be null. (Parameter 'source')</p>
<p>What is the issue now?</p>
",https://stackoverflow.com/questions/74770593/unit-testing-getbyidasync-method,"['c#', 'unit-testing', 'moq', 'xunit']",153,False,0,1
Unit Testing Xamarin Essentials,"<p>How to Unit Test the value of <code>Preference.Set(&quot;AppVersion&quot;,&quot;1.0&quot;)</code> in Xamarin forms ?</p>
<p>Tried <code>Assert.Equals(Preferences.Get(&quot;AppVersion&quot;, string.Empty), &quot;1.0&quot;);</code> but getting Xamarin.Essentials.Notimplementedinreferenceassemblyexception</p>
",https://stackoverflow.com/questions/72773877/unit-testing-xamarin-essentials,"['unit-testing', 'xamarin.forms', 'xamarin.essentials']",266,False,0,0
Unit Testing a Cubit,"<p>This is my first effort at testing my <code>Cubit</code> class, so please bear with me as I am completely out of ideas after trying for many hours.</p>
<p>I'm trying to test a simple cubit that looks like this:</p>
<pre><code>@injectable
class ResetPasswordCubit extends Cubit&lt;ResetPasswordState&gt; {

  ResetPasswordCubit() : super(ResetPasswordInitial());

  void attemptPasswordReset({required ResetPasswordParams params}) async {
    emit(ResetPasswordLoading());
    emit(ResetPasswordLoaded());
  }
}
</code></pre>
<p>All I want to do is to verify that both of these states were emitted in order. According to the <a href=""https://pub.dev/packages/bloc_test/example"" rel=""nofollow noreferrer"">docs</a>, there are a couple of ways to do this, but I'm not even sure which one I should be using. I would prefer to use the unit test, although I've tried both. Here is what I have:</p>
<pre><code>class MockResetPasswordCubit extends MockCubit&lt;ResetPasswordState&gt;
    implements ResetPasswordCubit {}

@GenerateMocks([ResetPassword])
void main() {
  late MockResetPassword mockResetPassword;
  late MockResetPasswordCubit cubit;
  late ResetPasswordParams params;

  setUp(() {
    mockResetPassword = MockResetPassword();
    cubit = MockResetPasswordCubit();
    params = const ResetPasswordParams(
        pin: &quot;1234&quot;, password: &quot;hello&quot;, confirmPassword: &quot;hello&quot;);
    when(mockResetPassword.call(params))
        .thenAnswer((_) async =&gt; const Right(ResetPasswordResult.validated));
  });

  blocTest&lt;ResetPasswordCubit, ResetPasswordState&gt;(
      'when attempt to validate password is made then loading state is emitted',
      build: () =&gt; cubit,
      act: (cubit) =&gt; cubit.attemptPasswordReset(params: params),
      expect: () =&gt; [ResetPasswordLoading(), ResetPasswordLoaded()]);
}
</code></pre>
<p>And this is the error that gets displayed:</p>
<blockquote>
<p>Expected: [Instance of 'ResetPasswordLoading', Instance of
'ResetPasswordLoaded']<br>   Actual: []<br>    Which: at location [0]
is [] which shorter than expected<br></p>
</blockquote>
<p>I'm really out of ideas, so hoping someone can set me straight. Thanks.</p>
",https://stackoverflow.com/questions/71188505/unit-testing-a-cubit,"['flutter', 'dart', 'bloc', 'bloc-test']",1324,False,-1,1
Java Springboot Unit-Testing,"<p>Building a UnitTest into a CRUD Application</p>
<p>I tried adding a hardcoded business item as variables to the Application.<a href=""https://i.stack.imgur.com/uSL3A.png"" rel=""nofollow noreferrer"">Unit Test</a><a href=""https://i.stack.imgur.com/UOU6Q.png"" rel=""nofollow noreferrer"">Component class</a> <a href=""https://i.stack.imgur.com/8F0wB.png"" rel=""nofollow noreferrer"">Controller Class</a><a href=""https://i.stack.imgur.com/J5xc6.png"" rel=""nofollow noreferrer"">output</a></p>
",https://stackoverflow.com/questions/74734439/java-springboot-unit-testing,"['java', 'spring', 'spring-boot', 'unit-testing', 'crud']",27,False,0,0
Unit testing java maven,"<p>I have a maven project that looks like this:</p>
<p><a href=""https://i.stack.imgur.com/clHaG.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/clHaG.png"" alt=""enter image description here"" /></a></p>
<p>If I run in the terminal:</p>
<pre><code>mvn test
</code></pre>
<p>it will build the application and run the 3 tests:</p>
<pre><code>SocialMultiplicationApplicationTests

MultiplicationServiceTest

RandomGeneratorServiceTest
</code></pre>
<p>but not <code>RandomGeneratorServiceImplTest</code>.</p>
<p>If I try to explicitly run this class:</p>
<pre><code>mvn test -Dtest=RandomGeneratorServiceImplTest
</code></pre>
<p>I get:</p>
<pre><code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) 
on project social-multiplication: No tests were executed!  (Set -DfailIfNoTests=false to ignore this error.) -&gt; [Help 1]
</code></pre>
<p>Here's my 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.7.3&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;microservices.book&lt;/groupId&gt;
    &lt;artifactId&gt;social-multiplication&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;social-multiplication&lt;/name&gt;
    &lt;description&gt;Social Multiplication App&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-web&lt;/artifactId&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-test&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mockito&lt;/groupId&gt;
            &lt;artifactId&gt;mockito-core&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.assertj&lt;/groupId&gt;
            &lt;artifactId&gt;assertj-core&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;junit&lt;/groupId&gt;
            &lt;artifactId&gt;junit&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
    &lt;/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>Here's the test class that won't run:</p>
<pre><code>package microservices.book.multiplication.service;


import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class RandomGeneratorServiceImplTest {

    private RandomGeneratorServiceImpl randomGeneratorServiceImp;

    @Before
    public void setUp(){
        randomGeneratorServiceImp = new RandomGeneratorServiceImpl();
    }

    @Test
    public void generateRandomFactorIsBetweenExpectedLimits() {
        List&lt;Integer&gt; randomFactors = IntStream.range(0,1000)
                .map(i -&gt; randomGeneratorServiceImp.generateRandomFactor())
                .boxed()
                .collect(Collectors.toList());

        for(Integer i: randomFactors){
            assertThat(i).isIn(
                    IntStream.range(11, 100).
                            boxed().collect(Collectors.toList()));
        }
    }
}

</code></pre>
<p><strong>EDIT: SOLUTION</strong></p>
<p>The proble was indeed the conflict between junit4 and junit5.</p>
<p>I chose to move my tests to junit5, hence I replaced <code>@Before</code> with <code>@BeforeAll</code> and added <code>@TestInstance(Lifecycle.PER_CLASS)</code> on top of the <code>RandomGeneratorServiceImplTest</code> class definition.</p>
<p>Couple links I found useful:</p>
<p><a href=""https://junit.org/junit5/docs/current/user-guide/"" rel=""nofollow noreferrer"">junit docs</a></p>
<p><a href=""https://howtodoinjava.com/junit5/junit-5-vs-junit-4/"" rel=""nofollow noreferrer"">differences between junit4 and junit5</a></p>
",https://stackoverflow.com/questions/73941023/unit-testing-java-maven,"['java', 'maven', 'unit-testing']",81,True,0,2
Unit Testing Spring Issues,"<p>I'm trying to learn how to do unit testing / mockito testing in spring with java 8 and running into some problems. I'm trying to test my method findUserById but it keeps running false. Optional type issues were an issue but may have resolved those. However, it still runs false. My other tests work, so its just this one test that is being stubborn. I would appreciate your help.</p>
<pre><code>User Controller : 

 @GetMapping(&quot;/{id}&quot;)
    public ResponseEntity&lt;User&gt; findUserById(@PathVariable Integer id){
        return ResponseEntity.ok(userServiceImp.findUserById(id));
    }
</code></pre>
<pre><code>
UserApplictionTester : 


  @Autowired
    private Service service;

   @MockBean
    private Repository repo;

@Test
    public void exampleTest() {

        User expectedUser = new User(3, &quot;example@gmail.com&quot;, &quot;password1&quot;, &quot;exampleName&quot;, &quot;USER&quot;);
        User testUser = new User();
        testUser.setId(3);
        when(repo.findById(any())).thenReturn(Optional.of(testUser));
        assertEquals(expectedUser, service.findUserById(testUser.getId()));
    }

</code></pre>
",https://stackoverflow.com/questions/73585117/unit-testing-spring-issues,"['java', 'spring', 'testing', 'mockito']",23,False,0,1
Rspec unit testing without database,"<p>Guys bear with me on this. I would highly appreciate any advise provided.</p>
<p>So lets say I have a controller with the below code:</p>
<pre><code>class PersonController &lt; ApplicationController
  serialize_with personSerializer
  string: title
  int: age


  def update
    authorize(person, can_update?)
    person.update(title:title,age:age)

    serialize person
  end
end
</code></pre>
<p>So in terms of Business Logic we have here:</p>
<ol>
<li>check for authorize</li>
<li>update the object</li>
<li>return the serializer of the object (it's just a json result)</li>
</ol>
<p>Now I want to test this piece of code with RSpec, but there is no DB to save or receive an object (well there was one earlier, but I want to remove it when running tests).</p>
<p>So far I have tried using nulldb gem to remove the db dependency. But the problem arrives when the created object cannot be retrieved.</p>
<p>If I want to test the authorize (1). It's a function of another gem that tests if the user can even use this controller.</p>
<p>Do I need to completely mock it? If so, how? Which tool to use?</p>
<p>Same for the update, if I do person.update, how should I check if it works if I don't have access to the active record?</p>
",https://stackoverflow.com/questions/72564072/rspec-unit-testing-without-database,"['ruby-on-rails', 'ruby', 'unit-testing', 'rspec', 'rubygems']",365,True,7,2
Xcode 14 unit testing clone simulator,"<p>In Xcode 14, running unit testing seems to be creating simulator 'clones' (named 'Clone 1/2.. of iPhone').
On older machines, this can take a long time. This is happening every time when switching from running the App and running tests.
For example, running the App will launch the Simulator. Running tests will launch new one or more Simulators (Clone of ...), and running the App again will reload the original Simulator.<br />
Any way to control this? This makes running tests a real pain on older machines.</p>
",https://stackoverflow.com/questions/73746572/xcode-14-unit-testing-clone-simulator,['xcode14'],1776,True,11,1
Unit testing for functions defined on databricks notebook and unit testing for pyspark DF,"<p>I have defined few functions and calling it in other notebooks, i want to create a notebook which does unit testing for all these functions in ADF and also need to do unit testing like count match between source file and data frame.</p>
<p>How to achieve this?</p>
",https://stackoverflow.com/questions/73018323/unit-testing-for-functions-defined-on-databricks-notebook-and-unit-testing-for-p,"['unit-testing', 'databricks', 'azure-databricks', 'azure-data-factory']",514,True,2,2
Databricks unit testing with Nutter,"<p>I m trying to run unit test inside Databricks with Nutter but return always <code>None</code></p>
<p>notebook1</p>
<pre><code>def add_nums(a, b):
    return a + b
</code></pre>
<p>notebook2 (Where I want to make the unit test)</p>
<pre><code>%pip install nutter 
from runtime.nutterfixture import NutterFixture, tag
</code></pre>
<p>import the notebook1 in notebook 2</p>
<pre><code>%run /notebook1/
</code></pre>
<p>I just make a tes to verify function in notebook1 is correctly added.</p>
<pre><code>print(add_nums(1, 3)) # return 4 so everything fine.

class gcTestClass(NutterFixture):
    def test_add(self):
        assert (add_nums(1, 3) == 4)

result = gcTestClass().execute_tests()
print(result.to_string())
</code></pre>
<p>I get that output</p>
<p>Notebook: N/A - Lifecycle State: N/A, Result: N/A<br />
Run Page URL: N/A</p>
<p>==================================================</p>
<p>No test cases were returned.
Notebook output: None</p>
<p>could somebody help me to figure out what I m doig wrong ?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/74437990/databricks-unit-testing-with-nutter,"['unit-testing', 'pyspark', 'databricks', 'azure-databricks']",523,True,3,1
Firebase Flutter unit testing Firebase.initializeApp(),"<p>It's my first time testing an app I tried to test firebase auth and had this error
I also search in the doc but everything is outdated or doesn't implement firebase</p>
<p><a href=""https://i.stack.imgur.com/0g02a.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0g02a.png"" alt=""enter image description here"" /></a></p>
<p>This is my code</p>
<pre><code>import 'package:ecommerce/main.dart';
import 'package:ecommerce/services/auth.dart';
import 'package:fake_cloud_firestore/fake_cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:rxdart/subjects.dart';

class MockFirebaseAuth extends Mock implements FirebaseAuth {}

class MockFirebaseUser extends Mock implements User {}

class MockUserCredential extends Mock implements Future&lt;UserCredential&gt; {}

void main() {
  MockFirebaseAuth _auth = MockFirebaseAuth();
  MockUserCredential mockUserCredential = MockUserCredential();
  AuthService authManager = AuthService();

  final instance = FakeFirebaseFirestore();

  group(&quot;User Auth Test&quot;, () {
    test('Returns no user if not signed in', () async {
      final auth = MockFirebaseAuth();
      final user = auth.currentUser;
      expect(user, isNull);
    });
  });
}
</code></pre>
",https://stackoverflow.com/questions/74432677/firebase-flutter-unit-testing-firebase-initializeapp,"['flutter', 'firebase', 'unit-testing', 'flutter-test', 'flutter-mockito']",106,False,3,0
Unit testing Vue composition functions,"<p>I'm attempting to write a data-fetching &quot;hook&quot; (not entirely clear what the word for this is in Vue, but a state function that does not render a template). The Hook takes an asynchronous data resolver as a parameter. The hook itself is very simple, it simply adds loading state to a function that returns a promise.</p>
<pre class=""lang-js prettyprint-override""><code>import { ref, watch } from &quot;vue&quot;;

export function useDataFetcher&lt;T&gt;(
  resolver: () =&gt; Promise&lt;T&gt;,
) {
  const isLoading = ref(false);
  const data = ref&lt;T&gt;();
  watch(resolver, () =&gt; {
    isLoading.value = true;
    resolver(...parameters)
      .then((fetchedData) =&gt; {
        data.value = fetchedData;
      })
      .finally(() =&gt; {
        isLoading.value = false;
      });
  });
  return {
    isLoading: isLoading.value,
    data,
    parameters,
  };
}
</code></pre>
<p>I am attempting to write a test against this function to ensure that the isLoading method is updating correctly:</p>
<pre class=""lang-js prettyprint-override""><code>import { useDataFetcher } from &quot;./useDataFetcher&quot;;
test(&quot;While the fetcher is loading data, isLoading should be true&quot;, async () =&gt; {
  const promise = new Promise&lt;void&gt;((resolver) =&gt;
    setTimeout(() =&gt; resolver(), 2000)
  );
  const { isLoading } = useDataFetcher(() =&gt; promise);
  expect(isLoading).toBeTruthy();
  await promise;

  expect(isLoading).toBeFalsy();
});
</code></pre>
<p>As written, this test is not working. I have not seen a lot of information in the interwebs about testing these state functions in Vue.
There are two stack overflow questions that seem related:
<a href=""https://stackoverflow.com/questions/68697265/is-it-possible-to-test-a-vue-3-composition-library-which-uses-inject-without-a-w"">Is it possible to test a Vue 3 Composition library which uses inject without a wrapping component?</a></p>
<p>and
<a href=""https://stackoverflow.com/questions/59957561/how-to-unit-test-standalone-vue-composition"">How to unit test standalone Vue composition</a></p>
<p>But neither of these seem to quite scratch the itch I'm having here.</p>
<p>In React, you have the @testing-library/react-hooks library to manage these tests, and it makes it very simple. It seems to me that I'm missing something to the effect of <code>await Vue.nextTick()</code>.</p>
<p>So, finally, the question: What exactly is the best way to test these Vue hooks that don't render templates?</p>
",https://stackoverflow.com/questions/70946159/unit-testing-vue-composition-functions,"['vue.js', 'jestjs', 'vuejs3', 'vue-composition-api']",1665,True,2,2
Unit testing Project Reactor&#39;s publish,"<p>Suppose you need to mock a method that accepts a flux.</p>
<pre class=""lang-java prettyprint-override""><code>@ExtendWith(MockitoExtension.class)
public class FooTest {
    @Mock Bar bar;
    @InjectMocks Foo foo;

    @Test
    void test() {
        when(bar.delete(any())).thenReturn(Mono.empty());

        StepVerifier.create(foo.deleteRelated(&quot;123&quot;))
                .expectNext()
                .verifyComplete();
    }
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>public class Foo {
    private final Bar bar;
    public Foo(Bar bar) {
        this.bar = bar;
    }

    public Mono&lt;Void&gt; deleteRelated(String id) {
        return Mono.just(id)
                .flatMapMany(this::findById)
                .log()
                .publish(bar::delete)
                .collectList()
                .then();
    }

    private Flux&lt;String&gt; findById(String id) {
        return Flux.just(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;);
    }
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>public class Bar {
    public Mono&lt;Void&gt; delete(Flux&lt;String&gt; vals) {
        return vals.buffer(3)
                .flatMap(this::deleteAFewAtATime)
                .collectList()
                .then();
    }

    private Mono&lt;Void&gt; deleteAFewAtATime(List&lt;String&gt; key) {
        return Mono.empty();
    }
}
</code></pre>
<p>Running this test results in an output with a cancel:</p>
<pre><code>reactor.Flux.MonoFlatMapMany.1 : onSubscribe([Synchronous Fuseable] FluxArray.ArraySubscription)
reactor.Flux.MonoFlatMapMany.1 : cancel()
</code></pre>
<p>I wouldn't have expected the cancel signal to be emitted. I believe this is because the input to <code>bar.delete()</code> was not subscribed to.</p>
<p>How can I mock a function with a Flux as an input, and have that Flux be subscribed to?</p>
",https://stackoverflow.com/questions/74881845/unit-testing-project-reactors-publish,"['java', 'mockito', 'project-reactor']",318,False,2,1
Unit testing Apollo useMutation onCompleted,"<p>I have an onCompleted that I am trying to test from my useMutation, I am using jest and react-testing-library. This is the piece of code I am trying to test</p>
<p>this is my react code:</p>
<pre><code>const [deleteJobs] = useMutation&lt;DeleteJobsMutation, MutationDeleteJobsArgs&gt;(
mutationQuery,
{
  refetchQueries: refetchQueries as string[],
  onCompleted: () =&gt; (callback ? callback() : onCancel?.(null)),
},)
</code></pre>
<p>my mutation:</p>
<pre><code>mutation deleteJobs($jobIds: [ID!]!) { deleteJobs(jobIds: $jobIds) {
successful}}
</code></pre>
<p>I have managed to mock it so it does call and I have also mocked it to succeed so I can test scenarios on success but I can't seem to work out how to get it to trigger the onCompleted</p>
",https://stackoverflow.com/questions/71527376/unit-testing-apollo-usemutation-oncompleted,"['reactjs', 'graphql', 'apollo', 'react-apollo', 'react-apollo-hooks']",3713,True,1,1
Flutter unit testing with provider,"<p>I am not able to use the provider in unit testing
I am using the following code. I am getting this error</p>
<pre><code>00:02 +2 -1: test student controller with add and remove student test controller for add new set [E]                                            
  Null check operator used on a null value
  package:provider/src/provider.dart 274:20  Provider.of
  test/student_controller_test.dart 53:22    main.&lt;fn&gt;.&lt;fn&gt;
  test/student_controller_test.dart 36:53    main.&lt;fn&gt;.&lt;fn&gt;
</code></pre>
<p>class MockBuildContext extends Mock implements BuildContext {}</p>
<pre><code>void main() {
  late MockBuildContext _mockContext;

  setUpAll(() {
    _mockContext = MockBuildContext();
  });


test('test student controller for add new student', () async {
      List&lt;Students&gt; sts = [
        Students(
            name: 'Barbels',
            age: 21,
            weight: 70,
          ),
         Students(
            name: 'Hazel',
            age: 31,
            weight: 60,
          ),
      ];
      var id = '1';
      print(_mockContext);
      MyController.saveStuden(_mockContext, id, sets);
      print(Provider.of&lt;StudentProvider&gt;(_mockContext, listen: false)
          .items
          .length);
});
</code></pre>
",https://stackoverflow.com/questions/74501192/flutter-unit-testing-with-provider,"['flutter', 'unit-testing', 'dart', 'flutter-provider']",75,False,1,1
Unit testing in Databricks notebooks,"<p>The following code is intended to run unit tests in Databricks notebooks, using pytest.</p>
<pre class=""lang-py prettyprint-override""><code>import pytest
import os
import sys

repo_name = &quot;Databricks-Code-Repo&quot;

# Get the path to this notebook, for example &quot;/Workspace/Repos/{username}/{repo-name}&quot;.
notebook_path = dbutils.notebook.entry_point.getDbutils().notebook().getContext().notebookPath().get()

# Get the repo's root directory name.
repo_root = os.path.dirname(os.path.dirname(notebook_path))
    
# Prepare to run pytest from the repo.
os.chdir(f&quot;/Workspace/{repo_root}/{repo_name}&quot;)
print(os.getcwd())
    
# Skip writing pyc files on a readonly filesystem.
sys.dont_write_bytecode = True
    
# Run pytest.
retcode = pytest.main([&quot;.&quot;, &quot;-v&quot;, &quot;-p&quot;, &quot;no:cacheprovider&quot;])
    
# Fail the cell execution if there are any test failures.
assert retcode == 0, &quot;The pytest invocation failed. See the log for details.&quot;
</code></pre>
<p>This code snippet is in the <a href=""https://docs.databricks.com/notebooks/testing.html#language-Python"" rel=""nofollow noreferrer"">guide</a> provided by Databricks.
However, it produces the following error:</p>
<pre class=""lang-bash prettyprint-override""><code>PermissionError: [Errno 1] Operation not permitted: '/Workspace//Repos/&lt;email_address&gt;/Databricks-Code-Repo/Databricks-Code-Repo'
</code></pre>
<p>This notebook is inside Databricks Repos. I have two other notebooks:</p>
<ul>
<li><code>functions</code> (where I have defined three data transformation functions);</li>
<li><code>test_functions</code> (where I have defined test function for each of the data transformation functions from the previous notebook).</li>
</ul>
<p>I get that the error has something to do with permissions, but I can't figure out what is causing it. I will appreciate any suggestions.</p>
",https://stackoverflow.com/questions/74926786/unit-testing-in-databricks-notebooks,"['github', 'pyspark', 'pytest', 'databricks', 'databricks-repos']",422,False,1,1
&quot;Unit testing&quot; a Maven build,"<p>I have a complex Maven build, and I would like to have some automated check that the JAR files and POM files produced by the build actually contain what I expect them to contain.</p>
<p>For instance, I would like to check for the presence of an <code>Automatic-Module-Name</code> entry in the manifest file. It's a multi-release JAR, so I would like to check that the proper class files exist inside of <code>META-INF/versions</code>. I'm going to publish to Maven Central, so I'd also like to check that the produced pom file contains the dependencies the project needs, but that the produced pom file for the fat jar that I also publish, <em>doesn't</em> contain these dependencies.</p>
<p>Basically, I'd like to unit test my build :).</p>
<p>Unfortunately, it's hard to google for this, because of the words I would use to describe this (&quot;test&quot;, &quot;verify&quot;) already have very specific different meanings in Maven.</p>
<p>Is there a nice way to do this? I would prefer a Maven plugin, since I'm obviously already using that, but I'm open to other things too.</p>
",https://stackoverflow.com/questions/70861878/unit-testing-a-maven-build,"['maven', 'automated-tests']",69,True,1,1
Unit testing nuxt fetch hook,"<p>I'm trying to unit test with Nuxt. Everything's going smoothly, but my problem lies with unit testing fetch. It seems that since this.$axios isn't a library (well, it is, but is injected to the context), there's no easy way to jest.mock it. I've the few posts that there are on this, but they have not worked.</p>
<pre><code>async fetch() {
    try {
        this.maxSpace = await this.$axios.$get('/api/system/max-space')
    }
    catch (err) {
        this.maxSpace = 0
    }
},
</code></pre>
<p>This is the simple code I'm attempting to unit test</p>
",https://stackoverflow.com/questions/71503482/unit-testing-nuxt-fetch-hook,"['jestjs', 'nuxt.js', 'vue-test-utils']",575,False,1,0
python testing and unit testing,"<p>I have a simple calculator program and want to testing it using unit test concepts and this is my code :</p>
<pre><code>def add(x, y):
    result =  x + y
    return result

# This function subtracts two numbers
def subtract(x, y):
    result =  x - y
    return result

# This function multiplies two numbers
def multiply(x, y):
    result =  x * y
    return result

# This function divides two numbers
def divide(x, y):
    if y == 0:
        print(&quot;You can't divide by zero!&quot;)
        raise ZeroDivisionError(&quot;You can't divide by zero!&quot;)
    elif x == 0:
        return 0
    else:
        result =  x / y
        return result



def calculate(choice, num1, num2 ):
    # check if choice is one of the four options
    if not num1 or not num2:
        print(&quot;inputs can not be null&quot;)
        raise ValueError(&quot;inputs can not be null&quot;)  
    num1 = check_user_input(num1)
    num2 = check_user_input(num2)
    result = &quot;&quot;
    if choice in ('1', '2', '3', '4'):

        if choice == '1':
            result = add(num1, num2)

        elif choice == '2':
            result = subtract(num1, num2)

        elif choice == '3':
            result = num1, &quot;*&quot;, num2, &quot;=&quot;, multiply(num1, num2)

        elif choice == '4':
            if num2 == 0:
                print(&quot;You can't divide by zero!&quot;)
                raise ZeroDivisionError(&quot;You can't divide by zero!&quot;)
            result = num1, &quot;/&quot;, num2, &quot;=&quot;, divide(num1, num2)
    else:
        raise Exception(&quot;Invalid choice!&quot;)

    return result
</code></pre>
<p>and i want to test calculate function using mock.</p>
<p>so i did this  :</p>
<pre><code>def test_checkCalculate4(self):
        self.assertEqual(calculate('1',6,3), 9) 
</code></pre>
<p>but this didn't work and filed with error :</p>
<pre><code>self.assertEqual(calculate('1',6,3), 9)
AssertionError: 5 != 9
</code></pre>
<p>any idea about it and how i can do it ?</p>
",https://stackoverflow.com/questions/71966489/python-testing-and-unit-testing,"['python', 'python-3.x', 'unit-testing']",176,False,1,0
Unit testing angular async promise,"<p>I have some hard times trying to resolve some unit testing. I succeed in testing the function if params.callType === 'inbound' but don't know how to test if params.calltype === &quot;something else&quot;. Here is the code I have to test:</p>
<pre><code>searchObject(params: ISearchObjectParams): Promise&lt;IScreenPopSearchObjectResult&gt; {
return new Promise((resolve, reject) =&gt; {
  let searchParams;
  if (params.searchValuesString) {
    searchParams = params.searchValuesString;
  } else {
    const quotedSearchValues = params &amp;&amp; params.searchValues &amp;&amp; params.searchValues.map(x =&gt; '&quot;' + x + '&quot;');
    searchParams = quotedSearchValues &amp;&amp; quotedSearchValues.join(' OR ');
  }
  if (params.callType === 'inbound') {
    sforce.opencti.searchAndScreenPop({
      searchParams: searchParams,
      queryParams: params.queryParams,
      callType: params.callType,
      deferred: true,
      callback: response =&gt; {
        if (response.success) {
          resolve(this.createSearchObjectResult(response));
        } else {
          reject(this.parseLightningError(response, LocaleKeys.searchObject));
        }
      }
    });
  }
});
</code></pre>
<p>Here is the unit test I made that <strong>is working</strong> for the <strong>&quot;if (params.callType === 'inbound').</strong></p>
<pre><code>it('should resolve with parsed search result', async () =&gt; {
      service.createSearchObjectResult = jasmine.createSpy().and.returnValue({});
      sforce.opencti.searchAndScreenPop = jasmine.createSpy().and.callFake((params: {
        callback: (response: { returnValue: { runApex: string }, success: boolean }) =&gt; void
      }) =&gt; {
        params.callback({ success: true } as any);
      });
      await expectAsync(service.searchObject({ searchValues: ['value1', 'value2'], callType: 'inbound' } as any)).toBeResolvedTo({} as any);
      testUtils.expectSingleCall(service.createSearchObjectResult, { success: true });
    });
</code></pre>
<p>I'm trying to make it for <strong>the else,</strong> but I can't succeed. This is what I tried for <strong>params.callType === &quot;outbound&quot;(that should be the else condition):</strong></p>
<pre><code>  it('should not resolve if is not inbound', async () =&gt; {
      sforce.opencti.searchAndScreenPop = jasmine.createSpy().and.callFake((params: {
        callback: (response: { returnValue: { runApex: string }, success: boolean }) =&gt; void
      }) =&gt; {
        params.callback({ success: false } as any);
      });
      await expectAsync(service.searchObject({ searchValuesString: 'value1&amp;&amp;value2', callType: 'inbound' } as any)).toBeRejected({} as any);
      testUtils.expectNotCalled(sforce.opencti.searchAndScreenPop);
      expect(sforce.opencti.searchAndScreenPop).not.toHaveBeenCalled();
    });
</code></pre>
<p>Suggestions please?</p>
",https://stackoverflow.com/questions/72733610/unit-testing-angular-async-promise,"['angular', 'unit-testing', 'async-await', 'promise', 'jasmine']",47,False,1,1
Embedded Cassandra unit testing options,"<p>Our team was in the process of updating our dependencies and one of those is <a href=""https://github.com/jsevellec/cassandra-unit"" rel=""nofollow noreferrer"">Cassandra Unit</a>. I noticed that the last time this library was <a href=""https://mvnrepository.com/artifact/org.cassandraunit/cassandra-unit"" rel=""nofollow noreferrer"">updated was in January of 2020</a> and that there hasn't been any activity in a long time. In addition there are 12 open pull requests that have just been sitting. I did notice some developers have forked this repo to add features they wanted.</p>
<p>We have enjoyed using this library to test CQL in our DAO objects via JUnit and are planning to upgrade to the latest version (4.3.1.0).</p>
<p>I hope that the developer (jsevellec) that was leading this effort is doing well. But in the absence of activity on this repo, and thinking longer term, I was wondering what other libraries might be available that allow ease of testing using an embedded Cassandra instance via JUnit that are more actively supported.</p>
",https://stackoverflow.com/questions/72006470/embedded-cassandra-unit-testing-options,"['java', 'junit', 'cassandra', 'cassandraunit']",948,False,1,1
Angular unit testing router events,"<p>I'm trying to mock router.events.subscribe() but it's not working. I tried to provide and event but I get an error: TypeError: Cannot read properties of undefined (reading 'root'). How can I do it?
TS code:</p>
<pre><code>ngOnInit(): void {
        this.router.events.subscribe(event =&gt; {
            this.splitRoutes();
        });
    }

    private splitRoutes() {
        const routes = this.router.url.toString().split('/');
            }
        }
    }
</code></pre>
<p>spec.ts:</p>
<pre><code>beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [],
      providers: [{
        provide: Router,
        useValue: {
          url: '/non-pdp/phases/8',
          events: of(
            new NavigationEnd(0, 'http://localhost:4200/#/non-pdp/phases/8', 'http://localhost:4200/#/non-pdp/phases/8')),
          navigate: jasmine.createSpy('navigate')
        }],
      })
    .compileComponents();
});
</code></pre>
",https://stackoverflow.com/questions/73047441/angular-unit-testing-router-events,"['angular', 'unit-testing', 'routes', 'mocking', 'angular-ui-router']",150,False,1,0
Classist Unit Testing - Avoiding Mocks,"<p>I am trying to follow the Classist approach for Unit Testing. I try to only mock external dependencies (external API, file system, etc...). I try to separate data access code (EF Core) from core domain classes, allowing me to test those core classes without those dependencies.</p>
<p>In the following class:</p>
<pre><code>using System;
using System.Threading.Tasks;
using Cornerstone.Services;
using MediatR;
using Cornerstone.Entities.Cornerstone.Actions.LDAP;
using Cornerstone.Entities.Cornerstone.Actions;

namespace Cornerstone.Features.Actions.ActionExecuters
{
    public class AddUserActionExecuter : IActionExecuter
    {
        private readonly LdapService ldapService;
        private readonly AddUserAction action;
        private readonly IMediator mediator;

        public AddUserActionExecuter(LdapService ldapService, AddUserAction action, IMediator mediator)
        {
            this.ldapService = ldapService ?? throw new ArgumentNullException(nameof(ldapService));
            this.action = action ?? throw new ArgumentNullException(nameof(action));
            this.mediator = mediator;
        }

        public async Task&lt;bool&gt; CanExecute()
        {
            var sourceContact = await mediator.Send(new GetContactForActionQuery(action));
            return !string.IsNullOrWhiteSpace(action.SamAccountName) 
                &amp;&amp; !string.IsNullOrWhiteSpace(action.Email) 
                &amp;&amp; !string.IsNullOrWhiteSpace(sourceContact.FirstName) 
                &amp;&amp; !string.IsNullOrWhiteSpace(sourceContact.Surname) 
                &amp;&amp; !string.IsNullOrWhiteSpace(action.Ou) 
                &amp;&amp; action.Groups.Count &gt; 0;
        }

        public async Task&lt;ExecutionResult&gt; Execute()
        {
            var sourceContact = await mediator.Send(new GetContactForActionQuery(action));
            ldapService.CreateUserAccount(action.Ou, action.SamAccountName, action.Password, action.UniqueCN, action.Email,  sourceContact.FirstName, sourceContact.Surname, action.Email);
            ldapService.AddUserToGroups(action.SamAccountName, action.Groups.ToArray());
            return new ExecutionResult { Successful = true };
        }

    }
}
</code></pre>
<p>you can see that I am using MediatR to send queries. Using MediatR, I am fetching a Contact that corresponds to a <code>SourceContactId</code> property on the <code>AddUserAction</code> class.</p>
<p>If I want to unit test the logic in the <code>CanExecute</code> method, I can see two choices:</p>
<ol>
<li>Mock the MediatR handler and make it return a contact I prepared</li>
<li>Create a new class like <code>AddAdUserActionExecuter_Helper</code> that has a method <code>bool CheckCanExecute(AddUserAction action, Contact contact)</code> and move the logic there, then I would call this from the original <code>CanExecute</code> and unit test only the new method which now has no dependency on MediatR.</li>
</ol>
<p><strong>My question is</strong>: in number 2 which may be the option more inline with my design choices,  given that there is only one user for this introduced method, doesn't it seem like we're adding a new class and exposing its method just for the sake of testing?</p>
",https://stackoverflow.com/questions/70980628/classist-unit-testing-avoiding-mocks,"['c#', 'unit-testing', 'refactoring', 'mediatr']",68,False,1,0
React Unit testing onClick event,"<p>I have a Button wrapper component in which I am using mui button. I want to do the unit testing for this button wrapper component. I wrote some code but for onClick test it is falling.</p>
<p><strong>index.tsx (ButtonWrapper Component)</strong></p>
<pre><code>    import React from 'react';
    import { Button } from '@material-ui/core';
    import { ButtonProps } from '../../../model';
    
    type ConfigButtonProps ={
      // variant?: string,
      // color?: string,
      // fullWidth?: boolean,
      // type?: string
    }
    
    export const ButtonWrapper = (props: ButtonProps) =&gt; {
      const {children, onSubmit, disabled, type, onClick,  ...otherprops} = props
      console.log(&quot;button&quot;, otherprops, type);
    
      const configButton:ConfigButtonProps = {
        variant: 'contained',
        color: 'primary',
        fullWidth: true,
        type: type
      }
    
      return (
        &lt;Button disabled={disabled} onClick={onSubmit} {...configButton}&gt;
          {children}
        &lt;/Button&gt;
      );
    };
</code></pre>
<p><strong>index.test.tsx (Button Wrapper test)</strong></p>
<pre><code>import { ButtonWrapper } from &quot;./index&quot;
import { fireEvent, render, screen } from &quot;@testing-library/react&quot;;
import { ButtonProps } from &quot;../../../model&quot;;


const makeSut = (props: ButtonProps) =&gt; {
  return render(&lt;ButtonWrapper onClick={jest.fn()} {...props} /&gt;);
};

describe(&quot;&lt;ButtonWrapper /&gt;&quot;, () =&gt; {

  test(&quot;Button renders correctly&quot;,()=&gt;{
    render(&lt;ButtonWrapper /&gt;)

    const buttonElem = screen.getByRole('button')
    expect(buttonElem).toBeInTheDocument()
  })

  test(&quot;Should call onClick successfully&quot;, () =&gt; {
    const spy = jest.fn();

    const { getByRole } = makeSut({ onClick: spy });

    fireEvent.click(getByRole('button'));

   expect(spy).toHaveBeenCalled();
  });
});
</code></pre>
<p><strong>FormContainer.tsx (Parent Container)</strong></p>
<pre><code>return (&lt;form onSubmit={event=&gt;this.onSubmit(event)}&gt;
            {/* &lt;div&gt;FormContainer {JSON.stringify(this.props.states, null, 2)}&lt;/div&gt; */}
               {this.state.fields.map((field,index)=&gt;{
                   return &lt;FormControl 
                    key={field.id}
                    fieldConfig={field}
                    focused={(event:React.ChangeEvent&lt;HTMLInputElement&gt;)=&gt;this.fieldBlur(event,field,index)} 
                    changed={(event:React.ChangeEvent&lt;HTMLInputElement&gt;)=&gt;this.fieldChange(event,field,index)} /&gt;
               })}
               &lt;ButtonWrapper type='submit'&gt;Submit&lt;/ButtonWrapper&gt;
           &lt;/form&gt;)
</code></pre>
<p><strong>Error</strong>
<a href=""https://i.stack.imgur.com/L1lY5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/L1lY5.png"" alt=""enter image description here"" /></a></p>
<p>I also want to know in order to make 90% test coverage what else I need to test ?</p>
<p>[![enter image description here]]</p>
<p>I tried this below mentioned code also but the last line fails.</p>
<pre><code> test(&quot;Should call onClick successfully&quot;, () =&gt; {
    const onSubmitHandler = jest.fn();
    render(&lt;ButtonWrapper onClick={onSubmitHandler} /&gt;)
    
    const buttonElement = screen.getByRole('button');
    user.click(buttonElement)
    expect(onSubmitHandler).toHaveBeenCalledTimes(1) //This line fails

  });
</code></pre>
",https://stackoverflow.com/questions/73972388/react-unit-testing-onclick-event,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",466,False,1,1
unit testing a class export,"<p>file main.js:</p>
<pre><code>class myClass {
    constructor(options) {
        super({
            ...options,
   ...
    myFuncToTest(objects) {}


if (require.main !== module) {
    // Export the constructor in compact mode
    /**
     * @param {Partial&lt;utils.AdapterOptions&gt;} [options={}]
     */
    module.exports = (options) =&gt; new myClass(options);
}
</code></pre>
<p>now I want to do a unit test of the myFuncToTest.</p>
<pre><code>const main = require(&quot;./main.js&quot;);
</code></pre>
<p>how do I get a handle to the function?
Thanks</p>
",https://stackoverflow.com/questions/71276284/unit-testing-a-class-export,"['javascript', 'node.js']",77,False,1,0
Unit testing Angular Router queryParamMap,"<p>I am looking to utilize <a href=""https://angular.io/api/router/ActivatedRoute#queryParamMap"" rel=""nofollow noreferrer"">Angular queryParamMap</a> in ngOnInit lifecycle. The goal is to pass queryparam from this component as state to another. Although functionality works like charm, I am unable to unit test the code functionality.</p>
<pre><code>export class AppComponent implements OnInit {

  constructor(private readonly route: Router, private router: ActivatedRoute) {}

  ngOnInit() {
    this.router.queryParamMap.subscribe((resp) =&gt; {
      
    const state ={} as any;
    state.token = resp.get('token')
    state.clientID = resp.get('id')
    state.timestamp = resp.get('timeStamp')
      
      this.route.navigate(['/dashboard'],{state})
    });
  }}
</code></pre>
<p>And this is my unit test approach with jest</p>
<pre><code>const activatedRouteMock = {
    queryParamMap: of(routes:{token:1,id:2},
    test(key){
return this.routes.key
})
  };



const mockRoute = mock&lt;Router&gt;();
</code></pre>
<p>when I do</p>
<pre><code>it('should be defined', () =&gt; {
    component.ngOnInit()
expect(mockRoute.navigate).toBeCalledTimes(1)
expect(mockRoute.navigate).toBeCalledWith(['dashboard'], {state:{token:1,id:2}})
});
</code></pre>
<p>But I get error as</p>
<blockquote>
<p>Expected call 1
Received call 0</p>
</blockquote>
<p>I am not sure on how do I unit test this functionality with QueryParamMap as the properties could be null.</p>
",https://stackoverflow.com/questions/72235491/unit-testing-angular-router-queryparammap,"['angular', 'typescript', 'unit-testing', 'jestjs', 'url-parameters']",845,True,0,1
Unit Testing Azure ServiceBusClient Typescript,"<p>So I have this simple bit of code to put messages on a azure queue:</p>
<pre class=""lang-js prettyprint-override""><code>  const sbClient = new ServiceBusClient(process.env.QUEUE_CONNECTION_STRING);
  const sender = sbClient.createSender(process.env.QUEUE_NAME);

  try {
    const user: User = {
      firstname: 'John',
      lastname: 'Deer',
      age: 69,
    };

    await sender.sendMessages({
      body: user,
      contentType: 'application/json',
    });
    await sender.close();
  } catch (error) {
    //handle errors
  } finally {
    await sbClient.close();
  }
</code></pre>
<p>Now I am looking at unittesting my code, but I have not found a solution online after quite some digging. For axios calls you can stub them and mock the response for example, but I have found nothing of the sort for Azure Service Bus. Do any of you have experience with this? How do I approach this? Is there a way to Mock the ServiceBusClient?</p>
",https://stackoverflow.com/questions/74810465/unit-testing-azure-servicebusclient-typescript,"['typescript', 'azure', 'unit-testing', 'mocking', 'servicebus']",48,False,0,0
Angular routing unit testing failing,"<p><strong>Background:</strong></p>
<p>I have a simple reactive form where the users enters address and chooses a few products to ship to their address and a few other details. Once they submit (invokes <code>redirectToPayment()</code>) they are getting redirected after N seconds.</p>
<p><strong>Issue</strong></p>
<p>I have been trying to write an unit test case (jasmine) for the same. However, when I try to execute the test case it is failing and getting a warning in the terminal as when I run <code>ng test</code> as below:</p>
<pre><code>'Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?'
</code></pre>
<p>And following exceptions are thrown when I check the chrome console of the Jasmine reports.</p>
<pre><code>ChunkLoadError: Loading chunk 13 failed.
(timeout: http://localhost:9876/_karma_webpack_/13.js)
    at Function.requireEnsure [as e] (bootstrap:126:1)
    at webpackAsyncContext (.*\.entry\.js$ include: \.entry\.js$ exclude: \.system\.entry\.js$ namespace object:185:1)
    at loadModule (index-e806d1f6.js:1947:12)
    at initializeComponent (index-e806d1f6.js:1609:1)
    at index-e806d1f6.js:1750:1
    at ZoneDelegate.invoke (zone-evergreen.js:364:1)
    at FakeAsyncTestZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.FakeAsyncTestZoneSpec.onInvoke (zone-testing.js:1652:1)
    at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (zone-testing.js:289:1)
    at ZoneDelegate.invoke (zone-evergreen.js:363:1)
    at Zone.run (zone-evergreen.js:123:1) undefined
localConsole.&lt;computed&gt; @ context.js:265
----------------------------------------------------------------------------------------------
Unhandled Promise rejection: Cannot read properties of undefined (reading 'isProxied') ; Zone: ProxyZone ; Task: Promise.then ; Value: TypeError: Cannot read properties of undefined (reading 'isProxied')
    at initializeComponent (index-e806d1f6.js:1616:1) TypeError: Cannot read properties of undefined (reading 'isProxied')
    at initializeComponent (http://localhost:9876/_karma_webpack_/node_modules/@ionic/core/dist/esm/index-e806d1f6.js:1616:1)

</code></pre>
<p><strong>Jasmine Report</strong></p>
<pre><code>ProductComponent &gt; should navigate to payment page
Expected '' to equal '/payment'.
Error: Expected '' to equal '/payment'.
    at &lt;Jasmine&gt;
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/src/app/product/product.component.spec.ts:241:17)
    at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:1749:1)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:364:1)
</code></pre>
<p><strong>Code snippets</strong></p>
<ul>
<li>Implementation for <code>redirectToPayment()</code></li>
</ul>
<pre><code>redirectToPayment() {
    this.form.markAsTouched();

    if (this.form.valid) {      
      const { fName, lName, address, product, paymentMode } = this.form.value;
      this._paymentService.payment(fName, lName, address, product, paymentMode)
      .subscribe(
        res =&gt; {           
          setTimeout(() =&gt; { this._router.navigate(['/','payment']); }, 2000); 
        }, 
        (err) =&gt; {          
          console.error(err);          
        }
      );
   }
}
</code></pre>
<ul>
<li>Implementation for <code>payment()</code> method in Payment service</li>
</ul>
<pre><code>public payment(fName: string, lName: string, address: string, product: Product[], paymentMode: number) {
  return of({fName, lName, address, product, paymentMode});
}
</code></pre>
<p><strong>Test Suite Setup (beforeEach)</strong></p>
<pre><code>beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [
        SelectProductsComponent
      ],
      imports: [
        HttpClientTestingModule,
        ReactiveFormsModule,
        RouterTestingModule.withRoutes([
          { path: '/payment', component: DummyPaymentComponent }
        ]),
      ],
      providers: [
        FormBuilder,
        PaymentService
      ]
    }).compileComponents();

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

    fixture = TestBed.createComponent(SelectProductsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    form = component.productsForm;
}));
</code></pre>
<p><strong>Failing unit test case</strong></p>
<pre><code>fit('should navigate to payment page', fakeAsync(() =&gt; {

    form.patchValue(validFormData);
    fixture.detectChanges();

    const paymentService = TestBed.inject(PaymentService);
    const authSpy = spyOn(paymentService , 'payment').and.returnValue(of(mockSuccessRes));

    component.redirectToPayment();
    fixture.detectChanges();
    
    flush();
    expect(location.path()).toEqual('/payment');
}));
</code></pre>
<p>I am running my project on Angular version 10.</p>
<p>Could someone help me if I am missing out any detail ? Or I need to adopt a different approach ?</p>
",https://stackoverflow.com/questions/72069753/angular-routing-unit-testing-failing,"['javascript', 'angular', 'jasmine', 'karma-jasmine']",369,False,0,0
ServiceBusTrigger Unit testing with XUNIT,"<p>I have an Azure Function as below. In the following code, I'm adding a product to the database using Repository &amp; EF Core. Is there any way we can test it using <code>Xunit</code>? Currently, I'm testing this using <code>Azure Service Bus Explorer</code>.</p>
<pre><code>[FunctionName(&quot;SaveProductData&quot;)]
public void Run([ServiceBusTrigger(&quot;mytopicname&quot;, Connection = &quot;ServiceBusConnectionString&quot;)]
ProductItemUpdate message, ILogger log)
{
    var product = new Domain.Entities.Product()
    {
       ... prop init goes here..... 
    };

    log.LogInformation($&quot;Processed Product - Sain: {message.ProductId}&quot;);
    _productRepository.Add(product);
 }
</code></pre>
",https://stackoverflow.com/questions/72033211/servicebustrigger-unit-testing-with-xunit,"['c#', 'azure-functions', 'xunit']",288,True,-1,1
Mock VNCoreMLFeatureValueObservation for unit testing,"<p>Is it possible to mock <code>VNCoreMLFeatureValueObservation</code> for unit tests without any dependencies? I need to adjust the <code>featureName</code> and <code>featureValue</code>. I've tried to inherit this object and override needed properties, but the object is still marked as uninitialized...</p>
",https://stackoverflow.com/questions/72627718/mock-vncoremlfeaturevalueobservation-for-unit-testing,"['ios', 'swift', 'coreml', 'vision']",17,False,0,0
Laravel 9 Migration (Unit Testing),"<p>I'm working on a Laravel 9 app, it has no migration files.
And when writing test cases, I got server error 500 and
<code>PDOException: SQLSTATE[HY000]: General error: 1 no such table: {table-name} in /vendor/laravel/framework/src/Illuminate/Database/Connection.php:368</code></p>
<p>I created test migration files and run them with its path but does not work</p>
<pre><code>class AppTest extends TestCase {      
      use DatabaseMigrations;
      public function setUp(): void {
         parent::setUp();
         Artisan::call('migrate', ['--path' =&gt; base_path('tests/migrations/')]);
     }
}
</code></pre>
<p>How can I test the app without migration files, or is there another way?</p>
",https://stackoverflow.com/questions/72702769/laravel-9-migration-unit-testing,"['unit-testing', 'phpunit', 'laravel-9']",292,False,0,0
Unit testing with Clean Architecture,"<p>I have <code>Core project</code> which contains e.g. interaface <code>ISomeValidator</code> and in <code>Application project</code> I have implementation of this interface. If I want to test this interface, should I create test named like Core.UnitTests or Application.UnitTests? I don't know because Core contains interface of this class and Application his implementation. And I will use interface, not directly implementation.</p>
",https://stackoverflow.com/questions/74037618/unit-testing-with-clean-architecture,"['unit-testing', 'clean-architecture']",589,True,-1,1
Unit Testing Angular Component Library,"<p>I'm having no luck unit-testing an angular component library in isolation. I see this question in a few places, but no workable solutions.</p>
<p>The library works in a development environment when it accompanies the parent projects.</p>
<p><a href=""https://i.stack.imgur.com/cwT1d.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/cwT1d.png"" alt=""Angular Component Library File Structure"" /></a></p>
<p>I've tried many iterations of <code>npm i</code> and <code>ng test</code> with no luck :(</p>
<p>My latest is on the projects/interface-commons and this is my exception</p>
<pre><code>An unhandled exception occurred: Cannot find module '@angular-devkit/build-angular/package.json'
</code></pre>
<p>My research has led me to the following questions:</p>
<ol>
<li>Can an Angular library be unit-tested using Karma/Jasmin without a parent project?</li>
<li>If so, can you suggest a good resource?</li>
</ol>
<p>If not...</p>
<p>I get much closer running <code>ng test</code> from a parent directory. At least the Karma web page opens :\  The first problem I encounter is:</p>
<p><code>error TS2307: Cannot find module '@angular/core' or its corresponding type declarations.</code></p>
<p>I've been able to get past this by running <code>npm i</code> on the library's dist folder; which seems counter-intuitive to me.</p>
<p>Now I'm running into:</p>
<p><code>error TS2591: Cannot find name 'require'. Do you need to install type definitions for node? Try </code>npm i --save-dev @types/node<code> and then add 'node' to the types field in your tsconfig.</code></p>
<p>I've followed numerous suggestions to fix this, but have to ask?</p>
<p>AM I'm missing some fundamental piece of knowledge here? Am I going about this the right way or is my flayling due to something I don't know that I don't know?</p>
<p>Thanks
Dave</p>
",https://stackoverflow.com/questions/74535569/unit-testing-angular-component-library,"['angular', 'unit-testing']",17,False,0,0
Undefined Symbol: SwiftyJSON - Unit Testing,"<p>I've been looking at how to fix this bug extensively without success. Currently, I'm using Xcode 14. I don't know if this has something to do with these errors.</p>
<p>Basically, they appear when I try to execute the test so doesn't compile the project.</p>
<p><a href=""https://i.stack.imgur.com/12hwi.png"" rel=""nofollow noreferrer"">These are the errors</a></p>
<pre><code>Undefined symbol: :$s10SwiftyJSON0B0V17dictionaryLiteralACSS_yptd_tcfC

Undefined symbol: _$s10SwiftyJSON0B0VMn
</code></pre>
<h4>My code</h4>
<h5>Mock (just using the <em>createReport</em> function):</h5>
<pre><code>import Foundation
@testable import PurchHist
import SwiftyJSON

struct JsonObject: Codable {
    let subject: String
    let detail: String
}

class MockErrorReport: ReportIssuesServiceProtocol {
    
    var error: ErrorKind?
    let json = JSON()
    
    func createReport(withParams params: JSON, completion: @escaping ReportIssueResponse) {
        completion(error, nil)
    }
    
    func uploadImage(uploadData: UploadData, completion: @escaping ReportIssueImageResponse) {
    }
}
</code></pre>
<h5>Unit Testing:</h5>
<pre><code> func testSendReport() {
    let mock = MockErrorReport()
    viewModel = .init(reportService: mock)
    
    var capturedResult: Any?
    var capturedError: Error?

    let promise = expectation(description: &quot;Completion handler has been invoked&quot;)
    viewModel.reportService.createReport(withParams: mock.json, completion: { error, errors in
        if error == nil &amp;&amp; errors == nil {
            capturedResult = true
        } else {
            capturedError = error
        }
        promise.fulfill()
    })
    waitForExpectations(timeout: 5)

    XCTAssertEqual(capturedResult as! Bool, true)
    XCTAssertNil(capturedError)
}
</code></pre>
",https://stackoverflow.com/questions/73988874/undefined-symbol-swiftyjson-unit-testing,"['swift', 'unit-testing', 'swifty-json', 'undefined-symbol', 'xcode14']",81,True,0,1
Learning unit testing in C#,"<p>So I'm trying to learn unit testing in C# with a sample project I found online. The project is <a href=""https://github.com/swarooprooney/MoqSample/tree/dev/MoqTest"" rel=""nofollow noreferrer"">here</a>.</p>
<p>This is my first time doing unit testing so, I am still learning and have come across some errors. Here is the code I am trying to test:</p>
<p><code>IRoosterService</code>:</p>
<pre><code>namespace MoqBusiness
{    
    public interface IRoosterService
    {
        IList&lt;Player&gt; GetPlayersFromRepo();
    }
}
</code></pre>
<p><code>RoosterService</code>:</p>
<pre><code>namespace MoqBusiness
{
    public class RoosterService : IRoosterService
    {
        private readonly IPlayersRepo _players;

        public RoosterService(IPlayersRepo players)
        {
            _players = players;
        }
        
        public IList&lt;Player&gt; GetPlayersFromRepo()
        {
            return _players.GetPlayerList();
        }
    }
}
</code></pre>
<p><code>IPlayersRepo</code>:</p>
<pre><code>namespace MoqDataRepos
{
    public interface IPlayersRepo
    {
        IList&lt;Player&gt; GetPlayerList();
    }
}
</code></pre>
<p><code>PlayersRepo</code>:</p>
<pre><code>namespace MoqDataRepos
{
    public class PlayersRepo:IPlayersRepo
    { 
        public IList&lt;Player&gt; GetPlayerList()
        {
            var playerList = new List&lt;Player&gt; {
                new Player { Name = &quot;Swaroop&quot;, Age = 28 ,PlayersClub = new Club{ ClubName = &quot;Manchester United&quot;,CountryName = &quot;GB&quot;,Position = 7} },
                new Player { Name = &quot;Seema&quot;, Age = 30 ,PlayersClub = new Club{ ClubName = &quot;Manchester United&quot;,CountryName = &quot;GB&quot;,Position = 7}},
                new Player { Name = &quot;Jay&quot;, Age = 35 ,PlayersClub = new Club{ ClubName = &quot;Arsenal&quot;,CountryName = &quot;GB&quot;,Position = 4}},
                new Player { Name = &quot;Don&quot;, Age = 30 ,PlayersClub = new Club{ ClubName = &quot;Manchester City&quot;,CountryName = &quot;GB&quot;,Position = 1}}
            };
            return playerList;
        }
    }
}
</code></pre>
<p>So I am trying to test this <code>RoosterService</code> class to start with, using Moq and XUnit.</p>
<p>My thinking was I am testing to see if the <code>GetPlayersFromRepo</code> method returns the players that are in <code>PlayersRepo</code> - <code>GetPlayerList</code> so I would first use <code>GetPlayersFromRepo</code> method, then call <code>PlayersRepo</code> - <code>GetPlayerList</code> method and compare the two to see if they are equal.</p>
<p>Here is my code for this Test:</p>
<pre><code>namespace MoqTests
{
    public class RoosterServiceTests
    {
        private readonly RoosterService _service;
        private readonly Mock&lt;IPlayersRepo&gt; playersRepoMock = new Mock&lt;IPlayersRepo&gt;();

        public RoosterServiceTests()
        {
            _service = new RoosterService(playersRepoMock.Object);
        }
        
        [Fact]
        public void GetPlayersFromRepo_ShouldReturnPlayers()
        {
            //Arrange
            var expected = playersRepoMock.Setup(p =&gt; p.GetPlayerList()).Returns(new List&lt;Player&gt;());
            
            //Act
            var players = _service.GetPlayersFromRepo();

            //Assert
            Assert.Equal(players, expected);
        }

    }
}
</code></pre>
<p>However this does not work as the following error message comes up</p>
<blockquote>
<p>Argument 2: cannot convert from 'Moq.Language.Flow.IReturnsResult&lt;MoqDataRepos.IPlayersRepo&gt;' to 'System.Collections.Generic.IEnumerable&lt;MoqDataModel.Player&gt;'</p>
</blockquote>
<p>I don't understand why this is happening as both methods return a list so not sure why this error occurs. Since this is my first test I guess I may be setting it up wrong too? Any advice appreciated.</p>
",https://stackoverflow.com/questions/74933572/learning-unit-testing-in-c,"['c#', 'unit-testing', 'moq', 'xunit']",74,True,-1,2
Podam Unit Testing same instance,"<p>I've seen while I init and manufactor Pojo's in the multiple Unit tests that the Instance of pojo is the same, how can I get init different Instance for each Test .</p>
<pre><code>/Init PodamFactory
    PodamFactory podamFactory = new PodamFactoryImpl();

    //Define Strategy to exclude some fields
    DefaultClassInfoStrategy classInfoStrategy = DefaultClassInfoStrategy.getInstance();
</code></pre>
",https://stackoverflow.com/questions/73746211/podam-unit-testing-same-instance,"['spring-boot', 'junit', 'jemos-podam']",120,False,0,0
Python Unit Testing: Assert Statements,"<p>I am trying to write unit tests for a function that returns a list of lists. What is the best way to check that this output is as expected? The actual string value that is returned is not important at all, I just need to validate the format is the same [['any string],[any string]]</p>
<p>I am having trouble finding the correct assert statement to use. I am generating fake string data using faker.  Here is an example of what I am trying as of now</p>
<pre><code>import unittest
import faker
class TestListElements(unittest.TestCase):
    def setUp(self):
        pdf_text = [faker.pystr()]
        v1 = Pdf_class(&quot;pdf file path&quot;) 
        self.expected = pdf_text
        self.result = v1.get_pdf_data 

    def test_type(self):
        self.assertIsInstance(self.result, list)
        self.assertIsInstance(self.expected, list)
</code></pre>
",https://stackoverflow.com/questions/73144199/python-unit-testing-assert-statements,"['python', 'unit-testing', 'python-unittest']",48,False,0,0
IConfiguration dependency injection Unit testing,"<p>I've been working on Unit test using XUnit for a project.
The challenge I'm facing is dependency injection with <code>IConfiguration</code>.</p>
<p>When I'm calling the usermanagementservice in the test class, the <code>IApiConfigurationSerivce</code> which is being injected in the usermanagementservice class is null.</p>
<p>The <code>appsettings.json</code> has properties <strong>Copy to output <em>Directory:Copy always</em></strong></p>
<p>My Test class:</p>
<pre><code>[Order(2)]
public class UserMgtTest : TestBase
{
 
    [Fact, Order(1)]
    public void Testing()
    {

        __userManagementService.CreateUser();
    }
</code></pre>
<p>}</p>
<p>ApiApplicationConfiguration:</p>
<pre><code>public class ApiApplicationConfiguration : IApiApplicationConfiguration
{
    #region Private Declarations

    private readonly IConfiguration configuration;

    #endregion Private Declarations


    public ApiApplicationConfiguration(IConfiguration config)
    {
        configuration = config;
    }

   
    public string AppConnectionString =&gt; configuration.GetConnectionString(ConstantVariables.DefaultConnectionConfig);
</code></pre>
<p>}</p>
<p>My startup is as follows:</p>
<pre><code>public class TestStartup
{
    public IConfigurationRoot Configuration { get; }

    public TestStartup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
           .SetBasePath(env.ContentRootPath)
           .AddJsonFile(&quot;appsettings.json&quot;, optional: false, reloadOnChange: false);

        Configuration = builder.Build();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddOptions();
        services.AddAllDbContext(Configuration);
        services.AddIdentityConfiguration();
        services.AddTransientServices();
        services.AddScopedServices();
        services.BuildServiceProvider();
    }

    public void Configure(IApplicationBuilder app)
    {
       // app.RequestLocalization();
    }
}
</code></pre>
<p>My base is as follow:</p>
<pre><code>public partial class TestBase : IDisposable
{
    private WebHostBuilder webBuilder;
    protected TestServer _testServer;
    protected IApiApplicationConfiguration _apiApplicationConfiguration;
    protected IUserManagementService _userManagementService;

    public TestBase()
    {
        webBuilder = new WebHostBuilder();
        webBuilder.UseStartup&lt;TestStartup&gt;();

        _testServer = new TestServer(webBuilder);
        _apiApplicationConfiguration = _testServer.Host.Services.GetRequiredService&lt;IApiApplicationConfiguration&gt;();
        _userManagementService = _testServer.Host.Services.GetRequiredService&lt;IUserManagementService&gt;();
    }

    public void Dispose()
    {
        _testServer.Dispose();
    }
}
</code></pre>
<p>Which is I'm doing wrong?</p>
",https://stackoverflow.com/questions/73862592/iconfiguration-dependency-injection-unit-testing,"['c#', 'unit-testing', 'asp.net-core', 'xunit', 'xunit.net']",307,False,0,0
Unit testing GatewayFilter causes NullPointerException,"<p>I'm trying to unit test my <code>GatewayFilter</code>, however I'm having troubles running even simple test.</p>
<p>This is small example of what is failing right now</p>
<pre><code>@ExtendWith(MockitoExtension.class)
public class SomeFilterTest {

    private final GatewayFilter gatewayFilter = (exchange, chain) -&gt;
            Mono.just(&quot;Hello&quot;)
                    .flatMap(this::doSomething)
                    .switchIfEmpty(Mono.defer(() -&gt; chain.filter(exchange)));

    private Mono&lt;Void&gt; doSomething(String value) {
        System.out.println(value);
        return Mono.empty();
    }

    @Test
    void test1() {
        var exchange = MockServerWebExchange.from(MockServerHttpRequest.get(&quot;/&quot;).build());
        var chain = mock(GatewayFilterChain.class);

        gatewayFilter.filter(exchange, chain).block();
    }
}
</code></pre>
<p>Unfortunatelly, it is failing because of</p>
<blockquote>
<p>The Mono returned by the supplier is null
java.lang.NullPointerException: The Mono returned by the supplier is
null  at java.base/java.util.Objects.requireNonNull(Objects.java:246)
at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44)    at
reactor.core.publisher.Mono.subscribe(Mono.java:4361)</p>
</blockquote>
<p>And to be honest, I have no idea why is that happening?</p>
",https://stackoverflow.com/questions/70741012/unit-testing-gatewayfilter-causes-nullpointerexception,"['spring', 'unit-testing', 'spring-webflux']",621,False,0,1
Unit testing with react-admin,"<p>I am having a hard time get the tests passed for my simple react-admin application which renders a header text on screen. Need HELP</p>
<p>Here is the component that renders text on screen</p>
<pre><code>export const PostCreate = () =&gt; {
    return (
        &lt;Create&gt;
            &lt;SimpleForm&gt;
                &lt;Typography
                    variant=&quot;h6&quot;
                    sx={{
                        p: 2,
                        alignSelf: &quot;center&quot;,
                        color: &quot;rgb(77, 77, 77)&quot;,
                        fontFamily: &quot;Poppins&quot;,
                        fontWeight: &quot;600&quot;,
                        fontSize: &quot;h5.fontSize&quot;,
                    }}
                &gt;
                    Create Post
                &lt;/Typography&gt;
            &lt;/SimpleForm&gt;
        &lt;/Create&gt;
    );
};
</code></pre>
<p>Here is the test suite that checks if <strong>Create Post</strong> is rendered on screen</p>
<pre><code>render(
  &lt;AdminContext&gt;
    &lt;PostCreate {...defaultProps} /&gt;
  &lt;/AdminContext&gt;
);
expect(screen.getByText(&quot;Create Post&quot;)).toBeInTheDocument();
</code></pre>
<p>When I run <code>yarn test</code> test is failing with error <code>Error: Uncaught [TypeError: Cannot read property 'toLowerCase' of undefined]</code>
Please help to resolve this issue</p>
",https://stackoverflow.com/questions/74703652/unit-testing-with-react-admin,['react-admin'],52,False,0,0
Unit testing HttpInterceptor using Jest,"<p><strong>Need help to write unit test for the the below scenario:</strong></p>
<p>HttpInterceptor code</p>
<pre><code>import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, Observable, throwError } from 'rxjs';
import { UnauthorizedErrorDialogComponent } from 'src/app/shared/components/unauthorized-error-dialog/unauthorized-error-dialog.component';
import { SvDialogService } from 'sv-shared-library';

@Injectable({
  providedIn: 'root'
})
export class GlobalErrorIntercepterService
  implements HttpInterceptor
{
  constructor(private dialog: SvDialogService) {}

  intercept(
    req: HttpRequest&lt;any&gt;,
    next: HttpHandler
  ): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    return next.handle(req).pipe(
      catchError((err) =&gt; {
        console.log(err);
        if (err.status === 401) {
          this.dialog.open(UnauthorizedErrorDialogComponent);
        }
        return throwError(() =&gt; new Error(err));
      })
    );
  }
}
</code></pre>
<p><strong>Test Cases:-</strong></p>
<ol>
<li>If the error status is 401 the dialog box should open</li>
<li>If the error status is not 401 if should throw error</li>
</ol>
",https://stackoverflow.com/questions/74268445/unit-testing-httpinterceptor-using-jest,"['angular', 'jestjs', 'angular-http-interceptors']",53,False,-2,1
Unit testing ag-grid OnGridReady,"<p>I am trying to write unit testing for OnGridReady method in ag-grid. But I am stucked on how to pass params : GridReadyEvent to OnGridReady method. I tried mocking it but as it does not have data, My method is failing with some assigning undefined error. Need help in covering OnGridReady method.</p>
",https://stackoverflow.com/questions/74059948/unit-testing-ag-grid-ongridready,"['angular', 'unit-testing', 'jasmine', 'ag-grid']",51,False,0,0
Unit testing CSV parsing logic,"<p>I'm using the <a href=""https://crates.io/crates/csv"" rel=""nofollow noreferrer"">CSV crate</a> to read CSV files.  I then parse the content.  I would like to unit test the parsing logic.  Here's a simplified version of the code:</p>
<pre><code>fn main() -&gt; Result&lt;(), Box&lt;dyn Error&gt;&gt; {
    let mut rdr = csv::ReaderBuilder::new()
        .from_path(&quot;test.csv&quot;)?;

    process(rdr.records());

    Ok(())
}

fn process(iter: StringRecordsIter&lt;File&gt;) -&gt; Result&lt;String, String&gt; {
    for result in iter {
        // Parsing takes place here
        println!(&quot;{:?}&quot;, result);
    }
    //  Post-parsing using entire file content takes place here
    Ok(String::from(&quot;My Result Here&quot;))
}
</code></pre>
<p>In my unit test I would like to be able to construct sequences of <code>StringRecord</code> objects, pass them to the <code>process()</code> method and validate the results.  I can successfully create a <code>StringRecord</code> using the simple <code>StringRecord::new()</code> and fill it with values using <code>record.push_field(&quot;my field value&quot;)</code>.  However, I'm struggling to create an iterator that returns my values to pass to the <code>process()</code>.  Any suggestions?  I'm happy to change the arguments to <code>process()</code> if this makes things easier.</p>
",https://stackoverflow.com/questions/70800445/unit-testing-csv-parsing-logic,"['csv', 'rust']",196,True,0,1
Unit testing on imported package,"<p>I am currently creating unit testing for a project, i need to test a function that have dependency injection without interface from an entity. Here is the code</p>
<pre><code>func (u UserUsecase) CreateUser(ctx context.Context, p request.StoreUser) (entity.User, error) {
    user := &amp;entity.User{
        Username:  p.Username,
        Email:     p.Email,
        Phone:     p.Phone,
        Password:  p.Password,
        CompanyID: p.CompanyID,
    }

    err := user.Create(ctx, u.userRepo)
    if err != nil {
        return entity.User{}, err
    }

    return *user, nil
}
</code></pre>
<p>In the <code>user.Create(ctx, u.userRepo)</code> there is a function that call another function so when I create a test function I've been stuck and getting invalid memory address or null pointer. Here is the code in the <code>user.Create(ctx, u.userRepo)</code></p>
<pre><code>func (u *User) Create(ctx context.Context, ur UserStoreRepo) error {
    u.UUID = uuid.New()
    u.Status = constanta.ACTIVE
    pass, err := helpers.Bcrypting(u.Password)
    if err != nil {
        return err
    }
    u.Password = pass

    err = ur.Store(ctx, u)
    return err
}
</code></pre>
<p>What is the best method to override the <code>user.Create(ctx, u.userRepo)</code> so i can test the <code>CreateUser(ctx context.Context, p request.StoreUser)</code>.</p>
",https://stackoverflow.com/questions/72189953/unit-testing-on-imported-package,"['unit-testing', 'go', 'dependency-injection', 'mocking', 'stub']",140,True,-1,1
Unit testing void public methods,"<p>I have a class that I am trying to write a few unit tests for, specifically, a void method within the class. Im not entirely sure whether or not the fact that the method is void is of any consequence here, but this is the basic structure of the class.</p>
<pre><code>public class MyClass {
   private Map&lt;String,Object&gt; myMap;

   public void process(Bucket bucket){
      //parses bucket, updates myMap
   }

   public int getAnswer(String input){
      //searches map data
   }


}
</code></pre>
<p>The basic usage of the class is that the process method is called for each bucket to ingest it’s data, and the getAnswer method returns a summation of sorts about the data that has been processed from the buckets.</p>
<p>I’ve written a few unit tests for the getAnswer method, but since the process method doesn’t return anything, but rather just updates the internal state of my object, is there a way to properly unit test it? Since it’s a public method, I figured that it needed to be unit tested, but haven’t figured out how to do so, independent of the getAnswer method.</p>
",https://stackoverflow.com/questions/73191460/unit-testing-void-public-methods,"['java', 'junit', 'mockito']",184,True,0,2
Unit testing object mapper method,"<p>I was told that I should unit test this method but I'm not sure how? How would I unit test a method that only maps a JSON string to a DTO. The String line I will get from a Kafka topic through a Kafkalistener.</p>
<pre><code>    public void Mapper(String line) {

    try {
        LeadTimeDTO leadTimeDTO = objectMapper.readValue(line, LeadTimeDTO.class);
        
        System.out.println(&quot;leadTimeDTO:&quot; + leadTimeDTO);
    } catch (JsonProcessingException e) {
        throw new IllegalArgumentException(&quot;Error parsing to DTO&quot;);

    }

}
</code></pre>
",https://stackoverflow.com/questions/73945076/unit-testing-object-mapper-method,"['java', 'spring', 'spring-boot', 'unit-testing']",413,True,0,1
Errors when unit testing nestjs,"<p>When unit testing the nestjs file:
yandex-ndd-api-client.controller.spec.ts
there are errors like this (many):</p>
<pre><code>  Cannot find module 'src/sync.service' from 'yandex-ndd-api-client/yandex-ndd-api-client.controller.spec.ts'
</code></pre>
<p>I'm trying to change to a relative path:</p>
<pre><code>import { SyncService } from './../../src/sync.service';
</code></pre>
<p>In the test file itself, it stops swearing, but when I do the same in the project files, the project itself gives an error when launched:</p>
<pre><code>Error: Cannot find module './../../src/sync.service'
</code></pre>
<p>In tsconfig.json:
&quot;baseUrl&quot;: &quot;./&quot;,</p>
<p>How to make friends tests with the application?</p>
",https://stackoverflow.com/questions/74194267/errors-when-unit-testing-nestjs,"['testing', 'nestjs']",118,False,0,0
PHP Unit testing - test sqlsrv_connect,"<p>I am trying to test a class which connects to the database via sqlsrv_connect (maybe mocking it) but I can't find the appropriate way to do it, I have researched a little bit but seems not to be able to find the correct tutorial. Every attempt fails with sqlsrv_connect not found.  Can anyone support?</p>
<pre><code>    $this-&gt;conn = sqlsrv_connect($server_name, array(&quot;Database&quot;=&gt;$db_name));
</code></pre>
",https://stackoverflow.com/questions/70925630/php-unit-testing-test-sqlsrv-connect,"['php', 'testing', 'phpunit', 'code-coverage', 'sqlsrv']",60,False,0,0
Unit testing component text -- philosophy,"<p>I'm a bit new to unit testing, and I've really only tested methods and things. I'm curious about components like <code>&lt;h1&gt;text&lt;/h1&gt;</code> Is it common to unit test the value inside h1? I understand that it would be useful to see in the tests that it has changed, and that the test knows, similar to knowing if any other method or item has changed. But it seems like a lot of work to unit test every line of text in a project. Thoughts? Is it common to unit test text? I understand how framework pieces like Vuetify or React-bootstrap it would be vital to making sure it is rendered in the correct spots, but is it useful in standard projects</p>
",https://stackoverflow.com/questions/71773164/unit-testing-component-text-philosophy,['unit-testing'],39,True,-1,1
mock createWriteStream jest unit testing,"<p>how to make jest unit testing this file.ts and how to mock createWriteStream</p>
<pre><code>
import { join } from 'path';
import { createWriteStream } from 'fs';
import { v4 as uuidV4 } from 'uuid';

export async function saveUpload(file: any): Promise&lt;string&gt; {
  try {
    const filePath = join(
      __dirname,
      `../../src/uploads/${uuidV4()}-${file.filename}`
    );

    await file.createReadStream().pipe(createWriteStream(filePath));

    return filePath;
  } catch (error) {
    throw error;
  }
}
</code></pre>
",https://stackoverflow.com/questions/74384968/mock-createwritestream-jest-unit-testing,"['javascript', 'typescript', 'unit-testing', 'next.js', 'jestjs']",38,False,0,0
PHP unit testing without Composer,"<p>Does anyone know of a basic unit testing framework for PHP that does <em>not</em> require Composer in order to use it?  The project's testing requirements are simple, and I expect any framework would be fine. I'd be very happy with <a href=""https://phpunit.de/"" rel=""nofollow noreferrer"">PHPUnit</a> if there's a way of using that without Composer, though I don't think that's possible.  The alternative is to roll my own, but I'd rather not do that unless it's necessary.</p>
<p>I know Composer is a perfectly good system, and if the decision were mine, we'd be using it.  But it's not my decision, and it has been made clear that the project leader would rather not have any unit testing if the alternative is to use Composer.  That's wholly irrational, I know, but it's not a battle I have time to fight.</p>
",https://stackoverflow.com/questions/70897553/php-unit-testing-without-composer,"['php', 'unit-testing']",309,True,0,1
Unit testing network bound resource,"<p>I'm aware that there are a couple of topics on this but none of them solve my issue.</p>
<p>I'm trying to test an implementation of NetworkBoundResource.</p>
<pre><code>inline fun &lt;ResultType, RequestType, ErrorType&gt; networkBoundResource(
    crossinline query: () -&gt; Flow&lt;ResultType&gt;,
    crossinline fetch: suspend () -&gt; Response&lt;RequestType&gt;,
    crossinline saveFetchResult: suspend (RequestType) -&gt; Unit,
    crossinline onFetchFailed: (Response&lt;*&gt;?, Throwable?) -&gt; ErrorType? = { _, _ -&gt; null },
    crossinline shouldFetch: (ResultType) -&gt; Boolean = { true },
    coroutineDispatcher: CoroutineDispatcher
) = flow&lt;Resource&lt;ResultType, ErrorType&gt;&gt; {
    val data = query().first()
    emit(Resource.Success(data))

    if (shouldFetch(data)) {
        val fetchResponse = safeApiCall { fetch() }
        val fetchBody = fetchResponse.body()
        if (fetchBody != null) {
            saveFetchResult(fetchBody)
        }

        if (!fetchResponse.isSuccessful) {
            emit(Resource.Error(onFetchFailed(fetchResponse, null)))
        } else {
            query().map { emit(Resource.Success(it)) }
        }
    }
}.catch { throwable -&gt;
    emit(Resource.Error(onFetchFailed(null, throwable)))
}.flowOn(coroutineDispatcher)
</code></pre>
<p>This works as expected in my use case in production code.</p>
<pre><code>override suspend fun getCategories() = networkBoundResource(
    query = {
        categoryDao.getAllAsFlow().map { categoryMapper.categoryListFromDataObjectList(it) }
    },
    fetch = {
        categoryServices.getCategories()
    },
    onFetchFailed = { errorResponse, _ -&gt;
        categoryMapper.toError(errorResponse)
    },
    saveFetchResult = { response -&gt;
        // Clear the old items and add the new ones
        categoryDao.clearAll()
        categoryDao.insertAll(categoryMapper.toDataObjectList(response.data))
    },
    coroutineDispatcher = dispatchProvider.IO
)
</code></pre>
<p>I have my test setup like this (using turbine for flow testing).</p>
<pre><code>@OptIn(ExperimentalCoroutinesApi::class)
class NetworkBoundResourceTests {

    data class ResultType(val data: String)
    sealed class RequestType {
        object Default : RequestType()
    }

    sealed class ErrorType {
        object Default : RequestType()
    }

    private val dispatchProvider = TestDispatchProviderImpl()

    @Test
    fun `Test`() = runTest {
        val resource = networkBoundResource(
            query = { flowOf(ResultType(data = &quot;&quot;)) },
            fetch = { Response.success(RequestType.Default) },
            saveFetchResult = { },
            onFetchFailed = { _, _ -&gt; ErrorType.Default },
            coroutineDispatcher = dispatchProvider.IO
        )

        resource.test {
           
        }
    }
}
</code></pre>
<p>The coroutine dispatcher is set to unconfined through DI/Test dispatcher.</p>
<p>I want to test that;</p>
<p>Emitting first data from query, then query is updated and new data from saveFetchResult then <code>query().map { emit(Resource.Success(it)) }</code> emits the updated data from that save result.</p>
<p>I think I need to do something around a spyk on my flow with MockK but I can't seem to figure it out. <code>query()</code> will always return the same flow of data as it's mocked to do so if I <code>awaitItem()</code> again it returns the same data (as it should) as that's what the mock is setup for.</p>
",https://stackoverflow.com/questions/74245208/unit-testing-network-bound-resource,"['android', 'kotlin', 'mockk']",121,False,0,1
React unit testing conditional query,"<p>My component receives prop and make an apollo query based on that <code>Component.tsx</code></p>
<pre><code>// Component.tsx
import { useQuery } from '@apollo/client';

const MyComponent: React.FC&lt;MyComponentProps&gt; = ({ id, skipCondition }) =&gt; {
  const [displayLink, setDisplayLink] = React.useState(false);

  const { error, refetch } = useQuery(GET_LINK_BY_ID, {
     variables: { id },
     skip: skipCondition === 'N', // condition to skip the query
     onCompleted: (data) =&gt; {
       setDisplayLink(...)
     }
  })
  return &lt;&gt;
     {displayLink &amp;&amp; &lt;Link to=&quot;/test&quot;&gt;Test link&lt;/Link&gt;}
  &lt;/&gt;
}
</code></pre>
<p>How can I create Unit Test for cases it skips the query, calls the query and show the <em>link</em> on template? Appreciate your helps.</p>
",https://stackoverflow.com/questions/74188573/react-unit-testing-conditional-query,"['reactjs', 'jestjs', 'enzyme', 'apollo-client', 'react-testing-library']",87,False,0,0
Unit testing rxjs in Angular,"<p>Im having a problem writing unit tests for observable in Angular... Im trying to test cases if displayPaymentsLineItem$ will be true or false depending on the values of
mobileAccountBalance$, and selectedMobileDigitalBill$... Can anyone help?</p>
<pre><code>  public selectedMobileDigitalBill$: Observable&lt;MobileDigitalBill&gt;;
  public mobileAccountBalance$: Observable&lt;MobileAccountBalance&gt;;

  private expandedLinesMap: object = {};
  private expandedTaxesAndFees: boolean = false;
  private devices: MobileDevice[] = [];
  private destroy$: Subject&lt;void&gt; = new Subject();

  constructor(]
    private mobileStatementsTabFacade: MobileStatementsTabFacade,
    private billingMobileFacade: BillingMobileFacade,
  ) {}

  ngOnInit() {
        this.mobileAccountBalance$ = this.mobileStatementsTabFacade.mobileAccountBalance$;

        this.displayPaymentsLineItem$ = combineLatest([
          this.mobileAccountBalance$,
          this.selectedMobileDigitalBill$,
        ]).pipe(
          map(([mobileAccountBalance, selectedMobileDigitalBill]: [MobileAccountBalance, MobileDigitalBill]) =&gt; {
            const isPastDue: boolean = mobileAccountBalance?.pastdue &gt; 0;
            const hasPayments: boolean = selectedMobileDigitalBill?.payments?.length &gt; 0;

            return isPastDue &amp;&amp; hasPayments;
          })
        );
      }
    });
</code></pre>
",https://stackoverflow.com/questions/70965764/unit-testing-rxjs-in-angular,"['javascript', 'angular', 'typescript', 'unit-testing']",122,False,0,1
Unit testing angular custom validator,"<p>I'm just starting to learn unit testing and I have this problem that causes unit tests not to run.
after running ng test it says Executed 0 out of 0 Success
here's my code</p>
<p>validator</p>
<pre><code>export function validateUrl(control: FormControl): ValidationErrors | null {
  let valid = true;
  try{
   let str = control.value;
   if(str.indexOf('://') === -1){
    str = `http://${str}`
    new URL(str);
    control.setValue(str);
  }else{
    new URL(control.value);
  }
 }catch{
   valid = false
 }
  return valid ? null : { invalidUrl: true }
}
</code></pre>
<p>spec file</p>
<pre><code>import { TestBed} from &quot;@angular/core/testing&quot;;
import { FormControl } from &quot;@angular/forms&quot;;
import { validateUrl } from &quot;./web-page-details.component&quot;;
describe('maxTextLength', () =&gt; {
  beforeEach(() =&gt; TestBed.configureTestingModule({}))
   const control = new FormControl();
  it('should return null if input string contains protocol', () =&gt; {
   control.setValue('http://test.com');
   expect(validateUrl(control)).toBeNull();
 });
  it('should return null if url doesnt contain protocol', () =&gt; {
   control.setValue('test.com');
   expect(validateUrl(control)).toBeNull();
 });
});
</code></pre>
",https://stackoverflow.com/questions/71607145/unit-testing-angular-custom-validator,"['angular', 'typescript', 'unit-testing', 'validation']",976,False,0,0
Unit Testing a Kafka SpringBoot producer,"<p>I am trying to create a unit test for my Kafka Producer which is integrated into a file. Here's my Kafka Producer:</p>
<pre><code>FileName: MessageProducer.java

public boolean sendMessage(ReceivedMessage message) {
    private String topicName = &quot;output-flow&quot;;
    try{
        logger.info(&quot;Sending message: {} to topic: {}&quot;, message, topicName);
        kafkaProducer.send(topicName, message).get();
        return true;
    } catch (Exception e){
        logger.error(&quot;Error sending message: {} to topic: {}&quot;, message, topicName, e);
        return false;
    }
}
</code></pre>
<p>And here is what I have done so far for my unit test, obviously, with not success at all:</p>
<pre><code>@Mock
private KafkaTemplate&lt;String, ReceivedMessage &gt; kafkaProducer;

private static final String TRANSACTION_TOPIC = &quot;test&quot;;

// Function for parameterized values

@ParameterizedTest
@MethodSource(&quot;getTransactionProvider&quot;)
public void sendMessageTest(ReceivedMessage message) {
    MessageProducer mockProducer = new MessageProducer(kafkaProducer);
    when(kafkaProducer.send(TRANSACTION_TOPIC, message)).thenReturn({no idea what to put here});
    when(mockProducer.sendMessage(message)).thenReturn(true);
    assertTrue(mockProducer.sendMessage(message));
}

// Test for exception
// Fails too
@ParameterizedTest
@MethodSource(&quot;getTransactionProvider&quot;)
public void sendMessageTest_ThrowsException(ReceivedMessage message) {
    MessageProducer mockProducer = new MessageProducer(kafkaProducer);
    when(kafkaProducer.send(TRANSACTION_TOPIC, message)).thenThrow(new RuntimeException());
    assertThrows(RuntimeException.class, () -&gt; mockProducer.sendMessage(null));
}
</code></pre>
<p>I get <code>Exception: org.opentest4j.AssertionFailedError: Expected java.lang.RuntimeException to be thrown, but nothing was thrown.</code> for the latter unit test.</p>
",https://stackoverflow.com/questions/72628487/unit-testing-a-kafka-springboot-producer,"['java', 'spring-boot', 'unit-testing', 'apache-kafka', 'spring-kafka']",2286,True,3,2
Kafka client unit testing for dotnet,"<p>Im looking for assistance in writing unit tests for kafka in dotnet. Confluent seems to provide a Mocks for producers and consumers in Java only.</p>
",https://stackoverflow.com/questions/73314009/kafka-client-unit-testing-for-dotnet,"['c#', 'apache-kafka', 'confluent-kafka-dotnet']",2069,True,3,1
Unit-testing a .pl Perl file,"<p>I am brand new to Perl, but am trying to add some functionality to Sanoid (<a href=""https://github.com/jimsalterjrs/sanoid"" rel=""nofollow noreferrer"">https://github.com/jimsalterjrs/sanoid</a>), which is written in Perl as a single script without .pm Module files (as far as I understand these things).</p>
<p>I wanted to add some simple unit tests to a new subroutine I have added and I was expecting to be able to do this as easily as in Python, where you can just <code>import</code> the name of the other file and test subroutine return values from various inputs.</p>
<p>I have read a number of testing tutorials and think I follow how to do the actual testing, but I'm struggling at the first hurdle of importing the script I want to test.</p>
<p>From what I have read, the main way to import things is to turn it into a .pm module and <code>use</code> it, but I do not want to attempt rearchitecting someone's code just for testing (particularly when I'm so new to Perl). The alternative seems to be to <code>require</code> or <code>do</code> the file, which I understand will execute the file (which isn't ideal as this does things even if called without arguments) and means I need to add a <code>1;</code> to the end of the file to ensure it returns true when required.</p>
<p>It looks like I can use <code>unless (caller)</code> to rearrange things so that nothing is executed if it is <code>require</code>d, but I wanted to check I had not missed something obvious.</p>
",https://stackoverflow.com/questions/71212667/unit-testing-a-pl-perl-file,"['unit-testing', 'perl']",227,True,3,2
"Dependency injection in unit testing, xUnit","<p>This might be a stupid question, but I'm having one of those days.</p>
<p>I have a class called <code>JwtManager</code> and an interface called <code>IJwtManager</code>, I'm trying to inject the interface into a unit-testing class so I can test it but it doesn't work, the compiler gives me this message: <code>The following constructor parameters did not have matching fixture data: IJwtManager jwtManager</code>.</p>
<p>I think the problem is the compiler doesn't know what class should the interface be mapped to, but how can I write the equivalent of <code>services.AddScoped&lt;&gt;()</code> in a test class?</p>
<p>Code sample of test class:</p>
<pre><code>public class JwtManagerTests
{
    private readonly IJwtManager jwtManager;
    public JwtManagerTests(IJwtManager jwtManager)
    {
        this.jwtManager = jwtManager;
    }

    [Fact]
    public void Test_Something()
    {
        // Test here
    }
}
</code></pre>
",https://stackoverflow.com/questions/70884367/dependency-injection-in-unit-testing-xunit,"['c#', '.net', 'dependency-injection', 'xunit']",2419,True,2,1
Mock spark Dataframewriter for unit testing,"<p>I am writing unit testcase for a function using mockito that writes the df to a hivetable using insertinto.</p>
<pre><code>def method():Unit={
val df=spark.sql(&quot;some query&quot;) 
df.write.insertInto(&quot;tablename&quot;)
}
</code></pre>
<p>How can I mock this part of the function (within a scala object) to do nothing or skip this call. I do not want to write it to any external source system hence mocking.</p>
",https://stackoverflow.com/questions/71320725/mock-spark-dataframewriter-for-unit-testing,"['scala', 'unit-testing', 'apache-spark', 'apache-spark-sql', 'mocking']",211,False,2,0
Unit Testing Passport Strategy / NestJS Guard,"<p>I have a JWTGuard() decorator which follows the implementation as described in <a href=""https://docs.nestjs.com/security/authentication#jwt-functionality"" rel=""nofollow noreferrer"">https://docs.nestjs.com/security/authentication#jwt-functionality</a></p>
<p>It looks like so:</p>
<pre class=""lang-js prettyprint-override""><code>import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { IS_PUBLIC_ROUTE } from '../decorators/public-route.decorator';

@Injectable()
export class JWTAuthenticationGuard extends AuthGuard('jwt') {
  constructor(private readonly reflector: Reflector) {
    super();
  }
 canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {
    const isPublic = this.reflector.getAllAndOverride&lt;boolean&gt;(
      IS_PUBLIC_ROUTE,
      [context.getHandler(), context.getClass()],
    );

    if (isPublic) return true;

    return super.canActivate(context)
  }
}
</code></pre>
<p>It works as expected, but having difficulty unit testing the guard. In short, I want to test three things:</p>
<ul>
<li>If IS_PUBLIC_ROUTE is set, then canActivate() returns true ✅ this unit test works</li>
<li>If an expired/invalid/incorrectly signed token is passed, canActivate() returns false ❌</li>
<li>If a valid token is found, canActivate() returns true ❌</li>
</ul>
<p>I tried to follow <a href=""https://github.com/jmcdo29/testing-nestjs/blob/master/apps/complex-sample/src/cat/cat.guard.spec.ts"" rel=""nofollow noreferrer"">https://github.com/jmcdo29/testing-nestjs/blob/master/apps/complex-sample/src/cat/cat.guard.spec.ts</a> which just tests a bare guard, not extending a Passport Guard.</p>
<p>Tests are setup as follows:</p>
<pre class=""lang-js prettyprint-override""><code>  let guard: JWTAuthenticationGuard;
  const reflector = new Reflector();

  beforeEach(() =&gt; {
    guard = new JWTAuthenticationGuard(reflector);
    passport.use('jwt', new JWTStrategy());
  });
</code></pre>
<p>The first test (should return false)</p>
<pre class=""lang-js prettyprint-override""><code> it('should return false if no authorization token is found', () =&gt; {
    const context = createMock&lt;ExecutionContext&gt;();

    const result = guard.canActivate(context);

    expect(result).toBe(false);
  });
</code></pre>
<p>My test never even makes it to the <code>expect()</code> clause, as it has thrown an UnauthorisedException and the test suite exits entirely.</p>
<p>I tried debugging inside the canActivate() method, and checking the type of super.canActivate() which tells me that it's a pending promise. I tried awaiting it, but still says its Pending, I tried wrapping in a try/catch, but the catch block never runs. Reading through the code of passport's AuthGuard, it never throws either.</p>
<p>I tried to add a valid token:</p>
<pre class=""lang-js prettyprint-override""><code>it('should return false if no authorization token is found', async () =&gt; {
    const context = createMock&lt;ExecutionContext&gt;();
    expect(context.switchToHttp()).toBeDefined();
    context.switchToHttp().getRequest.mockReturnValue({
      headers: {
        Authorization:
          'Bearer ey...[truncated]...dE',
      },
    });

    const result = await guard.canActivate(context);

    expect(result).toBe(true);
</code></pre>
<p>however I still just get an UnauthorisedException thrown from god knows where at the <code>result = guard.can...</code> line, and still never makes it to the expect.</p>
<p>Any guidance would be appriciated.</p>
",https://stackoverflow.com/questions/73904339/unit-testing-passport-strategy-nestjs-guard,"['unit-testing', 'nestjs', 'passport.js']",430,False,1,0
Unit testing camel routes containing serviceCall(),"<p>I have a camel route that reaches out to a URL and does some processing with the results:</p>
<pre><code>from(&quot;direct:doURL&quot;)
    .routeId(&quot;urlRouteId&quot;)
    .to(&quot;http://host:port/path&quot;)
    .process(e -&gt; {
        //Do Stuff
    });
</code></pre>
<p>I can run unit test on that route without making an actual call to the URL by intercepting the call in my unit test like follows:</p>
<pre><code>AdviceWith.adviceWith(context, &quot;urlRouteId&quot;, a -&gt;
    a.interceptSendToEndpoint(&quot;http://host:port/path&quot;).skipSendToOriginalEndpoint().to(&quot;mock:test&quot;)
);
</code></pre>
<p>I’m updating that route to use .serviceCall() instead to look up the actual URL of the service, something like this:</p>
<pre><code>from(&quot;direct:doService&quot;)                
    .routeId(&quot;servcieRouteId&quot;)
    .serviceCall(&quot;myService/path&quot;)
    .process(e -&gt; {
        //Do Stuff
    });
</code></pre>
<p>This works great, but I don’t know how to do a similar unit test on this route.  Is there some sort of LoadBalancerClient I can use for testing?  What is the standard way to unit test routes with service calls?  I've been googling around for awhile and haven't had much luck, any ideas?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/73830116/unit-testing-camel-routes-containing-servicecall,"['unit-testing', 'apache-camel', 'apache-camel-3']",66,True,1,1
Mockito unit testing a retry logic,"<p>I have a piece of code that retries when it fails with <code>ExceptionOne</code>, and if it continues to fail, it will throw a <code>ExceptionTwo</code>. I want to test this behavior, but am not sure how to.</p>
<pre><code>public void someMethod(String x) {
    boolean retry;
    int try = 0;
    do {
        retry = false;
        try {
             someFunction(x);
        } catch (ExceptionOne e) {
            if (try &lt; 5) {
                retry = true;
                attempt++;
            } else {
                throw new ExceptionTwo();
            }
        }
    } while (retry);
    
}

private void someFunction(String x) {
    doSomething(); //This can throw ExceptionOne
}
</code></pre>
<p>Suppose these functions are inside a <code>SomeClass</code>. I mocked <code>SomeClass</code> and tried something like</p>
<pre><code>doThrow(new ExceptionOne()).doNothing().when(mockObject).someMethod(any())
</code></pre>
<p>for consecutive calls, but this isn't quite what I am looking for since I believe this is really testing the someMethod, not <code>someFunction</code> or the retry functionality.</p>
<p>How do you test something like this? That is, how do I verify that the behavior that when <code>someFunction</code> fails with ExceptionOne, it will retry until it succeeds or until it runs out of retries and throws an ExceptionTwo?</p>
",https://stackoverflow.com/questions/70963645/mockito-unit-testing-a-retry-logic,"['java', 'unit-testing', 'testing', 'mockito', 'retry-logic']",1205,False,1,1
Failed: Errors in unit testing angular,"<p>I set up testing environment for a component that I would like to test, but unfortunately getting some errors which I can not get my head around..</p>
<pre><code>describe('HelloWorldComponent', () =&gt; {
        let component: HelloWorldComponent;
        let fixture: ComponentFixture&lt;HelloWorldComponent&gt;;
        let cookieValue: string;
    
    
        beforeEach(async(() =&gt; {
            
            const cookieSvcMock = jasmine.createSpyObj&lt;CookieService&gt;('CookieService', ['check', 'get', 'set', 'delete']);
    
            cookieValue = 'eyJ1c2VyX2lkIjoiNGJm.....';
            mockedCookieService.check.and.returnValue(true);
            mockedCookieService.get.and.returnValue(cookieValue);

           const routes = [
            {path: '/site1', component: AnotherComponent},
            {path: '/site2', component: ComponentTwo}]
    
    
            TestBed.configureTestingModule({
                declarations: [HelloWorldComponent],
                imports: [     
                    FormsModule,
                    ReactiveFormsModule,
                    MatInputModule,
                    MatIconModule,
                    MatSlideToggleModule,
                    MatTooltipModule,
                    RouterTestingModule.withRoutes((routes)),                       
                ],
                providers: [
                    {provide: ActivatedRoute, useValue: {params: of({id: 1})}},
                    {provide: CookieService, useValue: mockedCookieService},
                ]
            }).compileComponents();
        }));
    
        beforeEach(() =&gt; {
            fixture = TestBed.createComponent(HelloWorldComponent);
            component = fixture.componentInstance;
            fixture.detectChanges();
        });
    
        it('should create', () =&gt; {
            expect(component).toBeTruthy();
        });
    
    });
    
    describe('get array of strings', () =&gt; {
    
        let helloWorldComponent = new HelloWorldComponent(null,
            new CookieService(document));
       
        it('should return array', () =&gt; {
    
            const text = 'dsfsfsf@domain.comsfssdffdsf.Adfgdfg&lt;&gt;';
            const textArr = ['dsfsfsf@domain.com']
    
            let getTextArr: string[];
    
            getTextArr = helloWorldComponent.getEmails(text);
    
            expect(getTextArr).toBe(textArr);
        })
    })
</code></pre>
<p>But I am getting the following errors when running ng test:</p>
<p>HelloWorldComponent &gt; should create
1.Error:</p>
<p>Failed: Component AnotherComponent is not part of any NgModule or the module has not been imported into your module.</p>
<pre><code>Error: Component AnotherComponent is not part of any NgModule or the module has not been imported into your module.
    at JitCompiler._createCompiledHostTemplate (http://localhost:9876/_karma_webpack_/node_modules/@angular/compiler/fesm2015/compiler.js:25915:1)
    at http://localhost:9876/_karma_webpack_/node_modules/@angular/compiler/fesm2015/compiler.js:25891:1
    at &lt;Jasmine&gt;
    at http://localhost:9876/_karma_webpack_/node_modules/@angular/compiler/fesm2015/compiler.js:25888:1
    at &lt;Jasmine&gt;
    at JitCompiler._compileComponents (http://localhost:9876/_karma_webpack_/node_modules/@angular/compiler/fesm2015/compiler.js:25877:1)
    at http://localhost:9876/_karma_webpack_/node_modules/@angular/compiler/fesm2015/compiler.js:25815:1
    at Object.then (http://localhost:9876/_karma_webpack_/node_modules/@angular/compiler/fesm2015/compiler.js:2166:27)
    at JitCompiler._compileModuleAndAllComponents (http://localhost:9876/_karma_webpack_/node_modules/@angular/compiler/fesm2015/compiler.js:25813:1)
    at JitCompiler.compileModuleAndAllComponentsAsync (http://localhost:9876/_karma_webpack_/node_modules/@angular/compiler/fesm2015/compiler.js:25775:1)
</code></pre>
<p>2 Error:</p>
<pre><code>Error: Expected undefined to be truthy.
        at &lt;Jasmine&gt;
        at UserContext.&lt;anonymous&gt; (http://localhost:9876/_karma_webpack_/src/app/hello-world(hello-world.component.spec.ts:30:40)
        at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-evergreen.js:359:1)
        at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:308:1)
</code></pre>
<p>Error for spec getArr:</p>
<p>InvalidTokenError: Invalid token specified: Cannot read properties of undefined (reading 'replace')</p>
<pre><code>at &lt;Jasmine&gt;
at Object../node_modules/jwt-decode/lib/index.js (http://localhost:9876/_karma_webpack_/node_modules/jwt-decode/lib/index.js:9:1)
at __webpack_require__ (http://localhost:9876/_karma_webpack_/webpack/bootstrap:79:1)
at Module../hello-world.component.ts (http://localhost:9876/_karma_webpack_/main.js:1036:69)
at __webpack_require__ (http://localhost:9876/_karma_webpack_/webpack/bootstrap:79:1)
at Module../src/app/hello-world/hello-world.component.spec.ts (http://localhost:9876/_karma_webpack_/main.js:900:80)
at __webpack_require__ (http://localhost:9876/_karma_webpack_/webpack/bootstrap:79:1)
at Module../src/test.ts (http://localhost:9876/_karma_webpack_/src/test.ts:10:1)
at __webpack_require__ (http://localhost:9876/_karma_webpack_/webpack/bootstrap:79:1)
at checkDeferredModules (http://localhost:9876/_karma_webpack_/webpack/bootstrap:45:1)
at http://localhost:9876/_karma_webpack_/webpack/bootstrap:152:1
</code></pre>
<p>I'm not sure if the question is too specific, I've been hanging out here for a long time unfortunately and I'm not sure how to solve this.
Any help would be greatly appreciated!</p>
",https://stackoverflow.com/questions/72557856/failed-errors-in-unit-testing-angular,"['angular', 'unit-testing']",646,True,1,2
Flutter Unit testing TextFormField access obscureValue,"<p>So i have a TextFormField</p>
<pre><code>Widget buildPassword() =&gt; TextFormField(
    key: const Key('passwordFormKey'),
    obscureText: true,
    maxLines: 1,
    initialValue: password,
    style: const TextStyle(
      color: Colors.blue,
      fontWeight: FontWeight.bold,
      fontSize: 20,
    ),
    decoration: const InputDecoration(
      border: OutlineInputBorder(),
    ),
    validator: (password) =&gt;
    password != null &amp;&amp; password.isEmpty ? 'The password cannot be empty' : null,
    onChanged: onChangePassword,
  );
</code></pre>
<p>And i want to check for initial value/state that the TextFormField is being obscured</p>
<p>But i can't find a way to check in my unit test that obscureText value from the TextFormField itself.</p>
<p>Any idea how to access it ?</p>
<pre><code>testWidgets('Mail And Password are Empty and initialed correctly', (widgetTester) async {
    await widgetTester.pumpWidget(createWidgetUnderTest());
    final TextFormField mailField = widgetTester.widget&lt;TextFormField&gt;(find.byKey(const Key('mailFormKey')));
    final TextFormField passwordField = widgetTester.widget&lt;TextFormField&gt;(find.byKey(const Key('passwordFormKey')));
    
    expect(mailField.controller?.value, '');
    expect(passwordField.controller?.value, '');
    expect(mailField.initialValue, '');
    expect(passwordField.initialValue, '');

  });
</code></pre>
",https://stackoverflow.com/questions/74021303/flutter-unit-testing-textformfield-access-obscurevalue,"['flutter', 'unit-testing', 'flutter-textformfield']",103,False,1,1
Unit testing for grpc python client,"<p>I have created python grpc client to communicate with java grpc server and have implemented one grpc api from client side.</p>
<pre><code>self.channel = grpc.insecure_channel(
                self.host, options=[(&quot;grpc.lb_policy_name&quot;, &quot;round_robin&quot;)]
            )
            self.blocking_stub = contacts_pb2_grpc.ExampleServiceStub(self.channel
</code></pre>
<p>and invoked the grpc api by following call</p>
<pre><code>def create_call(self, request):
    return self.blocking_stub.createCall(
        request, metadata=add_meta_data(self), timeout=self.deadline_seconds
    )
</code></pre>
<p>my question here is I want to mock the create_call and need to get the response back
so I have created python service implementation.</p>
<p>I want to make sure the service code is called whenever I made create_call in unitest .In java we have something like this.</p>
<pre><code> String serverName = InProcessServerBuilder.generateName();

 grpcCleanup.register(
        InProcessServerBuilder.forName(serverName)
            .directExecutor()
            .addService(ServiceImplTestHelper.serviceImpl)
            .build()
            .start());
 channel =
        grpcCleanup.register(InProcessChannelBuilder.forName(serverName).directExecutor().build());
</code></pre>
<p>Can someone suggest how we can do this in python ?</p>
",https://stackoverflow.com/questions/70671533/unit-testing-for-grpc-python-client,"['python', 'pytest', 'grpc', 'grpc-python', 'pytest-mock']",557,False,1,0
Unit testing GORM associations with sqlmock,"<p>I'm working on my first Go + Gin + GORM project. I've two models: <code>List</code> and <code>Todo</code> as follows:</p>
<pre class=""lang-golang prettyprint-override""><code>type List struct {
    gorm.Model

    Name        string

    Todos []*Todo `gorm:&quot;many2many:list_todos;&quot;`
}

type Todo struct {
    gorm.Model

    Title       string

    Lists []*List `gorm:&quot;many2many:list_todos;&quot;`
}
</code></pre>
<p>I've a helper function to add a <code>Todo</code> to a <code>List</code>:</p>
<pre class=""lang-golang prettyprint-override""><code>func (self *List) AddTodos(db *gorm.DB, todos ...*Todo) error {
    return db.Model(self).Association(&quot;Todos&quot;).Append(todos)
}
</code></pre>
<p>I want to unit test the <code>AddTodos</code> function. I'm using <code>sqlmock</code> for mocking. This is the code for the unit test:</p>
<pre class=""lang-golang prettyprint-override""><code>func TestAddTodosWithNoTodos(t *testing.T) {
    gormDB, db, mock, _ := misc.GetMockedGormDBWithMock()
    defer db.Close()

    mockList := &amp;List{
        Model: gorm.Model{ID: 1},
    }

    mock.NewRows([]string{&quot;id&quot;}).AddRow(mockList.ID)

    if err := mockList.AddTodos(gormDB); err != nil {
        // test fails here
        t.Errorf(&quot;Expected no error, got %v&quot;, err)
    }

    todos := []Todo{}
    if err := gormDB.Model(mockList).Association(&quot;Todos&quot;).Find(&amp;todos); err != nil {
        // test also fails here
        t.Errorf(&quot;Expected no error, got %v&quot;, err)
    }

    if len(todos) != 0 {
        t.Errorf(&quot;Expected no todos, got %v&quot;, todos)
    }
}
</code></pre>
<p>I've marked the two places where the test fails. The <code>error</code> object being checked at both these places are from GORM, however, in the test failure error messages, it is revealed that <code>sqlmock</code> is causing these errors:</p>
<p>First error message:</p>
<pre><code>Expected no error, got all expectations were already fulfilled, call to database transaction Begin was not expected
</code></pre>
<p>Second error message:</p>
<pre><code>Expected no error, got all expectations were already fulfilled
</code></pre>
<p>I don't want to test which queries are executed, hence, I've not used <code>sqlmock</code>'s <code>ExpectQuery</code>. Still, &quot;unexpected queries&quot; are causing errors.</p>
<p>How can I unit test <code>AddTodos</code> without testing the queries it performs?</p>
",https://stackoverflow.com/questions/72136934/unit-testing-gorm-associations-with-sqlmock,"['unit-testing', 'go', 'go-gorm', 'go-sqlmock']",500,False,1,0
Unit testing DynamoDB SDK in Go?,"<p>I'm using the AWS SDK in Go, but I'm having trouble unit testing my DynamoDB updates. Basically, I'm using <code>gomock</code> to set the expected <code>UpdateItemInput</code> like so:</p>
<pre><code>return m.EXPECT().UpdateItemWithContext(
            gomock.Any(),
            &amp;dynamodb.UpdateItemInput {
                ConditionExpression: aws.String(&quot;(#0 = :0) AND (#1 = :1)&quot;),
                ExpressionAttributeNames: map[string]*string{
                    &quot;#0&quot;: aws.String(&quot;PK&quot;),
                    &quot;#1&quot;: aws.String(&quot;SK&quot;),
                    &quot;#2&quot;: aws.String(&quot;SomeAttrName&quot;),
                },
                ExpressionAttributeValues: map[string]*dynamodb.AttributeValue {
                    &quot;:0&quot;: {S: aws.String(primaryKey)},
                    &quot;:1&quot;: {S: aws.String(secondaryKey)},
                    &quot;:2&quot;: {S: aws.String(ValueToUpdate)},
                },
                Key: map[string]*dynamodb.AttributeValue{
                    &quot;PK&quot;: {S: aws.String(primaryKey)},
                    &quot;SK&quot;: {S: aws.String(secondaryKey)},
                },
                ReturnValues:     aws.String(dynamodb.ReturnValueAllNew),
                TableName:        aws.String(dynamo.TableName),
                UpdateExpression: aws.String(&quot;SET #2 = :2\n&quot;),
            }

</code></pre>
<p>However, when I run the test, it fails because it seems there is a mismatch between what gomock expected and what it got. The positions of the values in the <code>UpdateItemInput</code> from the business logic are different every time I run the test, which I think is what's messing this up.</p>
<p>Is there a better way to test things like this in Go? Or if not, is there a way to enforce the same order every time, or ignore the order?</p>
",https://stackoverflow.com/questions/71384143/unit-testing-dynamodb-sdk-in-go,"['amazon-web-services', 'go', 'testing']",700,False,1,1
Ktor - Unit testing is throwing 404,"<p>I have a simple program in Ktor. It runs perfectly, but when I run the unit testing class it only throws this error: &quot;expected:&lt;200 OK&gt; but was:&lt;404 Not Found&gt;&quot;</p>
<p>This is my unit test code:</p>
<pre><code>class ApplicationTest {
@Test
fun testRoot() = testApplication {
    val response = client.get(&quot;/&quot;)
    assertEquals(HttpStatusCode.OK, response.status)
}

@Test
fun testStart() = testApplication {
    val response = client.post(&quot;/start&quot;)
    assertEquals(HttpStatusCode.OK, response.status)
}
}
</code></pre>
<p>This is my Application.kt:</p>
<pre><code>const val enableHTTPS = false
const val portHTTP = 80
const val portHTTPS = 7001


lateinit var environment: ApplicationEngineEnvironment
fun main() {
    initEnvironment()

    embeddedServer(Netty, environment = environment).start(wait = true)
}

</code></pre>
<p>My routing file is:</p>
<pre><code>fun Application.configureRouting() {
    routing {
        get {
            call.respond(ApiDetails())
        }

        post(&quot;/start&quot;) {
            call.response.status(HttpStatusCode.OK)
        }

        post(&quot;/move&quot;) {
            val gameDetails: GameDetails = call.receive()
            val move = BasicStrategy().move(gameDetails, application)

            call.respond(move)
        }

        post(&quot;/end&quot;) {
        }
    }
}

</code></pre>
",https://stackoverflow.com/questions/72317906/ktor-unit-testing-is-throwing-404,"['unit-testing', 'kotlin', 'junit', 'httprequest', 'ktor']",727,True,1,1
Unit testing void function in Swift,"<p>I am new to unit testing. I am using MVVM in my project. I also use RxSwift to pass data or communicate between view and ViewModel. I don't understand how I can write unit tests in my case. Any suggestions are appreciable. I really appreciate any help you can provide.</p>
<pre><code>class MovieListViewModel: ViewModel {
       private let moviesSubject: PublishSubject&lt;[Movie]&gt; = PublishSubject()
    private let errorSubject: PublishSubject&lt;Error&gt; = PublishSubject()
    

    public var movies: Observable&lt;[Movie]&gt; {
        return moviesSubject.asObservable()
    }
    
    public var errors: Observable&lt;Error&gt; {
        return errorSubject.asObservable()
    }
    
    init(httpMovieService: MovieApiService, cachedMovieService: LocalMovieService) {
        self.httpMovieService = httpMovieService
        self.cachedMovieService = cachedMovieService
    }
    
    func searchMovies(keyword: String, page: Int, type: String) {

        self.httpMovieService
            .searchMovies(keyword: keyword, page: page, type: type)
            .subscribe(onSuccess: { [weak self] movies in
                self?.moviesSubject.onNext(movies)
            }, onFailure: { [weak self] error in
                self?.errorSubject.onNext(error)
            }).disposed(by: disposeBag)
    }
</code></pre>
<p>Note: <code>httpMovieService.searchMovies()</code> provide a Single type object</p>
<p>Here is my MockService ..</p>
<pre><code>class MockMovieApiService: MovieApiService {
    func searchMovies(keyword: String, page: Int, type: String) -&gt; Single&lt;[Movie]&gt; {
        let posterUrl = &quot;https://m.media-amazon.com/images/M/MV5BOGE4NzU1YTAtNzA3Mi00ZTA2LTg2YmYtMDJmMThiMjlkYjg2XkEyXkFqcGdeQXVyNTgzMDMzMTg@._V1_SX300.jpg&quot;
        let movie = Movie(title: &quot;Title&quot;,
                          year: &quot;2022&quot;,
                          imdbID: &quot;tt0800369&quot;,
                          type: &quot;movie&quot;,
                          poster: posterUrl)
        let movie2 = Movie(title: &quot;Title2&quot;,
                          year: &quot;2022&quot;,
                          imdbID: &quot;tt0800368&quot;,
                          type: &quot;movie&quot;,
                          poster: posterUrl)

        return Single.just([movie, movie2])
    }
    
    func getMovieDetails(imdbId: String) -&gt; Single&lt;MovieDetails&gt; {
        let posterUrl = &quot;https://m.media-amazon.com/images/M/MV5BOGE4NzU1YTAtNzA3Mi00ZTA2LTg2YmYtMDJmMThiMjlkYjg2XkEyXkFqcGdeQXVyNTgzMDMzMTg@._V1_SX300.jpg&quot;
        let movieDetails = MovieDetails(title: &quot;Thor&quot;, year: &quot;2022&quot;, rated: &quot;PG-13&quot;, released: &quot;Nov, 2022&quot;, runtime: &quot;134 min&quot;, genre: &quot;Horror, Comedy&quot;, director: &quot;Director&quot;, writer: &quot;Writer&quot;, actors: &quot;salman khan&quot;, plot: &quot;When thor sleeps..&quot;, language: &quot;English&quot;, country: &quot;Germany&quot;, awards: &quot;Oscar&quot;, poster: posterUrl, ratings: [], metascore: &quot;5&quot;, imdbRating: &quot;4.5&quot;, imdbVotes: &quot;566&quot;, imdbID: &quot;tt1981115&quot;, type: &quot;type&quot;, dvd: &quot;dvd&quot;, boxOffice: &quot;box&quot;, production: &quot;prod&quot;, website: &quot;n/a&quot;, response: &quot;True&quot;)
        return Single.just(movieDetails)
    }
    
    
}
</code></pre>
",https://stackoverflow.com/questions/74920108/unit-testing-void-function-in-swift,"['swift', 'unit-testing', 'mvvm', 'rx-swift']",331,True,1,2
Unit testing internal function in react,"<p>I want to snapshot testing (jest) just this chuck of logic of my react component. The problem is <code>handle1</code> and <code>handle2</code> aren't (of course) pure functions, they depend on other functions in <code>View</code> component, therefore I can't move the 2 lines (#4-5) in a utility function to <code>export</code>. What could be the best approach to this?</p>
<pre><code>1    export default function View() {
2      return (
3        ...
4        {CASE1 || CASE2 &amp;&amp; (&lt;SidebarButton onClick={handle1}&gt;one&lt;/SidebarButton&gt;)}
5        {CASE2 &amp;&amp; (&lt;SidebarButton onClick={handle2}&gt;two&lt;/SidebarButton&gt;)}
6        ...
7       )
8    }
</code></pre>
",https://stackoverflow.com/questions/74704536/unit-testing-internal-function-in-react,"['reactjs', 'jestjs']",31,False,1,0
AWS Amplify Cognito Angular Unit testing,"<p>I am new to unit testing and just decided to add test coverage for my existing app. I am struggling in writing the unit test cases for the given service .
I have created a AWS service file .</p>
<pre><code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Router } from '@angular/router';
import { Auth } from 'aws-amplify';
import { IUser } from '../../models/userModel';
@Injectable({
  providedIn: 'root'
})
export class AwsAmplifyAuthService {
  private authenticationSubject: BehaviorSubject&lt;any&gt;;
  constructor(private router: Router) {
    this.authenticationSubject = new BehaviorSubject&lt;boolean&gt;(false);
  }

  // SignUp
  public signUp(user: IUser): Promise&lt;any&gt; {
    return Auth.signUp({
      username: user.name,
      password: user.password,
      attributes: {
        email: user.email,
        name:user.name
      }
    });
   }

  // Confirm Code
  public confirmSignUp(user: IUser): Promise&lt;any&gt; {
    return Auth.confirmSignUp(user.name, user.code);
  }

  // SignIn
  public signIn(user: IUser): Promise&lt;any&gt; {
    return Auth.signIn(user.name, user.password)
      .then((r) =&gt; {
        console.log('signIn response', r);
        this.authenticationSubject.next(true);
        if (user) {
          if (r.challengeName === 'NEW_PASSWORD_REQUIRED') {
            this.router.navigateByUrl('/forgotpass');
          } else {
            this.router.navigateByUrl('/home');
          }
        }
      });
  }
</code></pre>
<p>and created a interface model</p>
<pre><code>export interface IUser {
    email: string;
    password: string;
    code: string;
    name: string;
}
</code></pre>
<p>I have tired the mocking the service in the .spec.</p>
<pre><code>    beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      providers: [
        {
          provide: Auth,
          useValue: { currentUserInfo: () =&gt; Promise.resolve('hello') },
        },
      ]
    })
      .compileComponents();
    service = TestBed.inject(AwsAmplifyAuthService);
  });


  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });
  it('#signIn should return expected data', async (done: any) =&gt; {
    await service.signIn(expectedData).then(data =&gt; {
      expect(data).toEqual(expectedData);
      done();
    });
  });
</code></pre>
<p>I am not able to pass the test case. Any guidance on the same would be appreciated.</p>
",https://stackoverflow.com/questions/72221295/aws-amplify-cognito-angular-unit-testing,"['angular', 'unit-testing']",336,False,1,2
unit testing in springboot - best approach,"<p>I'm trying to figure out what is the best approch to unittesting in SpringBoot app. Before last friday i thought that best approach is to test:</p>
<ul>
<li>controllers with mockmvc and mocked services</li>
<li>services with mocked repositories</li>
<li>repositories with mocked db</li>
<li>using <code>SpringBootTest</code> mainly for integration tests.</li>
</ul>
<p>But then i watched this -<a href=""https://www.youtube.com/watch?v=EZ05e7EMOLM"" rel=""nofollow noreferrer"">Ian Cooper - TDD, Where Did It All Go Wrong</a> and I've realized that my testswas implementation tests, and I should only mock db, filesystem, other systems, not my application.</p>
<p>And I'am wondering how should I be doing this? Because when I will be creating all objects myself it will still be &quot;testing implementation&quot;, so I can use <code>SpringBootTest</code> with <code>MockBean</code> but this would be extremly slow.</p>
<p>Can someone clever than me could share his experience or thougths on this?</p>
",https://stackoverflow.com/questions/70928972/unit-testing-in-springboot-best-approach,"['spring-boot', 'unit-testing', 'tdd']",192,False,1,2
Unit testing for Exception in flutter,"<p>i'm trying to pass my unit test in flutter. i'm getting my expected value and actual value still my test got failed.</p>
<p><strong>This is my Method in BaseApi class.</strong></p>
<p><em>Exception getNetErrorException(String url) =&gt; HttpException(url);</em></p>
<p><strong>and this is my test :</strong></p>
<pre><code>group(&quot;getNetErrorException&quot;, () {
  test(&quot;Should throw a HttpException when there is an error&quot;, () {
    BaseApi api = BaseApi();
    expect(api.getNetErrorException(&quot;&quot;), HttpException(&quot;&quot;));
  });
});
</code></pre>
",https://stackoverflow.com/questions/71294460/unit-testing-for-exception-in-flutter,"['flutter', 'dart']",897,True,1,1
Unit Testing by mocking S3 bucket,"<p>I am new to unit testing and I require to perform some simple unit tests for an object storage class.</p>
<p>I have a class named OSBucket as follows:</p>
<pre><code>def __initBucket(self):        
        
        ecs_session = boto3.Session(
        aws_access_key_id=&quot;OSKEY&quot;,
        aws_secret_access_key=&quot;SECRETKEY&quot;
        ) 

        OS_resource = ecs_session.resource('s3', verify=cert, endpoint_url=endpoint)
        self.mybucket = OS_resource.Bucket(OS_BUCKET)
                
        
def get_mybucket(self): 
        
   return self.mybucket


def download_file(self, fileName,filepath):
        
   self.mybucket.download_file(fileName, filepath)

def upload_file(self, filepath,dest_file_name):   
   self.mybucket.upload_file(filepath, '%s%s' % (&quot;/&quot;,dest_file_name))


</code></pre>
<p>The method __initBucket is called in the constructor of the class.</p>
<p>How could I start creating a unit test class to test, for example, the download_file method?</p>
<p><strong>UPDATE 1</strong></p>
<pre><code>        moto_fake.start()
        conn = boto3.resource('s3', aws_access_key_id=&quot;fake_id&quot;,
        aws_secret_access_key=&quot;fake_secret&quot;)
        conn.create_bucket(Bucket=&quot;OS_BUCKET&quot;)    

        os_bucket = OSBucket.OSBucket(thisRun)

        sourcefile = &quot;testingMoto.txt&quot;   
        filePath = os.path.join(&quot;/&quot;, sourcefile)   
        os_bucket.upload_file(filePath, sourcefile)  
</code></pre>
<p>which executes the <code>moto_fake.start()</code> before creating the <code>os_bucket</code> object does not work for me.</p>
<p><strong>UPDATE 2</strong></p>
<p>Using patch.object to change the endpoint variable to None, makes the test pass</p>
",https://stackoverflow.com/questions/71765091/unit-testing-by-mocking-s3-bucket,"['python', 'unit-testing', 'amazon-s3', 'mocking', 'bucket']",14697,True,1,1
Pytest Unit Testing Sending Email SMTP,"<p>I want to test the following function in pytest without actually creating an SMTP server and sending email to the specified address.</p>
<pre><code>def send_email_investor_owner_occupier(self,user_type,smtp_server):
        message=MIMEMultipart()
        message['From']=self.email_address
        message['To']=self.email_address
        suburb_set={suburb for location in user_type.locations for suburb in location.keys()}
        suburb_string=','.join(suburb_set)
        message['Subject']=f'Investment Properties in {suburb_string} last updated {user_type.date_posted}'
        body= f'{user_type.properties} with {user_type.bedrooms} bedrooms, {user_type.bathrooms} bathrooms,{user_type.car_spaces} car spaces, priced between ${user_type.min_price} and ${user_type.max_price} in {suburb_string} last updated {user_type.date_posted}. Key metrics calculated for {user_type.loan_type} {user_type.variable_loan_type if user_type.variable_loan_type!=None else &quot;&quot;} loan with {user_type.lvr/100} lvr for {user_type.loan_term} years with {user_type.mortgage_interest}% interest.'
        message.attach(MIMEText(body,&quot;plain&quot;))
        message.attach('property_data.csv',self.property_data_io.getvalue(),'text/csv')
        with smtplib.SMTP(smtp_server,self.port) as server:
            server.starttls()
            server.login(self.email_address,self.password)
            server.sendmail(self.email_address,self.email_address,message.as_string())
            server.quit()
</code></pre>
<p>I am aware that SMTP server can be mocked using the python unittest module as per <a href=""https://jingwen-z.github.io/how-to-send-emails-with-python/"" rel=""nofollow noreferrer"">https://jingwen-z.github.io/how-to-send-emails-with-python/</a> but I cannot figure it out using pytest. I would like to be able to do this in pytest if possible given all my other tests use the module.</p>
",https://stackoverflow.com/questions/73496790/pytest-unit-testing-sending-email-smtp,"['python', 'unit-testing', 'email', 'smtp', 'pytest']",1012,False,0,2
Mock Spring Security unit testing WebTestClient,"<p>I am trying to write unit test cases for Mycontroller using <strong>WebTestClient</strong> in my web-flux Spring boot application.</p>
<p>It is always returning <strong>401</strong> while try to execute my unit test case. I already go through some old answers of stackoverflow but no luck.</p>
<p>Below are the approaches that I followed till now:</p>
<ol>
<li><p>Disable security using @WebFluxTest(controllers = MyController.class,excludeAutoConfiguration = {ReactiveSecurityAutoConfiguration.class}))</p>
<p>Above one disabled security perfecty but the issue is I am getting <strong>java.security.Principal</strong> <em><strong>null</strong></em> in MyController and controller throwing null pointer exception while trying to fetch value from Principal.</p>
</li>
<li><p>Add default bearer token in my webTestClient test. In this case I am getting 401.</p>
</li>
<li><p>Add valid bearer token in WebTestClient test that we are using to hit APIs normally. It this case as well I am getting 401[unauthorized] error.</p>
</li>
<li><p>Tried to mock Principal object but didn't got success. below is the code that I tried:</p>
<pre><code>Authentication authentication = Mockito.mock(Authentication.class);
SecurityContext securityContext = Mockito.mock(SecurityContext.class);
Mockito.when(securityContext.getAuthentication()).thenReturn(authentication);
SecurityContextHolder.setContext(securityContext);
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL);
SecurityContextHolder.getContext().setAuthentication(authentication);
Collection&lt;GrantedAuthority&gt; authorities = new ArrayList&lt;&gt;();
UsernamePasswordAuthenticationToken principal1 = new UsernamePasswordAuthenticationToken(&quot;testUser&quot;, &quot;testPass&quot;);

Mockito.when(authentication.getPrincipal()).thenReturn(principal1);
</code></pre>
</li>
</ol>
<p>Below is MyController and MyControllerTest class for your reference:</p>
<ol>
<li><p>MyColroller.java</p>
<pre><code>@GetMapping(produces = APPLICATION_JSON_VALUE, value = &quot;/myController/{transactionId}&quot;)
@Operation(
    security = @SecurityRequirement(name = OAUTH2),
    responses = {
            @ApiResponse(responseCode = &quot;200&quot;,
                    content = @Content(mediaType = APPLICATION_JSON_VALUE,
                            schema = @Schema(implementation = TransactionDocumentResponse.class)))
    })
public ResponseEntity&lt;TransactionDocumentResponse&gt; get(
    @PathVariable(value = &quot;transactionId&quot;) String transactionId, Principal principal) {

    Map&lt;String, String&gt; userInfo = (Map) ((Authentication) principal).getDetails();
    utility.checkForMissingToken(userInfo, xTestHeader);
    return service.get(transactionId, userInfo);
}
</code></pre>
</li>
<li><p>MyControllerTest.java</p>
<pre><code>@RunWith(SpringRunner.class)
@WebFluxTest(controllers = {MyController.class})
@AutoConfigureWebTestClient
@TestPropertySource(
        properties = {
                &quot;default-jwt-token = my default jwt token&quot;,
        }
)
public class MyControllerTests {

    private static final String testTransactionId = &quot;abc_def&quot;;
    private static final BigInteger testTransactionIdBigInteger = BigInteger.valueOf(123);

    @Value(&quot;${default-jwt-token}&quot;)
    private String jwtToken;

    @MockBean
    MyServiceImpl service;

    @MockBean
    Utility utility;

    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void test_success() {

        TransactionDocumentResponse transactionDocumentResponse = new TransactionDocumentResponse();
        transactionDocumentResponse.setTransactionId(testTransactionIdBigInteger);
        ResponseEntity&lt;TransactionDocumentResponse&gt; response = ResponseEntity.of(Optional.of(transactionDocumentResponse));

        Mockito.doNothing().when(utility).checkForMissingToken(anyMap(), anyString());
        when(service.getRevolvingTransactions(anyString(), anyMap())).thenAnswer(createAnswer(response));

        WebTestClient.BodySpec&lt;JSONObject, ?&gt; stringBodySpec = webTestClient
                .method(HttpMethod.GET)
                .uri(&quot;/myController/{transactionId}&quot;, testTransactionId)
                .headers(h -&gt; {
                    h.setBearerAuth(jwtToken);
                })
        .exchange()
        .expectBody(JSONObject.class);

        assertEquals(123, stringBodySpec.returnResult().getResponseBody().get(&quot;transactionId&quot;));
    }
}
</code></pre>
</li>
</ol>
<p>Basically I need some mechanism to mock Spring security so that 401 error gone and I got some value in my Principal object.</p>
<p>Also I already tried older solutions so please don't mark it duplicate :).</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/72811094/mock-spring-security-unit-testing-webtestclient,"['java', 'unit-testing', 'spring-security', 'spring-webflux', 'webtestclient']",1529,False,0,2
Unit Testing in Asp.Net MVC project,"<p>I am a newbie to write a unit testing please provide the guidance on what is the unit test for  the following simple structure which may be passed in TestResult in VS 2019???</p>
<pre><code>public ActionResult About()
{
    ViewBag.Message = &quot;Your application description page.&quot;;
    return View();
}
</code></pre>
",https://stackoverflow.com/questions/72839248/unit-testing-in-asp-net-mvc-project,"['c#', 'unit-testing', 'asp.net-core-mvc']",43,True,0,1
Pytest Unit Testing Sending Email SMTP,"<p>I want to test the following function in pytest without actually creating an SMTP server and sending email to the specified address.</p>
<pre><code>def send_email_investor_owner_occupier(self,user_type,smtp_server):
        message=MIMEMultipart()
        message['From']=self.email_address
        message['To']=self.email_address
        suburb_set={suburb for location in user_type.locations for suburb in location.keys()}
        suburb_string=','.join(suburb_set)
        message['Subject']=f'Investment Properties in {suburb_string} last updated {user_type.date_posted}'
        body= f'{user_type.properties} with {user_type.bedrooms} bedrooms, {user_type.bathrooms} bathrooms,{user_type.car_spaces} car spaces, priced between ${user_type.min_price} and ${user_type.max_price} in {suburb_string} last updated {user_type.date_posted}. Key metrics calculated for {user_type.loan_type} {user_type.variable_loan_type if user_type.variable_loan_type!=None else &quot;&quot;} loan with {user_type.lvr/100} lvr for {user_type.loan_term} years with {user_type.mortgage_interest}% interest.'
        message.attach(MIMEText(body,&quot;plain&quot;))
        message.attach('property_data.csv',self.property_data_io.getvalue(),'text/csv')
        with smtplib.SMTP(smtp_server,self.port) as server:
            server.starttls()
            server.login(self.email_address,self.password)
            server.sendmail(self.email_address,self.email_address,message.as_string())
            server.quit()
</code></pre>
<p>I am aware that SMTP server can be mocked using the python unittest module as per <a href=""https://jingwen-z.github.io/how-to-send-emails-with-python/"" rel=""nofollow noreferrer"">https://jingwen-z.github.io/how-to-send-emails-with-python/</a> but I cannot figure it out using pytest. I would like to be able to do this in pytest if possible given all my other tests use the module.</p>
",https://stackoverflow.com/questions/73496790/pytest-unit-testing-sending-email-smtp,"['python', 'unit-testing', 'email', 'smtp', 'pytest']",1012,False,0,2
answers Quarkus unit-testing and properties,"<p>In Qaurkus Project while I am running with an in-memory Profile so runs OK . so I want to run my Junit5 with an in-memory profile, how so i can do this , if anyone has suggestion about this.</p>
",https://stackoverflow.com/questions/73455158/answers-quarkus-unit-testing-and-properties,['quarkus'],64,False,0,0
Unit testing a Facade design pattern,"<p>This is a simple python code for Facade design pattern. The code itself doesn't have any problems but I'm new to unit testing and I don't know how to do it. Also, this is not my code and I'm just trying to practice unit testing.</p>
<pre><code>class Addition:
    def __init__(self, field1: int, field2: int):
        self.field1 = field1
        self.field2 = field2

    def get_result(self):
        return self.field1 + self.field2


class Multiplication:
    def __init__(self, field1: int, field2: int):
        self.field1 = field1
        self.field2 = field2

    def get_result(self):
        return self.field1 * self.field2


class Subtraction:
    def __init__(self, field1: int, field2: int):
        self.field1 = field1
        self.field2 = field2

    def get_result(self):
        return self.field1 - self.field2


class Facade:
    @staticmethod
    def make_addition(*args) -&gt; Addition:
        return Addition(*args)

    @staticmethod
    def make_multiplication(*args) -&gt; Multiplication:
        return Multiplication(*args)

    @staticmethod
    def make_subtraction(*args) -&gt; Subtraction:
        return Subtraction(*args)


if __name__ == &quot;__main__&quot;:
    addition_obj = Facade.make_addition(5, 5)
    multiplication_obj = Facade.make_multiplication(5, 2)
    subtraction_obj = Facade.make_subtraction(15, 5)

    print(addition_obj.get_result())
    print(multiplication_obj.get_result())
    print(subtraction_obj.get_result())
</code></pre>
<p>I tried looking it up in the internet but I'm too novice to understand at all.</p>
",https://stackoverflow.com/questions/74223369/unit-testing-a-facade-design-pattern,"['python', 'unit-testing', 'facade']",55,False,0,0
Unit testing unknown fields in grpc,"<p>I am trying to write unit tests for code generated by grpc(autogen code). how can we write tests for unknown fields generated in autogen.</p>
<p>below is the code for the request message.</p>
<pre><code>public HelloRequest(HelloRequest other) : this()
{
    name_ = other.name_;
    _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
</code></pre>
<p>I wrote a normal unit test which covers fields in request, but i am not sure how to cover unknown fields for code coverage purpose.</p>
",https://stackoverflow.com/questions/71602356/unit-testing-unknown-fields-in-grpc,"['c#', 'unit-testing', 'grpc', 'proto']",133,False,0,0
Unit Testing Controller ActionResult&lt;T&gt; Response,"<p>I'm trying to unit test an ASP.NET 5 controller.
The controller is returning a value wrapped in an ActionResult.</p>
<p>The ActionResult seems to have 2 properties - Result and Value. The Value is null, but my service response containing the data is inside the Result. It is not as simple as accessing it by actionResult.Result.Value.Data.Id.</p>
<p>Other posts suggest using  ((ObjectResult)actual.Result).Value   which seems to work. However I can't access the ServiceResponse's Data inside this value.</p>
<p>((ObjectResult)actual.Result).Value.Data.Id does not work.</p>
<p>I'd appreciate any help, I'm going round in circles.</p>
<p><a href=""https://i.stack.imgur.com/PnRi1.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/PnRi1.png"" alt=""enter image description here"" /></a></p>
<p>Here's a pic of my debugger, the Data is in the Value but it can't be accessed as above.</p>
<p><a href=""https://i.stack.imgur.com/Cf2cq.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Cf2cq.png"" alt=""enter image description here"" /></a></p>
<p>My Controller:</p>
<pre><code>[HttpGet]
    [Route(&quot;GetUser/{id}&quot;)]
    public async Task&lt;ActionResult&lt;ServiceResponse&lt;GetUserDto&gt;&gt;&gt; GetUser(int id)
    {
        try
        {
            // Validation
            IValidate validate = new Validate();
            int passValidation = validate.numberValidation(id.ToString());

            // 0 is a pass, 1 is a fail.
            if (passValidation == 0)
            {
                return Ok(await _userService.GetUser(id));           // 200 OK
            }

            // Send a message to tell user of the error
            var serviceResponse = new ServiceResponse&lt;GetUserDto&gt;();
            serviceResponse.Data = null;
            serviceResponse.Success = false;
            serviceResponse.Message = &quot;Validation Failed.&quot;;

            _logger.LogInformation(&quot;Error - Validation Failed in UserController.GetUser - ID: {0} &quot;, id.ToString());

            return Ok(serviceResponse);
        }
        catch(Exception ex)
        {
            _logger.LogError(&quot;Error - Exception in UserController.GetUser - {0} &quot;, ex);
            return NotFound();      // 404
        }
    }
</code></pre>
<p>And this is my unit test:</p>
<pre><code>        [Fact]
    public async void GetUser_Works()
    {
        using (var mock = AutoMock.GetLoose())
        {
        // Arrange
            int userId = 1;

            var expected = new ServiceResponse&lt;GetUserDto&gt;
            {
               Data = new GetUserDto {
                    Id = userId,
                    UserName = &quot;mockuser1&quot;,
                    Email = &quot;mockuser1@moq.com&quot;,
                    FirstName = &quot;barry&quot;,
                    LastName = &quot;smith&quot;,
                    Dept = &quot;management&quot;,
                    Salary = 180000
                },
                Success = true,
                Message = &quot;Success&quot;
            };

            // Mock the Controller call to UserService
            _userService.Setup(x =&gt; x.GetUser(userId))
                .ReturnsAsync(expected);


        // Act
            ActionResult&lt;ServiceResponse&lt;GetUserDto&gt;&gt; actual = await _userController.GetUser(userId);


            // Assert
            // Controller returns an OK ActionResult, we need to look inside its &quot;ActionResult.Result.Value&quot; to find the ServiceResponse.
            Assert.Equal(expected.Data.Id, ((ObjectResult)actual.Result).Value);
            Assert.Equal(expected.Data.UserName, ((ObjectResult)actual.Result).Value);
        }
    }
</code></pre>
",https://stackoverflow.com/questions/73037147/unit-testing-controller-actionresultt-response,"['unit-testing', 'asp.net-core', 'moq', 'xunit']",665,True,0,1
Unit testing for spark-bigquery-connector,"<p>I am trying to write unit test case for my spark bigquery implementation.
Say, If I want to test this below piece of code:</p>
<pre><code>val wordsDF = (spark.read.format(&quot;bigquery&quot;)
              .option(&quot;table&quot;,&quot;bigquery-public-data:samples.shakespeare&quot;)
              .load()
              .cache())
</code></pre>
<p>And do some assertion on wordsDF</p>
<p>I am trying to think on the lines of:</p>
<ul>
<li>Embedded kafka for kafka</li>
<li>Embedded cassandra for cassandra</li>
</ul>
<p>Do we have any such library or alternative that can be used to write spark bigquery unit test</p>
",https://stackoverflow.com/questions/72950923/unit-testing-for-spark-bigquery-connector,"['scala', 'apache-spark', 'google-bigquery', 'spark-streaming', 'spark-bigquery-connector']",287,False,0,0
Unit testing MatSelectChange with if else,"<p>I am writing unit tests and I have this simple method that does something depending on the value of matSelectChange.
How can I test this so the code coverage is 100%?</p>
<pre><code> selectionChanged(matSelectChange: MatSelectChange): void {
            if (matSelectChange.value === '1') {
                this.service.doSomething();
            } else if (matSelectChange.value === '2') {
                this.service.doSomethingElse();
            }
        }
</code></pre>
",https://stackoverflow.com/questions/70782564/unit-testing-matselectchange-with-if-else,"['angular', 'unit-testing', 'karma-jasmine']",261,True,0,1
near-sdk-rs - unit testing promises,"<p>What is the right (intended) way to test promises and their results in near-sdk-rs? Please, point me in the right direction (docs/examples/...).</p>
<p>Let's take the simplest example (from here <a href=""https://www.near-sdk.io/promises/token-tx"" rel=""nofollow noreferrer"">https://www.near-sdk.io/promises/token-tx</a>): <code>Promise::new(account_id).transfer(amount)</code>.</p>
<p>How to unit test that the right account received the right amount?</p>
",https://stackoverflow.com/questions/72289846/near-sdk-rs-unit-testing-promises,"['unit-testing', 'nearprotocol', 'near-sdk-rs']",78,False,0,1
Android Unit testing Mockk argument capture,"<pre><code>interface SomeAPIHandler {
    fun getUserContent(apiInterface: APIInterface&lt;UserModel&gt;)
}

interface APIInterface&lt;T&gt; {
    fun onSuccess(responseModel: T)
    fun onError(errorModel: ErrorModel)
}
</code></pre>
<p>In my presenter class, it is called like:</p>
<pre><code>apiClient.getUserContent(object : APIInterface&lt;UserModel&gt; {
            override fun onSuccess(responseModel: UserModel) = handleSuccess(responseModel)
            override fun onError(errorModel: ErrorModel) = handleGetUserModelError()
})
</code></pre>
<p>I am getting code coverage issue from SonarQube for this two lines in presentor class:</p>
<pre><code>override fun onSuccess(responseModel: UserModel) = handleSuccess(responseModel)
override fun onError(errorModel: ErrorModel) = handleGetUserModelError()
</code></pre>
<p>I am using mockk.io and I think i need to use <code>slot</code> for this. Can someone help how to cover this ?</p>
",https://stackoverflow.com/questions/73076418/android-unit-testing-mockk-argument-capture,"['android', 'unit-testing', 'kotlin', 'mockk']",57,False,0,0
Approaches for unit testing DB components,"<p>I have a component that provides a CRUD interface to store and manage data internally in a database. For unit testing this component, I have several options:</p>
<ol>
<li>Test each method individually using a mock DB client and check whether the correct methods were called with the correct arguments,</li>
<li>Test each method individually using a functional DB client and check whether the internal state of the DB is as expected,</li>
<li>Test methods together, e.g.,
<pre><code>put(&quot;a&quot;, &quot;1&quot;);
result = get(&quot;a&quot;);
assert_equals(&quot;1&quot;, result);
</code></pre>
</li>
</ol>
<p>I personally tend to use method 3 because 1 and 2 are very fragile towards changes to the underlying data management. But what are the pros and cons of each method? Which method is usually used for such code?</p>
",https://stackoverflow.com/questions/71641581/approaches-for-unit-testing-db-components,['unit-testing'],20,True,-1,1
Unit testing class without using @InjectMocks,"<p>I am trying to add unit tests for an class and I need to mock (and inject) a dependency into a class without making changes to the class under test(as that will cause lots of changes in other parts of the application which we want to avoid).</p>
<p>I have created the class manually (without using <code>@InjectMocks</code>) as I need to mock <code>AppConfig</code> in the test.</p>
<p>I am getting a null pointer exception on the line where the system expects the dependency to be injected.</p>
<p>What am I missing and what could I do to fix this issue?</p>
<p><strong>PageModelBuilder.java:</strong></p>
<pre><code>public class PageModelBuilder {
    private final String baseUrl = AppConfig.findString(&quot;baseUrl&quot;);
    @Inject
    private StringTranslator stringTranslator;
    public PageModel buildFrom(final @NonNull ProductData productData) {
        PageModel.PageModelBuilder builder = new PageModel.PageModelBuilder();
        productData.getProductTitle().ifPresent(productTitle -&gt; {
            builder .pageDescription(String.format(stringTranslator.getStringById(&quot;page_description_format&quot;),
                            productTitle.getDisplayString())); //&lt;= stringTranslator is null here
        });
        productData.getProductLink()
                .ifPresent(productLink -&gt; builder.canonicalURL(baseUrl + productLink));
        return builder.build();
    }
}
</code></pre>
<p><strong>PageModelBuilderTest.java:</strong></p>
<pre><code>     @RunWith(MockitoJUnitRunner.Silent.class)
    public class PageModelBuilderTest {
        @Mock
        private StringTranslator stringTranslator;
        private PageModelBuilder pageModelBuilder;
        @Before
        public void setup() {
            if (!AppConfig.isInitialized()) {
                AppConfig.initialize(&quot;WebApp&quot;, null, new String[] {
                        &quot;--root=.&quot;, &quot;--domain=test&quot;});
            }
        }
        @After
        public void after() {
            if (AppConfig.isInitialized()) {
                AppConfig.destroy();
            }
        }
        @Test
        public void givenProductDataWithProductLink_whenBuildPageModel_thenPageModelHasCanonicalURL() {
            AppConfig.insertString(&quot;baseUrl&quot;, &quot;https://www.google.com&quot;);
when(stringTranslator.getStringById(&quot;page_description_format&quot;)).thenReturn(&quot;sample description&quot;);
            pageModelBuilder = new PageModelBuilder();
            ProductData productData = ProductTestData.getProductDataBuilder()
                    .title(&quot;TestMed&quot;)
                    .productLink(&quot;/PRODUCT-DESCRIPTION/dp/asin&quot;)
                    .build();
            PageModel pageModel = pageModelBuilder.buildFrom(productData);
            assertEquals(&quot;https://www.google.com/PRODUCT-DESCRIPTION/dp/asin&quot;, pageModel.getCanonicalURL());
        }
    }
</code></pre>
",https://stackoverflow.com/questions/74696622/unit-testing-class-without-using-injectmocks,"['java', 'spring-boot', 'unit-testing', 'mocking', 'mockito']",106,False,0,1
Angular Unit Testing For Subscribe methods,"<p>`I want to unit test my subscribe functions. Please help me out.
ts</p>
<pre><code>export class EmployeeFormDetailsComponent implements OnInit {
  employeeData : any;
  id !: number;`your text`
  constructor(private api: ApiService) { }

  ngOnInit(): void {
    this.getEmployeeDetails();
  }
getEmployeeDetails(){
  this.api.getEmployee()
  .subscribe(res =&gt;{
   this.employeeData= res;
   console.log(res);
  })
}
deleteEmployee(row : any){
  this.api.deleteEmployee(row.id)
  .subscribe(res=&gt;{
    this.getEmployeeDetails();
  )
}
postEmployeeDetails() {
    this.employeeModelObj.firstName = this.registrationForm.value.firstName;
    this.employeeModelObj.lastName = this.registrationForm.value.lastName;
    this.employeeModelObj.startDate = this.registrationForm.value.startDate;
    this.employeeModelObj.endDate = this.registrationForm.value.endDate;
    this.employeeModelObj.experience = this.registrationForm.value.experience;
    this.api.postEmployee(this.employeeModelObj)
      .subscribe(res =&gt; {
        console.log(res);
        this.router.navigate(['employeeFormDetails'])
      })
  }
  getEmployeeDetails(Experience: string) {
     this.filteredList = this.api.getemployeeByExperience(Experience)
    console.log(this.filteredList); 
  }
</code></pre>
<p>}
````your text`</p>
<p>I have written a unit test case for my get method and it has worked.. But I want to unit test for my delete method, get by experience method and my post method.
spec.ts</p>
<pre><code> it('should call get method', ()=&gt;{
  const response: EmployeeModel[] =[];
  spyOn(service, 'getEmployee').and.returnValue(of(response))
  component.getEmployeeDetails();
  fixture.detectChanges();
  expect(component.employeeData).toEqual(response);
  });
</code></pre>
",https://stackoverflow.com/questions/74794571/angular-unit-testing-for-subscribe-methods,"['angular', 'unit-testing', 'karma-jasmine']",39,True,0,1
Unit testing using jUnit5 and mockito,"<p>Hi Im having troubles with my saveStudent method I can't seem to make the test work. What my saveStudent method do is when I add a student it automatically adds the fixed subjects from the database to the student. Can anyone explain to me what Im doing wrong in the testing and how to test this kind of method. Gladly appreciate it. Thank you for the answer!</p>
<p>Here is my TestService and my ServiceImplimentation</p>
<pre><code>@ExtendWith(MockitoExtension.class)
public class StudentServiceTest {

    @Mock
    private StudentRepository studentRepository;
    
    @Mock
    private SubjectRepository subjectRepository;
    

    @InjectMocks
    private StudentServiceImpl studentService;

    private Student student;
    
    private List&lt;Subject&gt; subject;


//  private List&lt;Subject&gt; subjectList;

    private Collection&lt;Remark&gt; remarks = new ArrayList&lt;&gt;();

    @BeforeEach
    public void setup() {

        student = new Student(1L, &quot;Martin&quot;, 6, remarks);
        subject = Arrays.asList(
                new Subject(1L, &quot;Math&quot;, remarks),
                new Subject(2L, &quot;English&quot;, remarks));
        

    }

    // JUnit test for saveStudent method
    @DisplayName(&quot;JUnit test for saveStudent method&quot;)
    @Test
    public void givenStudentObject_whenSaveStudent_thenReturnStudentObject() {
        
        given(subjectRepository.findAll()).willReturn(subject);
        
        System.out.println(subject);
        
        given(studentRepository.save(student)).willReturn(student);

        System.out.println(studentRepository);
        System.out.println(studentService);
        
        Student savedStudent = studentService.saveStudent(student);
        
        System.out.println(savedStudent);


        assertThat(savedStudent).isNotNull();

    }

    // JUnit test for getStudentList method
    @DisplayName(&quot;JUnit test for getStudentList method&quot;)
    @Test
    public void givenStudentsList_whenGetAllStudents_thenReturnStudentsList() {

        Student student1 = new Student(1L, &quot;Edmark&quot;, 4, remarks);

        given(studentRepository.findAll()).willReturn(Arrays.asList(student, student1));

        List&lt;Student&gt; studentList = studentService.findAll();

        assertThat(studentList).isNotNull();
        assertThat(studentList.size()).isEqualTo(2);

    }

    // JUnit test for getStudentById method
    @DisplayName(&quot;JUnit test for getStudentById method&quot;)
    @Test
    public void givenStudentId_whenGetStudentId_thenReturnStudentObject() {

        given(studentRepository.findById(1L)).willReturn(Optional.of(student));

        Student savedStudent = studentService.findById(student.getStudentId());

        assertThat(savedStudent).isNotNull();
    }

    // JUnit test for updateStudent method
    @DisplayName(&quot;JUnit test for updateStudent method&quot;)
    @Test
    public void givenStudentObject_whenUpdateStudent_thenReturnUpdatedStudent() {

        given(studentRepository.findById(1L)).willReturn(Optional.of(student));
        given(studentRepository.save(student)).willReturn(student);

        student.setStudentGrade(8);
        student.setStudentName(&quot;Mark&quot;);

        Student updatedStudent = studentService.updateStudent(1L, student);

        assertThat(updatedStudent.getStudentName()).isEqualTo(&quot;Mark&quot;);
        assertThat(updatedStudent.getStudentGrade()).isEqualTo(8);
    }

    @DisplayName(&quot;JUnit test for deleteStudent method&quot;)
    @Test
    public void givenStudentId_whenDeleteStudent_thenNothing() {

        long studentId = 1L;

        given(studentRepository.findById(studentId)).willReturn(Optional.of(student));

        BDDMockito.willDoNothing().given(studentRepository).deleteById(studentId);

        studentService.deleteStudent(studentId);

        verify(studentRepository, times(1)).deleteById(studentId);
    }

}


@Service
public class StudentServiceImpl implements StudentService {
    
    @Autowired
    private SubjectRepository subjectRepository;
    
    private StudentRepository studentRepository;

    public StudentServiceImpl(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @Override
    public Student saveStudent(Student student) {       
        Collection&lt;Remark&gt; remarkList = new ArrayList&lt;&gt;();
        List&lt;Subject&gt; subjects = subjectRepository.findAll();
        for (Subject subject : subjects) {
            Remark remark = new Remark();
            remark.setSubject(subject);
            remark.setStudent(student);
            remark.setGrade(0);
            remarkList.add(remark);
        }
        student.setRemarks(remarkList);
        
        return studentRepository.save(student);
    }

    @Override
    public List&lt;Student&gt; findAll() {

        return studentRepository.findAll();
    }

    @Override
    public Student findById(Long studentId) {

        Optional&lt;Student&gt; student = studentRepository.findById(studentId);

        if (!student.isPresent()) {
             throw new ResourceNotFoundException(&quot;Student not found with id : &quot; + studentId);
        }
        return studentRepository.findById(studentId).get();
    }


    @Override
    public Student updateStudent(@PathVariable(value = &quot;id&quot;) Long studentId, @RequestBody Student student) {
        
        Optional&lt;Student&gt; tempStudent = studentRepository.findById(studentId);
        if (!tempStudent.isPresent()) {
             throw new ResourceNotFoundException(&quot;Student not found with id : &quot; + studentId);
        }
        Student studentDetails = tempStudent.get();

        studentDetails.setStudentName(student.getStudentName());
        studentDetails.setStudentGrade(student.getStudentGrade());
        studentDetails.getRemarks().addAll(student.getRemarks());

        Student updatedStudent = studentRepository.save(studentDetails);

        return updatedStudent;

    }

    @Override
    public void deleteStudent(long studentId) {
        Optional&lt;Student&gt; student = studentRepository.findById(studentId);
        
        if (!student.isPresent()) {
             throw new ResourceNotFoundException(&quot;Student not found with id : &quot; + studentId +&quot; or already deleted&quot;);
        }
        studentRepository.deleteById(studentId);
        
    }

}
</code></pre>
",https://stackoverflow.com/questions/73570338/unit-testing-using-junit5-and-mockito,"['spring', 'rest', 'unit-testing', 'junit', 'mockito']",47,False,0,0
Enable jasmine/globals in unit testing,"<p>In my .eslintrc.json file(which inherits from a root .eslintrc.json file), I have this configuration</p>
<pre><code>&quot;extends&quot;: [&quot;&lt;root&gt;/.eslintrc&quot;],
&quot;ignorePatterns&quot;: [&quot;!**/*&quot;],
&quot;overrides&quot;: [
  {
    &quot;files&quot;: [&quot;*.ts&quot;, &quot;*.tsx&quot;, &quot;*.js&quot;, &quot;*.jsx&quot;],
    &quot;parserOptions&quot;: {
      &quot;project&quot;: [&quot;&lt;path&gt;/tsconfig.*?.json&quot;]
    },
    &quot;settings&quot;: {
      &quot;disable/plugins&quot;: [&quot;jest&quot;]
    }
  },
]
}
</code></pre>
<p>The root .eslintrc.json file has</p>
<pre><code>  &quot;plugins&quot;: [&quot;@nrwl/nx&quot;, &quot;jest&quot;, &quot;jasmine&quot;],
  &quot;extends&quot;: [&quot;plugin:jest/recommended&quot;, &quot;plugin:jasmine/recommended&quot;],
</code></pre>
<p>For my project I only need to use jasmine and not jest. While the test runs successfully, I get a lint error of
<code>error    Illegal usage of global `spyOn`, prefer `jest.spyOn`  jest/no-jasmine-globals</code></p>
<p>On adding <code> rules: {&quot;jest/no-jasmine-globals&quot;: &quot;off&quot;}</code> and <code> &quot;env&quot;: { &quot;jasmine-globals&quot;: true }</code> I get another lint error that says <code>jasmine-globals could not be identified</code></p>
<p>I need to suppress the jest plugins and allow jasmine alone. What are the modifications that I need to do?</p>
",https://stackoverflow.com/questions/73146100/enable-jasmine-globals-in-unit-testing,"['unit-testing', 'jestjs', 'jasmine']",153,False,0,0
Unit Testing Firebase Realtime Database Android,"<p>I am using Firebase Realtime database. I want to unit test my repository.
I am new to unit testing. I was doing normally like this:</p>
<pre><code> @Test
public void Insert(){
     DataRepository dataRepository = new DataRepository();
     int prevSize = dataRepository.getAllData().size();
}
</code></pre>
<p>.</p>
<pre><code> @Override
    public List&lt;UserData&gt; getAllData() {
        mDataRef = FirebaseDatabase.getInstance().getReference(&quot;UserData&quot;);

        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                //  List&lt;UserData&gt; userDataList = new ArrayList&lt;UserData&gt;();
                userDataList.clear();

                for (DataSnapshot noteSnapshot : snapshot.getChildren()) {
                    UserData userData = noteSnapshot.getValue(UserData.class);
                    // userDataList.add(userData);
                    userDataList.add(0, userData);
                }
                Log.d(&quot;SIZE OF USELIST&quot;, userDataList.size() + &quot;&quot;);

                ;

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Log.d(&quot;loadData:onCancelled&quot;, error.getMessage());

            }



        };

        mDataRef.addValueEventListener(valueEventListener);

        mDataEventListener = valueEventListener;

        return userDataList;
    }
</code></pre>
<p>But this was giving error at <strong>FirebaseDatabase.getInstance()</strong> saying it was not instantiate.
So what is the solution or there is other process to unit test my repository.</p>
<p>The error giving me is that:</p>
<pre><code>java.lang.ExceptionInInitializerError
    at com.google.firebase.FirebaseApp.&lt;clinit&gt;(FirebaseApp.java:97)
    at com.google.firebase.database.FirebaseDatabase.getInstance(FirebaseDatabase.java:56)
    at com.pialroni.mycardi.DataRepository.getAllData(DataRepository.java:97)
    at com.pialroni.mycardi.DataPresenterTest.Insert(DataPresenterTest.java:31)
    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.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.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 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.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$2.run(TestWorker.java:176)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
Caused by: java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
    at android.os.Looper.getMainLooper(Looper.java)
    at com.google.firebase.FirebaseApp$UiExecutor.&lt;clinit&gt;(FirebaseApp.java:696)
    ... 48 more
</code></pre>
",https://stackoverflow.com/questions/73005413/unit-testing-firebase-realtime-database-android,"['java', 'android', 'unit-testing', 'firebase-realtime-database']",63,False,0,0
Service layer unit testing spring boot,"<p>I want to test my service layer but stuck with an error.
I have <code>Company</code> entity and createCompany method in my service</p>
<pre><code>    public Company createCompany(String name) {
        Optional&lt;Company&gt; existingCompany = companyRepository.findCompanyByName(name);
        if (existingCompany.isPresent()) {
            log.error(&quot;Company with name {} already exists&quot;, name);
            throw new ValidationException(&quot;Company with name &quot; + name + &quot; already exists&quot;);
        } else {
            return companyRepository.save(new Company(UUID.randomUUID(), name, new HashSet&lt;&gt;()));
        }
    }
</code></pre>
<p>Here's my test:</p>
<pre><code>    @Test
    public void whenCreateCompany_thenReturnCompany() {
        // prepare
        Company company = new Company();
        when(companyRepository.save(any())).thenReturn(company);

        // testing
        Company createdCompany = companyService.createCompany(&quot;name&quot;);

        // validate
        verify(companyRepository).save(company);
    }
</code></pre>
<p>But when I run test, I get an error</p>
<pre><code>Argument(s) are different! Wanted:
companyRepository.save(
    Company(id=null, name=null)
);
Actual invocations have different arguments:
companyRepository.findCompanyByName(
    &quot;name&quot;
);

companyRepository.save(
    Company(id=f7cf1525-0dc4-4c27-a9af-693e2a295437, name=name)
);
</code></pre>
<p>How to test the service level correctly?</p>
",https://stackoverflow.com/questions/73106351/service-layer-unit-testing-spring-boot,"['spring', 'unit-testing', 'testing']",157,True,0,1
Unit Testing a &quot;Catch&quot; in C#,"<p>I have created an API project using .NET 6.0.
I have configured the app.MapGet method correctly, and they are executing their respective methods.
These methods execute their respective Datacalls and return &quot;Results.Ok(results)&quot;</p>
<pre><code>   public static class ResultSetBeingReturned
{
    public static async Task&lt;IResult&gt; ExecuteResultSet&lt;T&gt;(this Task&lt;IEnumerable&lt;T&gt;&gt; task)
    {
        try
        {
            var results = await task;

            if (results == null) return Results.NotFound();

            return Results.Ok(results);
        }
        catch (Exception ex)
        {

            return Results.Problem(ex.Message);
        }
    }
}
</code></pre>
<p>I want to unit test this method, so my question is: How do I invoke an API that is going to generate an Exception that is NOT a 404 Not Found?</p>
",https://stackoverflow.com/questions/70879817/unit-testing-a-catch-in-c,"['c#', 'api', 'unit-testing', '.net-6.0']",72,True,0,1
Dummy Array Value for Unit Testing,"<p>If have this error in unit testing wherein it cant detect the <code>id</code>:</p>
<pre><code>claim.claimReference[claim.claimId[claim.claimants[0].id]]
</code></pre>
<p>Currently, I am trying to put a dummy value for this</p>
<pre><code>claim: {
     claimReference: [{
      claim: {
        claimId: [
          {
            claim: {
              claimants: [{
                id: &quot;CM-0000003&quot;,
              }],
            },
          },
        ],
      },
    }],
  },
</code></pre>
<p>What is my mistake in here? Thank you for your correction.</p>
<p>EDIT: OHH WAIT. I THINK MY QUESTION WAS MISUNDERSTOOD. SORRY.
PLEASE SEE THE IMAGE ATTACHED.</p>
<p><a href=""https://i.stack.imgur.com/HjdS5.png"" rel=""nofollow noreferrer"">ERROR IN UNIT TESTING</a></p>
<p>WHAT I AM TRYING TO DO IS TO HAVE A DUMMY VALUE SO THAT I COULD SATISFY THE <code>claim.claimReference[claim.claimId[claim.claimants[0].id]]</code></p>
",https://stackoverflow.com/questions/70575803/dummy-array-value-for-unit-testing,"['javascript', 'arrays', 'reactjs', 'unit-testing']",69,False,0,1
Unit Testing for EventEmitter with Jest,"<p>I'm new to unit testing as a whole and especially new with javascript. I'm working on some unit testing with Jest and I came across this one script that doesn't make much sense to me. But, I figured I'd try to write a test for it.</p>
<p>I am completely new to this so even learning about EventEmitter is throwing me off. I did read that you have to call, in this case, newCommandEmitter but this script doesn't have that at all. It's just three lines.</p>
<p>Code is below, but I want to know, is this even worth writing a test for?</p>
<pre><code>const EventEmitter = require('events')
const newCommandEmitter = new EventEmitter()
module.exports = newCommandEmitter
</code></pre>
<p>My test script is as follows:</p>
<pre><code>const newCommandEmitter = require(&quot;./newCommandEmitter.js&quot;);
const events = require(&quot;events&quot;);

jest.mock(&quot;./newCommandEmitter.js&quot;);
jest.mock(&quot;events&quot;)

describe(&quot;Testing for events if command is used for events.&quot;, () =&gt; {

    test(&quot;First test to see if we get events data.&quot;, async () =&gt; {

        expect(newCommandEmitter).toBeTruthy();
    });
});
</code></pre>
",https://stackoverflow.com/questions/72737898/unit-testing-for-eventemitter-with-jest,"['javascript', 'node.js', 'jestjs', 'eventemitter']",336,True,0,1
Unit testing route handler with Jest?,"<p>I have the following code snippet that works as a handler for my certain route. I am trying to perform the unit test using Jest but I have no idea what are things I can test on the following function. I managed to test something but I am not sure whether I am in the right direction or not and what to test.</p>
<p>route.js</p>
<pre><code>exports.routeHandler = function (param1, param2) {
  return async function(req, res){
    const { id } = req.params;
    try {
      const user = await param1.user.getAuthUser(res);
      if(!user) return res.sendStatus(404).json();
      const results = await getUserId(user, param1, param2);
      const getInformation = await getInfo(results, id, param1, param2);
      res.sendStatus(200).json({
        getInformation
      })
    } catch (error) {
      return res.sendStatus(500);
    }
  }
}
</code></pre>
<p>route.test.js</p>
<pre><code>const mockResponse = () =&gt; {
  const res = {};
  res.sendStatus = jest.fn().mockReturnValue(res);
  res.json = jest.fn().mockReturnValue(res);
  return res;
}

const mockRequest = () =&gt; {
  return {
      params: {
          id : 1
      }
  }
}

const mockParam1 = {
  user: {
      getAuthUser: jest.fn()
  }
};
const mockParam2 = {
  error: jest.fn()
};


describe('checkAuth', () =&gt; {
  test('should 404 if user is not set', async() =&gt; {
      const req = mockRequest();
      const res = mockResponse();
      const routeHandlerTest = routeHandler(mockParam1, mockParam2);
      await routeHandlerTest(req, res)
       expect(res.sendStatus).toHaveBeenCalledWith(404);
  })
})
</code></pre>
<p>Another problem here is I am not being able to mock or spy the function <strong>getUserId</strong> and <strong>getInfo</strong>.</p>
<p>getUserId.js</p>
<pre><code>async function getUserId(user, param1, param2) {
  try {
    return await param1.database.query(
      'SELECT &quot;id&quot; from &quot;user&quot; WHERE &quot;username&quot; = $username',
      {
        type: &quot;SELECT&quot;,
        bind: { username: user.username },
      }
    );
  } catch (error) {
    param2.error(error);
  }
}
</code></pre>
<p>getInfo.js</p>
<pre><code>async function getInfo(results, id, param1, param2) {
  try {
    return await param1.database.query(
      // query
      ,
      {
        type: &quot;SELECT&quot;,
        bind: {
          id: id,
          userId: results[0].id,
        },
      }
    );
  } catch (error) {
    param2.error(error);
  }
}
</code></pre>
<p>Note: the functions <strong>getUserId</strong> and <strong>getInfo</strong> are in different modules</p>
",https://stackoverflow.com/questions/71335910/unit-testing-route-handler-with-jest,"['javascript', 'unit-testing', 'jestjs', 'mocking', 'spy']",403,False,0,0
SSDT Unit Testing with Database Variables,"<p>I have a database project in Visual Studio 2019 that references another database.  I have added a dacpac and use a variable to reference that database.</p>
<p>This works great, until it comes to unit tests.  I have added a unit test project, but the Unit Test project doesn't perform the variable substitution - it says the object [$(db)]... is undefined.</p>
<p>How can I unit test with database variables?</p>
",https://stackoverflow.com/questions/73516863/ssdt-unit-testing-with-database-variables,"['sql-server', 'sql-server-data-tools', 'ssdt-2019']",86,False,0,0
Unit testing weak reference application Android,"<p>I am passing weak reference of application is the constructor of a class for which I want to test.</p>
<pre><code>class FireBaseTracker @Inject constructor(
private val application: WeakReference&lt;Application&gt;
) :
BaseTracker {

private val TAG: String =
    RapidoAnalytics::class.java.simpleName + FireBaseTracker::class.java.simpleName
private var firebaseAnalytics: FirebaseAnalytics? =
    application.get()?.let { FirebaseAnalytics.getInstance(it) }

override fun trackEvent(eventName: String, eventProperties: HashMap&lt;String, Any&gt;?) {
    Log.d(TAG, &quot;event: $eventName  properties: $eventProperties&quot;)
    firebaseAnalytics?.logEvent(
        eventName,
        eventProperties?.toList()
            ?.let { bundleOf(*it.toTypedArray()) }
    )
  }
}
</code></pre>
<p>Unit test class</p>
<pre><code>@RunWith(MockitoJUnitRunner::class)
class FirebaseTrackerTest {
private lateinit var fireBaseTracker: FireBaseTracker
private val application: Application = mockk()
private val weakApplication: WeakReference&lt;Application&gt; =
    spyk(WeakReference&lt;Application&gt;(application))
private val firebaseAnalytics = FirebaseAnalytics.getInstance(application)

@Before
fun setUp() {
    fireBaseTracker = FireBaseTracker(weakApplication)
}

@Test
fun `should track firebase event when track event is invoked`() {
    fireBaseTracker.trackEvent(eventName, null)
    verify(exactly = 1) {
        firebaseAnalytics.logEvent(eventName, null)
    }
  }
}
</code></pre>
<p>Upon executing the test I am getting below error</p>
<pre><code>no answer found for: Application(#1).getResources()
io.mockk.MockKException: no answer found for: Application(#1).getResources()
at io.mockk.impl.stub.MockKStub.defaultAnswer(MockKStub.kt:93)
at io.mockk.impl.stub.MockKStub.answer(MockKStub.kt:42)
at io.mockk.impl.recording.states.AnsweringState.call(AnsweringState.kt:16)
at io.mockk.impl.recording.CommonCallRecorder.call(CommonCallRecorder.kt:53)
at io.mockk.impl.stub.MockKStub.handleInvocation(MockKStub.kt:266)
at io.mockk.impl.instantiation.JvmMockFactoryHelper$mockHandler$1.invocation(JvmMockFactoryHelper.kt:23)
at io.mockk.proxy.jvm.advice.Interceptor.call(Interceptor.kt:21)
at android.content.ContextWrapper.getResources(ContextWrapper.java)
at com.google.android.gms.measurement.internal.zzgc.zza(com.google.android.gms:play-services-measurement-base@@21.0.0:1)
at com.google.android.gms.internal.measurement.zzee.&lt;init&gt;(com.google.android.gms:play-services-measurement-sdk-api@@21.0.0:8)
at com.google.android.gms.internal.measurement.zzee.zzg(com.google.android.gms:play-services-measurement-sdk-api@@21.0.0:2)
at com.google.firebase.analytics.FirebaseAnalytics.getInstance(com.google.android.gms:play-services-measurement-api@@21.0.0:1)
at com.rapido.rapidoanalytics.trackers.FirebaseTrackerTest.&lt;init&gt;(FirebaseTrackerTest.kt:22)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:250)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:260)
at org.junit.runners.BlockJUnit4ClassRunner$2.runReflectiveCall(BlockJUnit4ClassRunner.java:309)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.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)
</code></pre>
",https://stackoverflow.com/questions/73245336/unit-testing-weak-reference-application-android,"['android', 'unit-testing', 'mockito', 'weak-references', 'applicationcontext']",47,False,0,0
ngx-translate Problems with unit testing,"<p>0</p>
<p>I'm using ngx-translate library and having some issues with unit testing because it wont find certain provides. The issue its that even tho i place a provider, it keeps asking for another one and it never solves the issue.</p>
<p>So basically im unit testing mi auth component, which uses in its constructor the translate service.</p>
<p>Tests ask me (like im showing on the next picture) that they need &quot;TraslateService&quot; as providers, so im adding them.</p>
<pre><code>  providers:[
    TranslateService
  ]
</code></pre>
<p>But once i add this, it asks for another thing from the translate, and it goes on in on. I believe that the solution should be another way.</p>
<p><em>Error image</em>
<img src=""https://i.stack.imgur.com/GAH1K.png"" alt=""Error image"" /></p>
<p><strong>app.module</strong></p>
<pre><code>  return new TranslateHttpLoader(http);
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
       },
    defaultLanguage: 'en'
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p>Quiero destacar que el sharedModule, ya exporta el translateModule que se usa en otros lugares de la app.</p>
<p>I wanna remark that on the sharedModule, TranslateModule it's already being exported which is used in other places on the app.</p>
<p><strong>Shared Module</strong></p>
<pre><code>@NgModule({
  imports: [
    ...,
    TranslateModule,
  ],
  exports: [
    ...,
    TranslateModule
  ],
  providers:[
  ]
})
export class SharedModule { }
</code></pre>
<p>** Also, the auth is a lazy module too.</p>
<p>auth.module**</p>
<pre><code>@NgModule({
  declarations: [
    AuthComponent
  ],
  imports: [
    CommonModule,
    AuthRoutingModule,
    SharedModule
  ]
})
export class AuthModule { }
</code></pre>
<p><strong>auth.component.ts</strong></p>
<pre><code>export class AuthComponent implements OnInit { 

  constructor(public translate: TranslateService)
}
</code></pre>
<p><strong>Spect.ts</strong></p>
<pre><code>describe('AuthComponent', () =&gt; {
  let component: AuthComponent;
  let fixture: ComponentFixture&lt;AuthComponent&gt;;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports:[
        HttpClientTestingModule,
        SharedModule,
      ],
      providers:[
        TranslateService,
      ],
      declarations: [ AuthComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  });

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

</code></pre>
<p>Any idea on how to fix this?</p>
",https://stackoverflow.com/questions/72221197/ngx-translate-problems-with-unit-testing,"['angular', 'angularjs', 'typescript', 'unit-testing', 'angular-test']",499,True,0,1
Mocha and Chai unit testing AssertionError,"<p>I don't understand why these are failing the variations I have tried are:</p>
<p>response.body.should.be.a('object').and.to.have.property('id');</p>
<p>and</p>
<p>response.body.should.have.property('id');</p>
<p>I get the error
Uncaught AssertionError: expected { Object (starss) } to have property 'id'</p>
<p>here is my JSON payload from Postman</p>
<pre><code>
{
    &quot;starss&quot;: {
        &quot;id&quot;: 1,
        &quot;name&quot;: &quot;1&quot;,
        &quot;discovery_name&quot;: &quot;1&quot;,
        &quot;imageFileName&quot;: &quot;test1.jpg&quot;,
        &quot;datediscovered&quot;: &quot;2001-01-01T00:00:00.000Z&quot;,
        &quot;colour&quot;: &quot;1&quot;,
        &quot;mass&quot;: &quot;1.000&quot;,
        &quot;dfe&quot;: &quot;1.000&quot;,
        &quot;galaxy_origin&quot;: &quot;1&quot;,
        &quot;star_categories_id&quot;: 1,
        &quot;createdAt&quot;: &quot;2021-12-03&quot;,
        &quot;updatedAt&quot;: &quot;2021-12-12&quot;
    }
}

</code></pre>
<p>here are my Mocha tests</p>
<pre><code>describe('GET/stars/:id',() =&gt; {
        it(&quot;it should get one star by ID&quot;, (done) =&gt;
        {
            // Uncaught AssertionError: expected { Object (starss) } to be a starss
            // star GET by ID
            const starId = 1;
            chai.request(server)
                .get(&quot;/stars/&quot; + starId )
                .end((err,response)=&gt;{
                    response.should.have.status(200);
                    response.body.should.be.a('object');
                    response.body.should.be.a('object').and.to.have.property('id');
                    response.body.should.have.property('id');
                    // response.body.should.have.property('name');
                    // response.body.should.have.property('discovery_name');
                    // response.body.should.have.property('imageFileName');
                    // response.body.should.have.property('datediscovered');
                    // response.body.should.have.property('colour');
                    // response.body.should.have.property('mass');
                    // response.body.should.have.property('dfe');
                    // response.body.should.have.property('galaxy_origin');
                    // response.body.should.have.property('star_categories_id');
                    done();
                });

        });

</code></pre>
",https://stackoverflow.com/questions/70670622/mocha-and-chai-unit-testing-assertionerror,"['javascript', 'unit-testing', 'mocha.js', 'chai', 'chai-http']",397,True,0,1
Python unit-testing a complicated method,"<p>I am looking for any advice on how to unit test the following method.</p>
<pre class=""lang-py prettyprint-override""><code>def delete_old_files(self):
        &quot;&quot;&quot;Deletes all recordings older then a predefined time period.

        Checks the mtime of files in _store_dir and if it is older then the predefined time period
        delete them.
        &quot;&quot;&quot;
        now = time.time()
        self.logger.info(
            f&quot;Delete: Looking for files older then {self.config.delete.older_then}&quot;
            f&quot; days in: {self._store_dir}.&quot;
        )
        try:
            for root, dirs, files in os.walk(self._store_dir):
                for file in files:
                    try:
                        if file == &quot;.gitignore&quot;:
                            continue
                        file = os.path.join(root, file)
                        # check if the mtime is older then x days (x * hours * minutes * seconds)
                        if os.stat(file).st_mtime &lt; now - (
                            self.config.delete.older_then * 24 * 60 * 60
                        ):
                            if os.path.isfile(file):
                                os.remove(file)
                                self.logger.info(f&quot;Delete:\t{file}&quot;)
                    except FileNotFoundError:
                        self.logger.warning(
                            f'Could not find &quot;{file}&quot;. Continue without deleting this file.'
                        )
                    except PermissionError:
                        self.logger.warning(
                            f'Permission denied when trying to delete &quot;{file}&quot;.'
                            &quot; Continue without deleting this file.&quot;
                        )
        # TODO: Do we want to handle the exception here or higher up?
        # Should we treat this as unacceptable or not?
        except FileNotFoundError:
            self.logger.warning(
                f&quot;Directory not found! Could not find {self._store_dir}&quot;
                &quot; Continue without deleting old files.&quot;
            )
        except PermissionError:
            self.logger.warning(
                f&quot;Permission denied! Could not access {self._store_dir}&quot;
                &quot; Continue without deleting old files.&quot;
            )
</code></pre>
<p>A little bit of background information: I am writing a audio recorder which saves all files into <code>self._store_dir</code> and the method I want to test is kind of an optional garbage collector. Files older then <code>self.config.delete.older_then</code> should be deleted. Any advice on how to unit test such a method or refactor it so it becomes easier to test is very welcome.</p>
<p>Ideas I have are:</p>
<ul>
<li>mock the filesystem and provided all the different cases. But that is the opposite of what a unit-test should do, right?</li>
<li>split up the method into smaller method and test them on their own.</li>
</ul>
",https://stackoverflow.com/questions/73885064/python-unit-testing-a-complicated-method,"['python', 'unit-testing', 'testing', 'mocking']",47,True,0,1
Unit Testing Spring WebClient Api call,"<p>I am using Spring Web module for writing REST Apis and using WebClient class to call external apis and using block() method to wait for the response.</p>
<p>I understand that I should write REST apis in fully non blocking way using Spring WebFlux. But that is not an option here.</p>
<p>I am having trouble writing unit tests and Mocking WebClient. I have read few WebClient mocking threads in Stack Overflow but none of them seems to be working in my case.</p>
<p>Following is my code</p>
<pre><code>

ResponseEntity&lt;String&gt; response = null;
        
        try {
            response = webClient
                    .post()
                    .uri(uriBuilder())
                    .bodyValue(request)
                    .retrieve()
                    .toEntity(String.class)
                    .block();
           } catch (WebClientResponseException e) {
 
            // Process different types of exceptions here

           if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
           // process HttpStatus.NOT_FOUND exception here
           }

         }


</code></pre>
<p>Can anyone please let me know how to unit test of this code?</p>
<p>Request class is a POJO class. uriBuilded() method returns an uri.</p>
",https://stackoverflow.com/questions/71476540/unit-testing-spring-webclient-api-call,"['spring-boot', 'spring-mvc', 'spring-webflux', 'spring-boot-test', 'spring-webclient']",2163,False,0,1
Run Python script unit testing - Selenium,"<p>I am a junior developer and totally new to Python and Selenium. I have to learn unit testing. They shared a small repository as an example. As required I installed Python and Selenium, but I don't know how to run. I have looked some tutorials, they just installed Python and Selenium, and added chromedriver, that's it. I have completed same steps, added PYTHONPATH and everything. But still getting errors.</p>
<p>My PYTHONPATH variable <code>C:\Users\yanke\altrium-systemtests\altsys</code></p>
<p><strong>Readme.md</strong></p>
<pre><code>System tests for Altrium frontend.

Install Python

export PYTHONPATH=&quot;.&quot;
python altsys/tests.py
</code></pre>
<p><strong>tests.py</strong></p>
<pre><code>&quot;&quot;Test altrium portal&quot;&quot;&quot;
import unittest
from selenium import webdriver

from altsys.selenium_helpers import sreenshot_on_fail

from altsys.page import AltriumPage


@sreenshot_on_fail()
class LoginTest(unittest.TestCase):
    &quot;&quot;&quot;Test altrium portal login

    Args:
        unittest ([type]): [description]
    &quot;&quot;&quot;
    def setUp(self) -&gt; None:
        self.driver = webdriver.Chrome()
        # self.driver = webdriver.Firefox()
        self.page = AltriumPage(self.driver, 'https://alpha.altrium.sg/login')

    def test_login(self):
        &quot;&quot;&quot;Test login
        &quot;&quot;&quot;
        self.page.login(
            'tdrobiszewski+st@gmail.com',
            'TestPassword123!'
            )

        # SLACK_TOKEN = 'xoxb-1178000328886-3062418273846-EIxTJ17QSbELkwB7WnbfHuFr'

if __name__ == '__main__':
    unittest.main()

</code></pre>
<p><em><strong>When I run I am getting these errors:</strong></em></p>
<pre><code>Error
Traceback (most recent call last):
  File &quot;C:\Program Files\Python310\lib\unittest\loader.py&quot;, line 34, in testFailure
    raise self._exception
ImportError: Failed to import test module: tests
Traceback (most recent call last):
  File &quot;C:\Program Files\Python310\lib\unittest\loader.py&quot;, line 154, in loadTestsFromName
    module = __import__(module_name)
  File &quot;C:\Users\yanke\altrium-systemtests\altsys\tests.py&quot;, line 5, in &lt;module&gt;
    from altsys.selenium_helpers import sreenshot_on_fail
  File &quot;C:\Users\yanke\altrium-systemtests\altsys\selenium_helpers.py&quot;, line 3, in &lt;module&gt;
    from slack_sdk import WebClient
ModuleNotFoundError: No module named 'slack_sdk'







Ran 1 test in 0.006s

FAILED (errors=1)

Process finished with exit code 1
</code></pre>
<p><em><strong>On Terminal</strong></em></p>
<pre><code>Traceback (most recent call last):
  File &quot;C:\Users\yanke\altrium-systemtests\altsys\tests.py&quot;, line 5, in &lt;module&gt;
    from altsys.selenium_helpers import sreenshot_on_fail
ModuleNotFoundError: No module named 'altsys'
</code></pre>
",https://stackoverflow.com/questions/73660710/run-python-script-unit-testing-selenium,"['python', 'selenium', 'unit-testing', 'testing', 'automated-tests']",45,False,0,0
Jest Unit Testing in Docker Container,"<p>I am trying to move my tests to my docker image build stage but it seems to ignore my test build at all and just skip it when I build the image.</p>
<p>What can be the problem?</p>
<pre><code># Base build 
FROM node:16.13 AS build
RUN mkdir /app
WORKDIR /app
ADD package*.json ./
RUN npm i -g npm@6.14.15
RUN npm i --production
COPY . .
RUN npm run build

# Clean
RUN npm prune --production
RUN npm install -g node-prune
RUN node-prune

# Test
FROM build AS test
RUN npm i -g npm@6.14.15
RUN npm i -D jest typescript
RUN npm i -D ts-jest @types/jest
RUN npm i -D @shelf/jest-mongodb
RUN npx jest

# Release
FROM node:16.13-alpine
RUN mkdir /app
WORKDIR /app
COPY --from=build /app/dist ./dist/
COPY --from=build /app/node_modules ./node_modules/
COPY --from=build /app/package.json ./
CMD npm start

</code></pre>
<p>Above you can see my <code>Dockerfile</code> where I am preparing the build, then plan to have tests and after that, I am making my release image.</p>
<p>I've already been playing around with that for hours; I cleared cache, made tweaks with the order in the file) but it didn't help. It keeps ignoring my test build.</p>
<p>Any hint of that and in general on my Dockerfile is welcomed</p>
",https://stackoverflow.com/questions/70727020/jest-unit-testing-in-docker-container,"['node.js', 'docker', 'unit-testing', 'jestjs', 'dockerfile']",1931,True,0,1
Unit-testing generics in JUnit 4,"<p>I have a class, <code>MyClass&lt; T &gt;</code>, which has a static function, <code>myFunction</code> that will modify the array of <code>T</code> received as its single parameter. (But currently it does nothing as I would like to set up testing first.)</p>
<p>I use JUnit 4.12. The problem with testing is <code>T</code>, which is a generic type, and must be determined at compile time. So to keep these tests in the same file, I created an Outer class <code>TestMyClass</code>, and inside it an abstract base class, <code>TestMyClass_T</code>, and a concrete derived class, <code>TestMyClass_Integer</code> (to be followed by <code>TestMyClass_Double</code> and <code>TestMyClass_String</code> once it works).</p>
<p>My first (but less important) problem is that although I declared <code>TestMyClass_T</code> abstract, I cannot declare its <code>getParameters</code> abstract because it is static. And I cannot omit it because I would get an error during testing:</p>
<pre><code>Error: java.lang.Exception: No public static parameters method on class TestMyClass$TestMyClass_T
</code></pre>
<p>So I decided to return an empty array but I hope there is a more elegant solution.</p>
<p><strong>My main problem</strong> is that although <code>TestMyClass_Integer</code> is a subclass of <code>TestMyClass_T</code> and inherits its <code>testMyFunction</code> method, ordinarily it is not called during testing and I get this result:</p>
<pre><code>All tests completed successfully.
</code></pre>
<p>But if I add an empty test <code>testDummy</code> which doesn't do anything, I get my expected test output:</p>
<pre><code>1 test failed:
  TestMyClass$TestMyClass_Integer
    testMyFunction[0]
    testDummy[1]
    testMyFunction[1]
File:   [line: 55]
Failure: arrays first differed at element [0]; expected:&lt;1&gt; but was:&lt;0&gt;
</code></pre>
<p>Here is my code:</p>
<pre><code>import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;


@RunWith( Enclosed.class )
public class TestMyClass {
    
    @RunWith( Parameterized.class )
    public static class TestMyClass_T&lt; T extends Comparable&lt; T &gt; &gt; {
    
        @Parameters
        public static Object[][]
        getParameters() {
            return new Object[][]{};
        }
        
        @Parameter( 0 )
        public T[] input;
        
        @Parameter( 1 )
        public T[] expectedOutput;
        
        @Test
        public void
        testMyFunction() {
            T[] actualOutput = Arrays.copyOf( input, input.length );
            MyClass.myFunction( actualOutput );
            assertArrayEquals( expectedOutput, actualOutput );
        }
        
    }
    
    @RunWith( Parameterized.class )
    public static class TestMyClass_Integer extends TestMyClass_T&lt; Integer &gt; {
        
        @Parameters
        @SuppressWarnings( &quot;unchecked&quot; )
        public static Object[][]
        getParameters() {
            return new Object[][] {
                { new Integer[] { 0 },
                  new Integer[] { 0 } },
                { new Integer[] { 0 },
                  new Integer[] { 1 } }
            };
        }
        
        @Test
        public void
        testDummy() {
        }
        
    }
    
}
</code></pre>
",https://stackoverflow.com/questions/72949952/unit-testing-generics-in-junit-4,"['java', 'unit-testing', 'generics', 'junit4']",75,False,0,0
Unit Testing for a random number,"<p>I am trying to create a junit test on a random number generator. However, I am not sure how you do this.</p>
<pre><code>package main;
import java.util.Random;
    
public class Dice {
    public int DiceRoll() {
        Random rand = new Random();
        return rand.nextInt(6)+1;
    }
}
</code></pre>
",https://stackoverflow.com/questions/71188966/unit-testing-for-a-random-number,"['java', 'unit-testing', 'junit', 'junit4']",557,True,0,1
Python unit testing with unittest module,"<p>This is how I wrote the code to start a test with the <strong>unittest</strong> module but it is returning as 0 tests. Is the return making any problems? (I am able to share the complete code but it is long). Posting the code and the script below:</p>
<ol>
<li><p>Script:</p>
<pre><code>class Test1(unittest.TestCase):

    def get_avg(temps, predict_month):
       #print(&quot;Temp:==&gt;&gt;&gt;&quot;,temps,&quot;predict_month:=&gt;&gt;&gt;&gt;&quot;,predict_month)
        temp_arr = []
        idx_num = month_dict[predict_month]
        temp_arr.append(float(temps[idx_num]))
        for i in range (0, 5, 1):
            idx_num += 1
            idx_num = idx_num % 12
            temp_arr.append(float(temps[idx_num]))
            pass
        # return np.average(temp_arr, axis=0) 
</code></pre>
</li>
<li><p>Showing the error with 0 tests:</p>
<pre><code>Ran 0 tests in 0.000s

OK
</code></pre>
</li>
<li><p>I ran the main <strong>unittest</strong> at the end with this:</p>
<pre><code>if __name__ == '__main__':
     unittest.main()
</code></pre>
</li>
</ol>
<p>I want to know about my faults and loopholes.</p>
",https://stackoverflow.com/questions/71815825/python-unit-testing-with-unittest-module,"['python', 'unit-testing', 'testing', 'automated-tests', 'python-unittest']",264,False,0,2
Unit testing errors in Angular 14,"<p>I created a brand new Angular project using the cli <code>ng new ...</code>
and when I run <code>npm test</code> I get the below error in the browser:</p>
<p><a href=""https://i.stack.imgur.com/MQP0O.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/MQP0O.png"" alt=""enter image description here"" /></a></p>
<p>and in the console I see this error:</p>
<p><a href=""https://i.stack.imgur.com/89ghp.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/89ghp.png"" alt=""enter image description here"" /></a></p>
<p>I've not added anything extra;</p>
<p>I tested with Node versions 14.17.1 and 16.16.0 (I am on macOS, and using nvm); I tried uninstalling both Node versons, deleted all nvm cache files, installed Node again, but still getting the error</p>
<p>How can I debug or solve this issue?</p>
",https://stackoverflow.com/questions/73053951/unit-testing-errors-in-angular-14,"['angular', 'unit-testing', 'jasmine', 'angular14']",404,True,0,1
Automapper inside service when unit testing,"<p>I am wondering how to configure automapper inside some unit tests.
The service does a few things:</p>
<ul>
<li>Fetches a user</li>
<li>Created an integration object</li>
<li>Maps integration object</li>
<li>Updates the user</li>
</ul>
<p>Service:</p>
<pre><code>public void Update(UserUpdateDto userUpdateDto)
    {
        var user = _userValidationService.ValidateUser(userUpdateDto.Id);

        var integration = _integrationService.UpdateIntegration(userUpdateDto.Integration, userUpdateDto.Id);

        var integrationGateway = _mapper.Map&lt;IntegrationGateway&gt;(integration);
        user.Integration = integrationGateway;

        _repository.Update(user);
        _repository.Commit();
    }
</code></pre>
<p>Test</p>
<pre><code>//Arrange
        

        InMemoryRepository.Add(userGateway); 

        _mockIntegrationService.Setup(x =&gt; x.UpdateIntegration(It.IsAny&lt;IntegrationDto&gt;(), It.IsAny&lt;int&gt;())).Returns(integration);

        //Act
        _usersService.Update(userUpdateDto);

        //Assert
        var integrationResult = InMemoryRepository.GetAll&lt;UserGateway&gt;().FirstOrDefault(u =&gt; u.Id == 1)!.Integration;
        Assert.AreEqual(userUpdateDto.Integration.WooConsumerKey, integrationResult.WooConsumerKey);
</code></pre>
<p>I have thought about setting up an expected return for the map method but this would defeat the purpose of the test?</p>
<p>If my service is not very testable then I would appreciate advise on how I could refactor this. Cheers</p>
<p>.NET 6, MSTEST</p>
",https://stackoverflow.com/questions/71134475/automapper-inside-service-when-unit-testing,"['c#', 'mstest']",205,False,0,1
Unit Testing using Sinon for document.addListener,"<p>I'm doing unit test for a function with document.addEventListener</p>
<pre><code>document.addEventListener('keydown', this.rfidListener, false);
</code></pre>
<p>I try to use sinon.stub to mock addEventListener. But it fail to mock it. The following is my unit test mock code. But it seems like not working. Anyway for me to mock addEventListener code above???</p>
<pre><code>  sinon.stub(document, 'addEventListener').value('A');
</code></pre>
",https://stackoverflow.com/questions/74784900/unit-testing-using-sinon-for-document-addlistener,"['javascript', 'unit-testing', 'mocha.js', 'sinon', 'karma-mocha']",47,False,0,0
Unit Testing authenticated user in Laravel,"<p>I am developing an app and now I need to do some testing. Everything in the app is based on authenticated user so this is the first test that I need to do. I have a google captcha in the form but I modified the <code>.env</code> file so that will not be required. This is my feature test.</p>
<pre><code>public function test_users_can_authenticate()
{
     $user = User::factory()-&gt;create();

     $response = $this-&gt;get('/login', [
         '_token' =&gt; csrf_token(),
         'email' =&gt; $user-&gt;email,
         'password' =&gt; 'secret',
         'g-recaptcha-response' =&gt; ''
     ]);
        
     $this-&gt;assertAuthenticated();
     $response-&gt;assertRedirect(RouteServiceProvider::HOME);
}
</code></pre>
<p>The test is failing  on this line <code>$this-&gt;assertAuthenticated();</code> saying that <code>The user is not authenticated. Failed asserting that false is true.</code> I did not now what can I do to make it work. I tried <code>php artisan config:clear</code> before <code>php artisan test</code>, not working. I uncomment the lines in <code>phpunit.xml</code></p>
<pre><code>&lt;!-- &lt;server name=&quot;DB_CONNECTION&quot; value=&quot;mysql&quot;/&gt; --&gt;
&lt;!-- &lt;server name=&quot;DB_DATABASE&quot; value=&quot;:memory:&quot;/&gt; --&gt;
</code></pre>
<p>but still with no result. Working with Laravel 8.x. What can I do to make this work? Thanks.</p>
",https://stackoverflow.com/questions/71573750/unit-testing-authenticated-user-in-laravel,"['php', 'laravel', 'unit-testing']",429,True,0,1
Unit testing sessionStorage value in emberJS,"<p>I'm new to ember and trying to figure out how to unit test, using sinon, the  sessionStorage based on url parameters when that page is visited. I've tried a few things but still can't get the desired result. It passes even if I change the 'sessionValue' without editing the query param.
Thank you in advance.</p>
<p><em>ember component</em></p>
<pre><code>beforeModel(transition) {

    //transition will contain an object containing a query parameter. '?userid=1234' and is set in the sessionStorage.

    if(transition.queryparam.hasOwnProperty('userid')){
        sessionStorage.setItem('user:id', transition.queryparam)
    }
}
</code></pre>
<p><em>Ember test</em></p>
<pre><code>test('Session Storage contains query param value', async assert =&gt; {
let sessionKey = &quot;user:id&quot;;
let sessionValue = &quot;1234&quot;

let store = {};
  const mockLocalStorage = {
    getItem: (key) =&gt; {
      return key in store ? store[key] : null;
    },
    setItem: (key, value) =&gt; {
      store[key] = `${value}`;
    },
    clear: () =&gt; {
      store = {};
    }
  };

  asserts.expect(1);
  
  let spy = sinon.spy(sessionStorage, &quot;setItem&quot;);
  spy.calledWith(mockLocalStorage.setItem);

  let stub = sinon.stub(sessionStorage, &quot;getItem&quot;);
  stub.calledWith(mockLocalStorage.getItem);
  stub.returns(sessionValue);

  await visit('/page?userid=1234');
     
  mockLocalStorage.setItem(sessionKey, sessionValue);
  assert.equal(mockLocalStorage.getItem(sessionKey), sessionValue, 'storage contains value');
})
</code></pre>
",https://stackoverflow.com/questions/72588826/unit-testing-sessionstorage-value-in-emberjs,"['unit-testing', 'ember.js', 'ember-cli', 'sinon', 'ember-qunit']",151,False,0,1
Unit-testing grpc functions in golang,"<p>I have created a function that utilizes the grpc package in golang. I don't know if it is relevant but the purpose is the communication with a GoBGP router over grpc. An example is the following function which prints all the peers (neighbors) of the router:</p>
<pre><code>func (gc *Grpc) Peers(conn *grpc.ClientConn) error {
    defer conn.Close()

    c := pb.NewGobgpApiClient(conn)
    ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
    defer cancel()

    p := pb.ListPeerRequest{}
    peer, err := c.ListPeer(ctx, &amp;p)
    if err != nil {
        return err
    }
    for {
        res, err := peer.Recv()
        if err != nil {
            return err
        }
        fmt.Println(res)
    }
    return nil
}
</code></pre>
<p>Now, I want to create unit tests for the function. To do so, I used <code>google.golang.org/grpc/test/bufconn</code> package, and initialized the following:</p>
<pre><code>type server struct {
    pb.UnimplementedGobgpApiServer
}    
func (s *server) ListDefinedSet(in *pb.ListDefinedSetRequest, ls pb.GobgpApi_ListDefinedSetServer)  error {
    return  nil
}

var lis *bufconn.Listener

const bufSize = 1024 * 1024

func init() {
    lis = bufconn.Listen(bufSize)
    s := grpc.NewServer()
    pb.RegisterGobgpApiServer(s, &amp;server{})
    go func() {
        if err := s.Serve(lis); err != nil {
            fmt.Println(&quot;Server failed!&quot;)
        }
    }()
}

func bufDialer(context.Context, string) (net.Conn, error) {
    return lis.Dial()
}
</code></pre>
<p>This way, I can run a unit-test creating a connection as follows:</p>
<pre><code>ctx := context.Background()
conn, _ := grpc.DialContext(ctx, &quot;bufnet&quot;, grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
Peers(conn)
</code></pre>
<p>However, the problem is that the stream seems to be always empty and thus the peer.Recv()
always returns EOF. Is there any way to populate the stream with dummy data? If you have experience, is my methodology correct?</p>
",https://stackoverflow.com/questions/73707313/unit-testing-grpc-functions-in-golang,"['unit-testing', 'go', 'grpc']",335,False,0,0
Unit Testing using Moq and RepoDb,"<p>I'm pretty new about Unit Testing and I need some information. I'm developing a Web API project using Dependency Injection, RepoDb as ORM (Sql Server only) and Moq in C#.</p>
<p>I deduced that I need Unit Tests and Integration Tests.</p>
<ol>
<li><p>For Integration Tests I would need to make API calls without mocking but going to create an ad hoc test database. Is it right?</p>
</li>
<li><p>For Unit Tests I should use collections instead of the database. The connection to the database is obtained <strong>at runtime</strong> starting from the customer's name (it's in <code>commonInfoService</code>):</p>
<pre><code> public class MyService : BaseDbService
 {
     private readonly IMyRelatedService _myRelatedService;
     private readonly IOtherRelatedService _otherRelatedService;

     public MyService(IConfiguration config, ILogger&lt;MyService&gt; logger, ICommonInfoService commonInfoService, IMyRelatedService myRelatedService, IOtherRelatedService otherRelatedService) : base(config, logger, commonInfoService)
     {
         _myRelatedService = myRelatedService;
         _otherRelatedService = otherRelatedService;
     }

     public async Task&lt;int&gt; CreateObject(MyObject myObject)
     {
         // TODO
     }
}
</code></pre>
</li>
</ol>
<p>There are many related services in the constructor.</p>
<p>In the Unit Test:</p>
<pre><code>[TestInitialize]
public void Setup()
{
    _loggerService = Mock.Of&lt;ILogger&lt;MyService&gt;&gt;();
    _commonInfoService = Mock.Of&lt;ICommonInfoService&gt;();
    _config = Mock.Of&lt;IConfiguration&gt;();
    // ...
}

[TestMethod]
public async Task TestCreateObjectWrongExtension()
{
    // Arrange
    Mock.Get(_commonInfoService).SetupGet(mock =&gt; mock.CustomerName).Returns(&quot;FIXEDVALUE&quot;);

    var configForSmsApi = new Dictionary&lt;string, string&gt;
    {
        {&quot;AppSettings:InstanceRootFolder&quot;, &quot;c:\\temp&quot;},
    };

    var configuration = new ConfigurationBuilder()
        .AddInMemoryCollection(configForSmsApi)
        .Build();

    Mock.Get(_myRelatedService).Setup(mock =&gt; mock.GetAllowedExtensions().Returns(&quot;.pdf&quot;);

    MyService service = new MyService(_config, _loggerService, _commonInfoService, _myRelatedService, It.IsAny&lt;IOtherRelatedService&gt;());

    MyObject myObject = new MyObject();
    myObject.Filename = &quot;test.abc&quot;;

    // Act
    // Assert
    HttpStatusException exceptionThrown = await Assert.ThrowsExceptionAsync&lt;HttpStatusException&gt;(async () =&gt; await service.CreateObject(myObject));
}
</code></pre>
<p>Is it right?
How do I get my context to replace the real database with a collection of values ​​created ad hoc?</p>
",https://stackoverflow.com/questions/72657677/unit-testing-using-moq-and-repodb,"['c#', 'unit-testing', 'dependency-injection', 'moq', 'webapi']",122,False,0,0
Method unit testing failing in nestjs,"<p>I have below only method in my controller.</p>
<pre><code>@Controller()
export class AppController {
  
  @Get('whoami')
    @Roles(Role.All)
    @ApiResponse({ status: 200, type: User })
    currentUser(@Req() request: Request) {
        return request.user;
    }
}
</code></pre>
<p>I am writing below test case for the same.</p>
<pre><code>describe('AppController', () =&gt; {
    let controller: AppController;

    beforeAll(async () =&gt; {
        const app: TestingModule = await Test.createTestingModule({
            controllers: [AppController],
        }).compile();

        controller = app.get&lt;AppController&gt;(AppController);
    });

    it('should be defined', () =&gt; {
        expect(controller).toBeDefined();
    });

    it('currentUser should be called', () =&gt; {
        expect(controller.currentUser).toBeDefined();
        expect(controller.currentUser).toEqual(&quot;shruti&quot;);
    });
});
</code></pre>
<p>not only this is failing but also  <code>return request.user;</code> not getting covered in coverage. below is the error.</p>
<p><a href=""https://i.stack.imgur.com/pZdV3.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/pZdV3.png"" alt=""enter image description here"" /></a></p>
<p>what wrong I am doing?</p>
",https://stackoverflow.com/questions/72599858/method-unit-testing-failing-in-nestjs,"['javascript', 'unit-testing', 'testing', 'jestjs', 'nestjs']",289,True,0,1
Unit Testing rest controller with @AuthenticationPrincipal,"<p>I am developing a rest api with spring boot and spring security.</p>
<p>the code looks like so:</p>
<pre class=""lang-java prettyprint-override""><code>@RestController
@RequestMapping(path = &quot;/api&quot;)
@PreAuthorize(&quot;isAuthenticated()&quot;)
public class RestController {

  @GetMapping(path = &quot;/get&quot;, produces = &quot;application/json&quot;)
  public ResponseEntity&lt;InDto&gt; get(
      @AuthenticationPrincipal final CustomUser user) {

    // ...

    return ResponseEntity.ok(outDto);
  }
}


public class CustomUser {
    // does not inherit from UserDetails
}


public class CustomAuthenticationFilter extends OncePerRequestFilter {

  @Override
  protected void doFilterInternal(
    @NonNull final HttpServletRequest request,
    @NonNull final HttpServletResponse response,
    @NonNull final FilterChain filterChain)
    throws ServletException, IOException {

    if (/* condition */) {
      // ...
      final CustomUser user = new CustomUser(/* parameters */);

      final Authentication authentication =
          new PreAuthenticatedAuthenticationToken(user, &quot;&quot;, new ArrayList&lt;&gt;());
      SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    filterChain.doFilter(request, response);
  }
}
</code></pre>
<p>I would like to unit test the RestController class ideally without the security feature but I don't know how to inject a specific CustomUser object during test.</p>
<p>I have tried to manually add a user to the security context before each test (see below) but the user injected into the controller during test is not the mocked on.</p>
<pre class=""lang-java prettyprint-override""><code>@WebMvcTest(RestController.class)
@AutoConfigureMockMvc(addFilters = false)
class RestControllerTest {

  @Autowired private MockMvc mockMvc;
  private CustomerUser userMock;

  @BeforeEach
  public void skipSecurityFilter() {
    userMock = Mockito.mock(CustomUser.class);
    SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
    final Authentication auth = new PreAuthenticatedAuthenticationToken(userMock, null, List.of());
    SecurityContextHolder.getContext().setAuthentication(auth);
  }

  @Test
  void test() {
    mockMvc.perform(
            MockMvcRequestBuilders.get(&quot;/api/get&quot;)
                .contentType(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk());

  }
}
</code></pre>
<p>What is wrong? How to inject the specific userMock into the controller to perform the test?</p>
<p>EDIT to test with @WithMockCustomUser</p>
<p>as suggested in the doc <a href=""https://docs.spring.io/spring-security/reference/servlet/test/method.html#test-method-withsecuritycontext"" rel=""nofollow noreferrer"">https://docs.spring.io/spring-security/reference/servlet/test/method.html#test-method-withsecuritycontext</a> i have updated the test to:</p>
<pre class=""lang-java prettyprint-override""><code>@Retention(RetentionPolicy.RUNTIME)
@WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
public @interface WithMockCustomUser {
}

@Service
public class WithMockCustomUserSecurityContextFactory
    implements WithSecurityContextFactory&lt;WithMockCustomUser&gt; {

  @Override
  public SecurityContext createSecurityContext(final WithMockCustomUser customUser) {
    final SecurityContext context = SecurityContextHolder.createEmptyContext();

    final Authentication auth =
        new PreAuthenticatedAuthenticationToken(Mockito.mock(IUser.class), null, List.of());
    context.setAuthentication(auth);
    return context;
  }
}

@WebMvcTest(RestController.class)
@AutoConfigureMockMvc(addFilters = false)
class RestControllerTest {

  @Autowired private MockMvc mockMvc;
  private CustomerUser userMock;

  @BeforeEach
  public void skipSecurityFilter() {
    userMock = Mockito.mock(CustomUser.class);
  }

  @Test
  @WithMockCustomUser
  void test() {
    mockMvc.perform(
            MockMvcRequestBuilders.get(&quot;/api/get&quot;)
                .contentType(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk());

  }
}

</code></pre>
<p>but the user object in the controller is still not the mock (created in the factory)</p>
",https://stackoverflow.com/questions/74024642/unit-testing-rest-controller-with-authenticationprincipal,"['java', 'spring-boot', 'rest', 'spring-security', 'spring-test-mvc']",388,True,0,1
Unit testing | Mocking FileOutputStream using Mockk.io,"<p>I need to test three things from the below mentioned method:</p>
<ul>
<li>verify <code>output.write(any&lt;ByteArray&gt;())</code> is called</li>
<li>verify <code>output.close()</code> is called</li>
<li>assert that <code>fullPath</code> is returned</li>
</ul>
<pre><code>fun saveFile(fullPath: String, model: SomeDataModel): String? {
        try {
            val output = FileOutputStream(fullPath)
            output.write(Base64.decode(model.someString, Base64.DEFAULT))
            output.close()
        } catch (e: IOException) {
            return null
        }
        return fullPath
 }
</code></pre>
<p>Facing issue:</p>
<ul>
<li>Mocking <code>FileOutputStream</code></li>
</ul>
<p>Tried:</p>
<pre><code>    @Test
    fun `saveFile returns file path if fileOutputStream write succeeds`() {
        val fullPath = &quot;test/full/path&quot;
        val model = SomeDataModel()
        val stringByteArray: ByteArray? = someModel.someString?.toByteArray(Charset.defaultCharset())


        mockkStatic(&quot;android.util.Base64&quot;)
        every { Base64.decode(model.someString, Base64.DEFAULT) } returns stringByteArray

        mockkConstructor(FileOutputStream::class)
        val fileOutputStream = mockk&lt;FileOutputStream&gt;()
        every { constructedWith&lt;FileOutputStream&gt;(OfTypeMatcher&lt;String&gt;(String::class)) } returns fileOutputStream
        // Getting error on above line: Missing mocked calls inside every { ... } block: make sure the object inside the block is a mock

        every { saveFile(fullPath, model) } returns filePath

        val result = saveFile(fullPath, model)

        verify { fileOutputStream.write(stringByteArray) }

        assertEquals(fullPath, result)
    }
</code></pre>
<p>Please help me to write correct test case using Mockk.io/Mockito</p>
",https://stackoverflow.com/questions/73059436/unit-testing-mocking-fileoutputstream-using-mockk-io,"['android', 'unit-testing', 'kotlin', 'mockito', 'mockk']",340,False,0,1
Unit Testing Failing on Build Server,"<p>We had a build server doing CI. All of a sudden the Unit test were failing without any changes. We are getting below error:</p>
<p>Unhandled Exception: System.AggregateException: One or more errors occurred. ---&gt; Microsoft.VisualStudio.TestPlatform.Common.TestRunner.ProcessExitedException: Executor process exited. ---&gt; System.ServiceModel.CommunicationException: There was an error reading from the pipe: Unrecognized error 109 (0x6d). ---&gt; System.IO.PipeException: There was an error reading from the pipe: Unrecognized error 109 (0x6d).
at System.ServiceModel.Channels.PipeConnection.FinishSyncRead(Boolean traceExceptionsAsErrors)
at System.ServiceModel.Channels.PipeConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
--- End of inner exception stack trace ---</p>
<p>Server stack trace:
at System.ServiceModel.Channels.PipeConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
at System.ServiceModel.Channels.DelegatingConnection.Read(Byte[] buffer, Int32 offset, Int32 size, TimeSpan timeout)
at System.ServiceModel.Channels.ConnectionUpgradeHelper.InitiateUpgrade(StreamUpgradeInitiator upgradeInitiator, IConnection&amp; connection, ClientFramingDecoder decoder, IDefaultCommunicationTimeouts defaultTimeouts, TimeoutHelper&amp; timeoutHelper)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.SendPreamble(IConnection connection, ArraySegment`1 preamble, TimeoutHelper&amp; timeoutHelper)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.DuplexConnectionPoolHelper.AcceptPooledConnection(IConnection connection, TimeoutHelper&amp; timeoutHelper)
at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)
at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceModel.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)</p>
<p>Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type)
at Microsoft.VisualStudio.TestPlatform.Core.ITestExecutorService.InitializeConnection(IEnumerable<code>1 pathToAdditionalExtensions, Boolean loadOnlyWellKnownExtensions) at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceProxy.InitializeConnection(IEnumerable</code>1 pathToAdditionalExtensions, Boolean loadOnlyWellKnownExtensions)
at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.TestConnection(Binding binding, EndpointAddress address, ITestExecutorServiceProxy&amp; proxy)
at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.InitializeProxy(String namedPipeIdentifierToken)
--- End of inner exception stack trace ---
at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.CheckExecutorProcessExited(Exception ex)
at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.InitializeProxy(String namedPipeIdentifierToken)
at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.Initialize_NoLock(Architecture targetPlatform, FrameworkVersion targetFramework)
at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.EnsureInitialized(IDictionary<code>2 environmentVariables, TestExecutionContext context) at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.&lt;&gt;c__DisplayClass18_0.&lt;StartTestRun&gt;b__0() at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.InvokeTestExecutorServiceAction(Action action) at Microsoft.VisualStudio.TestPlatform.Client.TestExecutorServiceClient.StartTestRun(IEnumerable</code>1 sources, TestExecutionContext executionContext, String runSettings, IDictionary<code>2 environmentVariables, String dataCollectionServiceUri, ITestCaseLog testCaseLog, ITestRunLog testRunLog, IFrameworkHandleInternal frameworkHandle) at Microsoft.VisualStudio.TestPlatform.Client.Rocksteady.ParallelTestExecutorServiceClient.TriggerExecutionForNextSource(ITestExecutorServiceClient executorServiceClient) at Microsoft.VisualStudio.TestPlatform.Client.Rocksteady.ParallelTestExecutorServiceClient.&lt;StartTestRunPrivate&gt;b__23_0() at System.Threading.Tasks.Task</code>1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at Microsoft.VisualStudio.TestPlatform.Client.Rocksteady.ParallelTestExecutorServiceClient.StartTestRunPrivate(TestExecutionContext executionContext, String runSettings, IDictionary<code>2 environmentVariables, String dataCollectionServiceUri, ITestCaseLog testCaseLog, ITestRunLog testRunLog, IFrameworkHandleInternal frameworkHandle) at Microsoft.VisualStudio.TestPlatform.Client.Rocksteady.ParallelTestExecutorServiceClient.StartTestRun(IEnumerable</code>1 sources, TestExecutionContext executionContext, String runSettings, IDictionary<code>2 environmentVariables, String dataCollectionServiceUri, ITestCaseLog testCaseLog, ITestRunLog testRunLog, IFrameworkHandleInternal frameworkHandle) at Microsoft.VisualStudio.TestPlatform.Client.Rocksteady.RocksteadyExecutionManager.StartTestRun(TestRunCriteria testRunCriteria, Boolean inIsolation, DataCollectionParameters dataCollectionParameters, ITestRunEventsHandler runEventsHandler) at Microsoft.VisualStudio.TestPlatform.Client.TestRunRequest.ExecuteAsync() at Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.RunTestsArgumentProcessor.RunTests(IEnumerable</code>1 sources, String packageFullName, String deviceInfo, Boolean isPhoneAppx, Boolean isUniversalTestAppx)
at Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.RunTestsArgumentProcessor.Execute()
at Microsoft.VisualStudio.TestPlatform.CommandLine.Executor.Execute(String[] args)
at RockSteady.Program.Main(String[] args)</p>
",https://stackoverflow.com/questions/74715659/unit-testing-failing-on-build-server,['tfsbuild'],42,False,0,1
Coil unit testing - how to do this?,"<p>Is it possible to mock coil network level when unit testing? With <code>MockWebServer</code>? Or test it somehow else? I can't find information on the Internet about it.</p>
",https://stackoverflow.com/questions/72920606/coil-unit-testing-how-to-do-this,"['android', 'unit-testing', 'coil']",184,True,5,1
Unit testing SwiftUI/Combine @Published boolean values,"<p>I am trying to acquaint myself with unit testing some view models in SwiftUI. The view model currently has two <code>@Published</code> boolean values that publish changes when an underlying <code>UserDefaults</code> property changes. For my unit tests, I have followed <a href=""https://www.swiftbysundell.com/tips/avoiding-mocking-userdefaults/"" rel=""nofollow noreferrer"">this guide</a> on how to setup <code>UserDefaults</code> for testing so my production values are not modified. I am able to test the default value as such:</p>
<pre><code>func testDefaultValue() {
     XCTAssertFalse(viewModel.canDoThing)
}
</code></pre>
<p>How would I go about toggling the <code>@Published</code> value then ensuring my view model has received the changes? So for instance, I have a reference to my mock user defaults in my XCTestCase. I attempted to do the following with zero success:</p>
<pre><code>func testValueTogglesToTrue() {
     defaults.canDoThing = true
     XCTAssertTrue(viewModel.canDoThing)
</code></pre>
<p>}</p>
<p>The thought being that updating the underlying user defaults value that is publishing changes to the published value in the view model will notify our view model. The above does not do anything to the view model variable. Do I need to subscribe to the publisher and use sink to accomplish this?</p>
",https://stackoverflow.com/questions/70809030/unit-testing-swiftui-combine-published-boolean-values,"['unit-testing', 'swiftui', 'combine']",879,True,3,1
Using Specflow without the unit testing frameworks,"<p>So for my current project I need to perform several tests on a (physical) system.
Within my company we have this testing framework, which provides several features out of the box, such as writing my results to a database and such.</p>
<p>Now I've heard about BDD and I found that a gherkin way of writing these tests would be really nice and clean.
So I started looking into Specflow, which looks really good.
Only problem with Specflow is that you are required to use a Unit Testing framework. This is not at all what I want, since my own framework already provides all this stuff. Starting a test for example needs to be done by an operator from a GUI. So the unit testing framework is not needed at all.</p>
<p>Now my question is whether I can use Specflow simply to generate these tests (within their own test class or something) and keep using my own framework.</p>
<p>So as an example, what I'm looking for is something along these lines:</p>
<pre><code>Given that the machine is in base state
When we open the valve
Then the valve sensor should have value higher than 450
</code></pre>
<p>Then have a StepDefinition file, which will contain the actual machine interface (sample code ofc)</p>
<pre><code>public void MachineInBaseState()
{
    machine.GoToBaseState();
}
public void ValvePosition(bool open)
{
    machine.SetValve(open);
}
public void CheckValveSensorPosition(int valueToCheckAgainst)
{
    testResults.Add(new ValueResult(value:machine.GetSensorValue(),min:valueToCheckAgainst,max:double.NaN));
}
</code></pre>
<p>Then during build of the project, to have the gherkin file be generated in such a way that my own testing framework can pick up the generated testresults.</p>
<p>I know that this may not be something that a lot of people do, but maybe someone has seen something like it before.</p>
<p>Another way of course is to write a source generator, but that will take a lot more time.</p>
",https://stackoverflow.com/questions/73165522/using-specflow-without-the-unit-testing-frameworks,"['c#', '.net-6.0', 'specflow', 'gherkin']",126,True,2,2
Mock grpc service in unit testing nestjs,"<p>I want write an unit test for my <code>getAllGroups()</code> method in <strong>mail.service.ts</strong>:</p>
<pre><code>public async getAllGroup(): Promise&lt;{ id: number, name: string }[]&gt; {
  try {
    return (await lastValueFrom(this.groupService.GetAllGroup({}))).groups;
  } catch (error) {
    throw error;
  }
}
</code></pre>
<p>The problem is i want to mock <code>GetAllGroups()</code> that is a grpc method and fetch datas.
how i add groupService in <strong>mail.service.ts</strong>:</p>
<pre><code>constructor(
  @Inject('groupService') private groupClient: ClientGrpc,
) { }
private readonly groupService = this.groupClient.getService&lt;GroupService&gt;('groupService');
</code></pre>
<p>In <strong>mail.service.spec.ts</strong> how i provide groupService:</p>
<pre><code>{
   provide: 'groupService',
   useValue: createMock&lt;ClientGrpc&gt;()
             .getService&lt;GroupService&gt;('groupService')
}
</code></pre>
<p>And the test i write for <code>getAllGroups()</code> method:</p>
<pre><code>it(`getAllGroup() should return list of gropus`, async () =&gt; {
    const groupMock = createMock&lt;MailService&gt;();
    groupMock.GetAllGroup.mockReturnValue( of({ groups: [{ id: 123, name: &quot;abc&quot; }] }));

    expect(service.getAllGroup()).toEqual([
        { id: 123, name: &quot;abc&quot; }
    ]);
})
</code></pre>
<p>After test execution its failed and return this:</p>
<pre><code>Expected: [{&quot;id&quot;: 123, &quot;name&quot;: &quot;abc&quot;}]
Received: {}

  56 |         groupMock.GetAllGroup.mockReturnValue( of({ groups: [{ id: 123, name: &quot;abc&quot; }] }));
  57 |
&gt; 58 |         expect(service.getAllGroup()).toEqual([
     |                                       ^
  59 |             { id: 123, name: &quot;abc&quot; }
  60 |         ]);
  61 |     })
</code></pre>
",https://stackoverflow.com/questions/72238116/mock-grpc-service-in-unit-testing-nestjs,"['node.js', 'unit-testing', 'mocking', 'nestjs', 'grpc']",890,True,2,1
unit testing on nextJS + chakra-UI project,"<p>I am working on a <code>NextJS + chakra-UI</code> project and so far I couldn't find any information on how to get <code>jest</code> and <code>react-testing</code> library to understand the way chakra-UI renders components. My tests keep throwing <code>errors</code> like the following:</p>
<pre><code>TypeError: Cannot use 'in' operator to search for 'colors.green.200' in undefined

       6 | describe(&quot;Nav-bar testing&quot;, () =&gt; {
       7 |   it(&quot;should render NavBar correctly&quot;, () =&gt; {
    &gt;  8 |     render(&lt;NavBar /&gt;);
         |           ^
       9 |     const button = screen.getByText(&quot;Login&quot;);
      10 |     expect(button).toBeInTheDocument();
      11 |   });
</code></pre>
<p>When I make a <code>react jsx</code> element without the components chakra provides tests execute correctly. Is there any source explaining how to set things up in this case ?</p>
<p>EDIT
This is the test file:</p>
<pre><code>import React from &quot;react&quot;;
import { screen, render } from &quot;@testing-library/react&quot;;
import &quot;@testing-library/jest-dom&quot;;
import NavBar from &quot;../components/NavBar/NavBar&quot;;

describe(&quot;Nav-bar testing&quot;, () =&gt; {
  it(&quot;should render NavBar correctly&quot;, () =&gt; {
    render(&lt;NavBar /&gt;);
    const button = screen.getByText(&quot;Login&quot;);
    expect(button).toBeInTheDocument();
  });
});
</code></pre>
<p>This is the _app which contains the chakra theme object and the wrapper:</p>
<pre><code>import type { AppProps } from &quot;next/app&quot;;
import &quot;../styles/globals.css&quot;;
import { ChakraProvider } from &quot;@chakra-ui/react&quot;;
import { extendTheme } from &quot;@chakra-ui/react&quot;;

const theme = extendTheme({
  fonts: {
    body: &quot;montserrat, sans-serif&quot;,
  },
  textStyles: {
    h1: {
      fontSize: &quot;60px&quot;,
      fontWeight: &quot;bold&quot;,
    },
  },
});

export default function MyApp({ Component, pageProps }: AppProps) {
  return (
    &lt;ChakraProvider theme={theme}&gt;
      &lt;Component {...pageProps} /&gt;
    &lt;/ChakraProvider&gt;
  );
}
</code></pre>
<p>This is the navBar component:</p>
<pre><code>import { Box, Button, Flex, Image, Text } from &quot;@chakra-ui/react&quot;;
import SearchBar from &quot;../SearchBar/SearchBar&quot;;
const NavBar = () =&gt; {
  return (
    &lt;Flex
      bg=&quot;#f00&quot;
      h={600}
      w=&quot;100%&quot;
      bgGradient=&quot;linear(to-r, green.200, pink.500)&quot;
      overflow={&quot;hidden&quot;}
      position=&quot;relative&quot;
      flexDirection={&quot;column&quot;}
    &gt;
      &lt;Flex //nav bar
        w={&quot;100%&quot;}
        h={100}
        alignItems=&quot;center&quot;
        justifyContent=&quot;flex-end&quot;
      &gt;
        &lt;Flex // Login button container
          cursor=&quot;pointer&quot;
          alignItems={&quot;center&quot;}
          justifyContent=&quot;center&quot;
          borderRadius={10}
          padding={1}
          marginRight={450}
        &gt;
          &lt;Button //login button
            variant=&quot;solid&quot;
            colorScheme=&quot;pink&quot;
            isLoading={false}
            h={50}
            w={100}
            fontSize={25}
            fontWeight={700}
          &gt;
            Login
          &lt;/Button&gt;
        &lt;/Flex&gt;
        &lt;Text
          fontSize={25}
          fontWeight={800}
          color=&quot;white&quot;
          cursor=&quot;pointer&quot;
          marginRight={70}
        &gt;
          Help
        &lt;/Text&gt;
        &lt;Text
          fontSize={25}
          fontWeight={800}
          color=&quot;white&quot;
          cursor=&quot;pointer&quot;
          marginRight={70}
        &gt;
          About us
        &lt;/Text&gt;
        &lt;SearchBar /&gt;
      &lt;/Flex&gt;
      &lt;Box //container of &quot;more than tickets&quot;
        w={800}
        h={400}
        position=&quot;absolute&quot;
        left=&quot;0&quot;
        bottom=&quot;0&quot;
        marginLeft={50}
        marginBottom={50}
        borderRadius={100}
        overflow=&quot;hidden&quot;
        bg=&quot;rgb(167, 138, 173)&quot;
      &gt;
        &lt;Box&gt;
          &lt;Text // text &quot;more than tickets&quot;
            fontSize={40}
            fontWeight={800}
            color=&quot;white&quot;
            marginLeft={90}
            marginTop={30}
          &gt;
            More than just tickets.
          &lt;/Text&gt;
          &lt;Text marginLeft={90} fontSize={20} color=&quot;white&quot; fontWeight={600}&gt;
            Purchase your NFT ticket today, hold it forever
          &lt;/Text&gt;
        &lt;/Box&gt;
        &lt;Image src={&quot;/wave.svg&quot;} position=&quot;absolute&quot; bottom={0} /&gt;
      &lt;/Box&gt;
      &lt;Image //svg of people cheering
        src=&quot;/crowd3.svg&quot;
        alt=&quot;crowd3&quot;
        position={&quot;absolute&quot;}
        right={0}
        bottom={-320}
        w={800}
      /&gt;
      &lt;Image // second svg of people cheering
        src=&quot;/crowd2.svg&quot;
        alt=&quot;crowd2&quot;
        position={&quot;absolute&quot;}
        right={800}
        bottom={-350}
        w={300}
      /&gt;
    &lt;/Flex&gt;
  );
};
export default NavBar;
</code></pre>
",https://stackoverflow.com/questions/71686137/unit-testing-on-nextjs-chakra-ui-project,"['reactjs', 'next.js', 'chakra-ui']",1256,True,2,1
React Navigation Unit Testing Components with useRoute(),"<p>I have a component</p>
<pre><code>export function Component() {
  const route = useRoute&lt;RouteProp&lt;StackParamList&gt;&gt;();
  const amount = route.params.amount

  return (&lt;View&gt; &lt;Text&gt;{amount} is now&lt;/Text&gt;&lt;/View&gt;)
}
</code></pre>
<p>and my test is very simple but it fails, I am just checking if the text is rendered.</p>
<pre><code>test('should display amount', () =&gt; {
  const screen = renderWithWrapper(
    &lt;Navigation&gt;
     &lt;Component /&gt;
    &lt;/Navigation&gt;
  ) 
 expect(screen.queryByText(/is now/))
})
</code></pre>
<p>The code fails here <code>const amount = route.params.amount</code> says TypeError: Cannot read properties of undefined (. reading params).</p>
<p>I guess my question is how do I mock the useRoute to receive the <code>amount</code> params??</p>
",https://stackoverflow.com/questions/71262968/react-navigation-unit-testing-components-with-useroute,"['react-native', 'react-navigation']",356,False,2,1
retry polly unit testing (xunit and moq),"<p>I have .net core weabpi (see code below). I am using polly retry policy (see policy below). I would like to unit test endpoint (getProducts) and test polly retry</p>
<p>I have found <a href=""https://github.com/App-vNext/Polly/wiki/Unit-testing-with-Polly---with-example"" rel=""nofollow noreferrer"">these examples</a> but it is not clear how to unit test endpoint and retry policy?</p>
<pre><code>services
  .AddHttpClient&lt;IProductService, ProductService&gt;()
  .AddPolicyHandler(GetRetryPolicy(3, 2)); 

static IAsyncPolicy&lt;HttpResponseMessage&gt; GetRetryPolicy(int retryCount, int breakDuration)
{
    return HttpPolicyExtensions
        .HandleTransientHttpError()
        .OrResult(msg =&gt; msg.StatusCode == System.Net.HttpStatusCode.NotFound)
        .WaitAndRetryAsync(retryCount, retryAttempt =&gt; TimeSpan.FromSeconds(Math.Pow(breakDuration,
            retryAttempt)));
}
</code></pre>
<p><strong>.Net core api:</strong></p>
<pre><code>public interface IProductService
{
    Task&lt;IEnumerable&lt;ProductResponse&gt;&gt; GetProducts(string productType);
}
</code></pre>
<pre><code>public class ProductService: IProductService
{ 
    private readonly HttpClient _httpClient;
    
    public ProductService(HttpClient httpClient)
    {
         _httpClient = httpClient;
    }
    
    public async Task&lt;IEnumerable&lt;ProductResponse&gt;&gt; GetProducts(string productType)
    {
         var response = await _httpClient.GetAsync(&quot;uri&quot;);
         ...
    }
}
</code></pre>
",https://stackoverflow.com/questions/73087890/retry-polly-unit-testing-xunit-and-moq,"['c#', 'unit-testing', 'asp.net-core', 'dotnet-httpclient', 'polly']",696,True,2,1
Angular Unit Testing: Observable not returning results,"<p>I'm working on an old Angular app and trying to unit test that the functions work as expected.</p>
<p>I'm simply trying to test that a function returns the correct http request but the test isn't able to read the observable.</p>
<pre><code>import {HttpClient} from '@angular/common/http';

@Injectable()
export class MyService {
  constructor(private http: HttpClient) {}

  getUrl() {
     //lots of logic to determine which url to get

     return this.http.put(url, null, { headers: requestHeaders, withCredentials: true 
     }).pipe(
      map((response: any) =&gt; {
        return response;
     }));
  }

}
</code></pre>
<p>Is there a way to test the result of this getUrl function?</p>
<p>If I simply log the result of this function, I get an observable.</p>
<pre><code>Observable{_isScalar: false, source: Observable{_isScalar: false, source: Observable{_isScalar: ..., source: ..., operator: ...}, operator: MapOperator{project: ..., thisArg: ...}}, operator: CatchOperator{selector: handleError(error) { ... }, caught: Observable{_isScalar: ..., source: ..., operator: ...}}}

</code></pre>
<p>And If I subscribe to this observable, nothing happens.</p>
<pre><code>let test = null;
service.getUrl().subscribe((value) =&gt; {
  test = value
});

console.log('test result', test);
</code></pre>
<p>This will log null.</p>
<p>Would appreciate any advice on how I can get the result of this function. thanks</p>
",https://stackoverflow.com/questions/71318960/angular-unit-testing-observable-not-returning-results,"['angular', 'angularjs', 'unit-testing']",368,True,1,1
Angular11 unit testing for formBuilder for valueChanges,"<p>Unable to cover search() function in unit testing.</p>
<p>I am not sure how to mock fomBuilder and FormControl.
Also the service needs to return data so how to mock it.</p>
<pre><code>ngOnInit() {
    this.search()
  }
 searchForm = this.fb.group({
    searchText: new FormControl()
  });
  subscription$: any;
  search() {
    this.subscription$ = this.searchForm.controls['searchText'].valueChanges
      .pipe(
        debounceTime(200),
        tap(() =&gt; {
          this.errorMsg = '';
          this.filteredOptions = [];
          this.isLoading = true;
        }),
        switchMap((value: string) =&gt; {
          this.toHighlight = value;
          this.searchKeyword = value;
          if (value != '' &amp;&amp; value !== undefined) {value = value.toUpperCase();  this._assetService.setSearchKey(this.toHighlight);}
          this.isLoading = true;
          return this._assetService.fetchVlmSearch(value).pipe((finalize(() =&gt; {
            this.isLoading = false;
          })))
        })
      ).subscribe((data: any) =&gt; {
        if (data.rows.length &gt; 0) {
          this.filteredOptions = data.rows;
        }
        else {
          this.errorMsg = 'No Data Found';
          this.filteredOptions = [];
          this.searchKeyword = '';
        }

      })
  }

</code></pre>
",https://stackoverflow.com/questions/73397643/angular11-unit-testing-for-formbuilder-for-valuechanges,"['angular', 'unit-testing', 'karma-jasmine']",66,False,1,0
Android unit testing for flow with emitAll,"<p>I have a function that return flow by emitAll</p>
<pre><code> fun handle(actions: MoviesActions): Flow&lt;MoviesStates&gt; = flow {
    when (actions) {
        is MoviesActions.LoadMovies -&gt; {
            emit(MoviesStates.Loading)
            emitAll(moviesUseCase.execute())
        }
    }
}
</code></pre>
<p>And this the use case function</p>
<pre><code>suspend fun execute(): Flow&lt;MoviesStates&gt; = flow {
    combine(f1, f2) { state1: MoviesStates, state2: MoviesStates -&gt;
     
          // some code
        
    }.collect {
        emit(it)
    }
}
</code></pre>
<p>No problem in testing the first emission <code>MoviesStates.Loading</code>, the problem is when I try to test the flow which return from usecase by emitAll <code>emitAll(moviesUseCase.execute())</code>, the test fails and I got this result</p>
<blockquote>
<p>java.util.NoSuchElementException: Expected at least one element</p>
</blockquote>
<p>this is my unit test</p>
<pre><code>@Test
fun testLoadMovies() = runBlocking {
    whenever(useCase.execute()).thenReturn(flow {
        MoviesStates.EmptyList
    })

    val actual = viewModel.handle(MoviesActions.LoadMovies).drop(1).first()
    val expected = MoviesStates.EmptyList

    assertEquals(actual, expected)
}
</code></pre>
<p><strong>So How can I test it correctly?</strong></p>
",https://stackoverflow.com/questions/72581606/android-unit-testing-for-flow-with-emitall,"['android', 'unit-testing', 'kotlin', 'kotlin-coroutines', 'kotlin-flow']",1277,True,1,1
php unit testing dealing with input text,"<p>I am trying to run some basic unit tests for the below code. The trouble i am facing is i am not sure how to deal with the input_text.</p>
<p>sample input_text:</p>
<p>module1,60newlinemodule2,50newlinemodule3,40</p>
<p>this is the class i would like to test:</p>
<pre><code>&lt;?php
function getMaxMin($input_text)
{
    $lines = explode(&quot;newline&quot;, $input_text);
    $module_marks=array();
    foreach ($lines as $line) {
       $line_array = explode(&quot;,&quot;, $line);
       $module_marks_array = array(&quot;module&quot;=&gt;$line_array[0], &quot;marks&quot;=&gt;$line_array[1]);
       array_push($module_marks,$module_marks_array);
    }

    usort($module_marks, function($a, $b) {
          return $b['marks'] &lt;=&gt; $a['marks'];
    });

    $maxModule = $module_marks[0]['module'] . ', ' . $module_marks[0]['marks'];
    $minModule = $module_marks[count($module_marks)-1]['module'] . ', ' . $module_marks[count($module_marks)-1]['marks'];
    $maxminModule = $maxModule . 'newline' . $minModule;

    return $maxminModule;
}
</code></pre>
<p>this is what i have so far for test:</p>
<pre><code>&lt;?php
use PHPUnit\Framework\TestCase;
require('functions.inc.php');

class TotalTest extends TestCase {

public function testgetMaxMin(){
        $this-&gt;assertSame(60, 40,  getMaxMin('m1,60newlinem2,50newlinem3,40'));
}
}
</code></pre>
<p>the actual i believe is incorrect, just unsure how to deal with input like this. Any resources or help is much apricated.</p>
",https://stackoverflow.com/questions/73431027/php-unit-testing-dealing-with-input-text,['php'],76,True,1,1
&quot;Bypassing&quot; a mock in Quarkus unit testing,"<p>I have a Quarkus project where I have most of the business logic placed in services, aka injectable beans using @ApplicationScoped annotations, where all of the CRUD operations take place. In the JAX-RS resource files themselves, the bulk of the logic is just validation, often using whole validation beans. This has meant that we needed to mock our injected services when we tested the resources, to prevent the unit tests from becoming essentially integration tests. We do this having a structure like this (example project);</p>
<p><a href=""https://i.stack.imgur.com/qAdLK.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/qAdLK.png"" alt=""enter image description here"" /></a></p>
<p>The file MockGreetingService.java in turn looks like this:</p>
<pre><code>import io.quarkus.test.Mock;

import javax.enterprise.context.ApplicationScoped;

@Mock
@ApplicationScoped
public class MockGreetingService extends GreetingService {

    @Override
    public String sayHello(String name) {
        return String.format(&quot;Hello %s, your id is %s&quot;, name, &quot;1234&quot;);
    }
}
</code></pre>
<p>Our actual project is a bit more sophisticated than this in the way that the mocks always return our DTO classes regardless of input, but the principle is the same as above. They work flawlessly for our JAX-RS resource tests. However, trying to test the actual service beans themselves means problems with this setup. I built a service test, which uses the same annotations and flow as the code below:</p>
<pre><code>import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import javax.inject.Inject;

@QuarkusTest
public class GreetingServiceTest {

    @Inject
    GreetingService greetingService;

    @Test
    void checkReturnsHello () {

        String result = greetingService.sayHello();
        System.out.println(result);
        Assertions.assertEquals(&quot;hello Martin! Your country is Italy&quot;, result);
    }
}
</code></pre>
<p>With the dependency injection in the class above, which we don't do in our resource tests, I expected Quarkus to understand that we want to use the original service in this test. How foolish of me. A simple log has shown that the mock service methods indeed still run in the latter test above.</p>
<p>Now I wonder - is it a way to disable the mock for this latter test? Preferably without having to modify or remove the mock classes, although I realize that might not be possible in the way I imagine it to be. Thanks in advance!</p>
",https://stackoverflow.com/questions/70869508/bypassing-a-mock-in-quarkus-unit-testing,"['java', 'quarkus']",877,True,1,1
Unit Testing Azure Functions With Dependency Injection,"<p>I haven't written any Azure functions in quite a long time, and thought I'd refresh myself today, but I've clearly forgotten how to write appropriate unit tests for them. I have the following Function - it picks a random quote from a list;</p>
<pre><code>public class QuoteFunction
{
    private readonly IQuoteBank _repository;

    public QuoteFunction(IQuoteBank repository)
    {
        _repository = repository;
    }

    [FunctionName(&quot;GetQuote&quot;)]
    public async Task&lt;IActionResult&gt; Run(
        [HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;, &quot;post&quot;, Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation(&quot;C# HTTP trigger function processed a request.&quot;);
        Quote quote = _repository.getQuote();
        return new OkObjectResult(quote);
    }
}
</code></pre>
<p>and it uses dependency injection to obtain the list of quotes - I have the following in Startup;</p>
<pre><code>public override void Configure(IFunctionsHostBuilder builder)
{
    builder.Services.AddSingleton&lt;IQuoteBank, QuoteBank&gt;();
    builder.Services.AddLogging();
}
</code></pre>
<p>which is injected into the constructor of the Function. as shown in the first snippet.</p>
<p>What I am struggling with is how I can use Moq to force the quote (which is randomly selected) to be consistent. I know I can mock the Interface IQuoteBank - but there is no where I can pass this mock object into the Run method.</p>
<p>So what I want to know is how I can pass a mock object to make the same quote be produced for unit testing? Has anyone done anything like this before? any examples in github?</p>
<p>I'm pretty sure I did a few years ago, just cant remember at all.</p>
",https://stackoverflow.com/questions/74817239/unit-testing-azure-functions-with-dependency-injection,"['c#', 'azure', 'unit-testing', 'azure-functions', 'moq']",313,True,1,1
Usage of eq() method in unit testing,"<p>I am writing unit test case for update method for book.</p>
<pre class=""lang-java prettyprint-override""><code>@Test
void testUpdateBook() {
    //initializing the bookId here
    givenBookId();
    //initializing the book here 
    givenBook();
    givenMock();
    //call the updateBook method 
    whenUpdateBookRequested();
    thenVerifyBook();
}

givenMock() {
   when(bookRepository.updateBook(bookId,any()).thenReturn(Optional.ofNullable(expectedBook));
}
</code></pre>
<p>Every other method is working fine but givenMock() is producing error:</p>
<p><code>Invalid use of argument matchers. 2 matchers expected, 1 recorded</code></p>
<p>And if I write the same method like below, then test is running successfully but I am not able to understand the meaning of eq(). Can someone please explain the difference between the previous and the modified method?</p>
<pre class=""lang-java prettyprint-override""><code>givenMock(){
    when(bookRepository.updateBook(eq(bookId),any()).thenReturn(Optional.ofNullable(expectedBook));
}
</code></pre>
",https://stackoverflow.com/questions/73106150/usage-of-eq-method-in-unit-testing,"['java', 'unit-testing', 'java-8', 'mockito', 'junit5']",628,True,1,2
Mapbox Unit Testing - Failed to initialize WebGL,"<p>I'm currently using Mapbox for a React application and I'm trying to perform unit testing but it doesn't seem to work. I've set the Mapbox testMode to true and it still gives me an error saying:</p>
<pre><code>Error: Failed to initialize WebGL.
at new Map (C:\Users\...\node_modules\mapbox-gl\dist\mapbox-gl.js:35:427889)
</code></pre>
<p>The following snippet is how we generate the mapbox component which also receives a test variable to set the testMode.</p>
<pre><code>const MapBox = (props: MapBoxProps) =&gt; {
  const { floorPlan, isTest } = props;
  const { width } = useWindowDimensions();
  const mapContainer = useRef(null);
  const map = useRef(null);
  const [lng, setLng] = useState(48);
  const [lat, setLat] = useState(25);
  const [zoom, setZoom] = useState(1.8);

  const createMapbox = () =&gt; {
    if (!isTest) {
      mapboxgl.accessToken = appConfig.MAPBOX_TOKEN;
    }
    const mb = new mapboxgl.Map({
      attributionControl: false,
      container: mapContainer.current,
      testMode: isTest,
      style: {
        version: 8,
        sources: {},
        layers: [
          {
            id: &quot;background&quot;,
            type: &quot;background&quot;,
            paint: {
              &quot;background-color&quot;: &quot;white&quot;,
            },
          },
        ],
      },
      center: [lng, lat],
      zoom: zoom,
      maxZoom: 6,
      dragRotate: false,
    });
    mb.addControl(new mapboxgl.NavigationControl({ showCompass: false }));
    return mb;
  };
  return &lt;div
        data-cr=&quot;mapbox-container&quot;
        ref={mapContainer}
      /&gt;;
}
</code></pre>
<p>And the code for testing our <strong>CustomMapBox</strong> component is as follows:</p>
<pre><code>const renderMapBox = () =&gt; {
  return render(&lt;CustomMapBox floorPlan={mockedFloorPlan} isTest={true} /&gt;);
};

describe(&quot;MapBox&quot;, () =&gt; {
  it(&quot;renders without error and two floors&quot;, () =&gt; {
    renderMapBox();
  });
}
</code></pre>
<p>I've tried to:</p>
<ul>
<li>Change versions</li>
<li>Change jest configurations</li>
<li>Set mapbox testMode to true</li>
</ul>
<p>And nothing seems to work.</p>
<p>Versions:</p>
<pre><code>&quot;mapbox-gl&quot;: &quot;^2.8.2&quot;,
&quot;react&quot;: &quot;^17.0.2&quot;,
&quot;react-dom&quot;: &quot;^17.0.2&quot;,
&quot;ts-jest&quot;: &quot;^27.0.7&quot;,
&quot;jest&quot;: &quot;^27.3.1&quot;,
</code></pre>
<p>I'd really appreciate if someone could help me.
Best regards,
Daniel</p>
",https://stackoverflow.com/questions/72628355/mapbox-unit-testing-failed-to-initialize-webgl,"['javascript', 'reactjs', 'typescript', 'unit-testing', 'mapbox']",859,False,1,1
Unit testing a plugin in Nuxt 3,"<p>I've created a relatively simple plugin which is responsible for making an api call, and receives a base URL to prepend to the endpoint, following the instructions here: <a href=""https://v3.nuxtjs.org/api/composables/use-nuxt-app/"" rel=""nofollow noreferrer"">https://v3.nuxtjs.org/api/composables/use-nuxt-app/</a></p>
<p>My plugin:</p>
<pre><code>import { $fetch } from &quot;ohmyfetch&quot;;
import {useRuntimeConfig} from &quot;#app&quot;;

export default defineNuxtPlugin(nuxtApp =&gt; {
    const config = useRuntimeConfig();
    nuxtApp.provide('apiFetch', $fetch.create({baseURL: config.BASE_URL}))
});
</code></pre>
<p>I want to use Jest to unit test this plugin, just to follow best practices and ensure that any changes in the future won't affect it. For context, the way this is going to be used in a component is</p>
<p><code>const posts = await useNuxtApp().$apiFetch('/api/prints');</code></p>
<p>I have no idea how to replicate this in my test file, as all I need to do is call the plugin with some params, and check that fetch is called with the params I would expect - or better still, mock some data for the api endpoint, and check that what's expected is returned.</p>
<p>I'm having problems understanding how to inject the plugin into nuxt and then call it. Older versions of Jest used <code>createLocalVue</code>, but I'm unsure how to do this in Nuxt 3.</p>
<p>This is all I've got so far, which gives me this error: <code>TypeError: (0 , _app_1.useNuxtApp) is not a function </code></p>
<p>I'm assuming I'll have to do some mocking somewhere, but am unsure how or of what.</p>
<pre><code>import { useNuxtApp } from &quot;#app&quot;;

it('calls fetch with correct endpoint', async() =&gt; {
    await useNuxtApp().$apiFetch
});
</code></pre>
<p>Any help would be greatly appreciated!</p>
",https://stackoverflow.com/questions/73567095/unit-testing-a-plugin-in-nuxt-3,"['unit-testing', 'jestjs', 'nuxt.js', 'nuxtjs3']",692,False,1,0
Unit testing with AWS Cognito and GraphQL,"<p>I'm currently writing tests for my software but got stuck at the point.
I try to get data from my db with a normal GraphQL Query but my endpoint is first checking, if the idToken within the header is valid.
For the user handling I'm using AWS Cognito but couldn't find a good way to mock the login to retrieve the valid token to query and mutate the data within various endpoints.</p>
<p>Any idea how to handle this case?</p>
<p>Here is my code from the graphene docs (<a href=""https://docs.graphene-python.org/projects/django/en/latest/testing/"" rel=""nofollow noreferrer"">https://docs.graphene-python.org/projects/django/en/latest/testing/</a>):</p>
<pre><code># Create a fixture using the graphql_query helper and `client` fixture from `pytest-django`.
import json
import pytest
from graphene_django.utils.testing import graphql_query

# https://docs.graphene-python.org/projects/django/en/latest/testing/


@pytest.fixture
def client_query(client):
  def func(*args, **kwargs):
    return graphql_query(*args, **kwargs, client=client)

  return func

# Test you query using the client_query fixture
def test_some_query(client_query):
   response = client_query(
    '''
    query GetAllProjectConfig{
    getAllProjectConfig{
        project{
            id
            slug
            name
        }
        config{
            id
        }
    }
    }
    ''',
)

content = json.loads(response.content)
assert 'errors' not in content
</code></pre>
",https://stackoverflow.com/questions/73078632/unit-testing-with-aws-cognito-and-graphql,"['django', 'graphql', 'pytest', 'amazon-cognito']",146,False,1,1
unit testing is failing for ngrx-effect?,"<p>Unit test is failing for ngrx effect.</p>
<p><strong>Effect method code:</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>  addNewLedgerAccountRequest$ = createEffect(() =&gt;
  this.actions$.pipe(
    ofType(AddNewLedgerAccountActions.AddNewLedgerAccountActionTypes.ADD_NEW_LEDGER_ACCOUNT_REQUEST),
    withLatestFrom(this.addNewLedgerAccountStore$.select(AddNewLedgerAccountSelectors.ledgerAccountFormSelector)),
    switchMap(([, addNewLedgerAccountForm]: [Action, LedgerAccountFormDef]) =&gt; {
      return this.addNewLedgerAccountService.addNewLedgerAccount$(addNewLedgerAccountForm).pipe(
        map((ledgerAccount: LedgerAccountDef) =&gt; new AddNewLedgerAccountActions.AddNewLedgerAccountSuccess({ ledgerAccount })),
        catchError(() =&gt; of(new AddNewLedgerAccountActions.AddNewLedgerAccountFailure()))
      );
    })
  )
);</code></pre>
</div>
</div>
</p>
<p><strong>Effect test method code:</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>describe(`AddNewLedgerRequest$`, () =&gt; {
    it(`should dispatch AddNewLedgerAccountRequest action if service succeeds`, () =&gt; {
      const action = new fromActions.AddNewLedgerAccountRequest();
      actions$ = hot('-a', { a: action });
      const outcome = new fromActions.AddNewLedgerAccountSuccess({ ledgerAccount: mockedLedgerAccount });
      const expected$ = cold('--b', { b: outcome });
      const result$ = cold( '-b', { b: mockedLedgerAccount } );
      addNewLedgerAccountSpy.mockReturnValue( result$ );
      expect( effects.addNewLedgerAccountRequest$ ).toBeObservable( expected$ );
      expect( addNewLedgerAccountSpy ).toHaveBeenCalledWith( mockedLedgerAccountForm );
    } );
  } );</code></pre>
</div>
</div>
</p>
<p><strong>Result:</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>        Expected: --b,
        Received: --?,

        Expected:
        [{""frame"":20,""notification"":{""kind"":""N"",""value"":{""payload"":{""ledgerAccount"":{""id"":""1234"",""name"":""TestLedger"",""number"":""3344"",""type"":""12"",""taxRate"":""12"",""taxRatePercent"":""12""}},""type"":""[point - CONFIGURATION WIZARD] Add new ledger account - Success""},""hasValue"":true}}]

        Received:
        [{""frame"":20,""notification"":{""kind"":""N"",""value"":{""payload"":{""ledgerAccount"":{""id"":""1234"",""name"":""TestLedger"",""number"":""3344"",""type"":""12"",""taxRate"":""12"",""taxRatePercent"":""12""}},""type"":""[point - CONFIGURATION WIZARD] Add new ledger account - Success""}}}],

      86 |       const result$ = cold( '-b', { b: mockedLedgerAccount } );
      87 |       addNewLedgerAccountSpy.mockReturnValue( result$ );
    &gt; 88 |       expect( effects.addNewLedgerAccountRequest$ ).toBeObservable( expected$ );
         |                                                     ^
      89 |       expect( addNewLedgerAccountSpy ).toHaveBeenCalledWith( mockedLedgerAccountForm );
      90 |     } );</code></pre>
</div>
</div>
</p>
<p>The only difference is Expected has ,&quot;hasValue&quot;:true and Received is missing it. Please let me know how to solve it. Thank you,</p>
",https://stackoverflow.com/questions/72560295/unit-testing-is-failing-for-ngrx-effect,"['angular', 'ngrx']",173,True,1,1
Unit testing hibernate search with elastic backend,"<p>We are using hibernate search and its orm mapper together with JPA for our Java based search services. The challenge I'm facing is to write unit tests, such as:</p>
<ul>
<li>Insert JPA entity car &quot;tesla v3&quot;</li>
<li>Search for &quot;tesla&quot;</li>
<li>Validate the JPA entity &quot;tesla v3&quot; to be contained in the result set of hibernate search</li>
</ul>
<p>To do so, my first thought was to run some kind of in-memory, single node elastic cluster, test against this cluster, and tear it down afterwards. But it seems that there exists no such thing.</p>
<p>The official documentation (<a href=""https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/"" rel=""nofollow noreferrer"">https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/</a>) does not explain unit testing for hibernate search.</p>
<p>Now I'm curious how you test your hibernate search implementations. Do I need a test instance? Do you rename your indices for testing and clear it before each test run?</p>
<p>I'm grateful for every input!</p>
",https://stackoverflow.com/questions/72430785/unit-testing-hibernate-search-with-elastic-backend,"['java', 'elasticsearch', 'junit', 'hibernate-search']",334,True,1,1
Unit Testing sqlboiler with sqlmock failing select,"<p>I'm trying to mock a method written with sqlboiler but I'm having massive trouble building the mock-query.
The model I'm trying to mock looks like this:</p>
<pre><code>type Course struct {
ID int, Name string, Description null.String, EnrollKey string, ForumID int, 
CreatedAt null.Time, UpdatedAt null.Time, DeletedAt null.Time, 
R *courseR, L courseL
}
</code></pre>
<p>For simplicity I want to test the GetCourse-method</p>
<pre><code>func (p *PublicController) GetCourse(id int) (*models.Course, error) {

    c, err := models.FindCourse(context.Background(), p.Database, id)
    if err != nil {
        return nil, err
    }
    return c, nil
}
</code></pre>
<p>with this test</p>
<pre><code>func TestGetCourse(t *testing.T) {
    db, mock, err := sqlmock.New()
    if err != nil {
        t.Fatalf(&quot;an error '%s' was not expected&quot;, err)
    }

    oldDB := boil.GetDB()
    defer func() {
        db.Close()
        boil.SetDB(oldDB)
    }()
    boil.SetDB(db)

    ctrl := &amp;PublicController{db}

    rows := sqlmock.NewRows([]string{&quot;ID&quot;, &quot;Name&quot;, &quot;Description&quot;, &quot;EnrollKey&quot;, &quot;ForumID&quot;}).AddRow(42, &quot;Testkurs&quot;, &quot;12345&quot;, 33)

    query := regexp.QuoteMeta(&quot;SELECT ID, Name, Description, EnrollKey, ForumID FROM courses WHERE ID = ?&quot;)
    //mockQuery := regexp.QuoteMeta(&quot;SELECT * FROM `courses` WHERE (`course AND (`courses`.deleted_at is null) LIMIT 1;&quot;)

    mock.ExpectQuery(query).WithArgs(42).WillReturnRows(rows)

    course, err := ctrl.GetCourse(42)
    assert.NotNil(t, course)
    assert.NoError(t, err)
}
</code></pre>
<p>But running this test only returns</p>
<blockquote>
<p>Query: could not match actual sql: &quot;select * from <code>course</code> where <code>id</code>=? and <code>deleted_at</code> is null&quot; with expected regexp &quot;SELECT ID, Name, Description, EnrollKey, ForumID FROM courses WHERE ID = ?&quot;
bind failed to execute query
And I can't really find out how to construct it correctly.
How do I correctly mock the sqlboiler-query for running unit tests?</p>
</blockquote>
<p><strong>UPDATE</strong>
I managed to solve this by using different parameters in AddRow()</p>
<pre><code>.AddRow(c.ID, c.Name, null.String{}, c.EnrollKey, c.ForumID)
</code></pre>
<p>and building the query differently</p>
<pre><code>query := regexp.QuoteMeta(&quot;select * from `course` where `id`=? and `deleted_at` is null&quot;)
</code></pre>
<p>Now my issue is that in contrast to this method the others have a very large complexity in comparison with a large amount of complex queries (mainly insert-operations). From my understanding, sqlboiler-tests needs to mimic every single interaction made with the database.</p>
<p>How do I extract the necessary queries for the large amount of database interactions? I solved my problem by just using the &quot;actual sql-query&quot; instead of the previously used one but I'm afraid this procedure is the opposite of efficient testing.</p>
",https://stackoverflow.com/questions/72492208/unit-testing-sqlboiler-with-sqlmock-failing-select,"['unit-testing', 'go', 'mocking', 'go-sqlmock', 'sqlboiler']",615,False,1,0
Unit Testing with Jest for Strapi v4,"<p>I am trying to perform unit tests with Jest for the new version of Strapi, v4 which was just released a couple of weeks ago. In accordance with their documentation, the old guide for unit testing no longer runs as expected. I have, however, modified the code to work to a certain extent. Currently I have the following:</p>
<p><code>./test/helpers/strapi.js</code>:</p>
<pre class=""lang-js prettyprint-override""><code>const Strapi = require(&quot;@strapi/strapi&quot;);

let instance;

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

    await instance.server.mount();
  }
  return instance;
}

module.exports = {
  setupStrapi
};
</code></pre>
<p><code>./tests/app.test.js</code>:</p>
<pre class=""lang-js prettyprint-override""><code>const fs = require(&quot;fs&quot;);
const { setupStrapi } = require(&quot;./helpers/strapi&quot;);

beforeAll(async () =&gt; {
  await setupStrapi();
});

afterAll(async () =&gt; {
  const dbSettings = strapi.config.get(&quot;database.connection.connection&quot;);

  //close server to release the db-file
  await strapi.server.destroy();

  //DATABASE_FILENAME=.tmp/test.db

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

    if (fs.existsSync(tmpDbFile)) {
      fs.unlinkSync(tmpDbFile);
    }
  }
});

it(&quot;should return hello world&quot;, async () =&gt; {
  await request(strapi.server.httpServer).get(&quot;/api/hello&quot;).expect(200); // Expect response http code 200
});

</code></pre>
<p><code>./config/env/test/database.js</code></p>
<pre class=""lang-js prettyprint-override""><code>const path = require(&quot;path&quot;);

module.exports = ({ env }) =&gt; ({
  connection: {
    client: &quot;sqlite&quot;,
    connection: {
      filename: path.join(
        __dirname,
        &quot;../../../&quot;,
        env(&quot;DATABASE_FILENAME&quot;, &quot;.tmp/test.db&quot;)
      ),
    },
    useNullAsDefault: true,
  },
});

</code></pre>
<p>The route <code>/api/hello</code> is a custom API endpoint. This works perfectly when running <code>strapi develop</code>, and all permissions are set correctly.</p>
<p>The tests run, but every endpoint that is not <code>/</code> or <code>/admin</code> returns <code>403 Forbidden</code>, meaning there is a problem with the permissions. It would seem that the database file <code>.tmp/data.db</code> (used in development) is not replicated correctly in <code>.tmp/test.db</code>. In other words, this is close to working, but the permissions for API endpoints are not set correctly.</p>
<p>I have been searching through StackOverflow and the Stapi Forums over the past few days but to no avail. I would greatly appreciate some pointers as to how to fix this :)</p>
",https://stackoverflow.com/questions/70974645/unit-testing-with-jest-for-strapi-v4,"['javascript', 'node.js', 'unit-testing', 'jestjs', 'strapi']",1083,True,1,2
Unit testing saga in nestjs cqrs pattern,"<p>We are writing unit test using jest for application and we want to cover saga in unit test. However, we are struggling to unit test saga.</p>
<p>While writing unit test, we are publishing InventoryEvent in inventory.saga.spec.ts file and expecting inventory() in inventory.saga.ts to be called but this published event through test file is not received by saga whereas when we publish the same event through application then event is received in saga.</p>
<p>Please help my to identify the issue why event published through test file is not received by saga.</p>
<p>The current flow of application is</p>
<ol>
<li>inventory handler publish InventoryEvent</li>
<li>saga is acting as event listeners and listen for InventoryEvent and it invokes InventoryCacheCommand</li>
</ol>
<p>Below are the code snippet</p>
<p>inventory.handler.ts</p>
<pre><code>await this.eventBus.publish(new InventoryEvent(inventoryData));
</code></pre>
<p>inventory.event.ts</p>
<pre><code>import { IEvent } from '@nestjs/cqrs';
import { InventoryStatusInterface } from '../../../interface/inventory.interface';

export class InventoryEvent implements IEvent {
  constructor(public readonly inventoryData: InventoryStatusInterface) {}
}
</code></pre>
<p>inventory.saga.ts</p>
<pre><code>import { Injectable } from '@nestjs/common';
import { ICommand, ofType, Saga } from '@nestjs/cqrs';
import { map, Observable } from 'rxjs'
import { createLog } from '../../infrastructure/service/utils/logger';
import { InventoryCacheCommand } from '../commands/impl/inventory-cache.command';
import { InventoryEvent } from '../events/impl/inventory.event';
@Injectable()
export class InventorySaga {

private logger = createLog(InventorySaga.name);

@Saga()
inventory = (events$: Observable&lt;any&gt;): Observable&lt;ICommand&gt; =&gt; {  
    return events$.pipe(
        ofType(InventoryEvent),
        map((event: InventoryEvent) =&gt; {
            this.logger.info('received inventory event to upsert inventory cache: ',event.inventoryData);
            return new InventoryCacheCommand(event.inventoryData);
        })
    );
}
}
</code></pre>
<p>inventory.saga.spec.ts</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { InventorySaga } from './inventory.saga';
import { InventoryEvent } from '../events/impl/inventory.event';
import { CommandBus, EventBus } from '@nestjs/cqrs';
import { InventoryCacheCommand } from '../commands/impl/inventory-cache.command';
import { Observable } from 'rxjs';
jest.mock('../commands/impl/inventory-cache.command')

describe('InventorySaga', () =&gt; {
  let saga: InventorySaga;
  let eventBus: EventBus
  beforeEach(async () =&gt; {

    const module: TestingModule = await Test.createTestingModule({
      providers: [
        InventorySaga,
        EventBus,
        CommandBus
      ],
    }).compile();

    saga = module.get&lt;InventorySaga&gt;(InventorySaga);
    eventBus = module.get&lt;EventBus&gt;(EventBus)
 });

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

   it('should publish InventoryEvent', async () =&gt; {

     const inventoryData = [
       {
         sku: 'TH4344-43-L',
         qty: 3,
       },
       {
         sku: 'TH4344-43-S',
         qty: 55,
       },
       {
         sku: 'TH4344-43-XL',
         qty: 55,
       },
     ];
     const spy = jest.spyOn(saga, 'inventory');
  
     await eventBus.publish(new InventoryEvent(inventoryData));
  
     expect(spy).toBeCalled()
   })
 })
});
</code></pre>
",https://stackoverflow.com/questions/74002680/unit-testing-saga-in-nestjs-cqrs-pattern,"['javascript', 'unit-testing', 'jestjs', 'nestjs', 'saga']",820,True,1,1
Unit testing an Exec stdout event NodeJS,"<p>I have below code.</p>
<pre><code>//utils.js
const cp = require('child_process');

module.exports.execuateBashCommand = ()=&gt; {
    return new Promise((resolve, reject)=&gt; {
        try {
            cp.exec('bash bash.sh').stdout.on('data', (response)=&gt; {
                if (response.toString().indexOf(&quot;Success&quot;) &gt; -1) {
                    //Some business logic
                    const result = &quot;working&quot;;
                    resolve(result);
                }
            });
        } catch (error) {
            console.log(&quot;Error&quot;, error);
            reject(error);
        }
    })
}
</code></pre>
<p>Here, there is an anonymous function that gets fired when a data event is emitted by stdout of exec process. I have no control over the output of bash.js, the desired response may take 5 to 10 seconds. Also I cannot add a timer and wait for this event to fire as I have mocked the exec response using sinon. So there is no real call to bash.js. So how can I emit this event manually and see if the business logic get computed? I am new to unit testing in Javascript. Currently I am using mocha and sinon for my unit testing requirements.</p>
<p>I have following test case, but it is not working as expected..</p>
<pre><code>//utils.test.js
 it(&quot;1. test case&quot;, (done)=&gt; {
        try {
            const mockStdout = new events.EventEmitter();
            mockStdout.on('data', ()=&gt; {
                return &quot;Success&quot;;
            });
            mockStdout.emit('data');
            sandbox.stub(cp.exec('test test'), 'stdout').returns(mockStdout);
            utils.execuateBashCommand().then((result)=&gt; {
                assert(data, &quot;working&quot;);
                done();
            });
        } catch (error) {
            console.log(&quot;Error in test cases: &quot;, error);
        }
    })
</code></pre>
<p>Please advice.</p>
",https://stackoverflow.com/questions/71570247/unit-testing-an-exec-stdout-event-nodejs,"['javascript', 'node.js', 'events', 'chai', 'sinon']",318,True,0,1
Vue unit testing: router path is always /,"<p>The router's <code>currentRoute.path</code> should be <code>/SignUpUser</code> as that is the page I import and it's route is <code>/SignUpUser</code>. However, the <code>path</code> turns out to be <code>root</code>.</p>
<p>This is the code:</p>
<pre class=""lang-js prettyprint-override""><code>import SignUpUser from '@/components/SignForms/SignUpUser.vue'

const localVue = createLocalVue()
localVue.use(VueRouter)


  it('does not route to root when sign up is interrupted because validations fail', async () =&gt; {
    let router = new VueRouter()
    const wrapper = mount(SignUpUser, {
      localVue,
      router,
    })

    console.log(router.currentRoute.path) // should be '/SignUpUser' but is '/'

    let usernameField = wrapper.findComponent('#username');
    usernameField.setValue('Avi')

    let submitBtn = wrapper.findComponent('button')

    await submitBtn.trigger('click');

    expect(router.currentRoute.path).toBe('/SignUpUser')
  })
</code></pre>
<p>Moreover, <code>expect(router.currentRoute.path).toBe('/SignUpUser')</code> fails because the path is still <code>/</code>. I am unsure what is happening and could really use some help.</p>
",https://stackoverflow.com/questions/72372627/vue-unit-testing-router-path-is-always,"['javascript', 'vue.js', 'unit-testing', 'jestjs']",192,False,0,1
Unit testing viewModel that uses StateFlow and Coroutines,"<pre><code>Kotlin 1.4.21
</code></pre>
<p>I have a very simple ViewModel that uses coroutine and stateFlow. However, the unit test will fail as the stateFlow doesn't seem to get updated.</p>
<p>I think its because the test will finish before the <code>stateFlow</code> is updated.</p>
<p><code>expected not to be empty</code></p>
<p>This is my ViewModel under test</p>
<pre><code>class TrendingSearchViewModel @Inject constructor(
    private val loadTrendingSearchUseCase: LoadTrendingSearchUseCase,
    private val coroutineDispatcher: CoroutineDispatcherProvider
) : ViewModel() {

    private val trendingSearchMutableStateFlow = MutableStateFlow&lt;List&lt;String&gt;&gt;(emptyList())
    val trendingSearchStateFlow = trendingSearchMutableStateFlow.asStateFlow()

    fun getTrendingSearch() {
        viewModelScope.launch(coroutineDispatcher.io()) {
            try {
                trendingSearchMutableStateFlow.value = loadTrendingSearchUseCase.execute()
            } catch (exception: Exception) {
                Timber.e(exception, &quot;trending ${exception.localizedMessage}&quot;)
            }
        }
    }
}
</code></pre>
<p>This is my actual test class, I have tried different things to get it to work</p>
<pre><code>class TrendingSearchViewModelTest {
    private val loadTrendingSearchUseCase: LoadTrendingSearchUseCase = mock()
    private val coroutineDispatcherProvider = CoroutineDispatcherProviderImp()
    private lateinit var trendingSearchViewModel: TrendingSearchViewModel

    @Before
    fun setUp() {
        trendingSearchViewModel = TrendingSearchViewModel(
            loadTrendingSearchUseCase,
            coroutineDispatcherProvider
        )
    }

    @Test
    fun `should get trending search suggestions`() {
        runBlocking {
            // Arrange
            val trending1 = UUID.randomUUID().toString()
            val trending2 = UUID.randomUUID().toString()
            val trending3 = UUID.randomUUID().toString()

            whenever(loadTrendingSearchUseCase.execute()).thenReturn(listOf(trending1, trending2, trending3))

            val job = launch {
                trendingSearchViewModel.trendingSearchStateFlow.value
            }

            // Act
            trendingSearchViewModel.getTrendingSearch()

            // Assert
            val result = trendingSearchViewModel.trendingSearchStateFlow.value
            assertThat(result).isNotEmpty()

            job.cancel()
        }
    }
}
</code></pre>
<p>This is the usecase I am mocking in the test:</p>
<pre><code>class LoadTrendingSearchUseCaseImp @Inject constructor(
    private val searchCriteriaProvider: SearchCriteriaProvider,
    private val coroutineDispatcherProvider: CoroutineDispatcherProvider
) : LoadTrendingSearchUseCase {

    override suspend fun execute(): List&lt;String&gt; {
        return withContext(coroutineDispatcherProvider.io()) {
            searchCriteriaProvider.provideTrendingSearch().trendingSearches
        }
    }
}
</code></pre>
<p>Just in case its needed this is my interface:</p>
<pre><code>interface CoroutineDispatcherProvider {
    fun io(): CoroutineDispatcher = Dispatchers.IO
    fun default(): CoroutineDispatcher = Dispatchers.Default
    fun main(): CoroutineDispatcher = Dispatchers.Main
    fun immediate(): CoroutineDispatcher = Dispatchers.Main.immediate
    fun unconfined(): CoroutineDispatcher = Dispatchers.Unconfined
}

class CoroutineDispatcherProviderImp @Inject constructor() : CoroutineDispatcherProvider
</code></pre>
",https://stackoverflow.com/questions/71406113/unit-testing-viewmodel-that-uses-stateflow-and-coroutines,"['android', 'unit-testing', 'kotlin', 'kotlin-coroutines', 'kotlin-stateflow']",3963,True,7,2
Springboot: Unit testing with H2 emulating postgres,"<p>I'm trying to test queries against H2 emulating Postgress.</p>
<p>The unit test look as follow:</p>
<p>Unit test</p>
<pre><code>@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = {MyRepository.class})
@Sql(scripts = &quot;classpath:schema-test.sql&quot;, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
//@TestPropertySource(&quot;classpath:application-test.properties&quot;)
public class ImportIdTest {

    @Autowired
    private MyRepository repo;


    @Test
    public void importIdSeqTest() {
        assertEquals(1, repo.getNexImportId());
        assertEquals(2, repo.getNexImportId());
    }
}
</code></pre>
<p>And the test application properties as follow:</p>
<p>application-test.properties</p>
<pre><code>spring.datasource.url=jdbc:h2:mem:mydatabase;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS myschema
spring.datasource.username=sa
spring.datasource.password=password
spring.datasource.driverClassName=org.h2.Driver
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQL95Dialect
spring.datasource.platform=test
spring.jpa.hibernate.ddl-auto= none
spring.jpa.defer-datasource-initialization=true
</code></pre>
<p>pom.xml</p>
<pre class=""lang-xml prettyprint-override""><code>        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;com.h2database&lt;/groupId&gt;
            &lt;artifactId&gt;h2&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
        &lt;/dependency&gt;
</code></pre>
<p>While running the unit test, the error I'm getting is:</p>
<p><code>No qualifying bean of type 'cfoo.bar.MyRepository'</code></p>
<p>while <code>@ContextConfiguration(classes = {MyRepository.class})</code> as been added to the unit test.</p>
<p>What am I doing wrong ?</p>
<p>EDIT</p>
<p>As per comment, in the project code :</p>
<p>Repository declaration:</p>
<pre><code>@Repository
public interface MyRepository extends JpaRepository&lt;MyEntity, Long&gt; {

    @Query(value = &quot;SELECT nextval('import_id_seq')&quot;, nativeQuery = true)
    Long getNexImportId();
}
</code></pre>
",https://stackoverflow.com/questions/71034031/springboot-unit-testing-with-h2-emulating-postgres,"['postgresql', 'spring-boot', 'unit-testing', 'jpa']",710,False,0,0
Mocking KafkaAvroDeserializer for unit testing using Mockito,"<p>I am trying to unit test a class which uses KafkaAvroDeserializer to deserialize an object. I would like to mock the KafkaAvroDeserializer so that I can test the business logic. However, when I am trying to mock KafkaAvroDeserializer, I get the following error:</p>
<blockquote>
<p>Underlying exception : org.mockito.exceptions.base.MockitoException: Could not modify all classes [class io.confluent.kafka.serializers.AbstractKafkaAvroDeserializer, interface org.apache.kafka.common.serialization.Deserializer, interface java.io.Closeable, class io.confluent.kafka.serializers.KafkaAvroDeserializer, class io.confluent.kafka.serializers.AbstractKafkaSchemaSerDe, interface java.lang.AutoCloseable]</p>
</blockquote>
<blockquote>
<p>org.mockito.exceptions.base.MockitoException:
Mockito cannot mock this class: class io.confluent.kafka.serializers.KafkaAvroDeserializer.</p>
</blockquote>
<p>Mockito version: 4.8.0
JDK: 8 and tried 11 too.</p>
<p>Any help here is appreciated. Thanks.</p>
",https://stackoverflow.com/questions/74954853/mocking-kafkaavrodeserializer-for-unit-testing-using-mockito,"['java', 'unit-testing', 'apache-kafka', 'mockito', 'confluent-schema-registry']",211,False,0,1
php unit testing problem in phpunit.xml file,"<p>working with php unit testing and My phpunit.xml file is like this</p>
<pre><code>&lt;?xml version=&quot;1.0&quot;  encording=&quot;UTF-8&quot; ?&gt;

&lt;phpunit bootstrap=&quot;vendor/autoload.php&quot;&gt;

    &lt;testsuits&gt;
    
         &lt;testsuit name=&quot;unit&quot;&gt;
         
             &lt;directory&gt;tests&lt;/directory&gt;
         
         &lt;/testsuit&gt;
    
    &lt;/testsuits&gt;

&lt;/phpunit&gt;
</code></pre>
<p>but when i execute following running command <code>vendor/bin/phpunit</code> compiler got following error messages
<code>Could not load &quot;C:\Users\Orukawa\Desktop\phpunittest\phpunit.xml&quot;.</code>
<code>parsing XML declaration: '?&gt;' expected</code></p>
<p>how could I fix this prob?</p>
",https://stackoverflow.com/questions/70549706/php-unit-testing-problem-in-phpunit-xml-file,"['php', 'xml', 'phpunit']",316,False,-2,1
Getting Error in Unit Testing TeamsFx app,"<p>Is there any recommended framework to be used for unit testing the application built using TeamsFx tab app that can be integrated in a CI/CD pipeline.</p>
<p>I've tried using Jest and Enzyme but was getting errors. Are there any sample projects that can be referred for this?</p>
",https://stackoverflow.com/questions/71651401/getting-error-in-unit-testing-teamsfx-app,"['microsoft-graph-teams', 'teams-toolkit']",113,False,0,1
Unit testing react hook inside react-admin,"<p>Is there any way to mock the user authenticated status using useAuthState as a mock?</p>
<p>Things i have tried so far include: React Hooks Testing Library, Enzyme component rendering, jest.mock, jest.createMockFromModule. I know if i don't include my component inside a provider i will get &quot;could not find react-redux context value; please ensure the component is wrapped in a Provider&quot;</p>
<pre><code>import React from 'react';
import { makeStyles } from '@material-ui/core';
import Typography from '@material-ui/core/Typography';
import { useAuthState } from 'ra-core';
import { Redirect } from 'react-router';
import { Routes } from '../../ui/constants';
import { UnAuthenticatedLayoutWithTheme } from '../UnAuthenticatedLayout';

export const GettingStarted = () =&gt; {
    const classes = useStyles();
    const { loading, authenticated } = useAuthState();

    if (loading) {
        return null;
    }

    if (authenticated) {
        return &lt;Redirect to={Routes.default} /&gt;;
    }

    return (
        &lt;UnAuthenticatedLayoutWithTheme showActions&gt;
            &lt;Typography
                variant=&quot;h3&quot;
                align=&quot;center&quot;
                className={classes.sectionTitle}
            &gt;
                Onboarding
            &lt;/Typography&gt;
...
</code></pre>
<pre><code>test('should display page with user not authenticated', async() =&gt; {
        const { getByText } = renderWithRedux(
            &lt;ApiHubProvider url=&quot;/getting-started&quot; tenantName=&quot;getting-started&quot;&gt;
                 &lt;GettingStarted /&gt;
            &lt;/ApiHubProvider&gt;
        );

        await wait(() =&gt; {
            expect(getByText('Onboarding')).not.toBeNull();
        });
    });
</code></pre>
<p>ApiHubProvider Implementation</p>
<pre><code>import React, { createContext, useContext, useRef } from 'react';
import get from 'lodash/get';

export const ApiHubContext = createContext();

export const ApiHubProvider = ({
    url,
    tenantName,
    originHubName,
    children,
}) =&gt; {
    const value = useRef({
        originHubName,
        tenantName,
        url,
        urlWithApi: `${url}/api`,
        urlWithTenant: `${url}/api/${tenantName}`,
    });
    return (
        &lt;ApiHubContext.Provider value={value.current}&gt;
            {children}
        &lt;/ApiHubContext.Provider&gt;
    );
};
</code></pre>
",https://stackoverflow.com/questions/70994635/unit-testing-react-hook-inside-react-admin,"['reactjs', 'react-hooks', 'jestjs', 'react-admin']",419,False,0,1
Unit testing infinite Flux speed of generation,"<p>I have Flux, which generates event in some pace (in infinite manner). I would like to use StepVerifier that after 5 seconds there is at least 2 events generated. How can I verify this behavior using StepVerifier?</p>
<p>Sample flux for testing can look like this:</p>
<pre><code>public fluxTest() {
    final AtomicLong counter = new AtomicLong(0);
    final Random rnd = new Random();

    final Flux&lt;String&gt; randomIntervalEmitter = Flux.generate(generator -&gt; {
        try {
            final long counterDivided = counter.get() % 12;
            if (counterDivided &gt; 0) {
                TimeUnit.SECONDS.sleep(rnd.nextInt(1, 10));
            } else {
                TimeUnit.MILLISECONDS.sleep(rnd.nextInt(1, 50));
            }
            generator.next(&quot;asdf &quot; + counterDivided);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    });

    final Flux&lt;String&gt; regularDummyUpdate = Flux.interval(Duration.ofSeconds(5)).map(e -&gt; &quot;&quot; + (88 + (System.currentTimeMillis() % 104)));
    final Flux&lt;String&gt; stringFluxWithSomePace = randomIntervalEmitter.mergeWith(regularDummyUpdate);
    
    stringFluxWithSomePace.subscribe(System.out::println);
}
</code></pre>
",https://stackoverflow.com/questions/73082901/unit-testing-infinite-flux-speed-of-generation,"['testing', 'project-reactor']",59,False,0,1
How to process files for unit testing?,"<p>I have 5 input files in a folder, for each input file (1.in for example), I process it and produce a new output file (1.out) printing a integer in it.</p>
<p>How do I do this?</p>
<p>Right now this is what I have, I want to run different files like a2.in and print output in new file like a2.out (name them based on the input file names).</p>
<pre><code>public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(&quot;a1.in&quot;));
    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(&quot;a1.out&quot;)));

public int compareTo(Event a) {
            return ans;
}
</code></pre>
",https://stackoverflow.com/questions/73108962/how-to-process-files-for-unit-testing,['java'],58,True,-2,1
Unit testing a collection with equivalent object,"<p>I'm in search of a simple way to test that a collection contains logically equivalent object (ignoring instance) in c#.</p>
<pre class=""lang-cs prettyprint-override""><code>public class BarObject
{
    public string name { get; set; }
    public string info { get; set; }
}

public class Foo
{
    public Foo() { }
    public IEnumerable&lt;BarObject&gt; Bars { get; set; } = 
        new List&lt;BarObject&gt;() 
        { 
            new BarObject() { name = &quot;johndoe&quot;, info = &quot;wierdo&quot; } 
        };
}

[TestClass]
public class FooTests
{
    [TestMethod]
    public void TestDefaultInList()
    {
        Foo foo = new Foo();
        //Using NUnit
        CollectionAssert.Contains(foo.Bars.ToList(), 
            new BarObject() { name = &quot;johndoe&quot;, info = &quot;wierdo&quot; }
        );
    }
}

</code></pre>
<p>The issue that I believe that I am having is that it is checking the instance of the object instead of the values within. How do I test that there is an object with specific values in an array simply without writing my own comparers?</p>
",https://stackoverflow.com/questions/71074100/unit-testing-a-collection-with-equivalent-object,"['c#', 'unit-testing', 'collections', 'nunit']",215,False,0,0
Unit testing DynamoDB with XUnit and Moq,"<p>I'm starting to write my DAL for a .Net 6 application that hooks into AWS DynamoDB. We are going for a document model implementation, everything is setup up within AWS already, just need to start the data access with a set of unit and integration tests.</p>
<p>I've tried to start this with my unit tests, in true TDD fashion, but am struggling to mock the DynamoDB client. I haven't found anything that helps with the mocking of DynamoDb but have seen people using DynamoDB locally for this. I don't want to use a local instance for this as it doesn't feel like they are unit tests but also these unit tests will be running as part of the build pipeline within devops so need to run independently.</p>
<p>This gives an idea of what I've been trying to do but I just get an object not set to a reference exception when the client is trying to get the table description and I seem to be going around in circles with this one...can anyone please help?</p>
<p>Code/context below:</p>
<pre><code>[Fact]
public void Get_WithValidId_ReturnsEntity()
{
    var mockDynamoClient = new Mock&lt;IAmazonDynamoDB&gt;();
    
    var describeTableResponse = new DescribeTableResponse
    {
        Table = new TableDescription
        {
            TableName = &quot;TestTable&quot;
        },
        HttpStatusCode = HttpStatusCode.OK
    };

    // Trying a couple of different ways to get the table description
    mockDynamoClient
        .Setup(s =&gt; s.DescribeTableAsync(It.IsAny&lt;string&gt;(), It.IsAny&lt;CancellationToken&gt;()))
        .ReturnsAsync(describeTableResponse);

    mockDynamoClient
        .Setup(s =&gt; s.DescribeTableAsync(It.IsAny&lt;DescribeTableRequest&gt;(), It.IsAny&lt;CancellationToken&gt;()))
        .ReturnsAsync(describeTableResponse);

    var repo = new DynamoRepository(mockDynamoClient.Object);

    var result = repo.Get(3);

    result.Should().NotBeNull();
}
</code></pre>
<p>Error: Object reference not set to an instance of an object.</p>
<p>Stack Trace</p>
<pre><code>   at Amazon.DynamoDBv2.DocumentModel.Table.DescribeTable(String tableName)
   at Amazon.Runtime.Internal.Util.Cache`2.GetValueHelper(TKey key, Boolean&amp; isStaleItem, Func`2 creator)
   at Amazon.Runtime.Internal.Util.Cache`2.GetValue(TKey key, Func`2 creator, Boolean&amp; isStaleItem)
   at Amazon.DynamoDBv2.DocumentModel.Table.LoadTableInfo()
   at Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(IAmazonDynamoDB ddbClient, TableConfig config)
   at Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(IAmazonDynamoDB ddbClient, String tableName, DynamoDBEntryConversion conversion, Boolean isEmptyStringValueEnabled)
   at Amazon.DynamoDBv2.DocumentModel.Table.LoadTable(IAmazonDynamoDB ddbClient, String tableName)
   at MyApp.Infrastructure.Data.Repositories.DynamoRepository.Get(Int32 id) in C:\projects\MyApp\Infrastructure\Data\Repositories\DynamoRepository.cs:line 29
</code></pre>
<p>This is the corresponding method (not finished yet) which may give some extra context behind the implementation.</p>
<pre><code>public async Task&lt;Document&gt; Get(int id)
{
    try
    {
        var table = Table.LoadTable(_dynamoDbClient, Constants.DynamoTableName);

        var item = await table.GetItemAsync(id);

        return item;
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
        throw;
    }
}
</code></pre>
",https://stackoverflow.com/questions/74442184/unit-testing-dynamodb-with-xunit-and-moq,"['c#', 'unit-testing', 'amazon-dynamodb', 'moq', 'xunit']",41,False,0,1
Mock DateTime.UtcNow for Unit Testing in C#,"<p>I'm trying to mock the <code>DateTime.UtcNow</code> in a unit test, using <a href=""https://github.com/tonerdo/pose"" rel=""nofollow noreferrer"">Pose</a>, but it seems that is not working in .NET 6.
The code looks like this:</p>
<pre><code>// Arrange
...
var created = DateTime.UtcNow;
var expectedRequest = new ExpectedRequest()
{
    Created = created
    ...
};

var shim = Shim.Replace(() =&gt; DateTime.UtcNow).With(() =&gt; created);

PoseContext.Isolate(() =&gt;
{
    // Act
    var mappedRequest = request.ToExpectedRequest();

    // Assert
    mappedRequest.Should().BeEquivalentTo(expectedRequest);
}, shim);
...
</code></pre>
<p>The problem is that the unit test is stuck when <code>PoseContext.Isolate(()</code> is reached and when I try to stop the unit test, Visual Studio freezes and restarts itself.</p>
<p>Is there any other option or library similar to <a href=""https://github.com/tonerdo/pose"" rel=""nofollow noreferrer"">Pose</a>?</p>
<p>I know that the most common approach is to introduce an interface that the application logic will use instead of the direct use of <code>DateTime.UtcNow</code> property, but I don't want to inject a new service just for that and I'm trying to find a solution without modifying the implementation.</p>
<p><strong>Edit:</strong>
There are multiple ways to 'solve' this mocking problem for <code>DateTime</code> that can be found <a href=""https://levelup.gitconnected.com/5-ways-to-mock-datetime-now-for-unit-testing-in-c-bf0438eab032"" rel=""nofollow noreferrer"">here</a> or <a href=""https://methodpoet.com/unit-testing-datetime-now/"" rel=""nofollow noreferrer"">here</a>, but I choose the Ambient Context <a href=""https://dvoituron.com/2020/01/22/UnitTest-DateTime/"" rel=""nofollow noreferrer"">approach</a>.</p>
<p>The unit test looks like this now:</p>
<pre><code>// Arrange
...
using var context = new DateTimeProviderContext(DateTime.UtcNow);
var expectedRequest = new ExpectedRequest()
{
    Created = DateTimeProvider.UtcNow
    ...
};

// Act
var mappedRequest = request.ToExpectedRequest();

// Assert
mappedRequest.Should().BeEquivalentTo(expectedRequest);
...
</code></pre>
<p>In the implementation the only thing left to do was to use <code>Created = DateTimeProvider.UtcNow</code> instead of <code>Created = DateTime.UtcNow</code>.</p>
<p>I will add here those 2 classes <code>DateTimeProvider</code> and <code>DateTimeProviderContext</code> in case someone needs them.</p>
<pre><code>public static class DateTimeProvider
{
    public static DateTime Now
        =&gt; DateTimeProviderContext.Current == null
        ? DateTime.Now
        : DateTimeProviderContext.Current.ContextDateTime;

    public static DateTime UtcNow =&gt; Now.ToUniversalTime();
}
</code></pre>
<pre><code>public class DateTimeProviderContext : IDisposable
{
    internal DateTime ContextDateTime;
    private static readonly ThreadLocal&lt;Stack&gt; _threadScopeStack = new(() =&gt; new Stack());
    private bool _isDisposed = false;

    public DateTimeProviderContext(DateTime contextDateTime)
    {
        ContextDateTime = contextDateTime;
        _threadScopeStack.Value?.Push(this);
    }

    public static DateTimeProviderContext? Current
    {
        get
        {
            if (_threadScopeStack.Value?.Count == 0)
            {
                return null;
            }
            else
            {
                return _threadScopeStack.Value?.Peek() as DateTimeProviderContext;
            }
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_isDisposed &amp;&amp; disposing)
        {
            _threadScopeStack.Value?.Pop();
        }
        _isDisposed = true;
    }
}
</code></pre>
",https://stackoverflow.com/questions/74594624/mock-datetime-utcnow-for-unit-testing-in-c,"['c#', 'unit-testing', 'datetime', '.net-6.0']",316,False,0,0
Unit Testing on Springboot WebClient with MockWebServer,"<p>After searching around the net for few days, couldn't really find the resources I need for my use case as many of it are implemented in Java.</p>
<p>I have a service class that is calling external api, and I am trying to write unit tests on it with MockWebServer</p>
<pre><code>@Service
class ApiService {
    @Autowired
    private lateinit var webClient: WebClient

    fun getApiResult(name: String): ResultDto? {
        return try {
           webClient
               .get()
               .uri(&quot;https://www.example.com/&quot;)
               .retrieve()
               .bodyToMono(Result::class)
               .block()
            catch {
               null
        }
    }
}
</code></pre>
<pre><code>@ExtendWith(MockitoExtension::class)
@MockitoSettings(strictname = Strictness.LENIENT)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ApiServiceTest {
    @Mock
    private lateinit var webClient: WebClient

    @InjectMocks
    private lateinit var mockApiService: ApiService

    private val mockName = &quot;mockName&quot;
    private val mockDetailDto = DetailDto(name = &quot;mockName&quot;, age = 18)

    @Test
    fun canGetDetails() {
        mockWebServer.enqueue(
            MockResponse()
                .setResponse(200)
                .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .setBody(mockDetailDto))
        )

        mockApiService.getApiResult(mockName)
        val request: RecordedRequest = mockWebServer.takeRequest()

        // Assert statements with request
    }
}
</code></pre>
<p>However, I am getting <code>lateinit property webClient has not been initialised</code>. But if I were to use <code>@Spy</code> instead of <code>@Mock</code> for the webClient in my test, it will be making actual apis calls which is not the goal of unit test. My goal would be able to check the <code>request</code> for some of the details such as <code>GET</code> and its return value. Appreciate the community's help.</p>
",https://stackoverflow.com/questions/72358534/unit-testing-on-springboot-webclient-with-mockwebserver,"['spring-boot', 'unit-testing', 'kotlin', 'junit5', 'mockwebserver']",1418,False,0,1
flutter unit testing stubbed method returns null,"<p>I,m unit testing flutter class using mockito. I stubbed one method using 'when()' but it returns null. is there something wrong in my testing?. I have used freezed union to generate Result class. My Repository is an abstract class</p>
<p>this is my test class</p>
<pre><code>class MockRepository extends Mock implements Repository {}

void main() {
  late CryptoUseCases useCases;
  late MockRepository repository;

  final Result&lt;List&lt;Crypto&gt;, Exception&gt; data = const Result.success([
    Crypto(
      id: 1,
      name: 'Bitcoin',
      symbol: 'BTC',
      priceUsd: 4000,
      availableSupply: 879787908,
      logo: '',
      volumeUsd24h: 786876,
      totalSupply: 876587,
      marketCapUsd: 698,
      maxSupply: 867987,
      rank: 1,
    ),
    Crypto(
      id: 3,
      name: 'Euthereum',
      symbol: 'ETH',
      priceUsd: 134,
      availableSupply: 879787908,
      logo: '',
      volumeUsd24h: 786876,
      totalSupply: 876587,
      marketCapUsd: 698,
      maxSupply: 867987,
      rank: 2,
    ),
  ]);
  setUp(() {
    repository = MockRepository();
    useCases = CryptoUseCases(repository);
  });

  test('getCryptos return a list of crypto', () async {
    //arrange
    when(repository.getCryptos()).thenAnswer((_) async =&gt; data);

    //act

    final result = await useCases.getCryptos();

    //assert
    expect(result, equals(data));
    verify(repository.getCryptos()).called(1);
    verifyNoMoreInteractions(repository);
  });
}
</code></pre>
<p>this is my class</p>
<pre><code>class CryptoUseCases {
  final Repository repository;

  CryptoUseCases(this.repository);

  Future&lt;Result&lt;List&lt;Crypto&gt;, Exception&gt;&gt; getCryptos() async {
    final result = await repository.getCryptos();
    result.when(success: (data) {
      return Result.success(data);
    }, error: (e) {
      return Result.error(e);
    });
    return Result.error(Exception());
  }
}
</code></pre>
<p>i'm using freezed here. is that a problem?</p>
<p>this is the error</p>
<pre><code>type 'Null' is not a subtype of type 'Future&lt;Result&lt;List&lt;Crypto&gt;, Exception&gt;&gt;'
package:crypto_app/src/domain/repositories/repository.dart 6:43  MockRepository.getCryptos
test\use_cases_test.dart 51:21                                   main.&lt;fn&gt;
test\use_cases_test.dart 49:46 
</code></pre>
",https://stackoverflow.com/questions/71510631/flutter-unit-testing-stubbed-method-returns-null,"['flutter', 'flutter-test', 'flutter-freezed']",460,True,0,1
Java Mockito Unit Testing - SPY nested HashMap,"<p>I have a  nested method call where I need to <code>@Spy</code> a HashMap in the nested method calls. I just want to verify its size or contents, but its <em><strong>not</strong></em> being passed as a method argument <em><strong>nor</strong></em> is it a Class member field/property. My <em>concrete</em> <strong>Classes</strong> looks like this:</p>
<p><strong>// 1st method call from &quot;MyClass&quot; which declared using <code>@InjectMocks</code></strong></p>
<pre><code> in UT
public class MyClass {

   public boolean method1(Arg arg1, int arg2) {
      Map&lt;String, Object&gt; inputMap = arg1.method2(arg2);

      return false;
}
</code></pre>
<p><strong>// 2nd nested method call which is returning the HashMap that I want</strong> to be able to see the contents of in my UT</p>
<pre><code>public class MyOtherClass {
   
   public Map&lt;String, Object&gt; method2(arg2) {
       Map&lt;String, Object&gt; map = new HashMap();

      switch(arg2) {
      case 0: 
         map.put(&quot;key&quot;, new Object());
         break;
      default:
         break;
      }

      // some logic here
      return map;
}
</code></pre>
<p><strong>.....And my <em>Unit Test</em> (UT) looks something like this:</strong></p>
<pre><code>public class MyClassTest {
   
   @InjectMocks
   private MyClass myClass;

   @Spy
   private Map&lt;String, Object&gt; inputMapSpy = new HashMap&lt;&gt;();

   
   @Test
   public void myUnitTestThatWillNotAllowMeToSpyTheNestedHashMap() {
       // stuff
       Arg arg1 = new Arg();

       myClass.method1(arg1, 5000);

       // every time inputMapSpy is 0, so its not getting &quot;injected&quot;
       assertTrue(inputMapSpy.size() == 10);
   }
</code></pre>
<p>Can anyone help me? Everytime as I said the <code>@Spy</code> of the Hashmap is never being used in the nested method calls so its size is always 0. Help!</p>
",https://stackoverflow.com/questions/73297954/java-mockito-unit-testing-spy-nested-hashmap,"['java', 'unit-testing', 'mockito']",91,False,0,0
"React unit testing, JEST + axios mock problem","<p>I have a problem with unit test with JEST and Axios. The mock does not work and I do not get data during the unit test. I have no idea why it happens. My only thought is that I mocked it in a wrong way since I use axios.client.get?</p>
<p>test:</p>
<pre><code>jest.mock(&quot;axios&quot;);
const mockedAxios = axios as jest.Mocked&lt;typeof axios&gt;;

describe(&quot;Test of products fetch&quot;, () =&gt; {
  test(&quot;render products&quot;, async () =&gt; {
    mockedAxios.get.mockResolvedValueOnce({
      title: &quot;product&quot;,
      description: &quot;description&quot;,
      _id: &quot;123&quot;,
      imageData: &quot;&quot;,
      price: &quot;15&quot;,
    });

    render(
      &lt;ReduxProvider&gt;
        &lt;Products /&gt;
      &lt;/ReduxProvider&gt;,
    );
    const productsList = await screen.findAllByRole(&quot;a&quot;);
    expect(productsList).toBeGreaterThan(0);
    expect(productsList).toBeLessThan(10);
  });
});
</code></pre>
<p>component</p>
<pre><code>useEffect(() =&gt; {
    const getProducts = async (): Promise&lt;void&gt; =&gt; {
      const prods = await getProducts(actualPage);
      setProducts(prods);
    };
    getProducts();
  }, [actualPage]);
&lt;Fragment&gt;
              {products.map((product) =&gt; (
                &lt;ProductItem
                  key={product.title}
                  title={product.title}
                  imageData={decodeBase64(product.imageData)}
                  price={product.price}
                  id={product._id}
                /&gt;
              ))}
            &lt;/Fragment&gt;
</code></pre>
<p>api-call</p>
<pre><code>export async function getProducts(pageNum: number): Promise&lt;IProduct[]&gt; {
  const response = await productsClient.get&lt;IProduct[]&gt;(
    `/get-products?page=${pageNum}`,
  );
  const data = response.data;
  return data;
}
</code></pre>
<p>error: <code>const response = await productsClient.get&lt;IProduct[]&gt;( Cannot read properties of undefined (reading 'get')</code></p>
",https://stackoverflow.com/questions/73869744/react-unit-testing-jest-axios-mock-problem,"['reactjs', 'typescript', 'unit-testing', 'axios', 'jestjs']",25,False,0,1
Unit testing Internet connectivity in Xamarin Forms,"<pre><code>public class InternetConnection : IInternetConnection
{
    public async Task&lt;bool&gt; CheckInternetStatusAsync()
    {
        if (Connectivity.NetworkAccess != NetworkAccess.Internet)
        {
            //delay to check handle network blips in restaurants
            await Task.Delay(2000);
            if (Connectivity.NetworkAccess != NetworkAccess.Internet)
            {
                return false;
            }
        }
        return true;
    }
}
</code></pre>
<p>How do i Unit test Internet Connectivity in xamarin forms ?
UnitTesting using NUnit.</p>
",https://stackoverflow.com/questions/72813599/unit-testing-internet-connectivity-in-xamarin-forms,"['unit-testing', 'xamarin.forms']",82,True,-1,1
Flutter: How to unit testing moor/drift?,"<p>I already implementation of Drift for local storage, and want make it testable function. But I get stack and idk how to fix it the unit test.</p>
<p>HomeDao</p>
<pre class=""lang-dart prettyprint-override""><code>@DriftAccessor(tables: [RepositoriesTable])
class HomeDao extends DatabaseAccessor&lt;AppDatabase&gt; with _$HomeDaoMixin {
  HomeDao(AppDatabase db) : super(db);

  Future&lt;List&lt;RepositoriesTableData&gt;&gt; getRepositories() async =&gt;
      await select(repositoriesTable).get();
}
</code></pre>
<p>AppDatabase</p>
<pre class=""lang-dart prettyprint-override""><code>@DriftDatabase(
  tables: [RepositoriesTable],
  daos: [HomeDao],
)
class AppDatabase extends _$AppDatabase {
  AppDatabase() : super(_openConnection());

  @override
  int get schemaVersion =&gt; 1;
}

QueryExecutor _openConnection() {
  return SqfliteQueryExecutor.inDatabaseFolder(
    path: 'db.sqlite',
    logStatements: true,
  );
}
</code></pre>
<p>LocalDataSources</p>
<pre class=""lang-dart prettyprint-override""><code>abstract class GTHomeLocalDataSource {
  const GTHomeLocalDataSource();

  Future&lt;List&lt;RepositoriesTableData&gt;&gt; getRepositories();
}

class GTHomeLocalDataSourceImpl implements GTHomeLocalDataSource {
  final AppDatabase appDatabase;

  const GTHomeLocalDataSourceImpl({required this.appDatabase});

  @override
  Future&lt;List&lt;RepositoriesTableData&gt;&gt; getRepositories() async =&gt;
      await appDatabase.homeDao.getRepositories();
}

</code></pre>
<p>UnitTesting</p>
<pre class=""lang-dart prettyprint-override""><code>void main() =&gt; testGTHomeLocalDataSource();

class MockDatabaseHandler extends Mock implements AppDatabase {}

void testGTHomeLocalDataSource() {
  late GTHomeLocalDataSource localDataSource;
  late AppDatabase databaseHandler;

  setUp(() {
    databaseHandler = MockDatabaseHandler();
    localDataSource = GTHomeLocalDataSourceImpl(
      appDatabase: databaseHandler,
    );
  });

  group(&quot;GTHomeLocalDataSource -&quot;, () {
    test(''' \t
      GIVEN Nothing
      WHEN call getRepositories
      THEN databaseHandler select function has been called and return list of RepositoriesTableData
      ''', () async {
      // GIVEN
      when(() =&gt; databaseHandler.homeDao.getRepositories())
          .thenAnswer((_) =&gt; Future.value(repositoriesDummyTable));

      // WHEN
      final result = await localDataSource.getRepositories();

      // THEN
      verify(() =&gt; databaseHandler.homeDao.getRepositories());

      expect(result, isA&lt;List&lt;RepositoriesTableData&gt;&gt;());
      expect(result.length, repositoriesDummyTable.length);
      expect(result.first.language, repositoriesDummyTable.first.language);
    });
  });

  tearDown(() async {
    await databaseHandler.close();
  });
}
</code></pre>
<p>My function is work well for get data from the local db and show it in the app, but when running as unit test, I stacked with this error.</p>
<pre><code>package:gt_core/local/database/database_module.g.dart 424:22           MockDatabaseHandler.homeDao
package:gt_home/data/data_sources/gt_home_local_datasource.dart 20:25  GTHomeLocalDataSourceImpl.getRepositories
test/data/data_sources/gt_home_local_datasource_test.dart 35:44        testGTHomeLocalDataSource.&lt;fn&gt;.&lt;fn&gt;
test/data/data_sources/gt_home_local_datasource_test.dart 29:12        testGTHomeLocalDataSource.&lt;fn&gt;.&lt;fn&gt;
type 'Null' is not a subtype of type 'Future&lt;void&gt;'
package:drift/src/runtime/api/db_base.dart 125:16                MockDatabaseHandler.close
test/data/data_sources/gt_home_local_datasource_test.dart 47:27  testGTHomeLocalDataSource.&lt;fn&gt;
test/data/data_sources/gt_home_local_datasource_test.dart 46:12  testGTHomeLocalDataSource.&lt;fn&gt;
===== asynchronous gap ===========================
dart:async                                                       _completeOnAsyncError
test/data/data_sources/gt_home_local_datasource_test.dart        testGTHomeLocalDataSource.&lt;fn&gt;
test/data/data_sources/gt_home_local_datasource_test.dart 46:12  testGTHomeLocalDataSource.&lt;fn&gt;

type 'Future&lt;List&lt;RepositoriesTableData&gt;&gt;' is not a subtype of type 'HomeDao'
</code></pre>
<p>Anyone know how to fix it?</p>
",https://stackoverflow.com/questions/72845985/flutter-how-to-unit-testing-moor-drift,"['flutter', 'unit-testing', 'flutter-moor', 'drift']",485,False,0,1
Python unit testing with VSCode behaves weird,"<p>I am using VSCode for my Python project. Unit testing (<a href=""https://code.visualstudio.com/docs/python/testing"" rel=""nofollow noreferrer"">https://code.visualstudio.com/docs/python/testing</a>) works fine, but every time I execute a test (via panel or in code editor), the panel jumps from <code>Test Explorer</code> to <code>Explorer</code>.</p>
<p><a href=""https://i.stack.imgur.com/Cbfh2.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Cbfh2.png"" alt=""enter image description here"" /></a></p>
<p>This started a couple of days ago out of the blue. Any idea?</p>
",https://stackoverflow.com/questions/73171301/python-unit-testing-with-vscode-behaves-weird,"['python', 'visual-studio-code', 'python-unittest']",68,False,0,0
X Unit Testing Filtered Include EF Core,"<p>We have a scenario in .Net Core API to Soft Delete Principal entity and all its dependent entities So We just loaded the dependent entities to include only Active dependent entities with Include(), set the Active = false and update with '''SavesChanges()'''. This part of logic is working fine. The problem is on Unit Test Part.
We have configured DbContext to use In Memory Seed data, so it is not filtering dependent entities as per logic due to shared context. It works fine if We add AsNoTracking(), however in that case we are not able to update the relationships.</p>
",https://stackoverflow.com/questions/73683230/x-unit-testing-filtered-include-ef-core,"['unit-testing', 'entity-framework-core', 'asp.net-core-webapi']",14,False,0,0
Integrating Postman Requests with Unit Testing Framework,"<p>Say you have developed a number of Postman Requests in a collection. Such requests are huge and complex and they are used to test end-points or perform certain actions such as creating a sample test case for testing be carried out on the web application.</p>
<p>All such requests can, in theory, be scripted using NodeJS, PowerShell, or C#, and within the context of Unit Testing Framework such as Pester, NUnit, Jest, Selenium, Chia, Mocha …etc.</p>
<p>However, we want to take advantage of the work done in Postman and we need to script the invocation of such Postman requests in a given collection, to be executed against a given Environment. All the other details such as Environment Configurations, Authentication, Request Boyd, Request Header …etc. are all configured properly in Postman.</p>
<p>Now I have setup my local dev environment testing project using vscode, C#/PowerShell, Selenium WebDriver and NUnit. I want to script the test case in C# (NUnit) or PowerShell (Pester) to invoke the relevant Postman requests to be executed against the intended environment.</p>
<p>How is this possible?</p>
<p>I appreciate your help.</p>
<p>Tarek</p>
",https://stackoverflow.com/questions/71428699/integrating-postman-requests-with-unit-testing-framework,"['c#', 'unit-testing', 'visual-studio-code', 'frameworks', 'postman']",649,True,0,1
Unit testing a custom exception in Java,"<p>Pretty new to Java and trying to practice writing unit tests. I have a few similar custom exceptions to the below and wondering what way I can write a test to cover this.</p>
<pre><code>public class ExampleException extends RuntimeException{
    public ExampleException(String message, Throwable e) {
        super(message, e);
    }
}
</code></pre>
",https://stackoverflow.com/questions/71018642/unit-testing-a-custom-exception-in-java,"['java', 'unit-testing', 'junit', 'junit4']",1201,True,0,1
Unit Testing for Activity Theme in Android,"<p>I have written code with an Android app that dynamically sets an Activity's theme (within the java file that defines the activity). I would like to write a unit test for this. Right now (using <a href=""https://truth.dev/"" rel=""nofollow noreferrer"">Truth</a>, although that's just an implementation detail) I have</p>
<pre><code>assertThat(context.getTheme()).isEqualTo(R.style.TheThemeImTesting);
</code></pre>
<p>However that returns error <code>int is not compatible with Theme</code> since <code>getTheme()</code> returns a Theme but <code>R.style.TheThemeImTesting</code> is an Int.</p>
<p>What's the best way to get the two types to agree?</p>
",https://stackoverflow.com/questions/73408198/unit-testing-for-activity-theme-in-android,"['android', 'unit-testing', 'android-theme']",79,False,0,0
Unit testing constructor initialization and public logic,"<p>Suppose you have the following class:</p>
<pre class=""lang-java prettyprint-override""><code>public class RepositoryImpl implements Repository {
  private static final Object DEFAULT_OBJECT = new Object();

  private final Persistence persistence;
  private volatile Object cachedObject; // maybe ignore that this is volatile and non-final

  public RepositoryImpl(Persistence persistence) {
    this.persistence = persistence;
    this.cachedObject = getInitialCachedObject();
  }

  private Object getInitialCachedObject() {
    try {
      return persistence.get();
    } catch (ObjectNotFoundException e) {
      persistence.persist(DEFAULT_OBJECT);
      return DEFAULT_OBJECT;
    }
  }

  public Object update() { /*some logic*/ }
  public Object get() { /*some logic*/ }
  public Object delete() { /*some logic*/ }
}
</code></pre>
<p>Then I want to unit test the Repository class and I mock out the persistence.
I want to have probably 2 tests that test the initialization logic (happy path and exception) and 3 more tests for the public methods.</p>
<p>The question is how should I approach the testing of this?</p>
<p>The possible options that I managed to think of are:</p>
<ol>
<li>Consider calling the initialization from outside through a public method after ctor
<ul>
<li>breaks the immutability (in my particular case this is already broken as cachedObject needs to be volatile and not final, but in the general case.. yeah)</li>
</ul>
</li>
<li>Create the RepositoryImpl in each test case instead of using @InjectMocks or @Before</li>
<li>Create two nested test classes - one for the init logic and one for the core logic</li>
<li>Somehow use @InjectMocks but re-initialize only in one test, not sure if possible</li>
<li>Some lazy approach in get(), but also breaks immutability in the general case</li>
</ol>
<p>To me option 3 seems clean, but maybe there is a better approach or further refactoring is needed idk. Any suggestions are highly appreciated.</p>
<p>Note that I cannot just use @Cachable in the Persistence because this is not a Spring project.</p>
",https://stackoverflow.com/questions/73722261/unit-testing-constructor-initialization-and-public-logic,"['java', 'unit-testing', 'junit', 'mockito', 'junit4']",85,True,0,1
Unit Testing of an API in Kotlin?,"<p>I am new to this unit testing, can somebody help me in writing a unit for an API that is used for logging. I don't know where to start and how to start writing tests for an API.</p>
",https://stackoverflow.com/questions/72372689/unit-testing-of-an-api-in-kotlin,"['api', 'unit-testing', 'kotlin', 'junit']",187,False,0,1
Unit testing Flink Topology without using MiniClusterWithClientResource,"<p>I have a Fink topology that consists of multiple Map and FlatMap transformations.  The source/sink are from/to Kafka. The Kakfa records are of type <code>Envelope</code> (defined by someone else), and are not marked as &quot;serializable&quot;.  I want to Unit test this topology.
I defined a simple SourceFunction that returns a list of <code>Envelope</code> as the source:</p>
<pre><code>public class MySource extends RichParallelSourceFunction&lt;Envelope&gt; {

    private List&lt;Envelope&gt; input;

    public MySource(List&lt;Envelope&gt; input) {
        this.input = input;
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);

    }

    @Override
    public void run(SourceContext&lt;Envelope&gt; ctx) throws Exception {
        for (Envelope listElement : inputOfSubtask) {
            ctx.collect(listElement);
        }
    }

    @Override
    public void cancel() {}
}

</code></pre>
<p>I am using MiniClusterWithClientResource to Unit test the topology.  I ran onto two problems:</p>
<ol>
<li>I need to make MySource serializable, as Flink wants/needs to serialize the source.  As a workaround, I make <code>input</code> transient.  The allowed the code to compile.</li>
<li>Then I ran into the runtime error:</li>
</ol>
<pre><code>org.apache.flink.api.common.functions.InvalidTypesException: The return type of function 'Custom Source' could not be determined automatically, due to type erasure. You can give type information hints by using the returns(...) method on the result of the transformation call, or by letting your function implement the 'ResultTypeQueryable' interface.
</code></pre>
<p>I am trying to understand why I am getting this error, which I was not getting before when the topology is consuming from a kafka cluster using a KafkaConsumer.  I found a workaround by providing the Type info using the following:</p>
<pre><code>.returns(TypeInformation.of(Envelope.class))
</code></pre>
<ol start=""3"">
<li>However, during runtime, after deserialization, <code>input</code> is set to <code>null</code> (obviously, as there is no deserialization method defined.).</li>
</ol>
<p>Questions:</p>
<ol>
<li>Can someone please help me understand why I am getting the <code>InvalidTypesException</code> exception?</li>
<li>Why if MySource being deserialized/serialized?  Is there a way I can void this while usingMiniClusterWithClientResource?</li>
<li>I could hack some <code>writeObject()</code> and <code>readObject()</code> method in MySource. But I prefer to avoid that route. Is it possible to use some framework / class to test the Topology without providing a Source (and Sink) that is Serializable?  It would be great if I could use something like <code>KeyedOneInputStreamOperatorTestHarness</code> that I could pass as topology, and avoid the whole deserialization / serialization step in the beginning.</li>
</ol>
<p>Any ideas / pointers would be greatly appreciated.</p>
<p>Thank you,
Ahmed.</p>
",https://stackoverflow.com/questions/73016135/unit-testing-flink-topology-without-using-miniclusterwithclientresource,"['apache-flink', 'flink-streaming']",228,False,0,1
Django Unit Testing for standalone variables (coverage),"<p>I'm starting to write unit tests for a django project, and running coverage shows I have 0% coverage over a simple list of tuples.</p>
<p>Example:</p>
<pre><code>STATE_CHOICES = [
    (&quot;MO&quot;, &quot;Missouri&quot;,),
    (&quot;AL&quot;, &quot;Alabama&quot;,),
]
</code></pre>
<p>Is there some kind of test I could write to get coverage over this list of tuples?
I assumed simple</p>
<p><code>len() &gt; 0</code> and <code>is not None</code></p>
<p>tests would cover it, but apparently not.</p>
",https://stackoverflow.com/questions/71793234/django-unit-testing-for-standalone-variables-coverage,"['django', 'unit-testing', 'coverage.py']",43,False,0,0
Jacoco: Testing @Data annotation in Unit Testing?,"<p>After running test and generating coverage report via Jacoco, I realized that there is a static method where a <code>@Data</code> annotation is used and the line of it is marked yellow indicating that it is not tested.</p>
<p><a href=""https://i.stack.imgur.com/nvqo6.png"" rel=""nofollow noreferrer"">Report</a></p>
<p>So, is it normal or how can I test that line?</p>
",https://stackoverflow.com/questions/72013558/jacoco-testing-data-annotation-in-unit-testing,"['java', 'unit-testing', 'junit', 'mockito', 'jacoco']",1134,True,-1,2
FirebaseMessaging.getInstance() function calling failes my unit testing,"<p>I am getting an error while running my Videmodel class unit test:</p>
<pre><code>Caused by: java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
    at android.os.Looper.getMainLooper(Looper.java)
    at com.google.firebase.FirebaseApp$UiExecutor.&lt;clinit&gt;(FirebaseApp.java:707)
</code></pre>
<p>I am calling a function inside of init block of the <code>Viewmodel</code> to get the Firebase token.
This function calling is the cause of the error. if I comment the function, it works well.</p>
<p>How can i solve this issue?
Here i have added the code.
Thanks in advance.</p>
<p>ViewModel:</p>
<pre><code>    @HiltViewModel
    class LoginViewModel @Inject constructor(....) : AndroidViewModel(application) {
    init {
            getFcmToken()
}
    .........
    
    private fun getFcmToken() {
    
            FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task -&gt;
                if (!task.isSuccessful) {
                    Log.w(&quot;TAG&quot;, &quot;Fetching FCM registration token failed&quot;, task.exception)
                    return@OnCompleteListener
                }
                _deviceToken.value = task.result
            })
    
        }
        }
    }
</code></pre>
<p>Test Class:</p>
<pre><code>@ExperimentalCoroutinesApi
class LoginViewModelTest {

    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @get:Rule
    var mainCoroutineRule = MainCoroutineRule()

private lateinit var loginViewModel: LoginViewModel
    
    @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)
            loginViewModel =
                LoginViewModel(
                    resourceHelper = resourceHelper,
                    loginUseCase = loginUseCase,
                    application = application
                )
    }
 @Test
    fun `login with incorrect mobile and password`() {
.................................
}
</code></pre>
",https://stackoverflow.com/questions/73260898/firebasemessaging-getinstance-function-calling-failes-my-unit-testing,"['android', 'kotlin', 'kotlin-coroutines', 'android-testing', 'android-unit-testing']",167,False,0,0
Unit testing class with concrete type member,"<p>I have the following class that I want to test</p>
<pre><code>class A
{
public:
  void register()
  {
    b = new B();
  }
...
private:
  B *b;
};
</code></pre>
<p>How can I mock <code>b</code> besides adding a template parameter to <code>A</code> ?</p>
",https://stackoverflow.com/questions/74931313/unit-testing-class-with-concrete-type-member,"['c++', 'unit-testing', 'mocking']",21,False,-2,1
Kotlin Coroutines Channel unit testing in 1.6.0,"<p>I am trying to test BroadcastChannel in my viewmodel.</p>
<pre><code>@ExperimentalCoroutinesApi
@VisibleForTesting
internal val queryChannel = BroadcastChannel&lt;String&gt;(Channel.CONFLATED)

internal val internalSearchResult = queryChannel
    .asFlow()
    .debounce(SEARCH_DELAY_MS)
    .distinctUntilChanged()
    .mapLatest { name -&gt; some code here 
    result
}

@FlowPreview
@ExperimentalCoroutinesApi
val searchResult = internalSearchResult.asLiveData()
</code></pre>
<p>The code inside mapLatest is working with repository, but not launching any new coroutine.
My test class looks like this:</p>
<pre><code>class SearchViewModelTest {
        @get:Rule
    val testingRule = InstantTaskExecutorRule()
@get:Rule
val coroutinesRule = MainCoroutineDispatcherRule()

private val repository = CardSearchRepositoryStub()
private val viewModel: SearchViewModel = createSearchViewModel(repository)
private val result: SearchResult
    get() = viewModel.searchResult.getOrAwaitValue()

@Test
fun `test search query correctness`() = runTest {

    val expectedResult = SearchResult.InvalidRequest
    viewModel.queryChannel.send(&quot;       &quot;)
    advanceUntilIdle()
    assertEquals(expectedResult, result)
}
</code></pre>
<p>Where MainCoroutineDispatcherRule is</p>
<pre><code>@ExperimentalCoroutinesApi
class MainCoroutineDispatcherRule(private val dispatcher: TestDispatcher = StandardTestDispatcher()) :
    TestWatcher() {

    override fun starting(description: Description?) {
        super.starting(description)
        Dispatchers.setMain(dispatcher)
    }

    override fun finished(description: Description?) {
        super.finished(description)
        Dispatchers.resetMain()
    }
}
</code></pre>
<p>But i keep getting the error</p>
<pre><code>Test worker @coroutine#1&quot; java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used
</code></pre>
",https://stackoverflow.com/questions/72088614/kotlin-coroutines-channel-unit-testing-in-1-6-0,"['android', 'unit-testing', 'kotlin-coroutines']",672,False,0,0
unit testing - Mockito When...thenReturn not working,"<p>Im writing unit test cases of a controller file</p>
<p><strong>LoginController.java</strong></p>
<pre><code>CustomerDao customerdao = new CustomerDao();
    Customer customer = new Customer();
    InvoiceDao invoceDao = new InvoiceDao();
    DashboardDao dashboarddao = new DashboardDao();
    private static final Logger log = LogManager.getLogger(LoginController.class);
    LoginDao loginDao = null;

    @RequestMapping(value = &quot;/login.do&quot;, method = RequestMethod.POST)
    public ModelAndView login(HttpServletRequest req, HttpServletResponse res)
            throws SQLException, PropertyVetoException {
        boolean isAlpha = false;
        boolean isAdmin = false;
        boolean checkRoleAssigned = false;
        String password = req.getParameter(&quot;password&quot;);
        String staffId = req.getParameter(&quot;username&quot;);
        loginDao = new LoginDao();
        
        Admin admin = loginDao.getAdminDetails(staffId, password);
        System.err.println(&quot;\n\nadmin -&gt; &quot; + admin);
        if (admin != null) {
            int roleId = loginDao.isRoleExistInRbac(admin.getStaffId());
            checkRoleAssigned = loginDao.checkUserAccess(admin.getStaffId());
            isAlpha = loginDao.checkUserAccessInRbac(roleId);
            isAdmin= loginDao.checkAdmin(admin.getUserId());
            admin.setAdminStatus(loginDao.checkAdmin(admin.getUserId()));
            if (isAdmin) {
                HttpSession session = req.getSession();
                session.setMaxInactiveInterval(120 * 20);
                session.setAttribute(&quot;admin&quot;, admin);
                
              
                return new ModelAndView(&quot;redirect:dashboardView.do&quot;);//prevoiusly it was redirect:listInvoice.do
                

            } else {

                if (checkRoleAssigned) {
                    if (isAlpha) {
                        HttpSession session = req.getSession();
                        session.setMaxInactiveInterval(120 * 20);

                        session.setAttribute(&quot;admin&quot;, admin);

                        //return new ModelAndView(&quot;redirect:listInvoices.do&quot;);
                        return new ModelAndView(&quot;redirect:dashboardView.do&quot;);
                    } else {
                        return new ModelAndView(&quot;index&quot;, &quot;errorMessage&quot;, &quot; Sorry , You dont have any module access.&quot;);
                    }

                } else {
                    return new ModelAndView(&quot;index&quot;, &quot;errorMessage&quot;, &quot; Sorry , You are not a authorised person.&quot;);
                }

            }
        }
        return new ModelAndView(&quot;index&quot;, &quot;errorMessage&quot;, &quot; Username or password incorrect.&quot;);
    }
</code></pre>
<p>and this is the test case for this method</p>
<p><strong>LoginControllerTest.java</strong></p>
<pre><code>@InjectMocks
    LoginController loginController;
    
    @Mock
    CustomerDao customerDao;
    
    @Mock
    Customer customer;
    
    @Mock
    InvoiceDao invoiceDao;
    
    @Mock
    DashboardDao dashboardDao;
    
    @Mock
    LoginDao loginDao;

    @Mock
    Admin admin;
    
    @Test
    void testLogin() throws Exception {
        
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();
        
        request.setParameter(&quot;password&quot;, &quot;pass&quot;);
        request.setParameter(&quot;username&quot;, &quot;uname&quot;);

        when(loginDao.getAdminDetails(anyString(), anyString())).thenReturn(admin);
        
        assertNotNull(loginController.login(request, response));
    }
</code></pre>
<p>but the problem is it is not functioning as I expected and <code>loginDao.getAdminDetails()</code> is returning null. plus its throwing UnneccessaryStubbingException too.</p>
<p>when I try to initialize the Dao class by using <code>mock()</code> method I do get rid of the exception, but the <code>thenReturn()</code> remains non-functional. Could anyone suggest what am I doing wrong?</p>
",https://stackoverflow.com/questions/74500209/unit-testing-mockito-when-thenreturn-not-working,"['java', 'junit', 'mockito']",67,False,0,1
Unit Testing Branch Partially Covered Using VectorCAST,"<p>I am using VectorCAST to test the code, and one branch is partially covered and I am just asking if there is a way to make it fully covered.</p>
<p>If I have a structure that it's elements are one bit in size.</p>
<p>and I have a code like this</p>
<pre><code>if(structure.bit.line1 == 0x01)
{
   //some code
}
else if(structure.bit.line1 == 0x00)
{
   //some code
}
</code></pre>
<p>I know that in the first <code>if</code> condition, I can make it fully covered by setting <code>structure.bit.line1</code> to <code>0x00</code> to satisfy the <code>FALSE</code> coverage and <code>0x01</code> to satisfy the <code>TRUE</code> coverage, but the next <code>else if</code> I only can test its <code>TRUE</code> state, so is there is a way to test the <code>FALSE</code> state.</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/74564651/unit-testing-branch-partially-covered-using-vectorcast,"['c', 'unit-testing', 'vectorcast']",90,True,0,1
Unit testing class with concrete type member,"<p>I have the following class that I want to test</p>
<pre><code>class A
{
public:
  void register()
  {
    b = new B();
  }
...
private:
  B *b;
};
</code></pre>
<p>How can I mock <code>b</code> besides adding a template parameter to <code>A</code> ?</p>
",https://stackoverflow.com/questions/74931313/unit-testing-class-with-concrete-type-member,"['c++', 'unit-testing', 'mocking']",21,False,-2,1
Kotlin Coroutines Channel unit testing in 1.6.0,"<p>I am trying to test BroadcastChannel in my viewmodel.</p>
<pre><code>@ExperimentalCoroutinesApi
@VisibleForTesting
internal val queryChannel = BroadcastChannel&lt;String&gt;(Channel.CONFLATED)

internal val internalSearchResult = queryChannel
    .asFlow()
    .debounce(SEARCH_DELAY_MS)
    .distinctUntilChanged()
    .mapLatest { name -&gt; some code here 
    result
}

@FlowPreview
@ExperimentalCoroutinesApi
val searchResult = internalSearchResult.asLiveData()
</code></pre>
<p>The code inside mapLatest is working with repository, but not launching any new coroutine.
My test class looks like this:</p>
<pre><code>class SearchViewModelTest {
        @get:Rule
    val testingRule = InstantTaskExecutorRule()
@get:Rule
val coroutinesRule = MainCoroutineDispatcherRule()

private val repository = CardSearchRepositoryStub()
private val viewModel: SearchViewModel = createSearchViewModel(repository)
private val result: SearchResult
    get() = viewModel.searchResult.getOrAwaitValue()

@Test
fun `test search query correctness`() = runTest {

    val expectedResult = SearchResult.InvalidRequest
    viewModel.queryChannel.send(&quot;       &quot;)
    advanceUntilIdle()
    assertEquals(expectedResult, result)
}
</code></pre>
<p>Where MainCoroutineDispatcherRule is</p>
<pre><code>@ExperimentalCoroutinesApi
class MainCoroutineDispatcherRule(private val dispatcher: TestDispatcher = StandardTestDispatcher()) :
    TestWatcher() {

    override fun starting(description: Description?) {
        super.starting(description)
        Dispatchers.setMain(dispatcher)
    }

    override fun finished(description: Description?) {
        super.finished(description)
        Dispatchers.resetMain()
    }
}
</code></pre>
<p>But i keep getting the error</p>
<pre><code>Test worker @coroutine#1&quot; java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used
</code></pre>
",https://stackoverflow.com/questions/72088614/kotlin-coroutines-channel-unit-testing-in-1-6-0,"['android', 'unit-testing', 'kotlin-coroutines']",672,False,0,0
unit testing - Mockito When...thenReturn not working,"<p>Im writing unit test cases of a controller file</p>
<p><strong>LoginController.java</strong></p>
<pre><code>CustomerDao customerdao = new CustomerDao();
    Customer customer = new Customer();
    InvoiceDao invoceDao = new InvoiceDao();
    DashboardDao dashboarddao = new DashboardDao();
    private static final Logger log = LogManager.getLogger(LoginController.class);
    LoginDao loginDao = null;

    @RequestMapping(value = &quot;/login.do&quot;, method = RequestMethod.POST)
    public ModelAndView login(HttpServletRequest req, HttpServletResponse res)
            throws SQLException, PropertyVetoException {
        boolean isAlpha = false;
        boolean isAdmin = false;
        boolean checkRoleAssigned = false;
        String password = req.getParameter(&quot;password&quot;);
        String staffId = req.getParameter(&quot;username&quot;);
        loginDao = new LoginDao();
        
        Admin admin = loginDao.getAdminDetails(staffId, password);
        System.err.println(&quot;\n\nadmin -&gt; &quot; + admin);
        if (admin != null) {
            int roleId = loginDao.isRoleExistInRbac(admin.getStaffId());
            checkRoleAssigned = loginDao.checkUserAccess(admin.getStaffId());
            isAlpha = loginDao.checkUserAccessInRbac(roleId);
            isAdmin= loginDao.checkAdmin(admin.getUserId());
            admin.setAdminStatus(loginDao.checkAdmin(admin.getUserId()));
            if (isAdmin) {
                HttpSession session = req.getSession();
                session.setMaxInactiveInterval(120 * 20);
                session.setAttribute(&quot;admin&quot;, admin);
                
              
                return new ModelAndView(&quot;redirect:dashboardView.do&quot;);//prevoiusly it was redirect:listInvoice.do
                

            } else {

                if (checkRoleAssigned) {
                    if (isAlpha) {
                        HttpSession session = req.getSession();
                        session.setMaxInactiveInterval(120 * 20);

                        session.setAttribute(&quot;admin&quot;, admin);

                        //return new ModelAndView(&quot;redirect:listInvoices.do&quot;);
                        return new ModelAndView(&quot;redirect:dashboardView.do&quot;);
                    } else {
                        return new ModelAndView(&quot;index&quot;, &quot;errorMessage&quot;, &quot; Sorry , You dont have any module access.&quot;);
                    }

                } else {
                    return new ModelAndView(&quot;index&quot;, &quot;errorMessage&quot;, &quot; Sorry , You are not a authorised person.&quot;);
                }

            }
        }
        return new ModelAndView(&quot;index&quot;, &quot;errorMessage&quot;, &quot; Username or password incorrect.&quot;);
    }
</code></pre>
<p>and this is the test case for this method</p>
<p><strong>LoginControllerTest.java</strong></p>
<pre><code>@InjectMocks
    LoginController loginController;
    
    @Mock
    CustomerDao customerDao;
    
    @Mock
    Customer customer;
    
    @Mock
    InvoiceDao invoiceDao;
    
    @Mock
    DashboardDao dashboardDao;
    
    @Mock
    LoginDao loginDao;

    @Mock
    Admin admin;
    
    @Test
    void testLogin() throws Exception {
        
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();
        
        request.setParameter(&quot;password&quot;, &quot;pass&quot;);
        request.setParameter(&quot;username&quot;, &quot;uname&quot;);

        when(loginDao.getAdminDetails(anyString(), anyString())).thenReturn(admin);
        
        assertNotNull(loginController.login(request, response));
    }
</code></pre>
<p>but the problem is it is not functioning as I expected and <code>loginDao.getAdminDetails()</code> is returning null. plus its throwing UnneccessaryStubbingException too.</p>
<p>when I try to initialize the Dao class by using <code>mock()</code> method I do get rid of the exception, but the <code>thenReturn()</code> remains non-functional. Could anyone suggest what am I doing wrong?</p>
",https://stackoverflow.com/questions/74500209/unit-testing-mockito-when-thenreturn-not-working,"['java', 'junit', 'mockito']",67,False,0,1
Unit Testing Branch Partially Covered Using VectorCAST,"<p>I am using VectorCAST to test the code, and one branch is partially covered and I am just asking if there is a way to make it fully covered.</p>
<p>If I have a structure that it's elements are one bit in size.</p>
<p>and I have a code like this</p>
<pre><code>if(structure.bit.line1 == 0x01)
{
   //some code
}
else if(structure.bit.line1 == 0x00)
{
   //some code
}
</code></pre>
<p>I know that in the first <code>if</code> condition, I can make it fully covered by setting <code>structure.bit.line1</code> to <code>0x00</code> to satisfy the <code>FALSE</code> coverage and <code>0x01</code> to satisfy the <code>TRUE</code> coverage, but the next <code>else if</code> I only can test its <code>TRUE</code> state, so is there is a way to test the <code>FALSE</code> state.</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/74564651/unit-testing-branch-partially-covered-using-vectorcast,"['c', 'unit-testing', 'vectorcast']",90,True,0,1
Angular: Unit testing GET method in service,"<p>I have a service method that returns item and unit test for the get method. However, the coverage shows that the getter method is not covered. Can you suggest what am I doing wrong in unit test?</p>
<pre><code>export class ItemService{
#item: Item;
  get item(): Item{
    return this.#item;
  }
}
</code></pre>
<pre><code>import itemMock from '../mocks/item-response.json';
describe('ItemService', () =&gt; {
  let itemService: ItemService;
  it('should get item information', () =&gt; {
      itemService['#item'] = itemMock ;
      spyOnProperty(itemService, 'item').and.returnValue(itemMock);
      expect(itemService['#item']).toEqual(itemMock );
  });
}
</code></pre>
",https://stackoverflow.com/questions/71466033/angular-unit-testing-get-method-in-service,"['angular', 'typescript', 'testing', 'methods', 'get']",1238,True,0,2
Rest Controller Unit testing Java Spring Boot,"<p>while mocking the controller class, i am unable to cover the catch block in my unit testing,</p>
<p>here is the code -
Controller Class -</p>
<pre><code>public ResponseEntity&lt;ResponseSentence&gt; getText(@RequestBody Text text) throws IOException {

    try {
        return new ResponseEntity&lt;&gt;(serviceImpl.getText(text), HttpStatus.OK);

    } catch (IOException e) {
        return new ResponseEntity&lt;&gt;(HttpStatus.BAD_REQUEST);
    }

}
</code></pre>
<p>this is my test class</p>
<pre><code>  @Autowired
private MockMvc mockMvc;

@MockBean
private Service service;

@MockBean
private ServiceImpl serviceImp;
@Autowired
private ObjectMapper objectMapper;



@Test
void getText() throws Exception {
    Text text = new Text();
    text.setText(&quot;&quot;);

    //given(service.getText(text)).willThrow(new IOException(&quot;boom&quot;));
    when(serviceImp.getText(text)).thenThrow(new IOException());

    ResultActions response = mockMvc.perform(post(&quot;/opennlp/v1/sentence&quot;)
            .contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(text)));


    response.andDo(print()).
            andExpect(status().isBadRequest());

    Mockito.verify(serviceImp).getText(any());

}
</code></pre>
<p>while code coverage the catch block is not covered.</p>
",https://stackoverflow.com/questions/73643655/rest-controller-unit-testing-java-spring-boot,"['spring-boot', 'unit-testing', 'junit', 'mockito', 'spring-restcontroller']",549,True,-1,1
Python unit testing - how to mock flask.current_app,"<p>I have the following method in my flask app, part of a healthchecks api:</p>
<pre><code>from flask import current_app

class Healthcheck():
    @classmethod
    def check_running(cls):
        if(current_app):
            return True, &quot;OK&quot;
        else:
            return False, &quot;Fail&quot;
</code></pre>
<p>My question is, how do I unit test the failure condition? These are my tests:</p>
<pre><code>def testRunningCheck_pass(self, flask_test_client):
    result = Healthcheck.check_running()
    assert result[0] == True, &quot;Unexpected check result&quot;
    assert result[1] == &quot;OK&quot;, &quot;Unexpected check message&quot;

@patch(&quot;flask.current_app&quot;)
def testRunningCheck_fail(self, flask_test_client):
    result = Healthcheck.check_running()
    assert result[0] == False, &quot;Unexpected check result&quot;
    assert result[1] == &quot;Fail&quot;, &quot;Unexpected check message&quot;
</code></pre>
<p><code>testRunningCheck_pass</code> passes, but <code>testRunningCheck_fail</code> bombs out with this error:</p>
<pre><code>./tests/test_healthcheck.py::TestHealthcheck::testRunningCheck_fail Failed: [undefined]RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
to interface with the current application object in some way. To solve
this, set up an application context with app.app_context().  See the
documentation for more information.
args = (&lt;tests.test_healthcheck.TestHealthcheck object at 0x110af3b50&gt;,)
keywargs = {}

    @wraps(func)
    def patched(*args, **keywargs):
&gt;       with self.decoration_helper(patched,
                                    args,
                                    keywargs) as (newargs, newkeywargs)
</code></pre>
<p>Is there a way to mock <code>flask.current_app</code> and control what is presented and be able to test that failure condition?</p>
",https://stackoverflow.com/questions/73362185/python-unit-testing-how-to-mock-flask-current-app,"['python', 'unit-testing', 'mocking']",120,False,0,0
AntBlazor unit testing with bUnit not working,"<p>I'm fairly new to Blazor, AntBlazor, and bUnit.</p>
<p>When my test executes I get the following error:</p>
<blockquote>
<p>Object reference not set to an instance of an object.
at AntDesign.Alert.OnAfterRenderAsync(Boolean firstRender)</p>
</blockquote>
<p>The component I am trying to test is making use of the <em>AntBlazor Alert</em> component.</p>
<pre><code>&lt;Alert Type=&quot;@AlertType.Error&quot; Message=&quot;Error text&quot; Closable class=&quot;mb-3&quot; /&gt;
</code></pre>
<p>When it needs to show it throws that exception but when it doesn't need to show then the test passes.</p>
<p>I do register the AntDesign services with the TestContext</p>
<pre><code>TestContext.Services.AddAntDesign();
</code></pre>
<p>Any advice would be appreciated.</p>
",https://stackoverflow.com/questions/73218858/antblazor-unit-testing-with-bunit-not-working,"['blazor-server-side', 'bunit', 'ant-blazor']",343,True,0,1
Unit testing - RestTemplate mock keeps retuning null,"<p>So Im writing unit test a class that does bankId authentication and the unit test looks like this.</p>
<pre><code>package se.kt.client;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.HttpEntity;
import se.kt.common.vo.PublicApplicationForm;
import se.kt.models.BankIdAuthRequest;
import se.kt.models.BankIdAuthResponse;
import se.kt.models.BankIdCollectResponse;
import static org.mockito.ArgumentMatchers.any;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;


@RunWith(MockitoJUnitRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class BankIdClientTest {

    private final RestTemplate restTemplate = Mockito.mock(RestTemplate.class);

    @InjectMocks
    private BankIdClient bankIdClient;

    @BeforeEach
    public void setUp() {
    }



    @Test
    public void testBankIdAuthentication_success() throws InterruptedException {
        PublicApplicationForm form = new PublicApplicationForm();
        form.setSsn(&quot;123456-7890&quot;);
        form.setIp_address(&quot;123.123.123.123&quot;);

        BankIdAuthRequest authRequest = bankIdClient.authRequestFromApplicationForm(form, &quot;123&quot;);

        BankIdAuthResponse authResponse = new BankIdAuthResponse();
        authResponse.setOrderRef(&quot;123456&quot;);

        BankIdCollectResponse collectResponse = new BankIdCollectResponse();
        collectResponse.setStatus(&quot;completed&quot;);

        Mockito.when(restTemplate.postForEntity(anyString(), any(HttpEntity.class), any()))
                .thenReturn(ResponseEntity.ok(authResponse));
        Mockito.when(restTemplate.getForEntity(anyString(), any()))
                .thenReturn(ResponseEntity.ok(collectResponse));

        assertTrue(bankIdClient.bankIdAuthentication(authRequest));
    }
}
</code></pre>
<p>And the class Im testing looks like this:</p>
<pre><code>package se.kt.client;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import se.kt.common.domain.AbstractApplicationForm;
import se.kt.common.vo.PublicApplicationForm;
import se.kt.models.BankIdAuthRequest;
import se.kt.models.BankIdAuthResponse;
import se.kt.models.BankIdCollectResponse;

import javax.validation.constraints.AssertFalse;
import javax.validation.constraints.AssertTrue;
import java.util.Objects;

@Component
public class BankIdClient {

    private static final Logger log = LoggerFactory.getLogger(BankIdClient.class);
    private final RestTemplate customRestTemplate;
    private static final String CONTENT_TYPE = &quot;Content-Type&quot;;

    @Value(&quot;${BankId.AuthUrl}&quot;)
    private String bankIdAuthUrl;

    @Value(&quot;${BankId.CollectUrl}&quot;)
    private String bankIdCollectUrl;

    @Value(&quot;${BankId.SecretKey}&quot;)
    private String bankIdSecretKey;

    public BankIdClient(RestTemplate customRestTemplate) {
        this.customRestTemplate = customRestTemplate;
    }

    public BankIdAuthRequest authRequestFromApplicationForm(PublicApplicationForm form, String jobId) {
        BankIdAuthRequest bankIdAuthRequest = new BankIdAuthRequest();
        bankIdAuthRequest.setPno(form.getSsn());
        bankIdAuthRequest.setIpAddress(form.getIp_address());
        bankIdAuthRequest.setRefID(jobId);
        bankIdAuthRequest.setSecretKey(bankIdSecretKey);
        bankIdAuthRequest.setAvsikt(&quot;Kt application&quot;);

        return bankIdAuthRequest;
    }

    public boolean bankIdAuthentication(BankIdAuthRequest bankIdAuthRequest) throws InterruptedException {
        //Setup header and body for request.
        HttpHeaders headers = new HttpHeaders();
        headers.add(CONTENT_TYPE, MediaType.APPLICATION_JSON.toString());

        ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();

        try {
            String bankIdAuthFormJson = ow.writeValueAsString(bankIdAuthRequest);

            HttpEntity&lt;String&gt; httpEntity = new HttpEntity&lt;&gt;(bankIdAuthFormJson, headers);
            ResponseEntity&lt;BankIdAuthResponse&gt; authResponse = customRestTemplate.postForEntity(bankIdAuthUrl, httpEntity, BankIdAuthResponse.class);

            bankIdCollectUrl += Objects.requireNonNull(authResponse.getBody()).getOrderRef();

            ResponseEntity&lt;BankIdCollectResponse&gt; collectResponse;

            do {
                collectResponse = customRestTemplate.getForEntity(bankIdCollectUrl, BankIdCollectResponse.class);

                Thread.sleep(1500);

                if (Objects.requireNonNull(collectResponse.getBody()).getStatus().equals(&quot;completed&quot;))
                    return true;
                if (Objects.requireNonNull(collectResponse.getBody()).getStatus().equals(&quot;failed&quot;))
                    return false;
            } while (Objects.requireNonNull(collectResponse.getBody()).getStatus().equals(&quot;progress&quot;));

        } catch (JsonProcessingException e) {
            log.info(e.getMessage());
        } catch (NullPointerException e) {
            log.info(e.toString());
            log.info(&quot;BankId API not responding correctly. Check server connection&quot;);
        }
        return false;
    }

    public void cancelBankIdAuthentication(@Value(&quot;${BankId.CancelUrl}&quot;) String bankIdCancelUrl) {
        customRestTemplate.postForEntity(bankIdCancelUrl, null, String.class);
    }
}
</code></pre>
<p>Now for some reson this line:</p>
<pre><code>ResponseEntity&lt;BankIdAuthResponse&gt; authResponse = customRestTemplate.postForEntity(bankIdAuthUrl, httpEntity, BankIdAuthResponse.class);
</code></pre>
<p>keeps producing the result <code>authResponse = null</code> indicating that</p>
<pre><code>Mockito.when(restTemplate.postForEntity(anyString(), any(HttpEntity.class), any()))
                .thenReturn(ResponseEntity.ok(authResponse));
</code></pre>
<p>is not working. Now I have been playing around with this for over 3h and i still get the same result. What could i be doing wrong?</p>
",https://stackoverflow.com/questions/74866026/unit-testing-resttemplate-mock-keeps-retuning-null,"['java', 'spring-boot', 'unit-testing', 'junit', 'mockito']",81,False,0,1
MongoDB C# Driver Unit Testing: Mock .AsQueryable(),"<p>I am using .NET 4.7.2 and latest MongoDB.
I heavily use the drivers support for LINQ.</p>
<p>This is what a standard usage in my repos looks like:</p>
<pre><code> var strategies = this.mongoClient.GetDatabase(&quot;test&quot;).GetCollection&lt;Strategy&gt;(&quot;strategies&quot;)
                .AsQueryable(new AggregateOptions { Hint = MongoDbIndexCreator.RunningStrategies })
                .Where(x =&gt; x.IsRunning == true);
</code></pre>
<p>I found ways to mock <code>IMongoQueryable</code> and <code>GetCollection</code>but static extension <code>.AsQueryable()</code> really is a problem for me.
Does anybody have a solution for this? How do MongoDB LINQ users unit test their applications?
Ideally I would not bother with mocking at all and rather use some kind of in-memory set up? But I am afraid there is no such thing for MongoDB?</p>
<p>A wrapper / abstraction does not help me either:</p>
<pre><code>  public interface IMongoDbProvider
    {
        IMongoCollection&lt;T&gt; GetCollection&lt;T&gt;();

        IMongoQueryable&lt;T&gt; GetQueryable&lt;T&gt;();
    }
</code></pre>
<p>Users of <code>IMongoDbProvider</code> still depend on either <code>IMongoCollection</code> or <code>IMongoQueryable</code> to leverage database features.</p>
",https://stackoverflow.com/questions/74486301/mongodb-c-driver-unit-testing-mock-asqueryable,"['c#', 'mongodb', 'unit-testing']",159,False,0,0
Unable to run unit testing with Robolectric,"<p>I have been having multiple errors when trying to run unit tests with <code>Robolectric</code>.</p>
<p>I am using <code>testImplementation 'org.robolectric:robolectric:4.8'</code></p>
<p>This is the error:</p>
<pre><code>java.lang.IllegalStateException: ClassLoader org.robolectric.internal.AndroidSandbox$SdkSandboxClassLoader should be of type BaseDexClassLoader

    at com.facebook.soloader.SoLoader$Api14Utils.getClassLoaderLdLoadLibrary(SoLoader.java:1258)
    at com.facebook.soloader.DirectApkSoSource.getDirectApkLdPath(DirectApkSoSource.java:93)
    at com.facebook.soloader.DirectApkSoSource.&lt;init&gt;(DirectApkSoSource.java:52)
    at com.facebook.soloader.SoLoader.addDirectApkSoSource(SoLoader.java:346)
    at com.facebook.soloader.SoLoader.initSoSources(SoLoader.java:293)
    at com.facebook.soloader.SoLoader.init(SoLoader.java:239)
    at com.facebook.soloader.SoLoader.init(SoLoader.java:255)
    at com.unicc.certificateofentitlement.MainApplication.onCreate(MainApplication.java:66)
    at org.robolectric.android.internal.AndroidTestEnvironment.lambda$installAndCreateApplication$2(AndroidTestEnvironment.java:350)
    at org.robolectric.util.PerfStatsCollector.measure(PerfStatsCollector.java:86)
</code></pre>
",https://stackoverflow.com/questions/74037987/unable-to-run-unit-testing-with-robolectric,"['android', 'unit-testing', 'robolectric']",188,False,0,0
toHaveBeenCalled() not working correctly Angular Unit Testing,"<p>I have following object in my angular component:</p>
<pre><code>let _user = {user: { id: 1 } };

ngOnInit(){
   if(Object.keys(_user.user).length &gt; 0){
       callSomething()
   }
}
</code></pre>
<p>=&gt; now for that component spec.ts file</p>
<pre><code>describe(&quot;&quot;,() =&gt; {
    let _user = { user: {id: 1} };   
    let component: TempComponent;
    let fixture: ComponentFixture&lt;TempComponent&gt;;
  
    beforeEach(() =&gt; {
         ... component configuration

         fixture.detectChanges(); 
         // this will call lifecycle methods and from there component's callSomething() will also get called.
    });

    it(&quot;should not call callSomething() if user properties == 0&quot;, () =&gt; {
        delete _user.user[&quot;id&quot;];
        // now _user will be only { user: {} }

        component.ngOnInit(); // or can call fixture.detectChanges();

        expect(component.callSomething).not.toHaveBeenCalled();
        // as now the user object will be empty, but because of beforeEach's detectChanges call, it is failing.
    });
});
</code></pre>
<p>Problem:</p>
<p>Here, when I run the test case it fails saying</p>
<blockquote>
<p>Expected spy not to have been called.</p>
</blockquote>
<p>with debugging, I figured out that it is failing because initially from <strong>fixture.detectChanges()</strong> ngOnInit called from there based on the condition <strong>callSomething()</strong> also got called.</p>
<p>So, when the testcase runs it has already called callSomething(). So, it is failing.</p>
<p>What shall I do, to test the case properly?</p>
",https://stackoverflow.com/questions/70711738/tohavebeencalled-not-working-correctly-angular-unit-testing,"['angular', 'unit-testing', 'jasmine', 'angular11']",1151,True,-1,1
MSTest: Unit Testing HttpContext.SignoutAsync for the logout,"<p>Simply passing Mock HttpContext to the controller context while unit testing logout functionality will throw following error
<strong>HttpContext.Signout + value can not be null (Parameter 'provider')</strong></p>
<pre><code>var mockHttpContext = new Mock&lt;HttpContext&gt;();

       
</code></pre>
<p>//set the controller HttpContext</p>
<pre><code>_controller.ControllerContext.HttpContext = mockHttpContext.Object;
</code></pre>
<p>// Now call the Logout action method and Test result</p>
",https://stackoverflow.com/questions/71168289/mstest-unit-testing-httpcontext-signoutasync-for-the-logout,"['mstest', 'httpcontext']",456,True,0,1
Unit Testing a Controller method returns null,"<p>I'm trying to learn Unit testing in .NET 6 by testing a controller function <code>GetProduct</code>. The problem is I get null returned in the variable <code>var product = await _productController.GetProduct(productId);</code>. As you can see in the picture below, the <code>Result</code> is ok but the <code>Value</code>, where the <code>ServiceResponse&lt;Product&gt;</code> was suppose to be is null.</p>
<p><a href=""https://i.stack.imgur.com/QkrYB.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/QkrYB.png"" alt=""enter image description here"" /></a></p>
<p>Here is the controller function:</p>
<pre><code>public class ProductController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet(&quot;{productId}&quot;)]
    public async Task&lt;ActionResult&lt;ServiceResponse&lt;Product&gt;&gt;&gt; GetProduct(int productId)
    {
        var result = await _productService.GetProductAsync(productId);
        return Ok(result);
    }
}
</code></pre>
<p>Here is the Test:</p>
<pre><code>public class ProductControllerTest
{
    private readonly ProductController _productController;
    private readonly Mock&lt;IProductService&gt; _productService = new Mock&lt;IProductService&gt;();

    public ProductControllerTest()
    {
        _productController = new ProductController(_productService.Object);
    }    

    [Test]
    public async Task GetProducts_ReturnsProduct_IfProductExists()
    {
        //Arange
        var productId = 1;
        var prodData = new Product
        {
            Id = productId,
            Title = &quot;null&quot;            
        };
        var prductResponse = new ServiceResponse&lt;Product&gt;
        {
            Data = prodData,
            Success = true ,
            Message = &quot;&quot;
        };

        _productService.Setup(x =&gt; x.GetProductAsync(productId)).ReturnsAsync(prductResponse);

        //Act
        var product = await _productController.GetProduct(productId);

        //Assert
        Assert.That(product?.Value?.Data?.Id, Is.EqualTo(productId));
    }

}
</code></pre>
",https://stackoverflow.com/questions/73139320/unit-testing-a-controller-method-returns-null,"['c#', '.net', 'unit-testing']",383,True,0,2
Unit testing a mobx store in React,"<p>Relatively new to MobX and wondering what the best approach would be to testing a MobX store using Jest that is using other stores in a few of their methods.</p>
<p>For example, in this <code>EpochManager</code> class, the <code>updateWatch</code> method is calling the <code>loadingPromise</code> method on the <code>unirepConfig</code> class. To test this method properly, do I have to instantiate the <code>UnirepConfig</code> class, too (and other stores that are used)?</p>
<p>Would appreciate more feedback on this. Thanks.</p>
<p>Here is the class in its entirety:</p>
<pre><code>import { createContext } from 'react'
import UnirepContext from './Unirep'
import UserContext from './User'
import { makeAutoObservable } from 'mobx'

const unirepConfig = (UnirepContext as any)._currentValue
const userContext = (UserContext as any)._currentValue

export class EpochManager {
    private timer: NodeJS.Timeout | null = null
    private currentEpoch = 0
    readonly nextTransition = 0
    readyToTransition = false

    constructor() {
        makeAutoObservable(this)
        if (typeof window !== 'undefined') {
            this.updateWatch()
        }
    }

    async updateWatch() {
        await unirepConfig.loadingPromise
        if (this.timer) {
            clearTimeout(this.timer)
            this.timer = null
        }
        this.readyToTransition = false
        this.currentEpoch = await unirepConfig.currentEpoch()
        // load the last transition time
        ;(this as any).nextTransition = await this._nextTransition()
        const waitTime = Math.max(this.nextTransition - +new Date(), 0)
        console.log(
            `Next epoch transition in ${waitTime / (60 * 60 * 1000)} hours`
        )
        this.timer = setTimeout(() =&gt; {
            this.timer = null
            this.tryTransition()
        }, waitTime) // if it's in the past make wait time 0
        return waitTime
    }

    private async _nextTransition() {
        await unirepConfig.loadingPromise
        const [lastTransition, epochLength] = await Promise.all([
            unirepConfig.unirep.latestEpochTransitionTime(),
            unirepConfig.epochLength,
        ])
        return (lastTransition.toNumber() + epochLength) * 1000
    }

    private async tryTransition() {
        // wait for someone to actually execute the epoch transition
        for (;;) {
            // wait for the epoch change to happen
            const newEpoch = await userContext.loadCurrentEpoch()
            if (newEpoch &gt; this.currentEpoch) {
                // we're ready to transition,
                this.currentEpoch = newEpoch
                this.readyToTransition = true
                return
            }
            await new Promise((r) =&gt; setTimeout(r, 10000))
        }
    }
}

export default createContext(new EpochManager())
</code></pre>
",https://stackoverflow.com/questions/74240119/unit-testing-a-mobx-store-in-react,"['reactjs', 'unit-testing', 'jestjs', 'mobx', 'mobx-react']",129,False,0,0
Unit testing imports urlparse python 2/3,"<p>I want to test part of code that copes for python 2/3 differences with urlparse. Below is a sample code. I am trying to run my unit test in python3 and want to unit test part of ImportError code.</p>
<p>sample.py</p>
<pre><code>try:
    from urllib.parse import urlparse
except ImportError:
    from urlparse import urlparse


def add_num(a, b):
return a + b
</code></pre>
<p>Below is what I tried, but I am not able to hit the ImportError</p>
<p>test_sample.py</p>
<pre><code>import sample
import mock
import sys

def test_urlparse():
    with mock.patch.dict(sys.modules, {'urlparse': None}):
        sample.add_num(1, 2)
</code></pre>
<p>How can we unit test this ? Thanks in advance</p>
",https://stackoverflow.com/questions/73948935/unit-testing-imports-urlparse-python-2-3,"['python', 'unit-testing', 'python-unittest', 'urlparse']",73,False,0,0
Reactive State function unit testing in vue,"<p>I am very new to unit testing. I have reactive state usage in the component. would like to write unit testing for the component.</p>
<p>The example test component is defined below</p>
<pre><code> &lt;script setup lang=&quot;ts&quot;&gt;
 const state = reactive({ 
  isExpired: true as boolean, 
 })
 &lt;/script&gt;
&lt;template&gt;
    &lt;div class=&quot;container&quot; v-if=&quot;state.isExpired === false&quot;&gt;&lt;/div&gt;
&lt;/template&gt;
</code></pre>
<p>Here, I want to check whether the container is rendering or not. isExpired value will be dynamically changed.</p>
<p>I have tried the test cases for the component as shared below</p>
<pre><code>describe(&quot;Test suit for component&quot;,()=&gt;{
   let wrapper = shallowMount(TestComponent,{
     isExpired : false
   });
   it(&quot;its should display container style&quot;,async ()=&gt;{ 
      expect(wrapper.find('.container').exists()).toBeTruthy();
   });
});
</code></pre>
<p>I am not able to find the relevant unit testing in the online resources. Would like to know how to test the reactive state of component.</p>
",https://stackoverflow.com/questions/73189637/reactive-state-function-unit-testing-in-vue,"['vue.js', 'jestjs', 'vuejs3', 'ts-jest']",544,False,0,1
Golang: unit testing fuction depenent on io.File.Write(),"<p>Hеllo, fellow Gophers!</p>
<p>Learning how to write unit tests and got stuck. Please, don't beat me up, cause I am new to this. I've googled and read a lot, but I still couldn't come up with a proper solution.
The exercise is to write a unit test for a function I wrote:</p>
<p><a href=""https://github.com/no-to-mediocrity/Learning_GO/blob/main/gocopy/main.go"" rel=""nofollow noreferrer"">Filecopy</a>(pathfrom, pathto string, limit, offset int64) error</p>
<p>The simplified function will look like this</p>
<pre><code>source, err := os.Open(pathfrom)
    destination, err := os.Create(pathto)
    buf := make([]byte, *buffersize)
    for {
        n, err := source.Read(buf)
        if err != nil &amp;&amp; err != io.EOF {
            return err
        }
        if _, err := destination.Write(buf[pos:n]); err != nil {
            return err
            if n == 0 {
                break
            }
        }
    }
</code></pre>
<p>Now I have to unit test it. And it's not going well. There are two ways I could test it:</p>
<ol>
<li>Provide it a real temp file with a predetermined contents, so the test function would know what to expect after the execution. Should work, but I read this option is NOT the way to unit test properly as it touches the FS.</li>
<li>Use fake FS. I've tried testing files generated by mapfs and afero, but no luck, my function doesn't work with it (it works with real files though), either I am doing something wrong.</li>
</ol>
<p>Please tell me how to unit test my function properly. Any help will be appreciated.</p>
",https://stackoverflow.com/questions/73319469/golang-unit-testing-fuction-depenent-on-io-file-write,"['go', 'testing', 'io']",302,False,0,0
Failed to patch object for unit testing,"<p>I have a class used to authenticate with google sheet API and retrieve data from some spreadsheets.<br />
Here a part of it:</p>
<p>spreadsheet.py</p>
<pre><code>from typing import Optional
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
import gspread


class GoogleSheet:
    def __init__(self, token_file: str):
        self.token_file: str = token_file
        self.google_client: Optional[gspread.Client] = None
        self.gsheet: Optional[gspread.Spreadsheet] = None

    def setup_connection(self) -&gt; None:
        credentials: Credentials = Credentials.from_authorized_user_file(self.token_file)
        if credentials.expired:
            credentials.refresh(Request())
        self.google_client = gspread.authorize(credentials)

    def open_gsheet_by_url(self, gsheet_url: str) -&gt; None:
        self.gsheet = self.google_client.open_by_url(gsheet_url)
</code></pre>
<p>I wanted to create some tests for the previous code.<br />
Here is what I ended to:<br />
test_spreadsheet.py</p>
<pre><code>import pytest
from spreadsheet import GoogleSheet
from unittest.mock import patch


class TestSpreadSheetData:
    @patch('spreadsheet.Credentials')
    @patch('spreadsheet.gspread')
    def test_setup_connection(self, mocked_creds, mocked_auth):
        google_sheet = GoogleSheet('api_token.json')
        google_sheet.setup_connection()
        assert mocked_creds.from_authorized_user_file.call_count == 1
        assert mocked_auth.authorize.call_count == 1
</code></pre>
<p>I tried the code above but it didn't work although I had similar approach with different project and packages.
So whenever I run the test, I get the following error:</p>
<pre><code>AssertionError
Assert 0 == 1
</code></pre>
<p>Can anyone helps me fix this?</p>
",https://stackoverflow.com/questions/70881553/failed-to-patch-object-for-unit-testing,"['python', 'unit-testing', 'pytest']",152,False,0,0
unit testing __init_subclass__ method in python 3.x,"<p>I am trying to unit test an inherited class for which its base class implements <code> __init_subclass__</code> method. Code is the following:</p>
<h4><strong><code>quick_test.py</code></strong></h4>
<pre class=""lang-py prettyprint-override""><code>import unittest
from unittest.mock import create_autospec

class Parent():

    PROPERTY = NotImplemented

    def __init_subclass__(cls, **kwargs):
        if cls.PROPERTY is NotImplemented:
            raise NotImplementedError(&quot;Please implement the `PROPERTY`.&quot;)
        super().__init_subclass__(**kwargs)

    def __init__(self, connection_type=&quot;default&quot;):
        self.connection_type = connection_type


class Child(Parent):

    PROPERTY = &quot;has value&quot;


class ChildNoProp(Parent):
    pass


class TestClass(unittest.TestCase):

    def test_required_params(self):
        mock = create_autospec(Child)
        self.assertRaises(NotImplementedError, mock)


if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>The problem is I can't even reach the test case because <code>ChildNoProp</code> definition calls <code>__init_subclass__</code> in base class and raises exception.</p>
<p>Is there a way I can unit test this with current implementation, or should I scrap the error raising in <code>__init_subclass__</code>?</p>
",https://stackoverflow.com/questions/72438984/unit-testing-init-subclass-method-in-python-3-x,"['python', 'testing', 'inheritance', 'definition']",164,True,4,1
NUnit - Unit testing two separate tests in parallel,"<p>I understand NUnit runs tests in parallel, which isn't what this question is about exactly. In a single test, I can have two local socket connections open using TcpClient on different ports, which can communicate with one another in the same unit test. The problem is the address space is of course shared by the thread executing the unit test, so it doesn't simulate communication through a network how I want.</p>
<p>If I have a test called Test1 with one TcpClient, and whilst it's running, I run Test2 with the other TcpClient, in these two tests I can have both the unit tests talking to one another and communicating - testing the protocol I've designed with separate address spaces, which does give me the simulation of a network I desire, and allows me to do the proper test assertions.</p>
<p>Now the question is, is there any way to do this automatically? I'd like to have a single test that can run Test1 &amp; Test2, where both these tests communicate via their respective sockets, instead of starting them both up manually in parallel.</p>
",https://stackoverflow.com/questions/74442164/nunit-unit-testing-two-separate-tests-in-parallel,"['c#', '.net', 'nunit', 'rider']",153,True,3,2
Electron - Need unit testing framework for bundled app,"<p>we are using electron framework to create <strong>WINDOWS</strong> and <strong>MAC</strong> installer. For frontend, we are using Angular to show data.
We are also using <strong>sqlite3</strong> database to store data locally in user's system using node.js.</p>
<p>Everything working fine like api calling using <strong>AXIOS</strong>, intercating with our local database(CRUD), intercating with client side(frontend) with <strong>electron-ipc-renderer</strong>, file system handling.
Our application is working properly as expected.</p>
<p>We are stuck with unit testing of our application.</p>
<p>We want to do end to end testing which will consume electrons basic libraries like:-</p>
<ul>
<li><strong>app</strong></li>
<li><strong>BrowserWindow</strong></li>
<li><strong>dialog</strong></li>
<li><strong>Menu</strong></li>
<li><strong>remote</strong></li>
<li><strong>screen</strong></li>
<li><strong>ipcMain</strong></li>
</ul>
<p>And we are using other node libraries also like <strong>axios, path, chokidar, sqlite3</strong>.</p>
<p>Has anyone achieved Unit test cases for such kind Electron App/knows anything which can help us?</p>
",https://stackoverflow.com/questions/74949787/electron-need-unit-testing-framework-for-bundled-app,"['node.js', 'unit-testing', 'electron', 'electron-builder', 'testcase']",56,False,3,0
Unit Testing in ts-jest with TypeOrm entities,"<p>Am trying to write tests, but am getting error. i think i have problem with connection.
&quot;Cannot execute operation on &quot;default&quot; connection because connection is not yet established.&quot;</p>
<p>i have tests folder, and in it am having <code>user.spec.ts</code> and <code>testhelper.ts</code></p>
<p>testhelper.ts</p>
<pre><code>// import { Connection, createConnection } from &quot;typeorm&quot;;
import { DataSource, DataSourceOptions } from &quot;typeorm&quot;;

import Database from &quot;better-sqlite3&quot;;

export class TestHelper {
  private static _instance: TestHelper;

  private constructor() {}

  public static get instance(): TestHelper {
    if (!this._instance) this._instance = new TestHelper();

    return this._instance;
  }

  private dbConnect!: DataSource;
  private testdb!: any;
  async setupTestDB() {
    this.testdb = new Database(&quot;:memory:&quot;, { verbose: console.log });

    this.dbConnect = new DataSource({
      name: &quot;default&quot;,
      type: &quot;better-sqlite3&quot;,
      database: &quot;:memory:&quot;,
      entities: [&quot;src/entity/**/*.ts&quot;],
      synchronize: true,
    } as DataSourceOptions);
  }

  teardownTestDB() {
    this.dbConnect.destroy();
    this.testdb.close();
  }
}
</code></pre>
<p>user.spec.ts</p>
<pre><code>import { createUser } from &quot;../src/controllers/user.controller&quot;;
//@ts-ignore
import { TestHelper } from &quot;./testhelper&quot;;

beforeAll(async () =&gt; {
  await TestHelper.instance.setupTestDB();
});

afterAll(() =&gt; {
  TestHelper.instance.teardownTestDB();
});

describe(&quot;User Tests&quot;, () =&gt; {
  test(&quot;should create user&quot;, async () =&gt; {
    const body = {
      firstname: &quot;John&quot;,
      lastname: &quot;Brut&quot;,
      email: &quot;john@examle.com&quot;,
      password: &quot;password123&quot;,
    };
    const res = {};
    //@ts-ignore
    const user = await createUser(body, res);
    //@ts-ignore
    expect(user.firstname).toBe(&quot;John&quot;);
    //@ts-ignore
    expect(user.lastname).toBe(&quot;Brut&quot;);
  });
});
</code></pre>
<p>I'm doing this first time. and am stuck on it very long time... can someone please help me with this... : (</p>
",https://stackoverflow.com/questions/72739602/unit-testing-in-ts-jest-with-typeorm-entities,"['javascript', 'typescript', 'jestjs', 'typeorm']",2684,False,3,1
How to write unit testing for streaming API,"<p>I have a <em><strong>consume</strong></em> function which get streaming response from a Restful API. How could I write JUnit testing on it?</p>
<p>I tried to create a test for the <em><strong>consume</strong></em> function but it looks like skipping the restTemplate execute call completely. Is there a way I could create a mock stream for the response so that I could process the data batches?</p>
<pre><code>@Override
public void consume(
        final String url, final String jwt,
        final Consumer&lt;StreamingDataBatch&gt; dataBatchConsumer) {

    final StreamingQueryRequest request = StreamingParameterizedQueryRequest.builder().responseBatchSize(batchSize).build();

    restTemplate.execute(url, HttpMethod.POST,
            req -&gt; {
                req.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                req.getHeaders().set(&quot;Authorization&quot;, jwt);
                restTemplate.httpEntityCallback(request)
                        .doWithRequest(req);
            },
            resp -&gt; {
                processStream(resp.getBody(), dataBatchConsumer);
                return null;
            });
}

private void processStream(
        final InputStream inputStream,
        final Consumer&lt;StreamingDataBatch&gt; dataBatchConsumer) throws IOException {

    final JsonFactory jsonFactory = objectMapper.getFactory();
    try (final JsonParser jsonParser = jsonFactory.createParser(inputStream)) {
        final JsonToken arrayToken = jsonParser.nextToken();
        if (!JsonToken.START_ARRAY.equals(arrayToken)) {
            throw new IllegalStateException(&quot;The response is not a JSON array.&quot;);
        }
        // Iterate through the objects of the array.
        while (JsonToken.START_OBJECT.equals(jsonParser.nextToken())) {
            final StreamingDataBatch batchData = jsonParser.readValueAs(
                    StreamingDataBatch.class);
            dataBatchConsumer.accept(batchData);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/73822855/how-to-write-unit-testing-for-streaming-api,"['java', 'api', 'rest', 'streaming']",165,False,2,0
"How to unit testing with Gorm, mux, postgresql","<p>I'm new in Go and unit test. I build a samll side projecy called &quot;urlshortener&quot; using Go with Gorm, mux and postgresql.</p>
<p>There is a qeustion annoying me after search many articles.</p>
<p>To make the question clean, I delete some irrelevant code like connect db, .env, etc</p>
<p>My code is below(main.go):</p>
<pre><code>package main

type Url struct {
    ID       uint   `gorm:&quot;primaryKey&quot;` // used for shortUrl index
    Url      string `gorm:&quot;unique&quot;`     // prevent duplicate url
    ExpireAt string
    ShortUrl string
}

var db *gorm.DB
var err error


func main() {
    // gain access to database by getting .env
    ...

    // database connection string
    ...

    // make migrations to the dbif they have not already been created
    db.AutoMigrate(&amp;Url{})

    // API routes
    router := mux.NewRouter()

    router.HandleFunc(&quot;/{id}&quot;, getURL).Methods(&quot;GET&quot;)

    router.HandleFunc(&quot;/api/v1/urls&quot;, createURL).Methods(&quot;POST&quot;)
    router.HandleFunc(&quot;/create/urls&quot;, createURLs).Methods(&quot;POST&quot;)

    // Listener
    http.ListenAndServe(&quot;:80&quot;, router)

    // close connection to db when main func finishes
    defer db.Close()
}
</code></pre>
<p>Now I'm building unit test for getURL function, which is a GET method to get data from my postgresql database called urlshortener and the table name is urls.</p>
<p>Here is getURL function code:</p>
<pre><code>func getURL(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    var url Url

    err := db.Find(&amp;url, params[&quot;id&quot;]).Error
    if err != nil {
        w.WriteHeader(http.StatusNotFound)
    } else {
        w.WriteHeader(http.StatusOK)
        json.NewEncoder(w).Encode(url.Url)
    }
}
</code></pre>
<p>This is work fine with my database. See curl command below:
<a href=""https://i.stack.imgur.com/XLXl3.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/XLXl3.png"" alt=""enter image description here"" /></a></p>
<p>I know that the unit test is not for mock data, and it aim to test a function/method is stable or not. Although I import mux and net/http for conncetion, but I think the unit test on it should be &quot;SQL syntax&quot;. So I decide to focus on testing if gorm return the right value to the test function.</p>
<p>In this case, db.Find will return a *gorm.DB struct which should be exactly same with second line. (see docs <a href=""https://gorm.io/docs/query.html"" rel=""nofollow noreferrer"">https://gorm.io/docs/query.html</a>)</p>
<pre><code>db.Find(&amp;url, params[&quot;id&quot;])
</code></pre>
<pre><code>SELECT * FROM urls WHICH id=&lt;input_number&gt;
</code></pre>
<p>My question is how to write a unit test on it for check the SQL syntax is correct or not in this case (gorm+mux)? I've check some articles, but most of them are testing the http connect status but not for SQL.</p>
<p>And my function do not have the return value, or I need to rewrite the function to have a return value before I can test it?</p>
<p>below is the test structure in my mind:</p>
<pre><code>func TestGetURL(t *testing.T) {

    //set const answer for this test

    //set up the mock sql connection

    //call getURL()
    
    //check if equal with answer using assert

}
</code></pre>
<p><strong>Update</strong></p>
<p>According to <a href=""https://stackoverflow.com/users/7567579/emin-laletovic"">@Emin Laletovic</a> answer</p>
<p>Now I have a prototype of my testGetURL. Now I have new questions on it.</p>
<pre><code>func TestGetURL(t *testing.T) {
    //set const answer for this test
    testQuery := `SELECT * FROM &quot;urls&quot; WHERE id=1`
    id := 1

    //set up the mock sql connection
    testDB, mock, err := sqlmock.New()
    if err != nil {
        panic(&quot;sqlmock.New() occurs an error&quot;)
    }

    // uses &quot;gorm.io/driver/postgres&quot; library
    dialector := postgres.New(postgres.Config{
        DSN:                  &quot;sqlmock_db_0&quot;,
        DriverName:           &quot;postgres&quot;,
        Conn:                 testDB,
        PreferSimpleProtocol: true,
    })
    db, err = gorm.Open(dialector, &amp;gorm.Config{})
    if err != nil {
        panic(&quot;Cannot open stub database&quot;)
    }

    //mock the db.Find function
    rows := sqlmock.NewRows([]string{&quot;id&quot;, &quot;url&quot;, &quot;expire_at&quot;, &quot;short_url&quot;}).
        AddRow(1, &quot;http://somelongurl.com&quot;, &quot;some_date&quot;, &quot;http://shorturl.com&quot;)

    mock.ExpectQuery(regexp.QuoteMeta(testQuery)).
        WillReturnRows(rows).WithArgs(id)

    //create response writer and request for testing
    mockedRequest, _ := http.NewRequest(&quot;GET&quot;, &quot;/1&quot;, nil)
    mockedWriter := httptest.NewRecorder()

    //call getURL()
    getURL(mockedWriter, mockedRequest)

    //check values in mockedWriter using assert

}

</code></pre>
<p>In the code, I mock the request and respone with http, httptest libs.
I run the test, but it seems that the getURL function in main.go cannot receive the args I pass in, see the pic below.
<a href=""https://i.stack.imgur.com/Q3uqS.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Q3uqS.png"" alt=""enter image description here"" /></a></p>
<p>when <code>db.find</code> called, <code>mock.ExpectQuery</code> receive it and start to compare it, so far so good.</p>
<pre><code>db.Find(&amp;url, params[&quot;id&quot;])
</code></pre>
<pre><code>mock.ExpectQuery(regexp.QuoteMeta(testQuery)).WillReturnRows(rows).WithArgs(id)
</code></pre>
<p>According to the testing log, it shows that when <code>db.Find</code> triggerd, it only excute <code>SELECT * FROM &quot;urls&quot;</code> but not I expected <code>SELECT * FROM &quot;urls&quot; WHERE &quot;urls&quot;.&quot;id&quot; = $1</code>.</p>
<p>But when I test <code>db.Find</code> on local with postman and log the SQL syntax out, it can be excute properly. see pic below.
<a href=""https://i.stack.imgur.com/BnOkX.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/BnOkX.png"" alt=""enter image description here"" /></a></p>
<p>In summary, I think the problem is the responeWriter/request I put in <code>getURL(mockedWriter, mockedRequest)</code> are wrong, and it leads that <code>getURL(w http.ResponseWriter, r *http.Request)</code> cannot work as we expect.</p>
<p>Please let me know if I missing anything~</p>
<p>Any idea or way to rewrite the code would be help, thank you!</p>
",https://stackoverflow.com/questions/71645815/how-to-unit-testing-with-gorm-mux-postgresql,"['rest', 'unit-testing', 'go', 'go-gorm', 'mux']",2610,True,2,2
Getting error while using useHeaderHeight() in unit-testing,"<p>Using <code>@react-navigation/stack</code> library in my project, while doing unit testing (using jest) I am getting this error</p>
<blockquote>
<p>Couldn't find the header height. Are you inside a screen in Stack?</p>
</blockquote>
<p>index.spec.js</p>
<pre><code>  it('should have a title and subtitle', () =&gt; {
  const { getByText } = render(&lt;Otp {...props} /&gt;);      });
</code></pre>
<p>Otp component</p>
<pre><code>&lt;SafeAreaView style={styles.mainContainer}&gt;
  &lt;KeyboardAvoidingView
    keyboardVerticalOffset={useHeaderHeight()} --&gt; getting error at this line
  &gt;
    &lt;Text&gt;...&lt;/Text&gt;
  &lt;/KeyboardAvoidingView&gt;
&lt;/SafeAreaView&gt;
</code></pre>
<p>Also tried a solution in which I mocked a navigator but got no success.</p>
",https://stackoverflow.com/questions/70894700/getting-error-while-using-useheaderheight-in-unit-testing,"['react-native', 'jestjs', 'react-navigation']",424,False,2,1
Unit testing NodeJS stream with jest - timeout issue,"<p>Given the following NodeJS Transform Stream:</p>
<pre><code>class ObjectToCSVTransform extends Transform {
  private hasSetHeaders: boolean;

  constructor() {
    super({ objectMode: true });
    this.hasSetHeaders = false;
  }

  static create(): ObjectToCSVTransform {
    return new this();
  }

  _write(
    object: Record&lt;string, unkwnown&gt;,
    _encoding: BufferEncoding,
    callback: TransformCallback
  ): void {
    this.push(this.generateCSV(telemetry));
    callback();
  }

  private generateCSV(object: Record&lt;string, unkwnown&gt;): string {
    let csv = '';

    if (!this.hasSetHeaders) {
      csv += this.createCSVHeaders(object);
      this.hasSetHeaders = true;
    }

    csv += this.createRecord(object);

    return csv;
  }

  private createCSVHeaders(object: Record&lt;string, unkwnown&gt;): string {
    return `${Object.keys(object)}\n`;
  }

  private createCSVRecord(object: Record&lt;string, unkwnown&gt;): string {
    return `${Object.values(object)}\n`;
  }
}
</code></pre>
<p>I implemented the following test case (using <strong>jest</strong>), to test that given a stream of plain objects of the <em>&quot;same type&quot;</em> the expected output is a valid CSV representation of them:</p>
<pre><code>describe('object to csv stream', () =&gt; {
  const items: Record&lt;string, unknown&gt; = [
    { foo: 1, bar: 2, baz: 3 },
    { foo: 10, bar: 20, baz: 30 },
    { foo: 100, bar: 200, baz: 300 },
  ];

  it('should transform a list of items to csv', (done) =&gt; {
    const expectedCsv = 'foo,bar,baz\n1,2,3\n10,20,30\n100,200,300\n';
    let csv = '';

    Readable.from(items)
      .pipe(ObjectToCSVTransform.create())
      .on('data', (csvResult) =&gt; {
        csv += csvResult;
        console.log(csvResult); // just for debugging purposes
      })
      .on('end', () =&gt; {
        console.log('streaming ended'); // just for debugging purposes
        expect(csv).toEqual(expectedCsv);
        done();
      });
  });
});
</code></pre>
<p>Apparently, <strong>during the test case implementation I wanted to see how my test case failed</strong>: the stream seemed to work as it logged every expected csv result line and the <code>'streaming ended'</code> message also at the end once the stream ended, but the test execution did not finish at all then. It was jest that actually finished the execution after exceeding the default timeout:</p>
<blockquote>
<p>thrown: &quot;Exceeded timeout of 5000 ms for a test. Use
jest.setTimeout(newTimeout) to increase the timeout value, if this is
a long-running test.&quot;</p>
</blockquote>
<p>What am I missing here?</p>
<p><em>Note that I am currently using the jest callback to notify when the async operation has finished.</em></p>
",https://stackoverflow.com/questions/70992048/unit-testing-nodejs-stream-with-jest-timeout-issue,"['javascript', 'node.js', 'typescript', 'jestjs', 'node-streams']",2807,True,2,2
Xunit Unit Testing for Dot Net core application,"<p>I recently started learning Unit Testing and now have the requirement write unit tests using Xunit and Moq for dot net core application.</p>
<p>I can write some very basic but when it comes to write them for complex classes , I am kind of stuck.</p>
<p>Below is the class I will be writing tests for.</p>
<pre><code> public class AgeCategoryRequestHandler : IInventoryRequestHandler&lt;InventoryRequest, HandlerResult&gt;
{
    private readonly IRepositoryResolver _repositoryResolver;
    Hotels.HBSI.Logging.ILogger logger;
    public AgeCategoryRequestHandler(IRepositoryResolver repositoryResolver, Hotels.HBSI.Logging.ILogger iLogger)
    {
        _repositoryResolver = repositoryResolver;
        logger = iLogger;
    }

    public async Task&lt;HandlerResult&gt; Run(InventoryRequest inventoryRequest)
    {
        var result = await ProcessRequest(inventoryRequest);
        return CreateResponse(inventoryRequest, result);
    }

    private async Task&lt;int&gt; ProcessRequest(InventoryRequest inventoryRequest)
    {
        logger.Info(&quot;AgeCategory requesthandler processrequest start&quot;);
        var repository = _repositoryResolver.ResolveEstabAgeCategory();
        if (repository is not null)
        {
            return await repository.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories)
           .ConfigureAwait(false);
        }
        logger.Info(&quot;AgeCategory requesthandler processrequest complete&quot;);
        return InernalError.reponotfound;
    }
    public HandlerResult CreateResponse(InventoryRequest inventoryRequest, int resultCount)
    {
        var requestCount = inventoryRequest.EstabAgeCategories.Count;
        var handlerResult = new HandlerResult() { Id = RequestHandlerEnum.AgeCategrory.ToInt() };
        if (requestCount &gt; 0 &amp;&amp; resultCount &lt; requestCount)
        {
            handlerResult.IsSuccess = false;
            handlerResult.ErrorCode = OTAErrorType.InvalidAgeCategory.ToInt();
        }
        else if (requestCount &gt; 0 || requestCount == resultCount)
        {
            handlerResult.IsSuccess = true;
            handlerResult.ErrorCode = 0;
        }
        return handlerResult;
    }
}
</code></pre>
<p>Just to start , IRepositoryResolver and ILogger are in the constructor so I have created mock for these but unable to go beyond that as I am still in initial phase of learning.</p>
<p>Could someone explain me the steps/approach to accomplish this?.</p>
<p>Edit : What I have done so far is below ( can't figure out what are the things to be done and where to start or write )</p>
<p>Edit 2 : Did some more modifications to my test code , can someone comment if I am in right direction ? what else can I test ?</p>
<pre><code> public class AgeCategoryRequestHandlerTest
{
    private AgeCategoryRequestHandler _ageCategoryRequestHandler;

    private readonly Mock&lt;AgeCategoryRequestHandler&gt; _ageCategory = new Mock&lt;AgeCategoryRequestHandler&gt;();

    private readonly Mock&lt;Hotels.HBSI.Logging.ILogger&gt; _mockLogger = new Mock&lt;Hotels.HBSI.Logging.ILogger&gt;();
    private readonly Mock&lt;IRepositoryResolver&gt; _mockRepositoryResolver = new Mock&lt;IRepositoryResolver&gt;();
    public AgeCategoryRequestHandlerTest()
    {

        _ageCategoryRequestHandler = new AgeCategoryRequestHandler(_mockRepositoryResolver.Object, _mockLogger.Object);


    }


    [Fact]


   public async void  Testtt()

    {
        var fixture = new Fixture();
        var inventory = fixture.Create&lt;InventoryRequest&gt;();
        var hndlr = fixture.Create&lt;HandlerResult&gt;();

        hndlr.ErrorCode = 0;
        int resultCount = 3;

        await _ageCategoryRequestHandler.Run(inventory);

        HandlerResult response =   _ageCategoryRequestHandler.CreateResponse(inventory, resultCount);

        Assert.Equal(hndlr.ErrorCode, response.ErrorCode);

     
    }
</code></pre>
<p>Tried running Chris B suggested code , was getting type conversion error  <code>EstabAgeCategories  = new List&lt;int&gt;</code></p>
<p>Now I have used fixture for creating automatic objects and did some assert values. Below is the code sample</p>
<pre><code>           var fixture = new Fixture();
        var inventoryRequest = fixture.Create&lt;InventoryRequest&gt;();
        
        _mockRepository
            .Setup(x =&gt; x.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories))
            .ReturnsAsync(6);

        _mockRepositoryResolver
            .Setup(x =&gt; x.ResolveEstabAgeCategory())
            .Returns(_mockRepository.Object);

        // act
        var result = await _ageCategoryRequestHandler.Run(inventoryRequest);

        // assert
        _mockRepository
            .Verify(x =&gt; x.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories), Times.Once);

        Assert.True(result.Id == 6);
        Assert.True(result.ErrorCode == 0);
        Assert.True(result.IsSuccess);
</code></pre>
",https://stackoverflow.com/questions/73700179/xunit-unit-testing-for-dot-net-core-application,"['asp.net-core', '.net-core', 'azure-functions', 'moq', 'xunit.net']",177,True,2,1
Are there architectural patterns for Swift Unit Testing?,"<p>I wondered if there were architectural patterns, like MVP, MVVM for unit tests in swift.</p>
<p>I know about AAA pattern, but it breaks the logic inside the test method. In all the stuff I've read, the structure of the tests was made the same as the structure of the project itself, and there was no architecture as such.</p>
<p><a href=""https://i.stack.imgur.com/aeSVU.png"" rel=""nofollow noreferrer"">It looks something like this</a></p>
<p>Maybe you know some architectures, patterns or approaches that would help to logically break up modular tests into different objects?</p>
",https://stackoverflow.com/questions/71901650/are-there-architectural-patterns-for-swift-unit-testing,"['ios', 'unit-testing', 'architecture', 'xctest', 'xctestcase']",421,True,2,1
WSO2 unit testing Mock Service is not working,"<p>I`m using the 2SO2 integration studio version is 8.0.0.
I tried to write junit suite test for my app using mock-service for my endpoint.
But when I tried to run the test I got the next failed :</p>
<p><a href=""https://i.stack.imgur.com/Z2kDj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Z2kDj.png"" alt=""enter image description here"" /></a></p>
<p>My mock-service is set up with port = 9090 ( i do not know it`s right or not, this port i found in documentation by wso2 : <a href=""https://ei.docs.wso2.com/en/7.2.0/micro-integrator/develop/creating-unit-test-suite/"" rel=""nofollow noreferrer"">https://ei.docs.wso2.com/en/7.2.0/micro-integrator/develop/creating-unit-test-suite/</a>):</p>
<p><a href=""https://i.stack.imgur.com/qm6jF.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/qm6jF.png"" alt=""enter image description here"" /></a></p>
<p>Test is :</p>
<pre><code>&lt;unit-test&gt;
    &lt;artifacts&gt;
        &lt;test-artifact&gt;
            &lt;artifact&gt;/LmaAPIConfigs/src/main/synapse-config/api/LmaAPI.xml&lt;/artifact&gt;
        &lt;/test-artifact&gt;
        &lt;supportive-artifacts/&gt;
        &lt;registry-resources/&gt;
        &lt;connector-resources/&gt;
    &lt;/artifacts&gt;
    &lt;test-cases&gt;
        &lt;test-case name=&quot;TestMock&quot;&gt;
            &lt;input&gt;
                &lt;request-path&gt;/currency&lt;/request-path&gt;
                &lt;request-method&gt;POST&lt;/request-method&gt;
                &lt;request-protocol&gt;http&lt;/request-protocol&gt;
                &lt;payload&gt;&lt;![CDATA[{&quot;currency&quot;: &quot;USD&quot;}]]&gt;&lt;/payload&gt;
                &lt;properties&gt;
                    &lt;property name=&quot;Content-Type&quot; scope=&quot;transport&quot; value=&quot;application/json&quot;/&gt;
                &lt;/properties&gt;
            &lt;/input&gt;
            &lt;assertions&gt;
                &lt;assertEquals&gt;
                    &lt;actual&gt;$body&lt;/actual&gt;
                    &lt;expected&gt;&lt;![CDATA[&lt;jsonObject&gt;&lt;r030&gt;840&lt;/r030&gt;&lt;txt&gt;Долар США&lt;/txt&gt;&lt;rate&gt;36.5686&lt;/rate&gt;&lt;cc&gt;USD&lt;/cc&gt;&lt;exchangedate&gt;]]&gt;&lt;/expected&gt;
                    &lt;message&gt;not equals&lt;/message&gt;
                &lt;/assertEquals&gt;
                &lt;assertNotNull&gt;
                    &lt;actual&gt;$body&lt;/actual&gt;
                    &lt;message&gt;body is null&lt;/message&gt;
                &lt;/assertNotNull&gt;
            &lt;/assertions&gt;
        &lt;/test-case&gt;
    &lt;/test-cases&gt;
    &lt;mock-services&gt;
        &lt;mock-service&gt;/LmaAPI/LmaAPIConfigs/test/resources/mock-services/Exchange.xml&lt;/mock-service&gt;
    &lt;/mock-services&gt;
&lt;/unit-test&gt;
</code></pre>
<p>The logs from wso2carbon.log file :</p>
<pre><code>[2022-09-19 08:49:43,467]  INFO {org.apache.synapse.unittest.UnitTestingExecutor} - Start processing test-case handler
[2022-09-19 08:49:43,467]  INFO {org.apache.synapse.unittest.UnitTestingExecutor} - Unit testing agent checks transport Pass-through HTTP Listener port
[2022-09-19 08:49:43,487]  INFO {org.apache.synapse.transport.passthru.core.PassThroughListeningIOReactorManager} - Pass-through EI_INTERNAL_HTTPS_INBOUND_ENDPOINT Listener started on 0:0:0:0:0:0:0:0:9164
[2022-09-19 08:49:43,495]  INFO {org.apache.synapse.unittest.SynapseTestcaseDataReader} - Artifact data from descriptor data read successfully
[2022-09-19 08:49:43,495]  INFO {org.apache.synapse.unittest.SynapseTestcaseDataReader} - Test case data from descriptor data read successfully
[2022-09-19 08:49:43,497]  INFO {org.apache.synapse.unittest.SynapseTestcaseDataReader} - Mock service data from descriptor data read successfully
[2022-09-19 08:49:43,498]  INFO {org.apache.synapse.unittest.ConfigModifier} - Mock service creator ready to start service for Exchange
[2022-09-19 08:49:43,530]  INFO {org.apache.synapse.unittest.MockServiceCreator} - Mock service started for Exchange in - http://localhost:9090/get-nbu-exchange
[2022-09-19 08:49:43,530]  INFO {org.apache.synapse.unittest.ConfigModifier} - Thread waiting for mock service(s) starting
[2022-09-19 08:49:43,609] ERROR {org.apache.synapse.unittest.UnitTestingExecutor} - Failed to get input stream from TCP connection java.io.EOFException
    at java.base/java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2842)
    at java.base/java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3337)
    at java.base/java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:925)
    at java.base/java.io.ObjectInputStream.&lt;init&gt;(ObjectInputStream.java:368)
    at org.apache.synapse.unittest.RequestHandler.readData(RequestHandler.java:112)
    at org.apache.synapse.unittest.RequestHandler.run(RequestHandler.java:74)
    at java.base/java.lang.Thread.run(Thread.java:834)

[2022-09-19 08:49:43,609] ERROR {org.apache.synapse.unittest.UnitTestingExecutor} - Error while reading data from received message java.lang.NullPointerException
    at org.apache.synapse.unittest.SynapseTestcaseDataReader.readAndStoreArtifactData(SynapseTestcaseDataReader.java:148)
    at org.apache.synapse.unittest.RequestHandler.preProcessingData(RequestHandler.java:137)
    at org.apache.synapse.unittest.RequestHandler.run(RequestHandler.java:80)
    at java.base/java.lang.Thread.run(Thread.java:834)

[2022-09-19 08:49:43,609] ERROR {org.apache.synapse.unittest.UnitTestingExecutor} - Reading Synapse testcase data failed
[2022-09-19 08:49:43,609] ERROR {org.apache.synapse.unittest.UnitTestingExecutor} - Error while running client request in test agent java.net.SocketException: Software caused connection abort: socket write error
    at java.base/java.net.SocketOutputStream.socketWrite0(Native Method)
    at java.base/java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:110)
    at java.base/java.net.SocketOutputStream.write(SocketOutputStream.java:150)
    at java.base/java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1883)
    at java.base/java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1792)
    at java.base/java.io.ObjectOutputStream.writeNonProxyDesc(ObjectOutputStream.java:1287)
    at java.base/java.io.ObjectOutputStream.writeClassDesc(ObjectOutputStream.java:1232)
    at java.base/java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1428)
    at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1179)
    at java.base/java.io.ObjectOutputStream.writeFatalException(ObjectOutputStream.java:1583)
    at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:352)
    at org.apache.synapse.unittest.RequestHandler.writeData(RequestHandler.java:238)
    at org.apache.synapse.unittest.RequestHandler.run(RequestHandler.java:92)
    at java.base/java.lang.Thread.run(Thread.java:834)

[2022-09-19 08:49:43,830]  INFO {io.netty.handler.logging.LoggingHandler} - [id: 0x00a2ce58] REGISTERED
[2022-09-19 08:49:43,830]  INFO {io.netty.handler.logging.LoggingHandler} - [id: 0x00a2ce58] BIND: localhost/127.0.0.1:9090
[2022-09-19 08:49:43,830]  INFO {io.netty.handler.logging.LoggingHandler} - [id: 0x00a2ce58, L:/127.0.0.1:9090] ACTIVE
[2022-09-19 08:49:44,040]  INFO {org.apache.synapse.unittest.ConfigModifier} - Mock service(s) are started with given ports
[2022-09-19 08:49:44,042]  INFO {org.apache.synapse.unittest.UnitTestingExecutor} - Main test artifact deployment started
[2022-09-19 08:49:44,042]  INFO {io.netty.handler.logging.LoggingHandler} - [id: 0x00a2ce58, L:/127.0.0.1:9090] READ: [id: 0x7fabaabd, L:/127.0.0.1:9090 - R:/127.0.0.1:61051]
[2022-09-19 08:49:44,042]  INFO {io.netty.handler.logging.LoggingHandler} - [id: 0x00a2ce58, L:/127.0.0.1:9090] READ COMPLETE
[2022-09-19 08:49:44,326]  INFO {org.apache.synapse.api.API} - {api:LmaAPI} Initializing API: LmaAPI
[2022-09-19 08:49:44,326]  INFO {org.apache.synapse.core.axis2.Axis2SynapseEnvironment} - Continuation call is set to true
[2022-09-19 08:49:44,326]  INFO {org.apache.synapse.deployers.APIDeployer} - API named 'LmaAPI' has been deployed from file : LmaAPI
[2022-09-19 08:49:44,326]  INFO {org.apache.synapse.unittest.TestingAgent} - Primary test API artifact deployed successfully
[2022-09-19 08:49:44,326]  INFO {org.apache.synapse.unittest.UnitTestingExecutor} - Synapse testing agent ready to mediate test cases through deployments
[2022-09-19 08:49:44,326]  INFO {org.apache.synapse.unittest.TestingAgent} - 1 Test case(s) ready to execute
[2022-09-19 08:49:44,326]  INFO {org.apache.synapse.unittest.UnitTestingExecutor} - Invoking URI - http://localhost:8290/lma/currency
[2022-09-19 08:49:44,467]  INFO {org.apache.synapse.mediators.builtin.LogMediator} - {api:LmaAPI} uri.var.currency = USD
[2022-09-19 08:49:44,472]  INFO {org.apache.synapse.mediators.builtin.LogMediator} - {api:LmaAPI} To: /lma/currency, MessageID: urn:uuid:898e7062-97b1-4179-a6d0-a3a63106455f, correlation_id: 898e7062-97b1-4179-a6d0-a3a63106455f, Direction: request, LmaAPI_currency = ERROR RESPONSE, Payload: {&quot;currency&quot;: &quot;USD&quot;}
[2022-09-19 08:49:44,498]  INFO {org.apache.synapse.unittest.Assertor} - Assert Equals - assert property for services started
[2022-09-19 08:49:44,514]  INFO {org.apache.synapse.unittest.Assertor} - Service Assert Expression - $body
[2022-09-19 08:49:44,514]  INFO {org.apache.synapse.unittest.Assertor} - Service mediated result for Actual - &lt;jsonObject&gt;&lt;currency&gt;USD&lt;/currency&gt;&lt;/jsonObject&gt;
[2022-09-19 08:49:44,514]  INFO {org.apache.synapse.unittest.Assertor} - Service Assert Expected - &lt;jsonObject&gt;&lt;r030&gt;840&lt;/r030&gt;&lt;txt&gt;ДоларСША&lt;/txt&gt;&lt;rate&gt;36.5686&lt;/rate&gt;&lt;cc&gt;USD&lt;/cc&gt;&lt;/jsonObject&gt;
[2022-09-19 08:49:44,514] ERROR {org.apache.synapse.unittest.Assertor} - Service assertEquals for $body expression failed with a message - not equals
[2022-09-19 08:49:44,514] ERROR {org.apache.synapse.unittest.Assertor} - Unit testing failed for the test case - TestMock
[2022-09-19 08:49:44,514]  INFO {org.apache.synapse.deployers.APIDeployer} - API named 'LmaAPI' has been undeployed
[2022-09-19 08:49:44,514]  INFO {org.apache.synapse.api.API} - {api:LmaAPI} Destroying API: LmaAPI
[2022-09-19 08:49:44,514]  INFO {org.apache.synapse.core.axis2.Axis2SynapseEnvironment} - Continuation call is set to false
[2022-09-19 08:49:44,514]  INFO {org.apache.synapse.unittest.TestingAgent} - Undeployed all the deployed test and supportive artifacts
[2022-09-19 08:49:44,514]  INFO {io.netty.handler.logging.LoggingHandler} - [id: 0x00a2ce58, L:/127.0.0.1:9090] INACTIVE
[2022-09-19 08:49:44,514]  INFO {io.netty.handler.logging.LoggingHandler} - [id: 0x00a2ce58, L:/127.0.0.1:9090] UNREGISTERED
[2022-09-19 08:49:44,521]  INFO {org.apache.synapse.commons.emulator.core.Emulator} - Emulator shutdown successfully.......
[2022-09-19 08:49:44,521]  INFO {org.apache.synapse.unittest.UnitTestingExecutor} - End processing test-case handler
</code></pre>
<p>My synapse artefacts :</p>
<p><a href=""https://i.stack.imgur.com/LTiJ1.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/LTiJ1.png"" alt=""enter image description here"" /></a></p>
<p>My API :</p>
<p><a href=""https://i.stack.imgur.com/LoHJf.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/LoHJf.png"" alt=""enter image description here"" /></a></p>
<p>My EP :</p>
<p><a href=""https://i.stack.imgur.com/U3Kfb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/U3Kfb.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73733542/wso2-unit-testing-mock-service-is-not-working,['wso2'],233,True,1,2
Python Unit testing script that calls some functions,"<p>I ended up with testing an &quot;automation&quot; script in python, basically just a script calling bunch of functions.</p>
<p>I have 3 classes: class_A, class_B, class_C, with each class having a &quot;run&quot; function</p>
<p>Script.py is calling class_A.run(), class_B.run, class_C.run()</p>
<p>My question would be if is there is a way of unit testing Script.py to just assert if the 3 run functions we're called, without actually running (going trough their code) them.</p>
<p>I tried patching the class and i can get the correct assert, but the run functions are still &quot;running&quot; their code.</p>
<p>Is it possible to somehow Mock the class_A.run() and assert if was called?</p>
",https://stackoverflow.com/questions/70609954/python-unit-testing-script-that-calls-some-functions,"['python', 'unit-testing', 'mocking']",51,True,1,1
Jest Unit Testing fails in soap.createClientAsync returning function,"<p>I have a soap RestAPI to call for excecuting a function from a service for which i have used soap lib with async await. The code is working fine. When comes to unit testing the test case fails at the callback method returning from the client. The code and UT error follows.</p>
<p><strong>Function to call Soap Client - Code - Helper.ts</strong></p>
<pre><code>class soapHelper {
    public async registerInSoap(
            uploadRequest: ImportExperimentRequestDto,
        ): Promise&lt;{ RegisterExperimentResult: IffManPublishResponseDto }&gt; {
            const url = &quot;http://test.com/Services/Req.svc?wsdl&quot;;
            const client = await soap.createClientAsync(flavourUrl);
            return client.RegisterExperimentAsync({ upload: uploadRequest});
        }
}
</code></pre>
<p><strong>Test Case - Code</strong></p>
<pre><code>describe(&quot;**** Register via soap service ****&quot;, () =&gt; {
        it(&quot;** should excecute register method **&quot;, async () =&gt; {
            const request = cloneDeep(MOCK.API_PAYLOAD);
            const clientResponse = {
                RegisterExperimentAsync: jest.fn(),
            };
            jest.spyOn&lt;any, any&gt;(soap, &quot;createClientAsync&quot;).mockReturnValueOnce(() =&gt; Promise.resolve(clientResponse));
            const result= await soapHelper.registerInSoap(request);
            expect(result).toEqual({ Result: AFB_MOCK_RESPONSE.API_RESPONSE });
        });
    });
</code></pre>
<p><strong>Error</strong></p>
<pre><code>TypeError: client.RegisterExperimentAsync is not a function
</code></pre>
<p><a href=""https://i.stack.imgur.com/0yDCG.png"" rel=""nofollow noreferrer"">UT Error</a></p>
",https://stackoverflow.com/questions/72610667/jest-unit-testing-fails-in-soap-createclientasync-returning-function,"['node.js', 'nestjs', 'soap-client', 'ts-jest', 'jest-fetch-mock']",518,False,1,1
Using 2 byte arrays in C# Unit Testing,"<p>I want to write a <code>[DataTestMethod]</code> that uses many <code>[DataRow]</code>s, all containing two byte arrays.
But, my problem is that the test method only uses the Data from the last row.</p>
<p>I have written a Test with data rows that just contains integers which works fine. And another one that containes one Byte array and some bools. But I can't get a multiple data rows with two byte arrays to work.</p>
<p>Working Tests:</p>
<pre><code>    [DataTestMethod]
    [DataRow(1, 1, 2)]
    [DataRow(2, 2, 4)]
    [DataRow(3, 3, 6)]
    public void AddTests(int x, int y, int expected)
    {
        Assert.AreEqual(expected, x + y);
    }

    [DataRow(new byte[] { 0x00 }, false, false, false)]
    [DataRow(new byte[] { 0x00 }, true, true, false)]
    [DataRow(new byte[] { 0x00 }, false, true, false)]
    [DataRow(new byte[] { 0x00 }, true, false, false)]
    [DataTestMethod()]
    public void ByteArrayIntegerTest(byte[] key,bool ctorsign, bool tasign,bool expectfail)
    {
        var bi = new ByteArrayInteger(key, ctorsign);
        var result = bi.ToByteArray(tasign);
        if (expectfail)
        {
            CollectionAssert.AreNotEqual(key, result);
        }
        else
        {
            CollectionAssert.AreEqual(key, result);
        }
    }
</code></pre>
<p>Not working Test:</p>
<pre><code>    [DataTestMethod]
    [DataRow(new byte[] { 0xCA, 0xFE }, new byte[] { 0xCA, 0xFE })]
    [DataRow(new byte[] { 0x00, 0xCA, 0xFE }, new byte[] { 0xCA, 0xFE })]
    [DataRow(new byte[] { 0x00, 0x00, 0xCA, 0xFE }, new byte[] { 0xCA, 0xFE })]

    public void MinimizeSerialnumberTest(byte[] serialnumber, byte[] expected)
    {
        CollectionAssert.AreEqual(expected, Util.MinimizeSerialnumber(serialnumber));
    }
</code></pre>
<p>With the non working test it only ever uses the last provided <code>DataRow</code>. There are no errors and the test runs just fine.</p>
<p>Does <code>Microsoft.VisualStudio.TestTools.UnitTesting</code> not support multiple byte arrays? Or what could be the problem?</p>
<p>Edit:
After some more research. Could the Problem be, that <code>DataRowAttribute</code> takes <code>Object, Object[]</code> as parameters in it's constructor? <a href=""https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.datarowattribute?view=visualstudiosdk-2022"" rel=""nofollow noreferrer"">Source</a></p>
<p>If so, how would I work with that?</p>
",https://stackoverflow.com/questions/73541427/using-2-byte-arrays-in-c-unit-testing,"['c#', 'unit-testing']",181,True,1,2
How to apply unit testing on react project?,"<p>Basically, I do not know how to implement unit test on react projects. Please, anyone, provide me resources for implementing unit test on react project.</p>
",https://stackoverflow.com/questions/70588808/how-to-apply-unit-testing-on-react-project,['reactjs'],25,False,1,1
unit test case returning null while unit testing,"<p>I have a below method which simply unnest the list within list and and create merged record all sub lists</p>
<p>e.g.</p>
<p><strong>testResultDTO</strong> similar to</p>
<pre><code>{
dept_name :'',
dept_id:'',
personList :'&lt;List&gt;'

}
</code></pre>
<p><strong>personList</strong> is list similat to</p>
<pre><code> {
first_name :'',
Last_name:'',
workHistList:'&lt;List&gt;'

    }
</code></pre>
<p><strong>workHistList</strong> is similar to</p>
<pre><code>{
task_name:'',
task_description:''}

 `
</code></pre>
<p>And the method is below</p>
<pre><code>   public async Task&lt;FileDTO&gt; GetWorkList(InputParameter inputParameter)
    {
      TestResultDTO testResultDTO = await GetPersonWorkList(inputParameter);

      var testDto = new List&lt;TestDto&gt;();

      if (testResultDTO != null)
      {     
        testDto = personWorkFile(testResultDTO);
      }
       
      return testDto;
}
</code></pre>
<p>The problem is in method <strong>personWorkFile</strong></p>
<pre><code>private List&lt;testDTO&gt; personWorkFile(testResultDTO testResultDTO)
  {
  List&lt;testDTO&gt; testDTO = new List&lt;testDTO&gt;();

  if (testResultDTO.workList is null) return new();

  foreach (var testItem in testResultDTO.workList)
  {
    if (testItem.personList != null &amp;&amp; testItem.personList.Any())
    {
      for (var j = 0; j &lt; testItem.personList.Count; j++)
      {
        List&lt;testDTO&gt; testDTOTemp = new List&lt;testDTO&gt;();
        for (var i = 0; i &lt; testItem.personList[j].workHistList.Count; i++)
        {
          testDTOTemp.Insert(i, mapper.Map(testItem.personList[j].workHistList[i], mapper.Map&lt;testDTO&gt;(testItem.personList[j])));
        }

        testDTO.AddRange(testDTOTemp);
      }
    }
  }
  return testDTO;
}
`
</code></pre>
<p>what it does is it create a finale list with record similar to</p>
<pre><code>{dept_name,dept_id,first_name, last_name, task_name, task_description}
</code></pre>
<p>Now when i create a unit test for it, it always fail because, it always insert null in list testDTOTemp.insert</p>
<p>my content of test case code is below</p>
<pre><code>  mapperMock.Setup(m =&gt; m.Map&lt;List&lt;TestResultDTO&gt;, List&lt;TestDTO&gt;&gt;(testResultDTO)).Returns(testDTO);
  
  //call actual service
  var result = await workService.GetWorkList(inputParameter);
</code></pre>
<p>Can someone please help me understand why it is not able to insert any data <em><strong>testDTOTemp</strong></em> list</p>
",https://stackoverflow.com/questions/73142466/unit-test-case-returning-null-while-unit-testing,"['c#', '.net', '.net-core', 'nunit', 'moq']",394,False,1,1
Patching over local JSON file in unit testing,"<p>I have some Python code that loads in a local JSON file:</p>
<pre class=""lang-py prettyprint-override""><code>with open(&quot;/path/to/file.json&quot;) as f:
    json_str = f.read()
    # Now do stuff with this JSON string
</code></pre>
<p>In testing, I want to patch that JSON file to be a JSON file located in my repo's test directory (<code>&quot;/path/to/repo/test/fake_file.json&quot;</code>).</p>
<p>How can I go about doing that?</p>
<p>One other requirement is I actually have a version of <code>&quot;/path/to/file.json&quot;</code> locally, but I don't want to change it.  I want it patched over at test time, and unpatched upon test completion.</p>
<p>Note: I use <code>pytest</code>, and it seems like the plug-in <code>pyfakefs</code> would do this.  Sadly, I can't figure out how to get it to patch in another local file (from within my repo's test directory).  I am open to solutions using vanilla Python 3.10+ and/or <code>pyfakefs</code>.</p>
",https://stackoverflow.com/questions/71271694/patching-over-local-json-file-in-unit-testing,"['python', 'mocking', 'filesystems', 'python-unittest.mock', 'pyfakefs']",627,True,1,1
Separate copy of DbContext class for unit testing?,"<p>I have a <code>CatalogDbContext</code> class.</p>
<p>I want to use <a href=""https://github.com/bchavez/Bogus/tree/master/Examples/EFCoreSeedDb"" rel=""nofollow noreferrer""><code>Bogus</code></a> library to seed fake data into the database that my unit tests will use.</p>
<p>The <a href=""https://github.com/bchavez/Bogus/tree/master/Examples/EFCoreSeedDb"" rel=""nofollow noreferrer"">example</a> provided in bogus's github repo makes use of the <code>HasData</code> method of the <code>CatalogDbContext</code> class to seed data into the tables.</p>
<p>However, I will not want this <code>HasData</code> method to be executed from the API - meaning, the <code>HasData</code> method should only be run if the DBContext is created from the Unit Tests.</p>
<p>Kindly advise how to achieve this?.</p>
<pre class=""lang-cs prettyprint-override""><code>using Bogus;
using Catalog.Api.Database.Entities;
using Microsoft.EntityFrameworkCore;

namespace Catalog.Api.Database
{
    public class CatalogDbContext : DbContext
    {
        public CatalogDbContext(DbContextOptions&lt;CatalogDbContext&gt; options) : base(options)
        {
        }
        public DbSet&lt;CatalogItem&gt; CatalogItems { get; set; }
        public DbSet&lt;CatalogBrand&gt; CatalogBrands { get; set; }
        public DbSet&lt;CatalogType&gt; CatalogTypes { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.ApplyConfiguration(new CatalogBrandEntityTypeConfiguration());
            builder.ApplyConfiguration(new CatalogTypeEntityTypeConfiguration());
            builder.ApplyConfiguration(new CatalogItemEntityTypeConfiguration());

            FakeData.Init(10);

            builder.Entity&lt;CatalogItem&gt;().HasData(FakeData.CatalogItems);
        }
    }

    internal class FakeData
    {
        public static List&lt;CatalogItem&gt; CatalogItems = new List&lt;CatalogItem&gt;();

        public static void Init(int count)
        {
            var id = 1;

            var catalogItemFaker = new Faker&lt;CatalogItem&gt;()
                .RuleFor(ci =&gt; ci.Id, _ =&gt; id++)
                .RuleFor(ci =&gt; ci.Name, f =&gt; f.Commerce.ProductName());
        }

    }
}
</code></pre>
",https://stackoverflow.com/questions/73015113/separate-copy-of-dbcontext-class-for-unit-testing,"['entity-framework-core', 'xunit', 'bogus']",166,False,1,0
Infinite Recursion with Spies in Angular Unit Testing,"<p>New to unit testing here.</p>
<p>I have a situation where the function I am testing <code>getFolderTree$()</code> recursively calls another function <code>getFolderChildren$()</code>. I tried setting up a spy for <code>getFolderChildren$()</code> as seen in the below attempt at a unit test. However, this results in <code>getFolderTree$()</code> never getting the chance to hit the base case because it keeps getting more and more children and a maximum call stack size exceeded error.</p>
<p>When I set the <code>getFolderChildren$()</code> spyOn to return an empty array, I solve the recursion issue but I can't cover the lines that deal with children.</p>
<p>Does anyone know how I can solve this issue and still get full coverage of the original function? Any help appreciated!</p>
<p><strong>Original Function</strong></p>
<pre><code>getFolderTree$(tenantId: number, folderId: number): Observable&lt;FolderTree&gt; {
  return combineLatest([
    this.getFolder$(tenantId, folderId),
    this.getFolderChildren$(tenantId, folderId)]).pipe(
      map(([folder, subFolders]) =&gt; ({
        parent: { name: folder.folderName, id: folder.id, description: folder.description, children: [] } as FolderTree,
        childFolders: subFolders
      })),
      mergeMap(data =&gt; forkJoin([
        of(data.parent),
        ...data.childFolders.map(child =&gt; this.getFolderTree$(child.tenantId, child.id))
      ])),
      map(([parent, ...children]) =&gt; { parent.children = children.sort(this.sortByFolderName); return parent; })
    );
}
</code></pre>
<p><strong>Unit Test</strong></p>
<pre><code>it('should get folder tree', () =&gt; {
        let folder = {id: 1, tenantId: tenantID, folderName: 'some folder'} as IFolder;
        let subFolders = [{id: 2, tenantId: tenantID, folderName: 'some child folder'} as IFolder];

        spyOn(folderService, 'getFolder$').and.returnValue(of(folder));
        spyOn(folderService, 'getFolderChildren$').and.returnValue(of(subFolders));

        let result = folderService.getFolderTree$(tenantID, folderID);
        result.subscribe(value =&gt; {
            //expectation here
        });
    });
</code></pre>
",https://stackoverflow.com/questions/70560028/infinite-recursion-with-spies-in-angular-unit-testing,"['angular', 'typescript', 'unit-testing', 'recursion', 'karma-jasmine']",139,False,1,0
Mock Injected Twilio Service in Unit Testing Nest.js,"<p>I have a problem with overriding provider/setup module testing in nest.js application for testing.</p>
<p>Module file: smsModule.ts:</p>
<pre><code>import { TwilioService } from './twilio/twilio.service';
import { DynamicModule, Module } from '@nestjs/common';
import { TwilioConfig, SMS_TWILIO_CONFIG } from './twilio.config';
import { TwilioClientCustom } from './twilio/twilio-client-custom';

@Module({
    imports: [],
    providers: [TwilioService],
})
export class SmsModule {
    static register(options: TwilioConfig): DynamicModule {
        return {
            module: SmsModule,
            imports: [HttpModule],
            providers: [
                {
                    provide: SMS_TWILIO_CONFIG,
                    useValue: options,
                },
                TwilioService,
                TwilioClientCustom,
            ],
            exports: [TwilioService],
        };
    }
}
</code></pre>
<p>Twilio client, config files:</p>
<pre><code>//client

import { TwilioConfig, SMS_TWILIO_CONFIG } from '../twilio.config';
import { Twilio } from 'twilio';
import { Inject, Injectable } from '@nestjs/common';

@Injectable()
export class TwilioClientCustom extends Twilio {
    constructor(@Inject(SMS_TWILIO_CONFIG) twilioConfig: TwilioConfig) {
        super(twilioConfig.accountSid, twilioConfig.authToken);
    }
}


//config 

import { IsString, IsNotEmpty, NotContains, IsOptional, IsArray } from 'class-validator';

const INFO = 'Must be ....';
export class TwilioConfig {
    @IsString()
    @IsNotEmpty()
    @NotContains('OVERRIDE_WITH_', { message: INFO })
    accountSid: string;

    @IsString()
    @IsNotEmpty()
    authToken: string;

    @IsArray()
    @IsOptional()
    @IsNotEmpty('OVERRIDE_WITH_', { message: INFO })
    serviceSid: string;
}
export const SMS_TWILIO_CONFIG = 'smsTwilioConfig';


</code></pre>
<p>Twilio service file: twilio.service.tst:</p>
<pre><code>import { HttpService } from '@nestjs/axios';
import { TwilioConfig, SMS_TWILIO_CONFIG } from '../twilio.config';
import { SendSmsTwilioService } from './../sendsms.service';
import { Inject, Injectable } from '@nestjs/common';
import { TwilioClientCustom } from './twilio-client-custom';

@Injectable()
export class TwilioService implements SendSmsTwilioService {
    constructor(
        @Inject(SMS_TWILIO_CONFIG) private readonly config: TwilioConfig,
        private readonly client: TwilioClientCustom,
        private readonly httpService: HttpService
    ) {}
    async sendSMS(to: string, from: string, body: string): Promise&lt;string&gt; {

        ......

        return this.client.messages
            .create({
                to, //Recipinet's number
                from, //Twilio number
                body, //Messages to Recipient
            })
            .then((message) =&gt; message.sid)
            .catch(() =&gt; {
                throw new Error('TWILIO accountSid or authToken not valid');
            });
    }
</code></pre>
<p>I would like to test my service:
test file:</p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
//import { TWILIO_CONFIG_SPEC } from './test.config';
import { TwilioClientCustom } from '../src/twilio/twilio-client-custom';
import { HttpService } from '@nestjs/axios';
import { TwilioConfig } from './../src/twilio.config';
import { TwilioService } from './../src/twilio/twilio.service';
import nock from 'nock';

describe('TwilioService', () =&gt; {
    let service: TwilioService;
    let client: TwilioClientCustom;
    let httpService: HttpService;

    afterEach(() =&gt; {
        nock.cleanAll();
    });

    //const smsServiceMock = {};

    beforeEach(async () =&gt; {
        const moduleRef: TestingModule = await Test.createTestingModule({
            providers: [
                TwilioService,

                {
                    provide: HttpService,
                    useValue: {
                        method1: jest.fn(),
                        method2: jest.fn(),
                        method3: jest.fn(),
                    },
                },
                TwilioService,
            ],
            imports: [
                NestConfigModule.forRoot({
                    config: TwilioConfig,
                } as Record&lt;string, unknown&gt;),
            ],
        }).compile();
        //getting service module from main module
        httpService = moduleRef.get&lt;HttpService&gt;(HttpService);
        client = moduleRef.get&lt;TwilioClientCustom&gt;(TwilioClientCustom);
        service = moduleRef.get&lt;TwilioService&gt;(TwilioService);
    });
    //check service is avaible
    it('Should be defined', () =&gt; {
        expect(client).toBeDefined();
        expect(service).toBeDefined();
        expect(httpService).toBeDefined();
    });
</code></pre>
<p><strong>And after running test I get following errors:</strong></p>
<pre><code>  Nest can't resolve dependencies of the TwilioService (?, TwilioClientCustom, HttpService). Please make sure that the argument smsTwilioConfig at index [0] is available in the RootTestModule context.

    Potential solutions:
    - If smsTwilioConfig is a provider, is it part of the current RootTestModule?
    - If smsTwilioConfig is exported from a separate @Module, is that module imported within RootTestModule?
      @Module({
        imports: [ /* the Module containing smsTwilioConfig */ ]
      })
</code></pre>
<p>How can I solve this problem ?</p>
",https://stackoverflow.com/questions/70998196/mock-injected-twilio-service-in-unit-testing-nest-js,"['node.js', 'jestjs', 'twilio', 'nestjs', 'nock']",949,True,1,1
Jest unit testing aws cdk (v1) NOT SERVERLESS,"<p><a href=""https://github.com/dabit3/cdk-graphql-backend"" rel=""nofollow noreferrer"">https://github.com/dabit3/cdk-graphql-backend</a>
using this link I have created the same cdk (version 1) project with redshift database.
How can I test the (Appsync, GraphQl, Lambda) using the Jest. Already checked the Jest testing example only found one example related to sqs queue test. So I need specific answer to this if anyone can help.</p>
<p>IN THE lib file</p>
<pre><code>const api = new appsync.GraphqlApi(this, &quot;Api&quot;, {
  name: &quot;api-name&quot;,
  schema: appsync.Schema.fromAsset(&quot;graphql/schema.graphql&quot;),
  authorizationConfig: {
    defaultAuthorization: {
      authorizationType: appsync.AuthorizationType.API_KEY,
      apiKeyConfig: {
        expires: cdk.Expiration.after(cdk.Duration.days(365)),
      },
    },
  },
  xrayEnabled: true,
});

   const wLambda = new lambda.Function(
      this,
      &quot;ApiHandler&quot;,
      {
        runtime: lambda.Runtime.NODEJS_16_X,
        handler: &quot;index.handler&quot;,
        layers: [layers.consolidatedWeatherAPILayer],
        code: lambda.Code.fromAsset(&quot;lambdas/functions&quot;, { exclude: [&quot;*.ts&quot;] }),
        memorySize: 1024,
        timeout: cdk.Duration.seconds(30),
      }
    );

const lambdaDS = new appsync.LambdaDataSource(this, &quot;LambdaDataSource&quot;, {
  api: api,
  lambdaFunction: wLambda,
});
</code></pre>
<p>code written in the test file:</p>
<pre><code>import &quot;@aws-cdk/assert/jest&quot;;
import { Stack } from &quot;@aws-cdk/core&quot;;
import myStack = require(&quot;../lib/test-cdk-project-stack&quot;);

test(&quot;appsync cloudformation&quot;, () =&gt; {
  const stack = new Stack()
  new myStack.TestCdkProjectStack(stack, &quot;appsynCloud&quot;);
  expect(stack).toHaveResource(&quot;AWS::AppSync::GraphQLApi&quot;, {
    xrayEnabled: true,
  });
});
</code></pre>
<p>Result:
<a href=""https://i.stack.imgur.com/9P52f.png"" rel=""nofollow noreferrer"">output with toHaveResource</a></p>
<p>If I use &quot;toHaveProperty&quot; instead of &quot;toHaveResource&quot;
Result:
<a href=""https://i.stack.imgur.com/ZwyYd.png"" rel=""nofollow noreferrer"">output with toHaveProperty</a></p>
<p>maybe I'm using the wrong function.</p>
",https://stackoverflow.com/questions/73409121/jest-unit-testing-aws-cdk-v1-not-serverless,"['amazon-web-services', 'unit-testing', 'facebook-graph-api', 'jestjs', 'aws-cdk']",113,False,1,1
"Setting up Vue 3, Typescript for unit testing","<p>I created a TodoApp in vue-typescript but I get an error as shown below when doing unit testing. Any idea why I get the error?  Here's my <a href=""https://github.com/isogunro/vuets-to-do-app"" rel=""nofollow noreferrer"">repo</a> to see my setup.</p>
<p><a href=""https://i.stack.imgur.com/kducU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/kducU.png"" alt=""enter image description here"" /></a></p>
<p>I did go through the documentation but unable to rid the error.  <strong>vue-jest</strong> is in the transform option of my package.</p>
",https://stackoverflow.com/questions/73955041/setting-up-vue-3-typescript-for-unit-testing,"['vue.js', 'unit-testing', 'vuejs3']",53,False,1,1
Unit testing camel routes using camel test support,"<p>I would like to right unit and integration test cases to test all the functional flow. Can someone share your thoughts on how I can create a mock endpoint to watch directory for file creation and further process them via multiple routes and move the file to different directories.</p>
<ol>
<li>Monitoring the <code>/hello</code> directory for new file creation.</li>
<li>If there is a file based on the file prefix, updated the headers with container name.</li>
<li>Upload to appropriate azure blob container based on file name.</li>
<li>Make an api call and move the file to <code>/success</code> directory once its processed.</li>
</ol>
<p><strong>FileWatcherRoute.java</strong></p>
<pre><code>@Service
public class FileWatcherRoute extends RouteBuilder {

  @Value(&quot;${watcher-base-url}&quot;)
  private String baseUrl;

  @Value(&quot;${watcher-subscription-key}&quot;)
  private String subscriptionKey;

  @Override
  public void configure() {

    Processor logResponse = exchange -&gt; log
        .info(&quot;The response code is: {}&quot;, exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE));

    from(&quot;file-watch:hello?events=CREATE&amp;antInclude=**/*.csv&amp;recursive=true&quot;)
        .routeId(&quot;fileWatch&quot;)
        .to(&quot;direct:updateHeaders&quot;)
        .end();

    from(&quot;direct:updateHeaders&quot;)
        .routeId(&quot;updateHeaders&quot;)
        .choice()

            .when((exchange -&gt; exchange.getIn().getHeader(Exchange.FILE_NAME).toString().trim().matches(&quot;\\d{8}_\\d{4}(_Inventory.csv)&quot;)))
            .setHeader(&quot;CamelAzureStorageBlobContainerName&quot;, constant(AppConstants.STORE))

                        .when(exchange -&gt; exchange.getIn().getHeader(Exchange.FILE_NAME).toString().trim().matches(&quot;\\d{8}-\\d{6}_Idle_Inventory_\\d{4}.csv&quot;))
            .setHeader(&quot;CamelAzureStorageBlobContainerName&quot;,constant(AppConstants.IDLE_FILE))

        .toD(&quot;direct:uploadFileToBlob&quot;)
        .end();

    from(&quot;direct:uploadFileToBlob&quot;)
        .routeId(&quot;uploadFile&quot;)
        .log(&quot;Container Name: ${header.CamelAzureStorageBlobContainerName}&quot;)
        .toD(&quot;azure-storage-blob://{accName}/${header.CamelAzureStorageBlobContainerName}?blobName=${header.CamelFileName}&amp;operation=uploadBlockBlob&amp;serviceClient=#serviceClient&quot;)
        .to(&quot;direct:startRestApi&quot;)
        .log(&quot;${header.CamelFileName} Uploaded to ${header.CamelAzureStorageBlobContainerName} Container Successfully&quot;)
        .end();


    from(&quot;direct:startRestApi&quot;)
        .routeId(&quot;restCall&quot;)
        .setHeader(Exchange.HTTP_METHOD, constant(&quot;GET&quot;))
        .setHeader(&quot;Content-Type&quot;,constant(&quot;application/json&quot;))
        .setHeader(&quot;Ocp-Apim-Subscription-Key&quot;,constant(subscriptionKey))
        .to(baseUrl)
        .to(&quot;direct:processedFiles&quot;)
        .process(logResponse)
        .end();

    from(&quot;direct:processedFiles&quot;)
        .routeId(&quot;fileProcessing&quot;)
        .choice()
        .when(exchange -&gt; exchange.getIn().getHeader(Exchange.HTTP_RESPONSE_CODE).equals(200))
        .to(&quot;file://success&quot;)
        .otherwise()
        .to(&quot;file://error&quot;)
        .end();
  }
}
</code></pre>
<p><strong>FileWatcherRouteTest.java</strong></p>
<pre><code>@CamelSpringBootTest
@SpringBootTest
@MockEndpoints
@UseAdviceWith
public class FileWatcherRouteTest {

  @Autowired
  CamelContext camelContext;

  @Autowired
  ProducerTemplate producerTemplate;

  @EndpointInject(&quot;mock:processedFiles&quot;)
  MockEndpoint mockEndpoint;

  @Test
  void when_new_file_created_should_update_header_with_container_name_and_upload_to_container() throws Exception {

    AdviceWith.adviceWith(camelContext, &quot;fileWatch&quot;, routeBuilder -&gt; {
      routeBuilder.replaceFromWith(&quot;direct:file-watch&quot;);
    });

    camelContext.start();
    mockEndpoint.assertIsSatisfied();

  }

}
</code></pre>
",https://stackoverflow.com/questions/70582600/unit-testing-camel-routes-using-camel-test-support,"['spring-boot', 'apache-camel', 'azure-storage', 'spring-camel', 'camel-test']",2607,True,1,1
Unable to load strapi instance in unit testing,"<p>I am trying to run test cases for strapi but it is not allowing me to do so. I am using postgres database.</p>
<p><strong>I have checked other answers and I have only one database.js file and not database.json</strong></p>
<p>The error I get-</p>
<p>lerna ERR! yarn run test:local stderr:
●  process.exit called with &quot;1&quot;</p>
<pre><code>   7 | async function setupStrapi() {
   8 |   if (!instance) {
&gt;  9 |     instance = await Strapi().load();
     |                ^
  10 |     await instance.app
  11 |       .use(instance.router.routes()) // populate KOA routes
  12 |       .use(instance.router.allowedMethods()); // populate KOA methods

  at Strapi.stop (../../node_modules/strapi/lib/Strapi.js:316:13)
  at Strapi.stopWithError (../../node_modules/strapi/lib/Strapi.js:302:17)
  at ../../node_modules/strapi-connector-bookshelf/lib/mount-models.js:688:18
  at module.exports (../../node_modules/strapi-connector-bookshelf/lib/mount-models.js:708:7)
  at mountConnection (../../node_modules/strapi-connector-bookshelf/lib/index.js:84:7)
      at async Promise.all (index 0)
  at Object.initialize (../../node_modules/strapi-database/lib/connector-registry.js:30:9)
  at DatabaseManager.initialize (../../node_modules/strapi-database/lib/database-manager.js:43:5)
  at Strapi.load (../../node_modules/strapi/lib/Strapi.js:362:5)
  at setupStrapi (tests/helpers/setup.js:9:16)
</code></pre>
<p>error Command failed with exit code 1.</p>
<p>Any leads to fix this?</p>
",https://stackoverflow.com/questions/70866716/unable-to-load-strapi-instance-in-unit-testing,"['unit-testing', 'jestjs', 'strapi']",115,False,1,0
Unit testing in Angular - property value not updating,"<p>I have simple function which shows and hides dropdown menu on click event. Here is HTML code</p>
<pre><code>&lt;div (click)=&quot;toggleDropdown()&quot; id=&quot;game-category&quot;&gt;Show/Hide menu&lt;/div&gt;
&lt;div class=&quot;relative&quot;&gt;
   &lt;app-category *ngIf=&quot;isShown&quot; [filtersList]=&quot;categories&quot;&gt;
   &lt;/app-category&gt;
&lt;/div&gt;
</code></pre>
<p>The function sets an opposite value to the property value of a component.</p>
<pre><code>isShown = false; 

toggleDropdown(): void {
     this.isShown = !this.isShown;
}
</code></pre>
<p>Everything works fine, but when I run the tests then I get an error. Here is the testing code:</p>
<pre><code>describe('CreateGameComponent', () =&gt; {

   let component: CreateGameComponent;
   let fixture: ComponentFixture&lt;CreateGameComponent&gt;;

    beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [
        CommonModule,
      ],
      declarations: [CreateGameComponent],
      providers: [RequestService, SessionService, AdminService],
    })
      .compileComponents()
      .then(() =&gt; {
        fixture = TestBed.createComponent(CreateGameComponent);
        component = fixture.componentInstance;
        component.isShown = false;
        fixture.detectChanges();
      });
   });

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

   it('should check if toggleDropdownwas called', fakeAsync(() =&gt; {
      spyOn(component, 'toggleDropdown');
      let button =
      fixture.debugElement.nativeElement.querySelector('#game-category');
      button.click();
      tick();
      fixture.detectChanges();

      expect(component.toggleDropdown).toHaveBeenCalled();
      expect(component.isShown).toBe(true, 'isShown has not changed');
   }));
      
      
 })
</code></pre>
<p>After triggering click event <code>isShown</code> property is not changing it's value.
Any help is appreciated. Thanks!</p>
",https://stackoverflow.com/questions/70656939/unit-testing-in-angular-property-value-not-updating,"['angular', 'unit-testing', 'jasmine', 'angular-unit-test']",1928,True,1,1
Spring Boot Unit Testing with WebMvcTest + JWT + AuthenticationPrinciple,"<p>I have a project with Spring-Boot + Spring-Security. In this project, typical I have MVC architecture.</p>
<p>My controller looks like:</p>
<pre><code>@RestController
DemoController
{
    public ResponseEntity&lt;?&gt; get(@AuthenticationPrinciple UserPrinciple userPrinciple)
    { 
       return ...
    }
}
</code></pre>
<p>I want to test this controller class with WebMvcTest. I know that I can handle it with SpringBootTest easily but SpringBootTest is not time-effective...</p>
<p>I've created a test class like:</p>
<pre><code>@WebMvcTest(controllers = {DemoController.class})
DemoControllerTest
{
    @Autowired
    private MockMvc mockMvc;

    @Test
    void test_get()
    {
        this.mockMvc.perform(get(&quot;/...&quot;)
                .header(AUTH_HEADER, getAuthorizationHeader())
            .andExpect(status().isOk());
    }
}
</code></pre>
<p>But I got error like userPrinciple is null or <code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.sha.springbootbookseller.security.CustomUserDetailsService' available: expected at least 1 bean which qualifies as autowire candidate.</code> How I can inject  AuthenticationPrinciple in WebMvcTest?</p>
<p>Example Code: <a href=""https://github.com/senolatac/spring-boot-book-seller"" rel=""nofollow noreferrer"">https://github.com/senolatac/spring-boot-book-seller</a></p>
<p>Test Class: <a href=""https://github.com/senolatac/spring-boot-book-seller/blob/master/src/test/java/com/sha/springbootbookseller/controller/PurchaseHistoryControllerTest.java"" rel=""nofollow noreferrer"">https://github.com/senolatac/spring-boot-book-seller/blob/master/src/test/java/com/sha/springbootbookseller/controller/PurchaseHistoryControllerTest.java</a></p>
",https://stackoverflow.com/questions/72978591/spring-boot-unit-testing-with-webmvctest-jwt-authenticationprinciple,"['spring-boot', 'unit-testing', 'spring-security']",441,True,0,1
Fluent Validator Unit Testing of Custom Property Validator,"<p>So I was updating my Fluent Validation version in my NetCore3.1 application and there I encountered in this issue which I was not able to figure out.
So there are Custom Property Validators that are present in my application. In the earlier version Fluent Validation (v 7.0.0.0), Custom Property Validators were implemented by in inherting validator logic by <strong>PropertyValidator</strong> . Here I can call Validate or ValidateAsync method of it to get the ValidationFailure response.</p>
<p><a href=""https://i.stack.imgur.com/Wthmx.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Wthmx.png"" alt=""enter image description here"" /></a></p>
<p>And In new version it is implemented by inheriting by <strong>PropertyValidator&lt;TModel, TProperty&gt;</strong>. There is no method to get Validation Failure here, PropertyValidator abstract class is trimmed with minimum methods in newer versions.</p>
<p><a href=""https://i.stack.imgur.com/21zQT.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/21zQT.png"" alt=""enter image description here"" /></a></p>
<p>I have my unit test cases written on this Custom Property Validator, with earlier versions I was able to Assert messages and errors by calling Validate method which returns ValidationFailure result.
How can I achieve same in the newer version?</p>
",https://stackoverflow.com/questions/73321394/fluent-validator-unit-testing-of-custom-property-validator,"['asp.net-core', 'validation', 'fluentvalidation', '.net-core-3.1', 'model-validation']",133,False,0,0
React app Unit testing help in covering line,"<pre><code> src/components         |   94.11 |      100 |   83.33 |   93.75 |                   
  Header.jsx            |     100 |      100 |     100 |     100 |                   
  Icn_adminPortal.jsx   |     100 |      100 |     100 |     100 |                   
  NavBar.jsx            |   66.66 |      100 |      50 |   66.66 | 8 

</code></pre>
<p>I can't figure out how to get line 8 covered</p>
<pre><code>import React from 'react';
import BlockBuilder from './Nav/BlockBuilder';
import config from '../navConfig.Json';

const NavBar = () =&gt; (
  &lt;nav className=&quot;nav nav-vertical border nav-chevron&quot; data-toggle=&quot;nav&quot; data-testid=&quot;nav&quot;&gt;
    &lt;ul className=&quot;nav-menu&quot;&gt;
      {Object.values(config).map((block) =&gt; BlockBuilder(block))} // Line 8 &lt;&lt;&lt;&lt;&lt;&lt;
    &lt;/ul&gt;
  &lt;/nav&gt;

);

export default NavBar;
</code></pre>
<p>The BlockBuilder just adds a <li> element with a data-testid. when I look for that data test id with getByTestId, it says the element doesn't exist. The app works fine, but the unit test doesn't work. How would I go about covering line 8?</p>
",https://stackoverflow.com/questions/74647402/react-app-unit-testing-help-in-covering-line,"['reactjs', 'unit-testing']",10,False,0,0
Unit testing for my local server with jest,"<p>I created mini project that running a local server in JS that shows the current date and time and another file that prints the time that is appear in my server, now i want to perform testing with jest on my project...i didnt find a way to perform some testing to verify that the date is appear or the line of the date and some tests like that, i only performed a test that checks if the server is running.</p>
<p>It will help to me a lot if you guys help me to under stand how to test my project with jest.</p>
<p>this is my code</p>
<p>this is the main server file server.js:</p>
<pre><code>    const express = require('express');
const app = express();

app.get('/', (req,res) =&gt;{
    console.log('Here');
    res.send(Date());    
});


app.listen(80);

this is the http request on another file called funcs.js:

    
var http = require('http');

var options = {
  host: 'localhost',
};

callback = function(response) {
  var str = '';

  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

http.request(options, callback).end();


this is one of the unit test i did successfully on test.js file:

    test('request should return something', async () =&gt;{
  axios
  .get('http://localhost:80/').then(res =&gt; {expect(true).toBe(true)}).catch((error)=&gt; {expect(true).toBe(false)});}

  )
</code></pre>
",https://stackoverflow.com/questions/73479486/unit-testing-for-my-local-server-with-jest,"['javascript', 'express', 'unit-testing', 'automation', 'jestjs']",270,False,0,0
Unit testing Laravel Model that includes a relationship,"<p>In my SUT I've got the following function:</p>
<pre class=""lang-php prettyprint-override""><code>class MyClass
{
    public function doSomething(Registration $registration)
    {
        return $registration-&gt;attendees-&gt;first()-&gt;last_name;
    }
}
</code></pre>
<p>Registration is a Laravel Eloquent model that has many Attendees.</p>
<p>I can't seem to create a test for this as everything seems to rely on magic methods.</p>
<p>In my test I've got this:</p>
<pre><code>public function testDoSomething()
{
    $this-&gt;attendeeMock-&gt;last_name = &quot;Bar&quot;;
    $this-&gt;collection[0] = $this-&gt;attendeeMock; // This is a real Eloquent Collection
    $this-&gt;registrationMock-&gt;attendees = $this-&gt;collection;
    $this-&gt;assertEquals('Bar', $this-&gt;myClass-&gt;doSomething($this-&gt;registrationMock));
}
</code></pre>
<p>The above code throws <code>Call to a member function first() on null</code>.</p>
<p>This seems to be such a simple use case, but on the internet I can't find appropriate answers. Are we supposed to avoid using magic accessors and use <code>getRelationship</code> and <code>getAttribute</code> for everything?</p>
",https://stackoverflow.com/questions/71491878/unit-testing-laravel-model-that-includes-a-relationship,"['php', 'laravel', 'unit-testing', 'phpunit']",981,False,-1,1
getting issue in jest unit testing for login,"<p>i have created login page,which works fine, when i created unit test for that module with jest, i am getting issue, it doesn't return promiss when login api calls, here is my code for react and jest respectively, i am not getting console for <code>console.log(&quot;after login&quot;);</code> can anyone please check my code and help to resolve this issue ?</p>
<pre><code>validateAll(formData, rules, message).then(async () =&gt; {


            dispatch(setLoading(true))

            console.log(&quot;before login&quot;);    
            const login = await authApi.login(app, email, password)
            console.log(&quot;after login&quot;);    

            if (login &amp;&amp; login.error &amp;&amp; login.error !== null) {

                dispatch(setLoading(false))
                ToastAlert({ msg: login.error.error || login.error.message, msgType: 'error' });
                dispatch(setToken(''))

            } else {
                console.log(&quot;done&quot;);
                dispatch(setToken(login.data._accessToken))
                setSuccess(true)
                dispatch(setLoading(false))
                //router.replace(&quot;/&quot;);
                ToastAlert({ msg: 'You have successfully logged in', msgType: 'success' });
            }
        }
</code></pre>
<p>auth</p>
<pre><code>import { resolve } from &quot;./resolve&quot;;
import * as Realm from &quot;realm-web&quot;;
function auth() {
    const register = async (app: any, data: object) =&gt; {
        return await resolve(
            app.emailPasswordAuth.registerUser(data)
                .then((response: any) =&gt; response)
        )
    }
    const login = async (app: any, email: string, password: string) =&gt; {
        const credentials = await Realm.Credentials.emailPassword(email, password);
        return await resolve(
            app.logIn(credentials)
                .then((response: any) =&gt; response)
        )
    }
    const confirmUser = async (app: any, data: object) =&gt; {
        return await resolve(
            app.emailPasswordAuth.confirmUser(data)
                .then((response: any) =&gt; response)
        )
    }
    const logout = async (app: any) =&gt; {
        return await resolve(

            app.currentUser.logOut()
                .then((response: any) =&gt; response)
        )
    }
    return {
        register,
        login,
        confirmUser,
        logout
    }
}
const authApi = auth();
export default authApi;
</code></pre>
<p>unit test</p>
<pre><code>test('login with correct username and password', async () =&gt; {
        const initialState = {
            email: '',
            password: '',
            error: {
                email: &quot;&quot;,
                password: &quot;&quot;
            },
        };
        const mockStore = configureStore();
        let store;
        store = mockStore(initialState);
        const { getByText,getByLabelText } = render(
            &lt;Provider store={store}&gt;
                &lt;Authenticate  /&gt;
            &lt;/Provider&gt;
        );
        // fill out the form
        fireEvent.change(screen.getByLabelText('Email'), {
            target: {value: '***@gmail.com'},
        })
        fireEvent.change(screen.getByLabelText(/Parola/i), {
            target: {value: '****@123'},
        })
        const loginAwait = screen.getByText(/Authentificare/i);      
        await fireEvent.click(loginAwait)

        // wait for the error message
        const alert = await screen.findByRole('alert')
        expect(alert).toHaveTextContent(/You have successfully logged in/i)
    })
</code></pre>
",https://stackoverflow.com/questions/74326920/getting-issue-in-jest-unit-testing-for-login,"['reactjs', 'next.js', 'jestjs']",924,True,0,1
Python unit testing with Docker and environment variables,"<p>I am trying to run unit tests for my application with a Docker container (and possibly in a GitHub workflow), but I can't figure out how to correctly pass env variables to it.</p>
<p>So normally for the building process I have a pretty standard Dockerfile</p>
<pre><code>FROM python:3.7-alpine3.15

WORKDIR /app

COPY requirements.txt requirements.txt

RUN pip3 install -r requirements.txt

COPY src/ .

CMD [ &quot;python3&quot;, &quot;main.py&quot; ]
</code></pre>
<p>and a workflow that builds it and pushes the image to Docker Hub. Then of course the usual <code>docker run --env-file=.env ...</code> command to run the application fetching the variables from a file.</p>
<p>Now I am adding tests to the code. The application needs some env variables to function properly (auth keys and other stuff), and so of course also to run the tests. I don't want to export the variables in my system and run the test from my terminal, so I want to use Docker. But I'm not really sure how to properly do it.</p>
<p>My goal is to be able to run the tests locally and to also have a workflow that runs on PRs, without committing the variables in the repo.</p>
<p>This is what I've tried so far:</p>
<ul>
<li>Add test to the Dockerfile: adding <code>RUN python -m unittest -s tests</code> doesn't really work because at build time Docker doesn't have access to the .env file</li>
<li>Add GitHub workflow with the test command: even using a GitHub environment to store secrets and deploying the job into that for some reason doesn't fetch the variables. Plus I would like to be able to test the code before pushing the changes, and have this workflow run only on PRs.</li>
</ul>
<pre class=""lang-yaml prettyprint-override""><code>jobs:
  test:
    runs-on: ubuntu-latest
    environment: test
    steps:
      - name: Checkout
        uses: actions/checkout@v2
      - name: Set up Python 3.7
        uses: actions/setup-python@v2
        with:
          python-version: 3.7
          cache: 'pip'
      - name: Install dependencies
        run: pip install -r requirements.txt
      - name: Run tests
        shell: bash
        env:
          EMAIL: ${{ secrets.EMAIL }}
          AUTH_KEY: ${{ secrets.AUTH_KEY }}
          ZONE_NAME: ${{ secrets.ZONE_NAME }}
          RECORD_ID: ${{ secrets.RECORD_ID }}
          CHECK_INTERVAL: ${{ secrets.CHECK_INTERVAL }}
          SENDER_ADDRESS: ${{ secrets.SENDER_ADDRESS }}
          SENDER_PASSWORD: ${{ secrets.SENDER_PASSWORD }}
          RECEIVER_ADDRESS: ${{ secrets.RECEIVER_ADDRESS }}
        run: |
          python -m unittest discover -t src -s tests
</code></pre>
<p><a href=""https://github.com/DaruZero/cloudflare-dns-auto-updater/tree/test/12/feature-add-testing"" rel=""nofollow noreferrer"">Here</a> you can find the full source code if needed.</p>
",https://stackoverflow.com/questions/74765040/python-unit-testing-with-docker-and-environment-variables,"['python', 'docker', 'unit-testing', 'environment-variables', 'github-actions']",393,True,0,1
"Unit Testing Javalin Framework, Mocking Context doesn&#39;t work","<p>I'm using Javalin 4 and Mockito 4, and I want to test a simple controller method.</p>
<p>I was reading a tutorial in here : <a href=""https://javalin.io/tutorials/testing"" rel=""nofollow noreferrer"">https://javalin.io/tutorials/testing</a></p>
<p>here is my controller :</p>
<pre class=""lang-java prettyprint-override""><code>package mhndev.controller;

import io.javalin.http.Context;

public final class CakeController 
{

    private CakeController() {}

    static String[] cakes = {&quot;Cheese&quot;, &quot;Chocolate&quot;, &quot;Carrot&quot;, &quot;Banana&quot;};

    public static void getOneCake(Context ctx) {
        for(String cake: cakes) {
            if(cake.equals(ctx.pathParam(&quot;cake&quot;))) {
                ctx.result(cake);
                return;
            }
        }
        ctx.result(&quot;cake was not found!&quot;);
    }
}
</code></pre>
<p>And this is my very simple test:</p>
<pre class=""lang-java prettyprint-override""><code>package mhndev;

import io.javalin.http.Context;
import mhndev.controller.CakeController;
import org.junit.jupiter.api.Test;

import static org.mockito.Mockito.*;

public class CakeControllerTest {

    private final Context ctx = mock(Context.class);

    @Test
    public void GET_apple_cakes() {
        when(ctx.pathParam(&quot;cake&quot;)).thenReturn(&quot;Banana&quot;);
        CakeController.getOneCake(ctx);
        verify(ctx, times(1)).pathParam(&quot;Banana&quot;);
    }

}

</code></pre>
<p>And I received this error upon running the test :</p>
<pre><code>
java.lang.NullPointerException: Parameter specified as non-null is null: method io.javalin.http.util.ContextUtil.pathParamOrThrow, parameter pathParams

    at io.javalin.http.util.ContextUtil.pathParamOrThrow(ContextUtil.kt)
    at io.javalin.http.Context.pathParam(Context.kt:175)
    at mhndev.CakeControllerTest.GET_apple_cakes(CakeControllerTest.java:15)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    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$7(TestMethodTestDescriptor.java:214)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    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:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)


Process finished with exit code 255
</code></pre>
<p>It's like Context.pathParam method is really getting called, using mockito and mocking the context object shouldn't create a new object and not calling the real method from real object? Why this happens and How should I test?</p>
<p>and finally this is my pom.xml</p>
<pre class=""lang-xml prettyprint-override""><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;

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

  &lt;groupId&gt;mhndev&lt;/groupId&gt;
  &lt;artifactId&gt;test&lt;/artifactId&gt;
  &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;
  &lt;name&gt;test&lt;/name&gt;
  &lt;url&gt;http://www.example.com&lt;/url&gt;

  &lt;properties&gt;
    &lt;java.version&gt;17&lt;/java.version&gt;
    &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt;
    &lt;maven.compiler.source&gt;17&lt;/maven.compiler.source&gt;
    &lt;maven.compiler.target&gt;17&lt;/maven.compiler.target&gt;
  &lt;/properties&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.8.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-core&lt;/artifactId&gt;
      &lt;version&gt;4.3.1&lt;/version&gt;
      &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;io.javalin&lt;/groupId&gt;
      &lt;artifactId&gt;javalin&lt;/artifactId&gt;
      &lt;version&gt;4.3.0&lt;/version&gt;
    &lt;/dependency&gt;
    &lt;dependency&gt;
      &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
      &lt;artifactId&gt;slf4j-simple&lt;/artifactId&gt;
      &lt;version&gt;1.7.36&lt;/version&gt;
    &lt;/dependency&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.13.1&lt;/version&gt;
    &lt;/dependency&gt;
  &lt;/dependencies&gt;
&lt;/project&gt;

</code></pre>
",https://stackoverflow.com/questions/71362745/unit-testing-javalin-framework-mocking-context-doesnt-work,"['java', 'unit-testing', 'mocking', 'mockito', 'javalin']",602,False,1,0
Using FakeFirebaseFirestore for unit testing in firebase flutter,"<p>I am trying to do some unit test for my firestore project. I am using a <code>FakeFirebaseFirestore()</code> to simulate the firestore database. I can call my methods with no problems but if this method have a cloud function call then I get an error <code>[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()' has been created - call Firebase.initializeApp() </code>. And I am not understanding why, because if I use a <code>FakeFirebaseFirestore</code> then I am suppose to have a firestore database. My error is when the method that I call have a cloud functions, I tried passing the <code>FirebaseFunction</code> as a parameter instead of calling it directly.</p>
<p>This is my test:</p>
<pre><code>  test('Test delete ', () async {
final firestore = FakeFirebaseFirestore();
FirebaseFunctions functions;
WidgetsFlutterBinding.ensureInitialized();


FirebaseCloudStorage firebaseCloudStorage = FirebaseCloudStorage(firestore: firestore,
    );
await firebaseCloudStorage.createNewShoppingCartList(ownerUserId: 'userId1', name: 'listName');

Iterable&lt;CloudShoppingCartList&gt; list =
    await firebaseCloudStorage.getShoppingCartLists(ownerUserId: 'userId1').first;

expect(list.first.name, 'listName');
expect(list.length, 1);

await firebaseCloudStorage.deleteShoppingCart(shoppingCartId: list.first.shoppingCartListId);

Iterable&lt;CloudShoppingCartList&gt; list2 = await firebaseCloudStorage.getShoppingCartLists(ownerUserId: 'userId1').first;

expect(list2.length, 0);
});
</code></pre>
<p>If I remove the call to deleteShoppingCart
Here is my <code>deleteShoppingCart</code>:</p>
<pre><code>Future&lt;void&gt; deleteShoppingCart({
 required String shoppingCartId,
}) async {
try {
  FirebaseFirestore db = firestore;
  final batch = db.batch();

  final data = {
    'shoppingCartListId': shoppingCartId,
    'name' : 'name Products'
  };
 //Here is the error when I call the functions I got the No Firebase App
  var delete = functions.httpsCallable(deleteShoppingListsCollectionsFunction).call(data);
  
  batch.delete(firestore.collection(shoppingCartListCollectionName).doc(shoppingCartId));
  batch.delete(firestore.collection(shoppingListCollectionName).doc(shoppingCartId));

  batch.commit();
} on FirebaseFunctionsException catch (err){
  print('The delete error is ' + err.toString());
} catch (e) {
  throw CouldNotDeleteListException();
}
</code></pre>
<p>}</p>
<p>Can anyone explain me why the <code>FirebaseFunctions</code> doesn't consider my <code>FakeFirebaseFirestore</code> as firebase app please? Or how should I make the unit test in this case?</p>
",https://stackoverflow.com/questions/74618614/using-fakefirebasefirestore-for-unit-testing-in-firebase-flutter,"['flutter', 'firebase', 'unit-testing', 'google-cloud-functions']",71,False,0,0
How to mock settings in Django Unit testing,"<p>I am new to Django Unit testing and am trying to write unit test for a simple function which is like below:</p>
<pre><code>utils.py
#some import statements
from django.conf import settings

if platform.system() == 'Linux':
    cx_Oracle.init_oracle_client(lib_dir=settings.GAP_DB_LIB_DIR)
else:
    cx_Oracle.init_oracle_client(lib_dir=settings.LOCAL_DB_LIB_DIR)
db_password = settings.DB_PASS
db_user = settings.DB_USER
db_connection_dsn = settings.DB_CONNECTION_DSN

def project(repo):
    pieces = parse.urlsplit(repo)
    return pieces.path.rstrip('/').split('/')[-1]
</code></pre>
<p>I am writing unit tests in test.py fie as below</p>
<pre><code>from django.test import TestCase
from common import utils
from utils import project
from django.test import override_settings

# Create your tests here.
class UtilsTest(TestCase):
    def setUp(self):
        self.repo = &quot;http://test/testrepo&quot;

    @override_settings(LOCAL_DB_LIB_DIR=&quot;c:/testdir&quot;)
    def test_project(self):
        response = utils.project(self.repo)
        self.assertEqual(response,&quot;testrepo&quot;)
</code></pre>
<p>When I run tests am getting below error:
AttributeError: 'Settings' object has no attribute 'LOCAL_DB_LIB_DIR'
Please help me where I am doing wrong and correct my coding. Thanks in advance.</p>
",https://stackoverflow.com/questions/74150869/how-to-mock-settings-in-django-unit-testing,"['python', 'django', 'django-unittest']",47,False,0,0
Unit testing Google Play Store Billing with Node,"<p>I want to write unit tests to test how my backend handles subscriptions and purchases in my android app. I am using the <a href=""https://developers.google.com/android-publisher/api-ref/rest/v3/monetization.subscriptions"" rel=""nofollow noreferrer"">Google Play Developer API</a> to create subscriptions and <a href=""https://developer.android.com/google/play/billing/rtdn-reference"" rel=""nofollow noreferrer"">real-time developer notifications</a> (RTDN) to listen for updates.</p>
<p>Is there a way to test either the Google Play Developer API or RTDN programatically? My goals are to do the following without using the frontend:</p>
<ol>
<li>Create subscriptions and test fake users paying for subscriptions</li>
<li>Send RTDN of the <a href=""https://developer.android.com/google/play/billing/rtdn-reference#sub"" rel=""nofollow noreferrer"">SubscriptionNotification</a> type to test how my backend handles subscription updates
<ul>
<li>I was able to publish a <a href=""https://developer.android.com/google/play/billing/rtdn-reference#test"" rel=""nofollow noreferrer"">TestNotification</a> using RTDN from the Google Play console, but the test notification does not allow me to test any logic related to updating user/payment information in the back end.</li>
</ul>
</li>
</ol>
<p>All the information I found surrounding <a href=""https://developer.android.com/google/play/billing/test"" rel=""nofollow noreferrer"">testing Google Play billing integration</a> requires an implemented UI. The Google support docs for <a href=""https://support.google.com/googleplay/android-developer/answer/6062777?hl=en"" rel=""nofollow noreferrer"">testing in-app billing</a> also do not have any information to test integration without implementing the frontend, and the <a href=""https://developers.google.com/android-publisher"" rel=""nofollow noreferrer"">Google Play Developer API Docs</a> don't have information regarding unit testing.</p>
<p>Is there any way to make test Google Play Store payments on the backend (with Node) without implementing any front-end functionality?</p>
<p>I figured there must be some way this is supported but I have look around a lot and have not found anything helpful. Are tests like these not supported with Google Play's billing system?</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/73239719/unit-testing-google-play-store-billing-with-node,"['android', 'unit-testing', 'google-play', 'google-play-developer-api', 'google-play-billing']",165,False,0,0
Unit testing of tls enabled in akka http,"<p>I have enabled tls in my application to use HTTPS instead of HTTP. Now I want to write its unit test.</p>
<pre class=""lang-scala prettyprint-override""><code> path(&quot;Ping&quot;) {
      complete(&quot;Pong&quot;)
    } 
</code></pre>
<pre class=""lang-scala prettyprint-override""><code>Get(&quot;/Ping&quot;) ~&gt; routes ~&gt; check {
          status shouldEqual StatusCodes.OK
        }
</code></pre>
<p>So I expect it to be <strong>break if request sent using http and work only if sent using https</strong>.</p>
<p>I have tried many things which I found on internet.</p>
<p>Could anyone please help me how can I test it.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/71673645/unit-testing-of-tls-enabled-in-akka-http,"['scala', 'https', 'akka', 'akka-http']",74,True,0,1
How do you do unit testing with SQFLITE?,"<p>I have a database class that handles all my database operations with functions inside it. How do I make unit tests with this, without it messing up my real database and how do I make it so that it always starts from a clean state?</p>
",https://stackoverflow.com/questions/73918727/how-do-you-do-unit-testing-with-sqflite,['flutter'],75,True,0,1
Unit testing of Hibernate Queries in Spring Boot,"<p>How do I write unit-test (slice test) cases for Hibernate Criteria queries written in the app? The <code>@DataJpaTest</code> isn't working in this case and seems to be working just for Spring Data JPA. Below is the unit test code</p>
<pre class=""lang-java prettyprint-override""><code>@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class AppDaoTests {

    @Autowired
    private AppDao appDao;

    @Autowired
    private EntityManager entityManager;

    @Test
    public void getAppWithName() {
        App expected = AppStub.getApp();
        App app = appDao.getApp(&quot;dummy&quot;);

        assertThat(app.getName()).isEqualTo(expected.getName());
    }
}
</code></pre>
<p>Below is the error log that is received.</p>
<pre class=""lang-java prettyprint-override""><code>  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.7.0)

2022-09-05 14:53:42.344
             INFO  [&lt;clinit&gt;] org.hibernate.validator.internal.util.Version : HV000001: Hibernate Validator 6.2.3.Final
2022-09-05 14:53:42.441
             INFO  [logStarting] org.springframework.boot.StartupInfoLogger : Starting AppDaoTests using Java 11.0.15.1 on QCLAP1884P890 with PID 24153 (started by vaibhav.swarnkar in /Users/vaibhav.swarnakar/IdeaProjects/shift(payout)/landing)
2022-09-05 14:53:42.448
             INFO  [logStartupProfileInfo] org.springframework.boot.SpringApplication : The following 1 profile is active: &quot;test&quot;
2022-09-05 14:53:43.600
             INFO  [multipleStoresDetected] org.springframework.data.repository.config.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2022-09-05 14:53:43.602
             INFO  [registerRepositoriesIn] org.springframework.data.repository.config.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2022-09-05 14:53:43.702
             INFO  [registerRepositoriesIn] org.springframework.data.repository.config.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 91 ms. Found 4 JPA repository interfaces.
2022-09-05 14:53:44.579
             INFO  [getConnection]       com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-09-05 14:53:45.146
             INFO  [getConnection]       com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2022-09-05 14:53:45.365
             INFO  [logPersistenceUnitInformation] org.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2022-09-05 14:53:45.431
             INFO  [logVersion]                    org.hibernate.Version : HHH000412: Hibernate ORM core version 5.6.9.Final
2022-09-05 14:53:45.700
             INFO  [&lt;clinit&gt;] org.hibernate.annotations.common.reflection.java.JavaReflectionManager : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2022-09-05 14:53:45.857
             INFO  [&lt;init&gt;]            org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect
2022-09-05 14:53:47.171
             INFO  [initiateService] org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2022-09-05 14:53:47.184
             INFO  [buildNativeEntityManagerFactory] org.springframework.orm.jpa.AbstractEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2022-09-05 14:53:48.067
             INFO  [logStarted] org.springframework.boot.StartupInfoLogger : Started AppDaoTests in 6.479 seconds (JVM running for 8.856)



============================
CONDITIONS EVALUATION REPORT
============================


Positive matches:
-----------------

   DataSourceAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType' (OnClassCondition)
      - @ConditionalOnMissingBean (types: io.r2dbc.spi.ConnectionFactory; SearchStrategy: all) did not find any beans (OnBeanCondition)

   DataSourceAutoConfiguration.PooledDataSourceConfiguration matched:
      - AnyNestedCondition 1 matched 1 did not; NestedCondition on DataSourceAutoConfiguration.PooledDataSourceCondition.PooledDataSourceAvailable PooledDataSource found supported DataSource; NestedCondition on DataSourceAutoConfiguration.PooledDataSourceCondition.ExplicitType @ConditionalOnProperty (spring.datasource.type) did not find property 'type' (DataSourceAutoConfiguration.PooledDataSourceCondition)
      - @ConditionalOnMissingBean (types: javax.sql.DataSource,javax.sql.XADataSource; SearchStrategy: all) did not find any beans (OnBeanCondition)

   DataSourceConfiguration.Hikari matched:
      - @ConditionalOnClass found required class 'com.zaxxer.hikari.HikariDataSource' (OnClassCondition)
      - @ConditionalOnProperty (spring.datasource.type=com.zaxxer.hikari.HikariDataSource) matched (OnPropertyCondition)
      - @ConditionalOnMissingBean (types: javax.sql.DataSource; SearchStrategy: all) did not find any beans (OnBeanCondition)

   DataSourceInitializationConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.jdbc.datasource.init.DatabasePopulator' (OnClassCondition)
      - @ConditionalOnSingleCandidate (types: javax.sql.DataSource; SearchStrategy: all) found a single bean 'dataSource'; @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.sql.init.SqlDataSourceScriptDatabaseInitializer,org.springframework.boot.autoconfigure.sql.init.SqlR2dbcScriptDatabaseInitializer; SearchStrategy: all) did not find any beans (OnBeanCondition)

   DataSourcePoolMetadataProvidersConfiguration.HikariPoolDataSourceMetadataProviderConfiguration matched:
      - @ConditionalOnClass found required class 'com.zaxxer.hikari.HikariDataSource' (OnClassCondition)

   DataSourceTransactionManagerAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'org.springframework.jdbc.core.JdbcTemplate', 'org.springframework.transaction.TransactionManager' (OnClassCondition)

   DataSourceTransactionManagerAutoConfiguration.JdbcTransactionManagerConfiguration matched:
      - @ConditionalOnSingleCandidate (types: javax.sql.DataSource; SearchStrategy: all) found a single bean 'dataSource' (OnBeanCondition)

   HibernateJpaAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean', 'javax.persistence.EntityManager', 'org.hibernate.engine.spi.SessionImplementor' (OnClassCondition)

   HibernateJpaConfiguration matched:
      - @ConditionalOnSingleCandidate (types: javax.sql.DataSource; SearchStrategy: all) found a single bean 'dataSource' (OnBeanCondition)

   JdbcTemplateAutoConfiguration matched:
      - @ConditionalOnClass found required classes 'javax.sql.DataSource', 'org.springframework.jdbc.core.JdbcTemplate' (OnClassCondition)
      - @ConditionalOnSingleCandidate (types: javax.sql.DataSource; SearchStrategy: all) found a single bean 'dataSource' (OnBeanCondition)

   JdbcTemplateConfiguration matched:
      - @ConditionalOnMissingBean (types: org.springframework.jdbc.core.JdbcOperations; SearchStrategy: all) did not find any beans (OnBeanCondition)

   JpaBaseConfiguration#entityManagerFactory matched:
      - @ConditionalOnMissingBean (types: org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean,javax.persistence.EntityManagerFactory; SearchStrategy: all) did not find any beans (OnBeanCondition)

   JpaBaseConfiguration#entityManagerFactoryBuilder matched:
      - @ConditionalOnMissingBean (types: org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder; SearchStrategy: all) did not find any beans (OnBeanCondition)

   JpaBaseConfiguration#jpaVendorAdapter matched:
      - @ConditionalOnMissingBean (types: org.springframework.orm.jpa.JpaVendorAdapter; SearchStrategy: all) did not find any beans (OnBeanCondition)

   JpaBaseConfiguration#transactionManager matched:
      - @ConditionalOnMissingBean (types: org.springframework.transaction.TransactionManager; SearchStrategy: all) did not find any beans (OnBeanCondition)

   NamedParameterJdbcTemplateConfiguration matched:
      - @ConditionalOnSingleCandidate (types: org.springframework.jdbc.core.JdbcTemplate; SearchStrategy: all) found a single bean 'jdbcTemplate'; @ConditionalOnMissingBean (types: org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations; SearchStrategy: all) did not find any beans (OnBeanCondition)

   NoOpCacheConfiguration matched:
      - Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration NONE cache type (CacheCondition)

   SqlInitializationAutoConfiguration matched:
      - @ConditionalOnProperty (spring.sql.init.enabled) matched (OnPropertyCondition)
      - NoneNestedConditions 0 matched 1 did not; NestedCondition on SqlInitializationAutoConfiguration.SqlInitializationModeCondition.ModeIsNever @ConditionalOnProperty (spring.sql.init.mode=never) did not find property 'mode' (SqlInitializationAutoConfiguration.SqlInitializationModeCondition)

   TestEntityManagerAutoConfiguration matched:
      - @ConditionalOnClass found required class 'javax.persistence.EntityManagerFactory' (OnClassCondition)

   TestEntityManagerAutoConfiguration#testEntityManager matched:
      - @ConditionalOnMissingBean (types: org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; SearchStrategy: all) did not find any beans (OnBeanCondition)

   TransactionAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.transaction.PlatformTransactionManager' (OnClassCondition)

   TransactionAutoConfiguration#platformTransactionManagerCustomizers matched:
      - @ConditionalOnMissingBean (types: org.springframework.boot.autoconfigure.transaction.TransactionManagerCustomizers; SearchStrategy: all) did not find any beans (OnBeanCondition)

   TransactionAutoConfiguration.EnableTransactionManagementConfiguration matched:
      - @ConditionalOnBean (types: org.springframework.transaction.TransactionManager; SearchStrategy: all) found bean 'transactionManager'; @ConditionalOnMissingBean (types: org.springframework.transaction.annotation.AbstractTransactionManagementConfiguration; SearchStrategy: all) did not find any beans (OnBeanCondition)

   TransactionAutoConfiguration.EnableTransactionManagementConfiguration.CglibAutoProxyConfiguration matched:
      - @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition)

   TransactionAutoConfiguration.TransactionTemplateConfiguration matched:
      - @ConditionalOnSingleCandidate (types: org.springframework.transaction.PlatformTransactionManager; SearchStrategy: all) found a single bean 'transactionManager' (OnBeanCondition)

   TransactionAutoConfiguration.TransactionTemplateConfiguration#transactionTemplate matched:
      - @ConditionalOnMissingBean (types: org.springframework.transaction.support.TransactionOperations; SearchStrategy: all) did not find any beans (OnBeanCondition)



Exclusions:
-----------

    None


Unconditional classes:
----------------------

    org.springframework.boot.test.autoconfigure.jdbc.TestDatabaseAutoConfiguration



2022-09-05 14:53:48.090
            ERROR  [prepareTestInstance] org.springframework.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@1f14f20c] to prepare test instance [test.dao.sql.dao.AppDaoTests@79aba813]
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'test.dao.sql.dao.AppDaoTests': Unsatisfied dependency expressed through field 'appDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'test.dao.sql.AppDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:417) ~[spring-beans-5.3.20.jar:5.3.20]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:119) ~[spring-test-5.3.20.jar:5.3.20]
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-5.3.20.jar:5.3.20]
</code></pre>
",https://stackoverflow.com/questions/73607360/unit-testing-of-hibernate-queries-in-spring-boot,"['java', 'spring', 'spring-boot', 'hibernate', 'unit-testing']",324,False,0,0
get value from a Promise for unit-testing,"<p>I have a method inside a class calculating the sum of 2 parameters that returns a Promise (a must):</p>
<pre><code>module.exports = class Sum {
  sum(a, b) {
    let c = a + b;
    const myPromise = new Promise(function(myResolve) {
      setTimeout(function(){ myResolve(c); }, 100);
    });
    return myPromise;
  }
}
</code></pre>
<p>I use Jasmine framework to unit-test</p>
<pre><code>const MyLocalVariable1 = require('../src/sum'); 
describe('CommonJS modules', () =&gt; {
  it('should import whole module using module.exports = sum;', async () =&gt; {
    const result = new MyLocalVariable1();
    expect(result.sum(4, 5).then(function(value) {
      return value;
    })).toBe(9);
  });
}
</code></pre>
<p>The first expression is what we want to test:</p>
<pre><code>result.sum(4, 5).then(function(value) {
  return value;
})
</code></pre>
<p>and the second one is the expected value:</p>
<pre><code>toBe(9)
</code></pre>
<p>But how can I get a value from the first expression, because it's a Promise, and expected value of it is <em>[object Promise]</em>. Thanks in advance</p>
",https://stackoverflow.com/questions/71945222/get-value-from-a-promise-for-unit-testing,"['javascript', 'unit-testing', 'jasmine']",72,True,0,1
Set Up Development Environment for Unit Testing C,"<p>I'm new to unit testing and have mostly programmed using IDEs, therefore I haven't created and/or modified makefiles before.</p>
<p>Now that I'm exploring Unit Testing and TDD in general; I'm not sure how to set up the development environment so that my unit tests automatically run on every build.</p>
<p>Please help. A general procedure to achieve this would do wonders.</p>
<p>I have not tried anything yet as I'm not very familiar with modifying C Make files.</p>
",https://stackoverflow.com/questions/74587051/set-up-development-environment-for-unit-testing-c,"['c', 'unit-testing', 'cmake', 'ide', 'development-environment']",154,True,0,1
Unit testing functions that call WordPress core functions,"<p>Need to write a php unit test for <code>init()</code>.</p>
<pre><code>namespace My\Space;

class MyClass{
   public function init(){
       add_action('my_hook','my_function',10,0);
   }
}
</code></pre>
<p>All the test needs to do is assert that <code>add_action()</code> was called with the correct parameters.  If <code>add_action()</code> was a method of another class (lets call it <code>class WP_Functions</code>), then an instance of that class could be passed into the constructor of <code>MyClass</code> and used in <code>init()</code> to do the <code>add_action()</code>.  If so, Unit testing could pass in a mock of <code>WP_Functions</code> that asserts that <code>add_action()</code> be called with the desired input parameters.  But now that <code>add_action()</code> is not a class method, what is the best solution?</p>
<p>Here is what I've tried:</p>
<ul>
<li><p>Let <code>add_action()</code> run as it is defined by WordPress.  Remove actions from <code>my_hook</code>, call <code>init()</code> and then assert all the correct values are set in <code>$wp_filter['my_hook']</code>. Simple enough for the above case but gets complicated for functions that have conditions and/or add/remove many hooks/filters.</p>
</li>
<li><p>Define mock version <code>add_action()</code> in the <code>My\Space</code> namespace and make it simply <code>var_dump()</code> the input parameters.  Then all the test needs to do is expect that <code>init()</code> will outputs the <code>var_dump</code> for the desired parameters.  This works well but requires <code>add_action()</code> be redefined for every namespace in which its used.  This becomes difficult to manage when there are many namespaces and/or many other functions similar to <code>add_action()</code> that require mock versions.  Also can get complicated if the callback function is member of <code>MyClass</code> such that it is specified as <code>[ $this, 'callback_name' ]</code>.  Plus, it utilizes <code>var_dump()</code> for a non-intended purpose.</p>
</li>
<li><p>Create a public method of <code>MyClass</code> that called <code>add_action</code> that calls the WordPress <code>add_action()</code>.  If so, testing can create a mock of <code>MyClass</code> that expects it's <code>add_action</code> method to be called with the desired parameters.  However, this requires an extra function call.  Plus it would require every class that calls <code>add_action()</code> to somehow have it's own <code>add_action</code> method.</p>
</li>
</ul>
<p>Is there a better solution?</p>
",https://stackoverflow.com/questions/73666538/unit-testing-functions-that-call-wordpress-core-functions,"['wordpress', 'unit-testing', 'mocking']",37,False,0,0
WKInterfaceDevice not found in scope while Unit Testing,"<p>I am using <code>WKInterfaceDevice</code> in my Watch App to provide haptic feedback. The app runs on a Simulator and Device without any errors. I recently added a Unit Test for this package and while building the app, it throws an error.</p>
<p><a href=""https://i.stack.imgur.com/TwyGC.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/TwyGC.png"" alt=""enter image description here"" /></a></p>
<p>Additional information - This is a part of a view that is written as a package, not sure if that would be relevant as it runs fine normally. The issue only occurs while building for testing.</p>
",https://stackoverflow.com/questions/74042563/wkinterfacedevice-not-found-in-scope-while-unit-testing,"['swift', 'unit-testing', 'apple-watch']",88,False,0,0
Unit testing: Check component does not have style,"<p>I have a component named <code>Message</code> and a property named <code>focus</code>. If focus is true, a style with <code>outline: none</code> will be added. I want to check the opposite case also, that if focus is false, the outline style will be not existed.</p>
<p>I write the test case like this, however the value return is same as focus=&quot;true&quot; (always check it have outline style)</p>
<pre><code>test(&quot;render component without focus&quot;, () =&gt; {
        const { container } = render(&lt;Message focus={false} message={&quot;Message&quot;} /&gt;);
        expect(container.firstChild).not.toHaveStyleRule(&quot;outline&quot;, &quot;none&quot;);
    });
</code></pre>
<p>Does anyone know what I am missing?
Thank all</p>
",https://stackoverflow.com/questions/73701716/unit-testing-check-component-does-not-have-style,"['unit-testing', 'jestjs', 'react-testing-library', 'ts-jest']",40,False,0,0
fastapi&#39;s class as dependency override in unit testing,"<p>Using the parameter supplied in the request body, I wanted to instantiate an object. For instance, if the request body contains <code>type=push</code> I desired to instantiate in this manner.</p>
<pre><code>    if channel_type.upper() == &quot;PUSH&quot;:
       return NotificationService(Push())
</code></pre>
<p>I am able to achieve this through classes as dependency of fastapi as following:</p>
<pre><code>def factory(channel_type):
    if channel_type.upper() == &quot;PUSH&quot;:
        return NotificationService(Push())
    elif channel_type.upper() == &quot;EMAIL&quot;:
        return NotificationService(Email())
    else:
        return NotificationService(Sms())


class NotificationRequest:
    def __init__(self, type: str = Body(&quot;push&quot;)):
        self.service = factory(type)


class MessageRequest(BaseModel):
    title: str
    message: str
    payload: Dict = {}


@router.post(&quot;/&quot;, response_model=dict)
def notify(message: MessageRequest, request: NotificationRequest = Depends()) -&gt; Any:
    request.service.send(users=get_users(), message=Message(
        title=message.title, message=message.message, payload=message.payload
    ))
    return {&quot;success&quot;: True}

 
</code></pre>
<p>However, I wanted to override the NotificationRequest dependency in the unit test so that I could provide fake instances of real classes:</p>
<pre><code>def get_factory(channel_type):
    if channel_type.upper() == &quot;PUSH&quot;:
        return NotificationService(FakePush())
    elif channel_type.upper() == &quot;EMAIL&quot;:
        return NotificationService(FakeEmail())
    else:
        return NotificationService(FakeSms()) 
</code></pre>
<p>I have tried following:</p>
<pre><code>app.dependency_overrides[factory] = lambda: get_factory
</code></pre>
<p>which fails because the factory is not injected through the dependency.</p>
<p>How can we give a parameter to the body and inject a dependency into the function to produce a fake instance for unit testing?</p>
",https://stackoverflow.com/questions/74813396/fastapis-class-as-dependency-override-in-unit-testing,['fastapi'],36,False,0,0
Unit testing with Optionals - Spring Boot and JUnit,"<p><a href=""https://i.stack.imgur.com/JuO0f.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JuO0f.png"" alt=""enter image description here"" /></a></p>
<p>Hey guys. I am trying to test a method that returns an <em>Optional</em>. I am using Spring Boot and JUnit, however, in the thenReturn method it doesn't allow me to return an <em>Optional</em>. I also tried it without <em>Optional.of()</em>. What is the best way to test Optionals? Thanks</p>
",https://stackoverflow.com/questions/74827867/unit-testing-with-optionals-spring-boot-and-junit,"['spring-boot', 'testing', 'junit', 'mockito']",102,False,0,1
Unit testing the modal component inside Blazored Modal,"<p>Been trying to unit test the component rendered inside Blazored Modal. I can of course test the code around it by mocking <code>IModalService</code> but if I want to test the modal component itself, I run into problems. And they stem from calls to <code>BlazoredModalInstance</code>, like to <code>BlazoredModalInstance.CloseAsync(ModalResult)</code>.</p>
<p>I would have liked to mock it but since it doesn't implement any interface, I can't. I tried to create a new <code>BlazoredModal</code> component, but it takes the <code>BlazoredModalInstance</code> as a private CascadingParameter which I cannot provide.</p>
<p>I have also tried rendering the <code>BlazoredModalInstance</code> with bUnit, giving it some <code>ModalOptions</code>, and passing the instance to my modal component, but calls to it lead to crashes (null reference).</p>
<p>Is this somehow possible to achieve? Is there a way to provide cascading parameters without the parameters.Add(...) way?</p>
",https://stackoverflow.com/questions/72199665/unit-testing-the-modal-component-inside-blazored-modal,"['blazor', 'bunit', 'blazored']",379,False,0,0
Stubbing order and process in Unit Testing function,"<p>I am starting to improve at Unit testing, but still thrown off by a few things. So I have the following service function</p>
<pre><code>const connectToService = async (connectionParams) =&gt; {
  try {
    const xmlRequest = await getLoginXml(
      connectionParams.username,
      connectionParams.password,
      connectionParams.url,
    );

    const res = await axios.post(connectionParams.msHost, xmlRequest);
    const dom = new DOMParser().parseFromString(res.data, 'text/xml');

    if (
      !dom.documentElement
        .getElementsByTagName('wsse:BinarySecurityToken')
        .item(0)
    ) {
      throw new Error('Invalid Username/Password');
    }
    return dom.documentElement
      .getElementsByTagName('wsse:BinarySecurityToken')
      .item(0).firstChild.nodeValue;
    
  } catch (e) {
    throw new Error(`Error making connection - ${e.message}`);
  }
};

module.exports = {
  connectToService,
};
</code></pre>
<p>So I have a relatively straight forward function above.  Takes <code>connectionParams</code> and injects some params using <code>getLoginXml</code>, which just returns some XML.</p>
<p>I then make a POST request with that xml and receive a response.  I then parse this response and return a token if there is one, if not, I throw an Error.</p>
<p>The thing that is throwing me is that there are a few things going on in this function, and I am not sure what to stub.</p>
<p>SO what would be the process first?  Stub <code>getLoginXml</code> and then let the rest of the function run?  And go through the file sequentially?</p>
<p>Any advice appreciated - I have done well with my integration tests, but unit test I am struggling to fully get to grips with.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/73437634/stubbing-order-and-process-in-unit-testing-function,"['node.js', 'unit-testing', 'mocha.js', 'sinon']",17,False,0,0
Android: unit testing use case that saves file,"<p>I'm writing unit tests for a use case that basically creates a file with the contents of an InputStream.</p>
<p>However, with the lines:</p>
<pre><code>val path = context.filesDir.path + &quot;/issues.csv&quot;
val fos = FileOutputStream(path)
</code></pre>
<p>I'm having trouble, as the when trying to create the <code>FileOutputStream</code> from the <code>path</code> it always results in a <code>FileNotFoundException</code>.</p>
<p>This is the complete code:</p>
<pre><code>class SaveFileUseCase @Inject constructor(
    private val context: Context,
    @DefaultCoroutineDispatcher private val defaultCoroutineDispatcher: CoroutineDispatcher
) {
    suspend operator fun invoke(body: ResponseBody) =
        withContext(defaultCoroutineDispatcher) {
            saveFile(body)
        }

    private fun saveFile(body: ResponseBody?) {
        if (body == null) {
            return
        }

        var input: InputStream? = null
        try {
            input = body.byteStream()
            val path = context.filesDir.path + &quot;/issues.csv&quot;
            val fos = FileOutputStream(path)
            fos.use { output -&gt;
                val buffer = ByteArray(4 * 1024) // or other buffer size
                var read: Int
                while (input.read(buffer).also { read = it } != -1) {
                    output.write(buffer, 0, read)
                }
                output.flush()
            }
        } catch (e: Exception) {
            Log.e(&quot;Error saving file&quot;, e.toString())
        } finally {
            input?.close()
        }
    }
}
</code></pre>
<p>How can I test this?</p>
<p>Thanks a lot in advance!</p>
",https://stackoverflow.com/questions/74336916/android-unit-testing-use-case-that-saves-file,"['android', 'kotlin', 'inputstream', 'android-context', 'fileoutputstream']",178,False,0,0
Unit Testing Prometheus Alerts: input series and interval,"<p>I have been writing unit tests for my Prometheus alerts and I have just increased the interval range in my alert, therefore I need to modify my current test. This is my modified test:</p>
<pre><code>  - interval: 15m
    # Series data.
    input_series:
      - series: 'some_bucket{service_name=&quot;some-service&quot;, le=&quot;1000&quot;}'
        values: 6 6 6 6 6 6 6
      - series: 'some_bucket{service_name=&quot;some-service&quot;, le=&quot;10000&quot;}'
        values: 10 11 12 13 14 14 14
      - series: 'some_bucket{service_name=&quot;some-service&quot;, le=&quot;+Inf&quot;}'
        values: 10 100 200 300 400 500 600
    alert_rule_test:
      - eval_time: 5m
        alertname: someName
        exp_alerts: []
      - eval_time: 15m
        alertname: someName
        exp_alerts:
          - exp_labels:
              severity: error
              service_name: some-service
            exp_annotations:
              summary: &quot;a summary&quot;
              description: &quot;adescription&quot;
</code></pre>
<p>and my alert rule is:</p>
<pre><code> histogram_quantile(0.95, sum by(le) (rate(some_bucket{service_name=&quot;some-service&quot;}[15m]))) &gt;= 1000
</code></pre>
<p>The test is working fine, it does not trigger at the <code>eval_time</code> of 5 minutes and it does when it hits the correct interval. My question is regarding the interval set at the top</p>
<pre><code> - interval: 15m
</code></pre>
<p>My understanding is that this should be the scraping interval, but if I change it to 1 the test fails. Why is that? Does it mean that my time series/input data needs changing?</p>
<p>Thank you</p>
",https://stackoverflow.com/questions/74667060/unit-testing-prometheus-alerts-input-series-and-interval,"['unit-testing', 'prometheus', 'alert']",321,True,0,1
Simple checkbox test with vue unit testing library,"<p>Trying to work out something that I thought would be pretty simple!</p>
<p>I have a PrimeVue checkbox component on my page (and I'm using Vue 3, PrimeVue, vitest, @testing-library/vue and @testing-library/user-event)</p>
<pre><code>&lt;div class=&quot;field-checkbox&quot;&gt;
    &lt;Checkbox role = &quot;checkbox&quot; :aria-label=&quot;`Select all students in class ${props.className}`&quot; @change=&quot;selectAllChecked()&quot; v-model=&quot;selectAll&quot; :binary=&quot;true&quot; /&gt;
    &lt;label&gt;Select All&lt;/label&gt;
&lt;/div&gt;
</code></pre>
<p>I just want to write a test to check the checkbox and then test that it is correctly checked - not a particularly meaningful test but I'm new to these libraries (and unit testing) so want to work out how to do this stuff.</p>
<p>In my test I have:</p>
<pre><code>it(&quot;checkbox test&quot;, async() =&gt; {
    const ariaLabel = `Select all students in class ${mockProps.className}`;
    const checkbox = screen.getByRole(&quot;checkbox&quot;, { name: ariaLabel });
    await userEvent.click(checkbox);
    expect(checkbox.getAttribute('checked')).toBe(true)
});
</code></pre>
<p><strong>if I remove the 3rd and 4th lines, the test passes so it seems to be checking that the checkbox is there ok.</strong></p>
<p>Lines 3 and 4 (I hoped) would allow me to confirm that the checkbox is now checked but my test fails with</p>
<pre><code>AssertionError: expected null to be true // Object.is equality
  - Expected   &quot;true&quot;
  + Received   &quot;null&quot;
</code></pre>
<p>on the 4th line</p>
",https://stackoverflow.com/questions/73557108/simple-checkbox-test-with-vue-unit-testing-library,"['vue.js', 'unit-testing', 'vitest', 'vue-testing-library']",452,False,0,0
Unit testing Mybatis response using mockito and junit,"<p>I have below piece of code in my project.</p>
<pre><code>@Qualifier(&quot;EmployeeServiceMapper&quot;)
EmployeeServiceMapper mapper;
    
public EmployeeResponse getEmployeeData(String id,String department){
    
       EmployeeResponse response = new EmployeeResponse();
       
       Map&lt;String,Object&gt; requestMap = new HashMap&lt;&gt;();
       requestMap.put(&quot;id&quot;, id);
       requestMap.put(&quot;dept&quot;, department);

       //connect to db stored procedure
       mapper.getEmployeesList(requestMap);
       
       //List from cursor response
       response.setEmpList((List&lt;Employee&gt;) requestMap.get(&quot;employeesList&quot;));
       response.setDeptInfo((Department) requestMap.get(&quot;departmentDetail&quot;));

       return response;     
    
    }
</code></pre>
<p>Mapper Interface:</p>
<pre><code>public interface EmployeeServiceMapper {
    void getEmployeesList(Map&lt;String,Object&gt; map);
}
</code></pre>
<p>Junit:</p>
<p>I would like to write unit test cases like checking if the data is populated in both empList and deptInfo. I am not sure how to write with Mockito. Can someone kindly help pls</p>
<pre><code>@Test
void testEmployeeData(){
 
    doNothing().when(mapper).getEmployeesList(anyMap());

    //how can I mock the mapper responses here i.e., requestMap.get(&quot;employeesList&quot;))

}
</code></pre>
",https://stackoverflow.com/questions/74614873/unit-testing-mybatis-response-using-mockito-and-junit,"['java', 'junit', 'mockito', 'mybatis', 'junit5']",294,False,0,0
Alternative to Enzyme for unit testing in React,"<p>Since Enzyme is dead for React 18 and everyone seems to be talking about React Testing Library, for a more integration-testing approach. However, in my case I need more of a unit-testing solution to test functions within my React component:</p>
<pre><code>export default function Chat({ userName, roomName }: ChatProps) {
    const [userInput, setUserInput] = useState(&quot;&quot;);
    const [messageList, setMessageList] = useState&lt;SocketMessageNS.NewMessageIn[]&gt;([]);

    const [sendSocketMessage, isConnected] = useSocketIo(userName, roomName, handleOnNewMessage);

    function handleOnNewMessage(msg: SocketMessageNS.NewMessageIn) {
        // ...
    }

    function handleOnSendMessage() {
        // ...
    }

    return (
        &lt;div className=&quot;Chat&quot;&gt;
            &lt;ChatHeader isConnected={isConnected} roomName={roomName} /&gt;
            &lt;ChatConversation data={messageList} userName={userName} /&gt;
            &lt;ChatInput value={userInput} onChange={setUserInput} onSubmit={handleOnSendMessage} /&gt;
        &lt;/div&gt;
    );
}
</code></pre>
<p>I want to be able to test my functions on their own, simply by calling them like you would do with Enzyme:       <code>wrapper.instance().handleOnSendMessage();</code></p>
<p>It doesn't seem to be possible with React Testing Library.
What do you do when you need to test your functions with React components with spies and such?</p>
",https://stackoverflow.com/questions/74281739/alternative-to-enzyme-for-unit-testing-in-react,"['reactjs', 'jestjs', 'react-testing-library']",49,False,-1,1
Angular unit testing check if input is undefined,"<p>I am unable to test else condition in my code as Unable to change value of input(). Please help.
Once I pass data in spec.ts unable to assign other data</p>
<pre><code>@Input() data: any;
ngOnInit(): void {
    if (this.data !== undefined) {
      this.fn1()
    }
    else {
      this fn2()
    }
  }```
</code></pre>
",https://stackoverflow.com/questions/74056695/angular-unit-testing-check-if-input-is-undefined,"['angular', 'unit-testing', 'karma-jasmine', 'angular-unit-test']",550,False,0,1
React hooks unit testing React.memo on a function,"<p>How can I test this function wrapped in the React.memo , below is the function :</p>
<pre><code>    const InternalDocuments = memo(
      forwardRef&lt;FormikProps&lt;BlocksTypes&gt;, InternalDocumentsProps&gt;(
        (
          {
            documentBlocks,
            loanId,
            updateZins,
            mainSetFieldValue,
            completedFieldRequiredRLA2,
            documentData,
          },
          formikRef,
        ) =&gt; {
          const [blocks, setBlocks] = useState&lt;BlockBackend[]&gt;([]);
          const classes = useStyles();
          const { setBalanceSheetValues, setBalanceSchufaValues } = useContext(DataContext);
    
          const mapDocumentBlocks = useCallback(
            () =&gt;
             ...
            [],
          );
    
          const updateDataField = useCallback(
            (levels: indexObj, value: string, id: number) =&gt; {
             ....
            },
            [blocks],
          );
    
          useEffect(() =&gt; {
          }, []);
    
          return (
           &lt;div&gt;...&lt;/div&gt;
          );
        },
      ),
    );
export default InternalDocuments;
</code></pre>
<p>This is my test below :</p>
<pre><code> it('should map document blocks', () =&gt;{
    const { result } = renderHook(() =&gt; InternalDocuments())
    expect(typeof result.current.updateDataField).toBe('function')
  })
</code></pre>
<p>But I get this error :</p>
<pre><code> TypeError: (0 , _InternalDocuments.default) is not a function
</code></pre>
",https://stackoverflow.com/questions/71857422/react-hooks-unit-testing-react-memo-on-a-function,"['reactjs', 'unit-testing', 'react-hooks-testing-library']",44,False,0,0
Unit testing- Test Switch Case Without any function,"<p>I have simple JavaScript file and not able to write the test cases using JEST ,React Testing Library - REACT JS. Below are the code:</p>
<pre><code>const ENV_URL = window.location.origin; //'https://note-dev.meta.com'
const REGEX = /(-)\w+/;
let LINK_ENV = ENV_URL.match(REGEX) &amp;&amp; ENV_URL.match(REGEX)[0];
 
switch (LINK_ENV) {
  case &quot;-dev&quot;:
    LINK_ENV = LINK_ENV.concat('1');
    break;
  default:
    LINK_ENV = '-prd';
    break;
}
export const CONFIGSERVICE = {
  LINK: 'http://oppo' + LINK_ENV + '.internal.meta.com',
  
};
</code></pre>
<p>My test case is:</p>
<pre><code>import {CONFIGSERVICE} from '../../config/development';
    test('success2', () =&gt; {
            const ENV_URL = 'https://note-dev.meta.com';
            const REGEX = /(-)\w+/;
            let LINK_ENV = ENV_URL.match(REGEX) &amp;&amp; ENV_URL.match(REGEX)[0];

            switch (LINK_ENV) {
            case &quot;-dev&quot;:
                LINK_ENV = LINK_ENV.concat('1');
                break;
            }
            expect(CONFIGSERVICE.LINK).toBe(&quot;http://oppo-dev1.internal.meta.com&quot;);
        })
</code></pre>
<p><a href=""https://i.stack.imgur.com/bNCvL.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/bNCvL.png"" alt=""enter image description here"" /></a>
Please help me out on this</p>
",https://stackoverflow.com/questions/71051812/unit-testing-test-switch-case-without-any-function,"['reactjs', 'jestjs', 'react-testing-library']",329,False,0,0
unit testing a function using jasmine in Angular,"<p>I want to write unit test case and code coverage to be dobe for the below code. How can i write?</p>
<pre><code>itemClick($event: any) {
for (let obj of this.tocFiles) {
  let results = this.getchildren(obj, label);
  if (results) {
    console.log(results, 'results');
    this.clickedItem = results.children;
    break;
  }
}
}

 getchildren(obj: any, label: any) {
    if (obj.label == label) {
      return obj;
    }

    if (obj.children) {
      for (let item of obj.children) {
        let check: any = this.getchildren(item, label);
        if (check) {
          return check;
        }
      }
    }
    return null;
  }
</code></pre>
<p>Below is the test case I wrote,</p>
<pre><code>it('Onclick of breadcrumb value, itemClick() to be executed',()=&gt;{ 
  const onCLick = spyOn(component, 'itemClick'); 
  component.itemClick(undefined); 
  expect(onCLick).toHaveBeenCalled(); 
});
</code></pre>
<p>I'm still not getting this code covered under code coverage</p>
",https://stackoverflow.com/questions/71689071/unit-testing-a-function-using-jasmine-in-angular,"['angular', 'typescript', 'unit-testing', 'karma-jasmine']",251,False,-1,1
Django unit testing FileField and ImageField using ContentFile,"<p>I am using Django 3.2</p>
<p>I have a model like this:</p>
<h4>Foo class</h4>
<pre><code>class Foo(models.Model):
    name = models.CharField(max_length=124)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    description = models.TextField()
    bio = models.TextField()
    attachment = models.FileField()
    photo = models.ImageField()
    recorded_date = models.DateField()
    time_of_day = models.TimeField()
    timestamp = models.DateTimeField()
    duration = models.DurationField()
    website = models.URLField()
    pseudo_array = models.CharField(max_length=256)
    pseudo_tags = models.CharField(max_length=128)
</code></pre>
<h4>Snippet of Unit test</h4>
<pre><code>import glob
import os
import json

from datetime import datetime, timedelta
from django.utils.timezone import make_aware

from model_bakery import baker

from django.test import TestCase
from django.core.exceptions import ValidationError
from django.core.files.base import ContentFile



image_mock =ContentFile(b&quot;R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==&quot;, name='photo.png')  
file_mock = ContentFile(&quot;Some random text&quot;, name='archive.txt')  



class TestModels(TestCase):
    def setUp(self):
        current_timestamp = datetime.now(timezone.utc)



        self.foo = Foo.objects.create( name='Accepted Object',bio='For accepted testing',
                                   owner=self.pattysmith,
                                   description='Object for accepted testing',
                                   attachment = file_mock,
                                   photo = image_mock,
                                   recorded_date = datetime.strptime('20200101','%Y%m%d'),
                                   time_of_day = datetime.strptime('10:00','%H:%M'),
                                   timestamp = make_aware(timezone.now().strptime('20200101 10:00','%Y%m%d %H:%M')),
                                   duration = timedelta(days=20, hours=10),
                                   website  = 'https://www.accepted.com',
                                   moderation_status=1,
                                   pseudo_tags='approved,nice, accepted'                            
                                 )    


    def tearDown(self):
        Foo.objects.all().delete()
        User.objects.all().delete()

        for f in glob.glob(&quot;*.png&quot;):
            os.remove(f)

        for f in glob.glob(&quot;*.txt&quot;):
            os.remove(f)            




    def test_change_moderated_char_field(self):
   
        self.foo.name='My new name'
        self.foo.save(update_fields=['name'])

        # test for number of changed fields ...
</code></pre>
<p>When I run the test <code>test_change_moderated_char_field</code> I see that the file and image field names have changed - looks like Django is auto-generating the file names.</p>
<p>Here is what my console printout looks like:</p>
<pre><code>moderated_field_current_field_value: 'My new name'  !=  'Accepted Object'  for moderated field:  name
moderated_field_current_field_value: /path/to/archive_Fo8NWLI.txt  !=  /path/to/archive.txt  for moderated field:  attachment
moderated_field_current_field_value: /path/to/photo_mVEyGtI.png  !=  /path/to/photo.png  for moderated field:  photo
@@@@@@@@@   changed_fields:  [&quot;name&quot;, &quot;attachment&quot;, &quot;photo&quot;]      @@@@@
</code></pre>
<p>I am currently accessing the name of the file/image by accessing the <code>path</code> attribute on the field. How do I get the name of the file when it is actually uploaded (since some name mangling seems to be taking place?</p>
",https://stackoverflow.com/questions/73494482/django-unit-testing-filefield-and-imagefield-using-contentfile,"['django', 'unit-testing', 'django-models']",58,False,0,0
How to integrate Jmeter with mocha unit testing?,"<p>I've written a simple uint test by Mocha Library.</p>
<pre><code>describe(&quot;simple test&quot;, async() =&gt;{

     it(&quot;first test&quot; , async()=&gt;{

        assert.equal( 1 , 1);
     })
})

</code></pre>
<p>Now I need to perform it by JMeter. But I did not find any source for this.</p>
<p>Is it possible to perform the Mocha testing by JMeter or not?</p>
<p>If yes, how?</p>
",https://stackoverflow.com/questions/72710004/how-to-integrate-jmeter-with-mocha-unit-testing,"['javascript', 'jmeter', 'mocha.js', 'performance-testing', 'load-testing']",105,True,-1,1
React-leaflet unit testing with react-testing-library,"<p>I am having some issues in unit testing my Map component created using React-Leaflet.</p>
<p>Here is my code:</p>
<pre><code>test('Map renders', () =&gt; {
  const {container} = render(
   &lt;Map data={mapData} /&gt;
  );
});
</code></pre>
<p>I am getting this error:
<strong>TypeError: Cannot use 'in' operator to search for '_leaflet_id' in null</strong></p>
<p>If I remove the data it works fine, which is required to render the Map.
I tried using <code>&lt;Map data={JSON.parse(mapData)} /&gt;</code> which gives invalid character error.</p>
<p><strong>EDIT:</strong></p>
<p>I finally figured out the problem, but not the solution. The issue is in rendering the Polygon in the Map component. If I comment it out everything(Marker, EditControl, Popup, Tooltip) works like a charm.
Is thetre any alternative way to fix it?</p>
",https://stackoverflow.com/questions/72858361/react-leaflet-unit-testing-with-react-testing-library,"['reactjs', 'unit-testing', 'react-leaflet']",277,False,0,0
How to do azure function (typescript) unit testing,"<p>I'm pretty new to typescripts and jest.  I have an azure function which works with the traffic manager, and I want to do some unit testing, basically updating endpoints.  One thing I want to test is, my code throws exception if the traffic manager does not have exact 2 endpoints.</p>
<p>Azure has a class <code>TrafficManagerManagementClient</code>, this is its definition</p>
<pre class=""lang-js prettyprint-override""><code>export declare class TrafficManagerManagementClient extends coreClient.ServiceClient {
    $host: string;
    apiVersion: string;
    subscriptionId: string;
    /**
     * Initializes a new instance of the TrafficManagerManagementClient class.
     * @param credentials Subscription credentials which uniquely identify client subscription.
     * @param subscriptionId Gets subscription credentials which uniquely identify Microsoft Azure
     *                       subscription. The subscription ID forms part of the URI for every service call.
     * @param options The parameter options
     */
    constructor(credentials: coreAuth.TokenCredential, subscriptionId: string, options?: TrafficManagerManagementClientOptionalParams);
    endpoints: Endpoints;
    profiles: Profiles;
    geographicHierarchies: GeographicHierarchies;
    heatMap: HeatMap;
    trafficManagerUserMetricsKeys: TrafficManagerUserMetricsKeys;
}
</code></pre>
<p>I need to get the endpoints this way</p>
<pre class=""lang-js prettyprint-override""><code>TrafficManagerManagementClient client = new TrafficManagerManagementClient(...);
let profile = client.profiles.get(...);
let endpoints = profile.endpoints;
</code></pre>
<p>So, I'm trying to mock <code>TrafficManagerManagementClient</code> this way</p>
<pre class=""lang-js prettyprint-override""><code>import {TrafficManager} from &quot;../services/trafficemanager&quot;;

jest.mock(&quot;@azure/arm-trafficmanager&quot;, () =&gt; {
    const original = jest.requireActual(&quot;@azure/arm-trafficmanager&quot;);
    return {
        __esModule: true,
        ...original,
        TrafficManagerManagementClient: class {
            constructor() {
            }
        },
    }
});
</code></pre>
<p>Then I got stuck here.  The mocked <code>TrafficManagerManagementClient</code> does not need any parameters for its constructor, but the compiler gives error here.</p>
<p>Am I mocking it correctly?</p>
",https://stackoverflow.com/questions/74291681/how-to-do-azure-function-typescript-unit-testing,"['typescript', 'unit-testing', 'jestjs', 'ts-jest']",119,False,0,0
Unit Testing Functions without Return Value in Python,"<p>My final project in CS50 is a salary slip generator in pdf format. I got these functions with me but I don't know to test them.</p>
<ol>
<li><p>create_pdf() - function that opens my data file (.xlsx), iterates over its data, puts them into variables which will then be called by fpdf to put them into the pdf file. This function will generate as much pdf's depending on the number of data inside the data file.</p>
</li>
<li><p>merge_pdf() - function that merges all the previously generated pdf's into one pdf. This function I might try to check if it outputs the merged pdf or not but still not quite clear to me how to implement it.</p>
</li>
<li><p>get_print_date() - this function only I created just for the sake of adding extra functions to my project hoping that I can test it. It takes datetime.now() and returns the string value of the current date and time. But how can I assert also the return value if the return value changes over time?</p>
</li>
</ol>
",https://stackoverflow.com/questions/74136789/unit-testing-functions-without-return-value-in-python,"['python', 'unit-testing', 'pyfpdf']",47,True,0,1
React Hooks: Timeout occurred during unit testing waitForValueToChange,"<pre><code>export function useTimer(initValue: number, isProceed: boolean) {
  const [value, setter] = useState(initValue)

  useEffect(() =&gt; {
    setter(initValue)
    const interval = setInterval(() =&gt; {
      if (isProceed &amp;&amp; value &gt; 0) setter((c) =&gt; c - 1)
      else if (value &lt; 0) {
        clearInterval(interval)
      }
    }, 1000)
    return () =&gt; {
      clearInterval(interval)
    }
  }, [initValue, value, isProceed])

  return {
    seconds:
      value &gt; 0
        ? `${Math.floor(value / 60)}:${value % 60 &lt; 10 ? '0' : ''}${value % 60}`
        : '',
    resetTimer: () =&gt; setter(initValue),
  }
}

  test('InitialCountState &lt; 0', async () =&gt; {
    const { hydrate, result, waitForValueToChange } = renderHook(() =&gt;
      useTimer(InitialCountState, isStartTimer)
    )
    InitialCountState = -1
    isStartTimer = true

    hydrate()
    await waitForValueToChange(() =&gt; result.current.seconds)
    expect(result.current.seconds).toBe('')
  })
</code></pre>
<p>Timed out in waitForValueToChange after 1000ms.</p>
<p>Failed to resolve failure result during hooks test. It's said that it failed because it was over time, but I don't know how to solve it. Is there a good way?</p>
",https://stackoverflow.com/questions/72282986/react-hooks-timeout-occurred-during-unit-testing-waitforvaluetochange,"['javascript', 'reactjs', 'unit-testing', 'testing']",887,False,0,0
Mock the selector state ngrx unit testing jasmine,"<p>I am trying to mock the selector but it is not create a selector it's a state
here is the ex.</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>export const InformationState = {
  systemType: string;
}

export const selectSystemType = (state: information) =&gt; state.systemType</code></pre>
</div>
</div>
</p>
<p>Trying to mock the above selector in the ts component file as shown the below
Component 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>this.store$.select(selectSystemType).subscribe(type =&gt; {
  const data = type;
})</code></pre>
</div>
</div>
</p>
<p>how to mock the above state in the component.spec.ts file?
Here is what I am trying to do</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>let store: MockStore;
let mockStore: MockStore &lt; InformationState &gt; ;
let selectAyatemType: MemoizedSelector &lt; any, string &gt; ;

beforeEach(async() =&gt; {
  wait TestBed.configurationModule({
    declartions: [component],
    providers: [provideMockStore({
      initialState
    })]
  }).compileComponents();
})
beforeEach(async() =&gt; {
  fixture = TestBed.createComponent(component);
  component = fixture.componentInstance;
  store = TestBed.inject(MockStore);
  mockStore = TestBed.inject(MockStore);
  selectSystemTypeMock = mockoverrideselector(selectSystemTye, """")
})</code></pre>
</div>
</div>
</p>
<p>getting error at this line selectSystemTypeMock = mockoverrideselector(selectSystemTye, &quot;&quot;)<br />
<a href=""https://i.stack.imgur.com/kH9iB.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/kH9iB.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/74545841/mock-the-selector-state-ngrx-unit-testing-jasmine,"['angular', 'karma-jasmine']",45,False,0,0
Unit testing .Net core 6 with injected logger,"<p>I am in the process of wrapping NLog and writing up some unit tests to check that NLog is registered as a service within the <code>ILoggingBuilder</code>. I register NLog using their extension method which extends the <code>ILoggingBuilder</code>:</p>
<pre><code>ILoggingBuilder Builder
Builder.AddNLog(config);
</code></pre>
<p>Obviously because this is a static extension method I can't test mock this and verify it's been called so I've resigned myself to the fact that I will need to test around it to assert that NLog has been registered as a logging service provider.</p>
<p>This is where I'm stuck. So far I have mocked the <code>ILoggingBuilder</code> and setup a service collection:</p>
<pre><code>//Arrange
var mockLoggingBuilder = new Mock&lt;ILoggingBuilder&gt;();
var config = new MyLoggerConfiguration();
var factory = new NLogFactory(config, mockLoggingBuilder.Object);
var mockServiceCollection = new ServiceCollection();
mockLoggingBuilder.SetupGet(x =&gt; x.Services).Returns(mockServiceCollection);
mockLoggingBuilder.Setup(x =&gt; x.Services).Returns(mockServiceCollection);


//Act
factory.SetupProvider();

//Assert
var services = mockLoggingBuilder.Object.Services;
services.Count.Should().Be(1,
&quot;nlog should have been added as a logging service with the call of SetupProvider on the factory.&quot;);
var configuredServices = services.GetEnumerator();
configuredServices.MoveNext();
var currentService = configuredServices.Current;
</code></pre>
<p>But I now can't figure out how to assert that this service is of the nlogger type.</p>
<p>Anyone able to point me in the right direction?</p>
",https://stackoverflow.com/questions/71172967/unit-testing-net-core-6-with-injected-logger,"['c#', 'logging', 'dependency-injection', 'extension-methods', 'nlog']",586,False,0,0
How to Unit testing in CQRS Pattern C#,"<p>I need to know how to Unit testing in CQRS pattern. as a beginer i dont have much idea about that. I develope below Command and queries. I need to Test those</p>
<p>Here is my <strong>add student command</strong></p>
<pre><code> public record AddStudentCommand(Student student):IRequest&lt;Student&gt;;
</code></pre>
<p>Hear is my <strong>Add Studnet Hadler</strong></p>
<pre><code> public class AddStudentHandler : IRequestHandler&lt;AddStudentCommand, Student&gt;
{
    private readonly appDbContext _context;
    public AddStudentHandler(appDbContext context)
    {
        _context = context;
    }

    public async Task&lt;Student&gt; Handle(AddStudentCommand request, CancellationToken cancellationToken)
    {
        _context.students.Add(request.student);
        await _context.SaveChangesAsync();
        return request.student;
    }
}
</code></pre>
<p>This is <strong>Get All Student Query</strong></p>
<pre><code>public record GetAllStudentDataQuery : IRequest&lt;IEnumerable&lt;Student&gt;&gt;;
</code></pre>
<p>This is my <strong>Get All Student Handler</strong></p>
<pre><code>public class GetAllStudentHandler : IRequestHandler&lt;GetAllStudentDataQuery, IEnumerable&lt;Student&gt;&gt;
{
    private readonly appDbContext _context;
    public GetAllStudentHandler(appDbContext context)
    {
        _context = context;
    }

    public async Task&lt;IEnumerable&lt;Student&gt;&gt; Handle(GetAllStudentDataQuery request, CancellationToken cancellationToken)
    {
        return _context.students;
    }
}
</code></pre>
<p><strong>I need to Unit test these methods.</strong></p>
",https://stackoverflow.com/questions/74010676/how-to-unit-testing-in-cqrs-pattern-c,"['unit-testing', 'testing', 'asp.net-web-api', 'cqrs']",165,False,0,1
Next JS using cypress for functions unit testing,"<p>I noticed  in cypress documentation that we can use Cypress for testing components. But i did not find any info regarding using cypress to test simple javascript functions like:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>function isObjectLike(value) {
  return value != null &amp;&amp; typeof value == 'object' &amp;&amp; !Array.isArray(value);
}</code></pre>
</div>
</div>
</p>
<p>In my situation i am using cypress to test Nextjs application. I test my components with unit tests and also for integration tests. So all my tests are visual tests. <br> I want also to tests my utlis/helpers functions using unit tests. <br> Question: Could i do this with cypress or it is not designed for what i want to do?</p>
",https://stackoverflow.com/questions/71871040/next-js-using-cypress-for-functions-unit-testing,"['reactjs', 'cypress']",668,True,0,1
"Angular unit testing the localstorage, Error ts(7053)","<p>beforeEach (() =&gt; { ...</p>
<pre><code>   let store = {};
  const mockSessionStorage = {
  getItem: (key: string): string =&gt; key in store ? store[key] : null,
  setItem: (key: string, value: string) =&gt; store[key] = `${value}`,
  removeItem: (key: string) =&gt; delete store[key],
  clear: () =&gt; store = {}
};
...
</code></pre>
<p>and i get the Error Message The element implicitly has a type &quot;any&quot; because the expression of type &quot;string&quot; cannot be used for the index type &quot;{}&quot;.
No index signature with a parameter of type &quot;string&quot; was found for type &quot;{}&quot;.ts(7053)</p>
<p>Also I'm new to typscript and don't know if it's because of the error message or if I'm doing something else wrong I would be happy if someone could take a quick look.</p>
",https://stackoverflow.com/questions/70625361/angular-unit-testing-the-localstorage-error-ts7053,"['javascript', 'angular', 'unit-testing', 'karma-jasmine']",243,True,0,1
Angular Excluding external javascript library from unit testing,"<p>I am unit testing my component which uses a external javascript library, I am importing and initializing the libary in my component.ts All my test cases work fine if I comment the line <strong>aksService = aksServiceFactory(); (code below)</strong> but it gives a error <strong>TypeError: Cannot read properties of undefined (reading 'AKS')</strong> if i uncomment it. I tried importing the library in spec.ts file also but it gives same error.</p>
<p>I want to include this library in my component.spec.ts file so it doesnt give me this error or if there is a way can we exclude this file from unit test so it doesnt give this error.</p>
<p>component.ts file</p>
<pre><code>import { aksServiceFactory } from '../../services/gdl.service';
import { GlobalConstants } from '../../global-constants';


@Component({
  selector: 'app-page',
  templateUrl: './opt-page.component.html',
  styleUrls: ['./opt-page.component.scss']

})

export class OptPageComponent implements OnInit {

  //initialize aks Service

  aksService = aksServiceFactory();
</code></pre>
<p>aks.service.ts</p>
<pre><code>// aks.service.js

export const aksServiceFactory = () =&gt; {
    const aksQueue = window.cms.aks;
    const sendPageview = (pageId) =&gt; {
      aksQueue.push(['event:publish', ['page', 'pageinfo']]);
    };

    const sendEvent = (category, name, payload) =&gt; {
      aksQueue.push(['event:publish', [category, name, payload]]);
    };

    const enableDebugMode=()=&gt;{
      aksQueue.debug.enable();
    }

    return {
      enableDebugMode,
      sendPageview,
      sendEvent,
    };
  };
</code></pre>
",https://stackoverflow.com/questions/71985987/angular-excluding-external-javascript-library-from-unit-testing,"['angular', 'jasmine', 'karma-jasmine', 'karma-runner', 'angular-unit-test']",301,False,0,1
Unit testing retry in Spring Webflux with mocked response,"<p>During unit testing retry the response of the mock seems cached, or most probably I am doing something wrong.</p>
<p>I am trying to request something, if error happened then retry twice with delay of 1 second.</p>
<pre><code>  public Mono&lt;Object&gt; someMethod(String someParam) {
    return someInjectedService.doSomething(someParam)
        .doOnError(ex -&gt; System.out.println(ex + &quot;: &quot; + System.currentTimeMillis()))
        .retryWhen(Retry.fixedDelay(2, Duration.ofSeconds(1)).filter(ex -&gt; ex instanceof SomeCustomException))
        .doOnSuccess(result -&gt; doSomethingOnSuccess(result));
  }
</code></pre>
<p>My test:</p>
<pre><code>  @Test
  void testshouldRequestThrice_whenErrorOccurs() {
    // Given
    String someParam = &quot;testParam&quot;;
    when(someInjectedService.doSomething(someParam))
        .thenReturn(Mono.error(new SomeCustomException(&quot;SomeCustomException&quot;))) // 1st response
        .thenReturn(Mono.error(new SomeCustomException(&quot;SomeCustomException&quot;))) // 2nd response
        .thenReturn(Mono.just(&quot;SomeValidResponse&quot;)); // 3rd valid response

    // When
    var result = testService.someMethod(someParam).block();

    // Then
    // Initial request, followed by two retries
    verify(someInjectedService, times(3)).doSomething(someParam);
  }
</code></pre>
<p>here <code>someInjectedService</code> is a mock.
My plan was to return an exception twice, and on third request return valid response. But what I get is:</p>
<blockquote>
<p>org.mockito.exceptions.verification.TooFewActualInvocations:
someInjectedService.doSomething(&quot;testParam&quot;);</p>
</blockquote>
<blockquote>
<p>Wanted 3 times:
-&gt; at shouldRequestThrice_whenErrorOccurs(test.java:138)</p>
</blockquote>
<blockquote>
<p>But was 1 time:</p>
</blockquote>
<p>While I do see 3 prints from <code>.doOnError(ex -&gt; System.out.println(ex + &quot;: &quot; + System.currentTimeMillis()))</code> block, I feel like the actual request is sent only once.</p>
<p>Thank you in advance,</p>
",https://stackoverflow.com/questions/70770215/unit-testing-retry-in-spring-webflux-with-mocked-response,"['java', 'project-reactor', 'webflux', 'retrywhen']",2367,True,5,1
Unit Testing a method which contains a Using block,"<p>I have a already written (was written years ago) C# function, I have been asked to cover this method with Unit Tests.</p>
<pre><code>public string PlaceOrder(int requestId, string orderedby)
    {
        try
        {
            using (DatabaseContext dbContext = new DatabaseContext(&quot;myConnectionStringHere&quot;))
            {
                var req = dbContext.Orders.Where(row =&gt; row.id == requestId).FirstOrDefault();
                if (req == null)
                    return &quot;not found&quot;;
               
                req.status=&quot;A&quot;;
                dbContext.SaveChanges();
                return &quot;found&quot;;
            }
        }
        catch (Exception ex)
        {
            return &quot;error&quot;;
        }
    }
</code></pre>
<p>Now while Unit testing I need to make sure that it does not write anything to database, so I have to <code>MOQ</code> it.
How can I <code>MOQ</code>, it contains <code>Using</code> block.</p>
<p>I know architecture could have been better and design patterns should have been followed but I am not allowed to change the structure of the application as it is a legacy application.</p>
",https://stackoverflow.com/questions/71299193/unit-testing-a-method-which-contains-a-using-block,"['c#', 'unit-testing', 'nunit', 'moq']",480,True,4,2
how does unit testing works in django? (with coverage),"<p>i am finding it kinda confusing to do unit testing especially with fields that has blank=True attribute or unique=True</p>
<p>look at this for example:</p>
<pre class=""lang-py prettyprint-override""><code>class TagTest(TestCase):
    def create(self):
        tag = models.Tag.objects.create(name='test')
        return tag
    def test_get(self):
        tag = self.create()
        self.assertIsInstance(tag, models.Tag)
        self.assertEqual(tag.name, tag.__str__())
        self.assertEqual(len(tag.name),4)class TagTest(TestCase):
    def create(self):
        tag = models.Tag.objects.create(name='test')
        return tag
    def test_get(self):
        tag = self.create()
        self.assertIsInstance(tag, models.Tag)
        self.assertEqual(tag.name, tag.__str__())
        self.assertEqual(len(tag.name),4)
</code></pre>
<p>look at coverage for example, it is telling me i am not covering the test case at all</p>
<p><a href=""https://i.stack.imgur.com/BtmkD.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/BtmkD.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73263758/how-does-unit-testing-works-in-django-with-coverage,"['python', 'django', 'unit-testing', 'code-coverage']",49,False,3,1
Unit-testing function with isolates and compute in flutter,"<p>I'm trying to test a widget that receives and displays some data. This widget uses a controller. In the constructor I start receiving data, after which I execute the parser in a separate isolate. During the tests, the function passed to the compute is not executed until the end, and the widget state does not change. In fact, the structure of the widget looks a little more complicated, but I wrote smaller widget that saves my problem:</p>
<pre class=""lang-dart prettyprint-override""><code>import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:rxdart/rxdart.dart';

class TestObj {
  int id;
  String name;
  String number;

  TestObj(this.id, this.name, this.number);

  static List&lt;TestObj&gt; jsonListParser(String data) {
    List mapObjs = json.decode(data) as List;
    if (mapObjs.isEmpty) return [];

    List&lt;TestObj&gt; testObjs = [];

    for (final Map mapObj in mapObjs as List&lt;Map&gt;)
      testObjs.add(
        TestObj(
          mapObj['id'] as int,
          mapObj['name'] as String,
          mapObj['number'] as String,
        ),
      );

    return testObjs;
  }
}

class TestController {
  final BehaviorSubject&lt;List&lt;TestObj&gt;&gt; testSubj;
  final String responseBody =
      '[{&quot;id&quot;:2,&quot;number&quot;:&quot;1&quot;,&quot;name&quot;:&quot;Объект 1&quot;},{&quot;id&quot;:1,&quot;number&quot;:&quot;2&quot;,&quot;name&quot;:&quot;Объект 2&quot;}]';

  TestController(this.testSubj) {
    getData(responseBody, testSubj);
  }

  Future&lt;void&gt; getData(
      String responseBody, BehaviorSubject&lt;List&lt;TestObj&gt;&gt; testSubj) async {
    List&lt;TestObj&gt; data = await compute(TestObj.jsonListParser, responseBody);
    testSubj.sink.add(data);
  }
}

class TestWidget extends StatelessWidget {
  final BehaviorSubject&lt;List&lt;TestObj&gt;&gt; testSubj;
  final TestController controller;

  const TestWidget(this.testSubj, this.controller);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder&lt;List&lt;TestObj&gt;&gt;(
      stream: testSubj.stream,
      builder: (context, snapshot) =&gt; snapshot.data == null
          ? const CircularProgressIndicator()
          : ListView.builder(
              itemBuilder: (context, index) =&gt; Text(snapshot.data[index].name),
            ),
    );
  }
}

void main() {
  testWidgets('example test', (tester) async {
    final BehaviorSubject&lt;List&lt;TestObj&gt;&gt; testSubj =
        BehaviorSubject.seeded(null);
    final TestController testController = TestController(testSubj);

    await tester.pumpWidget(
      TestWidget(testSubj, testController),
    );

    expect(find.byType(CircularProgressIndicator), findsNothing);
  });
}
</code></pre>
<p>I have tried using tester.pump, tester.pumpAndSettle (crashed by timeout) and tester.runAsync, but so far without success. What are the solutions of this problem?</p>
",https://stackoverflow.com/questions/72393843/unit-testing-function-with-isolates-and-compute-in-flutter,"['flutter', 'unit-testing', 'dart', 'dart-isolates']",325,False,2,1
Negative scenario creating conflict with positive angular unit testing,"<p>I've written the test case for services where I'm testing Negative and positive scenarios both but giving me errors for the negative scenario.
I've written in order first I'm checking the negative scenario and then the positive one.</p>
<p><em><strong>Configuration :</strong></em></p>
<pre><code>describe('CartItemProductService', () =&gt; {
let service: CartItemProductService;
const apiServiceSpy = jasmine.createSpyObj&lt;ApiService&gt;('ApiService', ['refreshToken', 'get', 'post', 'patch', 'delete']);
apiServiceSpy.refreshToken.and.returnValue(of(null));
const priceListServiceSpy = jasmine.createSpyObj&lt;PriceListService&gt;('PriceListService', ['isPricelistId']);

beforeEach(() =&gt; {
    TestBed.configureTestingModule({
        imports: [HttpClientTestingModule, ApttusModule, CommerceModule.forRoot({}), TranslateModule.forRoot()],
        providers: [
            CartItemProductService,
            { provide: ApiService, useValue: apiServiceSpy },
            { provide: PriceListService, useValue: priceListServiceSpy },
        ],
    });
    service = TestBed.inject(CartItemProductService);
});
</code></pre>
<p><em><strong>Negative Scenario :</strong></em></p>
<pre><code>    it('should return given Cart Line Item itself with no product info', () =&gt; {
    const results = service.addProductInfoToLineItems([CART_ITEMS_WITH_NO_PRODUCT_INFO[0]]);
    results.pipe(take(1)).subscribe((val) =&gt; {
        expect(apiServiceSpy.get).toHaveBeenCalledTimes(0);
        expect(val[0]).toEqual(CART_ITEMS_WITH_NO_PRODUCT_INFO[0]);
        expect(val[0].Product).toEqual(null);
    })
});
</code></pre>
<p><em><strong>Positive Scenario :</strong></em></p>
<pre><code>    it('should return additional info for the given cart line items', () =&gt; {
    priceListServiceSpy.isPricelistId.and.returnValue(true);
    apiServiceSpy.get.and.returnValue(of(PRODUCT_WITH_ADDITIONAL_INFO));
    const results = service.addProductInfoToLineItems([CART_ITEMS[2]]);
    results.pipe(take(1)).subscribe((val) =&gt; {
        expect(priceListServiceSpy.isPricelistId).toHaveBeenCalledTimes(1);
        expect(apiServiceSpy.get).toHaveBeenCalledTimes(1);
        expect(val[0].Product.Id).toEqual(CART_ITEMS[2].Product.Id);
        expect(val[0].Product.ProductCode).not.toEqual(null);
    });
});
</code></pre>
<p><strong>Error :</strong></p>
<p><a href=""https://i.stack.imgur.com/6laxQ.png"" rel=""nofollow noreferrer"">Image</a></p>
",https://stackoverflow.com/questions/73943518/negative-scenario-creating-conflict-with-positive-angular-unit-testing,"['angular', 'karma-jasmine', 'angular-unit-test']",103,False,2,0
Django unit testing - authenticated user check in model method,"<p>I am using Django 3.2</p>
<p>I am trying to test a model that checks if a user is authenticated. The model code looks something like this:</p>
<pre><code>class Foo(Model):
    def do_something(user, **kwargs):
        if user.is_authenticated():
            do_one_thing(user, **kwargs)
        else:
            do_another_thing(**kwargs)
</code></pre>
<p>My test code looks something like this:</p>
<pre><code>from model_bakery import baker
from django.contrib.auth import authenticate, get_user_model

User = get_user_model()


class FooModelTest(TestCase):
    def setUp(self):

        self.user1 = baker.make(User, username='testuser_1', password='testexample1', email='user1@example.com', is_active = True, is_superuser=False) 
        baker.make(User, username='testuser_2', password='testexample2', email='admin@example.com', is_active = True, is_superuser=True)         
        self.unauthorised_user = authenticate(username='testuser_2', password='wrongone')

       
    def test_user(self):
        self.assertTrue(self.user1.is_validated)  # why is this true? - I haven't &quot;logged in&quot; yet?
        self.assertFalse(self.unauthorised.is_validated) # Barfs here since authenticate returned a None
</code></pre>
<p>So, How am I to mock an unauthenticated user, for testing purposes? - since it appears that the <code>is_authenticated</code> property is read only?</p>
<p><strong>[[ Update ]]</strong></p>
<p>I've just done a little more research + testing, and it looks like the solution to this would be to use <code>AnnonymousUser</code> as follows:</p>
<pre><code>from django.contrib.auth.models import AnonymousUser

self.unaunthorised_user = AnonymousUser()
</code></pre>
<p>I am waiting to see if someone can confirm this (preferably, with a link to documentation)</p>
",https://stackoverflow.com/questions/73567611/django-unit-testing-authenticated-user-check-in-model-method,"['django', 'unit-testing', 'django-testing']",198,False,2,0
Spring Boot Unit testing with request scope bean dependency,"<p>I'm trying to run Unit tests on a service class that has an auto wired dependency which is <strong>request scoped</strong>. When running the unit test, it seems like spring container is unable to find the bean to auto wire into the service class. What should I do to fix this?</p>
<p><strong>Application.java</strong></p>
<pre><code>@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}
</code></pre>
<p><strong>AppConfig.java</strong></p>
<pre><code>@Configuration
public class AppConfig {

    @Bean
    @Scope(&quot;request&quot;)
    public ClassA classA(){
        return new ClassA();
    }
}
</code></pre>
<p><strong>ServiceA.java</strong></p>
<pre><code>@Service
public class ServiceA {

    @Autowired
    private ClassA classA;

    public void doSomething(){
        String value = classA.getValue();
        System.out.println(value);
    }
}
</code></pre>
<p>ServiceTest.java</p>
<pre><code>@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ServiceATest {

    @Test
    void contextLoads() {
    }

}
</code></pre>
<p><strong>Error message</strong></p>
<blockquote>
<p>org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'serviceA': Unsatisfied dependency
expressed through field 'classA'; nested exception is
org.springframework.beans.factory.support.ScopeNotActiveException:
Error creating bean with name 'classA': Scope 'request' is not active
for the current thread; consider defining a scoped proxy for this bean
if you intend to refer to it from a singleton; nested exception is
java.lang.IllegalStateException: No thread-bound request found: Are
you referring to request attributes outside of an actual web request,
or processing a request outside of the originally receiving thread? If
you are actually operating within a web request and still receive this
message, your code is probably running outside of DispatcherServlet:
In this case, use RequestContextListener or RequestContextFilter to
expose the current request.</p>
</blockquote>
",https://stackoverflow.com/questions/73661404/spring-boot-unit-testing-with-request-scope-bean-dependency,"['spring-boot', 'spring-boot-test']",160,False,2,0
Gitlab ci with unit testing that connects to MySQL,"<p>I have built a Golang project, I want to deploy the app when successfully tested with GitLab ci, but when do some tests, it fails because cannot connect to MySQL.
I want to use the Golang image and MySQL image in one stage.
This is my current pipeline. On stage test, on before script fails (/bin/bash: line 130: mysql: command not found)</p>
<pre><code># To contribute improvements to CI/CD templates, please follow the Development guide 

at:
# https://docs.gitlab.com/ee/development/cicd/templates.html
# This specific template is located at:
# https://gitlab.com/gitlab-org/gitlab/-/blob/master/lib/gitlab/ci/templates/Go.gitlab-ci.yml

image: golang:latest

services:
  - mysql:latest

stages:
  - test
  - build
  - deploy

variables:
  MYSQL_DATABASE: &quot;db&quot;
  MYSQL_USER: &quot;user&quot;
  MYSQL_PASSWORD: &quot;password&quot;
  MYSQL_ROOT_PASSWORD: &quot;password&quot;

format:
  stage: test
  variables:
    # Configure mysql environment variables (https://hub.docker.com/_/mysql/)
    MYSQL_DATABASE: $MYSQL_DATABASE
    MYSQL_PASSWORD: $MYSQL_PASSWORD
    MYSQL_ROOT_PASSWORD: $MYSQL_ROOT_PASSWORD
  services:
    - mysql:latest
  before_script:
    - mysql --version

  script:
    - go fmt $(go list ./... | grep -v /vendor/)
    - go vet $(go list ./... | grep -v /vendor/)
    - go test -race $(go list ./... | grep -v /vendor/)

compile:
  stage: build
  script:
    - mkdir -p typing
    - go build -o typing ./...
  artifacts:
    paths:
      - typing

deploy:
  image: google/cloud-sdk:alpine
  stage: deploy
  allow_failure: true
  script:
    - &quot;which ssh-agent || ( apt-get update -y &amp;&amp; apt-get install openssh-client -y )&quot;
    # Run ssh-agent (inside the build environment)
    - eval $(ssh-agent -s)
    # Add the SSH key stored in SSH_PRIVATE_KEY variable to the agent store
    - ssh-add &lt;(echo &quot;$SSH_PRIVATE_KEY&quot; | base64 -d)
    - mkdir -p ~/.ssh
    - '[[ -f /.dockerenv ]] &amp;&amp; echo -e &quot;Host *\n\tStrictHostKeyChecking no\n\n&quot; &gt; ~/.ssh/config'
    - (echo &quot;$SSH_PRIVATE_KEY&quot; | base64 -d) &gt; file
    - echo &quot;$SSH_PUBLIC_KEY&quot; &gt; file.pub
    - chmod 600 file
    - echo $SERVICE_ACCOUNT &gt; file.json
    - gcloud auth activate-service-account --key-file file.json
    - gcloud compute scp typing/* --project=&quot;project-id&quot; --zone=&quot;zone&quot;  vm-name:/home/ubuntu
    - ssh -i file ubuntu@public-ip 'sudo ./kill.sh; sudo ./start.sh'
  artifacts:
    paths:
      - typing
</code></pre>
<p>How can I achieve that?</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/72313322/gitlab-ci-with-unit-testing-that-connects-to-mysql,"['go', 'gitlab', 'gitlab-ci.yml']",516,True,2,1
Unit testing callable firebase function with App Check enabled,"<p>I am trying to unit test my firebase callable cloud function according to the examples provided. See <a href=""https://github.com/firebase/quickstart-testing/tree/master/unit-test-cloud-functions"" rel=""nofollow noreferrer"">Firebase Example</a>. It boils down to something like this</p>
<pre><code>const { expect } = require(&quot;chai&quot;);
const admin = require(&quot;firebase-admin&quot;);

const test = require(&quot;firebase-functions-test&quot;)({
    projectId: &quot;MYPROJECTID&quot;,
});

// Import the exported function definitions from our functions/index.js file
const myFunctions = require(&quot;../lib/test&quot;);
describe(&quot;Unit tests&quot;, () =&gt; {
  
  after(() =&gt; {
    test.cleanup();
  });

  it(&quot;tests a simple callable function&quot;, async () =&gt; {
    const wrapped = test.wrap(myFunctions.sayHelloWorld);

    const data = {
      eventName: &quot;New event&quot;
    };

    // Call the wrapped function with data and context
    const result = await wrapped(data);

    // Check that the result looks like we expected.
    expect(result).to.eql({
      c: 3,
    });
  });

});
</code></pre>
<p>The problem is that the function is protected by App Check in such a manner that if I try to test it, it always fails the App Check test:</p>
<pre><code>export const sayHelloWorld = functions.https.onCall(async (data, context) =&gt; {

    // context.app will be undefined if the request doesn't include a valid
    // App Check token.
    if (context.app === undefined) {
        throw new functions.https.HttpsError(
            'failed-precondition',
            'The function must be called from an App Check verified app.')
    }

</code></pre>
<p>How do I include a debug App Check Token, so that I can test the function?
For setting up AppCheck on iOS I followed this guid <a href=""https://firebase.google.com/docs/app-check/ios/app-attest-provider"" rel=""nofollow noreferrer"">Enable App Check with App Attest on Apple platforms</a>. When it comes to enforce AppCheck on cloud functions I followed these steps mentioned here. <a href=""https://firebase.google.com/docs/app-check/cloud-functions"" rel=""nofollow noreferrer"">Enable App Check enforcement for Cloud Functions</a>.</p>
",https://stackoverflow.com/questions/71679406/unit-testing-callable-firebase-function-with-app-check-enabled,"['node.js', 'firebase', 'unit-testing', 'google-cloud-functions', 'firebase-app-check']",466,True,2,1
unit testing controller action with call multi Mediator.Send command,"<p>I have a controller action that use multi mediator, but I don't know to how can I write unit test for this action. help me please</p>
<pre><code>var userObject = await _mediator.Send(new CreateUserCommand(contract),                
            cancellationToken);
var productObject = await _mediator.Send(new CreateProductCommand(contract), 
           cancellationToken);
var userProductObject = await _mediator.Send(new GetUserProductQuery(contract), 
           cancellationToken);

</code></pre>
",https://stackoverflow.com/questions/70786857/unit-testing-controller-action-with-call-multi-mediator-send-command,"['c#', 'unit-testing', 'asp.net-core', 'integration-testing', 'mediator']",400,False,1,0
Unit testing function embedded within another function in Scala,"<p>I was wondering if there is a way to test a function embedded within another function in Scala? Or the only to test it is to lift it as a top level function??</p>
<pre class=""lang-scala prettyprint-override""><code>  def processNumbers(n: Int): Int = {
    def isEven(num: Int): Boolean = num % 2 == 0
    if (isEven(n)) 0 else -1
  }
</code></pre>
<p>For example, in the code snippet above I would like to be able to unit test <code>isEven</code> without having to make it the top level function.</p>
<p>By &quot;top-level&quot;, I meant writing it at the same level as the &quot;parent&quot; function. In this case it would look like:</p>
<pre class=""lang-scala prettyprint-override""><code>  def isEven(num: Int): Boolean   = num % 2 == 0
  def processNumbers(n: Int): Int = if (isEven(n)) 0 else -1
</code></pre>
",https://stackoverflow.com/questions/74602093/unit-testing-function-embedded-within-another-function-in-scala,"['scala', 'unit-testing']",38,True,1,2
Is there a mock MQTT-Broker for unit testing?,"<p>I'm currently working on a module written in python.
In this module, a <code>paho.mqtt.client.Client</code> is created, connected to a broker and a few messages are published on a given topic.</p>
<p>Is there an easy way to unit-test this and so to say 'mock' the broker, so that I can verify, that the messages sent were correctly transmitted?</p>
<p>I was looking into this topic a bit but couldn't really find a satisfying solution:</p>
<ol>
<li>The answers on <a href=""https://stackoverflow.com/questions/59899733/mqtt-broker-for-testing"">MQTT broker for testing</a> suggest to either use some online tool, which I guess will not satisfy my need to make any assertions, or alternatively install and run some extra software, which has the same problem and possibly is difficult to share in the team or use on the CI-system.</li>
<li><a href=""https://github.com/eclipse/paho.mqtt.testing/tree/master/interoperability"" rel=""nofollow noreferrer"">https://github.com/eclipse/paho.mqtt.testing/tree/master/interoperability</a> Similar as above. Has to be run in an extra process.</li>
<li><a href=""https://github.com/eclipse/paho.mqtt.python/blob/master/tests/testsupport/broker.py"" rel=""nofollow noreferrer"">https://github.com/eclipse/paho.mqtt.python/blob/master/tests/testsupport/broker.py</a> This is paho's own solution. This looks the most promising and there I can find inspiration of how to use it in <a href=""https://github.com/eclipse/paho.mqtt.python/blob/master/tests/test_client.py"" rel=""nofollow noreferrer"">https://github.com/eclipse/paho.mqtt.python/blob/master/tests/test_client.py</a> . The problem is only, that this is not part of any of the packages I can install in my environment and I really don't want to copy that source.</li>
</ol>
<p>I would really appreciate some suggestions on how to unit test my MQTT-client without needing to set up a real broker. Thank you.</p>
",https://stackoverflow.com/questions/73985389/is-there-a-mock-mqtt-broker-for-unit-testing,"['python', 'pytest', 'paho']",1428,True,1,1
unit testing controller action with call multi Mediator.Send command,"<p>I have a controller action that use multi mediator, but I don't know to how can I write unit test for this action. help me please</p>
<pre><code>var userObject = await _mediator.Send(new CreateUserCommand(contract),                
            cancellationToken);
var productObject = await _mediator.Send(new CreateProductCommand(contract), 
           cancellationToken);
var userProductObject = await _mediator.Send(new GetUserProductQuery(contract), 
           cancellationToken);

</code></pre>
",https://stackoverflow.com/questions/70786857/unit-testing-controller-action-with-call-multi-mediator-send-command,"['c#', 'unit-testing', 'asp.net-core', 'integration-testing', 'mediator']",400,False,1,0
Unit testing function embedded within another function in Scala,"<p>I was wondering if there is a way to test a function embedded within another function in Scala? Or the only to test it is to lift it as a top level function??</p>
<pre class=""lang-scala prettyprint-override""><code>  def processNumbers(n: Int): Int = {
    def isEven(num: Int): Boolean = num % 2 == 0
    if (isEven(n)) 0 else -1
  }
</code></pre>
<p>For example, in the code snippet above I would like to be able to unit test <code>isEven</code> without having to make it the top level function.</p>
<p>By &quot;top-level&quot;, I meant writing it at the same level as the &quot;parent&quot; function. In this case it would look like:</p>
<pre class=""lang-scala prettyprint-override""><code>  def isEven(num: Int): Boolean   = num % 2 == 0
  def processNumbers(n: Int): Int = if (isEven(n)) 0 else -1
</code></pre>
",https://stackoverflow.com/questions/74602093/unit-testing-function-embedded-within-another-function-in-scala,"['scala', 'unit-testing']",38,True,1,2
NestJS unit testing of service involving transactional Entity Manager,"<pre><code>I have a create function on service like this on service.service.ts file

import { Service } from './entity/service.entity';
import { EntityManager } from 'typeorm';


async create(
  transactionalEntityManager: EntityManager,
  data: any
): Promise&lt;Service&gt; {
  return transactionalEntityManager.save(Service, data);
}
</code></pre>
<pre><code>And a POST route like this on service.controller.ts 

import { EntityManager, getConnection } from 'typeorm';
import { Service } from './entity/service.entity';


@Post()
async createService(
  @Body() body: ServiceDto,
  const user = { user_id: 1, company_id: 2 }
): Promise&lt;Service&gt; {
  return getConnection().transaction(async (t: EntityManager) =&gt;
    this.service.create(t, {
      ...body,
      company_id: user.company_id,
      added_by: user.user_id,
    })
  );
}


</code></pre>
<p>I need to write unit testing for the create function on service.service.ts.
How can i write unit testing for this function?
I got stuck on transaction.</p>
<p>I tried this <a href=""https://github.com/typeorm/typeorm/issues/2586"" rel=""nofollow noreferrer"">https://github.com/typeorm/typeorm/issues/2586</a>
But none of this worked for me.</p>
",https://stackoverflow.com/questions/74298475/nestjs-unit-testing-of-service-involving-transactional-entity-manager,"['unit-testing', 'jestjs', 'transactions', 'nestjs', 'typeorm']",76,False,1,0
Mockito or Embedded Mongo for unit testing spring mongorepository,"<p>Hi I am new to Spring Mongo testing. I know that using embedded db like flapdoodle ,fongo,mongo-java-server we can unit test the mongorepository.
But is the same possible using mockito?
If yes then which is better</p>
",https://stackoverflow.com/questions/73615461/mockito-or-embedded-mongo-for-unit-testing-spring-mongorepository,"['java', 'spring', 'junit', 'mockito', 'spring-data-mongodb']",359,True,1,1
Unit testing a method that calls other methods Jest,"<p>I was thinkig a lot on WHAT to test in a method that works like an &quot;orchestrator&quot; and it's only job is to calls functions. So I have this BattleInteractor class</p>
<pre><code>class BattleInteractor {
    constructor(opts) {
        this.battleRepository = opts.battleRepository
        this.battleEntity = opts.battleEntity
        this.battleWinner = opts.battleWinner
        this.typeFactoryService = opts.typeFactory
    }
    
    async execute(pokemonOne, pokemonTwo) {

        const battleResult = this.battle(pokemonOne, pokemonTwo)
        return battleResult
    }

    battle(pokemonOne, pokemonTwo) {
        const strategy = this.typeFactoryService.getStrategy(pokemonOne, pokemonTwo)
        const pokemonsSetted = strategy.setStats(pokemonOne, pokemonTwo)
        const battleResult = this.battleEntity.battleLogic(pokemonsSetted)
        return this.battleWinner.battleWinner(battleResult)
    }

}

module.exports = BattleInteractor
</code></pre>
<p>And the test file with all methods mocked:</p>
<pre><code>const BattleInteractor = require('../../../../src/application/useCases/battle/battleInteractor')
describe('BattleInteractor test', () =&gt; {

    const pokemonOneMock = 'mock'
    const pokemonTwoMock = 'mock'
    const battleWinnerMock = 'mock'

    class TypeMock {
        setStats() {
            return 'mockStats'
        }
    }

    const battleInteractor = new BattleInteractor({
        battleRepository: {
            savedDatabase: () =&gt; true
        },
        typeFactory: {
            getStrategy: () =&gt; {
                return new TypeMock()
            },
        },
        battleEntity: {
            battleLogic: () =&gt; {
                return &quot;battleLogicMock&quot;
            }
        },
        battleWinner: {
            battleWinner: () =&gt; {
                return battleWinnerMock
            }
        },
    })


    test.only('Should return properties formatted', async () =&gt; {
        const res = await battleInteractor.execute(pokemonOneMock, pokemonTwoMock)
        expect(res.message).toBe(&quot;carnivine and naganadel have tied&quot;)
    })


})
</code></pre>
<p>All works fine, so I have some questions:
What should I test in a method like this?
Is this a unit testing or a integration testing?
How necessary is it to test a class/method like this?</p>
",https://stackoverflow.com/questions/72066525/unit-testing-a-method-that-calls-other-methods-jest,"['javascript', 'node.js', 'unit-testing', 'jestjs', 'integration-testing']",493,False,1,0
Unit testing the parametrized test programmatically with out Suite,"<p>I do have some parametrized test and i want to run the tests <strong>programmatically</strong> and not with <code>annotation processors</code> e.g <code>@Suite</code> <code>@RunWith(Suite.class) </code> , is there a way that i can access and invoke the test classes from other test classes ?</p>
<ul>
<li>Some test cases</li>
</ul>

<pre class=""lang-html prettyprint-override""><code>@SpringBootTest
class Test {

    @ParameterizedTest
    @ValueSource(strings = {&quot;first&quot;, &quot;second&quot;})
    public void example(String values) {
    ...
    }
    
   ...
}
</code></pre>
",https://stackoverflow.com/questions/71600770/unit-testing-the-parametrized-test-programmatically-with-out-suite,"['java', 'unit-testing']",62,True,1,2
Issue with unit testing a unzip method node/jest,"<p>I have a small function designed to unzip a file using 'unzipper' and extract to a given location.</p>
<p>when unit testing the function times out, for unit testing I am using jest.</p>
<p>see below code :</p>
<pre><code>    exports.unzipFile = async (folderPath) =&gt; {
    return new Promise((resolve, reject) =&gt; {
    fs.createReadStream(folderPath)
      .pipe(unzipper.Extract({ path: tmpPath+ path.parse(folderPath).name })).on('close', () =&gt; resolve()).on('error', (error) =&gt; reject(error))
    })
</code></pre>
<p>The function itself works as expected. I have tried some changes to the function but this seems to break the function. I need this function to execute fully as the unzipped file is then relied on later in the program.</p>
<p>The program is written in node 16.
Any help would be appreciated thanks</p>
<p>EDIT: this is my current unit test- I have tried various things :</p>
<pre><code>const { PassThrough } = require('stream')
const os = require('os');
const unzipper = require(&quot;unzipper&quot;)
const fs = require(&quot;fs&quot;)

let tmpdir, mockReadStream
    
beforeEach(() =&gt; {

tmpdir = os.tmpdir() + &quot;/uploadFolder/&quot;;
 if (!fs.existsSync(tmpdir)){
     fs.mkdirSync(tmpdir);
 }
 fs.writeFileSync(tmpdir+&quot;tempfile.zip&quot;, &quot;file to be used&quot;)

mockReadStream = new PassThrough()
})
afterEach(() =&gt; {
  // Restore mocks
  jest.clearAllMocks()

})

describe('Test helper.js unzip method', () =&gt; {
  test('should be able to unzip file  ', async () =&gt; {


         jest.isolateModules(() =&gt; {
             helper = require('helper')
         })

     const result = await helper.unzipFile(tmpdir+&quot;tempfile.zip&quot;)
    console.log(result)
  })
})
</code></pre>
",https://stackoverflow.com/questions/73991213/issue-with-unit-testing-a-unzip-method-node-jest,"['node.js', 'unit-testing', 'jestjs', 'node-modules', 'nodejs-stream']",223,True,1,1
[Jest Unit Testing]: TypeError: component.setState is not a function,"<p>We are using Jest for Unit Testing. We have a common file that contains the common OnChange() function definition. While writing unit test case for OnChange, it's throwing below error:</p>
<p><a href=""https://i.stack.imgur.com/fGlcu.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fGlcu.png"" alt=""enter image description here"" /></a></p>
<p>e.g.</p>
<p><strong>CommonFunctions.tsx</strong></p>
<pre><code>export const OnChange = (component: any, property: any, event: any) =&gt; {
  property[event.target.name] = event.target.value;
  component.setState({
    ...component.state,
  });
};
</code></pre>
<p><strong>Calling for OnChange from a class Component:</strong></p>
<pre><code>this.onChangeHandler = (event: any) =&gt; OnChange(this, this.state, event);
</code></pre>
<p><strong>Jest Unit Test Case for OnChange: CommonFunctions.test.tsx</strong></p>
<pre><code>test('should call function &quot;OnChange&quot;', () =&gt; {
const property = {
  name: 'test',
};
const component = jest.fn();
const event = {
    preventDefault() {},
    target: { name: 'name', value: 'the-value' }
  };
expect(OnChange(component,property,event)).toBeCalledWith('the-value');
</code></pre>
<p>});</p>
<p>Please suggest a better or newer approach for this use case.</p>
<p><strong>Versions:</strong>
&quot;react&quot;: &quot;^18.1.0&quot;,
&quot;react-dom&quot;: &quot;^18.1.0&quot;,
&quot;jest&quot;: &quot;^29.0.3&quot;,</p>
",https://stackoverflow.com/questions/73816128/jest-unit-testing-typeerror-component-setstate-is-not-a-function,"['reactjs', 'unit-testing', 'jestjs', 'ts-jest', 'babel-jest']",924,True,1,1
Unit testing with jest multiple fails but one pass?,"<p>I am just trying to do a simple test to extract a json form a collections call and I am getting weird errors that make no sense. Like all of my tests fail except one meaning it went through? Here is my test:</p>
<pre><code>const base64Image = &quot;BASE_64_IMAGE&quot;;
const imageBuffer = new Buffer(base64Image, &quot;base64&quot;); //1 of them passed? I am confused
var imgfile = fs.readFileSync('./tests/testImages/crystal.png', imageBuffer);

describe(&quot;POST /collections&quot;, () =&gt; {
  
/*
    test(&quot;should respond with a 200 status code&quot;, async () =&gt; {
      const response = await request(app).post(&quot;/collections&quot;).send({
        myImage: imgfile
      })
      expect(response.statusCode).toBe(200)
    })
    */

    test(&quot;should Retrieve a Image&quot;, async () =&gt; { // it passed? 
      const response = await request(app).post(&quot;/retrievImageJson&quot;).send({
        _id: &quot;626702aa313718fb12cc11b6&quot;

      })
      expect(response.headers['content-type']).toEqual(expect.stringContaining(&quot;json&quot;))
    })

})
</code></pre>
<p>here is the route I am testing:</p>
<pre><code>router.post(&quot;/retrievImageJSON&quot;, requireLogin, async (req, res) =&gt; { 
    User.findOne({_id: req.user}).select(&quot;collectionArray&quot;).then( result =&gt;{
        res.send(result)
        
    }
    ).catch((err) =&gt;{
        console.log(err);
    })

    
});
</code></pre>
<p>and here is the test failures (there is alot weirdly)</p>
<pre><code> FAIL  tests/uploadImages.test.js
  ● Test suite failed to run

    SyntaxError: C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend\tests\uploadImages.test.js: Unexpected token, expected &quot;,&quot; (34:0)

      32 |
      33 |
    &gt; 34 |
         | ^

      at instantiate (node_modules/@babel/parser/src/parse-error/credentials.js:61:22)
      at instantiate (node_modules/@babel/parser/src/parse-error.js:58:12)
      at Parser.toParseError [as raise] (node_modules/@babel/parser/src/tokenizer/index.js:1736:19)
      at Parser.raise [as unexpected] (node_modules/@babel/parser/src/tokenizer/index.js:1781:16)
      at Parser.unexpected [as expect] (node_modules/@babel/parser/src/parser/util.js:153:28)
      at Parser.expect [as parseCallExpressionArguments] (node_modules/@babel/parser/src/parser/expression.js:988:14)
      at Parser.parseCallExpressionArguments [as parseCoverCallAndAsyncArrowHead] (node_modules/@babel/parser/src/parser/expression.js:863:29)
      at Parser.parseCoverCallAndAsyncArrowHead [as parseSubscript] (node_modules/@babel/parser/src/parser/expression.js:748:19)
      at Parser.parseSubscripts [as parseExprSubscripts] (node_modules/@babel/parser/src/parser/expression.js:689:17)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.678 s
Ran all test suites.
npm ERR! code 1
npm ERR! path C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c &quot;jest&quot;

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\tquig\AppData\Local\npm-cache\_logs\2022-05-05T19_19_58_127Z-debug.log
PS C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend&gt; npm test

&gt; team2@1.0.0 test
&gt; jest

 FAIL  tests/uploadImages.test.js
  ● Test suite failed to run

    ReferenceError: Cannot access 'app' before initialization

      1 |
      2 | const supertest = require('supertest')
    &gt; 3 | const request = supertest(app)
        |                           ^
      4 | const fs = require('fs');
      5 | const path = require('path')
      6 | const app = require('../server/server.js')

      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:317:13)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        0.75 s
Ran all test suites.
npm ERR! code 1
npm ERR! path C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c &quot;jest&quot;

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\tquig\AppData\Local\npm-cache\_logs\2022-05-05T19_21_05_748Z-debug.log
PS C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend&gt; npm test

&gt; team2@1.0.0 test
&gt; jest


  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Listening on port 5000&quot;.



      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at Server.&lt;anonymous&gt; (server/server.js:60:11)

(node:1852) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 FAIL  tests/uploadImages.test.js
  POST /collections
    × should respond with a 200 status code (1 ms)

  ● POST /collections › should respond with a 200 status code

    TypeError: request is not a function

      20 |
      21 |     test(&quot;should respond with a 200 status code&quot;, async () =&gt; {
    &gt; 22 |       const response = await request(app).post(&quot;/collections&quot;).send({
         |                              ^
      23 |         myImage: imgfile
      24 |       })
      25 |       expect(response.statusCode).toBe(200)

      at Object.request (tests/uploadImages.test.js:22:30)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.448 s
Ran all test suites.

  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Successfully connected to MongoDB&quot;.

      32 | app.use(express.json());
      33 | app.use(cors({
    &gt; 34 |   origin: [&quot;http://localhost:3000&quot;],
         |           ^
      35 |   credentials: true,
      36 | }));
      37 | //app.use(passport.initialize());

      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at NativeConnection.&lt;anonymous&gt; (server/server.js:34:11)
      at NativeConnection.Object.&lt;anonymous&gt;.Connection.onOpen (node_modules/mongoose/lib/connection.js:647:8)
      at _setClient (node_modules/mongoose/lib/connection.js:895:8)
PS C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend&gt; npm test

&gt; team2@1.0.0 test
&gt; jest


  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Listening on port 5000&quot;.



      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at Server.&lt;anonymous&gt; (server/server.js:60:11)

(node:8208) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 FAIL  tests/uploadImages.test.js
  POST /collections
    × should respond with a 200 status code (1 ms)

  ● POST /collections › should respond with a 200 status code

    TypeError: request is not a function

      20 |
      21 |     test(&quot;should respond with a 200 status code&quot;, async () =&gt; {
    &gt; 22 |       const response = await request(app).post(&quot;/collections&quot;).send({
         |                              ^
      23 |         myImage: imgfile
      24 |       })
      25 |       expect(response.statusCode).toBe(200)

      at Object.request (tests/uploadImages.test.js:22:30)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.348 s, estimated 3 s
Ran all test suites.

  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Successfully connected to MongoDB&quot;.

      32 | app.use(express.json());
      33 | app.use(cors({
    &gt; 34 |   origin: [&quot;http://localhost:3000&quot;],
         |           ^
      35 |   credentials: true,
      36 | }));
      37 | //app.use(passport.initialize());

      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at NativeConnection.&lt;anonymous&gt; (server/server.js:34:11)
      at NativeConnection.Object.&lt;anonymous&gt;.Connection.onOpen (node_modules/mongoose/lib/connection.js:647:8)
      at _setClient (node_modules/mongoose/lib/connection.js:895:8)
      at node_modules/mongoose/lib/connection.js:801:7
      at node_modules/mongodb/src/utils.ts:624:5
      at node_modules/mongodb/src/mongo_client.ts:434:9

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
npm ERR! path C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend
npm ERR! signal SIGINT
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c &quot;jest&quot;

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\tquig\AppData\Local\npm-cache\_logs\2022-05-05T19_22_59_129Z-debug.log
Terminate batch job (Y/N)? y
PS C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend&gt; npm test

&gt; team2@1.0.0 test
&gt; jest


  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Listening on port 5000&quot;.



      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at Server.&lt;anonymous&gt; (server/server.js:60:11)

(node:228) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 FAIL  tests/uploadImages.test.js
  POST /collections
    × should respond with a 200 status code (1 ms)

  ● POST /collections › should respond with a 200 status code

    TypeError: request is not a function

      20 |
      21 |     test(&quot;should respond with a 200 status code&quot;, async () =&gt; {
    &gt; 22 |       const response = await request(app).post(&quot;/collections&quot;).send({
         |                              ^
      23 |         myImage: imgfile
      24 |       })
      25 |       expect(true).toBe(true)

      at Object.request (tests/uploadImages.test.js:22:30)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.376 s, estimated 3 s
Ran all test suites.

  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Successfully connected to MongoDB&quot;.

      32 | app.use(express.json());
      33 | app.use(cors({
    &gt; 34 |   origin: [&quot;http://localhost:3000&quot;],
         |           ^
      35 |   credentials: true,
      36 | }));
      37 | //app.use(passport.initialize());

      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at NativeConnection.&lt;anonymous&gt; (server/server.js:34:11)
      at NativeConnection.Object.&lt;anonymous&gt;.Connection.onOpen (node_modules/mongoose/lib/connection.js:647:8)
      at _setClient (node_modules/mongoose/lib/connection.js:895:8)
      at node_modules/mongoose/lib/connection.js:801:7
      at node_modules/mongodb/src/utils.ts:624:5
      at node_modules/mongodb/src/mongo_client.ts:434:9

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
npm ERR! command failed
npm ERR! signal SIGINT
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c &quot;jest&quot;

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\tquig\AppData\Local\npm-cache\_logs\2022-05-05T19_23_26_676Z-debug.log
Terminate batch job (Y/N)? y
PS C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend&gt; npm test

&gt; team2@1.0.0 test
&gt; jest


  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Listening on port 5000&quot;.



      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at Server.&lt;anonymous&gt; (server/server.js:60:11)

(node:3644) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 PASS  tests/uploadImages.test.js
  POST /collections
    √ should respond with a 200 status code (1 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.39 s, estimated 3 s
Ran all test suites.

  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Successfully connected to MongoDB&quot;.

      32 | app.use(express.json());
      33 | app.use(cors({
    &gt; 34 |   origin: [&quot;http://localhost:3000&quot;],
         |           ^
      35 |   credentials: true,
      36 | }));
      37 | //app.use(passport.initialize());

      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at NativeConnection.&lt;anonymous&gt; (server/server.js:34:11)
      at NativeConnection.Object.&lt;anonymous&gt;.Connection.onOpen (node_modules/mongoose/lib/connection.js:647:8)
      at _setClient (node_modules/mongoose/lib/connection.js:895:8)
      at node_modules/mongoose/lib/connection.js:801:7
      at node_modules/mongodb/src/utils.ts:624:5
      at node_modules/mongodb/src/mongo_client.ts:434:9

Jest did not exit one second after the test run has completed.

npm ERR! path C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend
npm ERR! command failed
npm ERR! signal SIGINT
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c &quot;jest&quot;

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\tquig\AppData\Local\npm-cache\_logs\2022-05-05T19_24_26_582Z-debug.log
Terminate batch job (Y/N)? y
PS C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend&gt; npm test

&gt; team2@1.0.0 test
&gt; jest


  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Listening on port 5000&quot;.



      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at Server.&lt;anonymous&gt; (server/server.js:60:11)

(node:18276) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 FAIL  tests/uploadImages.test.js
  POST /collections
    × should respond with a 200 status code (1 ms)

  ● POST /collections › should respond with a 200 status code

    TypeError: app.address is not a function

      20 |
      21 |     test(&quot;should respond with a 200 status code&quot;, async () =&gt; {
    &gt; 22 |       const response = await request(app).post(&quot;/collections&quot;).send({
         |                                           ^
      23 |         myImage: imgfile
      24 |       })
      25 |       expect(response.statusCode).toBe(200)

      at Test.serverAddress (node_modules/supertest/lib/test.js:46:22)
      at new Test (node_modules/supertest/lib/test.js:34:14)
      at Object.obj.&lt;computed&gt; [as post] (node_modules/supertest/index.js:28:14)
      at Object.post (tests/uploadImages.test.js:22:43)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.404 s, estimated 3 s
Ran all test suites.

  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Successfully connected to MongoDB&quot;.

      32 | app.use(express.json());
      33 | app.use(cors({
    &gt; 34 |   origin: [&quot;http://localhost:3000&quot;],
         |           ^
      35 |   credentials: true,
      36 | }));
      37 | //app.use(passport.initialize());

      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at NativeConnection.&lt;anonymous&gt; (server/server.js:34:11)
PS C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend&gt; npm test

&gt; team2@1.0.0 test
&gt; jest


  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Listening on port 5000&quot;.



      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at Server.&lt;anonymous&gt; (server/server.js:60:11)

(node:19700) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 FAIL  tests/uploadImages.test.js
  POST /collections
    × should respond with a 200 status code (2 ms)

  ● POST /collections › should respond with a 200 status code

    TypeError: app.address is not a function

      20 |
      21 |     test(&quot;should respond with a 200 status code&quot;, async () =&gt; {
    &gt; 22 |       const response = await request(app).post(&quot;/collections&quot;).send({
         |                                           ^
      23 |         myImage: imgfile
      24 |       })
      25 |       expect(response.statusCode).toBe(200)

      at Test.serverAddress (node_modules/supertest/lib/test.js:46:22)
      at new Test (node_modules/supertest/lib/test.js:34:14)
      at Object.obj.&lt;computed&gt; [as post] (node_modules/supertest/index.js:28:14)
      at Object.post (tests/uploadImages.test.js:22:43)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.248 s, estimated 3 s
Ran all test suites.

  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Successfully connected to MongoDB&quot;.

      32 | app.use(express.json());
      33 | app.use(cors({
    &gt; 34 |   origin: [&quot;http://localhost:3000&quot;],
         |           ^
      35 |   credentials: true,
      36 | }));
      37 | //app.use(passport.initialize());

      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at NativeConnection.&lt;anonymous&gt; (server/server.js:34:11)
      at NativeConnection.Object.&lt;anonymous&gt;.Connection.onOpen (node_modules/mongoose/lib/connection.js:647:8)
      at _setClient (node_modules/mongoose/lib/connection.js:895:8)
      at node_modules/mongoose/lib/connection.js:801:7
      at node_modules/mongodb/src/utils.ts:624:5
      at node_modules/mongodb/src/mongo_client.ts:434:9

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
npm ERR! path C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend
npm ERR! command failed
npm ERR! signal SIGINT
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c &quot;jest&quot;        

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\tquig\AppData\Local\npm-cache\_logs\2022-05-05T19_30_02_610Z-debug.log
Terminate batch job (Y/N)? y
PS C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend&gt; npm test

&gt; team2@1.0.0 test
&gt; jest


  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Listening on port 5000&quot;.



      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at Server.&lt;anonymous&gt; (server/server.js:60:11)

(node:14128) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 FAIL  tests/uploadImages.test.js
  POST /collections
    × should respond with a 200 status code (2 ms)

  ● POST /collections › should respond with a 200 status code

    TypeError: app.address is not a function

      20 |
      21 |     test(&quot;should respond with a 200 status code&quot;, async () =&gt; {
    &gt; 22 |       const response = await request(app).post(&quot;/collections&quot;).send({
         |                                           ^
      23 |         myImage: imgfile
      24 |       })
      25 |       expect(response.statusCode).toBe(200)

      at Test.serverAddress (node_modules/supertest/lib/test.js:46:22)
      at new Test (node_modules/supertest/lib/test.js:34:14)
      at Object.obj.&lt;computed&gt; [as post] (node_modules/supertest/index.js:28:14)
      at Object.post (tests/uploadImages.test.js:22:43)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.311 s, estimated 3 s
Ran all test suites.

  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Successfully connected to MongoDB&quot;.

      32 | app.use(express.json());
      33 | app.use(cors({
    &gt; 34 |   origin: [&quot;http://localhost:3000&quot;],
         |           ^
      35 |   credentials: true,
      36 | }));
      37 | //app.use(passport.initialize());

      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at NativeConnection.&lt;anonymous&gt; (server/server.js:34:11)
      at NativeConnection.Object.&lt;anonymous&gt;.Connection.onOpen (node_modules/mongoose/lib/connection.js:647:8)
      at _setClient (node_modules/mongoose/lib/connection.js:895:8)
      at node_modules/mongoose/lib/connection.js:801:7
      at node_modules/mongodb/src/utils.ts:624:5
      at node_modules/mongodb/src/mongo_client.ts:434:9

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with `--detectOpenHandles` to troubleshoot this issue.
npm ERR! path C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend
npm ERR! command failed
npm ERR! signal SIGINT
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c &quot;jest&quot;

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\tquig\AppData\Local\npm-cache\_logs\2022-05-05T19_36_48_633Z-debug.log
Terminate batch job (Y/N)? y
PS C:\Users\tquig\OneDrive\Documents\GitHub\Team2\backend&gt; npm test

&gt; team2@1.0.0 test
&gt; jest


  ●  Cannot log after tests are done. Did you forget to wait for something async in your test?
    Attempted to log &quot;Listening on port 5000&quot;.



      at console.log (node_modules/@jest/console/build/CustomConsole.js:172:10)
      at Server.&lt;anonymous&gt; (server/server.js:60:11)

(node:5212) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 FAIL  tests/uploadImages.test.js
  POST /collections
    × should Retrieve a Image (2 ms)

  ● POST /collections › should Retrieve a Image

    TypeError: app.address is not a function

      29 |
      30 |     test(&quot;should Retrieve a Image&quot;, async () =&gt; {
    &gt; 31 |       const response = await (await request(app).post(&quot;/retrievImageJson&quot;)).send({
         |                                                  ^
      32 |         _id: &quot;626702aa313718fb12cc11b6&quot;
      33 |
      34 |       })

      at Test.serverAddress (node_modules/supertest/lib/test.js:46:22)
      at new Test (node_modules/supertest/lib/test.js:34:14)
      at Object.obj.&lt;computed&gt; [as post] (node_modules/supertest/index.js:28:14)
      at Object.post (tests/uploadImages.test.js:31:50)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        2.376 s, estimated 3 s
Ran all test suites.
</code></pre>
<p>I am just trying to make sense of this. I am not sure where it failed because some of the failures are on code that is nonexistent. If anyone has an idea on what is going on that would be super helpful.</p>
",https://stackoverflow.com/questions/72132847/unit-testing-with-jest-multiple-fails-but-one-pass,['jestjs'],658,False,1,0
repoistory.save() getting invoked with invalid entry when unit testing,"<p>I'm using java validation API to validate fields in my Note class:</p>
<pre class=""lang-java prettyprint-override""><code>@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = &quot;note&quot;)
public class Note {

    @Id
    @Column(name = &quot;id&quot;, nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = &quot;date&quot;, columnDefinition = &quot;DATE&quot;)
    private LocalDate date;

    @NotBlank(message = &quot;Enter a topic&quot;)
    @Column(name = &quot;topic&quot;)
    private String topic;

    @NotBlank(message = &quot;Content can't be empty&quot;)
    @Column(name = &quot;content&quot;)
    private String content;

    @Column(name = &quot;type&quot;)
    private NoteType noteType;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name = &quot;user_id&quot;)
    @JsonIgnore
    private User user;
}
</code></pre>
<p>NoteService:</p>
<pre class=""lang-java prettyprint-override""><code>@Service
@AllArgsConstructor
public class NoteService {

    @Autowired
    private NoteRepository noteRepository;

    @Autowired
    private UserRepository userRepository;


    public void addNote(@Valid Note note) {
        note.setUser(getLoggedInUser());
        if (validateNote(note)) {
            noteRepository.save(note);
        }
    }

    public List&lt;Note&gt; getNotes() {
        return getLoggedInUser().getNotes();
    }

    public Note editNote(Note newNote, Long id) {
        noteRepository.editNoteById(newNote, id);
        return newNote;
    }

    public List&lt;Note&gt; getNotesByTopic(String topic) {
        List&lt;Note&gt; notes = noteRepository.getNotesByTopicAndUser(topic, getLoggedInUser());
        return notes;
    }

    public boolean validateNote(Note note) {
        return  validateNoteType(note.getNoteType())
                &amp;&amp; note.getDate() != null;
    }

    public boolean validateNoteType(NoteType type) {
        return type.equals(NoteType.NOTE)
                || type.equals(NoteType.SKILL);
    }

    public User getLoggedInUser() {
        return userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName());
    }
}
</code></pre>
<p>Test:</p>
<pre class=""lang-java prettyprint-override""><code>@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
class NoteServiceTest {

    @Mock
    private NoteRepository noteRepositoryMock;
    @Mock
    private UserRepository userRepositoryMock;
    @Mock
    SecurityContext mockSecurityContext;
    @Mock
    Authentication authentication;
    private NoteService noteService;

    @BeforeEach
    void setUp() {
        noteService = new NoteService(noteRepositoryMock, userRepositoryMock);
        Mockito.when(mockSecurityContext.getAuthentication()).thenReturn(authentication);
        SecurityContextHolder.setContext(mockSecurityContext);
    }

    @Test
    void shouldAddNote() {
        LocalDate date = LocalDate.now();
        Note note = new Note(0L, date, &quot;test&quot;, &quot;&quot;, NoteType.NOTE, null);
        noteService.addNote(note);
        Mockito.verify(noteRepositoryMock).save(note);
    }
}
</code></pre>
<p>The field user in the Note class is annotated with @NotNull and I'm passing a null user to this note but the note is still getting saved. Same thing when I pass an empty string. Any idea why that is happening? I'm new to unit testing</p>
",https://stackoverflow.com/questions/71233788/repoistory-save-getting-invoked-with-invalid-entry-when-unit-testing,"['java', 'unit-testing', 'validation', 'mockito']",220,False,1,3
Python Mock: raise 3rd party exception for unit testing,"<p>Let's say i have a method <code>is_validate</code>, which internally calls <code>validate</code> method from library <code>gateway.service</code></p>
<pre><code>import gateway.service
from gateway.service.exception import ValidatorException

def is_validate():
   try:
       gateway.service.validate() # which throws ValidatorException
       return True
   except ValidatorException ex:
       return False

</code></pre>
<p>How to unit test <code>is_validate</code> method, mocking <code>gateway.service.validate</code> to throw <code>ValidatorException</code> ?</p>
",https://stackoverflow.com/questions/71742041/python-mock-raise-3rd-party-exception-for-unit-testing,"['python', 'pytest', 'pymock']",720,True,1,2
Quarkus : How to disable/mock Vault for unit testing,"<p>I'm currently facing an issue with Quarkus and Vault.</p>
<p>When I launch JUnit tests, Vault trying to start and it failed because Vault configuration is not setup to run locally.</p>
<pre><code>Caused by: java.lang.RuntimeException: Failed to start quarkus
at io.quarkus.runner.ApplicationImpl.doStart(ApplicationImpl.zig:912)
at io.quarkus.runtime.Application.start(Application.java:101)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Caused by: java.lang.NullPointerException
at io.quarkus.vault.runtime.config.VaultConfigSource.getSecretConfig(VaultConfigSource.java:78)
at io.quarkus.vault.runtime.config.VaultConfigSource.getValue(VaultConfigSource.java:59)
</code></pre>
<p>My question is, is there a way to disable Vault during Junit tests on Quarkus like on SpringBoot (with property) ? Or create Vault Mock which can be used locally ?</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/72230483/quarkus-how-to-disable-mock-vault-for-unit-testing,"['junit', 'quarkus', 'vault']",226,False,1,1
Error when unit testing in ReactJS Missing library modules,"<p>I am writing a test website using ReactJs &amp; Node for a class and am having difficulties running tests.
I have tried reinstalling packages via npm install. Upgrading and downgrading to certain versions of &quot;testing-library&quot; but that leads to more failed tests ive tried installing npm i helpers/helper</p>
<p>This is my package.json</p>
<pre><code>{
  &quot;name&quot;: &quot;landingpage-react-template&quot;,
  &quot;private&quot;: true,
  &quot;dependencies&quot;: {
    &quot;@testing-library/react&quot;: &quot;^9.3.2&quot;,
    &quot;axios&quot;: &quot;^0.27.2&quot;,
    &quot;bcrypt&quot;: &quot;^5.0.1&quot;,
    &quot;bcryptjs&quot;: &quot;^2.4.3&quot;,
    &quot;cors&quot;: &quot;^2.8.5&quot;,
    &quot;database.js&quot;: &quot;^0.0.1&quot;,
    &quot;detect-file&quot;: &quot;^1.0.0&quot;,
    &quot;detect-libc&quot;: &quot;^2.0.1&quot;,
    &quot;emailjs-com&quot;: &quot;^2.6.4&quot;,
    &quot;express&quot;: &quot;^4.18.1&quot;,
    &quot;express-fileupload&quot;: &quot;^1.4.0&quot;,
    &quot;express-handlebars&quot;: &quot;^6.0.6&quot;,
    &quot;multer&quot;: &quot;^1.4.5-lts.1&quot;,
    &quot;mv&quot;: &quot;^2.1.1&quot;,
    &quot;mysql&quot;: &quot;^2.18.1&quot;,
    &quot;mysql2&quot;: &quot;^2.3.3&quot;,
    &quot;nodemailer&quot;: &quot;^6.8.0&quot;,
    &quot;react&quot;: &quot;^17.0.1&quot;,
    &quot;react-cookie&quot;: &quot;^4.1.1&quot;,
    &quot;react-dom&quot;: &quot;^17.0.1&quot;,
    &quot;react-router-dom&quot;: &quot;^6.3.0&quot;,
    &quot;react-scripts&quot;: &quot;^5.0.1&quot;,
    &quot;react-youtube&quot;: &quot;^9.0.1&quot;,
    &quot;sequelize&quot;: &quot;^6.23.2&quot;,
    &quot;sequelize-cli&quot;: &quot;^6.5.1&quot;,
    &quot;smooth-scroll&quot;: &quot;^16.1.3&quot;
  },
  &quot;scripts&quot;: {
    &quot;start&quot;: &quot;react-scripts start&quot;,
    &quot;build&quot;: &quot;react-scripts build&quot;,
    &quot;test&quot;: &quot;react-scripts test&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;
    ]
  },
  &quot;devDependencies&quot;: {
    &quot;@testing-library/jest-dom&quot;: &quot;^5.16.5&quot;,
    &quot;@testing-library/user-event&quot;: &quot;^14.4.3&quot;,
    &quot;@wojtekmaj/enzyme-adapter-react-17&quot;: &quot;^0.6.7&quot;,
    &quot;enzyme&quot;: &quot;^3.11.0&quot;
  }
}

</code></pre>
<p>And this is the error im getting after running npm test</p>
<pre><code> FAIL  src/pages/components/resetPasswordPage/resetPasswordComponent.test.jsx
  ● Test suite failed to run

    Cannot find module '@testing-library/dom/dist/helpers.js' from 'node_modules/@testing-library/user-event/dist/cjs/utils/misc/getWindow.js'

    Require stack:
      node_modules/@testing-library/user-event/dist/cjs/utils/misc/getWindow.js
      node_modules/@testing-library/user-event/dist/cjs/utils/dataTransfer/Clipboard.js
      node_modules/@testing-library/user-event/dist/cjs/event/behavior/click.js
      node_modules/@testing-library/user-event/dist/cjs/event/dispatchEvent.js
      node_modules/@testing-library/user-event/dist/cjs/document/prepareDocument.js
      node_modules/@testing-library/user-event/dist/cjs/setup/setup.js
      node_modules/@testing-library/user-event/dist/cjs/setup/index.js
      node_modules/@testing-library/user-event/dist/cjs/index.js
      src/pages/components/resetPasswordPage/resetPasswordComponent.test.jsx

      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:324:11)
      at Object.&lt;anonymous&gt; (node_modules/@testing-library/user-event/dist/cjs/utils/misc/getWindow.js:5:18)
</code></pre>
",https://stackoverflow.com/questions/74594019/error-when-unit-testing-in-reactjs-missing-library-modules,"['node.js', 'reactjs', 'unit-testing']",443,True,1,1
Python Unit Testing of PHP functions (related to database),"<p>I need to test some functionality of specific platform. That platform is written in PHP and I have to test it via python script. What is the way to do this (i dont need mock since i have test database with a lot of data anyway).
For example I have function :</p>
<pre><code>function addUser($username,$address,$password){
some pdo to insert in database (mysql)........}
</code></pre>
<p>Now what is the best way to to AUTOMATION TESTS of functions like this in Python.
Right now I just rewrite function in python and test it with made up data.</p>
<pre><code>def addUser(username,address,password):
pymysql stuff...
</code></pre>
<p>I start unittest and than i just addUser(&quot;randomUser&quot;,&quot;randomaddress&quot;,&quot;randomPass&quot;). I'm not sure how to test.</p>
",https://stackoverflow.com/questions/73492374/python-unit-testing-of-php-functions-related-to-database,"['python', 'unit-testing', 'python-unittest']",47,False,0,0
Cannot save file when unit testing a file upload,"<p>I try to Unit test a mvc controller that receive a model that has a HttpPostedFile as parameter</p>
<pre><code>    var constructorInfo = typeof(HttpPostedFile).GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)[0];
    var obj = (HttpPostedFile)constructorInfo
        .Invoke(new object[] { @&quot;D:\test.xlsx&quot;, &quot;application/vnd.ms-excel&quot;, null });

    model.MembershipRegisterFile = new HttpPostedFileWrapper(obj);
</code></pre>
<p>When I run the test and the controller tries to save the file to disk I get an exception on this line..</p>
<p>file.SaveAs(completepath);</p>
<p>With error...</p>
<pre><code>System.NullReferenceException: 'Object reference not set to an instance of an object.'
</code></pre>
<p>I assume this is beacuse the file isnt really uploaded and the content length of the file is null. So how should I approach this. Should I inside my controller have logic for the possibility of contentlength equals to null or can the HttpPostedFile set the content length?</p>
<p>UPDATE: I mocked the file like this and this worked....</p>
<pre><code>var postedfile = new Mock&lt;HttpPostedFileBase&gt;();
postedfile.Setup(f =&gt; f.ContentLength).Returns(8192);
postedfile.Setup(f =&gt; f.FileName).Returns(&quot;myfile.txt&quot;);
postedfile.Setup(f =&gt; f.InputStream).Returns(new MemoryStream(8192));
myObject.HttpPostedFile = postedfile.Object;
</code></pre>
",https://stackoverflow.com/questions/72443946/cannot-save-file-when-unit-testing-a-file-upload,"['c#', 'unit-testing', 'httppostedfile']",167,True,0,1
C# - Unit Testing Errors - Debugging and Exit Code 0,"<p>So I am working on my C# .NET Project and I have merged a lot of separate solutions into one solution - not just copying and pasting the files over but specifically creating each new file then copying the code over.</p>
<p>I have three projects at the moment:</p>
<ul>
<li>Interfaces - Holds a number of interfaces and enum's (Console - 5.0)</li>
<li>Refactored-Code - This is a refactored version of the code. I could have used Git to Version Control it but I need to specifically show that I can refactor code (Console - 5.0)</li>
<li>Unit Tests - Just a lot of unit tests and thats about it (MSTest Test Project)</li>
</ul>
<p>Unit Tests has a Dependency built on Refactor-Code and Interfaces. Refactor-Code also has a Dependency on Interfaces</p>
<p>All is fine and well until I decided to run my Tests. As when I go to run my Tests I get errors. Error One is displayed in a yellow bar with the following text &quot;Feature 'Edit and Continue' is currently unavailable due to an internal error.&quot; and it can be opened to show:</p>
<pre><code>StreamJsonRpc.RemoteInvocationException: New debugging session can't be started until the existing one has ended.
   at StreamJsonRpc.JsonRpc.&lt;InvokeCoreAsync&gt;d__139`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.CodeAnalysis.EditAndContinue.RemoteEditAndContinueServiceProxy.&lt;&gt;c__DisplayClass7_0.&lt;&lt;StartDebuggingSessionAsync&gt;b__0&gt;d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
   at Microsoft.CodeAnalysis.Remote.BrokeredServiceConnection`1.&lt;TryInvokeAsync&gt;d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)
RPC server exception:
System.InvalidOperationException: New debugging session can't be started until the existing one has ended.
      at Roslyn.Utilities.Contract.Fail(String message)
      at Microsoft.CodeAnalysis.EditAndContinue.EditAndContinueWorkspaceService.&lt;StartDebuggingSessionAsync&gt;d__10.MoveNext()
   --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Microsoft.CodeAnalysis.EditAndContinue.RemoteEditAndContinueService.&lt;&gt;c__DisplayClass7_0.&lt;&lt;StartDebuggingSessionAsync&gt;b__0&gt;d.MoveNext()
   --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
      at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
      at Microsoft.CodeAnalysis.Remote.BrokeredServiceBase.&lt;RunServiceImplAsync&gt;d__14.MoveNext()
   --- End of stack trace from previous location where exception was thrown ---
      at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
      at Microsoft.VisualStudio.Telemetry.WindowsErrorReporting.WatsonReport.GetClrWatsonExceptionInfo(Exception exceptionObject)
</code></pre>
<p>Error Two came in the Output window resulting in:</p>
<pre><code>'dotnet.exe' (CoreCLR: DefaultDomain): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.17\System.Private.CoreLib.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Temp\C#\BCDE222-AssignmentThree-[MyIRLName]\UnitTesting\bin\Debug\net5.0\UnitTesting.dll'. Symbols loaded.
'dotnet.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.17\System.Runtime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
The program '[9908] dotnet.exe' has exited with code 0 (0x0).
</code></pre>
<p>Note: [MyIRLName] isn't the actual thing that is there, my IRL name is and I don't want to publicly show that</p>
<p>Does anyone know what's happening here? The odd occasion that I have run tests I normally get a .dll file is missing (idk how) but this is a totally new one to mke</p>
",https://stackoverflow.com/questions/74566498/c-unit-testing-errors-debugging-and-exit-code-0,"['c#', '.net', 'unit-testing']",55,False,0,0
What will be the unit testing for this code?,"<p>What will be the unit testing code for the given code below...
Got stuck for a while so please help me find the solution...</p>
<pre class=""lang-cs prettyprint-override""><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoAppCore
{
    public class Program
    {
        public static string CacluateGrade(float mark)
        {
            string grade = &quot;&quot;;
            if (mark &lt; 40)
                grade = &quot;FAIL&quot;;
            else if (mark &gt;= 40)
                grade = &quot;PASS&quot;;
            return grade;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/72327155/what-will-be-the-unit-testing-for-this-code,"['c#', 'unit-testing']",45,False,-2,1
React component unit testing does not render the changes,"<p>I'm trying to test a simple react component and have the following unit test</p>
<pre><code>it.only('should display the edit page when the edit button is clicked', async () =&gt; {
    let r: any
    r = render(
        &lt;MemoryRouter initialEntries={['/tickets/1']}&gt;
            &lt;Routes&gt;
                &lt;Route path='tickets/:ticketId' element={&lt;TicketDetailPage /&gt;}&gt;&lt;/Route&gt;
            &lt;/Routes&gt;
        &lt;/MemoryRouter&gt;
    )


    act(() =&gt; {
        const form = screen.getByTestId&lt;HTMLFormElement&gt;('ticketForm')
        fireEvent.submit(form)
    })


    await waitFor(() =&gt; {
        const f = screen.getByTestId&lt;HTMLFormElement&gt;('ticketForm')
        console.log(f.outerHTML)
    });
})
</code></pre>
<p>I have two problems with this</p>
<ol>
<li>I get the following error/warning <code>  Warning: An update to TicketDetailPage inside a test was not wrapped in act(...).</code>  As you can see I have clearly wrapped my component test code in <code>act</code></li>
<li>Submitting the form which is initially in read only mode changes the form to an edit mode.  I know the form gets the form event because I can see the log saying switching to edit mode.  However in the <code>console.log(f.outerHTML)</code> output I don't see the edit mode has rendered, its still in the read only mode.</li>
</ol>
<p>This same form works fine in the browser, however it fails in the unit test mode.</p>
<p>This is the source code of the original <code>TicketDetailPage</code></p>
<pre><code>import { useParams } from &quot;react-router-dom&quot;;
import Button from '@mui/material/Button';
import { useAppDispatch, useAppSelector } from &quot;../../hooks&quot;;
import styles from './TicketDetailPage.module.scss';
import React, { useEffect } from &quot;react&quot;;
import TextField from '@mui/material/TextField';
import { saveTicket } from &quot;./ticketThunks&quot;;
import { useForm, SubmitHandler } from &quot;react-hook-form&quot;;

export const TicketDetailPage = () =&gt; {

type Inputs = {
    id: string,
    title: string,
    owner: string,
    description: string
};

const { register, handleSubmit, formState: { errors } } = useForm&lt;Inputs&gt;();

let { ticketId } = useParams();
const dispatch = useAppDispatch()

const [isEditMode, setEditMode] = React.useState&lt;boolean&gt;(false);


const onSubmit: SubmitHandler&lt;Inputs&gt; = data =&gt; {
    if (!isEditMode) { // set the edit mode
        setEditMode(true)
    } else { // save the changes
        dispatch&lt;any&gt;(saveTicket({
            id: ticketId!,
            description: data.description,
            owner: data.owner,
            title: data.title
        }));
        setEditMode(false)
    }
}

const ticket = useAppSelector(state =&gt; state.ticket.tickets.find(t =&gt; t.id === ticketId))

return (
    &lt;form data-testid=&quot;ticketForm&quot; onSubmit={handleSubmit(onSubmit)}&gt;
        &lt;div className={styles.container}&gt;
            &lt;div className={styles.contentContainer}&gt;
                &lt;div className={styles.fieldNameContainer}&gt;
                    &lt;div&gt;
                        Id
                    &lt;/div&gt;
                    &lt;div&gt;
                        Title
                    &lt;/div&gt;
                    &lt;div&gt;
                        Owner
                    &lt;/div&gt;
                    &lt;div&gt;
                        Description
                    &lt;/div&gt;
                &lt;/div&gt;

                {!isEditMode &amp;&amp;
                    &lt;div className={styles.fieldValueContainer}&gt;
                        &lt;div&gt;
                            {ticket?.id}
                        &lt;/div&gt;
                        &lt;div&gt;
                            {ticket?.title}
                        &lt;/div&gt;

                        &lt;div&gt;
                            {ticket?.owner}
                        &lt;/div&gt;

                        &lt;div&gt;
                            {ticket?.description}
                        &lt;/div&gt;
                    &lt;/div&gt;
                }

                {isEditMode &amp;&amp;
                    &lt;div className={styles.fieldValueContainer}&gt;
                        &lt;div&gt;
                            {ticket?.id}
                        &lt;/div&gt;

                        &lt;div&gt;
                            &lt;TextField
                                id=&quot;title-input&quot;
                                data-testid=&quot;title&quot;
                                label=&quot;Title&quot;
                                variant=&quot;standard&quot;
                                defaultValue={ticket?.title}
                                {...register(&quot;title&quot;, {
                                    validate: {
                                        notEmpty: (title) =&gt; {
                                            return title.trim() !== &quot;&quot;
                                        },
                                    }
                                })}
                            /&gt;
                            {errors.title &amp;&amp; errors.title.type === &quot;notEmpty&quot; &amp;&amp; (
                                &lt;p&gt;please specify a title&lt;/p&gt;
                            )}
                        &lt;/div&gt;

                        &lt;div&gt;
                            &lt;TextField
                                id=&quot;owner-input&quot;
                                data-testid=&quot;owner&quot;
                                label=&quot;Owner&quot;
                                variant=&quot;standard&quot;
                                defaultValue={ticket?.owner}
                                {...register(&quot;owner&quot;, {
                                    validate: {
                                        notEmpty: (owner) =&gt; {
                                            return owner.trim() !== &quot;&quot;
                                        },
                                    }
                                })}
                            /&gt;
                            {errors.owner &amp;&amp; errors.owner.type === &quot;notEmpty&quot; &amp;&amp; (
                                &lt;p&gt;please specify an owner&lt;/p&gt;
                            )}
                        &lt;/div&gt;

                        &lt;div&gt;
                            &lt;TextField
                                id=&quot;description-input&quot;
                                data-testid=&quot;description&quot;
                                label=&quot;Description&quot;
                                variant=&quot;standard&quot;
                                defaultValue={ticket?.description}
                                {...register(&quot;description&quot;)}
                            /&gt;
                        &lt;/div&gt;
                    &lt;/div&gt;
                }
            &lt;/div&gt;

            &lt;div className={styles.buttonContainer}&gt;
                &lt;Button
                    variant=&quot;contained&quot;
                    color=&quot;success&quot;
                    type=&quot;submit&quot;
                    data-testid=&quot;editTicket&quot;
                &gt;
                    {isEditMode &amp;&amp; 'Save'}
                    {!isEditMode &amp;&amp; 'Edit'}
                &lt;/Button&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    &lt;/form&gt;
)
</code></pre>
<p>}</p>
",https://stackoverflow.com/questions/73482114/react-component-unit-testing-does-not-render-the-changes,"['reactjs', 'unit-testing']",20,False,0,0
How to spy on useNavigate in react unit testing?,"<p>I want to test if useNavigate has been called after clicking on a button and also if it has been called with correct path in my unit test. I try to spy on it, but I keep getting the following error:</p>
<pre><code>● Test suite failed to run

    TypeError: Cannot redefine property: useNavigate
        at Function.defineProperty (&lt;anonymous&gt;)
</code></pre>
<p>Here is the spy in my test that triggers an error:</p>
<pre><code>import * as router from &quot;react-router-dom&quot;;

jest.spyOn(router, 'useNavigate');
</code></pre>
<p>What could be the problem?</p>
",https://stackoverflow.com/questions/73681278/how-to-spy-on-usenavigate-in-react-unit-testing,"['javascript', 'reactjs', 'testing', 'navigation', 'spy']",363,False,0,1
Unit testing for code isn&#39;t working for cs50 problem,"<p>I'm currently working on a Cs50 problem called Testing my Twitter. The code works very well and has no problems. But I'm having trouble trying to run a unit test on it.</p>
<p>this is my regular code that needs testing:</p>
<pre><code>def shorten(word):
    tweet = input(&quot;Input: &quot;)
    for letter in tweet:
        if not letter in ['A','E','I','O','U','a','e','i','o']:
            return letter
    print()
</code></pre>
<p>And this is my unit test code:</p>
<pre><code>import twttr

def test_twttr():
    assert shorten('Hello') == 'Hll'
test_twttr()
</code></pre>
<p>I've run into a lot of errors and have reached this point in my code where it just says OK. I changed my code to have an error and I'm still getting the same message. Can someone please take a look and see what's going on?</p>
",https://stackoverflow.com/questions/74017795/unit-testing-for-code-isnt-working-for-cs50-problem,"['python', 'unit-testing', 'cs50']",264,False,0,1
Logging AssertionError exceptions &amp; pytest unit testing in Python,"<p>I've been implementing logging to my python app, and I've stumbled upon what looks like a contradiction between unit testing &amp; logging. I'm looking for the best practice here, thanks in advance for your help !</p>
<pre class=""lang-py prettyprint-override""><code># app.py
def my_function(foo: int) -&gt; int:
   assert isinstance(foo, (int))

   return foo * 2
</code></pre>
<p>The associated unit test</p>
<pre class=""lang-py prettyprint-override""><code># test_my_function.py
import pytest
from app import my_function

def test_wrong_type_input():
    test_input = '3'

    with pytest.raises(AssertionError):
        my_function(test_input)
</code></pre>
<p>The two files above work OK, and the unit test campaign ends with a successful status.
However, I'm implementing logging to my app and I noticed that if I do pass an object other than a <code>int</code> to my function, <strong>the AssertionError is not passed to the logger</strong>, and this would lead to a more complicated root cause analysis in production.</p>
<p>Looking for answers on this, the <code>logging</code> documentation mentions capturing exception with a <code>try/except</code> statement. The new <code>app.py</code> would be the following :</p>
<pre class=""lang-py prettyprint-override""><code># app.py
import logging

def my_function(foo: int) -&gt; int:
    try:
        assert isinstance(foo, (int))
    except:
        logging.exception(&quot;Input `foo` did not meet the function's requirements&quot;)

    return foo * 2
</code></pre>
<p>However, now my unit test fails because the AssertionError is captured by the <code>try/except</code>.</p>
<p>What's the best practice here ?
How can I get both :</p>
<ul>
<li>getting the full traceback in logs when experiencing an Exception</li>
<li>while still be able to use the <code>pytest.raises(AssertionError)</code> logic ?</li>
</ul>
<p>Thanks in advance !</p>
",https://stackoverflow.com/questions/71102030/logging-assertionerror-exceptions-pytest-unit-testing-in-python,"['python', 'unit-testing', 'logging', 'pytest', 'assertion']",996,False,0,1
Mockito-Mock functions within scala object for unit testing,"<p>I have a few functions within a scala object. The functions internally call other functions of the same object.</p>
<pre class=""lang-scala prettyprint-override""><code>object A {

    def method1:Unit= {
        spark=CreateSparkSession.create()
        Method2(spark,dbnm)
    }

    def Method2(spark:Sparksession, dbnm:String):Unit= {
        //some implementation 
    }
}
</code></pre>
<p>How can I write Unit testcase for Method1 without actually invoking method2.</p>
<p>CreateSparksession is another object with create method that returns sparksession.</p>
",https://stackoverflow.com/questions/71313608/mockito-mock-functions-within-scala-object-for-unit-testing,"['scala', 'unit-testing', 'mockito', 'partial-mocks']",338,False,0,1
Grail 4 Spoc framework unit testing - withFilters not working,"<p>We use to use withFilters function in Mixin while writing unit tests but it does not support in Grails 4 spoc framework</p>
<p>Please help me if you know what we can use at place of withFilters.
I was using Like this</p>
<pre><code> withFilters(controller:&quot;restDomainAbc&quot;, action:&quot;list&quot;) {
                controller.list()
            }
</code></pre>
",https://stackoverflow.com/questions/74627156/grail-4-spoc-framework-unit-testing-withfilters-not-working,"['unit-testing', 'filter', 'spock', 'grails-4']",15,False,0,0
Unit testing C# with protected methods and Mocking fields,"<p>Below is code from a NuGet package which is used by our main project, MyClass is called via the main project with authentication. The method GetMyAppStoreConfig() will only work when calling from the main project via authentication.</p>
<pre><code>  public class MyClass : MyClassBase
    {
        private SomeClass1 someClass1;
        private MyAppStore myAppStore; // Field newly added
        
        public MyClass(params object[] args)
            : base(args)
        {
            this.someClass1 = new SomeClass1();
            this.myAppStore = new MyAppStore(GetMyAppStoreConfig()); // Field newly added
        }

           protected override async Task&lt;SomeValues&gt; Process(
            SomeClass2 someClass2,
            SomeClass3 someClass3,
            SomeClass4 someClass4
           )
        {
          ...
          ...
          ...
  
        }
     
    // Below method uses myAppStore
    // Method newly added
        protected override async Task&lt;SomeValues&gt; ProcessWithAuth(
            SomeClass5 someClass5
           )
        {
          ...
          ...
          ...
  
        }

        private AppStoreConfig GetMyAppStoreConfig(){
        ...
        ...
        }


    }

</code></pre>
<p>Earlier the test code for above was.</p>
<pre><code> [TestClass()]
    public class MyClassTests : MyClass 
    {
        

        [TestMethod()]
        public void test1()
        {   
            ...
            ... = this.Process(someClass2,someClass3,someClass4);
            ...
        }
   }
</code></pre>
<p>But now it doesn't work as it throws error in GetMyAppStoreConfig(). Currently I don't need to test ProcessWithAuth(), what changes I should make for the test case to work.</p>
<p>I currently cannot create one more constructor and cannot change the protection level in MyClass.cs .</p>
<p>Process() has some code which I want to run in tests and not simply mock.</p>
",https://stackoverflow.com/questions/72872608/unit-testing-c-with-protected-methods-and-mocking-fields,"['c#', '.net', 'unit-testing', '.net-framework-version']",460,True,0,1
"Unit testing: Document is not defined, error for &#39;document.getElementById()&#39;","<p>I am new to javascript. I am doing a unit test on my project, and getting some error. Here is my code:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>function timeConvert() {

    let n = document.getElementById('yourNo').value;
    
    var Jam = Math.floor(n / 3600);
    var Menit = Math.floor(n / 60);
    var Detik = Math.floor(n % 60);

    document.getElementById(""result"")
    .innerHTML = ""Waktu yang tersisa: "" + ""&lt;br&gt;"" 
    + Jam + "" Jam "" + ""&lt;br&gt;"" 
    + Menit + "" Menit "" + ""&lt;br&gt;"" 
    +  Detik + "" Detik "";
}

console.log(""normal use"", timeConvert(1633790418));</code></pre>
</div>
</div>
</p>
<p>And i got error like this:</p>
<p>C:\Users\USER\Desktop\backend_test\backend.js:3
let n = document.getElementById('yourNo').value;
^</p>
",https://stackoverflow.com/questions/74333059/unit-testing-document-is-not-defined-error-for-document-getelementbyid,"['javascript', 'html', 'unit-testing']",39,False,0,0
Unit testing Spring Boot Rest Controller with JPA Repositories,"<p>I have ,probably a basic question,related to unit testing a spring boot application that uses RestControllers,JPA repositories.Oracle is used in the backend.Now to unit test the JPA repositories using junit,mockito and probably DataJPA,do the tables that are present in the backend,need to be recreated in the H2 in-memory db?</p>
",https://stackoverflow.com/questions/70986522/unit-testing-spring-boot-rest-controller-with-jpa-repositories,"['java', 'spring-boot', 'spring-data-jpa', 'mockito', 'junit5']",488,False,0,0
How to select child element in Angular unit testing,"<p>I want to check the textContent of a div that is a child of the component for which I'm writing the unit tests.</p>
<p>The HTML looks like</p>
<pre class=""lang-html prettyprint-override""><code>&lt;div 
    [ngClass]=&quot;containerClasses&quot;
    *ngIf=&quot;showTooltip&quot;&gt;

    &lt;div [ngClass]=&quot;arrowClasses&quot;&gt;&lt;/div&gt;
    
    &lt;div  class=&quot;label&quot; id=&quot;label&quot;&gt; {{ label }} &lt;/div&gt; 
&lt;/div&gt;

</code></pre>
<p>I want to check the textContent of the div with class=&quot;label&quot;.</p>
<p>I have tried approaches given on the internet and even on angular's website but they all return only null. Here's a snippet of how I tried it.</p>
<pre class=""lang-js prettyprint-override""><code>it('should have a label with max 255 chars', () =&gt; {
    // approach 1
     const labelElement = fixture.nativeElement.querySelector('.label'); // null

    // approach 2
    const labelElement2 = fixture.debugElement.query(By.css('.label')); // null

    // approach 3
    const labelElement3 = fixture.debugElement.nativeElement.querySelector('#label'); // null

    // approach 4
    const labelElement4 = fixture.debugElement.query((de)=&gt;{return de.nativeElement.id===&quot;label&quot;}); // null
  })
</code></pre>
<p>All of these approaches are said to be valid approaches online. But all of them return null when I do console.log or try to access the textContent property.</p>
<p>What should I do?</p>
",https://stackoverflow.com/questions/73971205/how-to-select-child-element-in-angular-unit-testing,"['angular', 'unit-testing', 'karma-jasmine']",512,False,0,0
Unit testing on local file throws java.io.FileNotFoundException in macbook,"<pre><code> response =
        File(&quot;src\\test\\java\\com\\resources\\products\\response.json&quot;).bufferedReader()
            .use { it.readText() }
</code></pre>
<p>I have this line of code for mocking response and it is working fine on pc but throws not found on macbook? Any solutions? Thanks.</p>
",https://stackoverflow.com/questions/70863193/unit-testing-on-local-file-throws-java-io-filenotfoundexception-in-macbook,"['java', 'android', 'unit-testing', 'kotlin', 'mockwebserver']",525,False,0,2
Unit testing of azure function(timer trigger) with mongoDB,"<p>I have one azure function which is deleting records from mongo database with certain condition. I need to write test case for that. Please guide me how that can be done.</p>
<p><strong>Function Code:</strong></p>
<pre><code>public class DeleteRef
{
    private readonly IDelete _iDelete;
    public DeleteRef(IDelete Delete)
    {
        _iDelete = Delete;
    }
    
    [FunctionName(&quot;DeletionOperation&quot;)]
    public async Task Run([TimerTrigger(&quot;0 */10 * * * *&quot;)] TimerInfo myTimer, ILogger log)
    {
        _iDelete.CleardData();
    }
}
</code></pre>
<p><strong>Mongo Code:</strong></p>
<pre><code>public  class CleardAllData : IDelete
{

 private readonly IMongoClient _mongoClient;
 
public CleardAllData(IMongoClient mongoClient)
{
   _mongoClient = mongoClient;
}

public void CleardData()
{
    var db = _mongoClient.GetDatabase(&quot;ABC&quot;);
    var collection = db.GetCollection&lt;BsonDocument&gt;(&quot;XYZ&quot;);
    var filter = new FilterDefination&lt;BsonDocument&gt;(); // I have some filter condition
    var deleteResult = await collection.DeleteManyAsync(filter);
    var numrowsdeleted = deleteResult.DeletedCount;
} 
}
</code></pre>
",https://stackoverflow.com/questions/71036399/unit-testing-of-azure-functiontimer-trigger-with-mongodb,"['c#', 'mongodb', 'azure', 'unit-testing', 'azure-functions']",273,False,0,1
Unit testing - how to write unit test in Angular,"<p>Hi I have below code in ts file,</p>
<pre><code>    constructor(private route: ActivatedRoute, private fhirService:FHIRService) { 
      oauth2.ready(this.onAuth2Ready.bind(this));
    }
    
    onAuth2Ready(fhirclient: Client) {
      this.fhirService.setFhirClient(fhirclient);
      this.fhirService.setPatientId(fhirclient.patient.id);
    }
</code></pre>
<p>In spec.ts file I wrote unit case as below</p>
<pre><code>it('test authentication', () =&gt; {

    let client = fixture.debugElement.injector.get(Client);
    expect(component.onAuth2Ready(client)).toBeDefined();
    let fhirServiceSpy = jasmine.createSpyObj(fhirService, ['setFhirClient', 'setPatientId']);
 
    fhirServiceSpy.setPatientId ={}
    expect(fhirServiceSpy.setPatientId).toHaveBeenCalledWith(fhirService.patientId);
    expect(fhirServiceSpy.setFhirClient(client)).toBeDefined();
    expect(fhirServiceSpy.setPatientId(&quot;900990&quot;)).toBeDefined();
  });
</code></pre>
<p>in service,</p>
<pre><code>   setFhirClient(client: Client) {
        this.fhirClient = client;
    } 
</code></pre>
<p>for the above test case getting below error
this.fhirService.setFhirClient is not a function</p>
<p><strong>For code coverage , how to write unit test case of onAuth2Ready method?</strong></p>
<p>Thanks In Advance!</p>
",https://stackoverflow.com/questions/73850323/unit-testing-how-to-write-unit-test-in-angular,"['angular', 'unit-testing', 'code-coverage']",28,False,0,0
Hitting Digest already called on cryptoJS during unit testing,"<pre class=""lang-js prettyprint-override""><code>import crypto from 'crypto';

export const getChecksum: (_: PathLike) =&gt; Promise&lt;string&gt; = (path: PathLike) =&gt;
  new Promise(resolve =&gt; {
    const hash = crypto.createHash('md5');
    const input = fs.createReadStream(path);

    input.on('data', chunk =&gt; {
      hash.update(chunk);
    });

    input.on('close', () =&gt; {
      resolve(hash.digest('hex'));
    });
  });
</code></pre>
<p>Given the function, it can accept a file path, and perform <code>hash.update</code> while streaming the file, I'm trying to write an unit test like below</p>
<pre class=""lang-js prettyprint-override""><code>describe('getChecksum()', () =&gt; {
  afterEach(() =&gt; {
    vol.reset();
  });

  it('should generate consistent checksum', async () =&gt; {
    vol.fromJSON(
      {
        './some/README.md': '1',
        './some/index.js': '2',
      },
      '/app'
    );

    const result = await getChecksum('/app/some/index.js');
    expect(result).toBe('c81e728d9d4c2f636f067f89cc14862c');
  });
});
</code></pre>
<p>From the Unit Test above, assertion was able to perform correctly, however, I'm hitting error below</p>
<pre class=""lang-sh prettyprint-override""><code>  ● getChecksum() › should generate consistent checksum

    Error [ERR_CRYPTO_HASH_FINALIZED] [ERR_CRYPTO_HASH_FINALIZED]: Digest already called

      63 |
      64 |     input.on('close', () =&gt; {
    &gt; 65 |       resolve(hash.digest('hex'));
         |                    ^
      66 |     });
      67 |   });
      68 |
</code></pre>
<p>Not too sure which part has gone wrong?</p>
",https://stackoverflow.com/questions/70835735/hitting-digest-already-called-on-cryptojs-during-unit-testing,"['javascript', 'node.js', 'jestjs', 'cryptojs']",374,False,0,0
How to enter in NGXS selector when unit testing?,"<p>Subscribing to the selector teamMemberService$ should return a list, and then there is some checking going on. I need to test this piece of code, but I don't know how to get into this type of subscription.</p>
<pre><code>    if (this.doctor != undefined) {
      this.store.dispatch(new SearchTeamMemberData(this.doctor));
      this.teamMemberService$.subscribe((res) =&gt; {
        res.forEach((element) =&gt; {
          if (element.id !== 0) {
            this.teamList = res;
          } else {
            this.listZoroh = res;
          }
        });
        this.isLoading$.subscribe((res) =&gt; {
          this.isLoading = res;
        });
      });
    }
</code></pre>
<p>Test:</p>
<pre><code>it(&quot;should subscribe to selector&quot;, () =&gt; {
    const doctor = {
      id: 9090900,
      name: &quot;DOKTOR&quot;,
      surname: &quot;TESTNI DRUGI&quot;,
      mbr: &quot;111111111&quot;,
      mbo: &quot;214000010&quot;,
      isReplacement: true,
      role: &quot;doctor&quot;,
      hasFileExchPermission: false,
      displayName: &quot;DOC&quot;,
    };
    component.doctor = doctor;
    const spy = jest.spyOn(component.teamMemberDetails$, &quot;subscribe&quot;);
    component.getView();
    fixture.detectChanges();
    expect(spy).toHaveBeenCalled();
  });
</code></pre>
<p>Since the subscription should return a list, I tried adding this to my test (as seen here <a href=""https://github.com/ngxs/store/issues/482"" rel=""nofollow noreferrer"">https://github.com/ngxs/store/issues/482</a>)</p>
<pre><code>Object.defineProperty(component, &quot;teamMemberDetails$&quot;, { writable: true });
component.teamMemberDetails$ = of([{ id: 1 }]);
</code></pre>
<p>I am getting</p>
<pre><code>TypeError: Cannot read property 'forEach' of undefined
</code></pre>
<p>And now I am clueless. Help appreciated.</p>
",https://stackoverflow.com/questions/72865028/how-to-enter-in-ngxs-selector-when-unit-testing,"['angular', 'unit-testing', 'jestjs']",88,False,0,1
Builder pattern in unit testing vs mocking all collaborators,"<p>Lets say a university offers courses and courses are attended by students:</p>
<pre class=""lang-java prettyprint-override""><code>class University{
    List&lt;Course&gt; courses;
}

class Course{
    Category category;
    List&lt;Student&gt; students;
}


class Student{
    Gender getGender();
    boolean hasGender(Gender gender);
}

</code></pre>
<p>I also have a class <code>Filter</code> which should return all male students which attend courses in <code>Category.MATH</code></p>
<pre class=""lang-java prettyprint-override""><code>public class Filter{


  University university;
   
  List&lt;Student&gt; selectSubgroup(){
     //to be implemented
  }
}
</code></pre>
<p>I normally use the builder pattern to write tests in such cases and i like it because of the readability.</p>
<pre class=""lang-java prettyprint-override""><code>class FilterTest{
    @Test
    void testThatOnlyMaleStudentsInCategoryMathAreSelected(){
        when(university.getCourses()).thenReturn(
            aCourse()
                .with(Category.MATH)
                .with(
                    aStudent()
                        .withGender(Gender.MALE),
                    aStudent()
                        .withGender(Gender.FEMALE)
                )
        );
        
        assertThat(filter.selectSubgroup()).hasSize(1);
    }
}
</code></pre>
<p>However, using this approach implies using the real method <code>hasGender</code> of class <code>Student</code>, so the test is not isolated.
Using mockito, a test might look like this:</p>
<pre class=""lang-java prettyprint-override""><code>class FilterTest{
    @Test
    void testThatOnlyMaleStudentsInCategoryMathAreSelected(){
    
        when(university.getCourses()).thenReturn(Arrays.asList(course));
        when(course.getStudents()).thenReturn(Arrays.asList(student, student2));
        when(course.getCategory()).thenReturn(Category.MATH);
        when(student.hasGender(eq(Gender.MALE))).thenReturn(true);
        when(student.hasGender(eq(Gender.FEMALE))).thenReturn(false);
        when(student2.hasGender(eq(Gender.FEMALE))).thenReturn(true);
        when(student2.hasGender(eq(Gender.MALE))).thenReturn(false);
        
        assertThat(filter.selectSubgroup()).hasSize(1);
    }
}
</code></pre>
<p>I find this less readable, but all the dependendent classes are mocked. So, which approach is better?</p>
",https://stackoverflow.com/questions/73584761/builder-pattern-in-unit-testing-vs-mocking-all-collaborators,"['junit', 'mocking', 'mockito', 'assertj']",54,False,0,0
Quarkus unit testing - How to deal with injection problems?,"<p>I'm trying to make unit test in quarkus for my application. I'm maybe missing something but I have a connection to database problem. For unit test, I do not need database connection but when I'm injecting my service, automatically, Quarkus try to connect to the database. How do I mock the repository inside of the service ?</p>
<p>Here is the error : <code>io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection refused: no further information: localhost/127.0.0.1:3306</code></p>
<p>Here is my test class:</p>
<pre><code>@QuarkusTest
class MyTestClass {

    @InjectMock
    MerchantRepository merchantRepository;

    @Inject
    MerchantService merchantService; // Problem with this injection I think

    @Inject
    MerchantMapper merchantMapper; 

    @Test
    void testupdate()  {

        MerchantDTO merchantDTO = new MerchantDTO();
        merchantDTO.setId(&quot;id&quot;);
        merchantDTO.setSomething2(&quot;hello&quot;);
        merchantDTO.setSomething3(&quot;hello&quot;);
        merchantDTO.setSomething4(&quot;hello&quot;);
        merchantDTO.setSomething5(false);
        
        String id = &quot;id&quot;;
        MerchantBO merchant = merchantMapper.toBOFromDTO(merchantDTO);
        MerchantBO fake = null;

        when(merchantRepository.somemethod(merchantDTO.getId())).thenReturn(Uni.createFrom().item(merchant));
        when(merchantRepository.somemethod2(Mockito.any(), Mockito.any())).thenReturn(Uni.createFrom().item(fake));
        when(merchantRepository.somemethod3(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Uni.createFrom().item(fake));

        assertEquals(merchantDTO, merchantService.update(id, merchantDTO).await().indefinitely());
    }

}

</code></pre>
<p>Here is my service:</p>
<pre><code>@ApplicationScoped
public class MerchantService {

    @Inject
    MerchantRepository merchantRepository;

    @Inject
    MerchantMapper merchantMapper;

    ...
}

</code></pre>
<p>Do you have any idea that could help ?</p>
<p>I tried to to Mock the repository inside of the object of the service and that was also not working.</p>
",https://stackoverflow.com/questions/74362258/quarkus-unit-testing-how-to-deal-with-injection-problems,"['unit-testing', 'dependency-injection', 'mockito', 'quarkus']",64,True,0,1
"Unit Testing Atomic Kotlin, how can I activate it?","<p>I want to use something called <a href=""https://www.angus-liu.cn/Atomic-Kotlin-zh/se06-ch06.html"" rel=""nofollow noreferrer"">AtomicTest</a>. I put at the top:</p>
<pre><code>import atomictest.eq
</code></pre>
<p>But it is not working. I got an error saying: <strong>Kotlin: Unresolved reference: eq</strong></p>
<p>Is there anything that I have to do in order for this test to work?</p>
",https://stackoverflow.com/questions/72186357/unit-testing-atomic-kotlin-how-can-i-activate-it,['kotlin'],147,False,0,1
Unit testing a state machine with all possible transitions?,"<p>I have a state machine implemented as this data structure under the hood:</p>
<pre><code>Map&lt;State, Map&lt;State, boolean&gt;&gt;
</code></pre>
<p>The idea being you use the original state as the input to lookup the list of possible target states. Then you lookup the target state in that embedded map, and if it's there, a possible transition exists.</p>
<p>My problem is unit testing all possible transitions, such that if you give the test some input that will throw an error (an invalid state transition), then the test should fail if you have not included <em>all</em> of the states.</p>
<p>My test looks something like this:</p>
<pre><code>public void invalid_state_transition() {
    State originalState = State0;
    List&lt;State&gt; targetStates = List.of(
        State1, 
        State2, 
        ...
    )

    for (targetState : targetStates) {
        TransitionToTargetState(originalState, targetState)
    }
}
</code></pre>
<p>How would I go about doing this? Or am I thinking about the problem in the wrong way?</p>
",https://stackoverflow.com/questions/71970545/unit-testing-a-state-machine-with-all-possible-transitions,"['java', 'state-machine']",200,False,0,0
How to do the unit testing of history.push function?,"<p>I want to unit test the following element, especially the <code>onClick</code> function, But have no idea how to do the unit testing</p>
<pre><code>const baseURL = &quot;/Security/Users/&quot;;


return (
    &lt;div&gt;
      &lt;div className=&quot;flex-between&quot;&gt;
        &lt;button
          className=&quot;bt-save&quot;
          onClick={() =&gt; history.push(baseURL + &quot;Add&quot;)}
        &gt;
          Add
        &lt;/button&gt;
       &lt;/div&gt;
    &lt;/div&gt;
  );
</code></pre>
<p>this is related to react unit testing using jest. From this, I want to unit test the Add Button <code>onClick</code> function.</p>
<p>Here is my approach to unit test this function</p>
<pre><code>it('Should run the callback function when clicked', async () =&gt; {
    const onClick = jest.fn(baseURL + &quot;Add&quot;)

    render(&lt;button push={onClick}&gt; Add &lt;/button&gt;)

    const addButton = screen.getByText('Add')
    await userEvent.click(addButton)
    expect(onClick).toHaveBeenCalled()
})
</code></pre>
<p>I'm getting the following error when I'm trying to do the testing.</p>
<p><a href=""https://i.stack.imgur.com/cH7lq.png"" rel=""nofollow noreferrer"">I'm getting this result on the console</a></p>
<p>Can anyone help me understand this <code>onClick</code> function unit testing</p>
",https://stackoverflow.com/questions/73647358/how-to-do-the-unit-testing-of-history-push-function,"['reactjs', 'jestjs']",36,False,-1,1
C# unit testing with mstest and mockink unexpected error,"<p>My testing code threw following error for unknow reason. Probably setting up mocking incorrectly but I have no idea how to do it right please help.</p>
<p>Message:
Test method GUI_VIS.MsTests.LoginTest.TestEmptyIsAdminWindow threw exception:
System.NotSupportedException: Unsupported expression: x =&gt; x.GetAllEmailAsync(&quot;Pepa&quot;, &quot;Heslo&quot;, new Worker() {  })
Non-overridable members (here: GenericController.GetAllEmailAsync) may not be used in setup / verification expressions.</p>
<p>Stack Trace:
Guard.IsOverridable(MethodInfo method, Expression expression) line 109
MethodExpectation.ctor(LambdaExpression expression, MethodInfo method, IReadOnlyList<code>1 arguments, Boolean exactGenericTypeArguments, Boolean skipMatcherInitialization, Boolean allowNonOverridable) line 87 ExpressionExtensions.&lt;Split&gt;g__Split|5_0(Expression e, Expression&amp; r, MethodExpectation&amp; p, Boolean assignment, Boolean allowNonOverridableLastProperty) line 219 ExpressionExtensions.Split(LambdaExpression expression, Boolean allowNonOverridableLastProperty) line 150 Mock.SetupRecursive[TSetup](Mock mock, LambdaExpression expression, Func</code>4 setupLast, Boolean allowNonOverridableLastProperty) line 643
Mock.Setup(Mock mock, LambdaExpression expression, Condition condition) line 498
Mock<code>1.Setup[TResult](Expression</code>1 expression) line 452
LoginTest.TestEmptyIsAdminWindow() line 48
ThreadOperations.ExecuteWithAbortSafety(Action action)</p>
<pre><code>    [TestMethod]
    public async Task TestEmptyIsAdminWindow()
    {
        Login login = new Login();

        Mock&lt;GenericController&gt; gcMock = new Mock&lt;GenericController&gt;();
        GenericController gc = new GenericController();

        login.IdBoxGet().Text = &quot;John&quot;;
        login.PasswordBoxGet().Text = &quot;Password&quot;;
        

        ObservableCollection&lt;Worker&gt; workers = new ObservableCollection&lt;Worker&gt;() {
            new Worker
            {
                Name = &quot;John&quot;,
                My_password = &quot;Password&quot;,
                Role = &quot;Boss&quot;
            }
        };

        gcMock.Setup(x =&gt; x.GetAllEmailAsync(&quot;John&quot;, &quot;Heslo&quot;, new Worker() { }))
            .ReturnsAsync(workers);
        
        var workersFromMocking = await gc.GetAllEmailAsync(&quot;John&quot;, &quot;Password&quot;, new Worker() { });


        Assert.IsTrue(workersFromMocking[0].Name == &quot;John&quot;);
    }
</code></pre>
",https://stackoverflow.com/questions/74004981/c-unit-testing-with-mstest-and-mockink-unexpected-error,"['c#', 'unit-testing', 'mocking']",64,True,0,1
DjangoRestFramework: Unit Testing AssertionError: 404 != 200 while Test update,"<p>I've started writing unit tests for my API's but am stuck while updating user details received an assertion error of 404!=200. I'm sharing mycode for the reference.
Please do let me know my mistake and a brief explanation as I'm new to django rest.</p>
<p>I've created only one class &quot;class TestUser(APITestCase):&quot; for testing 2 API is it fine as I'm extending the URL in the update client patch?</p>
<pre><code>models.py

mport email
from pyexpat import model
from django.db import models
from django.conf import settings
from django.db.models.signals import post_save
from django.dispatch import receiver

from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser)

GENDER_CHOICES = (
    (0, 'male'),
    (1, 'female'),
    (2, 'not specified'),)

class UserManager(BaseUserManager):
  def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None):
      &quot;&quot;&quot;
      Creates and saves a User with the given email, name and password.
      &quot;&quot;&quot;
      if not email:
          raise ValueError('User must have an email address')

      user = self.model(
          email=self.normalize_email(email),
          name=name,
          contact_number=contact_number,
          gender=gender,
          address=address,
          state=state,
          city=city,
          country=country,
          pincode=pincode,
          dob=dob,
          
      )

      user.set_password(password)
      
      user.save(using=self._db)
      return user

  def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None):
      &quot;&quot;&quot;
      Creates and saves a superuser with the given email, name and password.
      &quot;&quot;&quot;
      user = self.create_user(
          email,
          
          name=name,
          contact_number=contact_number,
          gender=gender,
          address=address,
          state=state,
          city=city,
          country=country,
          pincode=pincode,
          dob=dob,
          password=password,
          
      )
      user.is_admin = True
      user.save(using=self._db)
      return user



class User(AbstractBaseUser):
    email = models.EmailField(verbose_name='Email',max_length=255,unique=True)
    name = models.CharField(max_length=200)
    contact_number= models.IntegerField()
    gender = models.IntegerField(choices=GENDER_CHOICES)
    address= models.CharField(max_length=100)
    state=models.CharField(max_length=100)
    city=models.CharField(max_length=100)
    country=models.CharField(max_length=100)
    pincode= models.IntegerField()
    dob = models.DateField(null= True)


    # is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name','contact_number','gender','address','state','city','country','pincode','dob']

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        &quot;Does the user have a specific permission?&quot;
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        &quot;Does the user have permissions to view the app `app_label`?&quot;
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        &quot;Is the user a member of staff?&quot;
        # Simplest possible answer: All admins are staff
        return self.is_admin


</code></pre>
<pre><code>views.py

class UserListCreateAPIView(generics.ListCreateAPIView):
    permission_classes = [IsUserOrIsAdmin]
    serializer_class = UserSerializer
    def get_queryset(self):
        &quot;&quot;&quot;
        This view should return a list of all the purchases
        for the currently authenticated user.
        &quot;&quot;&quot;
        if self.request.user.is_staff == False:

            user_data= self.request.user.id
            data = User.objects.filter(id= user_data)
            return data
        else:
            data = User.objects.all()
            return data

    
    
    
class UserRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [IsUserOrIsAdmin]
    serializer_class = UserSerializer
    def get_queryset(self):
        &quot;&quot;&quot;
        This view should return a list of all the purchases
        for the currently authenticated user.
        &quot;&quot;&quot;
        if self.request.user.is_staff == False:

            user_data= self.request.user.id
            data = User.objects.filter(id= user_data)
            return data
        else:
            data = User.objects.all()
            return data
    
</code></pre>
<pre><code>urls.py

path('customer_info/', UserListCreateAPIView.as_view()),
    path('customer_info/&lt;int:pk&gt;/', UserRetrtieveUpdateDestroyAPIView.as_view()),
</code></pre>
<pre><code>tests.py

from rest_framework.test import APITestCase
from .models import User







class TestUser(APITestCase):
    url = &quot;/api/v1/customer_info/&quot;

    def setUp(self):
        User.objects.create(email=&quot;naveen@example.com&quot;,name=&quot;Naveen&quot;,contact_number=&quot;9090909098&quot;,gender=&quot;0&quot;,address=&quot;jaipur&quot;,state=&quot;Rajasthan&quot;,city=&quot;Jaipur&quot;,country=&quot;India&quot;,pincode=&quot;302016&quot;,dob=&quot;1907-07-20&quot;,is_active=&quot;True&quot;,
        is_admin= &quot;False&quot;)

    def test_get_User(self):

        response = self.client.get(self.url)
        print(response)
        result = response.json()
        # print(result)

        self.assertEqual(response.status_code, 200)
        self.assertIsInstance(result, list)
        

    def test_post_User(self):
        # definition
        data = {
            &quot;email&quot;:&quot;ujjval@example.com&quot;,
            &quot;password&quot;:&quot;123456&quot;,
            &quot;name&quot;:&quot;ujjval&quot;,
            &quot;contact_number&quot;:&quot;9090909098&quot;,
            &quot;gender&quot;:&quot;0&quot;,
            &quot;address&quot;:&quot;jaipur&quot;,
            &quot;state&quot;:&quot;Rajasthan&quot;,
            &quot;city&quot;:&quot;Jaipur&quot;,
            &quot;country&quot;:&quot;India&quot;,
            &quot;pincode&quot;:&quot;302016&quot;,
            &quot;dob&quot;:&quot;1907-07-20&quot;
        }

        # process
        response = self.client.post(self.url, data=data)
        # print(response)
        result = response.json()
        # print(result)

        # assert
        self.assertEqual(response.status_code, 201)
        self.assertEqual(result[&quot;email&quot;], &quot;ujjval@example.com&quot;)

    def test_update_User(self):
        pk = &quot;1&quot;
        data = {
            &quot;email&quot;:&quot;naveen@example.com&quot;,
            
        }

        response = self.client.patch(self.url + f&quot;{pk}/&quot;, data=data)
        result = response.json()
        print(result)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(result[&quot;email&quot;], &quot;ujjval@example.com&quot;)
</code></pre>
",https://stackoverflow.com/questions/73248088/djangorestframework-unit-testing-assertionerror-404-200-while-test-update,"['python', 'django', 'unit-testing', 'django-models', 'django-rest-framework']",403,True,0,1
Python unit-testing: view annotated coverage report in terminal,"<p>I'm using Python's unittest for testing, and I know I can view per-source-file annotated coverage report in browser by exporting it to HTML files with:</p>
<pre><code>coverage run -m unittest *_test.py
coverage html
</code></pre>
<p>But I want to view this in Linux/Unix command line: view a given source file, with covered lines marked with green, and missed lines marked with red.</p>
<p>I tested several terminal web browsers (w3m, links, elinks, links2) and none of them can display these html files in a readable manner.</p>
<p>Maybe I'm missing something, because it looks like a very obvious feature to have in &quot;coverage&quot; or &quot;green&quot; or other testing tools, but I can't find anything!</p>
",https://stackoverflow.com/questions/70718517/python-unit-testing-view-annotated-coverage-report-in-terminal,"['python', 'linux', 'unit-testing', 'code-coverage', 'python-unittest']",119,True,0,1
How to initialize WidgetInfo for unit testing in Xcode?,"<p>I am trying to initialize the <code>WidgetKit</code> struct <code>WidgetInfo</code> for unit testing a function that takes <code>WidgetInfo</code> as an argument:</p>
<pre><code>let widgetInfo = WidgetInfo()
</code></pre>
<p>This gives me the error:
<em>'WidgetInfo' cannot be constructed because it has no accessible initializers</em></p>
<p>I tried adding:</p>
<pre><code>extension WidgetInfo {
    public init() {}
}
</code></pre>
<p>and I can initialize - yay! But then I try to set one of its properties</p>
<pre><code>widgetInfo.family = .systemSmall
</code></pre>
<p>and get the error: <em>Cannot assign to property: 'family' is a 'let' constant</em></p>
<p>I tried another initializer with arguments:</p>
<pre><code>extension WidgetInfo {
    public init(family: WidgetFamily, kind: String) {
        self.family = family
        self.kind = kind
    }
}
</code></pre>
<p>and I get the error: <em>'let' property 'family' may not be initialized directly; use &quot;self.init(...)&quot; or &quot;self = ...&quot; instead</em></p>
<p>I'm stuck - is there a way for me to initialize <code>WidgetInfo</code>? Or another way to test a function that takes <code>WidgetInfo</code> as an argument?</p>
",https://stackoverflow.com/questions/72481788/how-to-initialize-widgetinfo-for-unit-testing-in-xcode,"['ios', 'swift', 'xcode', 'xctest', 'widgetkit']",90,True,0,1
Unit testing enable and disable method on reactive forms,"<p>Hi I am writing tests for reactive form in angular and I am having hard time testing this part of the code</p>
<pre><code>setForm(): void {
    const firstName = this.form.get('firstName');
    const lastName = this.form.get('lastName');

    lastName.disable();
    lastName.clearValidators();
    lastName.setValue('');

    firstName.enable();
    firstName.setValidators([Validators.required]);
}
</code></pre>
<p>This is a part of FormService file where I set the reactive form controls, validation and etc.
Is there a way to test this?</p>
",https://stackoverflow.com/questions/70830001/unit-testing-enable-and-disable-method-on-reactive-forms,"['angular', 'forms', 'unit-testing', 'karma-jasmine', 'angular-reactive-forms']",1214,False,0,1
Is chai HTTP considered unit testing or integration testing?,"<p>The project I am working on has Cloud Functions written in <code>user-controller.ts</code>, and I am writing tests for these cloud functions using chai HTTP functions. Here's a sample of a test I am writing</p>
<pre><code>it('should success and get all users', (done) =&gt; {
        chai.request(myFunctions.qa)
                .get('/getAllUsers')
                .set('x-api-key', API_KEY)
                .set('user-token', AdminToken)
                .set('content-type', 'application/json')
                .end((err, res) =&gt; {
                    res.should.have.status(200);
                    res.body.should.be.a('object').with.property('status', true);
                    res.body.should.have.a.property('data');
                    const data = res.body.data;
                    expect(data).to.be.an('object');
                    if (Object.keys(data).length &gt; 0) {
                        Object.values(data).map((user: any) =&gt; {
                            expect(user).to.have.property('firstName');
                            expect(user).to.have.property('lastName');
                        });
                    }
                    done();
                });
          });
</code></pre>
<p>I would like to know if this test is considered a unit test or integration test? If it's considered an integration test, how am I supposed to change it into a unit test?</p>
",https://stackoverflow.com/questions/71562679/is-chai-http-considered-unit-testing-or-integration-testing,"['mocha.js', 'chai', 'chai-http']",136,False,0,0
Unit testing a memo component with React hooks library,"<p>Am trying to perform unit tests with React hooks, but I haven't got a seamless approach, am using this library <a href=""https://react-hooks-testing-library.com/usage/basic-hooks"" rel=""nofollow noreferrer"">react hooks testing library</a>, and I want to ensure that I test a component but wrapped with a memo, inside it there are <code>useCallbacks</code>, I want to test them one by one, the component below is exported like this <code>export default memo(DateTimePicker); </code>  so how can I go deeper and test useCallback functions e.g <code>getValueFormat</code>, <code>setFormatter</code> etc.</p>
<p>Below is the component I want to test:</p>
<pre><code>const DateTimePicker = ({
  inputRefProp,
  options = undefined,
  datepicker = true,
  timepicker = true,
  placeholder = '',
  defaultValue = '',
  value: propValue = '',
  displayDateFormat = 'DD.MM.YYYY',
  displayTimeFormat = 'HH=mm',
  displayDateTimeFormat = 'DD.MM.YYYY HH=mm',
  value_format = undefined,
  onChange = undefined,
  onBlur = undefined,
  onBlurTyped = undefined,
  scrollInput = false,
  customInput = undefined,
  locale = 'de',
  maxDate = undefined,
  earlierDate = false,
}: Props) =&gt; {
  const [value, setValue] = useState&lt;ValueType&gt;('');
  const [isInvalid, setIsInvalid] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [selected, setSelected] = useState(false);
  const inputRef = useRef(null);

  const getDisplayFormat = useCallback(() =&gt; {
    if (datepicker &amp;&amp; timepicker) {
      return displayDateTimeFormat;
    }
    if (datepicker) {
      return displayDateFormat;
    }
    if (timepicker) {
      return displayTimeFormat;
    }
    return displayDateTimeFormat;
  }, [displayDateFormat, displayTimeFormat, displayDateTimeFormat, datepicker, timepicker]);

  const getValueFormat = useCallback(() =&gt; {
    if (value_format) {
      return value_format;
    }
    if (datepicker &amp;&amp; timepicker) {
      return ISO_DATETIME_FORMAT;
    }
    if (datepicker) {
      return ISO_DATE_FORMAT;
    }
    if (timepicker) {
      return ISO_TIME_FORMAT;
    }
    return ISO_DATETIME_FORMAT;
  }, [datepicker, timepicker, value_format]);

  const setFormatter = useCallback(() =&gt; {
    $.datetimepicker.setDateFormatter({
      parseDate(date: Date, _format: string) {
        const d = moment.utc(date, _format);
        return d.isValid() ? d.toDate() : false;
      },

      formatDate(date: Date, _format: string) {
        return moment.utc(date).format(_format);
      },
    });
  }, []);

  const getValue = useCallback(
    (newValue: ValueType = '') =&gt; {
      if (newValue) {
        return moment.utc(newValue, getValueFormat()).format(getDisplayFormat());
      }
      return moment.utc(value, getValueFormat()).format(getDisplayFormat());
    },
    [getDisplayFormat, getValueFormat, value],
  );

  const onChangeHandler = useCallback(
    (newValue: string) =&gt; {
      setSelected(true);
      let currenIsInvalid = false;
      if (newValue) {
        try {
          const momentValue = moment.utc(newValue, true);
          if (!momentValue.isValid()) {
            currenIsInvalid = true;
          } else {
            const newInputValue = moment.utc(newValue).format(getDisplayFormat());
            setInputValue(newInputValue || '');
            if (onChange &amp;&amp; newInputValue) {
              onChange(moment.utc(newInputValue, getValueFormat()).toDate());
            }
          }
        } catch (e) {
          currenIsInvalid = true;
        }
      } else {
        setInputValue(newValue);
        if (onChange &amp;&amp; newValue) {
          onChange(moment.utc(newValue, getValueFormat()).toDate());
        }
      }
      setIsInvalid(currenIsInvalid);
    },
    [getDisplayFormat, getValueFormat, onChange],
  );

  const setComputedValue = useCallback(
    (momentValue: ValueType) =&gt; {
      const newValue = momentValue &amp;&amp; moment.utc(momentValue, getValueFormat()).toDate();
      setInputValue(momentValue ? getValue(momentValue) : inputValue);
      setValue(newValue);
      const $input = $(inputRefProp.current);
      if ($input) {
        $input.datetimepicker('setOptions', { value: propValue });
      }
    },
    [getValue, getValueFormat, inputValue, inputRefProp, propValue],
  );

  const initPlugin = useCallback(() =&gt; {
    if (inputRefProp &amp;&amp; inputRefProp.current) {
      let $input = $(inputRefProp.current);
      const inputCurrentValue = value || defaultValue;
      const defaultOptions = {
        formatTime: displayTimeFormat,
        formatDate: displayDateFormat,
        dayOfWeekStart: 1,
      };
      const pickerOptions = {
        allowDates: [],
        ...defaultOptions,
        ...options,
      };
      const allowDateTimes = resolvePath(pickerOptions, 'allowDateTimes');
      if (allowDateTimes) {
        pickerOptions.allowDates = allowDateTimes.map((dt: moment.MomentInput) =&gt;
          moment.utc(dt, ISO_DATETIME_FORMAT).format(pickerOptions.formatDate),
        );
      }
      setFormatter();
      setInputValue('');
      $input.datetimepicker('destroy');
      $input = $input.datetimepicker({
        ...pickerOptions,
        format: getDisplayFormat(),
        datepicker,
        timepicker,
        onChangeDateTime: onChangeHandler,
        value: inputCurrentValue,
        scrollInput,
        maxDate,
        lazyInit: true,
      });
    }
    // This function has to run only once since it initialize the datetimepicker plugin
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  useEffect(() =&gt; {
    $.datetimepicker.setLocale(locale);
    initPlugin();
  }, [initPlugin, locale]);

  useEffect(() =&gt; {
    if (propValue) {
      if (propValue !== value) {
        if (earlierDate) {
          setComputedValue(new Date());
        } else {
          setComputedValue(propValue);
        }
      }
    } else {
      setInputValue('');
      setValue('');
    }
    // This function should run whenever the propValue changes
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [propValue]);

  const onBlurHandler = useCallback(
    (newValue: ValueType) =&gt; {
      if (onBlurTyped &amp;&amp; !selected) {
        if (maxDate) {
          const compareDates = compareDesc(
            newValue as Date,
            moment(new Date(maxDate as string).getUTCDate(), getValueFormat()).toDate(),
          );
          if (!newValue || compareDates === 0 || compareDates === 1) onBlurTyped(newValue);
          else onBlurTyped(value);
        } else onBlurTyped(newValue);
      }
      if (onBlur) onBlur(newValue);
    },
    [onBlurTyped, onBlur, selected, getValueFormat, maxDate, value],
  );

  const onBlurInput = useCallback(() =&gt; {
    if (isInvalid) {
      setInputValue('');
      setValue('');
      onBlurHandler('');
    } else {
      if (!inputValue) {
        setInputValue('');
        setValue('');
        onBlurHandler('');
        return;
      }
      const newValue = inputValue &amp;&amp; moment.utc(inputValue, getValueFormat()).toDate();
      setComputedValue(inputValue);
      onBlurHandler(newValue);
    }
  }, [getValueFormat, inputValue, isInvalid, onBlurHandler, setComputedValue]);

  const onChangeHandlerInput = useCallback(
    (newValue: string) =&gt; {
      const re = /^[0-9]{0,2}\.?[0-9]{0,2}\.?[0-9]{0,4}$/;
      let currentIsInvalid = false;
      setSelected(false);
      const validValue = re.test(newValue);
      if (validValue) setInputValue(newValue);
      if (newValue &amp;&amp; validValue) {
        try {
          const momentValue = moment.utc(newValue, getDisplayFormat());
          if (!momentValue.isValid()) {
            currentIsInvalid = true;
          }
        } catch (e) {
          currentIsInvalid = true;
        }
      } else {
        currentIsInvalid = true;
      }
      setIsInvalid(currentIsInvalid);
    },
    [getDisplayFormat],
  );

  const onChangeInput = useCallback(
    (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {
      onChangeHandlerInput(e.target.value);
    },
    [onChangeHandlerInput],
  );

  const renderInput = useCallback(() =&gt; {
    if (customInput) {
      return React.cloneElement(customInput, {
        inputRef,
        placeholder,
        value: inputValue,
        onChange: onChangeInput,
        onBlur: onBlurInput,
      });
    }
    const inputEl = &lt;input type=&quot;text&quot; /&gt;;
    return React.cloneElement(inputEl, {
      inputRef,
      placeholder,
      value: inputValue,
      onChange: onChangeInput,
      onBlur: onBlurInput,
    });
  }, [customInput, inputValue, onBlurInput, onChangeInput, placeholder]);

  return &lt;div className=&quot;datetimepicker&quot;&gt;{renderInput()}&lt;/div&gt;;
};

export default memo(DateTimePicker);
</code></pre>
<p><strong>EDIT :</strong></p>
<p>This what I have regarding unit tests, but they aren't working as expected :</p>
<pre><code>it('should test DateTimePicker default value. ', () =&gt;{
      const { result } = renderHook(() =&gt; &lt;DateTimePicker/&gt;)
      expect(result.current.value).toBe('')
  });
</code></pre>
",https://stackoverflow.com/questions/72201398/unit-testing-a-memo-component-with-react-hooks-library,"['javascript', 'reactjs', 'unit-testing', 'react-hooks']",148,False,0,0
Problems with Unit Testing in C++ (Visual studio 2022),"<p>Issues with unit testing</p>
<p>I cant really see what is going wrong with that code, but something doesn't include right
relevant files:</p>
<h4>MetaData.h</h4>
<pre><code>#pragma once
#include &lt;string&gt;
enum ChessColor
{
    White,
    Black
};
enum PieceType
{
   King,
   Queen,
   Rook,
   Bishop,
   Knight,
   Pawn,
   None
};
const int BOARD_SIZE = 8;

std::string getLongNameOfChessType(PieceType* type);
std::string getShortNameOfChessType(PieceType* type);

std::string getLongNameOfChessColor(ChessColor* color);
std::string getShortNameOfChessColor(ChessColor* color);
</code></pre>
<h4>MetaData.cpp</h4>
<pre><code>#include &quot;MetaData.h&quot;

std::string getLongNameOfChessType(PieceType* type)
{
    switch (*type)
    {
    case PieceType::King:
        return &quot;King&quot;;
    case PieceType::Queen:
        return &quot;Queen&quot;;
    case PieceType::Rook:
        return &quot;Rook&quot;;
    case PieceType::Bishop:
        return &quot;Bishop&quot;;
    case PieceType::Knight:
        return &quot;Knight&quot;;
    case PieceType::Pawn:
        return &quot;Pawn&quot;;
    default:
        return &quot;NoType&quot;;
    }
}

std::string getShortNameOfChessType(PieceType* type)
{
    switch (*type)
    {
    case PieceType::King:
        return &quot;K&quot;;
    case PieceType::Queen:
        return &quot;Q&quot;;
    case PieceType::Rook:
        return &quot;R&quot;;
    case PieceType::Bishop:
        return &quot;B&quot;;
    case PieceType::Knight:
        return &quot;N&quot;;
    case PieceType::Pawn:
        return &quot;P&quot;;
    default:
        return &quot;NoType&quot;;
    }
}
std::string getLongNameOfChessColor(ChessColor* color)
{
    switch (*color)
    {
    case ChessColor::White:
        return &quot;White&quot;;
    case ChessColor::Black:
        return &quot;Black&quot;;
    default:
        return &quot;NoColor&quot;;
    }
}
std::string getShortNameOfChessColor(ChessColor* color)
{
    switch (*color)
    {
    case ChessColor::White:
        return &quot;W&quot;;
    case ChessColor::Black:
        return &quot;B&quot;;
    default:
        return &quot;NoColor&quot;;
    }
}
</code></pre>
<h4>ChessTest.cpp</h4>
<p>The test file.</p>
<pre><code>#include &quot;pch.h&quot;
#include &quot;CppUnitTest.h&quot;
#include &lt;MetaData.h&gt;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace ChessTest
{
    TEST_CLASS(ChessTest)
    {
    public:
        
        TEST_METHOD(TestMethod1)
        {
            ChessColor c = ChessColor::Black;
            std::string actual = &quot;B&quot;;
            std::string trying = getShortNameOfChessColor(&amp;c);
            Assert::AreEqual(actual,trying);
        }
    };
}
</code></pre>
<p>So the errors i get are these</p>
<pre><code>Error   LNK2019 unresolved external symbol &quot;class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; __cdecl getShortNameOfChessColor(enum ChessColor *)&quot; (?getShortNameOfChessColor@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PEAW4ChessColor@@@Z) referenced in function &quot;public: void __cdecl ChessTest::ChessTest::TestMethod1(void)&quot; (?TestMethod1@ChessTest@1@QEAAXXZ)    ChessTest   C:\Users\censoredUsername\Desktop\prog\Chess\ChessProject\ChessTesting\ChessTest\ChessTest.obj  1
</code></pre>
<p>A few warnings</p>
<pre><code>Warning C26812  The enum type 'PieceType' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).    ChessProject    C:\Users\censoredUsername\Desktop\prog\Chess\ChessProject\ChessProject\MetaData.cpp 3
Warning C26812  The enum type 'ChessColor' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).   ChessProject    C:\Users\censoredUsername\Desktop\prog\Chess\ChessProject\ChessProject\MetaData.cpp 44  
Warning C26812  The enum type 'ChessColor' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).   ChessTest   C:\Users\censoredUsername\Desktop\prog\Chess\ChessProject\ChessTesting\ChessTest\ChessTest.cpp  14  
</code></pre>
<p>Error 2</p>
<pre><code>Error   LNK1120 1 unresolved externals  ChessTest   C:\Users\censoredUsername\Desktop\prog\Chess\ChessProject\x64\Debug\ChessTest.dll   1   
</code></pre>
<p>Some Extra info</p>
<p>I made a project, added some basic files and wanted to do a test driven development.<br />
Thus i added a Native Unit Test Project to my current Project.
Described here: <a href=""https://learn.microsoft.com/en-us/visualstudio/test/writing-unit-tests-for-c-cpp?view=vs-2022"" rel=""nofollow noreferrer"">MS Description to add unit tests</a></p>
<p>I coded in a lot of languages before, but have the most experience with java/c# (and as you know, these are very different to cpp)</p>
<p>I appreciate every comment/input for that matter.</p>
",https://stackoverflow.com/questions/72707644/problems-with-unit-testing-in-c-visual-studio-2022,"['c++', 'visual-studio', 'unit-testing', 'enums', 'include']",150,True,0,1
Unit testing for Golang squirrel query having VALUES clause,"<p>I am using golang,squirrel query builder tool and postgres DB.
I am having a query conatining a VALUES clause for &quot;constant table&quot; building.
The indiviual column values inside the VALUES clause are generated from an external map.
That part of the query would be similar to the one given below.</p>
<pre><code>VALUES('us','us'),('ca','ca'),('se','eu').........
</code></pre>
<p>i am using the sqlmock library of go. ref:-https://pkg.go.dev/github.com/DATA-DOG/go-sqlmock@v1.5.0</p>
<p>In the testing phase, I am checking whether the raw query is as expected.
But the problem i am facing is like, the order of the individual rows inside the VALUES
clause keeps on changing. So i cannot frame an exact expected query to match the actual sql query.</p>
",https://stackoverflow.com/questions/72554758/unit-testing-for-golang-squirrel-query-having-values-clause,['go'],370,False,0,0
MSW unit testing API in success &amp; error scenario,"<p>I am using MSW for local development and unit testing.</p>
<pre><code>#API fetch
const { loading, error, data } = useFetch('https://made.up/api/usage')

</code></pre>
<pre><code>#handler.js
import { rest } from 'msw'

export const handlers = [
  rest.get('https://made.up/api/usage', (req, res, ctx) =&gt; {
    return res(
      ctx.status(301),
      ctx.json({
        id: 1,
        firstName: 'John',
      }),
    )
  }),
]

</code></pre>
<pre><code>#server.js
import { setupServer } from 'msw/node'
import { handlers } from './handlers'

export const server = setupServer(...handlers)
</code></pre>
<pre><code>#setupTests.js
beforeAll(() =&gt; {
    server.listen({
      onUnhandledRequest: 'warn',
    })
  })

  afterEach(() =&gt; {
    server.resetHandlers()
  })

  afterAll(() =&gt; {
    server.close()
  })
</code></pre>
<pre><code>#App.test.js
import React from &quot;react&quot;;
import { rest } from &quot;msw&quot;;
import { render, screen } from &quot;@testing-library/react&quot;;
import { server } from &quot;../src/mocks/server&quot;;

import App from &quot;../src/App&quot;;

test(&quot;passes&quot;, async () =&gt; {
  render(&lt;App /&gt;);

  expect(
    // Expect the mocked response to be present in the DOM.
    await screen.findByText(`{&quot;id&quot;:1,&quot;firstName&quot;:&quot;John&quot;}`)
  ).toBeInTheDocument();
});

test(&quot;error&quot;, async () =&gt; {
  server.use(
    rest.get(&quot;https://made.up/api/usage&quot;, (req, res, ctx) =&gt; {
      return res(
        ctx.status(500),
        ctx.json({
          error: &quot;error&quot;
        })
      );
    })
  );
  render(&lt;App /&gt;);

  expect(
    // Expect the mocked error response to be present in the DOM.
    await screen.findByText(&quot;Error: error}&quot;)
  ).toBeInTheDocument();
});
</code></pre>
<p>I am overriding the API handler to test the error scenario. Both the tests do not pass when run together. If I run them individually, they work fine.</p>
<p>Am I missing any step? or we can test the same API for different responses in some other way using MSW?</p>
",https://stackoverflow.com/questions/71764462/msw-unit-testing-api-in-success-error-scenario,"['reactjs', 'unit-testing', 'msw']",1843,False,0,1
Laravel unit testing. Failed asserting that false is true,"<p>Im trying to test my reset password functionality but im getting the error. Can someone help me? Where am i wrong? Thanks.</p>
<pre><code>    public function test_it_reset_password_with_valid_token()
{
    // Given
    Event::fake();
    $user = Customer::factory()-&gt;create();

    // When
    $response = $this-&gt;post('/password/reset', [
        'token' =&gt; $this-&gt;getValidToken($user),
        'email' =&gt; $user-&gt;email,
        'password' =&gt; 'new-password',
        'password_confirmation' =&gt; 'new-password',
    ]);

    // Then
    $this-&gt;assertEquals($user-&gt;email, $user-&gt;fresh()-&gt;email);
    $this-&gt;assertTrue(Hash::check('new-password', $user-&gt;fresh()-&gt;password));
    $this-&gt;assertAuthenticatedAs($user);

    Event::assertDispatched(PasswordReset::class);
}
</code></pre>
<p><a href=""https://i.stack.imgur.com/7zW2x.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7zW2x.png"" alt=""Here is error message"" /></a></p>
",https://stackoverflow.com/questions/72305719/laravel-unit-testing-failed-asserting-that-false-is-true,"['laravel', 'unit-testing']",230,False,0,0
Unit Testing Replace remote API Server with predefined response,"<p>So, I have a server running FastAPI which will make a API call to a remote API upon request.
I am developping unit-testing for this application, but here comes the question:
Can I, for the purpose of the test, replace a legit remote API server response by a predefined response ?</p>
<p>Example of the tests runned:</p>
<pre class=""lang-py prettyprint-override""><code>from fastapi.testclient import TestClient
from web_api import app

client = TestClient(app)


def test_get_root():
    response = client.get('/')
    assert response.status_code == 200
    assert response.json() == {&quot;running&quot;: True}

</code></pre>
<p>And the my server</p>
<pre class=""lang-py prettyprint-override""><code>from fastapi import FastAPI

app = FastAPI()

@app.get(&quot;/&quot;)
def home():
    return {&quot;running&quot;: True}
</code></pre>
<p>This is a simple example, but on other endpoints of my API I would call an external remote API</p>
<pre class=""lang-py prettyprint-override""><code>  def call_api(self, endpoint:str, params:dict):
        url = self.BASEURL + urllib.parse.quote(endpoint)
        try:
            response = requests.get(url, params=params)
            response.raise_for_status()
        except requests.exceptions.HTTPError as error:
            print(error)
        return response
</code></pre>
<p>Because I want to test the response of MY API, I would like to replace the remote API with a predefined response.</p>
<p>Also, one user request can end-up in multiple background API requests with transformed pieces of data.</p>
<h3>Edit</h3>
<p>Here are some more details on the structure of the application:</p>
<pre><code>@app.get(&quot;/stuff/.......&quot;,  
         # lots of params
        )
def get_stuff_from_things(stuff:list, params):
    api = API(api_key=...)
    # Do some stuff with the params
    things = generate_things_list(params)
    api.search_things(params)
    # Check the result
    # do some other stuff
    return some_response


</code></pre>
<pre><code>class API:
    BASE_URL = 'https://api.example.com/'

    def search_things(self, params):
        # Do some stuff
        # like putting stuff in the params
        for s in stuff:
            s.update(self.get_thing(params)) # -&gt; get_thing()
        # Do some more stuff
        return stuff

    # get_thing &lt;- search_things
    def get_thing(self, params...):
        #  Some stuff
        results = self.call_api('something', params) # -&gt; call_api()
        json = results.json()
        #  Some more stuff
        things = []
        for thing in json['things']:
            t = Thing(thing)
            things.append(t)
        return things

    # call_api &lt;- get_thing
    def call_api(self, endpoint:str, params:dict):
        url = self.BASEURL + urllib.parse.quote(endpoint)
        try:
            response = requests.get(url, params=params)
            response.raise_for_status()
        except requests.exceptions.HTTPError as error:
            print(error)
        self.last_response = response
        return response


</code></pre>
<p><em>Nb. That is pseudo-code, I simplified the functions by removing the parameters, etc.</em></p>
<p>I hope it is clear, thanks for your help.</p>
",https://stackoverflow.com/questions/72958118/unit-testing-replace-remote-api-server-with-predefined-response,"['python', 'pytest', 'fastapi']",226,True,0,2
How to assert sending an email in unit testing,"<p>I have a method to send an email. How can I write a unit test to verify this method. I'm using MS test with shouldly</p>
<pre><code> public async Task SendEmail(string Id, string exception)
        {
            SendEmailModel sendEmailmodel = new SendEmailModel();
            var emailAddress = _emailConfiguration.ToEmailAddress;
            string[] toAddresses = emailAddress.Split(',', 10, StringSplitOptions.RemoveEmptyEntries);
            sendEmailmodel.Subject = &quot;Subject&quot;;
            sendEmailmodel.ToAddresses = toAddresses;
            sendEmailmodel.Message = exception;
            await _emailService.SendEmailAsync(sendEmailmodel);
        }
</code></pre>
<p>I tried writing test method as follows</p>
<pre><code>[TestMethod]
        public async Task SendEmail_should_send_email()
        {
            SendEmailModel sendEmailmodel = new SendEmailModel();
            var emailAddress = &quot;kumara@gmail.com&quot;;
            string[] toAddresses = emailAddress.Split(',', 10, StringSplitOptions.RemoveEmptyEntries);
            sendEmailmodel.Subject = &quot;HA test email&quot;;
            sendEmailmodel.ToAddresses = toAddresses;
            sendEmailmodel.Message = &quot;test&quot;;
            await emailService.SendEmailAsync(sendEmailmodel);

            A.CallTo(() =&gt; this.emailService.SendEmailAsync(sendEmailmodel));

           //how to assert 
           await this.limitsLogic.SendEmail(&quot;120&quot;, &quot;test&quot;);
            
        }
</code></pre>
",https://stackoverflow.com/questions/74311316/how-to-assert-sending-an-email-in-unit-testing,"['c#', 'shouldly']",35,True,0,1
Vector VRL Unit testing returning undefined fuction for strlen,"<p><a href=""https://vector.dev/docs/reference/vrl/functions/#strlen"" rel=""nofollow noreferrer"">https://vector.dev/docs/reference/vrl/functions/#strlen</a>
Hello everyone
I have a transform containing this field and everything is working well and logs are good :</p>
<pre><code>    .msg = slice(.message, start: int!(strlen(join!(arrayvar, separator: &quot; &quot;))) , end: int!(strlen(.message))) ?? &quot;undefined&quot;
</code></pre>
<p>BUT unit testing return <code>undefined function did you mean &quot;string&quot;?</code> on strlen function.</p>
<p>Anyone has an idea please?</p>
",https://stackoverflow.com/questions/72363119/vector-vrl-unit-testing-returning-undefined-fuction-for-strlen,"['logging', 'yaml', 'datadog', 'vector-vrl']",261,True,0,1
Unit Testing Vue with Jest and Vue Test Utils,"<p>I'm brand new at Unit Testing with vue.
I'm trying to unit test a navigation vue component. I started out easy, I just wanted to test a method that just makes a boolean false(triggered by an on click). I am also using vuetify. I somewhat managed to mimic a button and then my hope is that the variable I'm passing (showLoginDrawer) returns false in my unit test. My error is TypeError: _vm.is.has is not a function which relates to a different part of my code, I think I'm missing something but I couldn't find anything online about it.</p>
<p>Below I've included the component and my testing file.</p>
<pre><code>//Nav.vue
&lt;template&gt;
  &lt;v-btn
        :to=&quot;{ name: 'home' }&quot;
        aria-label=&quot;Home button&quot;
        @click=&quot;hideDiv()&quot;
   &gt;
   &lt;/v-btn&gt;

      &lt;div&gt;
        &lt;transition name=&quot;nav-fade&quot;&gt;
          &lt;component v-bind:is=&quot;drawerSection&quot;&gt;&lt;/component&gt;
        &lt;/transition&gt;
      &lt;/div&gt;

&lt;/template&gt;
&lt;script&gt;
     data() {
      return {
        drawerSection: function () {
          if (this.is.has('learning')) {
            return 'nav-learning'
          } else {
            return 'nav-explore'
          }
        },
      }
    },
    methods: {
      hideDiv() {
        if (!this.appState.restrictedAccessAlert)
          this.appState.showLoginDrawer = false
      }
}
&lt;/script&gt;
&lt;style&gt;//disregard&lt;/style&gt;

</code></pre>
<pre><code>//Nav.spec.js
import Vue from 'vue'
import Vuex from 'vuex'
import Vuetify from 'vuetify'
import { shallowMount, mount } from '@vue/test-utils'
import Nav from '@/components/Nav'


const localVue = createLocalVue()
localVue.use(Vuetify)
localVue.use(Vuex)

describe('Testing Nav component', () =&gt; {
    let vuetify
    beforeEach(() =&gt; {
      vuetify = new Vuetify()
    })
    test('Test Button click when logged out', () =&gt; {
    const wrapper = mount(Navigation, {
      data() {
        return {
          appState: {
            showLoginDrawer: true,
            lastCapabilityPath: '',
            restrictedAccessAlert: false,
          },
          is: 'learning',
          localVue,
          vuetify,
        }
      },
    })

    const event = jest.fn()
    const button = wrapper.findAll('.v-btn').at(0)
    expect(button.text()).toContain('My Profile')

    button.vm.$on('click', event)
    expect(event).toHaveBeenCalledTimes(0)
    expect(wrapper.vm.showLoginDrawer).toBeTruthy()
    button.trigger('click')
    expect(event).toHaveBeenCalledTimes(1)
    expect(wrapper.vm.showLoginDrawer).toBeFalsy()
  })
})
</code></pre>
<p>I get the error:</p>
<p><code>TypeError: _vm.is.has is not a function</code></p>
<p>Thank you for any help!</p>
",https://stackoverflow.com/questions/71712969/unit-testing-vue-with-jest-and-vue-test-utils,"['javascript', 'vue.js', 'unit-testing', 'jestjs', 'vue-test-utils']",846,True,0,2
AspNetCore 6 / Unit Testing with UnserManager without Mocking it,"<p>I am using AspNetCore 6 and trying to use the UserManager and RoleManager in my UnitTests.
I don't like to mock them because I want to test scenarios where I need access to different users stored in the database.
I have found a way to get to the UserManager, but then the DB context seems to be different.
I have oriented myself on <a href=""https://terencegolla.com/.net/unit-testing-asp-net-core-identity/"" rel=""nofollow noreferrer"">this</a></p>
<pre class=""lang-cs prettyprint-override""><code>[TestClass]
public abstract class BaseTest
{
    internal DBContext DBContext;
    internal UserManager&lt;ApplicationUser&gt; AppUserManager;
    internal RoleManager&lt;ApplicationRole&gt; AppRoleManager;
    internal HttpContext HttpContext;
    internal IConfiguration AppConfiguration = new ConfigurationBuilder().AddJsonFile(&quot;appsettings.Test.json&quot;).Build();

    [TestInitialize]
    public virtual void TestSetup()
    {
        // Mock the Http Context accessor
        var mockHttpContextAccessor = MockHttpContextAccessor(&quot;MrX&quot;, &quot;MrX&quot;);
        HttpContext = mockHttpContextAccessor.Object.HttpContext;

        IServiceCollection serviceCollection = new ServiceCollection();

        // Add the DbContext
        serviceCollection
            .AddDbContext&lt;DBContext&gt;(options =&gt;
            {
                options.UseOracle(AppConfiguration[&quot;OracleUnitTestDbConnection&quot;])
                .UseLazyLoadingProxies()
                .EnableSensitiveDataLogging();
            })
            .AddSingleton(mockHttpContextAccessor.Object)
            .AddLogging()
            .AddIdentity&lt;ApplicationUser, ApplicationRole&gt;()
            .AddEntityFrameworkStores&lt;DBContext&gt;()
            .AddUserManager&lt;UserManager&lt;ApplicationUser&gt;&gt;()
            .AddRoleManager&lt;RoleManager&lt;ApplicationRole&gt;&gt;()
            .AddDefaultTokenProviders();

        DBContext = serviceCollection.BuildServiceProvider().GetService&lt;DBContext&gt;();

        // When initializing like this it seems to get a different DBContext than the one above  
        AppUserManager = serviceCollection.BuildServiceProvider().GetService&lt;UserManager&lt;ApplicationUser&gt;&gt;();

        AppRoleManager = serviceCollection.BuildServiceProvider().GetService&lt;RoleManager&lt;ApplicationRole&gt;&gt;();

        DBContext.Database.BeginTransaction();          // Transaction will be Rollbacked in [TestCleanup]

        MrXRole = CreateRole(&quot;MrXRole&quot;);                // Adds the ApplicationRole &quot;MrXRole&quot; to DBContext
        MrX = CreateUser(&quot;MrX&quot;, MrXRole, &quot;Test1234!&quot;);  // Adds the ApplicationUser &quot;MrX&quot; to DBContext
        MrYRole = CreateRole(&quot;MrYRole&quot;);                // Adds the ApplicationRole &quot;MrYRole&quot; to DBContext
        MrY = CreateUser(&quot;MrY&quot;, MrYRole, &quot;Test1234!&quot;);  // Adds the ApplicationUser &quot;MrY&quot; to DBContext

        DBContext.SaveChanges();

        var test1 = DBContext.Users.Count();            // test1 = 2  --&gt; as expected
        var test2 = AppUserManager.Users.Count();       // test2 = 0  --&gt; not expected --&gt; different DBContext
    }
}
</code></pre>
<p><code>test2</code> probably has a different DB context. When I debug, I don't see the two previously created users in the AppUserManager context. In the DbContext they are there.</p>
<p>I really hope someone could help me out here as I invested a lot of time on this without any success</p>
",https://stackoverflow.com/questions/71525002/aspnetcore-6-unit-testing-with-unsermanager-without-mocking-it,"['c#', 'unit-testing', 'asp.net-core', '.net-core', 'asp.net-identity']",54,False,0,1
"Unit testing nested function, third-party function mocking. Jest","<p>I have a third-party function, return from a parent function, I am able to test the parent function call, toHaveBeenCalled but the nested return statement is not being tested. Definitely it needs to be mocked as it's a third-party function. The function looks like below:</p>
<pre><code>import * as _html2canvas from 'html2canvas';
// tslint:disable-next-line: no-any
const html2canvas: any = _html2canvas;

export const  downloadElement = (props: string, imageName: string): HTMLElement =&gt; {
const captureElement = document.querySelector(props);
const canvasBg = window.getComputedStyle(document.body, null).getPropertyValue('background-color');

const options = {
 scale: 0.8,
 backgroundColor: canvasBg,
 removeContainer: true,
 allowTaint: true
};

return html2canvas(captureElement, options)
   .then((canvas: HTMLCanvasElement) =&gt; {
     canvas.style.display = 'none';
     document.body.appendChild(canvas);
     return canvas;
   })
   .then((canvas: HTMLCanvasElement) =&gt; {
     const image = canvas
       .toDataURL('image/png')
       .replace('image/png', 'image/octet-stream');
     const a = document.createElement('a');
     a.setAttribute('download', `${imageName}.png`);
     a.setAttribute('href', image);
     a.click();
     canvas.remove();
   });
};

</code></pre>
<p>I am trying to cover: return html2canvas... till the end.</p>
<p>I tried-</p>
<pre><code>jest.mock('html2canvas', () =&gt; {
    html2canvas: jest.fn();
})
</code></pre>
<p>and</p>
<pre><code>jest.mock('html2canvas', () =&gt; () =&gt; ({
    then : jest.fn(() =&gt; ({
        then : jest.fn(() =&gt; ({
            toHaveBeenCalled : jest.fn().mockResolvedValue({})
        }))
    }))
}));

</code></pre>
<pre><code>
        const element = document.createElement('div');
        element.id = &quot;test&quot;;
        document.body.appendChild(element);
        let de = downloadElement('test', 'testImage') as any;

        expect(de).toBeCalled();

</code></pre>
<p>I tried mockResolvedValue as well.</p>
<pre><code>de = jest.fn().mockResolvedValue({});
</code></pre>
<p>Looks like I can't find the way to cover it. Any help appreciated.</p>
",https://stackoverflow.com/questions/72779851/unit-testing-nested-function-third-party-function-mocking-jest,"['javascript', 'reactjs', 'unit-testing', 'jestjs', 'html2canvas']",32,False,0,0
lateinit property fakeAuthRepository has not been initialized unit testing,"<p>I am using unit testing when I run test I am getting following exception</p>
<p>ateinit property fakeAuthRepository has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property fakeAuthRepository has not been initialized</p>
<p>below my ViewModel test where test giving an exception</p>
<pre><code>internal class SignInViewModelTest{
    private val _login =  MutableStateFlow&lt;UiStateObject&lt;SignInResponse&gt;&gt;(UiStateObject.EMPTY)

         @Mock
        lateinit var backendApi:BackendApi

    lateinit var fakeAuthRepository: FakeAuthRepository
    lateinit var authRepository: AuthRepository
    private lateinit var viewModel: SignInViewModel
    @Before
    fun setUp() {

        MockitoAnnotations.initMocks(this)
        fakeAuthRepository = FakeAuthRepository(backendApi)
        authRepository = AuthRepository(backendApi)
        viewModel = SignInViewModel(authRepository)

    }

    var login = _login

    @Test
    fun `testing repository`() = runBlockingTest {

        val fake = fakeAuthRepository.login(&quot;kyodgorbek@gmail.com&quot;, &quot;12345678&quot;, &quot;android&quot;, &quot;123455&quot;)
        val real = authRepository.login(&quot;kyodgorbek@gmail.com&quot;, &quot;12345678&quot;, &quot;android&quot;, &quot;123455&quot;)
        assertEquals(fake, real)


    }



}
</code></pre>
",https://stackoverflow.com/questions/73787027/lateinit-property-fakeauthrepository-has-not-been-initialized-unit-testing,"['android', 'unit-testing', 'kotlin', 'mockito', 'android-viewmodel']",814,True,0,1
Unit testing net5.0 ASP.Net projects with the NUnit console?,"<p>I've recently been trying to implement automated unit test within my Jenkins pipeline using the nunit3-console.exe, for multiple Test projects that implement Microsoft and Asp.Net related functionnalities within their set-up methods.<br />
The test projects are in Net 5.0 and trying to run them will give me this error:</p>
<pre><code>    1) SetUp Error : MyProjectPath
System.IO.FileNotFoundException : Could not load file or assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=5.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'. The specified file could not be found.
   at MyProjectTest.StartTest()
</code></pre>
<p>This is obviously not the only missing assembly, as it requires many of the Microsoft.Extensions and Asp.Net related dll to functions. Manually supplying said DLLs to the Test folder directory does allow the command to properly run, but this is obviously not a great solution in the long run. Supplying the missing assemblies to the GAC would also fix the problem, but only as long as we don't update any of our packages.</p>
<p>What would be the intended workflow when a Test requires such DLLs? Where should they be placed so that they can easily be maintained and/or replaced after updates? I've tried using the .Net Core console runner hoping it might include these DLLs as well.</p>
<p>Thanks a lot for your help!</p>
",https://stackoverflow.com/questions/73660095/unit-testing-net5-0-asp-net-projects-with-the-nunit-console,"['unit-testing', 'jenkins', 'nunit', 'nunit-console']",55,False,0,1
Unit Testing Flink Jobs with new Data Source API,"<p>in the past i unit tested the flink jobs by writing the job with pluggable Sources/Sink and then mocked them via simple <code>Source-/SinkFunctions</code>. Like this:</p>
<pre class=""lang-java prettyprint-override""><code>public class Example {

    private static SourceFunction&lt;String&gt; someSource;
    private static SourceFunction&lt;String&gt; someOtherSource;
    private static SinkFunction&lt;String&gt; someSink;

    Example(
        SourceFunction&lt;String&gt; someSource,
        SourceFunction&lt;String&gt; someOtherSource,
        SinkFunction&lt;String&gt; someSink
    ) {
        this.someSource = someSource;
        this.someOtherSource = someOtherSource;
        this.someSink = someSink;
    }
    
    void build(StreamExecutionEnvironment env) {
        /*
        ... build your logic here ... 
        */
    }
    
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        
        Example(
            new FlinkKafkaConsumer&lt;String&gt;(...),
            new FlinkKafkaConsumer&lt;String&gt;(...),
            new FlinkKafkaProducer&lt;String&gt;(...)
        ).build(env);
        
        env.execute();
    }
}
</code></pre>
<p>This way i could easily test the whole job by just exchange the real KafkaSinks &amp; Sources with custom <code>Sink-/SourceFunctions</code>.</p>
<p>The new <a href=""https://nightlies.apache.org/flink/flink-docs-release-1.15/docs/dev/datastream/sources/#use-the-source"" rel=""nofollow noreferrer"">DataSources</a> are much more complex for simply implementing it for test cases.
Even if i would implement it it would end in a generic hell to make this injectable at the constructor.
So i was wondering whats the best approach is to unit test the whole job without bring up e.g. a complete Kafka cluster.</p>
<p>Are there any ideas or solutions ?</p>
",https://stackoverflow.com/questions/73334129/unit-testing-flink-jobs-with-new-data-source-api,"['unit-testing', 'apache-flink', 'flink-streaming']",352,False,0,1
How to structure unit testing for a WXpython application?,"<p>I'm currently working on a project with two other contributors. I've been assigned to conduct unit tests on existing code using Pytest and Pytest coverage. We're building a GUI app using WXpython and I cannot figure out how to write these unit tests. Any guidance on how to do this properly would be of great help for me. This is just a small snippet of code out of many other modules in the project.</p>
<pre><code>class Chart(wx.Frame):
    def __init__(self, parent, title, chart_type, filter_parameters, data):
        wx.Frame.__init__(self, parent, title=title, size=(600, 600))
        self.chart_type = chart_type
        self.filter_parameters = filter_parameters
        self.data = data
        self.initialise_gui()

    def initialise_gui(self):
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.select_chart()
        self.statusbar = wx.StatusBar(self)
        self.statusbar.SetFieldsCount(len(self.filter_parameters))

        col = 0
        for i in self.filter_parameters:
            self.statusbar.SetStatusText(i + ': ' + str(self.filter_parameters[i]), col)
            col += 1

        self.SetStatusBar(self.statusbar)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.EXPAND | wx.LEFT | wx.TOP)
        self.SetSizerAndFit(self.sizer)

        self.Show(True)
</code></pre>
",https://stackoverflow.com/questions/73943970/how-to-structure-unit-testing-for-a-wxpython-application,"['python', 'unit-testing', 'pytest']",34,False,0,0
Unit testing of a python based project using Jenkinsfile,"<p>I am trying to do the unit test of a repository which is based on python. Here is the repo: <a href=""https://github.com/Alok018/giskardpy/tree/noetic-devel"" rel=""nofollow noreferrer"">https://github.com/Alok018/giskardpy/tree/noetic-devel</a>
In jenkins, I have installed python and junit plugin.
This <a href=""https://github.com/Alok018/giskardpy/blob/noetic-devel/Jenkinsfile"" rel=""nofollow noreferrer"">Jenkinsfile</a> is using to build the repo inside the ros workspace. After creating an image, I want to test those <a href=""https://github.com/Alok018/giskardpy/tree/noetic-devel/test"" rel=""nofollow noreferrer"">python</a> examples.</p>
",https://stackoverflow.com/questions/71165990/unit-testing-of-a-python-based-project-using-jenkinsfile,"['unit-testing', 'jenkins', 'junit', 'jenkins-pipeline']",114,False,0,0
Unit testing code coverage for multer Node.js using Jest,"<p>I am trying to cover the lines and functions for code coverage of the simple multer file in Node.js but I am not getting where I am going wrong.</p>
<p>Here is the file:</p>
<p>fileUpload.js</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>const express = require(""express"");
const multer = require(""multer"");
const path = require(""path"");

const storage = multer.diskStorage({
  destination: (req, file, callBack) =&gt; {
    callBack(null, ""uploads"");
  },
  filename: (req, file, callBack) =&gt; {
    callBack(null, `${file.originalname}`);
  },
});

const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) =&gt; {
    if (file.mimetype == ""image/png"" || file.mimetype == ""image/jpg"" || file.mimetype == ""text/plain"") {
      cb(null, true);
    } else {
      cb(null, false);
      return cb(new Error('Only .png, .jpg, .txt and .jpeg format allowed!'));
    }
  }
})
module.exports = {
  upload,
  express
};</code></pre>
</div>
</div>
</p>
<p>fileUpload.test.js</p>
<pre class=""lang-js prettyprint-override""><code>const multer = require('multer')
const fileStorage = require(&quot;../file-storage&quot;);

jest.mock('multer', () =&gt; {
  const multer = () =&gt; ({
    diskStorage: () =&gt; {
      return {
        destination: (req, res, callBack) =&gt; {
          callBack(null, 'uploads')
        },
        filename: (req, res, callBack) =&gt; {
          req.body = {
            userName: 'testUser'
          }
          req.files = [{
            originalname: 'sample.name',
            mimetype: 'sample.type',
            path: 'sample.url',
            buffer: Buffer.from('whatever'), // this is required since `formData` needs access to the buffer
          }, ]
          return callBack()
        }
      }

    },
  })
  multer.diskStorage = () =&gt; jest.fn()
  return multer

})

describe('65317652', () =&gt; {
  const upload = fileStorage.upload
  it('should pass', () =&gt; {
    const storage = upload.diskStorage();
    const uploadData = multer({
      storage: storage
    });
    expect(uploadData).toBeTruthy();
  });
});
</code></pre>
<p>I have searched plenty of blogs but didn't find any proper solution.</p>
<p><a href=""https://i.stack.imgur.com/pRJ4I.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/pRJ4I.png"" alt=""enter image description here"" /></a></p>
<p>How to cover those lines?</p>
",https://stackoverflow.com/questions/73661246/unit-testing-code-coverage-for-multer-node-js-using-jest,"['node.js', 'jestjs']",325,False,0,1
Unit testing for component with private @ViewChild child component?,"<p>How to write Unit testing for component with private @ViewChild child component?</p>
<p>Note: I can't change or update the main component codes just for writing test case.</p>
<p>Main component Code:</p>
<pre><code>import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child/child.component';

@Component({
  selector: 'app-root',
  template: `
    &lt;button type=&quot;button&quot; (click)=&quot;update()&quot;&gt;Update&lt;/button&gt;
    &lt;br&gt;
    &lt;app-child&gt;&lt;/app-child&gt;`
})
export class AppComponent {
  @ViewChild(ChildComponent, { static: false })
  private childComponent!: ChildComponent;
    
  flag=false;
  update() {
        this.childComponent.updateTimeStamp();
        this.flag=true;
      }
}
</code></pre>
<p>Unit test code:
Issue is when I try to supply mock object for app.childComponent in below code. Though it works if I add // @ts-ignore but I don't think its correct. There must be a way to mock private ViewChild component.</p>
<pre><code>import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () =&gt; {
  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ]
    }).compileComponents();
  });

  
  it('should call update', () =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app.flag).toBe(false);
   **// app.update(); //fails**
  });
</code></pre>
<p>if it would have been non-private member, I could mock the child component like this.</p>
<pre><code>  it('should call update', () =&gt; {
     const fixture = TestBed.createComponent(AppComponent);
     const app = fixture.componentInstance;
     app.childComponent = &lt;ChildComponent&gt;{updateTimeStamp:()=&gt;{}}
     expect(app.flag).toBe(false);
     app.update(); 
     expect(app.flag).toBe(true);
   });


});
</code></pre>
",https://stackoverflow.com/questions/73985408/unit-testing-for-component-with-private-viewchild-child-component,"['angular', 'unit-testing', 'angular-test']",201,False,0,1
Unit testing a class that depends on an async function,"<p>I have a view model with a state property enum that has 3 cases.</p>
<pre><code>protocol ServiceType {
    func doSomething() async
}

@MainActor
final class ViewModel {

    enum State {
        case notLoaded
        case loading
        case loaded
    }

    private let service: ServiceType
    var state: State = .notLoaded

    init(service: ServiceType) {
        self.service = service
    }

    func load() async {
        state = .loading
        await service.doSomething()
        state = .loaded
    }
}
</code></pre>
<p>I want to write a unit test that asserts that after <code>load</code> is called but before the async function returns, state == .loading .</p>
<p>If I was using completion handlers, I could create a spy that implements ServiceType, captures that completion handler but doesn't call it. If I was using combine I could use a schedular to control execution.</p>
<p>Is there an equivalent solution when using Swift's new concurrency model?</p>
",https://stackoverflow.com/questions/72623214/unit-testing-a-class-that-depends-on-an-async-function,"['swift', 'async-await', 'continuations', 'swift-concurrency']",1127,True,3,2
How to mock the results of BigQueryIO.read for unit testing?,"<p>I have an Apache Beam pipeline that reads data from BigQuery using a query that joins multiple tables.
I want to test the entire pipeline locally using mock data (i.e. without connecting to BigQuery).
Can I do this using <code>.withTestServices(fakeBigQueryServices)</code>? I could not find any relevant examples. Has anyone tried this approach or has suggestions on how this can be done?</p>
<pre><code>String query = &quot;Select o.*, p.name from Order o, Product p where o.product_id = p.id and o.created_on = '20220210'&quot;
pipeline.apply(&quot;read data&quot;, BigQueryIO.read(input -&gt; new OrderMapper().mapRow(input.getRecord()))
                                      .withCoder(SerializableCoder.of(Order.class))
                                      .fromQuery(query)
                                      .withoutValidation())
</code></pre>
",https://stackoverflow.com/questions/71168409/how-to-mock-the-results-of-bigqueryio-read-for-unit-testing,"['google-bigquery', 'apache-beam-io']",1085,False,3,1
Unit testing AWS Lambda that uses Layers - Node JS app,"<p>I have a SAM application with a bunch of Lambda functions and layers, using Mocha/Chai to run unit tests on the individual functions.</p>
<p>The issue is, that I am also using Layers for shared local modules.</p>
<p>The SAM project structure is like this..</p>
<p>functions/</p>
<ul>
<li>function-one/
<ul>
<li>app.js</li>
<li>package.json</li>
</ul>
</li>
<li>function-two/
<ul>
<li>app.js</li>
<li>package.json</li>
</ul>
</li>
</ul>
<p>layers/</p>
<ul>
<li>layer-one/
<ul>
<li>moduleA.js</li>
<li>moduleB.js</li>
<li>package.json</li>
</ul>
</li>
<li>layer-two/
<ul>
<li>moduleC.js</li>
<li>package.json</li>
</ul>
</li>
</ul>
<p>According to AWS once the function and layers are deployed, to <code>require</code> a local layer from a function you use this path...</p>
<p><code>const moduleA = require('/opt/nodejs/moduleA');</code></p>
<p>However, that running locally as a unit test wont resolve to anything.</p>
<p>Any idea on how to resolve the paths to the  layer modules when running unit tests?</p>
<p>I could set an ENV var, and then set a base path for the layers based on that, but I was wondering if there was a more elegant solution I was missing...</p>
<p>Is there any way to alias the paths when running Mocha ?</p>
<p>other options are to use <code>SAM INVOKE</code> but that has massive overheads and is more integration testing...</p>
",https://stackoverflow.com/questions/70878598/unit-testing-aws-lambda-that-uses-layers-node-js-app,"['node.js', 'amazon-web-services', 'npm', 'mocha.js', 'aws-sam']",956,True,2,1
How to solve this syncing issue in Unit testing golang?,"<p>Here when I'm printing the activity it is printing them in the order they are getting created but at the time of assertion it is picking up activities in random order and also it is picking expected values in random order. The api that I'm calling mastercontroller have some goroutines and could take time maybe that is the reason but not sure.</p>
<pre><code>for i, param := range params {
gin.SetMode(gin.TestMode)
        w := httptest.NewRecorder()
        ctx, _ := gin.CreateTestContext(w)

        ctx.Request = &amp;http.Request{
            URL:    &amp;url.URL{},
            Header: make(http.Header),
        }

        MockJsonPost(ctx, param)

        MasterController(ctx)
        time.Sleep(3 * time.Second)

        fmt.Println(&quot;response body&quot;, string(w.Body.Bytes()))
        fmt.Println(&quot;status&quot;, w.Code)
        // var activity *activity.Activity
        activity, err := activityController.GetLastActivity(nil)
        //tx.Raw(&quot;select * from activity order by id desc limit 1&quot;).Find(&amp;activity)
        if err != nil {
            fmt.Println(&quot;No activity found&quot;)
        }

        activityJson, err := activity.ToJsonTest()
        if err != nil {
            fmt.Println(&quot;error converting in json&quot;)
        }

        fmt.Printf(&quot;reponse activity %+v&quot;, string(activityJson))

        assert.EqualValues(t, string(expected[i]), string(activityJson))
}
</code></pre>
<pre><code>func MockJsonPost(c *gin.Context, content interface{}) {
    c.Request.Method = &quot;POST&quot; // or PUT
    c.Request.Header.Set(&quot;Content-Type&quot;, &quot;application/json&quot;)

    jsonbytes, err := json.Marshal(content)
    if err != nil {
        panic(err)
    }

    // the request body must be an io.ReadCloser
    // the bytes buffer though doesn't implement io.Closer,
    // so you wrap it in a no-op closer
    c.Request.Body = io.NopCloser(bytes.NewBuffer(jsonbytes))
}
</code></pre>
",https://stackoverflow.com/questions/71872970/how-to-solve-this-syncing-issue-in-unit-testing-golang,"['unit-testing', 'go', 'assertion']",41,False,2,0
How to do unit testing of ViewData in razor pages?,"<p>Having the following <em>reduced</em> code (.net core 3.1):</p>
<pre><code>public ActionResult OnGet()
{
    ViewData[&quot;ACustomMessage&quot;] = $&quot;This a custom message&quot;;

    return Page();
}
</code></pre>
<p>I need a unit test where I can test the message created in ViewData.</p>
<pre><code>public void Test_ViewData()
{
    var loggerMock = new Mock&lt;ILogger&lt;PrivacyModel&gt;&gt;();
    var httpContext = new DefaultHttpContext();
    var modelState = new ModelStateDictionary();
    var actionContext = new ActionContext(httpContext, new RouteData(), new PageActionDescriptor(), modelState);
    var modelMetadataProvider = new EmptyModelMetadataProvider();
    var viewData = new ViewDataDictionary(modelMetadataProvider, modelState);
    var tempData = new TempDataDictionary(httpContext, Mock.Of&lt;ITempDataProvider&gt;());
    var pageContext = new PageContext(actionContext)
    {
        ViewData = viewData
    };
    PrivacyModel privacyRazorPage = new PrivacyModel(loggerMock.Object)
    {
        PageContext = pageContext,
        TempData = tempData,
        Url = new UrlHelper(actionContext)
    };

    var resultPrivacy = privacyRazorPage.OnGet();

    Assert.AreEqual(&quot;This a custom message&quot;, ((PageResult)resultPrivacy).ViewData[&quot;ACustomMessage&quot;]);
}
</code></pre>
<p>This test does not work because <code>resultPrivacy</code> is returned as an instantiated object but with all its properties as null.</p>
<p><a href=""https://i.stack.imgur.com/84DxL.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/84DxL.png"" alt=""ViewData returned as null"" /></a></p>
",https://stackoverflow.com/questions/70828584/how-to-do-unit-testing-of-viewdata-in-razor-pages,"['c#', 'unit-testing', 'asp.net-core', 'razor-pages', 'asp.net-core-3.1']",881,True,2,1
Javascript unit testing framework that doesn&#39;t work in strict mode,"<p>Is there a way to unit test code from not strict mode. Most of the testing frameworks, mocha, jest, etc are strict mode only. My code involves use of eval that needs non-strict mode scope that I cannot rewrite into strict mode compatible form. Any idea or do I need to write my own unit testing framework.</p>
",https://stackoverflow.com/questions/71093181/javascript-unit-testing-framework-that-doesnt-work-in-strict-mode,"['javascript', 'node.js', 'unit-testing']",73,True,1,1
Unit-testing JDBI Mapper with ResultSet and StatementContext as parameters,"<p>I have to write a unit-test for the following method in <code>class VPartnerExtMapper</code> <em>(VPartnerExtMapper.java)</em>:</p>
<pre><code>import org.jdbi.v3.core.mapper.RowMapper;
import org.jdbi.v3.core.statement.StatementContext;

import java.sql.ResultSet;
import java.sql.SQLException;

public class VPartnerExtMapper implements RowMapper&lt;VPartnerExt&gt; {
  @Override
  public VPartnerExt map(ResultSet rs, StatementContext ctx) throws SQLException {
    int i = 1;
    VPartnerExt result = new VPartnerExt();

    result.setTecClient(rs.getLong(i++));
    result.setPartnerId(rs.getLong(i++));
    result.setTecVersionNr(rs.getLong(i++));
    result.setName(rs.getString(i++));
   
    return result;
  }
}
</code></pre>
<p><strong>My code for the unit-test so far</strong> <em>(VPartnerExtMapperTest.java)</em> <strong>:</strong></p>
<pre><code>import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.sql.ResultSet;
import java.sql.SQLException;

@RunWith(JUnit4.class)
public class VPartnerExtMapperTest {
  @Mock
  private ResultSet resultSet;

  @Mock
  StatementContext ctx;

  @Test
  public void map() throws SQLException {

    ResultSet resultSet = mock(ResultSet.class);

    when(resultSet.getString(&quot;NAME&quot;)).thenReturn(&quot;Michael&quot;);

    VPartnerExt result = new VPartnerExtMapper().map(resultSet, ctx);
    assertEquals(&quot;Michael&quot;, result.getName());
  }
}
</code></pre>
<p>(Please let me know if I missed something and need to put it in the explanation before downgrading the question.)</p>
",https://stackoverflow.com/questions/74067012/unit-testing-jdbi-mapper-with-resultset-and-statementcontext-as-parameters,"['java', 'spring', 'unit-testing', 'junit4', 'jdbi']",145,False,1,0
Unit testing the login method with firebase in android studio,"<p>I'm carrying out a university project. I need to know if the unit test I did of the login method with firebase in android studio is correct. I'm a beginner with unit testing. Below I indicate the method and the test carried out.</p>
<pre><code>public void signUp(String nickname, String email, String password,String dataOfBirth, String gender){
        auth = FirebaseAuth.getInstance();
        referenceDb = FirebaseDatabase.getInstance().getReference();
        auth.createUserWithEmailAndPassword(email,password)
                .addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
                    @Override
                    public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                        if (task.isSuccessful()) {

                            String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

                            UserDao userDao = new UserDao();
                            User currUser = new User(uid, nickname, email, password, dataOfBirth, gender);

                            referenceDb.child(&quot;Users&quot;).child(uid).setValue(currUser).addOnCompleteListener(new OnCompleteListener&lt;Void&gt;() {
                                @Override
                                public void onComplete(@NonNull Task&lt;Void&gt; task) {
                                    if (task.isSuccessful()) {

                                       Toast.makeText(singUp_fragment.getActivity(), &quot;SingUp successful&quot;, Toast.LENGTH_SHORT).show();
                                        openHomeFragment();
                                    } else {
                                        Toast.makeText(singUp_fragment.getActivity(), &quot;SingUp failed. Please try again&quot;, Toast.LENGTH_SHORT).show();
                                        singUp_fragment.progressBar.setVisibility(View.GONE);
                                    }
                                }
                            });
                        } else {
                            Resources resources = singUp_fragment.getStartActivity().getResources();
                            singUp_fragment.cleanTextInputErrors();
                            try {
                                throw task.getException();
                            } catch (NoInternetConnectionException e) {
                                MotionToast.display(
                                        singUp_fragment.getStartActivity(),
                                        R.string.toast_warning_internet_connection,
                                        MotionToastType.WARNING_MOTION_TOAST
                                );
                            } catch (FirebaseAuthInvalidUserException e) {
                                singUp_fragment.setTextInputNicknameError(
                                        resources.getString(R.string.fragment_sign_up_invalid_nickname)
                                );
                            } catch (FirebaseAuthUserCollisionException e) {
                                singUp_fragment.setTextInputEmailError(
                                        resources.getString(R.string.fragment_sign_up_invalid_login)
                                );
                            } catch (Exception e) {
                                MotionToast.display(
                                        singUp_fragment.getStartActivity(),
                                        R.string.toast_error_unknown_error,
                                        MotionToastType.ERROR_MOTION_TOAST
                                );
                            }
                        }
                        singUp_fragment.progressBar.setVisibility(View.GONE);
                        singUp_fragment.setEnabledButtonSignUp(true);
                    }
                });
    }
</code></pre>
<p>I tested it like this:</p>
<pre><code>public class SingIn_Test {
    FirebaseAuth auth;
    boolean test;

    @Test
    public void ValidEmailPasswordTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;annal@live.it&quot;, &quot;Annamaria2222&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidEmptyEmailPasswordTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;&quot;, &quot;&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidEmptyEmailTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;&quot;, &quot;Annamaria2222&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidEmptyPasswordTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;annal@live.it&quot;, &quot;&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidFormatEmailPasswordTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;annal@live&quot;, &quot;Annamaria&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidFormatPasswordTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;annal@live.it&quot;, &quot;Annamaria&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidFormatEmailTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;annal@live&quot;, &quot;Annamaria2222&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

}
</code></pre>
<p>it's correct?</p>
",https://stackoverflow.com/questions/74795167/unit-testing-the-login-method-with-firebase-in-android-studio,"['android', 'firebase', 'unit-testing']",77,False,1,0
how to stub a function for unit testing using mocktail,"<p>i'm using mocktail package to mock my repositories for unit testing. I already tested out few of my controllers and its passing, until i encountered a error in my <code>submitPhoneNumber</code> method which I cant figure out where the problem is and what am i missing.</p>
<p>The setup is I'm stubbing my <code>controller.submitPhoneNumber</code> to answer a <code>Future.value(true)</code>,  which means success. so my expectations are  the <code>authRepository.registerWithPhoneNumber</code> method should be called 1 time and the <code>debugState.value.hasError</code> should be false. But i'm getting this error:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>No matching calls. All calls: MockFirebaseAuthRepository.registerWithPhoneNumber(+15551234567, Closure: (String) =&gt; void, Closure: () =&gt; void)
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
package:test_api                                                                                        fail
package:mocktail/src/mocktail.dart 722:7                                                                _VerifyCall._checkWith
package:mocktail/src/mocktail.dart 515:18                                                               _makeVerify.&lt;fn&gt;
test/src/features/authentication/presentation/sign_in/phone_sign_in/sign_in_controller_test.dart 41:13  main.&lt;fn&gt;.&lt;fn&gt;</code></pre>
</div>
</div>
</p>
<p>this means that the <code>controller.submitPhoneNumber</code> has not been called and the <code>debugState.value.hasError</code> is true. But in actual, my controller is working fine in both emulator and physical device.</p>
<p>I cant figure out why this is happening so maybe I made mistake on how I stubbed my function.
Appreciated so much if someone could help me figure this out.</p>
<p>Here is my test:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>void main() {



  group('controller submit phone number test', () {
    final controller = SignInController(
        formType: SignInFormType.register, authRepository: authRepository);

    test('submit phonumber success', () async {
      const phoneNumber = '+15551234567';

///this is where the error is comming from

      when(() =&gt; controller.submitPhoneNumber(phoneNumber, (e) {}, () {}))
          .thenAnswer((_) =&gt; Future.value(true));

      await controller.submitPhoneNumber(phoneNumber, (e) {}, () {});
      
      verify(() =&gt; authRepository.registerWithPhoneNumber(
          phoneNumber, (e) {}, () {})).called(1);
      expect(controller.debugState.value.hasError, false);
      expect(controller.debugState.formType, SignInFormType.register);
      expect(controller.debugState.value, isA&lt;AsyncValue&gt;());
    }, timeout: const Timeout(Duration(milliseconds: 500)));

}</code></pre>
</div>
</div>
</p>
<p>And here is my controller</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>class SignInController extends StateNotifier&lt;SignInState&gt; {
  SignInController({
    required SignInFormType formType,
    required this.authRepository,
  }) : super(SignInState(formType: formType));
  final AuthRepository authRepository;

  Future&lt;bool&gt; submitPhoneNumber(String phoneNumber,
      void Function(String e) verificationFailed, VoidCallback codeSent) async {
    state = state.copyWith(value: const AsyncValue.loading());
    final value =
        await AsyncValue.guard(() =&gt; authRepository.registerWithPhoneNumber(
              phoneNumber,
              verificationFailed,
              codeSent,
            ));
    state = state.copyWith(value: value);
    return value.hasError == false;
  }

}


final signInControllerProvider = StateNotifierProvider.autoDispose
    .family&lt;SignInController, SignInState, SignInFormType&gt;((ref, formType) {
  final authRepository = ref.watch(authRepositoryProvider);
  return SignInController(
    authRepository: authRepository,
    formType: formType,
  );
});</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/74169184/how-to-stub-a-function-for-unit-testing-using-mocktail,"['flutter', 'unit-testing', 'mocking']",587,True,1,1
Mocking vue-router&#39;s push() method in Unit testing - Vue 3,"<p>I'm new to Vue and StackOverflow, but I'll try to explain my problem.</p>
<p>I get a TypeError when I try to run the unit test for my application.</p>
<p>&quot;TypeError: Cannot read properties of undefined (reading 'push')&quot;</p>
<p><a href=""https://i.stack.imgur.com/pqUkZ.png"" rel=""nofollow noreferrer"">https://i.stack.imgur.com/pqUkZ.png</a></p>
<p>The program runs exactly as it should otherwise, it's only the test that fails.</p>
<p>The test tries to run $router.push in the application, but can't, because it doesn't know what that is, how can I successfully mock the push method while testing?</p>
<p>My example.spec.js test code looks like this:</p>
<pre><code>import { shallowMount } from '@vue/test-utils'
import LoginView from '@/views/LoginView.vue'

describe('LoginView.vue', () =&gt; {
  it('loginSuccess-test', async () =&gt; {

    const wrapper = shallowMount(LoginView, {
      mocks: {
        $router: {
          push: () =&gt; {}
        }
      }
    })

    await wrapper.setData({username:'user', password:'pass'})
    await wrapper.find('button').trigger('click')
    const statusId = wrapper.find('#loginstatusLabel');

    expect(wrapper.find('#loginstatusLabel').element.textContent).toBe('true')

  })
})
</code></pre>
<p>My LoginView.vue methods code looks like this:</p>
<pre><code>  methods: {
    checkCredentials() {
      if (this.username === 'user' &amp;&amp; this.password === 'pass') {
        this.loginSuccess = 'true';
        this.$router.push({ name: 'home' });
      }
      else {
        this.toast.error(&quot;Username or password is incorrect    Try again&quot;);
        this.message = 'Login failed!';
        this.isActive = false;

      }
    }
&lt;/script&gt;
</code></pre>
<p>I'm trying to make the push method redirect the user to &quot;home&quot; when he successfully logs in and mock the redirection in testing.</p>
<p>Any help will be greatly appreciated</p>
",https://stackoverflow.com/questions/71361410/mocking-vue-routers-push-method-in-unit-testing-vue-3,"['javascript', 'vue.js', 'unit-testing', 'vue-router', 'vuejs3']",1103,True,1,2
Unit Testing Issue - Dialog box not rendering during unit test,"<p>I have a page (parent component) that has a button and when clicked, it brings up a primevue dialog. The code of the button and dialog are in a child component. By default the dialog is not visible. When I do a unit test, how can I render the dialog to appear? console.log(wrapper) just shows the button. Any help would be much appreciated.</p>
<pre><code>describe('DialogBoxForm.vue', () =&gt; {
let wrapper: VueWrapper;
beforeEach(async () =&gt; {

wrapper = mount(DialogBoxForm, {
global: {
stubs: { teleport: true, Toast: false },
plugins: [pinia, PrimeVue]
}
});
  await flushPromises();
});
console.log(wrapper)
</code></pre>
",https://stackoverflow.com/questions/73967765/unit-testing-issue-dialog-box-not-rendering-during-unit-test,"['vue.js', 'unit-testing', 'primevue']",160,False,1,0
Are spies a bad practice when we are unit testing?,"<p>When we have a situation where the method has no return and its behavior is just calling a dependency according to the input as in the example below, is it bad practice to use spies? Would it be correct to refactor the method to make it return something that represents its behavior?</p>
<p>For better understanding please check following example:</p>
<pre><code>MyClass {
    myMethod(input: number) {
      if(input &gt; 5) {
        this.service1.call('abc');
      } else {
        this.service1.call('xyz');
      }
    }
}

// Test
const callSpy = jest.SpyOn(service1, 'call');
const myClass = new MyClass();
myClass.myMethod(1)
expect(callSpy).toBeCalledWith('xyz')
</code></pre>
",https://stackoverflow.com/questions/70741379/are-spies-a-bad-practice-when-we-are-unit-testing,"['javascript', 'unit-testing', 'jestjs', 'spy']",74,False,1,0
Unit testing using EF Core InMemoryDatabase along with Moq mocks,"<p>I am using EF Core 6.0.x + NUnit + Moq. Below example is strongly anonymized, the real scenario actually makes sense.</p>
<p>I have a DbContext:</p>
<pre><code>public class MyDbContext : DbContext
{        
    public virtual DbSet&lt;Foo&gt; Foos { get; set; }

    public MyDbContext(DbContextOptions&lt;MyDbContext&gt; options) : base(options) { }
    
    public virtual void PreSaveActions()
        =&gt; throw new NotImplementedException(); //Here I've got something that must be done pre-save.

    public override int SaveChanges()
    {
        PreSaveActions();
        return base.SaveChanges();
    }
}
</code></pre>
<p>I have a method similar to this:</p>
<pre><code>public class SafeRemover
{
    private readonly IDbContextFactory&lt;MyDbContext&gt; _contextFactory;    

    public SafeRemover(IDbContextFactory&lt;MyDbContext&gt; contextFactory)
    {
        _contextFactory = contextFactory;
    }

    public int SafeRemove(string name, int barId)
    {
        using var context = _contextFactory.CreateDbContext();
        var itemToRemove = context.Foos.SingleOrDefault(foo =&gt; foo.BarId == barId &amp;&amp; foo.Name == name);

        if (itemToRemove != null)
            context.Foos.Remove(itemToRemove);
        
        return context.SaveChanges();
    }
}
</code></pre>
<p>DependencyInjection registrations:</p>
<pre><code>Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder()
       .ConfigureServices((_, services) =&gt; 
       {
           services
               .AddDbContextFactory&lt;MyDbContext&gt;(options =&gt; options.UseSqlServer(configuration.GetConnectionString(&quot;MyDbContext&quot;)))
               .AddSingleton&lt;SafeRemover&gt;();
       }).Build();
</code></pre>
<p>I want to unit test that this method removes or not certain entities from the given set in database context.</p>
<h3>Attempt 1 InMemoryDatabase + mocks:</h3>
<pre><code>private static readonly object[] _safeRemoveSource = 
{
    new TestCaseData(&quot;Foo1&quot;, 1, new List&lt;Foo&gt;()).SetName(&quot;SafeRemove_FooExists_FooRemoved&quot;),
    new TestCaseData(&quot;Foo2&quot;, 1, new List&lt;Foo&gt; { new Foo { Name = &quot;Foo1&quot;, BarId = 1 } }).SetName(&quot;SafeRemove_FooWithDifferentNameExists_FooNotRemoved&quot;),
    new TestCaseData(&quot;Foo1&quot;, 2, new List&lt;Foo&gt; { new Foo { Name = &quot;Foo1&quot;, BarId = 1 } }).SetName(&quot;SafeRemove_FooWithDifferentBarIdExists_FooNotRemoved&quot;),
}    

[TestCaseSource(nameof(_safeRemoveSource))]
public void SafeRemoveTest(string name, int barId, IList&lt;Foo&gt; expectedFoos)
{
    var options = new DbContextOptionsBuilder&lt;MyDbContext&gt;().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;  

    var contextMock = new Mock&lt;MyDbContext&gt;(options) {CallBase = true};
    contextMock.Setup(context =&gt; context.PreSaveActions());

    var contextFactoryMock = new Mock&lt;IDbContextFactory&lt;MyDbContext&gt;&gt;();
    contextFactoryMock.Setup(factory =&gt; factory.CreateDbContext()).Returns(contextMock.Object);

    var safeRemover = new SafeRemover(contextFactoryMock.Object);
    
    safeRemover.SafeRemove(name, barId);
    var actualFoos = contextMock.Object.Foos.ToList();

    Assert.AreEqual(expectedFoos.Count(), actualFoos.Count());
    for (var i = 0; i &lt; expectedFoos.Count(); i++)
        Assert.That(expectedFoos[i].Name.Equals(actualFoos[i].Name) &amp;&amp; expectedFoos[i].BarId == actualFoos[i].BarId);
}
</code></pre>
<p>When I use the <code>InMemoryDatabase</code> I am unable to check the value of <code>contextMock.Object.Foos.ToList()</code> after invoking <code>saveRemover.SafeRemove(name, barId)</code> because the <code>contextMock.Object</code> is already disposed:</p>
<blockquote>
<p>System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur is you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'Context'.</p>
</blockquote>
<h3>Attempt 2 Mocked dbset and callbacks:</h3>
<pre><code>private static readonly object[] _safeRemoveSource = 
{
    new TestCaseData(&quot;Foo1&quot;, 1, new List&lt;Foo&gt;()).SetName(&quot;SafeRemove_FooExists_FooRemoved&quot;),
    new TestCaseData(&quot;Foo2&quot;, 1, new List&lt;Foo&gt; { new Foo { Name = &quot;Foo1&quot;, BarId = 1 } }).SetName(&quot;SafeRemove_FooWithDifferentNameExists_FooNotRemoved&quot;),
    new TestCaseData(&quot;Foo1&quot;, 2, new List&lt;Foo&gt; { new Foo { Name = &quot;Foo1&quot;, BarId = 1 } }).SetName(&quot;SafeRemove_FooWithDifferentBarIdExists_FooNotRemoved&quot;),
}    

[TestCaseSource(nameof(_safeRemoveSource))]
public void SafeRemoveTest(string name, int barId, IList&lt;Foo&gt; expectedFoos)
{
    var actualFoos = new List&lt;Foo&gt; { new Foo { Name = &quot;Foo1&quot;, BarId = 1 } };
    var options = new DbContextOptionsBuilder&lt;MyDbContext&gt;().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;  

    var foosMock = new Mock&lt;DbSet&lt;Foo&gt;&gt; {CallBase = true};
    foosMock.Setup(set =&gt; set.Remove(It.IsAny&lt;Foo&gt;())).Callback&lt;Foo&gt;(foo =&gt; actualFoos.Remove(foo));

    var contextMock = new Mock&lt;MyDbContext&gt;(options) {CallBase = true};
    contextMock.Setup(context =&gt; context.PreSaveActions());
    contextMock.Setup(context =&gt; context.Foos).Returns(foosMock.Object);

    var contextFactoryMock = new Mock&lt;IDbContextFactory&lt;MyDbContext&gt;&gt;();
    contextFactoryMock.Setup(factory =&gt; factory.CreateDbContext()).Returns(contextMock.Object);

    var safeRemover = new SafeRemover(contextFactoryMock.Object);
    
    safeRemover.SafeRemove(name, barId);

    Assert.AreEqual(expectedFoos.Count(), actualFoos.Count());
    for (var i = 0; i &lt; expectedFoos.Count(); i++)
        Assert.That(expectedFoos[i].Name.Equals(actualFoos[i].Name) &amp;&amp; expectedFoos[i].BarId == actualFoos[i].BarId);
}
</code></pre>
<p>Everything seems to work as expected instead of one thing... I'm getting NotSupportedException on <code>SingleOrDefault</code> method in above configuration of mocks:</p>
<blockquote>
<p>System.NotSupportedException : Specified method is not supported.</p>
</blockquote>
<h3>Attempt 3 (successfull)</h3>
<p>I went back to the attempt 1 and removed <code>using</code> clause. Now it seems to work as expected, but am I safe to do so? Would <a href=""https://www.google.com/search?client=firefox-b-d&amp;q=nuget+dependency+injection+.net+6"" rel=""nofollow noreferrer"">DI container</a> be smart enough to leave it entirely for him?
I can't find anything about that in the docs and I'm not that good at profiling to check it comprehensively.</p>
<h1>@Edit:</h1>
<p>I've used InMemoryDatabase with derivered <code>TestMyDbContext</code> class. Still without success. I've got <code>ObjectDisposedException</code> on the following line: <code>var actualFoos = context.Foos.ToList();</code></p>
<p>TestMyDbContext:</p>
<pre><code>public class TestMyDbContext : MyDbContext
{
    public override void PreSaveActions() {}
}
</code></pre>
<p>Unit test:</p>
<pre><code>private static readonly object[] _safeRemoveSource = 
{
    new TestCaseData(&quot;Foo1&quot;, 1, new List&lt;Foo&gt;()).SetName(&quot;SafeRemove_FooExists_FooRemoved&quot;),
    new TestCaseData(&quot;Foo2&quot;, 1, new List&lt;Foo&gt; { new Foo { Name = &quot;Foo1&quot;, BarId = 1 } }).SetName(&quot;SafeRemove_FooWithDifferentNameExists_FooNotRemoved&quot;),
    new TestCaseData(&quot;Foo1&quot;, 2, new List&lt;Foo&gt; { new Foo { Name = &quot;Foo1&quot;, BarId = 1 } }).SetName(&quot;SafeRemove_FooWithDifferentBarIdExists_FooNotRemoved&quot;),
}    

[TestCaseSource(nameof(_safeRemoveSource))]
public void SafeRemoveTest(string name, int barId, IList&lt;Foo&gt; expectedFoos)
{
    var initialFoos = new List&lt;Foo&gt; { new Foo { Name = &quot;Foo1&quot;, BarId = 1 } };
    var options = new DbContextOptionsBuilder&lt;MyDbContext&gt;().UseInMemoryDatabase(Guid.NewGuid().ToString()).Options;  

    using var context = new TestMyDbContext(options);
    context.Foos.AddRange(actualFoos);
    context.SaveChanges();

    var contextFactoryMock = new Mock&lt;IDbContextFactory&lt;MyDbContext&gt;&gt;();
    contextFactoryMock.Setup(factory =&gt; factory.CreateDbContext()).Returns(context);

    var safeRemover = new SafeRemover(contextFactoryMock.Object);
    
    safeRemover.SafeRemove(name, barId);
    var actualFoos = context.Foos.ToList();

    Assert.AreEqual(expectedFoos.Count(), actualFoos.Count());
    for (var i = 0; i &lt; expectedFoos.Count(); i++)
        Assert.That(expectedFoos[i].Name.Equals(actualFoos[i].Name) &amp;&amp; expectedFoos[i].BarId == actualFoos[i].BarId);
}
</code></pre>
",https://stackoverflow.com/questions/71587176/unit-testing-using-ef-core-inmemorydatabase-along-with-moq-mocks,"['c#', 'unit-testing', 'dependency-injection', 'entity-framework-core', 'moq']",2229,True,1,1
Jest: $ is not defined in Angular unit testing typescript/Jquery,"<p>I will be trying to write a unit test case for some angular components. so it has been thrown an error <strong>ReferenceError: $ is not defined</strong> <a href=""https://i.stack.imgur.com/W8zkx.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/W8zkx.png"" alt=""ReferenceError: $ is not defined"" /></a></p>
<p>we call the function in ng afterViewInit() that will use the jquery so import the npm jquery
below i mention code snippet:</p>
<pre><code>ngAfterViewInit() {
    $('.draggable').draggable({
      containment: '#droppable',
      helper: 'clone',
      revert: 'invalid',
      cursor: 'move',
      iframeFix: true,
      zIndex: 6,
      start: this.onAnnotationDrag.bind(this),
    });

    document.getElementById('paletteDiv').style['display'] = 'none';
    document.getElementById('annotationsDiv').style['display'] = 'block';

    this.setToolbarVisibility();

    $('.dropdown').click(function () {
      $('.dropdown-menu').toggleClass('show');
    });
  }
</code></pre>
<p><strong>Unit test case:</strong></p>
<pre><code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ToolbarComponent } from './toolbar.component';
import { HttpClientModule, HttpClient } from '@angular/common/http'
import { MsAdalAngular6Service, MsAdalAngular6Module } from &quot;microsoft-adal-angular6&quot;;
import { Constants } from '../../app.constants';
import $ from 'jquery';

jest.mock(
  'jquery',
  () =&gt; {
    const m$ = { on: jest.fn(), ready: jest.fn(), addClass: jest.fn() };
    return jest.fn(() =&gt; m$);
  },
  // remove this option if you have installed jquery module
  { virtual: true },
);

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

  beforeEach(async(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientModule, MsAdalAngular6Module.forRoot(Constants.ADAL_CONFIG)],
      declarations: [ToolbarComponent],
      providers: [HttpClient, MsAdalAngular6Service]
    })
      .compileComponents();
  }));

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

  it('should create', () =&gt; {
    $().ready.mockImplementationOnce((callback) =&gt; callback());
    $().on.mockImplementationOnce((event, handler) =&gt; handler());
    expect(component).toBeTruthy();
  });
});
</code></pre>
",https://stackoverflow.com/questions/70594172/jest-is-not-defined-in-angular-unit-testing-typescript-jquery,"['jquery', 'angular', 'unit-testing', 'jestjs', 'ts-jest']",442,False,1,0
How to get access token for Unit Testing in .Net,"<p>I require an access token to test methods in a service. I tried to hardcode the access token and it is working well. If I run the application after some time all test cases get failed. I believe it's because the access token gets expired. How can I generate access tokens without hardcoding?</p>
",https://stackoverflow.com/questions/72360574/how-to-get-access-token-for-unit-testing-in-net,"['moq', 'xunit']",937,False,1,1
multiple definition of global with gmock-global in unit testing,"<p>I am trying to mock global function using <a href=""https://github.com/apriorit/gmock-global"" rel=""nofollow noreferrer"">https://github.com/apriorit/gmock-global</a> library.</p>
<p>Note: this description contains example of the real scenario not the exact real scenario. Also I am not allowed to make any changes to global.hpp.</p>
<p>My example dir structure looks like below</p>
<pre><code>--src
------global.hpp
------classA.hpp
------classB.hpp
------main.cpp
--ut
------classATests.cpp
------classBTests.cpp
------main.cpp
</code></pre>
<p>The ut/main.cpp tests testcases in classATests.cpp and classBTests.cpp.</p>
<p>global.hpp contains a global function</p>
<pre><code>int giveIndex()
{
    return 1;
}
</code></pre>
<p>classA.hpp calls giveIndex() global function</p>
<pre><code>#include &quot;global.hpp&quot;
class A
{
public:
int checkIndex() { return giveIndex(); };
}
</code></pre>
<p>classB.hpp calls giveIndex() global function</p>
<pre><code>#include &quot;global.hpp&quot;
class B
{
public:
int checkIndex() { return giveIndex(); };
}
</code></pre>
<p>classATests.cpp contains</p>
<pre><code>#include &lt;memory&gt;
#include &lt;gtest/gtest.h&gt;
#include &lt;gmock/gmock.h&gt;
#include &lt;gmock-global/gmock-global.h&gt;
#include &quot;src/classA.hpp&quot;
MOCK_GLOBAL_FUNC0(giveIndex, int(void));

using namespace ::testing
struct classATests : public ::testing::Test
{
    void Setup() override
    {
        sut_ = std::make_shared&lt;A&gt;();
    }
    std::shared_ptr&lt;A&gt; sut_;
};
TEST_F(classATests , checkIndex)
{
    EXPECT_GLOBAL_CALL(giveIndex, giveIndex()).WillOnce(Return(1));
    sut_-&gt;checkIndex();
}
</code></pre>
<p>classBTests.cpp contains</p>
<pre><code>#include &lt;memory&gt;
#include &lt;gtest/gtest.h&gt;
#include &lt;gmock/gmock.h&gt;
#include &lt;gmock-global/gmock-global.h&gt;
#include &quot;src/classB.hpp&quot;
MOCK_GLOBAL_FUNC0(giveIndex, int(void));

using namespace ::testing
struct classBTests : public ::testing::Test
{
    void Setup() override
    {
        sut_ = std::make_shared&lt;B&gt;();
    }
    std::shared_ptr&lt;B&gt; sut_;
};
TEST_F(classBTests , checkIndex)
{
    EXPECT_GLOBAL_CALL(giveIndex, giveIndex()).WillOnce(Return(1));
    sut_-&gt;checkIndex();
}
</code></pre>
<p>The issue now is when i compile and run UT for both classATests.cpp and classBTests.cpp i get errors saying</p>
<blockquote>
<p>... multiple definition of 'giveIndex' ;
and
... multiple definitions of gmock_globalmock_giveIndex_instance</p>
</blockquote>
<p>Is there any way to avoid this issue ? classA tests and classB tests need to be in 2 different files like it is now.</p>
",https://stackoverflow.com/questions/74503322/multiple-definition-of-global-with-gmock-global-in-unit-testing,"['c++', 'unit-testing', 'googletest']",175,True,1,3
Unit Testing using JUnit 5 and Mockito in Spring Boot,"<p>What are the things I need to test in Controller Testing, Service Testing and Repository Testing</p>
<p>Example:
In controller testing I should test:</p>
<ol>
<li>If the endpoint will not work in different HTTP Methods</li>
<li>If the endpoint can receive request</li>
</ol>
<p>I want to ask suggestions from other devs so I can learn the other goals in testing</p>
<p>I already know some of the parts that needs to be tested but I wanna ask if there are parts that I don't know</p>
",https://stackoverflow.com/questions/74387706/unit-testing-using-junit-5-and-mockito-in-spring-boot,"['spring', 'spring-boot', 'unit-testing', 'mockito', 'junit5']",104,False,1,0
React Jest Unit Testing await in private function uncovered line,"<p>I call a async function in useEffect</p>
<pre><code> const [documents, setDocuments] = useState(Array());

  async function findDocuments() {
    const res = await findDocumentList([], {});
    setDocuments(res.data);
  }

  useEffect(() =&gt; {
    findDocuments();
  }, []);
</code></pre>
<p>I'm seeing <code>state not covered</code> issue in my coverage report.</p>
<p><a href=""https://i.stack.imgur.com/5Mv3e.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/5Mv3e.png"" alt=""enter image description here"" /></a></p>
<p>How can I fix this issue?</p>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/70765422/react-jest-unit-testing-await-in-private-function-uncovered-line,"['jestjs', 'code-coverage', 'istanbul']",308,False,1,1
Unit testing stream in flutter with error gives wrong instance,"<p>I am trying to ping a server from my code. I am using <code>StreamController&lt;ConnectionState&gt;</code> to check for internet connectivity every 5 (1 in below test) second. The case for the test is passing invalid uri. I want to test that there is an error.</p>
<p>I have tried <code>expectLater(connectionStream, emitsError(ConnectionError));</code> in the test. However, I am getting the below error.</p>
<p><strong>Error:</strong></p>
<pre><code>Expected: should emit an error that Type:&lt;ConnectionError&gt;
Actual: &lt;Instance of '_ControllerStream&lt;ConnectionState&gt;'&gt;
Which: emitted ! Instance of 'ConnectionError'
</code></pre>
<p><strong>File: connection.dart</strong></p>
<pre class=""lang-dart prettyprint-override""><code>import 'dart:async';
import 'dart:io';

import 'package:http/http.dart' as http;

class ConnectionController {
  String serverUrl;
  Duration repeatInterval;

  Timer? _timer;

  late final StreamController _controller;

  Stream get stream =&gt; _controller.stream;

  ConnectionController({
    this.serverUrl = 'https://google.com',
    this.repeatInterval = const Duration(
      seconds: 5,
    ),
  }) {
    _controller = StreamController&lt;ConnectionState&gt;(
      onListen: () {
        _timer ??= Timer.periodic(repeatInterval, (timer) async {
          try {
            Uri parsedUri = Uri.parse(serverUrl);

            final response = await http.get(parsedUri);

            if (response.statusCode == HttpStatus.ok) {
              _controller.add(ConnectionState(isConnected: true));
            } else {}
          } catch (error, stacktrace) {
            if (error is ArgumentError || error is SocketException) {
              print(error.toString());
              _controller.addError(
                ConnectionError(
                    errorType: ConnectionErrorType.invalidServerUrl,
                    errorDescription: error.toString()),
              );
            }
            print(error);
            print(error.runtimeType);
            print(stacktrace);
          }
        });
      },
      onCancel: () {
        _timer?.cancel();
      },
    );
  }
}

class ConnectionState {
  bool isConnected;
  ConnectionState({
    required this.isConnected,
  });
}

class ConnectionError extends Error {
  ConnectionErrorType errorType;
  String errorDescription;

  ConnectionError({
    required this.errorType,
    required this.errorDescription,
  });
}

enum ConnectionErrorType {
  invalidServerUrl,
}

</code></pre>
<p><strong>File: tests\connection_test.dart</strong></p>
<pre class=""lang-dart prettyprint-override""><code>import 'package:connection_info/connection.dart';
import 'package:flutter_test/flutter_test.dart';

import 'mocks/connection_error.dart';

void main() {
  group('Connection Controller tests', () {
    test('send invalid server url and get error', () async {
      var connectionError = MockConnectionError();

      final controller = ConnectionController(
        serverUrl: 'http://asdom',
        repeatInterval: Duration(seconds: 1),
      );

      Stream connectionStream = controller.stream;

      expectLater(connectionStream, emitsError(ConnectionError));
    });
  });
}
</code></pre>
<p>I want to validate that the stream has received the error. How can I test properly for the error?</p>
",https://stackoverflow.com/questions/70929709/unit-testing-stream-in-flutter-with-error-gives-wrong-instance,"['flutter', 'stream', 'flutter-test']",652,True,1,1
Unit testing APIGatewayProxyFunction API Controller methods (C# inheritance problem maybe?),"<p>I have an ASP.NET Core web API application that's set up as an AWS Serverless lambda function with API Gateway.</p>
<p>I'm working with an instance of <code>APIGatewayProxyFunction</code> and I'm trying to unit test some of my controller behavior by injecting <code>NSubstitute</code> versions of my database repo.</p>
<p>Now, of course I can instantiate my controller directly and inject the mocked dependencies, but using the auto-gen'd <code>LambdaEntryPoint</code> class and taking advantage of the host builder logic lets me get all the MVC routing goodies and I can test actual HTTP method matching and route matching.</p>
<p>My problem is, <code>builder.UseStartup&lt;Startup&gt;()</code> uses my real DI service registration code.  I was hoping I could override this behavior and register a mocked instance of my database repo class.</p>
<p>There doesn't seem to be a way to get at the ServiceCollection in the unit test once the object is constructed, so I thought I'd just sub-class the <code>LambdaEntryPoint</code> and override the <code>Init()</code> function to supply a subclass of <code>Startup</code> <code>MockStartup</code> instead which registers mocked instances.</p>
<p>The problem it seems is that <code>Init()</code> actually gets called during the constructor chain, so I can't really feed mocked instances into my subclass to be used during the <code>Init()</code> override.</p>
<p>Super pared down example:</p>
<pre><code>var myClass = new ChildClass(7);


public class BaseClass
{
    public BaseClass()
    {
        Console.WriteLine(&quot;Base class constructing&quot;);
        Init();
    }

    public virtual void Init()
    {
        Console.WriteLine(&quot;Base class init&quot;);
    }
}

public class ChildClass : BaseClass
{
    private readonly int? _mockedService;

    public ChildClass(int mockedService)
    {
        _mockedService = mockedService;
        Console.WriteLine(&quot;Child class constructed&quot;);
    }

    public override void Init()
    {
        Console.WriteLine($&quot;Child class init with mocked service {_mockedService}&quot;);
    }
}
</code></pre>
<p>This, of course does not work, because <code>_mockedService</code> is still null when we get to executing the overridden <code>Init()</code> function.</p>
<p>So, I'm looking for guidance on how I can write a unit test which can submit actual JSON posts to prove MVC routes and HTTP methods for my application while still providing a mocked instance of my database interface?</p>
<p>I'm open to all options, but if possible, I'd like to do this without spinning up a full http webservice and <em>actually</em> submitting http requests, but if that's the only option, guidance on the best way to do that with substitutes would be appreciated as well.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/74594829/unit-testing-apigatewayproxyfunction-api-controller-methods-c-inheritance-prob,"['c#', 'unit-testing', '.net-core', 'aws-lambda', 'aws-serverless']",66,True,0,1
Instantiating `TypeElement`s outside the processor context for unit testing,"<p>In my project, I have a few classes that operate on objects from the <code>java.compiler</code> module such as <code>TypeMirror</code>s and <code>Element</code>s. Typically, these classes are used by an annotation processor that has access to <code>ProcessingEnvironment</code> for fetching code <code>Element</code>s, but I'd like to be able to test those classes in isolation too. How can I obtain e.g. a <code>TypeElement</code> compiled from a mock java source file inside my test framework?</p>
<p>I'm aware that a similar question was asked here: <a href=""https://stackoverflow.com/questions/27554658/how-to-instantiate-a-typemirror"">How to instantiate a TypeMirror</a>, but the accepted answer doesn't meet my needs.</p>
",https://stackoverflow.com/questions/73294594/instantiating-typeelements-outside-the-processor-context-for-unit-testing,"['java', 'annotations', 'annotation-processing']",24,False,0,0
how to do unit testing using jest in vue js,"<p>How can I write unit test cases in jest in vue application. I need a unit test for mousedown function</p>
<pre><code>  export default {
  name: 'DrgModal',
  components: {
    
  },
  data() {
    return {
      }
  },

  methods: {
    mousedown(e){
      let isMultipleDrg = localStorage.getItem(&quot;showMultipleDrg&quot;);
      if (isMultipleDrg === &quot;true&quot;) {
        console.log(&quot;inside condition&quot;);
        let isResizing = this.isResizing;
        let seleDragElement = this.$refs.drageableElement;
        window.addEventListener(&quot;mousemove&quot;, mousemove);
        window.addEventListener(&quot;mouseup&quot;, mouseup);
        let prevX = e.clientX;
        let prevY = e.clientY;
        function mousemove(e){
          if (!isResizing) {
            let newX = prevX - e.clientX;
            let newY = prevY - e.clientY;
            const rect = seleDragElement.getBoundingClientRect();
            seleDragElement.style.left = rect.left - newX + &quot;px&quot;;
            seleDragElement.style.top = rect.top - newY + &quot;px&quot;;
            prevX = e.clientX;
            prevY = e.clientY;
          }
        }

        function mouseup(e){
          window.removeEventListener(&quot;mousemove&quot;, mousemove);
          window.removeEventListener(&quot;mouseup&quot;, mouseup);
        }
      }
</code></pre>
",https://stackoverflow.com/questions/73152703/how-to-do-unit-testing-using-jest-in-vue-js,"['vue.js', 'unit-testing', 'jestjs']",40,False,0,0
Python unit testing: How to stop gevent.monkey.patch_all() affecting asyncio tests?,"<p>We have a python test suite that tests code that uses <code>gevent.monkey.patch_all()</code>. The tests run fine.</p>
<p>In the same code base we have an alternative entrypoint that uses <code>asyncio</code>. There are also tests for this, which run fine on their own, with this kind of setup:</p>
<pre><code>import asyncio
from our_module import main

class AsyncioTests(unittest.TestCase):
    &quot;&quot;&quot;Test some asyncio stuff.&quot;&quot;&quot;
    
    def test_something(self):
        asyncio.run(main())
</code></pre>
<p>However, if they run after the tests that import the module with the monkey patching, they hang forever. It seems to be <strong>because</strong> of the monkey patching.</p>
<p>Is there a way to stop this, by reversing the monkey patching?</p>
",https://stackoverflow.com/questions/74210878/python-unit-testing-how-to-stop-gevent-monkey-patch-all-affecting-asyncio-tes,"['python-asyncio', 'python-unittest', 'gevent', 'monkeypatching']",139,False,0,1
How to write Unit testing for OdataController net core 6,"<p>how can I write unit test for .net core 6 .I am unable to identified how can i write proper code.Please help me with an example or code.</p>
<pre><code>    [EnableQuery]
    [HttpGet(&quot;MoSearch&quot;)]

    public async Task&lt;ActionResult&lt;DfNetworElement&gt;&gt; MoSearch([FromHeader] string connString)
    {
        try
        {
            var context = new cm_common_infoContext(Global.DecryptString(this.Request.Headers[&quot;ConnString&quot;].ToString(), _configuration[&quot;cipher&quot;]));
            var result = context.DfNetworElements.AsQueryable();
          return Ok(result);
        }
        catch (Exception ex)
        {
            _logger?.LogError(ex.ToString());
            return BadRequest(ex.Message);
        }
    }
</code></pre>
",https://stackoverflow.com/questions/72725811/how-to-write-unit-testing-for-odatacontroller-net-core-6,"['unit-testing', 'controller', 'odata', 'mstest', 'asp.net-core-6.0']",101,False,0,0
Expected: &lt;false&gt; Actual: &lt;Closure: () =&gt; Future&lt;bool&gt;&gt; in flutter unit testing,"<p>I'm writing unit tests to test the authorise function below which is in AuthService class.</p>
<pre><code>  Future&lt;bool&gt; authorize() async {
 
    AuthorizationTokenResponse? authResult;

    try {
     
      authResult = await appAuth.authorizeAndExchangeCode(
        AuthorizationTokenRequest(
            bsEnv.AD_CLIENT_ID!,
           ));

      if (authResult != null) {
        return true;
      }
    } on PlatformException catch (e) {
        forgetPassword();
      }
    }

    return false;
  }

</code></pre>
<p>I am using Mocktail to make the mocks. Below is one written test for the authorise function mentioned in the above code.</p>
<pre><code>
class MockBEnv extends Mock implements BEnv {}

class MockSharedPrefsService extends Mock implements SharedPrefsService {}

class MockFlutterAppAuth extends Mock implements FlutterAppAuth {}

class MockAuthorizationServiceConfiguration extends Mock
    implements AuthorizationServiceConfiguration {}

class MockAuthorizationTokenResponse extends Mock
    implements AuthorizationTokenResponse {}

class MockAuthorizationTokenRequest extends Mock
    implements AuthorizationTokenRequest {}

class MockTokenResponse extends Mock implements TokenResponse{}

class MockTokenRequest extends Mock implements TokenRequest{

}

void main() {
  late AuthService authService;
  late MockFlutterAppAuth mockFlutterAppAuth;
  late MockBEnv mockBEnv;
  late MockSharedPrefsService mockStorageService;
  late MockAuthorizationTokenResponse mockAuthorizationTokenResponse;
  late MockAuthorizationTokenRequest mockAuthorizationTokenRequest;
  
  const tUrl = 'https://endpoint/';
  const tUserImp = 'user';
  const tAppLan = 'sv-SE';
  const tClientId = 'client';
  const tIosUri = 'ios';
  const tTokenEndPoint = 'abcdeff';

  setUp(() {
    mockFlutterAppAuth = MockFlutterAppAuth();
    mockBEnv = MockBEnv();
    mockStorageService = MockSharedPrefsService();
    mockAuthorizationTokenRequest = MockAuthorizationTokenRequest();
    mockAuthorizationTokenResponse = MockAuthorizationTokenResponse();
    authService = AuthService(
        appAuth: mockFlutterAppAuth,
        bsEnv: mockBEnv,
        sharedPrefs: mockStorageService);
  });

  group('authorize', () {
    test(
        'should return true when the call to authorized method if result is not null',
        () async {
      // Arrange
      when(() =&gt; mockBEnv.AD_CLIENT_ID).thenAnswer((_) =&gt; tClientId);
      when(() =&gt; mockFlutterAppAuth
              .authorizeAndExchangeCode(mockAuthorizationTokenRequest))
          .thenAnswer((_)=&gt; Future.value(mockAuthorizationTokenResponse));
      // Act
      final result =  authService.authorize;
      // Assert
      expect(() =&gt; result(), equals(false));
    });
  });
}

</code></pre>
<p>My test fails and below is the error message I get,</p>
<p>Expected: &lt; false &gt;</p>
<p><strong>Actual: &lt;Closure: () =&gt; Future&gt;</strong></p>
<p>How can I fix this issue?</p>
",https://stackoverflow.com/questions/74843581/expected-false-actual-closure-futurebool-in-flutter-unit-testing,"['flutter', 'unit-testing', 'flutter-test']",296,False,0,1
Beans are null when unit testing spring-retry with SpringRunner,"<p>I am trying to write unit tests for a class having spring retry using the springRunner. But my @Autowired beans are null . Could you please let me know what I did wrong?</p>
<p>Below is my test class</p>
<pre><code>@RunWith(SpringRunner.class)
@ContextConfiguration
public class DeltaHelperTest {

    @Autowired
    private DeltaHelper deltaHelper;
    
    @Before
    public void setUp() { System.setProperty(&quot;delta.process.retries&quot;, &quot;2&quot;); }

    @After
    public void validate() { validateMockitoUsage(); }

    @Test
    public void retriesAfterOneFailAndThenPass() throws Exception {
        when(deltaHelper.restService.call(any(), any())).thenThrow(new HttpException());
        deltaHelper.process(any(),any());
        verify(deltaHelper, times(2)).process(any(), any());
    }

    @Configuration
    @EnableRetry
    @EnableAspectJAutoProxy(proxyTargetClass=true)
    @Import(MockitoSkipAutowireConfiguration.class)

    public static class Application {

        @Bean
        public DeltaHelper deltaHelper() {
            DeltaHelper deltaHelper = new DeltaHelper();
            deltaHelper.myStorageService= myStorageService();
            deltaHelper.restService = restService();
            return deltaHelper;
        }

        @Bean
        public MyStorageService myStorageService() {
            return new MyStorageService();
        }

        @Bean
        public MyRestService restService() {
            return new MyRestService();
        }

        @Bean
        public MyRepo myRepository() {
            return mock(MyRepo.class);
        }
    }


    @Configuration
    public static class MockitoSkipAutowireConfiguration {
        @Bean MockBeanFactory mockBeanFactory() {
            return new MockBeanFactory();
        }
        private static class MockBeanFactory extends InstantiationAwareBeanPostProcessorAdapter {
            @Override
            public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
                return !mockingDetails(bean).isMock();
            }
        }
    }
}
</code></pre>
<blockquote>
<p>Here test service is null on deltaHelper object .</p>
</blockquote>
<blockquote>
<p>MyRepo.class is mocked as it has some more @autowired bean reference</p>
</blockquote>
<p>Attaching other classes here</p>
<pre><code>@Component
public class DeltaHelper {

    @Autowired
    MyRestService restService;

    @Autowired
    MyStorageService myStorageService;

    @NotNull
    @Retryable(
            value = Exception.class,
            maxAttemptsExpression = &quot;${delta.process.retries}&quot;
    )
    public String process(String api, HttpEntity&lt;?&gt; entity) {
            return restService.call(api, entity);
    }
    @Recover
    public String recover(Exception e, String api, HttpEntity&lt;?&gt; entity) {

            myStorageService.save(api);
            return &quot;recover&quot;;
    }
}


@Service
public class MyStorageService {

    @Autowired
    MyRepo myRepo;

    @Async
    public MyEntity save(String api) {
        return myRepo.save(new MyEntity(api, System.currentTimeMillis()));
    }
}



public class MyRestService extends org.springframework.web.client.RestTemplate {
}
</code></pre>
<p>Thank you</p>
<blockquote>
<p>Tried MockitoJUnitRunner, But found that @Retryable works only when running with Spring</p>
</blockquote>
",https://stackoverflow.com/questions/74796996/beans-are-null-when-unit-testing-spring-retry-with-springrunner,"['java', 'junit', 'mockito', 'spring-retry', 'springrunner']",114,True,0,1
Permission to Clipboard When Unit Testing in Angular&#39;s Karma Framework,"<p>I was wondering how I can grant permission to clipboard when unit testing in the Angular's Karma framework. I'm currently unit testing the copy-and-paste functionality in the frontend with the system clipboard, and I am not sure if there is a way to configure Karma so that the permission to the clipboard is granted when pasting something from the clipboard. This is easy to do if I want to do the testing in my own browser where I can simply toggle on the permission, but since Karma is an automated system, I wonder if there's a way to go about that. I used the Clipboard API by the way to implement the pasting, i.e., navigator.clipboard.readText().</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/73270630/permission-to-clipboard-when-unit-testing-in-angulars-karma-framework,"['angular', 'unit-testing']",108,False,0,0
How to perform Unit Testing for hibernate transactional query statements?,"<p>Need some advice on how to do Unit testing for DAO class. My application uses DAO class to interact with my database directly and it is heavily used. I would like to construct unit tests for those DAO class functions. What would be a good way to do it?</p>
<p>Below are some of the methods in a sample DAO class:</p>
<pre><code>
@Repository
public class PortfolioDaoImpl implements PortfolioDao {
    
private static final Logger log = LoggerFactory.getLogger(PortfolioDaoImpl.class);
    
    public List&lt;Portfolio&gt; findAll(Pageable pageable){
        log.info(&quot;findAll in DaoImpl..&quot;);
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            
            String sql = &quot;SELECT * FROM PMS_PORT order by ID desc &quot;;                
                    
            NativeQuery sqlQuery = session.createSQLQuery(sql);
    
            sqlQuery.addEntity(Portfolio.class);
            sqlQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
            sqlQuery.setMaxResults(pageable.getPageSize());
    
            List&lt;Portfolio&gt; portfolio = sqlQuery.list();
            
            return portfolio;
        } catch (Exception e) {
            // convert to HibernateException then to DataAccessException
            throw SessionFactoryUtils.convertHibernateAccessException(new HibernateException(e.getMessage()));
        }
    }
    
    public void addPortfolio(Portfolio portfolioForm) {
        log.info(&quot;adding portfolio in DaoImpl..&quot;);
        
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            Transaction transaction = session.beginTransaction();
            
            String sql = &quot;insert into PMS_PORT (ID,PORT_NAME,CREATED_BY,CREATED_DT,LAST_MDFY_BY,LAST_MDFY_DT,REMARKS) values &quot;
                    + &quot;(SQ_PMS_PORT.nextval, :portfolioName, :createdBy, sysdate , :lastMdfyBy, sysdate, :remarks)&quot; ; 
            
            NativeQuery query = session.createSQLQuery(sql);
            query.setParameter(&quot;portfolioName&quot;, portfolioForm.getPortfolioName());
            query.setParameter(&quot;createdBy&quot;, portfolioForm.getCreatedBy());
            query.setParameter(&quot;lastMdfyBy&quot;, portfolioForm.getLastMdfyBy());
            query.setParameter(&quot;remarks&quot;, portfolioForm.getRemarks());
            query.executeUpdate();
            
            transaction.commit();
            session.close();
            
        } catch (Exception e) {
            // convert to HibernateException then to DataAccessException
            throw SessionFactoryUtils.convertHibernateAccessException(new HibernateException(e.getMessage()));
        }
    }
    
    public Portfolio updatePortfolio(Portfolio portfolioForm){
        log.info(&quot;updating portfolio in DaoImpl..&quot;);
        
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            Transaction transaction = session.beginTransaction();
            
            String sql = &quot;update PMS_PORT set port_name =:portfolioName, remarks = :remarks, &quot;
                    + &quot;last_mdfy_by = :lastMdfyBy, last_mdfy_dt = sysdate where id = :id&quot;;
            
            log.info(&quot;id: &quot; + portfolioForm.getId().toString());
            
            NativeQuery query = session.createSQLQuery(sql);
            query.setParameter(&quot;id&quot;,portfolioForm.getId());
            query.setParameter(&quot;portfolioName&quot;,portfolioForm.getPortfolioName());
            query.setParameter(&quot;remarks&quot;, portfolioForm.getRemarks());
            query.setParameter(&quot;lastMdfyBy&quot;, portfolioForm.getLastMdfyBy());        
            query.executeUpdate();
            
            transaction.commit();
            session.close();
        
            return portfolioForm;
        
        } catch (Exception e) {
            // convert to HibernateException then to DataAccessException
            throw SessionFactoryUtils.convertHibernateAccessException(new HibernateException(e.getMessage()));
        }
    }
    
    public void deletePortfolio(long id) {
        log.info(&quot;deleting portfolio in DaoImpl..&quot;);
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            Transaction transaction = session.beginTransaction();
            
            String sql1 = &quot;delete from PMS_PORT where id = :id&quot;; 
            String sql2 = &quot;delete from PMS_PORT_TRANS where port_id = :id&quot;;
            String sql3 = &quot;delete from PMS_PORT_HOLD where port_id = :id&quot;;
            String sql4 = &quot;delete from PMS_UNREAL_PL where port_id = :id&quot;;
            String sql5 = &quot;delete from PMS_REAL_PL where port_id = :id&quot;;
            
            NativeQuery query = session.createSQLQuery(sql1);
            query.setParameter(&quot;id&quot;,id);
            query.executeUpdate();
            
            NativeQuery query2 = session.createSQLQuery(sql2);
            query2.setParameter(&quot;id&quot;,id);
            query2.executeUpdate();
            
            NativeQuery query3 = session.createSQLQuery(sql3);
            query3.setParameter(&quot;id&quot;,id);
            query3.executeUpdate();
            
            NativeQuery query4 = session.createSQLQuery(sql4);
            query4.setParameter(&quot;id&quot;,id);
            query4.executeUpdate();
            
            NativeQuery query5 = session.createSQLQuery(sql5);
            query5.setParameter(&quot;id&quot;,id);
            query5.executeUpdate();
            
            transaction.commit();
            session.close();
        
        } catch (Exception e) {
            // convert to HibernateException then to DataAccessException
            throw SessionFactoryUtils.convertHibernateAccessException(new HibernateException(e.getMessage()));
        }
    }
</code></pre>
<p>My idea is to do something like below. But I think modifying data on the actual tables are not a good way to do testing. Will using dummy table be feasible? How can i do so?</p>
<pre><code>
@Test
public void TestAddPortfolio(){
  
//Make sure that table PMS_PORT has 0 record

  //create new object -&gt;     Portfolio portfolio = new Portfolio();

  //execute addPortfolio(Portfolio portfolio)

  //assert that PMS_PORT has 1 record
}
</code></pre>
",https://stackoverflow.com/questions/72715859/how-to-perform-unit-testing-for-hibernate-transactional-query-statements,"['hibernate', 'unit-testing', 'testing', 'transactions']",83,False,0,0
Unit Testing with Jest and React - Axios Get Inside useEffect,"<p>How do I write a unit test in Jest for the initializePlayers function inside the useEffect?
Test if the call is working?</p>
<pre><code>export default function App() {

...

  useEffect(() =&gt; {
    const initializePlayers = async () =&gt; {
      await axios.get(url)
      .then(async res=&gt; {
        const activePlayers = res.data.filter(p =&gt; p.active === true);
        setPlayers(activePlayers);
      }).catch(err =&gt; {
        console.log(err);
      })
    }

    initializePlayerPool();
  }, []);
</code></pre>
",https://stackoverflow.com/questions/72371362/unit-testing-with-jest-and-react-axios-get-inside-useeffect,"['reactjs', 'unit-testing', 'axios', 'jestjs', 'use-effect']",1370,True,0,1
Unit testing a method whose statements run on different task,"<p>I have a method:</p>
<pre><code>public class WorkerClass : IWorkerClass
{
private int myworkId = 0;
public void Workflow(int theWorkid)
        {
            var aTask = new Task(() =&gt;
            {
                this.myworkId = theWorkid;
                //Some calculations
              
            });

            aTask.Start();
        }
}
</code></pre>
<p>I have a Unit test method :</p>
<pre><code>[DataTestMethod]
[DataRow(23)]
public class workerTester
{
 public void WorkflowTest(int theWorkflowMode)
        {
            // Arrange 
           
            var aWorkTester = new Mock&lt;IWorkerClass&gt;();
            var aExpectedWorkflowMode = 23;
            myWorkerPrivateObj = new PrivateObject(aWorkTester);

            // Act

            myWorkerPrivateObj .Invoke(&quot;Workflow&quot;, theWorkflowMode);

            // Assert

            //Thread.Sleep(1000); If i uncomment it works
            var aActualWorkflowModeType = myWorkerPrivateObj.GetField(&quot;myworkId&quot;);
            Assert.AreEqual(aExpectedWorkflowModeType, aActualWorkflowModeType);
            
        }
}
</code></pre>
<p>If i uncomment Thread.Sleep(1000), aActualWorkflowModeType comes as 23. But if i comment it aActualWorkflowModeType comes as 0. I am assuming my assert is called before my task is complete.
How can i wait until task is complete in my Unit test?</p>
",https://stackoverflow.com/questions/71124844/unit-testing-a-method-whose-statements-run-on-different-task,"['c#', 'multithreading', 'unit-testing', 'moq']",40,True,-1,1
React unit testing - accessing querystring parameters off the match object,"<p>I am trying to test a React component against various querystring options. This is a simplified version of my test code.</p>
<pre><code>import { Provider } from 'react-redux';
import { act, render } from '@testing-library/react';
import { BrowserRouter as Router } from 'react-router-dom';

const defaultProps = {
    match: { params: { id: 1 } },
};

act(async () =&gt; {
    render(
        &lt;Provider store={mockStore()}&gt;
            &lt;Router&gt;
                &lt;ComponentToTest {...defaultProps} /&gt;
            &lt;/Router&gt;
        &lt;/Provider&gt;
    );
});

</code></pre>
<p>However, the match object is somehow being overwritten (I suspect by the Router) to:</p>
<pre><code>{ path: '/', url: '/', params: {}, isExact: true }
</code></pre>
<p>The ComponentToTest is looking for match as a top level property.</p>
<pre><code>export const ComponentToTest = ({ match, history }) =&gt; {
    // Stuff here which uses redux, match and history
};
</code></pre>
<p>How should I be passing in the match data into this component?</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/71526614/react-unit-testing-accessing-querystring-parameters-off-the-match-object,"['reactjs', 'unit-testing']",31,False,0,1
Receiving null Element when unit testing FormGroup as an Observable,"<p>I've been trying to unit test this bit of code for a couple hours and I've become completely stuck. All I need to do is test that the form is visible.</p>
<p><strong>component.ts</strong></p>
<pre><code>form$ = Observable&lt;FormGroup&gt;

constructor() {
    this.form$ = this.fieldData$.pipe(
        map(values =&gt; this.formBuilder.group({}))
    )
}
</code></pre>
<p><strong>component.spec.ts</strong></p>
<pre><code>describe('handling fields with a response', () =&gt; {
  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AppComponent)
    component = fixture.componentInstance
    fixture.detectChanges()
  })

  it('should display the form', fakeAsync(() =&gt; {
    component.form$ = component.fieldData$.pipe(
      (responseBody: any) =&gt; of(ResponseBody)
    )
    component.form$.subscribe((value: FormGroup) =&gt; {
      expect(value).toStrictEqual(ResponseBody)
      fixture.detectChanges()
      fixture.whenStable()
      const form = fixture.debugElement.query(By.css('#form')).nativeElement
      expect(form).toBeTruthy()
    })
    flush()
  }))
})
</code></pre>
<p>However when I run this test I get the following error message</p>
<p><code>TypeError: this.form._updateTreeValidity is not a function</code></p>
<p>If I remove the <code>fixture.detectChanges()</code> from inside of the display test I receive:
<code>TypeError: Cannot read property 'nativeElement' of null</code></p>
<p>I would like to be able to receive the following from this posting:</p>
<ol>
<li>Why this occurs</li>
<li>Best Practices</li>
<li>Guide to solutions</li>
</ol>
",https://stackoverflow.com/questions/72805912/receiving-null-element-when-unit-testing-formgroup-as-an-observable,"['angular', 'unit-testing']",72,False,0,0
how to configure a service for unit testing in angular,"<p>One of the service(ProductService) is dependent on the LoggerService, want to perform the unit testing ofProductService.
Spyobj Loggerservice is registered in the provider of the testbed and in the testcase will get the ProductService using TestBed.Inject(ProductService).</p>
<p>Compared testcase with the one of the example available in the angular.io -&gt; <a href=""https://angular.io/guide/testing-services"" rel=""nofollow noreferrer"">https://angular.io/guide/testing-services</a>
In the example both Service and dependent service are registered in the provider of the testbed.</p>
<p>Do we need to register in the provider array of the test bed before getting the ProductService using TestBed.Inject?</p>
<pre><code>            let masterService: MasterService;
            let valueServiceSpy: jasmine.SpyObj&lt;ValueService&gt;;

            beforeEach(() =&gt; {
              const spy = jasmine.createSpyObj('ValueService', ['getValue']);

              TestBed.configureTestingModule({
                // Provide both the service-to-test and its (spy) dependency
                providers: [
                  MasterService,
                  { provide: ValueService, useValue: spy }
                ]
              });
              // Inject both the service-to-test and its (spy) dependency
              masterService = TestBed.inject(MasterService);
              valueServiceSpy = TestBed.inject(ValueService) as jasmine.SpyObj&lt;ValueService&gt;;
            });


            export class LogserviceService {

              constructor() { }

              public logMessage(value:string)
              {
                console.log(value);
              }
            }

            export class ProductService {

               products:IProduct[]=[];

              constructor(private logservice:LogserviceService) {
                console.log('getting the service created');
                console.log(logservice);
                console.log(logservice instanceof (LogserviceService));
               }
              getProducts(): IProduct[] {

                this.products =
                [
                  {name:&quot;TV&quot;,cost:100,model:&quot;123434&quot;,category:&quot;Electronics&quot;},
                 
                ];

                this.logservice.logMessage(&quot;I am in the product service&quot;);

                return this.products;
              }

              getProduct(category:string):IProduct[]
              {
                this.logservice.logMessage(&quot;callling getProduct&quot;);

                let products = this.getProducts();
                let prodct= products.filter(x=&gt;x.category ===category);
                return prodct;
              }

            }

            describe('ProductService', () =&gt; {
              let service: ProductService;
              let logService: LogserviceService;

              logService = jasmine.createSpyObj(['logMessage']);
              beforeEach(() =&gt; {
                TestBed.configureTestingModule({
                  providers: [{ provide: LogserviceService, useValue: logService },
                    
                  ],
                });
              });

             
              it('should get the product list, if valid caterogy is sent', () =&gt; {
               
                let service = TestBed.inject(ProductService);  //product service not registered in the providers
                let products = service.getProduct('Electronics');

                expect(products.length).toBeGreaterThan(0);
                expect(logService.logMessage).toHaveBeenCalledWith('callling getProduct');
                expect(products[0].category).toEqual('Electronics');

              });
            });
</code></pre>
",https://stackoverflow.com/questions/71527479/how-to-configure-a-service-for-unit-testing-in-angular,"['angular', 'jasmine']",393,False,0,0
Unit testing - how to set values for mock object Python,"<p>I'm a beginner to unit test in Python - I'm trying to test a function which takes in a class object and returns a set of strings. Input is a class object with some_attr Ps, p is also a class object with attribute 'name'.</p>
<pre><code>def my_func(input):
    results = set(map(lambda p: p.name, input.Ps))
    return results
</code></pre>
<p>I'm trying to use Mock module by setting the input as a mock object.</p>
<pre><code>@dataclass
class TestClass:
    name: str

@patch('some related module')
def Test_my_func(TestCase, mock_input):
    import my_func
    mock_input = MagicMock()
    p1 = TestClass('name1')
    p2 = TestClass('name2')
    mock_input.Ps.return_value = tuple([p1, p2])
    expectedResult = set(['name1', 'name2'])

    self.assertEqual(my_func(mock_input), expectedResult)
</code></pre>
<p>The issue I'm having is that my_func(mock_input) returns set() and did not pick up the mock_input.Ps.return_value = tuple([p1, p2]) as I expected. Can someone please shed some light on this? Much appreciated.</p>
<pre><code>Error message: AssertionError: Items in the second set but not the first
</code></pre>
",https://stackoverflow.com/questions/73256980/unit-testing-how-to-set-values-for-mock-object-python,"['python', 'unit-testing', 'testing', 'mocking', 'magicmock']",636,True,0,1
How does the unit testing works in Web API testing,"<p>I have a below code which is working fine. But I am not able to understand how <strong>act</strong> part works in below code. When I am debugging the code, it's not hitting to DB which is expected in unit testing as we do it using mock data instead of actual DB data. But then what is the use of below line and how does it make test successful while comparing the result with mock data.</p>
<pre><code>[Fact]
        public async Task GetEmployee_ShouldReturnOk()

        {

            //arrange
            var employees = fixure.Create&lt;List&lt;Employee&gt;&gt;();
            var empName = fixure.Create&lt;string&gt;();

            empService.Setup(x =&gt; x.GetEmployee(empName)).ReturnsAsync(employees);
            
            //act
            //this line is calling a controller method but not hitting to data access layer. So from where its getting data?
            var employeesResult = await EmpController.GetEmployee(empName);
            //assert
            employeesResult.Should().NotBeNull();
            employeesResult.Should().BeAssignableTo&lt;ActionResult&lt;IEnumerable&lt;Employee&gt;&gt;&gt;();
            employeesResult.Result.Should().BeAssignableTo&lt;OkObjectResult&gt;();
            empService.Verify(x=&gt;x.GetEmployee(empName), Times.Once());
        }
</code></pre>
",https://stackoverflow.com/questions/74191447/how-does-the-unit-testing-works-in-web-api-testing,"['.net', 'unit-testing', '.net-core', 'asp.net-web-api', 'xunit']",39,False,0,1
Unit testing ViewChild and MockedDirective prevents it from being initialized,"<p>When running a unit test to see if a ViewChild is DEFINED, it fails to initialized.  This only occurs if I have the *appUserProfile directive on the component.</p>
<p>Otherwise the unit test will pass and the ViewChild will be DEFINED. Please Help.</p>
<pre><code>&lt;div id=&quot;user&quot; *appUserProfile=&quot;[ Profile.GAPGENAC ]&quot; style=&quot;text-align: right&quot;&gt;
  &lt;div class=&quot;page-title-div&quot;&gt;
    &lt;mat-label class=&quot;page-title&quot;&gt;View Roster&lt;/mat-label&gt;
  &lt;/div&gt;
  &lt;div style=&quot;width: 100%; margin: 0 auto&quot;&gt;
    &lt;div class=&quot;view-roster-controls&quot;&gt;
      &lt;div id=&quot;filter-text-box-container&quot;&gt;
        &lt;img
          id=&quot;view-roster-search-icon&quot;
          src=&quot;../../assets/icons/search-outline.svg&quot;
          class=&quot;search-icon&quot;
          alt=&quot;search&quot;
        /&gt;
        &lt;input
          id=&quot;filter-text-box&quot;
          aria-label=&quot;Filter&quot;
          (input)=&quot;onFilterTextBoxChanged()&quot;
          type=&quot;text&quot;
          placeholder=&quot;Search the Roster&quot;
        /&gt;
      &lt;/div&gt;
      &lt;div id=&quot;right-controls-container&quot;&gt;
        &lt;button
          id=&quot;view-roster-export&quot;
          (click)=&quot;onBtnExport()&quot;
          value=&quot;Export to CSV&quot;
        &gt;
          &lt;img
            id=&quot;view-roster-export-icon&quot;
            src=&quot;../../assets/icons/download-outline.svg&quot;
            class=&quot;export-icon&quot;
            alt=&quot;search&quot;
          /&gt;
          &lt;p id=&quot;export-button-text&quot;&gt;Export to CSV&lt;/p&gt;
        &lt;/button&gt;
        &lt;div class=&quot;roster-controls-vertical-break&quot;&gt;&lt;/div&gt;
        &lt;div id=&quot;display-columns-container&quot;&gt;
          &lt;div style=&quot;display: flex; height: 100%&quot;&gt;
            &lt;img
              id=&quot;view-roster-columns-icon&quot;
              src=&quot;../../assets/icons/columns.svg&quot;
              class=&quot;columns-icon&quot;
              alt=&quot;column&quot;
            /&gt;
            &lt;p id=&quot;displayed-columns-text&quot;&gt;Display Columns&lt;/p&gt;
          &lt;/div&gt;
          &lt;mat-form-field id=&quot;invisible-display-columns&quot; appearance=&quot;fill&quot;&gt;
            &lt;mat-label for=&quot;displayColumn&quot; id=&quot;mat-lbl-display-col&quot;
              &gt;Displayed Columns&lt;/mat-label
            &gt;
            &lt;mat-select
              multiple
              [formControl]=&quot;selectFormControl&quot;
              role=&quot;combobox&quot;
              id=&quot;mat-sel-display-col&quot;
              aria-label=&quot;select&quot;
              aria-expanded=&quot;false&quot;&gt;
              &lt;mat-option
                role=&quot;option&quot;
                for=&quot;displayColumn&quot;
                *ngFor=&quot;let column of columnDefs&quot;
                [value]=&quot;column.field&quot;
                [attr.aria-label]=&quot;column.headerName&quot;
                aria-disabled=&quot;true&quot;
                (onSelectionChange)=&quot;selectionChange($event)&quot;
                &gt;{{ column.headerName }}&lt;/mat-option&gt;
            &lt;/mat-select&gt;
            &lt;div id=&quot;panel&quot;&gt;&lt;/div&gt;
          &lt;/mat-form-field&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    &lt;/div&gt;
    &lt;ag-grid-angular
      id=&quot;member-roster&quot;
      #memberRosterGrid
      style=&quot;width: 100%&quot;
      class=&quot;ag-theme-alpine&quot;
      [columnDefs]=&quot;columnDefs&quot;
      [rowData]=&quot;rowData$ | async&quot;
      [defaultColDef]=&quot;defaultColDef&quot;
      [pagination]=&quot;true&quot;
      [paginationPageSize]=&quot;15&quot;
      [unSortIcon]=&quot;true&quot;
      (gridReady)=&quot;onGridReady()&quot;
      (cellValueChanged)=&quot;onCellValueChanged()&quot;
      (displayedColumnsChanged)=&quot;onDisplayedColumnsChanged($event)&quot;
      (columnVisible)=&quot;oncolumnVisible()&quot;
      (sortChanged)=&quot;onSortChanged()&quot;
      (filterChanged)=&quot;onFilterChanged()&quot;
      (paginationChanged)=&quot;onPaginationChanged()&quot;
      (bodyScroll)=&quot;onBodyScroll()&quot;
    &gt;
    &lt;/ag-grid-angular&gt;
  &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<pre><code>import { HttpClientTestingModule } from '@angular/common/http/testing';
import { Input, Directive, OnInit } from '@angular/core';
import { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AgGridModule } from 'ag-grid-angular';
import { Observable } from 'rxjs';
import { UserProfileDirective } from 'src/app/directives/user-profile-directive';
import { Profile } from 'src/app/models/profile';
import { MaterialModule } from '../../material/material.module';
import { MemberRoster } from '../../models/memberroster.model';
import { AuthenticationService } from '../../services/authentication.service';
import { MemberService } from '../../services/member.service';
import { MemberrosterComponent } from './memberroster.component';

@Directive({ selector: '[appUserProfile]' })
export class MockUserProfileDirective implements OnInit {
    @Input() appUserProfile: Profile[];

    ngOnInit() {
        console.log('mocked Directive: ', this.appUserProfile);
    }
}

fdescribe('MemberRosterComponent', () =&gt; {
    let component: MemberrosterComponent;
    let fixture: ComponentFixture&lt;MemberrosterComponent&gt;;
    let authServiceMock: AuthenticationService;
    let authServiceSpyObj = jasmine.createSpyObj('AuthenticationService', ['isAuthenticated']);

    let memberServiceSpyObj = jasmine.createSpyObj('MemberService', ['getMembers']);
    memberServiceSpyObj.getMembers.and.returnValue(new Observable&lt;MemberRoster[]&gt;());

    beforeEach(async () =&gt; {
        await TestBed.configureTestingModule({
            declarations: [
                MemberrosterComponent,
                MockUserProfileDirective
            ],
            imports: [
                HttpClientTestingModule,
                AgGridModule,
                MaterialModule,
                BrowserAnimationsModule,
                ReactiveFormsModule
            ],
            providers: [
                { provide: AuthenticationService, useValue: authServiceSpyObj },
                { provide: MemberService, useValue: memberServiceSpyObj }
            ]
        })
            .compileComponents();

        fixture = TestBed.createComponent(MemberrosterComponent);

        component = fixture.componentInstance;
    });

    it('should create', () =&gt; {
        fixture.detectChanges();

        expect(component).toBeTruthy();
        expect(component.rowData$).toBeDefined();
    });

    fit('grid API is available after `detectChanges`', fakeAsync(() =&gt; {
        // Setup template bindings and run ngOInit. This causes the &lt;ag-grid-angular&gt; component to be created.
        // As part of the creation the grid apis will be attached to the gridOptions property.
        fixture.detectChanges();
        flush();
        console.log('component.grid: ', component.grid);
        expect(component.grid.api).toBeDefined();
    }));
});
</code></pre>
<pre><code>import { Component, ViewChild, OnInit, ViewEncapsulation } from &quot;@angular/core&quot;;
import { Router } from &quot;@angular/router&quot;;
import { ILdapUser } from &quot;../../models/ldap-user&quot;;
import { AuthenticationService } from &quot;../../services/authentication.service&quot;;
import { MemberService } from &quot;../../services/member.service&quot;;
import { MemberRoster } from &quot;../../models/memberroster.model&quot;;
import { ColDef, ICellRendererParams, DisplayedColumnsChangedEvent } from &quot;ag-grid-community&quot;;
import { AgGridAngular } from &quot;ag-grid-angular&quot;;
import { FormControl } from &quot;@angular/forms&quot;;
import { MatOptionSelectionChange } from &quot;@angular/material/core&quot;;
import { Profile } from '../../models/profile';
import { Observable } from &quot;rxjs&quot;;

@Component({
  selector: &quot;app-memberroster&quot;,
  templateUrl: &quot;./memberroster.component.html&quot;,
  styleUrls: [&quot;./memberroster.component.css&quot;],
  encapsulation: ViewEncapsulation.None,
})
export class MemberrosterComponent implements OnInit {
  @ViewChild(&quot;memberRosterGrid&quot;) grid!: AgGridAngular;
  user: ILdapUser;
  rowData$: Observable&lt;MemberRoster[]&gt;;
  userName: string;
  groupNumber: string;
  Profile = Profile;

  constructor(
    public authService: AuthenticationService,
    public memberService: MemberService,
    private router: Router
  ) { }

  ngOnInit() {
    console.log('ngOnInit called');
    const ariaHiddenControls = document.querySelectorAll(
      '[aria-hidden=&quot;true&quot;]'
    );
    ariaHiddenControls.forEach((b) =&gt; b.setAttribute(&quot;tabindex&quot;, &quot;-1&quot;));

    this.rowData$ = this.memberService.getMembers();

    const pageControls = document.getElementById(&quot;ag-25-row-count&quot;);
    if (pageControls) {
      pageControls.insertAdjacentText(&quot;afterend&quot;, &quot; records&quot;);
    }
  }

  columnDefs: ColDef[] = [
    {
      field: &quot;health_id&quot;,
      headerName: &quot;Member ID&quot;,
      cellClass: &quot;cellAlignment&quot;
    },
    {
      field: &quot;last_name&quot;,
      sort: &quot;asc&quot;,
      sortIndex: 0,
      headerName: &quot;Last Name&quot;,
      cellClass: &quot;cellAlignment&quot;,
      filter: &quot;agTextColumnFilter&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
      },
      width: 160
    },
    {
      field: &quot;first_name&quot;,
      headerName: &quot;First Name&quot;,
      filter: &quot;agTextColumnFilter&quot;,
      cellClass: &quot;cellAlignment&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
      },
      width: 160
    },
    {
      field: &quot;birth_date&quot;,
      headerName: &quot;Date of Birth&quot;,
      comparator: this.dateComparator,
      filter: &quot;agDateColumnFilter&quot;,
      cellClass: &quot;cellAlignment&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
        comparator: (filterLocalDateAtMidnight, cellValue) =&gt; {
          const cellDate = new Date(cellValue);

          if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) {
            return 0;
          }

          if (cellDate &lt; filterLocalDateAtMidnight) {
            return -1;
          }

          if (cellDate &gt; filterLocalDateAtMidnight) {
            return 1;
          }
        },
      }
    },
    {
      field: &quot;contract_type&quot;,
      headerName: &quot;Contract Type&quot;,
      cellClass: &quot;cellAlignment&quot;,
      filter: &quot;agTextColumnFilter&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
      }
    },
    {
      field: &quot;enrollment_status&quot;,
      headerName: &quot;Enrollment Status&quot;,
      filter: &quot;agTextColumnFilter&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
      },
      cellRenderer: this.enrollmentStatusRenderer
    },
    {
      field: &quot;section_number&quot;,
      headerName: &quot;Section #&quot;,
      cellClass: &quot;cellAlignment&quot;,
      filter: &quot;agNumberColumnFilter&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
      }
    },
    {
      field: &quot;section_name&quot;,
      headerName: &quot;Section Name&quot;,
      cellClass: &quot;cellAlignment&quot;,
      filter: &quot;agTextColumnFilter&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
      }
    },
    {
      field: &quot;section_description&quot;,
      headerName: &quot;Section Description&quot;,
      cellClass: &quot;cellAlignment&quot;,
      filter: &quot;agTextColumnFilter&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
      }
    },
    {
      field: &quot;cancel_date&quot;,
      headerName: &quot;Cancel Date&quot;,
      comparator: this.dateComparator,
      filter: &quot;agDateColumnFilter&quot;,
      cellClass: &quot;cellAlignment&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
        comparator: (filterLocalDateAtMidnight, cellValue) =&gt; {
          const cellDate = new Date(cellValue);

          if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) {
            return 0;
          }

          if (cellDate &lt; filterLocalDateAtMidnight) {
            return -1;
          }

          if (cellDate &gt; filterLocalDateAtMidnight) {
            return 1;
          }
        },
      }
    },
    {
      field: &quot;department_number&quot;,
      headerName: &quot;Department&quot;,
      cellClass: &quot;cellAlignment&quot;,
      filter: &quot;agTextColumnFilter&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
      }
    },
    {
      field: &quot;employee_id&quot;,
      headerName: &quot;Employee ID&quot;,
      cellClass: &quot;cellAlignment&quot;,
      filter: &quot;agTextColumnFilter&quot;,
      filterParams: {
        buttons: [&quot;clear&quot;, &quot;apply&quot;],
      }
    }
  ];

  public defaultColDef: ColDef = {
    resizable: true,
    sortable: true,
    minWidth: 100,
    width: 200,
    icons: {
      menu: &quot;&lt;img src='../../assets/icons/filter.svg' class='view-roster-filter-icon' alt='filter'&gt;&quot;,
      move: &quot;&lt;img id='view-roster-move-icon' src='../../assets/icons/move-outline.svg' class='move-icon' alt='move'&gt;&quot;,
      sortAscending: &quot;&lt;div class='sort-icon-container'&gt;&quot; +
        &quot;&lt;img src='../../assets/icons/caret-up-outline-green.svg' class='sort-icon-top' alt='ascending sort'&gt;&quot; +
        &quot;&lt;img src='../../assets/icons/caret-down-outline.svg' class='sort-icon-bottom' alt='ascending sort'&gt;&quot; +
        &quot;&lt;/div&gt;&quot;,
      sortDescending: &quot;&lt;div class='sort-icon-container'&gt;&quot; +
        &quot;&lt;img src='../../assets/icons/caret-up-outline.svg' class='sort-icon-top' alt='ascending sort'&gt;&quot; +
        &quot;&lt;img src='../../assets/icons/caret-down-outline-green.svg' class='sort-icon-bottom' alt='ascending sort'&gt;&quot; +
        &quot;&lt;/div&gt;&quot;,
      sortUnSort: &quot;&lt;div class='sort-icon-container'&gt;&quot; +
        &quot;&lt;img src='../../assets/icons/caret-up-outline.svg' class='sort-icon-top' alt='ascending sort'&gt;&quot; +
        &quot;&lt;img src='../../assets/icons/caret-down-outline.svg' class='sort-icon-bottom' alt='ascending sort'&gt;&quot; +
        &quot;&lt;/div&gt;&quot;
    }
  };

  selectFormControl: FormControl = new FormControl(
    this.columnDefs.filter((col) =&gt; !col.hide).map((col) =&gt; col.field)
  );

  selectionChange(event: MatOptionSelectionChange) {
    if (event.isUserInput) {
      this.grid.columnApi.applyColumnState({
        state: [
          {
            colId: event.source.value,
            hide: !event.source.selected,
          },
        ],
      });
    }
  }

  ariaControlsReset() {
    let controls = document.querySelectorAll(
      '[aria-description=&quot;Press ENTER to sort. Press CTRL ENTER to open column menu.&quot;]'
    );
    controls.forEach((b) =&gt; b.removeAttribute(&quot;aria-description&quot;));
    controls = document.querySelectorAll(
      '[aria-description=&quot;Press ENTER to sort.&quot;]'
    );
    controls.forEach((b) =&gt; b.removeAttribute(&quot;aria-description&quot;));
    document.querySelector('[id=&quot;mat-sel-display-col&quot;]').setAttribute(&quot;aria-controls&quot;, &quot;panel&quot;);
  }

  onGridReady() {
    console.log('on grid ready');
    this.ariaControlsReset();
  }
  onCellValueChanged() {
    this.ariaControlsReset();
  }
  onDisplayedColumnsChanged(event: DisplayedColumnsChangedEvent) {
    this.ariaControlsReset();
    for (let col of event.columnApi.getColumns()) {
      if (!(event.columnApi.getAllDisplayedColumns().includes(col))) {
        this.columnDefs.filter(colDef =&gt; colDef.field === col.getColDef().field).forEach(colDef =&gt; colDef.hide = true);
      }
      else {
        this.columnDefs.filter(colDef =&gt; colDef.field === col.getColDef().field).forEach(colDef =&gt; colDef.hide = false);
      }
    }
    this.selectFormControl = new FormControl(
      this.columnDefs.filter((col) =&gt; !col.hide).map((col) =&gt; col.field)
    );
  }
  oncolumnVisible() {
    this.ariaControlsReset();
  }
  onSortChanged() {
    this.ariaControlsReset();
  }
  onFilterChanged() {
    this.ariaControlsReset();
  }
  onPaginationChanged() {
    this.ariaControlsReset();
  }
  onBodyScroll() {
    this.ariaControlsReset();
  }

  dateComparator(date1, date2) {
    const date1Number = date1 &amp;&amp; new Date(date1).getTime();
    const date2Number = date2 &amp;&amp; new Date(date2).getTime();

    if (date1Number === null &amp;&amp; date2Number === null) {
      return 0;
    }

    if (date1Number === null) {
      return -1;
    } else if (date2Number === null) {
      return 1;
    }

    return date1Number - date2Number;
  }

  onFilterTextBoxChanged() {
    this.grid.api.setQuickFilter(
      (document.getElementById(&quot;filter-text-box&quot;) as HTMLInputElement).value
    );
  }

  onBtnExport() {
    this.grid.api.exportDataAsCsv();
  }

  enrollmentStatusRenderer(params: ICellRendererParams) {
    let cssClass = &quot;&quot;;
    if (params.value === &quot;Active&quot;)
      cssClass = &quot;member-roster-enrollment-status-active&quot;;
    else if (params.value === &quot;Cancelled&quot;)
      cssClass = &quot;member-roster-enrollment-status-cancelled&quot;;
    else if (params.value === &quot;Future&quot;)
      cssClass = &quot;member-roster-enrollment-status-future&quot;;

    return &quot;&lt;div class=&quot; + cssClass + &quot;&gt;&quot; + params.value + &quot;&lt;/div&gt;&quot;;
  }
}
</code></pre>
",https://stackoverflow.com/questions/74868409/unit-testing-viewchild-and-mockeddirective-prevents-it-from-being-initialized,"['angular', 'jasmine']",104,True,0,1
How to write a Unit testing for Azure Function app?,"<p>I have an azure function based on .Net core 3.1. It triggers when a file is uploaded into the Azure Blob Container, processes the CSV file and updates the database</p>
<p>Below is the code excerpt</p>
<p><strong>FileTrigger.cs</strong></p>
<pre><code>namespace aspnetcore_azurefun_blob
{
    [StorageAccount(&quot;AzureWebJobsStorage&quot;)]
    public class FileTrigger
    {
        #region Property
        private readonly IFileProcessor fileProcessor;
        #endregion

        #region Constructor
        public FileTrigger(IFileProcessor fileProcessor)
        {
            this.fileProcessor = fileProcessor;
        }
        #endregion

        [FunctionName(&quot;FileTrigger&quot;)]
        public void ProcessFilesFromSamplesContainer([BlobTrigger(&quot;samples-workitems/{name}&quot;)]Stream myBlob, string name, ILogger log, ExecutionContext context)
        {
            log.LogInformation(&quot;Function: ProcessFilesFromSamplesContainer is called&quot;);
            log.LogInformation($&quot;C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes&quot;);

            var result = fileProcessor.ProcessAsync(myBlob, name, log, context);

            log.LogInformation($&quot;Function Completed {result.Result} on {DateTime.Now.ToLongDateString()} @ {DateTime.Now.ToShortTimeString()}.\n.&quot;);
        }
    }
}
</code></pre>
<p><strong>FileProcessor.cs</strong></p>
<pre><code>namespace ClientCore.Processor
{
    public interface IFileProcessor
    {
        Task&lt;string&gt; ProcessAsync(Stream myBlob, string name, ILogger log, ExecutionContext context);
    }

    public class FileProcessor : IFileProcessor
    {
        #region Property
        private readonly IFileProcessingServiceFacade fileProcessingService;
        #endregion

        #region Constructor
        public FileProcessor(IFileProcessingServiceFacade fileProcessingService)
        {
            this.fileProcessingService = fileProcessingService;
        }
        #endregion

        #region Public Methods
        public async Task&lt;string&gt; ProcessAsync(Stream myBlob, string name, ILogger log, ExecutionContext context)
        {
            var processingResult = fileProcessingService.ProcessAsync(myBlob, name, log, context);

            return await Task.FromResult($&quot;{processingResult.Result}&quot;);
        }
        #endregion

    }
}
</code></pre>
<p><strong>FileProcessingService.cs</strong></p>
<pre><code>namespace BusinessService.Services
{
    public interface IFileProcessingServiceFacade
    {
        Task&lt;string&gt; ProcessAsync(Stream myBlob, string name, ILogger log, ExecutionContext context);
    }

    partial class FileProcessingServiceFacade : IFileProcessingServiceFacade
    {
        #region Public Methods
        public async Task&lt;string&gt; ProcessAsync(Stream myBlob, string name, ILogger log, ExecutionContext context)
        {
            // Get the Contents from the CSV File
            var csvData = GetCSVData(myBlob);

            AppDbContext.FileRecords.Add(new FileRecords
            {
                FileName = name,
                IsCompleted = DefaultValues.IsCompleted
            });
            AppDbContext.SaveChanges();

            log.LogInformation($&quot;Reading configuration from the configuration settings file: {Configurator.AzureSQLServerConfigurator.ConnnectionString}&quot;);
            log.LogInformation(&quot;Database is updated..!&quot;);

            return await Task.FromResult($&quot;success&quot;);
        }
        #endregion

    }

    partial class FileProcessingServiceFacade : ServiceBase&lt;FileProcessingServiceFacade&gt;
    {
        #region Constructor
        public FileProcessingServiceFacade(AppDbContext appDbContext, IOptions&lt;AppConfigurator&gt; configurator) 
            : base(appDbContext, configurator) { }
        #endregion

        #region Extract Data from CSV
        protected static List&lt;dynamic&gt; GetCSVData(Stream jobData)
        {
            try
            {
                #region CsvHelper Mapping and Conversion
                var csvHelperConfig = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    NewLine = Environment.NewLine,
                    PrepareHeaderForMatch = args =&gt; args.Header.ToUpper().Replace(&quot; &quot;, &quot;&quot;),
                    HasHeaderRecord = true
                };
                using var reader = new StreamReader(jobData);
                using var csvHelper = new CsvReader(reader, CultureInfo.InvariantCulture);
                csvHelper.Context.RegisterClassMap&lt;StudentDetailsMap&gt;();
                var csvHelperRrecords = csvHelper.GetRecords&lt;StudentDetails&gt;()
                    .Where(x =&gt; !string.IsNullOrWhiteSpace(x.Name))
                    .OrderBy(x =&gt; x.ID);

                return csvHelperRrecords.Cast&lt;dynamic&gt;().ToList();
                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
    }
}
</code></pre>
<p>How to write a Unit testing for the above Azure Function app? Just a head start is required.</p>
",https://stackoverflow.com/questions/72420799/how-to-write-a-unit-testing-for-azure-function-app,"['unit-testing', '.net-core', 'nunit', 'mstest', '.net-core-3.1']",1013,False,0,0
Unit-Testing Angular-Material mat-form-field input with ngModel,"<p>I am trying to test a value change in a mat-form-field input. I studied several solutions but i can't get it to work. The actual expect result is : &quot;<em>Expected '' to equal 'Open Travel'.</em>&quot; The value is correct stored in the native element but not in component.name. I really hope someone have a solution. I wasted already so much time on this.</p>
<p>This is my test:</p>
<pre><code> fit('some test definition', () =&gt; {
    fixture.whenStable().then(() =&gt; {
      expect(component.name).toEqual('');

      let inputName = fixture.debugElement.nativeElement.querySelector('#name');
      
      inputName.focus();
      inputName.value = 'Open Travel';
      inputName.dispatchEvent(new Event('input'));

      expect(component.name).toEqual('Open Travel');
    });
  });
</code></pre>
<p>snippet from html:</p>
<pre><code> &lt;mat-form-field appearance=&quot;fill&quot;&gt;
      &lt;mat-label&gt;Project Name&lt;/mat-label&gt;
      &lt;input id=&quot;name&quot; [(ngModel)]=&quot;name&quot; matInput&gt;
 &lt;/mat-form-field&gt;
</code></pre>
",https://stackoverflow.com/questions/74239835/unit-testing-angular-material-mat-form-field-input-with-ngmodel,"['angular', 'unit-testing', 'jasmine', 'karma-runner']",353,True,-1,1
How to mock react hooks while writing Unit testing (jest )?,"<p>I am writing some unit test cases which will test some functionality . So, basically it is giving me some error, while executing, saying &quot;CANT ACCEPT NULL OR UNDEFINED IN USESTATE, USEEFFECT&quot;.
My question is, if i want to test just its functionality, and want to skip all the hooks, how can i do that? or any other suggetions , on how to deal with React hooks , with unit testing in jest will be helpful.</p>
",https://stackoverflow.com/questions/74860238/how-to-mock-react-hooks-while-writing-unit-testing-jest,"['reactjs', 'unit-testing', 'react-hooks', 'jestjs']",47,False,0,0
Beans are null when unit testing spring-retry with SpringRunner,"<p>I am trying to write unit tests for a class having spring retry using the springRunner. But my @Autowired beans are null . Could you please let me know what I did wrong?</p>
<p>Below is my test class</p>
<pre><code>@RunWith(SpringRunner.class)
@ContextConfiguration
public class DeltaHelperTest {

    @Autowired
    private DeltaHelper deltaHelper;
    
    @Before
    public void setUp() { System.setProperty(&quot;delta.process.retries&quot;, &quot;2&quot;); }

    @After
    public void validate() { validateMockitoUsage(); }

    @Test
    public void retriesAfterOneFailAndThenPass() throws Exception {
        when(deltaHelper.restService.call(any(), any())).thenThrow(new HttpException());
        deltaHelper.process(any(),any());
        verify(deltaHelper, times(2)).process(any(), any());
    }

    @Configuration
    @EnableRetry
    @EnableAspectJAutoProxy(proxyTargetClass=true)
    @Import(MockitoSkipAutowireConfiguration.class)

    public static class Application {

        @Bean
        public DeltaHelper deltaHelper() {
            DeltaHelper deltaHelper = new DeltaHelper();
            deltaHelper.myStorageService= myStorageService();
            deltaHelper.restService = restService();
            return deltaHelper;
        }

        @Bean
        public MyStorageService myStorageService() {
            return new MyStorageService();
        }

        @Bean
        public MyRestService restService() {
            return new MyRestService();
        }

        @Bean
        public MyRepo myRepository() {
            return mock(MyRepo.class);
        }
    }


    @Configuration
    public static class MockitoSkipAutowireConfiguration {
        @Bean MockBeanFactory mockBeanFactory() {
            return new MockBeanFactory();
        }
        private static class MockBeanFactory extends InstantiationAwareBeanPostProcessorAdapter {
            @Override
            public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
                return !mockingDetails(bean).isMock();
            }
        }
    }
}
</code></pre>
<blockquote>
<p>Here test service is null on deltaHelper object .</p>
</blockquote>
<blockquote>
<p>MyRepo.class is mocked as it has some more @autowired bean reference</p>
</blockquote>
<p>Attaching other classes here</p>
<pre><code>@Component
public class DeltaHelper {

    @Autowired
    MyRestService restService;

    @Autowired
    MyStorageService myStorageService;

    @NotNull
    @Retryable(
            value = Exception.class,
            maxAttemptsExpression = &quot;${delta.process.retries}&quot;
    )
    public String process(String api, HttpEntity&lt;?&gt; entity) {
            return restService.call(api, entity);
    }
    @Recover
    public String recover(Exception e, String api, HttpEntity&lt;?&gt; entity) {

            myStorageService.save(api);
            return &quot;recover&quot;;
    }
}


@Service
public class MyStorageService {

    @Autowired
    MyRepo myRepo;

    @Async
    public MyEntity save(String api) {
        return myRepo.save(new MyEntity(api, System.currentTimeMillis()));
    }
}



public class MyRestService extends org.springframework.web.client.RestTemplate {
}
</code></pre>
<p>Thank you</p>
<blockquote>
<p>Tried MockitoJUnitRunner, But found that @Retryable works only when running with Spring</p>
</blockquote>
",https://stackoverflow.com/questions/74796996/beans-are-null-when-unit-testing-spring-retry-with-springrunner,"['java', 'junit', 'mockito', 'spring-retry', 'springrunner']",114,True,0,1
React unit testing nightmare with react-autosuggest and firing events,"<p>I have a component that uses up to 3 react-autosuggest components, there is a submit button.</p>
<pre><code>&lt;Autosuggest inputProps={{placeholder: 'Currency'}}/&gt;

&lt;Autosuggest inputProps={{placeholder: 'Account'}}/&gt;

&lt;Autosuggest inputProps={{placeholder: 'Account'}}/&gt;

&lt;button onClick={submit}&gt;SUBMIT&lt;/button&gt;
</code></pre>
<p>Each of the above autosuggests updates the state accordingly and the relevant data is acquired and sent over to the api. When the submit button is clicked, some validation takes place. This validation ensures the Currency and both Accounts have valid values. If any of those is not valid, an error message is shown.</p>
<p>For example if one of the accounts is not provided, an error message will be shown. The same applies to the other autosuggest inputs.</p>
<p>Practically when the app is run, all works as expected.</p>
<p>What's really annoying and frustrating is when testing this behaviour using the @testing-library/react.</p>
<p>One of the issues is as follows.</p>
<pre><code>const inputCurrency = screen.getByPlaceholderText(&quot;Currency&quot;);

fireEvent.focus(inputCurrency);

const suggestion = screen.getByText('GBP');

fireEvent.click(suggestion);
</code></pre>
<p>In the test find the currency autosuggest input by its placeholder text. Fire a focus event on it. This is to open the autosuggestion list.</p>
<p>From the list find a suggestion with the text GBP and fire a click event on this to simulate the autosuggest onChange event.</p>
<p>It is on this change event the state is updated for the corresponding field (currency).</p>
<p>I am able to see that the setState update is taking place:</p>
<p><a href=""https://i.stack.imgur.com/O3DH9.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/O3DH9.png"" alt=""enter image description here"" /></a></p>
<p>The problem faced at this point is that, on firing that event which selects a suggestion, from then on trying to query anything from the DOM is non-existent.</p>
<p>For example, after firing the suggestion click event.</p>
<p>Doing this:</p>
<pre><code>const tb =  await screen.findByText('SUBMIT');
</code></pre>
<p>Causes the tests to fail with the following message:</p>
<p><strong>Unable to find an element with the text: SUBMIT. 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.</strong></p>
<p>But we know the element will exist after updating the autosuggest. In fact the button will still be visible even after all three autosuggests are populate and further more it will be clicked to do the validation.</p>
<p>When it comes to the tests, this scenario just fails and doesn't get far.</p>
<p>Regardless whether I use act or waitFor when firing events or getting elements the thing still fails. With the above message.</p>
<pre><code>const inputCurrency = screen.getByPlaceholderText(&quot;Currency&quot;);

await act(() =&gt; {
  fireEvent.focus(inputCurrency);
});

const suggestion = screen.getByText('GBP');

await act(() =&gt; {
  fireEvent.click(suggestion);
});

await waitFor(() =&gt; {
  const tb =  screen.getByText('SUBMIT');
});
</code></pre>
<p><a href=""https://i.stack.imgur.com/ej2C0.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ej2C0.png"" alt=""enter image description here"" /></a></p>
<p>The weird part about this as well, is once I comment out the fireEvent.click(suggestion), it doesn't fail and is able to find the SUBMIT button:</p>
<p><a href=""https://i.stack.imgur.com/YA7yk.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/YA7yk.png"" alt=""enter image description here"" /></a></p>
<p><a href=""https://i.stack.imgur.com/2Agal.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2Agal.png"" alt=""enter image description here"" /></a></p>
<p>I'd like to get passed this hurdle but nothing has proved effective, not even from the react testing library docs. Whether synchronous or asynchronous.</p>
<p>React v18.0.0</p>
<p>Testing Library v13.0.0</p>
<p>react-autosuggest v10.1.0</p>
",https://stackoverflow.com/questions/72834933/react-unit-testing-nightmare-with-react-autosuggest-and-firing-events,"['reactjs', 'react-testing-library']",74,False,0,0
Single global instance for multiple test cases in unit testing,"<p>I want to setup a global instance variable for all the test cases. Currently I could setup the variable for one test case but it is not set for the other. Mentioned below is my setup code.</p>
<pre><code>func setupLightController()
{
    let btLight = HueBTLight(identifier: &quot;093FB4B8-82E6-A124-3888-4F25C19CFDB7&quot;)
    btLight.name = &quot;Hue Bloom&quot;
    lightController = HueBTLightController(light: btLight)
    lightController.delegate += self
    bluetoothManager?.selectLight(lightController.light!)
    bluetoothManager?.delegate += lightController
}
</code></pre>
<p>Here, is the code for my first test case which runs perfectly fine.</p>
<pre><code>func testColorModel()
{
    colorExpectation = self.expectation(description: &quot;Testing setting color&quot;)

    setupLightController()
    wait(for: [colorExpectation], timeout: 20)
  
}
</code></pre>
<p>And here is my second test case</p>
<pre><code>func testSetOn()
{
    lightExpectation = self.expectation(description: &quot;Testing setting on and off&quot;)

    setupLightController()

    wait(for: [lightExpectation], timeout: 20)
}
</code></pre>
<p>How can I setup the lightController only once to be used in both the test cases. Also, I am using only one delegate callback for the expectation fulfill which works for only one expectation.
Here is my delegate method</p>
<pre><code>func didConnectLightController(_ object: CDHueBTLightController, success: Bool)
{
    self.connectionSuccess = success
    colorExpectation.fulfill()
    lightExpectation.fulfill()
}
</code></pre>
",https://stackoverflow.com/questions/72476821/single-global-instance-for-multiple-test-cases-in-unit-testing,"['swift', 'unit-testing', 'expectations']",208,False,-1,1
Unit testing for backend and services methods calls with Jasmine,"<p>I started working with tests, more specifically with Jasmine, and I'm having some difficulty to test if the backend and some services methods are being called.</p>
<p>So basically I'm calling the <strong>forgotPassword</strong> method when the formulary is submitted and I was wondering how can I properly check if the API (<strong>apiSendPasswordResetLink</strong>) and the services methods (<strong>showLoader</strong>, <strong>showAlert</strong> and <strong>navigateTo</strong>) are being called as expected.</p>
<pre><code>async forgotPassword() {
    try {
        console.log(&quot;1&quot;);
        this.loadingService.showLoader();
        console.log(&quot;2&quot;);
        await this.userService
            .apiSendPasswordResetLink(this.form.value['email'])
            .toPromise();

        console.log(&quot;3&quot;);
        this.utilitiesService.showAlert(`We've emailed you a link to reset your password. Please check your mail box and spam.`);

        console.log(&quot;4&quot;);
        delay(1500);
        this.navigationService.navigateTo('/login/auth');
        console.log('5')
    } catch (err) {
        this.utilitiesService.showAlert(err);
    } finally {
        this.loadingService.hideLoader();
    }
}
</code></pre>
<p>The test:</p>
<pre><code>it('should submit email to reset password after submitting formulary', () =&gt; {
    component.form.setValue({
      email: 'test@test.io',
    });

    const loadingService = TestBed.inject(LoaderService);
    const userService = TestBed.inject(UserService);
    const utilitiesService = TestBed.inject(UtilitiesService);
    const navigationService = TestBed.inject(NavigationService);

    fixture.detectChanges();

    const button = fixture.debugElement.nativeElement.querySelector('#button');

    spyOn(component, 'forgotPassword').and.callThrough();
    spyOn(loadingService, 'showLoader');
    spyOn(userService, 'apiUserSendPasswordResetLink');
    spyOn(utilitiesService, 'showAlert');
    spyOn(navigationService, 'navigateTo');

    // Submitting form
    fixture.debugElement
      .query(By.css('form'))
      .triggerEventHandler('ngSubmit', null);

    expect(component.form.valid).toEqual(true);
    expect(button.disabled).toBeFalsy();
    expect(component.forgotPassword).toHaveBeenCalled();
    expect(loadingService.showLoader).toHaveBeenCalled();
    expect(userService.apiUserSendPasswordResetLinkGet).toHaveBeenCalled();
    expect(utilitiesService.showAlert).toHaveBeenCalled();
    expect(navigationService.navigateTo).toHaveBeenCalled();
  });
</code></pre>
<p>Every time I run and / or debug the test, I have the error</p>
<blockquote>
<p>Expected spy navigateTo to have been called.</p>
</blockquote>
<p>But the console never prints &quot;3&quot;, which means <strong>showAlert</strong> is also not being called and I should also have the same error regarding showAlert spy to be called, but I don't.</p>
<p>I don't know if this problem has to do if the await call to the API or something else. I would like to know how can I fix it, so all the test can pass as expected.</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/71462834/unit-testing-for-backend-and-services-methods-calls-with-jasmine,"['javascript', 'angular', 'unit-testing', 'jasmine', 'frontend']",136,False,0,1
FE: Unit testing window.location.href changing on button click (test fails),"<p>I am trying to test when the window.location.href changes after a button is clicked using react-testing-library. I have seen examples online where you manually update window.location.href inside of a test case as so <code>window.location.href = 'www.randomurl.com'</code> and then follow it with <code>expect(window.location.href).toEqual(www.randomurl.com)</code>. While this indeed will pass, I want to avoid this as I'd rather simulate the user actions instead of injecting the new value into the test. If I do that, even if I remove my button click (which is what will actually trigger the function call) the expect will still pass because I have anyway manually updated the window.location.href in my test</p>
<p>What I've opted for is having goToThisPage func (which will redirect the user) to be placed outside of my functional component. I then mock goToThisPage in my test file and in my test case check whether it has been called. I do know that the goToThisPage is being triggered  because I included a console.log and when I run my tests I see it in my terminal. Nonetheless, the test still fails. I have been playing around with both spyOn and jest.doMock/mock with no luck</p>
<p>component.js</p>
<pre><code>import React from 'react'
import { ChildComponent } from './childcomponent';
export const goToThisPage = () =&gt; {
  const url = '/url'
  window.location.href = url;
  console.log('reached');
};

export const Component = () =&gt; {
 return (&lt;ChildComponent goToThisPage={ goToThisPage }/&gt;)
}

export default Component;
</code></pre>
<p>Test file:</p>
<pre><code>  import * as Component from './component'
  import userEvent from '@testing-library/user-event';

  jest.doMock('./component', () =&gt; ({
   goToThisPage: jest.fn(),
  }));

  describe('goToThisPage', () =&gt; {
    test('should call goToThisPage when button is clicked', async () =&gt; {
        const goToThisPageSpy = jest.spyOn(Component, 'goToThisPage');
        const { container, getByTestId } = render(&lt;Component.Component /&gt;);

        userEvent.click(screen.getByTestId('goToThisPage')); // this is successfully triggered (test id exists in child component)
        expect(goToThisPageSpy).toHaveBeenCalled();
        // expect(Component.goToThisPage()).toHaveBeenCalled(); this will fail and say that the value must be a spy or mock so I opted for using spy above
    });
});
</code></pre>
<p>Note: when I try to just do jest.mock I got this error <code>Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.</code>
When testing out with <code>jest.doMock</code> the error disappeared but the actual test fails.</p>
<p>I am open to hear more refined ideas of solving my issue if someone believes this solution could be improved. Thanks in advance</p>
<p>Edit:
This is another approach I have tried out</p>
<pre><code>  import { Component, goToThisPage } from './component'
  import userEvent from '@testing-library/user-event';

  describe('goToThisPage', () =&gt; {
    test('should call goToThisPage when button is clicked', async () =&gt; {
        const goToThisPageSpy = jest.spyOn(Component, 'goToThisPage'); 
// I am not certain what I'd put as the first value in the spy. Because `goToThisPage` is an external func of &lt;Component/&gt; &amp; not part of the component
        const { container, getByTestId } = render(&lt;Component /&gt;);

        userEvent.click(screen.getByTestId('goToThisPage'));
        expect(goToThisPageSpy).toHaveBeenCalled();
    });
});
</code></pre>
",https://stackoverflow.com/questions/71021835/fe-unit-testing-window-location-href-changing-on-button-click-test-fails,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library', 'window.location']",5728,True,0,2
Mock or hide base class when unit testing in xunit,"<p>I am trying to write a test case for a method, that inside calls a method of the base class.</p>
<pre><code> protected override void OnServerStarting(ApplicationConfiguration configuration)
    {
        Log.Logger.Information(&quot;The server is starting.&quot;);

        base.OnServerStarting(configuration);

        // it is up to the application to decide how to validate user identity tokens.
        // this function creates validator for X509 identity tokens.
        CreateUserIdentityValidators(configuration);
    }
</code></pre>
<p>I just want to call CreateUserIdentityValidators (private) method. However, the base class method gets called and tries to do stuff like creating/reading certificates and throws exception.</p>
<p>Is there a way to hide/override/mock the base class method? Using moq and xunit here.</p>
",https://stackoverflow.com/questions/73122446/mock-or-hide-base-class-when-unit-testing-in-xunit,"['c#', 'moq', 'xunit', 'base-class']",179,False,0,0
NestJs unit testing error: TypeError: this.x is not a function,"<p>I have a small issue with a unit test I wrote for a controller method.</p>
<p><strong>Short version:</strong></p>
<pre><code>return this.userPreferencesService.createPreferences(eUserId, userPreferences);
</code></pre>
<p><strong>Long version:</strong></p>
<p>I get this error:</p>
<pre><code>UserPreferencesController › createUserPreferences › should create a new userPreferences
 TypeError: this.userPreferencesService.createPreferences is not a function

      31 |             userPreferences: TestUserPreferencesDto,
      32 |     ): Promise&lt;UserPreferences&gt; {
    &gt; 33 |         return this.userPreferencesService.createPreferences(eUserId, userPreferences);
         |                                            ^
      34 |     }
      35 |
      36 |     /**

      at UserPreferencesController.createPreferences (user-preferences/user-preferences.controller.ts:33:44)
      at Object.&lt;anonymous&gt; (user-preferences/user-preferences.controller.spec.ts:67:45)
</code></pre>
<p>The <code>toBeDefined</code> passes but the <code>createUserPreferences</code> fails for the error above.
The code works great and there only the test fails.
I just can't find the reason this is not a function?</p>
<p>service file content (relevant data only):</p>
<pre><code>@Injectable()
export class UserPreferencesService {

    constructor(@InjectModel('UserPreferences') private userPreferencesModel: Model&lt;UserPreferences&gt;) {
    }

   

    /**
     * ADD a single user preferences by id =&gt; POST api/v1/user-preferences/
     * @param userPreferences
     */
    async createPreferences(eUserId: string, userPreferences: TestUserPreferencesDto): Promise&lt;UserPreferences&gt; {

        Object.assign(userPreferences, {eUserId: eUserId});
        return this.userPreferencesModel.create(userPreferences);
    }
</code></pre>
<p>This is the controller (relevant data only)</p>
<pre><code>@Controller('v1/user-preferences')
export class UserPreferencesController {

    constructor(private userPreferencesService: UserPreferencesService) {}

    /**
     * Add user preferences to the database
     * @param userPreferences
     */
    @Post()
    async createPreferences(
        @Headers('x-e-user-id') eUserId: string,
        @Body()
            userPreferences: TestUserPreferencesDto,
    ): Promise&lt;UserPreferences&gt; {
        return this.userPreferencesService.createPreferences(eUserId, userPreferences);
    }
</code></pre>
<p>This is the entire test file:</p>
<pre><code>import {Test, TestingModule} from '@nestjs/testing';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {UserPreferencesController} from './user-preferences.controller';
import {UserPreferencesService} from './user-preferences.service';
import { exitToOptions } from './schemas/user-preferences.schema';

const ReturnedUserPreferencesMock = {
    _id: '62a161a9654a511b28e6f3db',
    eUserId: '123456',
    uiTheme: 'dark',
    panelWidth: 300,
    editingHandles: true,
    enableLightboxInEditor: true,
    hiddenElements: true,
    defaultDeviceView: 'mobile',
    exitTo: exitToOptions.DASHBOARD,
};

const eUserIdeMock = '123456';

const userPreferencesMock = {
    uiTheme: 'dark',
    panelWidth: 327,
    editingHandles: true,
    enableLightboxInEditor: true,
    hiddenElements: true,
    defaultDeviceView: 'mobile',
    exitTo: exitToOptions.DASHBOARD,
}


const mockUserPreferencesService = {
    create: jest.fn().mockResolvedValueOnce(ReturnedUserPreferencesMock),
}


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

    let controller: UserPreferencesController;
    let service: UserPreferencesService;

    beforeEach(async () =&gt; {
        const module: TestingModule = await Test.createTestingModule({
            controllers: [UserPreferencesController],
            providers: [{
                provide: UserPreferencesService,
                useValue: mockUserPreferencesService
            }]
        }).compile();

        controller = module.get&lt;UserPreferencesController&gt;(UserPreferencesController);
        service = module.get&lt;UserPreferencesService&gt;(UserPreferencesService);
    });

    it('Controler should be defined', () =&gt; {
        expect(controller).toBeDefined();
    });

    describe('createUserPreferences', () =&gt; {
        it('should create a new userPreferences', async () =&gt; {
            const result = await controller.createPreferences(eUserIdeMock, userPreferencesMock);
            expect(service.createPreferences).toHaveBeenCalledWith(eUserIdeMock, userPreferencesMock);
            expect(result).toEqual(ReturnedUserPreferencesMock);
        });
    });
});
</code></pre>
",https://stackoverflow.com/questions/72598971/nestjs-unit-testing-error-typeerror-this-x-is-not-a-function,"['unit-testing', 'jestjs', 'nestjs']",1432,False,0,1
Aurelia Jest with aurelia-ui-virtualization plugin unit testing errors,"<p>We implemented a feature in a component using aurelia-ui-virtualization and all works well. The problem is that it broke almost all our of unit tests. It throws an error now.</p>
<blockquote>
<p>TypeError: Cannot read property 'attrToRemove' of undefined</p>
</blockquote>
<p>I believe this is because of the <code>virtual-repeat.for</code> attribute.</p>
<p>I've created a simple test for this example:</p>
<pre><code>import {StageComponent} from 'aurelia-testing';
import {bootstrap} from 'aurelia-bootstrapper';

describe('c-form-select component', () =&gt; {
    let component;

    describe('Integration', () =&gt; {
        // Test if search is enabled
        it('testing search', async done =&gt; {
            component = StageComponent.withResources()
                .inView('&lt;c-form-select search.bind=&quot;customsearch&quot;&gt;&lt;/c-form-select&gt;')
                .boundTo({
                    customSearch: 1,
                });

            try {
                component.bootstrap(au =&gt; au.use.standardConfiguration().feature('src'));
                await component.create(bootstrap);
                expect(component.viewModel.search).toBe(false);
                component.dispose();
                done();
            } catch (e) {
                done.fail(e);
            }
        });
    });
});
</code></pre>
<p>So I assume aurelia needs to load the <code>aurelia-ui-virtualization</code> plugin. So I change this code:</p>
<pre><code>                component.bootstrap(au =&gt;
                    au.use
                        .standardConfiguration()
                        .plugin('aurelia-ui-virtualization')
                        .feature('src'),
                );
</code></pre>
<p>And I get this error:</p>
<blockquote>
<p>Cannot find module '/Users/dustin/dev/bindable/aurelia-ui-virtualization' from 'aurelia-loader-nodejs.js'</p>
</blockquote>
<p>I'm not sure why it is not looking in my <code>node_modules</code> directory. I assume it might be because of this part of my jest-pretest.ts file:</p>
<pre><code>import {Options} from 'aurelia-loader-nodejs';

Options.relativeToDir = path.join(__dirname, '../');
</code></pre>
<p>But I do have a jest.config.js file that has my node_modules directory included:</p>
<pre><code>    modulePaths: [
        '&lt;rootDir&gt;/src',
        '&lt;rootDir&gt;/node_modules'
    ],
</code></pre>
<p>If I change the plugin path to <code>node_modules/aurelia-ui-virtualization</code> then I get this error:</p>
<pre><code>    TypeError: Cannot read property 'bind' of undefined

      at Object.&lt;anonymous&gt; (node_modules/aurelia-ui-virtualization/dist/commonjs/aurelia-ui-virtualization.js:70:34)
      at advancedRequire (node_modules/aurelia-loader-nodejs/dist/commonjs/aurelia-loader-nodejs.js:78:28)
      at NodeJsLoader.&lt;anonymous&gt; (node_modules/aurelia-loader-nodejs/dist/commonjs/aurelia-loader-nodejs.js:196:46)
      at step (node_modules/aurelia-loader-nodejs/dist/commonjs/aurelia-loader-nodejs.js:42:23)
      at Object.next (node_modules/aurelia-loader-nodejs/dist/commonjs/aurelia-loader-nodejs.js:23:53)
      at node_modules/aurelia-loader-nodejs/dist/commonjs/aurelia-loader-nodejs.js:17:71
</code></pre>
<p>I've been spinning my wheels on this for a couple of days. If anyone can point me in the right direction to fix my unit tests I'd really be grateful!</p>
",https://stackoverflow.com/questions/72016996/aurelia-jest-with-aurelia-ui-virtualization-plugin-unit-testing-errors,"['node.js', 'typescript', 'jestjs', 'aurelia']",82,False,0,1
"Python unit testing: temporary directories, multiple tests, and context managers","<p>I've written a small module for work and I'm adding some unittesting. The module writes files that need to be read back in for testing purposes and I'm using <code>tempfile.TemporaryDirectory()</code>. I create the temporary directory in the <code>setUp()</code> method of my test class and tear it down in the <code>tearDown()</code> method because clearly, I don't want to trash up the file structure when tests are run in prod. My understanding is that the <code>setUp</code> and <code>tearDown</code> methods are run before and after each test and while this adds some overhead to the testing process (i.e., each test takes about 0.5 seconds to run), I'm not all that worried about the time.</p>
<p>My test class</p>
<pre><code>class MyUtilsTest(unittest.TestCase):
    
    def setUp(self) -&gt; None:
        self.dir_name = tempfile.TemporaryDirectory()
        file_name = &quot;file_used_for_testing.pptx&quot;
        self.presentation_path = self.dir_name.name + &quot;/&quot; + file_name

        # Do some things, including writing some stuff to the temporary directory

    def tearDown(self) -&gt; None:
        self.dir_name.cleanup()

    def test1(self) -&gt; None:
        self.assertTrue(
            os.path.isfile(self.presentation_path), f&quot;{self.presentation_path} exists.&quot;
        )

    def test2(self) -&gt; None:
        prs = Presentation(self.presentation_path)
        self.assertEqual(len(prs.slides), 4)

    def test3(self) -&gt; None:
        prs = Presentation(pptx=self.presentation_path)
        titles = [prs.slides[s].placeholders[0].text for s in np.arange(0, 4)]
        self.assertEqual(
            titles, [&quot;Test title&quot;, &quot;Image title&quot;, &quot;Table title&quot;, &quot;Bullet title&quot;]
        )

    # More tests that rely in files in self.dir_name here
</code></pre>
<p>When I have my test class set up like this, all of my tests run and pass without issue, but I get a linter warning:</p>
<p><a href=""https://i.stack.imgur.com/5xjh5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/5xjh5.png"" alt=""Pop-up linter warning"" /></a></p>
<p>I'm new-ish to writing software-like code in Python and in doing research on this linter warning, I ran into several questions on SO (e.g., <a href=""https://stackoverflow.com/questions/4199700/python-how-do-i-make-temporary-files-in-my-test-suite"">Python: How do I make temporary files in my test suite?</a>). I've tried editing my test class to incorporate using <code>with tempfile.TemporaryDirectory() as dir_name:</code> but when I do this, my tests fail. For example, when I edit the <code>setup()</code> method (and remove the <code>tearDown()</code>) to</p>
<pre><code>def setUp(self) -&gt; None:
    with tempfile.TemporaryDirectory() as dir_name:
        file_name = &quot;file_used_for_testing.pptx&quot;
        self.presentation_path = dir_name + &quot;/&quot; + file_name

        # Do some things, including writing some stuff to the temporary directory
</code></pre>
<p>the later tests can't find the temp directories, I suspect because the temp dir was destroyed after leaving the context/function and prior to the test running.</p>
<p>How can I keep the context manager open for subsequent tests that rely on the files that are produced in the <code>setUp()</code> method?</p>
",https://stackoverflow.com/questions/74264367/python-unit-testing-temporary-directories-multiple-tests-and-context-managers,"['python', 'unit-testing']",46,False,0,1
Vue/Jest unit testing Cannot read property &#39;shallowMount&#39; of undefined,"<p>I have been following the Vue school guides on implementing Jest with Vue in order to start writing some unit tests.</p>
<p>So far I've installed jest, jest-serializer-vue, vue-template-compiler.</p>
<pre><code>module.exports = {
    verbose: true,
    roots: [
        &quot;&lt;rootDir&gt;/src/&quot;,
        &quot;&lt;rootDir&gt;/src/specs/&quot;
    ],
    moduleFileExtensions: ['js', 'vue'],
    moduleNameMapper: {
        '^@/(.*)$': '&lt;rootDir&gt;/src/$1',
    },
    transform: {
        &quot;^.+\\.js$&quot;: &quot;babel-jest&quot;,
        &quot;^.+\\.vue$&quot;: &quot;vue-jest&quot;,
    },
    snapshotSerializers: [
        &quot;&lt;rootDir&gt;/node_modules/jest-serializer-vue&quot;
    ]
}
</code></pre>
<p>When writing my first test it is building successfully.</p>
<pre><code>import TestComponent from '../src/components/test';

test('mount a vue component', () =&gt; {
    console.log(TestComponent);
});
</code></pre>
<p>But when I try mounting Vue component it starts failing with the following error:</p>
<pre><code> FAIL  src/specs/test.spec.js
  ● Test suite failed to run

    TypeError: Cannot read property 'shallowMount' of undefined
</code></pre>
<p>The actual test file looks like this:</p>
<pre><code>import TestComponent from '../src/components/test';

import { shallowMount } from '@vue/test-utils';

test('mount a vue component', () =&gt; {
    const wrapper = shallowMount(TestComponent);

    console.log(wrapper);
});
</code></pre>
<p>I don't understand why this is happening, and there is no info (at least I could not find some) as why this is failing. Can someone help me?</p>
<p>PS: My project is NOT using vue-cli.</p>
",https://stackoverflow.com/questions/71159609/vue-jest-unit-testing-cannot-read-property-shallowmount-of-undefined,"['javascript', 'unit-testing', 'vuejs2', 'jestjs', 'vue-test-utils']",988,False,0,0
"Unit testing with Moq, how to update a single property","<p>I'm writing some unit test using nUnit and Moq that requires a lot of mocking of data. I have created a helper method to avoid having to mock the data inside each individual test. Here is a simplified version:</p>
<pre><code>protected void MockLotsOfData()
{
    var orders = new List&lt;Order&gt;()
    {
        new Order()
        {
            Id = 1234,
            Total = 67.95
            ExpressShip = false
        },
        new Order() 
        {
            Id = 5678,
            Total = 178.34
            ExpressShip = false
        }
    }
    
    var mockDbSetOrders = orders.AsMockDbSet();
    this._mockDbContext.Setup(x =&gt; x.ORDERS).Returns(mockDbSetOrders.Object);
}
</code></pre>
<p>I would then like to change a single property from a collection to be able to test. Here is more simplified code:</p>
<pre><code>[Test, Category(&quot;Unit&quot;)]
public void OrderService_ProcessOrderWithExpressShipping_ReturnsSuccess()
{
    //Arrange
    var service = this.CreateService();
    var request = new OrderRequest() { OrderNumber = 1234 };
    this.MockLotsOfData();

    // Need help here, how to change value of'ExpressShip' property for order Id = 1234?
    this._mockDbContext.SetupProperty(x =&gt; x.ORDERS.Where(y =&gt; y.Id = 1234)).Select(z =&gt; z.ExpressShip).Returns(true);

    //Act
    var response = service.ProcessOrder(request);

    //Assert
    Assert.IsTrue(response.Successful);
}
</code></pre>
<p>What I'm trying to do is update a single value from the mock data so I can test a different scenario. Is this possible?</p>
",https://stackoverflow.com/questions/74235195/unit-testing-with-moq-how-to-update-a-single-property,"['c#', 'unit-testing', 'nunit', 'moq']",192,True,0,1
How to check two if condition in angular unit testing,"<p>I have a method showStatus() in my ts file and in if loop two conditions must satisfy, but I'm not able to figure out how to write this condition in test cases.</p>
<p><strong>.ts</strong></p>
<pre><code>public showStatus(str:Event)
{
 if(this.currUser != null &amp;&amp; this.statusValid.valid) 
 {
 const status = new Status();
 status.statustext = this.statusValid.value;
 status.name = this.currUser.username;
 
 if(str.statuses == null){
 event.statuses = new Statuses();
 }

 str.statuses.allstatus.push(status);
 }
</code></pre>
<p><strong>test cases</strong></p>
<pre><code>it('should validate', () =&gt; {
spyOn(obj, 'showStatus').and.returnValue(true);
component.showStatus(mockdata)
});
</code></pre>
",https://stackoverflow.com/questions/74927626/how-to-check-two-if-condition-in-angular-unit-testing,"['angular', 'unit-testing']",60,False,0,1
How to mock Local Variables for unit testing in Jest?,"<p>I have two files, <code>file.component.ts</code> containing:</p>
<pre><code>  setTwoNumberDecimal(e) {
    const USER_VAL = parseFloat(e.target.value.replace(/,/g, ''));
    e.target.value = this.getTruncatedValue(USER_VAL, 1);
  }
</code></pre>
<p>and my test file <code>file.component.specs.ts</code> containing:</p>
<pre><code>describe('setTwoNumberDecimal()', () =&gt; {
  it('tests commas are removed and user value is set', () =&gt; {
    const mockEvent = {target: {value: '5.777,'}};
    component.setTwoNumberDecimal(mockEvent);
    expect(component.setTwoNumberDecimal).toHaveBeenCalled();
  });
});
</code></pre>
<p>I want to be able to check that, after <code>setTwoNumberDecimal(e)</code> is run:</p>
<ol>
<li><p><code>USER_VAL</code> is equal to <code>'5.777'</code> (that is, the comma has been removed); and</p>
</li>
<li><p><code>e.target.value is equal</code> to <code>'5.77'</code> (that is, the last value has been truncated)</p>
</li>
</ol>
<p>The functionality already works for the comma replace and the truncate.</p>
",https://stackoverflow.com/questions/74483597/how-to-mock-local-variables-for-unit-testing-in-jest,"['javascript', 'jestjs']",45,False,-1,1
Unit Testing Works in VSCode on Windows but not Linux,"<p>I'm having trouble debugging Xunit unittests in .NET6 running on Ubuntu 20.04 in VSCode (1.66.2). These run in VisualStudio and VSCode in Windows. I can run (not debug) the tests in Linux from the CLI or the <a href=""https://github.com/formulahendry/vscode-dotnet-test-explorer"" rel=""nofollow noreferrer"">.NET Core Test Explorer</a> extension.</p>
<p>If I try to debug the unittest with the context menu or the little magic command attribute that is placed above the unittest method declaration, I get an error:</p>
<pre><code>Failed to start debugger: 
&quot;System.InvalidOperationException: The debugger could not be started
at OmniSharp.DotNetTest.Services.DebugTestService.Handle 
(OmniSharp.DotNetTest.Models.DebugTestGetStartInfoRequest request) [0x00050] in &lt;9d87b466e5a04dffb95becc0b4dfd560&gt;:0
at OmniSharp.Endpoint.Exports.RequestHandlerExportHandler`2[TRequest,TResponse].Handle (TRequest request) [0x00000] in &lt;3d93fabea6954f4ba147450b0cf4332a&gt;:0
at OmniSharp.Endpoint.EndpointHandler`2[TRequest,TResponse].GetFirstNotEmptyResponseFromHandlers (OmniSharp.Endpoint.Exports.ExportHandler`2[TRequest,TResponse][] handlers, TRequest request) [0x00022] in &lt;3d93fabea6954f4ba147450b0cf4332a&gt;:0
at OmniSharp.Endpoint.EndpointHandler`2[TRequest,TResponse].HandleRequestForLanguage (System.String language, TRequest request, OmniSharp.Protocol.RequestPacket packet) [0x00163] in &lt;3d93fabea6954f4ba147450b0cf4332a&gt;:0
at OmniSharp.Endpoint.EndpointHandler`2[TRequest,TResponse].Process (OmniSharp.Protocol.RequestPacket packet, OmniSharp.Endpoint.LanguageModel model, Newtonsoft.Json.Linq.JToken requestObject) [0x0024b] in &lt;3d93fabea6954f4ba147450b0cf4332a&gt;:0
at OmniSharp.Stdio.Host.HandleRequest (System.String json, Microsoft.Extensions.Logging.ILogger logger) [0x000f3] in &lt;2584067dfcea42a69c19a025cfbc4799&gt;:0 &quot;
</code></pre>
<p>I also see this in the OUTPUT pane:</p>
<pre><code>/usr/share/dotnet/sdk/6.0.202/Microsoft.Common.CurrentVersion.targets(4650,5): error MSB3883: Unexpected exception:  [/home/danielp/Source/Experiments/LibAndTest/Library/Library.csproj]
/usr/share/dotnet/sdk/6.0.202/Microsoft.Common.CurrentVersion.targets(4650,5): error : DirectoryNotFoundException: Could not find a part of the path '/home/danielp/Source/Experiments/LibAndTest/Library/bin/Debug/net6.0/ref/Library.dll'. [/home/danielp/Source/Experiments/LibAndTest/Library/Library.csproj]
/usr/share/dotnet/sdk/6.0.202/Microsoft.Common.CurrentVersion.targets(4650,5): error :    at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter) [/home/danielp/Source/Experiments/LibAndTest/Library/Library.csproj]
/usr/share/dotnet/sdk/6.0.202/Microsoft.Common.CurrentVersion.targets(4650,5): error :    at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode) [/home/danielp/Source/Experiments/LibAndTest/Library/Library.csproj]
/usr/share/dotnet/sdk/6.0.202/Microsoft.Common.CurrentVersion.targets(4650,5): error :    at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize) [/home/danielp/Source/Experiments/LibAndTest/Library/Library.csproj]
/usr/share/dotnet/sdk/6.0.202/Microsoft.Common.CurrentVersion.targets(4650,5): error :    at System.IO.FileSystem.CopyFile(String sourceFullPath, String destFullPath, Boolean overwrite) [/home/danielp/Source/Experiments/LibAndTest/Library/Library.csproj]
/usr/share/dotnet/sdk/6.0.202/Microsoft.Common.CurrentVersion.targets(4650,5): error :    at System.IO.File.Copy(String sourceFileName, String destFileName, Boolean overwrite) [/home/danielp/Source/Experiments/LibAndTest/Library/Library.csproj]
/usr/share/dotnet/sdk/6.0.202/Microsoft.Common.CurrentVersion.targets(4650,5): error :    at Microsoft.CodeAnalysis.BuildTasks.CopyRefAssembly.Copy() [/home/danielp/Source/Experiments/LibAndTest/Library/Library.csproj]
/usr/share/dotnet/sdk/6.0.202/Microsoft.Common.CurrentVersion.targets(4650,5): error :  [/home/danielp/Source/Experiments/LibAndTest/Library/Library.csproj]
</code></pre>
<p>What I find interesting here is that it keeps looking for referenced dlls in <code>...Debug/net6.0/ref/Library.dll'</code> and there is no build output binary placed there much less a folder called <code>ref</code>.</p>
<p>For now, I can debug w/ a console app, but it sure seems strange that this works so well in Windows but not Linux. However, now that I say that out loud: it seems like it shouldn't be that surprising.</p>
<p>Lastly, I did try debugging mstest unittests w/ the same results.</p>
",https://stackoverflow.com/questions/71865322/unit-testing-works-in-vscode-on-windows-but-not-linux,"['linux', 'debugging', 'visual-studio-code', '.net-core', 'xunit']",782,True,0,1
Unit testing a DAO class extending a generic DAO class,"<p>My generic DAO class looks like:</p>
<pre><code>public abstract class DAO&lt;A,B&gt; {
     public Class&lt;B&gt; entity;

     protected final Provider&lt;EntityManager&gt; entityManagerFactory;
     
     @Inject
     public DAO(Provider&lt;EntityManager&gt; entityManagerFactory){
         this.entityManagerFactory = entityManagerFactory;
     }

     public A findById(B id){
        return entityManagerFactory.get().find(entity, id);
     }
}
</code></pre>
<p>The class I want to write unit tests for looks like:</p>
<pre><code>public class TestDAO extends DAO&lt;Test, Long&gt; {
     @Inject
     public TestDAO(Provider&lt;EntityManager&gt; entityManagerFactory){
         super(entityManagerFactory);
         entity = Test.class;
     }
}

</code></pre>
<p>I am unable to figure out how to initialize stuff for writing unit tests for this class? Any help would be appreciated. The generic DAO would later on also contain functions for updating, deleting, creating etc. I want to use junit4 for my testing purposes</p>
",https://stackoverflow.com/questions/71550505/unit-testing-a-dao-class-extending-a-generic-dao-class,"['java', 'hibernate', 'unit-testing', 'junit4']",65,False,0,0
How to do unit testing when api call in flutter,"<pre class=""lang-js prettyprint-override""><code>class CategoryMapping extends ChangeNotifier {
   final GetCategoryMapping _mapping = GetCategoryMapping();
   List categorizationData = [];
   List get categoryList =&gt; categorizationData;

Future getDatas() async {
try {
  final response = await _mapping.mapingDatas();
  Iterable data = response[&quot;helpDetails&quot;][&quot;mappingRows&quot;];
  final list = data;
  log(data.runtimeType.toString());
  categorizationData = list.map((e) =&gt; e).toList();
  log(&quot;data ${categorizationData[0][&quot;givenCategory&quot;]} &quot;);
} catch (e) {
  log(e.toString());
}
return categorizationData; //returining a dynamic list
} }
</code></pre>
<p>How to do unit testing in this api calls.In this methods i didin't used to models. I tried some time , but it failed. I am just started to learning unit testing. So kindly request to how to test this code in properly,</p>
",https://stackoverflow.com/questions/74096550/how-to-do-unit-testing-when-api-call-in-flutter,"['flutter', 'unit-testing', 'dart', 'flutter-test', 'provider']",64,False,0,0
unit testing with jest keep on running in looper CI,"<p>Running the unit test with jest in looper for a react project. The unit test job is triggered in the looper, all the unit tests were run and getting the coverage info in the logs. Got the message - &quot;Ran all test suites&quot; but still looper is not exiting from the unit test job. it keeps on running. How to exit from the job and kickstart the next job say sonar coverage.</p>
<p>Please find the logs from CI (looper)</p>
<p>14:59:03 Test Suites: 10 failed, 23 passed, 33 total
14:59:03 Tests:       29 failed, 90 passed, 119 total
14:59:03 Snapshots:   2 failed, 2 total
14:59:03 Time:        39.887s
14:59:03 Ran all test suites.</p>
<p>and getting stuck here and getting timed out.</p>
<p>Tried --forceExit, --openHandler etc nothing is worked out.</p>
",https://stackoverflow.com/questions/74452812/unit-testing-with-jest-keep-on-running-in-looper-ci,"['reactjs', 'unit-testing', 'jestjs', 'looper']",16,False,0,0
How to cover try/catch block in angular unit testing,"<pre><code>checkDefault(event) {
    try {
      this.defaultCard = event.checked;
      this.cardInfo.forEach((s) =&gt; {
        if (s.isDefault &amp;&amp; event.checked) {
          const dialog = this.dialogService.dialogMethod(this.message.isDefaultAlertCard, this.dialogType.confirmation, true);
          dialog.afterClosed().subscribe((res) =&gt; {
            Eif (!res) {
              this.defaultCard = false;
            }
          });
        }
      });
    } catch (err) {
      this.errorObject.message = 'Error in checkDefault: ' + err &amp;&amp; err.message ? err.message : null;
      this.sharedService.errorEmailNotification(this.storeId, this.errorObject);
      this.dialogService.dialogMethod(this.message.failedSave, this.dialogType.failure,
        true
      );
    }
  }
</code></pre>
<p>In this function, I covered try block but catch block was not covered. How to cover that.</p>
<p>My testcase for try block is</p>
<pre><code>test('should create checkDefault', () =&gt; { 
    component.cardInfo = [{ isDefault: true, customer: &quot;CustomerId&quot;, cardId: &quot;cardId&quot; }, { isDefault: false, customer: &quot;CustomerId&quot;, cardId: &quot;cardId&quot; }];
    component.checkDefault({ checked: true });
    expect(component.checkDefault).toBeTruthy();

  });
</code></pre>
",https://stackoverflow.com/questions/74301370/how-to-cover-try-catch-block-in-angular-unit-testing,"['angular', 'unit-testing', 'code-coverage', 'catch-block']",173,False,0,1
Cannot read properties of undefined (reading &#39;save&#39;) + TypeORM + Unit Testing,"<p>I'm still new to Unit Testing, TypeOrm, and NestJs. I currently have a user registration repository I'm trying to unit test. The feature works perfectly fine and I can register a user. But when I'm unit testing the repository I get the error <strong>Cannot read properties of undefined (reading 'save')</strong>.</p>
<p>This is my <strong>user.repository.ts</strong> file</p>
<pre><code>import {
  ConflictException,
  InternalServerErrorException,
} from '@nestjs/common';
import { EntityRepository, Repository } from 'typeorm';
import { genSalt, hash } from 'bcryptjs';
import { omit } from 'lodash';
import { generate } from 'randomstring';
import { CreateUserDto } from 'src/dtos/user/create-user-dto';
import { User } from './user.entity';

@EntityRepository(User)
export class UserRepository extends Repository&lt;User&gt; {
  async register(createUserDto: CreateUserDto): Promise&lt;object&gt; {
    const {
      firstName,
      ... //other destructured fields here
    } = createUserDto;
    const salt = await genSalt();
    const user = this.create();
    user.firstName = firstName;
    ... // created user here
    try {
      await this.save(user);
    } catch (error) {
      if (error.code === '23505') { //duplicate error
        console.log(error.message);
        // throw new ConflictException('Username or Password is Taken');
      } else {
        throw new InternalServerErrorException('THIS IS A 500 ERROR');
      }
    }
    let omitPasswordFromReturn = omit(user, ['password']);
    return omitPasswordFromReturn;
  }

  private async hashPassword(password: string, salt: string): Promise&lt;string&gt; {
    return hash(password, salt);
  }
}
</code></pre>
<p>And this is the <strong>user.repository.spec.ts</strong> file</p>
<pre><code>import { ConflictException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { CreateUserDto } from 'src/dtos/user/create-user-dto';
import { UserRepository } from './user.repository';

const mockCreateUserDto: CreateUserDto = {
  firstName: 'Muhammad',
  ...
};

describe('UserRepository', () =&gt; {
  let userRepository;

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      providers: [UserRepository],
    }).compile();

    userRepository = await module.get&lt;UserRepository&gt;(UserRepository);
  });

  describe('user registration', () =&gt; {
    let save;

    beforeEach(() =&gt; {
      save = jest.fn();
      userRepository.create = jest.fn().mockReturnValue({ save });
    });  

    it('should be defined', () =&gt; {
      expect(userRepository.register).toBeDefined();
    })

    it('should sucessfully register user', async () =&gt; {
      save.mockResolvedValue(undefined);
      await expect(
        userRepository.register(mockCreateUserDto),
      ).resolves.not.toThrow();
    });

  });
});
</code></pre>
<p>I have searched typeOrm docs and on here at StackOverflow but nothing is helping.
I've really run out of ideas to try. any form of help is welcome</p>
",https://stackoverflow.com/questions/72977323/cannot-read-properties-of-undefined-reading-save-typeorm-unit-testing,"['unit-testing', 'jestjs', 'repository', 'nestjs', 'typeorm']",442,False,0,0
Reference error when unit testing VUE3 component with jest typescript,"<p>I am new to vue and writing unit tests.
I am stuck on reference error even though my tests are passed.
My current test file:</p>
<pre class=""lang-js prettyprint-override""><code>    require('isomorphic-fetch');
    import { shallowMount } from '@vue/test-utils';
    import WeatherWidget from '@/components/WeatherWidget.vue';

    describe('WeatherWidget.vue', () =&gt; {
       it('renders', () =&gt; {
        const wrapper = shallowMount(WeatherWidget, {
            props: {
                lat: 41.3888,
                lon: 2.1667,
            },
        });
     });
</code></pre>
<p>and having error like:
<a href=""https://i.stack.imgur.com/RlDMQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/RlDMQ.png"" alt=""enter image description here"" /></a></p>
<p>The error reference it is showing is a separate file in which i m exporting a function which returns path to image (dynamic image name).</p>
<p>My script Component.vue:</p>
<pre class=""lang-js prettyprint-override""><code>&lt;script lang=&quot;ts&quot;&gt;
// Built-in Imports
import { computed, defineComponent, onBeforeMount, ref } from &quot;vue&quot;;

// 3rd Party Import
import { useLoading } from 'vue-loading-overlay'

// Custom Utils and Models Imports
import { Weather, WeatherSummary } from &quot;@/models/Weather&quot;;
import { windDirection } from &quot;@/utils/wind-direction&quot;;
import { getCountryByCode } from &quot;@/utils/countries-list&quot;;
import { getIconPath } from &quot;@/utils/fetch-weather-icon&quot;

// Component Import
import MiniForecastWidget from &quot;./MiniForecastWidget.vue&quot;;

export default defineComponent({
  setup(props) {

    // --------------------------------------------------------------------------
    // ------------------------- Initializing variables -------------------------
    // --------------------------------------------------------------------------

    const $loading = useLoading();

    const weatherAPI = `https://api.openweathermap.org/data/2.5/onecall?lon=${props.lon}&amp;lat=${props.lat}&amp;units=metric&amp;exclude=minutely,hourly&amp;appid=${process.env.OPEN_WEATHER_API_KEY}`;
    const geoCodeAPI = `http://api.openweathermap.org/geo/1.0/reverse?lon=${props.lon}&amp;lat=${props.lat}&amp;limit=1&amp;appid=${process.env.OPEN_WEATHER_API_KEY}`;

    // TODO: Dummy data | to be removed later
    let dummyData: Weather = {
      city: &quot;---&quot;,
      country: &quot;---&quot;,
      weatherId: 800,
      weatherMain: &quot;Clear&quot;,
      weatherIcon: &quot;01d&quot;,
      weatherDescription: &quot;clear&quot;,
      temperature: 0,
      date: 0,
      humidity: 0,
      uvi: 0,
      windSpeed: 0,
      windDeg: 0,
    };

    const currentWeather = ref&lt;Weather&gt;(dummyData);
    const weatherData = ref&lt;WeatherSummary[]&gt;([]);
    const location = ref&lt;{ city: string, country: string }&gt;({
      city: &quot;&quot;,
      country: &quot;-&quot;,
    });

    const rain = ref(false)

    // --------------------------------------------------------------------------
    // ---------------------------- Custom Functions ----------------------------
    // --------------------------------------------------------------------------

    // Fetching location with latitude and longitude
    const reverseGeocode = async () =&gt; {
      await fetch(geoCodeAPI)
        .then(res =&gt; res.json())
        .then(res =&gt; {
          const country = getCountryByCode(res[0]?.country);
          currentWeather.value.country = country;
          location.value = {
            city: res[0]?.name,
            country: country,
          };
        });
    };

    // Fetches weather data from the Open Weather API
    const fetchWeatherForecast = async () =&gt; {
      const loader = $loading.show({
        color: '#0668C2',
      });
      const response = await fetch(weatherAPI);
      const resp = await response.json();

      // Manually mapping response to our model
      if (resp.current) {
        const mappedData: Weather = {
          weatherId: resp.current.weather[0].id,
          weatherMain: resp.current.weather[0].main,
          weatherIcon: resp.current.weather[0].icon,
          weatherDescription: resp.current.weather[0].description,
          temperature: resp.current.temp,
          date: resp.current.dt,
          humidity: resp.current.humidity,
          uvi: resp.current.uvi,
          windSpeed: resp.current.wind_speed,
          windDeg: resp.current.wind_deg,
        }

        // Update current weather data
        currentWeather.value = mappedData;
      }


      if (resp.daily) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const dailyForecastData: any[] = resp.daily;
        const mappedDailyForecast: WeatherSummary[] = [];

        // Manually mapping Daily forecast response array to our custom model array
        dailyForecastData.map((obj) =&gt; {
          const mappedDailyForecastData: WeatherSummary = {
            weatherMain: obj.weather[0].main,
            weatherId: obj.weather[0].id,
            weatherDescription: obj.weather[0].description,
            weatherIcon: obj.weather[0].icon,
            date: obj.dt,
            maxTemperature: Math.round(obj.temp.max),
            minTemperature: Math.round(obj.temp.min),
          }

          mappedDailyForecast.push(mappedDailyForecastData);
        });

        // Update forecast data with next five days only
        weatherData.value = mappedDailyForecast.slice(0, 6);

        loader.hide();
      }

    }

    const updateWeather = async () =&gt; {
      await fetchWeatherForecast();
    };

    const makeItRain = () =&gt; {
      rain.value = !rain.value;
    }


    // --------------------------------------------------------------------------
    // ---------------------------- Life Cycle Hook -----------------------------
    // --------------------------------------------------------------------------

    onBeforeMount(() =&gt; {
      reverseGeocode();
      fetchWeatherForecast();
    });

    // --------------------------------------------------------------------------
    // -------------------- Computed Functions / Properties ---------------------
    // --------------------------------------------------------------------------


    const weatherIcon = computed(() =&gt; getIconPath(currentWeather.value.weatherId, currentWeather.value.weatherMain, currentWeather.value.weatherIcon)); // Get weather icon by invoking custom 'getWeatherIcon' util function
    const windDir = computed(() =&gt; windDirection(currentWeather.value.windDeg)); // Computing wind direction by invoking custom 'windDirection' util function
    const country = computed(() =&gt; getCountryByCode(currentWeather.value.country)); // Computing country by invoking custom 'getCountryByCode' util function
    const temperature = computed(() =&gt; Math.round(currentWeather.value.temperature)); // Round Temperature to nearest integer
    const windSpeed = computed(() =&gt; Math.round(currentWeather.value.windSpeed)); // Round Wind speed to nearest integer

    // --------------------------------------------------------------------------
    // --------------------------------- Return ---------------------------------
    // --------------------------------------------------------------------------

    return { location, weatherData, windDir, currentWeather, country, temperature, windSpeed, weatherIcon, updateWeather, makeItRain, rain };
  },
  components: {
    MiniForecastWidget
  },
  props: {
    lat: {
      type: Number,
      required: true,
    },
    lon: {
      type: Number,
      required: true,
    },
  }
});
&lt;/script&gt;
</code></pre>
<p>=&gt; <code>const weatherIcon = computed(() =&gt; getIconPath(currentWeather.value.weatherId, currentWeather.value.weatherMain, currentWeather.value.weatherIcon));</code></p>
<p>While the <code>currentWeather</code> is the ref object which updates after component mounting.</p>
<p>Well my getIconPath function invokes two nested function in it:</p>
<pre class=""lang-js prettyprint-override""><code>export function getIconPath(id: number, main: string, icon: string): string {
    let imgSrc = '';
    try {
        imgSrc = require(`@/assets/weather-widget-icons/ww-icon-${slugify(
            getWeatherIconName(id, main, icon)
        )}.svg`);
    } catch (error) {
        console.error(
            `Image '@/assets/weather-widget-icons/ww-icon-${slugify(
                getWeatherIconName(id, main, icon)
            )}.svg' not found!`
        );
    }
    return imgSrc;
}

</code></pre>
<p>Any help would be kind!</p>
",https://stackoverflow.com/questions/72408541/reference-error-when-unit-testing-vue3-component-with-jest-typescript,"['typescript', 'vue.js', 'jestjs', 'vuejs3', 'ts-jest']",410,False,0,0
"mocha unit testing, validate if property is a joi schema","<p>Im trying to write unit tests for my app.
In my app i have component that has a joi schema as property.</p>
<p>To ensure the schema is set, i need a way to check if the property is a joi schema, but i cant get it working.</p>
<pre class=""lang-js prettyprint-override""><code>const assert = require(&quot;assert&quot;);
const joi = require(&quot;joi&quot;);
const { describe, it } = require(&quot;mocha&quot;);


describe(&quot;should validate joi schema&quot;, () =&gt; {
    it(&quot;test for joi instance&quot;, () =&gt; {

        let schema = joi.object({
            name: joi.string()
        });

        assert(schema instanceof joi.object);

    });
});
</code></pre>
<p>What would be the correct way to check if a object is a joi schema/instance?</p>
<p>Error message:</p>
<pre><code>&gt; ./node_modules/.bin/mocha ./tests/index.js

  should validate joi schema
    1) test for joi instance


  1 failing

  1) should validate joi schema
       test for joi instance:

      AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:

  assert(schema instanceof joi.object)

      + expected - actual

      -false
      +true
      
      at Context.&lt;anonymous&gt; (tests/joi.js:13:9)
      at processImmediate (node:internal/timers:466:21)

</code></pre>
<p>Have tried various things:</p>
<ul>
<li><code>assert.deepEqual(schema, joi.object());</code></li>
<li><code>assert.deepEqual(schema, joi.object);</code></li>
<li><code>assert(schema === joi.object());</code></li>
<li><code>assert(joi.assert({ name: joi.string() }, schema));</code></li>
<li><code>assert(joi.attempt({ name: joi.string() }, schema));</code></li>
<li><code>assert(schema instanceof joi);</code></li>
</ul>
",https://stackoverflow.com/questions/71458095/mocha-unit-testing-validate-if-property-is-a-joi-schema,"['node.js', 'unit-testing', 'mocha.js', 'joi']",514,True,0,1
How to quickly instantiate a pyspark SparkContext for unit testing?,"<p>In my Python 3.8 unit test code, I need to instantiate a SparkContext to test some functions manipulating a <a href=""https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.RDD.html#pyspark.RDD"" rel=""nofollow noreferrer"">RDD</a>.</p>
<p>The problem is that instantiating a SparkContext takes a few seconds, which is too slow. I'm using this code to instantiate a SparkContext:</p>
<pre><code>from pyspark import SparkContext

return SparkContext.getOrCreate()
</code></pre>
<p>The tests only run <a href=""https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.RDD.filter.html#pyspark.RDD.filter"" rel=""nofollow noreferrer"">filter</a>, <a href=""https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.RDD.map.html#pyspark.RDD.map"" rel=""nofollow noreferrer"">map</a> and <a href=""https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.RDD.distinct.html#pyspark.RDD.distinct"" rel=""nofollow noreferrer"">distinct</a> on an RDD. In my tests, I only want to test an expected output against obtained output on a tiny dataset (lists of length between 5 and 10) and I want them to run almost instantaneously. I don't need all other features offered by PySpark (such as parallelization).</p>
<p>I tried various ways, such as below, but instantiation takes as much time:</p>
<pre><code>from pyspark import SparkContext, SparkConf

conf = SparkConf().setMaster(&quot;local[2]&quot;).setAppName(&quot;pytest-pyspark-local-testing&quot;)
sc = SparkContext(conf=conf)
</code></pre>
",https://stackoverflow.com/questions/74788241/how-to-quickly-instantiate-a-pyspark-sparkcontext-for-unit-testing,"['python', 'pyspark', 'rdd', 'python-unittest']",36,False,0,0
Angular Karma unit testing wait for isEmpty to emit value,"<p>I have following code for handling errors:</p>
<pre><code>              catchError((error) =&gt; {
                return statement ? EMPTY : otherValue;
              }),
</code></pre>
<p>I am trying to write an unit test for this. Here what I have achieved.</p>
<pre><code>  it('test description', fakeAsync(() =&gt; {
    let saved: boolean;
    action = new action({ data: 'some data'});
    action$.next(action);

    effects.save.pipe(isEmpty()).subscribe((data: boolean) =&gt; {
      console.log('data:', data);
      saved = data;
    });
    flush();

    console.log('saved:', saved);
    expect(saved).toBeTrue();
  }));
</code></pre>
<p>My output looks like:</p>
<pre><code>```
'saved:', undefined
'data:', true
Error: Expected undefined to be true.
```
</code></pre>
<p>What can I improve to make this test pass?</p>
",https://stackoverflow.com/questions/72346089/angular-karma-unit-testing-wait-for-isempty-to-emit-value,"['angular', 'rxjs', 'karma-runner']",158,False,0,1
Set State of Functional Component While Unit Testing in Jasmine,"<p>My Component:</p>
<pre class=""lang-js prettyprint-override""><code>import React from 'react';

export const Bar() {
 const [myState, setMyState] = React.useState([]);

 const disableSubmit = React.useMemo(() =&gt; {
  return myState.length === 0
 }, [myState]);

 // logic to get myState data by making API call
 setMyState(getMyStateData());

 const onSubmit = () =&gt; {
  // do some validation and make API call
 };
 
 return (
  &lt;form
   className=&quot;form-wrapper&quot;      
   onSubmit={event =&gt; props.onSubmit(event)}
  &gt;
   // logic to display myState data
   &lt;button className=&quot;btn custom-btn&quot; type=&quot;submit&quot; value=&quot;Submit&quot; disabled={disableSubmit}&gt;
     Submit
   &lt;/button&gt;
  &lt;/form&gt;
 );
}
</code></pre>
<p>I am using Jasmine to do unit testing on my components.</p>
<p>I want to write a unit test to simulate the click event on submit button but I can't do this until the value of <code>myState</code> is not set to some array with <code>length&gt;0</code>.</p>
<p>How can I set the value of <code>myState</code> in my unit test?</p>
<p>I have already tried using <code>instance</code> and then setting the value of <code>myState</code> but it throws an error that <code>component.instance()</code> is <code>undefined</code>.</p>
<p>I also came across <code>setState</code> but I found out that it only works for class components.</p>
<p>So, how can I set the value of <code>myState</code> in my unit test?</p>
",https://stackoverflow.com/questions/74199923/set-state-of-functional-component-while-unit-testing-in-jasmine,"['reactjs', 'unit-testing', 'jasmine', 'karma-jasmine']",102,False,0,0
Firebase Function Test with Sinon cannot mock user (Unit testing),"<p>I'm trying to junit test my firebase cloud functions with express, here is an example of my project structure for example the admin entities:</p>
<p>index.js:</p>
<pre><code> /**
 * Initialize the express app with the api.
 * @return {Express} []
 */
function initApi() {
  const app = express();
  app.use(cors());

  AdminController.prototype.bindEndpoints(app);
  .. all other controllers ...

  app.use((error, request, response, next) =&gt; {
    console.log(error);
    console.log(&quot;error called!&quot;);
    return response.status(500).send({
      code: 500,
      message: {
        it: &quot;Errore interno al server.&quot;,
        en: &quot;Internal server error.&quot;,
      },
    });
  });

  return app;
}

exports.api = functions.region(REGION).https.onRequest(initApi());
</code></pre>
<p>Here is the admin controller:</p>
<pre><code>/**
 * Controller for the admin entity.
 */
class AdminController extends BaseController {
  /**
   * Bind all the endpoints for the admin entites for the current app.
   * @param {Express} app [Current instance of the application]
   */
  bindEndpoints(app) {
   

    /**
     * Create a new admin in the storage
     * @return {Object} [Containing the response]
     */
    app.post(&quot;/admins&quot;, (request, response) =&gt; {
       ... call to services, whatever...
  
    });

  }
}
</code></pre>
<p>Now I'm trying to write some junit tests for the enpoints, here is my admin.spec.js class</p>
<pre><code>/* eslint-disable no-unused-vars */
/* eslint-disable max-len */
/* eslint-disable no-undef */
// eslint-disable-next-line no-unused-vars
/* ;
;*/

// test offline mode
const admin = require(&quot;firebase-admin&quot;);
const test = require(&quot;firebase-functions-test&quot;)();
const functions = require(&quot;../index.js&quot;);

const bodyParser = require(&quot;body-parser&quot;);
const sinon = require(&quot;sinon&quot;);
const request = require(&quot;supertest&quot;);
const express = require(&quot;express&quot;);

const AdminController = require(&quot;../Controller/AdminController&quot;);
const Calendar = require(&quot;common/Calendar/Calendar&quot;);


/**
 * Contains all the tests for the creation of an admin.
 */
describe(&quot;Admin creation&quot;, () =&gt; {
  let app;
  let adminInitStub;

  before((done) =&gt;{
    adminInitStub = sinon.stub(admin, &quot;initializeApp&quot;);
    app = express();
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));
    AdminController.prototype.bindEndpoints(app);
    app.listen((err) =&gt;{
      if (err) {
        console.log(err);
        return done(err);
      }
      done();
    });
  });

  /**
   * Successfull case
   */
  it(&quot;Admin creation - requestor is admin, credentials exist - OK &quot;, (done) =&gt; {
    test.database.makeDataSnapshot({
      name: &quot;admin&quot;,
      surname: &quot;test&quot;,
      token: &quot;ADM1&quot;,
      createdAt: Calendar.prototype.getTodaySeconds(),
    }, &quot;/admins/abcd&quot;);

    const mockAdminRequestor = test.auth.makeUserRecord({
      email: &quot;admin@test.com&quot;,
      uid: &quot;ADM1&quot;,
      customClaims: {
        role: &quot;admin&quot;,
        ID: &quot;abcd&quot;,
      },
    });

    const mockAdminCrdentials = test.auth.makeUserRecord({
      email: &quot;admin2@test.com&quot;,
      uid: &quot;ADM2&quot;,
      customClaims: {
        role: &quot;admin&quot;,
      },
    });

    request(app)
        .post(&quot;/admins&quot;)
        .send({
          name: &quot;admin2&quot;,
          surnam: &quot;test&quot;,
        })
        .set(&quot;Authorization&quot;, &quot;Bearer &quot; + mockAdminRequestor.uid)
        .set(&quot;credentials-token&quot;, mockAdminCrdentials)
        .expect(&quot;Content-Type&quot;, /json/)
        .expect(200, (err, response) =&gt;{
          console.log(response.body);
          if (err) {
            return done(err);
          }
          done();
        });
  });

  after(() =&gt; {
    test.cleanup();
  });
});
</code></pre>
<p>This test ALLWAYS fails because the application is unable to retrieve the firebase created user here:</p>
<pre><code>const mockAdminRequestor = test.auth.makeUserRecord({
      email: &quot;admin@test.com&quot;,
      uid: &quot;ADM1&quot;,
      customClaims: {
        role: &quot;admin&quot;,
        ID: &quot;abcd&quot;,
      },
    });
</code></pre>
<p>this is the output:</p>
<pre><code>{
  code: 404,
  message: { it: 'Actor ADM1 non trovato', en: 'Actor ADM1 not found' }
}
</code></pre>
<p>And it comes from a function called by the AdminController class:</p>
<pre><code>/**
   * [get the info of a firebase user with the provided ID]
   *  @param  {String} uid [uid of the user to get]
   * @return {Object} [Containing the response.]
   */
  getFirebaseUserAsync(uid) {
    return new Promise((res, rej) =&gt; {
      try {
        return admin
            .auth()
            .getUser(uid)
            .then((userRecord) =&gt; {
              return res({code: 200, data: userRecord.toJSON()});
            })
            .catch(() =&gt; {
              return rej({
                code: 404,
                message: {
                  it: &quot;Actor &quot; + uid + &quot; non trovato&quot;,
                  en: &quot;Actor &quot; + uid + &quot; not found&quot;,
                },
              });
            });
      } catch (err) {
        return rej({code: 500, error: err});
      }
    });
  }
</code></pre>
<p>I think there is something wrong with the initialization of the firebase admin app,any hints? Thanks.</p>
",https://stackoverflow.com/questions/74252448/firebase-function-test-with-sinon-cannot-mock-user-unit-testing,"['node.js', 'firebase', 'express', 'unit-testing', 'sinon']",65,False,0,0
Unit testing service calls from an Angular component rxjs subscription,"<p>I have this Angular (v13) code in a component:</p>
<pre><code>export class MyComp {
  destroy$ = new Subject&lt;void&gt;();
  submits$ = new Subject&lt;MyFormState&gt;(); // .next() in the template

  ngOnInit(){
    this.submits$.pipe(
      takeUntil(this.destroy$)
    ).subscribe(formState =&gt; this.service.doSomething(formState));
  }
}
</code></pre>
<p>and I am trying to unit test it using jasmine spy object:</p>
<pre><code>describe('MyComp', () =&gt; {
  let submits$ = new Subject&lt;MyFormState&gt;();
  let mock = jasmine.createSpyObj('MyService', [ 'doSomething' ]);

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ MyComp ],
      providers: [
        { provide: MyService, useValue: mock },
      ],
    });
  });

  it('should be called when clicking the button', () =&gt; {
    const f: MyFormState = { name: 'my name' };
    component.submits$.next(formState);

    waitForAsync(() =&gt; {
      expect(mock.doSomething).toHaveBeenCalledWith(f); // &lt;-- false positives, anything passes
    });
  });
});
</code></pre>
<p>I have also tried another async pattern</p>
<pre><code>it('should be called when clicking the button', fakeAsync(() =&gt; {
  // ...nexting

  tick();

  // without waitForAsync
  expect(mock.doSomething).toHaveBeenCalledWith(f);
}));
</code></pre>
<p>but in this case the method never gets called.</p>
<p>What am I doing wrong?
What would be the correct way of testing this code without using <code>done()</code>?
Is it possible to use TestScheduler with this sort of anonymous subscription?</p>
",https://stackoverflow.com/questions/73966602/unit-testing-service-calls-from-an-angular-component-rxjs-subscription,"['angular', 'rxjs', 'jasmine']",204,False,0,1
Guidance on unit testing in Python and usage of mock,"<p>I have a directory whose current structure is:</p>
<pre><code>raaj
|_ earth.py
|_ Science.json
|_ testearth.py
</code></pre>
<p>Inside <code>Science.json</code>:</p>
<pre><code>{
    &quot;items&quot;: [
        &quot;hello&quot;
    ]
}
</code></pre>
<p>My <code>earth.py</code> looks like this:</p>
<pre><code>import json

class Foo:
    foo_obj: str

    def __init__(self):
        self.foo_obj = &quot;Raaj&quot;
    
    def get_foo(self):
        return self.foo_obj

class Bar: 
    bar_obj: str

    def __init__(self):
        self.bar_obj = &quot;Science.json&quot;

    def get_bar(self):
        return self.bar_obj

class Earth:

    my_name: Foo
    file_path_obj: Bar

    def __init__(self):
        self.my_name = Foo()
        self.file_path_obj = Bar()

    def do_magic(self):
        with open(self.file_path_obj.get_bar(), &quot;rb&quot;) as json_file:
            json_data = json.load(json_file)
        names = json_data[&quot;items&quot;]
        print(names)
        mung_string = self.my_name.get_foo() + &quot; &quot; +  names[0]

        actual = Earth()
        print(mung_string)
        return &quot;Raaj hello&quot; == mung_string

if __name__ == &quot;__main__&quot;:
    eo = Earth()
    eo.do_magic()
</code></pre>
<p>For testing, I want to test this function <code>do_magic</code> and so I want to be able to mock various values of <code>mung_string</code>.
As one can see, since <code>mung_string</code> involves concatenating with JSON file string values, I figured I should mock the JSON file and have it return different expected string values.</p>
<p>I'm able to mock out values of class <code>Foo</code>. I'm able to mock the JSON file path using mock of class <code>Bar</code>. However, I'm stuck figuring out how exactly to achieve this return fake data and have it be routed through <code>do_magic</code>. I could use some help figuring out how to go about this.</p>
<p>For reference, this is how my <code>testearth.py</code> looks at the moment:</p>
<pre><code>import unittest
from unittest.mock import Mock, patch, mock_open
import json
from earth import Earth, Foo, Bar

class TestEarth(unittest.TestCase):

    @patch('earth.Bar.get_bar')
    @patch('earth.Foo.get_foo')
    def test_earth_working(self, mock_get_foo, mock_get_bar):
        &quot;&quot;&quot;
        In this test, several parts exist:
        - I need to test earth class that :
            - returns True or False when do_magic() is executed
            - Mocks JSON and returns modified values to test do_magic()
            - Mocks Foo and Bar to return modified a string representing name, and a string representing JSON file path respectively
        &quot;&quot;&quot;
        # modify return values of Foo and Bar
        mock_get_foo.return_value = &quot;PV&quot;
        mock_get_bar.return_value = &quot;Science.json&quot;

        # mock JSON
        expected_data = {
                &quot;items&quot;: [
                    &quot;PBV&quot;
                    ]
                }
        with patch('builtins.open', mock_open(read_data=expected_data) as filemock:
            with open(&quot;Science.json&quot;) as fh:
                mock_json_data = fh.read()
        print(&quot;mock JSON:{}&quot;.format(mock_json_data))
        filemock.assert_called_with(&quot;Science.json&quot;)

        earth_obj = Earth()
        expected_mung_string = &quot;PV PBV&quot;
        expected_output = False
        actual_output = earth_obj.do_magic()  # mung_string to pass = &quot;PV PBV&quot;, actual = &quot;Raaj hello&quot;
        self.assertNotEqual(expected_output, actual_output) 

if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>I get the following error on running the test:</p>
<pre><code>python -m unittest testearth.py 
E
======================================================================
ERROR: test_earth_working (testearth.TestEarth)
----------------------------------------------------------------------
Traceback (most recent call last):
  File &quot;/usr/lib64/python3.6/unittest/mock.py&quot;, line 1183, in patched
    return func(*args, **keywargs)
  File &quot;/u/pvmacibm/pooja/testearth.py&quot;, line 39, in test_earth_working
    mock_json_data = fh.read()
  File &quot;/usr/lib64/python3.6/unittest/mock.py&quot;, line 939, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File &quot;/usr/lib64/python3.6/unittest/mock.py&quot;, line 1005, in _mock_call
    result = effect(*args, **kwargs)
  File &quot;/usr/lib64/python3.6/unittest/mock.py&quot;, line 2352, in _read_side_effect
    return type(read_data)().join(_state[0])
AttributeError: 'dict' object has no attribute 'join'

----------------------------------------------------------------------
Ran 1 test in 0.007s
</code></pre>
",https://stackoverflow.com/questions/72689884/guidance-on-unit-testing-in-python-and-usage-of-mock,"['python', 'json', 'unit-testing']",23,False,0,0
Jest unit testing error: Received promise resolved instead of rejected,"<p>I am trying to test an exception being thrown, I keep getting this error. I feel like I am missing something.
I have this function:</p>
<pre><code>  async getPreferences(eUserId: string): Promise&lt;UserPreferences&gt; {    

    const userPreferences = await this.userPreferencesModel.findOne({
      eUserId,
    });

    if (!userPreferences) {
      throw new NotFoundException('no results');
    }
    return userPreferences;
  }
</code></pre>
<p>This is the test I have:</p>
<pre><code> it('should throw an error if no userPreferences found', async () =&gt; {
      // Mock findOne result
      jest
          .spyOn(model, 'findOne')
          .mockResolvedValueOnce(throwError(new NotFoundException()));

      const result = service.getPreferences('123123');

      // Assertion
      await expect(result).rejects.toThrow('no results');
    });
</code></pre>
<p>This is the failure error I get in the console:</p>
<pre><code>Received promise resolved instead of rejected
Resolved to value: {&quot;_subscribe&quot;: [Function init]}

  94 |
  95 |       // Assertion
&gt; 96 |       await expect(result).rejects.toThrow('no results');
     |             ^
  97 |     });
  98 |   });
  99 |

  at expect (../node_modules/expect/build/index.js:128:15)
  at Object.&lt;anonymous&gt; (user-preferences/user-preferences.service.spec.ts:96:13)
</code></pre>
",https://stackoverflow.com/questions/72613234/jest-unit-testing-error-received-promise-resolved-instead-of-rejected,"['unit-testing', 'jestjs', 'nest']",492,False,-1,1
Not able to print debug message while unit testing in Flutter,"<p>I am testing a pretty straightforward use-case in Flutter. Inside the use-case class, I have a function that I'm invoking from my test. And I want to add some debug print statements to print the value of some variables inside the function of use-case. But it's not getting printed anywhere. How can I achieve this?</p>
<p>The function in Use-case.</p>
<pre><code>Future&lt;Either&lt;Failure, List&lt;Contest&gt;&gt;&gt; call(NoParams params) async {
final result = await repository.getAllContests();
final currentDateTime = DateTime.now();
List&lt;Contest&gt; ongoingContests = [];

result.fold(
    (l) =&gt; throw ServerException(),
    (allContestList) =&gt; () {
          for (var contest in allContestList) {
            var contestStartTime = DateTime.parse(contest.start_time);
            var contestEndTime = DateTime.parse(contest.end_time);
            print(contestEndTime); //print statement
          }
        });

return Right(ongoingContests);
</code></pre>
<p>}
}</p>
<p>The test function</p>
<pre><code>test('Should return only the ongoing contests', () async {
  when(mockHomepageRepository.getAllContests()).thenAnswer((_) async =&gt;
      const Right([tContest, tOngoingContest, tUpcomingContest]));

  final result = await getOngoingContests(NoParams()); //invoking the function

  expect(result, const Right([tOngoingContest]));
  verify(mockHomepageRepository.getAllContests());
  verifyNoMoreInteractions(MockHomepageRepository());
});
</code></pre>
",https://stackoverflow.com/questions/71572593/not-able-to-print-debug-message-while-unit-testing-in-flutter,"['flutter', 'unit-testing', 'testing', 'clean-architecture']",243,False,4,0
How to upload files when unit testing firebase storage security rules?,"<p>I have a bucket into which users can upload audio files, and my goal is to test that it is working as expected. But when I try to use the &quot;@firebase/rules-unit-testing&quot; library to upload a test file into the emulator the upload gets stuck and makes no progress.</p>
<p><strong>Rules</strong></p>
<pre><code>rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if false;
    }
    match /audio/{audioFileID} {
      allow create: if request.auth != null &amp;&amp; request.resource.contentType.matches('audio/(flac|wav)');
    }
  }
}

</code></pre>
<p><strong>Test code</strong></p>
<pre class=""lang-js prettyprint-override""><code>import {
  assertFails,
  assertSucceeds,
  initializeTestEnvironment,
  RulesTestEnvironment,
} from &quot;@firebase/rules-unit-testing&quot;;
import { test, beforeAll, beforeEach, afterAll } from &quot;vitest&quot;;
import fs from &quot;fs&quot;;

const createTestFile = (size: number) =&gt; Buffer.alloc(size);
let testEnv: RulesTestEnvironment;

beforeAll(async () =&gt; {
  testEnv = await initializeTestEnvironment({
    projectId: &quot;stst-et-interviewer-dev&quot;,
    hub: {
      host: &quot;localhost&quot;,
      port: 4400,
    },
  });
});

beforeEach(async () =&gt; {
  await testEnv.clearStorage();
  await testEnv.clearFirestore();
});

afterAll(async () =&gt; await testEnv.cleanup());

const loadStepStoneImage = () =&gt;
  fs.readFileSync(&quot;./public/images/stepstoneLogo.svg&quot;);

test(&quot;Storage does not allow you to read files&quot;, async () =&gt; {
  const rouge = testEnv.unauthenticatedContext();
  const alice = testEnv.authenticatedContext(&quot;alice&quot;);
  await assertFails(
    rouge.storage().ref(&quot;audio/test-interview.flac&quot;).getDownloadURL()
  );
  await assertFails(
    alice.storage().ref(&quot;audio/test-interview.flac&quot;).getDownloadURL()
  );
  await assertFails(alice.storage().ref(&quot;audio/&quot;).listAll());
});

test(&quot;Storage does not allow you to upload a file if you are not logged in&quot;, async () =&gt; {
  const rouge = testEnv.unauthenticatedContext();
  const upload = rouge
    .storage(&quot;stst-et-interviewer-dev.appspot.com&quot;)
    .ref(&quot;audio/logo.svg&quot;)
    .put(createTestFile(200), { contentType: &quot;audio/flac&quot; });
  
  await assertFails(upload.then()); // &lt;- GETS STUCK HERE
  console.log(&quot;this does not happen&quot;);
});
</code></pre>
<p>What are the possible reasons for this happening? Are there any simple ways of debugging?</p>
",https://stackoverflow.com/questions/72815018/how-to-upload-files-when-unit-testing-firebase-storage-security-rules,"['node.js', 'firebase-storage', 'firebase-security']",159,False,4,0
Unit testing a function using java library azure-storage-blob mocked,"<p>When working with azure BlobStorage I'm quite new to this topic but I managed to get it working in java. So we have some xml files saved there and collect the file list as strings. Now I've tried to create a unit tests to verify it stays working and since the getFiles() function is a very small I expected it to be very simple to test.</p>
<pre><code>@Override
public List&lt;String&gt; getFiles(ExecutionContext context) {
    return StreamSupport.stream(blobContainerClient.listBlobs().spliterator(), true)
        .map(BlobItem::getName)
        .collect(Collectors.toList());
}
</code></pre>
<p>I can mock the com.azure.storage.blob.blobContainerClient and its function listBlobs, but when trying to create the PagedIterable from a simple List I cannot make it fit the right data types or it runs into an endless loop.</p>
<p>Since the functionality is so minimal, we would just skip to test this, but ou of curiosity I just want to know if it could be tested or what is wrong with my code:</p>
<pre><code>import com.azure.core.http.rest.*;
import com.azure.core.util.IterableStream;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.models.BlobItem;
import com.microsoft.azure.functions.ExecutionContext;
import lombok.SneakyThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.CoreSubscriber;
import reactor.core.Fuseable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;

class BlobstoreConnectorListFilesTest {
    private final BlobContainerClient blobContainerClientMock = mock(BlobContainerClient.class);
    private final ExecutionContext context = mock(ExecutionContext.class);

    private final String id1 = UUID.randomUUID().toString();
    private final String id2 = UUID.randomUUID().toString();

    @BeforeEach
    void setUp() {
        BlobItem item1 = mock(BlobItem.class);
        when(item1.getName()).thenReturn(id1 + &quot;.xml&quot;);
        
        BlobItem item2 = mock(BlobItem.class);
        when(item2.getName()).thenReturn(id2 + &quot;.xml&quot;);
        
        List&lt;BlobItem&gt; arrayList = new ArrayList&lt;&gt;();
        arrayList.add(item1);
        arrayList.add(item2);
        Mono&lt;PagedResponse&lt;BlobItem&gt;&gt; monoSource = new Mono&lt;&gt;() {
            private final Page&lt;BlobItem&gt; page = new Page&lt;&gt;() {
                @Override
                public IterableStream&lt;BlobItem&gt; getElements() {
                    return new IterableStream&lt;&gt;(Flux.fromIterable(arrayList));
                }

                @Override
                public String getContinuationToken() {
                    return null;
                }
            };
            final PagedResponseBase&lt;String, BlobItem&gt; pagedResponseBase = new PagedResponseBase&lt;&gt;(null, 200, null, page
                , null);

            final Fuseable.QueueSubscription&lt;BlobItem&gt; fuseableQueueSubscription = new Fuseable.QueueSubscription&lt;&gt;() {
                @Override
                public void request(long l) {
                }
                @SneakyThrows
                @Override
                public void cancel() {
                    throw new InterruptedException();
                }
                @Override
                public int size() {
                    return arrayList.size();
                }
                @Override
                public boolean isEmpty() {
                    return arrayList.isEmpty();
                }
                @Override
                public void clear() {
                    arrayList.clear();
                }
                @Override
                public BlobItem poll() {
                    var value = arrayList.stream().findFirst().orElse(null);
                    if(value!=null){
                        arrayList.remove(value);
                    }
                    return value;
                }
                @Override
                public int requestFusion(int i) {
                    return 0;
                }
            };

            @Override
            public void subscribe(CoreSubscriber&lt;? super PagedResponse&lt;BlobItem&gt;&gt; coreSubscriber) {
                coreSubscriber.onNext(pagedResponseBase);
                coreSubscriber.onSubscribe(fuseableQueueSubscription);
            }
        };
        Supplier&lt;Mono&lt;PagedResponse&lt;BlobItem&gt;&gt;&gt; blobItemSupplier = () -&gt; monoSource;
        PagedFlux&lt;BlobItem&gt; pagedFlux = new PagedFlux&lt;&gt;(blobItemSupplier);
        PagedIterable&lt;BlobItem&gt; leaflets = new PagedIterable&lt;&gt;(pagedFlux);
        doReturn(leaflets).when(blobContainerClientMock).listBlobs();
    }

    @Test
    void getAllFiles() {
        BlobstoreConnector connector = new BlobstoreConnector(blobContainerClientMock);

        List&lt;String&gt; actual = connector.getFiles(context);
        
        assertEquals(2, actual.size());
        assertTrue(actual.stream().anyMatch(fileName -&gt; fileName.equals(id1 + &quot;.xml&quot;)));
        assertTrue(actual.stream().anyMatch(fileName -&gt; fileName.equals(id2 + &quot;.xml&quot;)));
    }
}
</code></pre>
",https://stackoverflow.com/questions/70656755/unit-testing-a-function-using-java-library-azure-storage-blob-mocked,"['java', 'unit-testing', 'pagination', 'mocking', 'azure-blob-storage']",2902,False,3,0
Can we do unit testing controllers in Blazor WebAssembly using Bunit,"<p>Can we do unit testing for controllers/end point in Blazor WebAssembly using Bunit x unit?</p>
<p><a href=""https://bunit.dev/"" rel=""nofollow noreferrer"">https://bunit.dev/</a></p>
<p>like this
<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>If not what is the way to do unit test for API status code checking in Blazor WebAssembly?</p>
<p>Please guide me.</p>
",https://stackoverflow.com/questions/74828550/can-we-do-unit-testing-controllers-in-blazor-webassembly-using-bunit,"['unit-testing', 'blazor', 'xunit', 'blazor-webassembly', 'bunit']",80,False,2,0
Unit Testing the SEQUENCE of values emitted from a single livedata,"<p>I want to unit-test the sequence of a LiveData's results. I have a <code>result</code> LiveData which emits values when loading, success, or error. I want to test it to ensure that loading value is emitted first, then the success or error value.</p>
<p>is there a way to do this?</p>
",https://stackoverflow.com/questions/73090137/unit-testing-the-sequence-of-values-emitted-from-a-single-livedata,"['android', 'unit-testing', 'testing', 'android-livedata', 'android-architecture-components']",489,True,2,1
Abstracting/Interfacing a class within a Nuget Package for Unit Testing,"<p>So I have a Application that currrently uses the EAGetMail nuget package for scraping EmailServers. I am attempting to refactor my project and interface individual pieces for mocking in Unit Tests. My current issue is the classes in the package don't seem to be interfaced and I am not sure if interfacing them indirectly would work. Could just be a lack of understanding or a different way t<a href=""https://i.stack.imgur.com/JNlKb.png"" rel=""nofollow noreferrer"">enter image description here</a>o mock the data is needed. Anything would help!</p>
<p><a href=""https://i.stack.imgur.com/XI7MQ.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
<p><a href=""https://i.stack.imgur.com/MjQlm.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/MjQlm.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73919363/abstracting-interfacing-a-class-within-a-nuget-package-for-unit-testing,"['c#', '.net', 'visual-studio', 'unit-testing', 'interface']",145,True,1,1
Python unit testing Beautiful Soup 4 - ResultSet. How to mock that?,"<p>I have a function that returns dict based on ResultSet from Beautiful Soup:</p>
<pre><code>return {image[&quot;src&quot;]: image[&quot;alt&quot;] for image in images_data}
</code></pre>
<p>and i just have no idea how to test that.
My first idea was preparing a HTML document with images and expected data. Then I just compare expected data to returned dict:</p>
<pre><code>from bs4 import BeautifulSoup
import pytest


@pytest.fixture()
    def load_test_data(self):
        example_website = (
            Path(__file__).parent / &quot;../tests/test_data/example_website.html&quot;
        )
        with open(example_website, &quot;r&quot;) as f:
            website_data = BeautifulSoup(f.read(), &quot;html.parser&quot;)
        return string_operations.prepare_src_and_alt(
            website_data.select(&quot;img.full-image&quot;)
        )

    expected_data_keys = (&quot;string&quot;,)
    expected_data_values = (&quot;another_string&quot;,)

    @pytest.mark.parametrize(
        (&quot;img_src&quot;, &quot;img_alt&quot;), zip(expected_data_keys, expected_data_values)
    )
    def test_output_should_have_proper_data(self, load_test_data, img_src, img_alt):
        data = load_test_data
        assert data[img_src] == img_alt
</code></pre>
<p>I'm sure that is a bad way to do unit tests. Anyone had an idea how to properly mock ResultSet or make test data?</p>
",https://stackoverflow.com/questions/72578822/python-unit-testing-beautiful-soup-4-resultset-how-to-mock-that,"['python', 'unit-testing', 'beautifulsoup', 'pytest']",452,False,1,1
Unit testing of Angular app in Azure DevOps pipeline timing out,"<p>I'm trying to set up testing of our Angular app in an Azure DevOps pipeline, but am running into trouble with unit testing timing out.  This is in a Linux virtual machine, with the chromedriver npm package installed (<code>npm install chromedriver --chromedriver-force-download --include_chromium</code>).  Below is the error I am seeing (I tried increasing the timeout period, but it still times out):</p>
<pre><code>INFO [karma-server]: Karma v6.3.17 server started at http://localhost:9876/
INFO [launcher]: Launching browsers ChromeHeadless with concurrency unlimited
INFO [launcher]: Starting browser ChromeHeadless
WARN [launcher]: ChromeHeadless has not captured in 180000 ms, killing.
INFO [launcher]: Trying to start ChromeHeadless again (1/2).
WARN [launcher]: ChromeHeadless has not captured in 180000 ms, killing.
INFO [launcher]: Trying to start ChromeHeadless again (2/2).
WARN [launcher]: ChromeHeadless has not captured in 180000 ms, killing.
ERROR [launcher]: ChromeHeadless failed 2 times (timeout). Giving up.
</code></pre>
<p>The <code>CHROME_BIN</code> environment variable is set correctly via:</p>
<pre><code>export CHROME_BIN=&lt;project-path&gt;/node_modules/chromedriver/lib/chromedriver/chromedriver
</code></pre>
<p>Testing then then started with:</p>
<pre><code>ng test --watch=false --browsers=ChromeHeadless --reporters=junit --code-coverage
</code></pre>
<p>Is the chromedriver sufficient to run unit tests on an Angular app?  Do I need to install something else?  Is there any way to tell if testing is even happening?</p>
",https://stackoverflow.com/questions/72875291/unit-testing-of-angular-app-in-azure-devops-pipeline-timing-out,"['angular', 'unit-testing', 'azure-pipelines']",590,False,1,0
How to do unit testing to @Inject with ClientKafka in NestJS,"<p>I need to do some unit test to a kafka implementation in my project with NestJS but I don't know how to do it.</p>
<p>I have a <code>Service</code> thats inject a Client Kafka</p>
<pre><code>export class Service {
  private static readonly logger = new Logger(ProducerService.name);

  constructor(
    @Inject('kafka-registrar') private client: ClientKafka,
    private someOtherService: SomeOtherService,
  ) {}
</code></pre>
<p>Module</p>
<pre><code>@Module({
  imports: [
    ClientsModule.register([
      {
        name: 'kafka-registrar',
        transport: Transport.KAFKA,
        options: {
          client: {
            clientId: 'hero',
            brokers: ['localhost:9092'],
          },
          consumer: {
            groupId: '1',
          },
        },
      },
    ]),
    SomeOtherService,
  ],
  providers: [Service],
})
export class Module {}
</code></pre>
<p>Unit test</p>
<pre><code>describe('Test Controller', () =&gt; {
  let clientKafka: ClientKafka;
  let someOtherService: SomeOtherService;
  let producerService: ProducerService;

  beforeEach(async () =&gt; {
    const moduleRef = await Test.createTestingModule({
      providers: [
        ProducerService,
        {
          provide: SchemaRegistryService,
          useValue: {
            encodeWithId: jest.fn(),
          },
        },
        {
          provide: ClientKafka,
          useValue: {
            emit: jest.fn(),
          },
        },
      ],
    }).compile()

    clientKafka = moduleRef.get(ClientKafka);
    schemaRegistryService = moduleRef.get(SchemaRegistryService);
    producerService = moduleRef.get(ProducerService);
  });
</code></pre>
<p>The project give me this error:</p>
<pre><code>Error: Nest can't resolve dependencies of the ProducerService (?, SchemaRegistryService). Please make sure that the argument kafka-registrar at index [0] is available in the RootTestModule context.

Potential solutions:
- If kafka-registrar is a provider, is it part of the current RootTestModule?
- If kafka-registrar is exported from a separate @Module, is that module imported within RootTestModule?
  @Module({
    imports: [ /* the Module containing kafka-registrar */ ]
  })
</code></pre>
<p>I don't know how to resolve this in NestJS. For example in Java,I belive that this can be with <code>@Mock ClientKafka clientKafka</code> bit I dont have any other experience with NestJS... Please helpme! :)</p>
",https://stackoverflow.com/questions/70805031/how-to-do-unit-testing-to-inject-with-clientkafka-in-nestjs,"['nestjs', 'kafkajs']",1598,True,1,1
Trouble unit testing angular reactive form control reset from button click,"<p>I am facing an issue to write an unit test case in jasmine for my angular application.
Have a reactive form and trying to reset a particular form control from a button click.
Even though the scenario should be simple enough to test, it seems that I am missing something here.</p>
<p>Below is the code snippet from the app.</p>
<p>app.component.html:</p>
<pre><code>&lt;form [formGroup]=&quot;userForm&quot; novalidate (ngSubmit)=&quot;onSubmit()&quot;&gt;
  &lt;div&gt;
    &lt;input
      type=&quot;text&quot;
      id=&quot;fNameFld&quot;
      name=&quot;fName&quot;
      formControlName=&quot;fName&quot;
      placeholder=&quot;First Name&quot;
    /&gt;
    &lt;button (click)=&quot;clearField('fName')&quot; id=&quot;clrFName&quot;&gt;
      Clear First Name
    &lt;/button&gt;
  &lt;/div&gt;

  &lt;div&gt;
    &lt;input
      type=&quot;text&quot;
      id=&quot;lNameFld&quot;
      name=&quot;lName&quot;
      formControlName=&quot;lName&quot;
      placeholder=&quot;Last Name&quot;
    /&gt;
    &lt;button (click)=&quot;clearField('lName')&quot; id=&quot;clrLName&quot;&gt;Clear Last Name&lt;/button&gt;
  &lt;/div&gt;

  &lt;div&gt;
    &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;
  &lt;/div&gt;
&lt;/form&gt;
</code></pre>
<p>app.component.ts</p>
<pre><code>import { FormBuilder, FormGroup } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular ' + VERSION.major;
  userForm: FormGroup;

  constructor(private readonly fb: FormBuilder) {}

  ngOnInit() {
    this.userForm = this.fb.group({
      fName: this.fb.control(null),
      lName: this.fb.control(null),
    });
  }

  onSubmit() {
    console.log('Submitted Data', this.userForm.value);
  }

  clearField(controlName: string) {
    this.userForm.get(controlName).reset();
  }
}
</code></pre>
<p>Unit test code</p>
<pre><code>it('should clear fName control when the &quot;Clear First Name&quot; button is clicked', () =&gt; { 
    const spy = spyOn(component, 'clearField');
    const clearBtn = fixture.debugElement.query(By.css(&quot;button#clrFName&quot;));
    const form = component.userForm;
    
    form.patchValue({
      'fName': 'John,
      'lName': 'Doe'
    });
    
    clearBtn.nativeElement.click();
    fixture.detectChanges();
    expect(spy).toHaveBeenCalledTimes(1);  // passes
    expect(spy).toHaveBeenCalledWith('fName');  // passes
    expect(form.get('fName').value).toBeNull();  // fails: Expected 'John' to be null.
  });
</code></pre>
<p>Angular: 10.0.14</p>
<p>Angular CLI: 10.0.8</p>
<p>StackBlitz: <a href=""https://angular-ivy-fc6rik.stackblitz.io"" rel=""nofollow noreferrer"">https://angular-ivy-fc6rik.stackblitz.io</a></p>
",https://stackoverflow.com/questions/71005874/trouble-unit-testing-angular-reactive-form-control-reset-from-button-click,"['javascript', 'html', 'angular', 'jasmine']",2689,True,1,1
Unit testing Spring Service with the connections to Mapper and Repository,"<p>I'm wondering what's the best approach to test the Service layer when I use Mapper and Repository inside my Service:</p>
<pre class=""lang-java prettyprint-override""><code>public ExpenseDto create(NewExpenseDto newExpenseDto) {

    ExpenseEntity expenseEntity = expenseMapper.fromNewDtoToEntity(newExpenseDto);
    ExpenseEntity savedExpenseEntity = expenseRepository.save(expenseEntity);
    ExpenseDto expenseDto = expenseMapper.fromEntityToDto(savedExpenseEntity);

    return expenseDto;
}
</code></pre>
<p>I have written a test like this below, but I'm not sure if it's the best way - in accordance with the rules of programming.</p>
<pre class=""lang-java prettyprint-override""><code>@ExtendWith(MockitoExtension.class)
class ExpenseServiceTest {

    @Mock
    private ExpenseRepository expenseRepository;
    @Mock
    private ExpenseMapper expenseMapper;
    @InjectMocks
    private ExpenseService expenseService ;

    @Test
    void givenNewExpenseDto_whenNewExpense_thenExpenseDtoNotNull() {
        //Given
        NewExpenseDto newExpenseDto = new NewExpenseDto();
        ExpenseEntity expenseEntity = new ExpenseEntity();
        ExpenseDto expenseDto = new ExpenseDto();

        //When
        when(expenseMapper.fromNewDtoToEntity(any())).thenReturn(expenseEntity);
        when(expenseRepository.save(any())).thenReturn(expenseEntity);
        when(expenseMapper.fromEntityToDto(any())).thenReturn(expenseDto);
        ExpenseDto savedExpenseDto = expenseService.create(newExpenseDto);

        //Then
        assertNotNull(savedExpenseDto, &quot;Saved ExpenseDto is null&quot;);
    }
...
}
</code></pre>
",https://stackoverflow.com/questions/70760239/unit-testing-spring-service-with-the-connections-to-mapper-and-repository,"['java', 'spring', 'spring-boot', 'junit', 'mockito']",693,True,1,1
How to manually stub out a function in C# unit testing,"<p>I'm trying to create my own Mock function. I know Moq exists, but I really want to accomplish this.</p>
<p>I have no idea how I'd create a Mock function to stub out User#Foobar's calls to Product#Price in order to unit test User#Foobar:</p>
<pre><code>using System;

public class MyUnitTest
{
    // CODE BEING TESTED
    class Product {
        public string Price() {
            return &quot;I WANT TO STUB THIS OUT, DONT WANT TO SEE THIS STRING&quot;;
        }
    }
    class User {
        public string Foobar() {
            Product product = new Product();
            return $&quot;Foobar, Product#price returns: {product.Price()}&quot;;
        }    
    }
    //////////////////////
    
    // CODE THAT DOES THE TEST
    public void Mock(string mockedClass, string mockedFunction, string mockedReturn)
    {
        // no idea what to put here something to do with an interface
    }
    
    public void RunTests()
    {
        Mock(&quot;Product&quot;,&quot;Price&quot;,&quot;MOCKED DATA&quot;);
        string expected = new User().Foobar();
        Assert(expected, &quot;Foobar, Product#price returns: MOCKED DATA&quot;);
    }
        
    public void Assert(string actual, string expected){
        Console.WriteLine(actual == expected);
    }
    //////////////////////

    // How do I stub out Product to return &quot;MOCKED DATA&quot;?
}
                    
public class Program
{
    public static void Main(){
        new MyUnitTest().RunTests();
    }
}
</code></pre>
<p>I know how to do it in Ruby, but not in C#.</p>
<p>Here's a NET fiddle of the problem:</p>
<p><a href=""https://dotnetfiddle.net/8Re2jb"" rel=""nofollow noreferrer"">https://dotnetfiddle.net/8Re2jb</a></p>
<p>What should this Mock function do to intercept User#Foobar's call to Product#Price and return the string &quot;MOCKED DATA&quot;?</p>
<pre><code>public void Mock(string mockedClass, string mockedFunction, string mockedReturn)
{
}
</code></pre>
",https://stackoverflow.com/questions/72435054/how-to-manually-stub-out-a-function-in-c-unit-testing,"['c#', 'unit-testing', 'mocking']",412,True,1,1
What scope does unit testing cover in a weakly typed language?,"<p>The best way I can express my question is with an example.</p>
<pre class=""lang-js prettyprint-override""><code>class foo{
  constructor(size) {
    this.bar = new Array(size);
  }
  baz(index) {
    this.body[index] = true;
  }
}
</code></pre>
<p>Ignoring the constructor, assume we're unit testing <code>baz()</code>. baz is <strong>logically</strong> expected to take an input <code>index</code> that's between <code>0</code> and <code>bar.length - 1</code>, but the following can also compile:</p>
<ol>
<li><code>baz(['hey'])</code></li>
<li><code>baz(5) // with an array size of 2</code></li>
<li><code>baz(true)</code></li>
<li><code>baz('0')</code></li>
</ol>
<p>Now, I've been doing a lot of research on <strong>what</strong> we're actually testing with unit tests, and the best answer I can gather from what I read all around, is that, we're testing the function's behavior within the bounds of its logical contract with what/who's calling it. AKA, test implementation while implicitly assuming that <strong>it' called correctly</strong>.</p>
<p>I'm fully satisfied with this, but what I want to know is, where do we draw that line? None of the examples above will cause a typeerror, but I can disregard 1,3 and probably 4 if I'm to follow what I learned above.</p>
<p>But should I care about 2? Or do I also assume that the function's 'contract' will be upheld not only in terms of the inputs' implicit typing, but also their logical bounds.</p>
<p>Should I test and account for example 2 in my code?</p>
",https://stackoverflow.com/questions/72955017/what-scope-does-unit-testing-cover-in-a-weakly-typed-language,"['javascript', 'unit-testing', 'testing']",28,True,1,1
Django rest framework: Unit testing post request gets status code 400,"<p>I'm doing some unit tests in this restaurant app, and the API request to cancel orders returns code 400 when running &quot;manage.py test&quot; command, but doing the same request on Postman works fine (with the server also running on my local machine with the &quot;manage.py runserver&quot; command). I think it's something I'm doing wrong with the unit test, but I'm not sure. In settings, Debug = True and ALLOWED_HOSTS = ['*'] (but I also tried ALLOWED_HOSTS = []). Here's the code:</p>
<p>tests.py</p>
<pre><code>class CancelOrderAPITest(APITestCase):

    def setUp(self):
        test_product = Products.objects.create(id=1, name='testProduct', description='-test-', price=2.56)
        test_product.save()
        test_order = Order.objects.create(table=1, status='WA')
        test_order.save()
        test_order.product.add(test_product)

        self.user = User.objects.create(username='test')
        self.user.set_password('passtest')
        self.user.save()

        Payments.objects.create(value=0.0, user=self.user)
        Token.objects.create(user=self.user)

    def test_CancelWithCredentials(self):
        check_login = self.client.login(username='test', password='passtest')
        self.assertTrue(check_login)

        token = Token.objects.get_or_create(user=self.user)
        self.client.credentials(HTTP_AUTHORIZATION=f'Token {token[0].key}')

        data = {&quot;table&quot;: 1}

        response = self.client.post(reverse('cancel-order'), data=data, content_type='application/json')
        order = Order.objects.filter(table=data['table']).order_by('date')[0]

        self.assertEqual(response.status_code, status.HTTP_200_OK)  # returning 400. Investigate further
        self.assertEqual(order.status, Order.Status.CANCELED)
</code></pre>
<p>views.py</p>
<pre><code>class CancelOrder(APIView):
    # REST API view for waiters to cancel orders. The waiter must be an authenticated user
    permission_classes = (IsAuthenticated,)
    parser_classes = (JSONParser,)

    def post(self, request):
        data = request.data

        try:
            order = Order.objects.filter(table=data['table']).order_by('date')[0]
            order.status = Order.Status.CANCELED
            order.save()
            resp = {&quot;status&quot;: &quot;Order canceled!&quot;}
        except ObjectDoesNotExist:
            resp = {&quot;exception&quot;: &quot;Couldn't find requested product!&quot;}

        return Response(resp)
</code></pre>
<p>models.py</p>
<pre><code>class Order(models.Model):

    class Status(models.TextChoices):
        WAITING = 'WA', _('Waiting')
        DELIVERED = 'DE', _('Delivered')
        PARTIAL_DELIVER = 'PD', _('Partially Delivered')
        PREPARING = 'PP', _('Preparing')
        CANCELED = 'CA', _('Canceled')
        PAID = 'PA', _('Paid')

    product = models.ManyToManyField(Products)
    table = models.IntegerField(default=1)
    status = models.CharField(max_length=100, choices=Status.choices, default=Status.WAITING)
    date = models.DateTimeField(default=datetime.datetime.now)
    payment = models.ForeignKey(Payments, on_delete=models.DO_NOTHING, default=1)
</code></pre>
",https://stackoverflow.com/questions/71916877/django-rest-framework-unit-testing-post-request-gets-status-code-400,"['python', 'django', 'unit-testing', 'django-rest-framework']",1212,True,1,1
Is there a way of unit testing what imports are used?,"<p>Is there a way of unit testing what modules are imported in a Python file (a bit like ArchUnit in Java)? The context is in implementing a hexagonal architecture and wanting to ensure that the domain model does not import any code that resides in an adapter. I'd like unit tests to fail if there are forbidden imports.</p>
<p>For example, I might like to test that no modules within <code>foo.bar.domain</code> import anything from <code>foo.bar.adapter</code>. Imports of <code>foo.bar.domain</code> should be allowed from within <code>foo.bar.adapter</code>.</p>
<p>Is this possible in Python and what's the best way of achieving this?</p>
",https://stackoverflow.com/questions/71369419/is-there-a-way-of-unit-testing-what-imports-are-used,"['python', 'unit-testing', 'hexagonal-architecture']",302,True,1,2
Jetpack Compose unit testing performClick() not working with compose:1.1.0 update,"<p>I have updated my project to kotlin:1.6.10 and compose:1.1.0 version. After updating the versions my unit test case is keep on loading at performClick() it's never getting completed</p>
",https://stackoverflow.com/questions/73387130/jetpack-compose-unit-testing-performclick-not-working-with-compose1-1-0-updat,"['unit-testing', 'kotlin', 'testing', 'android-jetpack-compose']",161,False,1,0
Unit Testing for MultiPartEntityBuilder fails with org.apache.http.ContentTooLongException: Content length is unknown,"<p>I have a class in my javax servlet application that serves as a proxy and creates multipart form data for POST requests. During regression tests (actual calls to the servlet) the application performs as expected, however, my unit test continues to fail. This is the line in my unit test that throws the exception<code>String httpPostBody = IOUtils.toString(httpPost.getEntity().getContent());</code> It's specifically <code>httpPost.getEntity().getContent()</code>.</p>
<p>Full Unit Test</p>
<pre><code>@Test
public void testCreatePostRequest() throws IOException, ServletException, URISyntaxException, NullPointerException {
    URI newTargetUri = new URI(targetUriPost);
    cdsRequestBuilder = new CDSRequestBuilder();
    HttpPost httpPost = cdsRequestBuilder.createPostRequest(mockClientRequest, newTargetUri);

    // Parse the entity
    String httpPostBody = IOUtils.toString(httpPost.getEntity().getContent());

    // Perform evaluation
    Assert.assertNotNull(httpPost);
    Assert.assertEquals(httpPost.getHeaders(HttpHeaders.HOST)[0].toString(), (&quot;Host: &quot; + newTargetUri.getHost()));
    Assert.assertTrue(httpPost.getHeaders(HttpHeaders.CONTENT_LENGTH).length == 0);
    Assert.assertTrue(httpPostBody.contains(&quot;payload&quot;));
    Assert.assertTrue(httpPostBody.contains(&quot;file&quot;));
    Assert.assertTrue(httpPostBody.contains(testFileBinaryData));
}
</code></pre>
<p>Method that is tested calls this method</p>
<pre><code>private HttpEntity convertInputStreamToMultiPart(Collection&lt;Part&gt; clientParts, String boundary) throws IOException {
    Part payload = null;
    Part file = null;

    for (Part part : clientParts) {
        if (part.getName().equalsIgnoreCase(&quot;payload&quot;)) {
            payload = part;
        } else if (part.getName().equalsIgnoreCase(&quot;file&quot;)) {
            file = part;
        }
    }

    if(payload == null) {
        logIt.error(&quot;Failed to extract payload - no payload found&quot;);
        throw new IllegalStateException(&quot;Payload is missing from client request.&quot;);
    }

    if(file == null || file.getSubmittedFileName().length() == 0) {
        logIt.error(&quot;Failed to extract file - no file found&quot;);
        throw new IllegalStateException(&quot;File is missing from client request.&quot;);
    }

    logIt.info(&quot;Payload is parsed from client: {}&quot;, IOUtils.toString(payload.getInputStream()));

    return MultipartEntityBuilder.create()
            .addTextBody(&quot;payload&quot;, IOUtils.toString(payload.getInputStream()))
            .addBinaryBody(&quot;file&quot;, file.getInputStream(), ContentType.parse(&quot;application/pdf&quot;), file.getSubmittedFileName())
            .setContentType(ContentType.parse(MediaType.APPLICATION_FORM_URLENCODED))
            .setBoundary(boundary)
            .build();
}
</code></pre>
<p>This unit test passed fine previously when I was temporarily saving the file input stream to a File object and then using that to populate the binary body, but as a result of performance tests, I decided to simply pass in the file input stream itself. Note, that in my unit test, I mock the file input stream as such:
<code>Part mockFilePart = mock(Part.class);</code></p>
<pre><code>when(mockFilePart.getName()).thenReturn(&quot;file&quot;);
    when(mockFilePart.getSubmittedFileName()).thenReturn(testFileName);
    when(mockFilePart.getInputStream()).thenReturn(IOUtils.toInputStream(testFileBinaryData));
</code></pre>
<p>Full Exception</p>
<pre><code>org.apache.http.ContentTooLongException: Content length is unknown

at org.apache.http.entity.mime.MultipartFormEntity.getContent(MultipartFormEntity.java:101)
at gov.va.cds.test.CDSRequestBuilderTest.testCreatePostRequest(CDSRequestBuilderTest.java:117)
</code></pre>
",https://stackoverflow.com/questions/72627329/unit-testing-for-multipartentitybuilder-fails-with-org-apache-http-contenttoolon,"['java', 'servlets', 'mockito', 'multipartentity']",284,False,1,1
Dag run not found when unit testing a custom operator in Airflow,"<p>I've written a custom operator (DataCleaningOperator), which corrects JSON data based on a provided schema.</p>
<p>The unit tests previously worked when I didn't have to instatiate a TaskInstance and provide the operator with a context. However, I've updated the operator recently to take in a context (so that it can use xcom_push).</p>
<p>Here is an example of one of the tests:</p>
<pre><code>DEFAULT_DATE = datetime.today()

class TestDataCleaningOperator(unittest.TestCase):    
    &quot;&quot;&quot;
    Class to execute unit tests for the operator 'DataCleaningOperator'.
    &quot;&quot;&quot;
    def setUp(self) -&gt; None:
        super().setUp()
        self.dag = DAG(
            dag_id=&quot;test_dag_data_cleaning&quot;,
            schedule_interval=None,
            default_args={
                &quot;owner&quot;: &quot;airflow&quot;,
                &quot;start_date&quot;: DEFAULT_DATE,
                &quot;output_to_xcom&quot;: True,
            },
        )
        self._initialise_test_data()

    def _initialize_test_data() -&gt; None:
        # Test data set here as class variables such as self.test_data_correct
        ...

    def test_operator_cleans_dataset_which_matches_schema(self) -&gt; None:
        &quot;&quot;&quot;
        Test: Attempt to clean a dataset which matches the provided schema.
        Verification: Returns the original dataset, unchanged.
        &quot;&quot;&quot;
        task = DataCleaningOperator(
            task_id=&quot;test_operator_cleans_dataset_which_matches_schema&quot;,
            schema_fields=self.test_schema_nest,
            data_file_object=deepcopy(self.test_data_correct),
            dag=self.dag,
        )
        ti = TaskInstance(task=task, execution_date=DEFAULT_DATE)
        result: List[dict] = task.execute(ti.get_template_context())
        self.assertEqual(result, self.test_data_correct)
</code></pre>
<p>However, when the tests are run, the following error is raised:</p>
<pre><code>airflow.exceptions.DagRunNotFound: DagRun for 'test_dag_data_cleaning' with date 2022-02-22 12:09:51.538954+00:00 not found
</code></pre>
<p>This is related to the line in which a task instance is instantiated in test_operator_cleans_dataset_which_matches_schema.</p>
<p>Why can't Airflow locate the test_dag_data_cleaning DAG? Is there a specific configuration I've missed? Do I need to also create a DAG run instance or add the DAG to the dag bag manually if this test dag is outide of my standard DAG directory? All normal (non-test) dags in my dag dir run correctly.</p>
<p>In case it helps, my current Airflow version is 2.2.3 and the structure of my project is:</p>
<pre><code>airflow
├─ dags
├─ plugins
|  ├─ ...
|  └─ operators
|     ├─ ...
|     └─ data_cleaning_operator.py
|
└─ tests
   ├─ ...
   └─ operators
      └─ test_data_cleaning_operator.py
</code></pre>
",https://stackoverflow.com/questions/71221412/dag-run-not-found-when-unit-testing-a-custom-operator-in-airflow,"['python', 'python-3.x', 'airflow', 'airflow-scheduler']",2217,True,7,1
Getting an undefined error while running the unit testing in angular,"<p>I have injected the services and the model that have been used in the component.ts file, If I run the spec I was getting this error <code>TypeError: Cannot read properties of undefined (reading 'banner_image_url')</code> to solve this error I have tried several times but it failed the imports and declarations which has been given is correct or need to be changed</p>
<p>In component.ts file</p>
<pre><code>export class Component implements OnInit {
  subscriptions = new Subscription();
  filteredData: AddLandingPageResponse;
  faChevronLeft = faChevronLeft;

  constructor(
    public location: Location,
    private activatedRoute: ActivatedRoute,
    public store: Store&lt;StoreState&gt;
  ) {}
}
</code></pre>
<p>In component.spec.ts</p>
<pre><code>  let component: LandingDetailComponent;
  let fixture: ComponentFixture&lt;LandingDetailComponent&gt;;
  let translateService: TranslateService;
  let mockStore: MockStore&lt;StoreState['landing']&gt;;

 beforeEach(waitForAsync(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [LandingDetailComponent, MockComponent(LoadingButtonComponent), SafeHtmlPipe],
      imports: [
        ModalModule.forRoot(),
        BrowserAnimationsModule,
        RouterTestingModule,
        TranslateModule.forRoot({
          loader: { provide: TranslateLoader, useClass: JsonTranslationLoader },
          compiler: {
            provide: TranslateCompiler,
            useClass: TranslateMessageFormatCompiler,
          },
        }),
        ToastrModule.forRoot({
          preventDuplicates: true,
          closeButton: true,
          progressBar: true,
        }),
      ],
      providers: [
        provideMockStore({ initialState: { ...mockInitialAppState } }),
        Location,
        TranslateService
      ],
    }).compileComponents();
  }));

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(LandingDetailComponent);
    fixture.detectChanges();
    component = fixture.componentInstance;
    translateService = TestBed.inject(TranslateService);
    landingService = TestBed.inject(LandingService);
    mockStore = TestBed.inject(MockStore);
    translateService.use('en');
  });

 describe('Component', () =&gt; {
    it('call the component', () =&gt; {
      expect(component).toBeTruthy();
    });
  });

</code></pre>
<p>can anyone help me to solve this error</p>
",https://stackoverflow.com/questions/74863236/getting-an-undefined-error-while-running-the-unit-testing-in-angular,['angular'],385,True,0,1
Should we need to mock mongoose validate() method while unit testing?,"<p>I am unit testing my node application with Jest. Should we need to mock the mongoose validate() method?</p>
<p>I want to test my mongoose model which is this:</p>
<pre><code>const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, &quot;Please enter your name&quot;],
  },
  email: {
    type: String,
    required: [true, &quot;Please enter your email address&quot;],
  },
  password: {
    type: String,
    required: [true, &quot;Please enter password for your account&quot;]
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

export default mongoose.model(&quot;User&quot;, userSchema);
</code></pre>
<p>And I have written unit test like this.</p>
<pre><code>describe(&quot;User Model&quot;, () =&gt; {
  it(&quot;should throw validation error for required fields&quot;, async () =&gt; {
    const user = new User();

    try {
      await user.validate();
    } catch (err) {
      expect(err.errors.name).toBeDefined();
      expect(err.errors.email).toBeDefined();
      expect(err.errors.password).toBeDefined();
    }
  });

  it(&quot;should create a new user&quot;, async () =&gt; {
    const user = new User({
      name: &quot;Test&quot;,
      email: &quot;test@gmail.com&quot;,
      password: &quot;123456&quot;,
    });

    expect(user).toHaveProperty(&quot;_id&quot;);
  });
});
</code></pre>
<p>Please let me know is this correct way to unit test it? Thank You!</p>
",https://stackoverflow.com/questions/74411941/should-we-need-to-mock-mongoose-validate-method-while-unit-testing,"['javascript', 'node.js', 'unit-testing', 'jestjs']",20,False,0,0
Jest timeout when unit testing my express controller with async/await,"<p>So, using supertest and jest, when testing my simple controller I get a timeout message. I'm not sure if I am missing something from the config for jest set-up?</p>
<p>app.ts</p>
<pre><code>import express from 'express'
import bodyParser from 'body-parser'
import cors from 'cors'
import { UserRoute } from './components/user'

const App = () =&gt; {
  const app = express()
  app.use(bodyParser.json({ limit: &quot;50mb&quot; }))
  app.use(bodyParser.urlencoded({ limit: &quot;50mb&quot;, extended: true }))
  app.use(cors())

  app.use('/api/auth', UserRoute)

  return app
}

export default App
</code></pre>
<p>user.controller.ts</p>
<pre><code>export const SignUp = async (req: Request, res: Response, next: NextFunction) =&gt; {
  res.json({ message: &quot;pass!&quot; });
}
</code></pre>
<p>user.route.ts</p>
<pre><code>import { Router } from 'express'
import { SignUp } from './user.controller'

const router = Router()

router
  .route('/signup')
  .get(SignUp)

export default router
</code></pre>
<p>user.controller.spec.ts</p>
<pre><code>import App from '../../../app'
import supertest from 'supertest'

const request = supertest(App);

describe('Testing user controller', () =&gt; {

  it('testing /signup', async () =&gt; {
    const res = await request.get(&quot;/signup&quot;);
    expect(res.body.message).toBe(&quot;pass!&quot;);
  })
})
</code></pre>
<p>My jest timeout is 10000, not sure what is missing here for my controller not to return? Potentially to do with async/await?</p>
",https://stackoverflow.com/questions/71321971/jest-timeout-when-unit-testing-my-express-controller-with-async-await,"['javascript', 'typescript', 'express', 'jestjs', 'supertest']",407,False,0,0
How to mock Twilio using Jest and TypeScript for unit testing,"<p>I need your help to mock a twilio service which sends a message, using jest to mock the service
I have the next code:</p>
<pre><code>import { SQSEvent } from &quot;aws-lambda&quot;;
import { GetSecretValueResponse } from &quot;aws-sdk/clients/secretsmanager&quot;;

export async function sendSms(event: SQSEvent, data: GetSecretValueResponse) {
    const secrets = JSON.parse(data.SecretString);
    const accountSid = secrets.TWILIO_ACCOUNT_SID;
    const authToken = secrets.TWILIO_AUTH_TOKEN;
    const twilioNumber = secrets.TWILIO_PHONE_NUMBER;

    if (accountSid &amp;&amp; authToken &amp;&amp; twilioNumber) {
        //Create a Twilio Client
        const client = new Twilio(accountSid, authToken);
        //Loop into al records of the event, every record is every message sent from Sqs
        for (const record of event.Records) {
            const body = JSON.parse(record.body);
            const userNumber = &quot;+&quot; + body.number;
            //SendMessage function
            try {
                const message = client.messages.create({
                    from: twilioNumber,
                    to: userNumber,
                    body: body.message,
                });
                return message;
            } catch (error) {
                return `Failed to send sms message. Error Code: ${error.errorCode} / Error Message: ${error.errorMessage}`;
            }
        }
    } else {
        return &quot;You are missing one of the variables you need to send a message&quot;;
    }
}
</code></pre>
<p>The I call this function from my index:</p>
<pre><code>import { SQSEvent } from &quot;aws-lambda&quot;;
import { sendSms } from &quot;./services/sendSms/sendSms&quot;;
import { getSecret } from &quot;./services/obtainSecrets/getSecret&quot;;
import { SecretsManager } from &quot;aws-sdk&quot;;

export const lambdaHandler = async (event: SQSEvent) =&gt; {
    try {
        const obtainedSecret = await getSecret()
            .then((credentials: SecretsManager.GetSecretValueResponse) =&gt; {
                return credentials;
            })
            .catch(error =&gt; {
                return error;
            });
        const response = sendSms(event, obtainedSecret)
            .then(response =&gt; {
                return response;
            })
            .catch(error =&gt; {
                return error;
            });
        return {
            message: &quot;OK &quot; + obtainedSecret + response,
            code: 200,
        };
    } catch (error) {
        throw new Error(error);
    }
};
</code></pre>
<p>I have already make some tests, but them always makes a connection with Twilio api(requiring the real token, sid,etc), and I need to mock the Twilio service, so the function I call in my test.ts doesn't connects to internet.</p>
<pre><code>import { Twilio } from &quot;twilio&quot;;
import { MessageInstance } from &quot;twilio/lib/rest/api/v2010/account/message&quot;;
import { sendSms } from &quot;../../services/sendSms/sendSms&quot;;

//mock Twilio library and sendSms service
jest.mock(&quot;twilio&quot;);
jest.mock(&quot;../../services/sendSms/sendSms&quot;);

const smsMessageResultMock: Partial&lt;MessageInstance&gt; = {
    status: &quot;sent&quot;,
    sid: &quot;AC-lorem-ipsum&quot;,
    errorCode: undefined,
    errorMessage: undefined,
};
describe(&quot;SMS Service&quot;, () =&gt; {
    describe(&quot;Send Message&quot;, () =&gt; {
        it(&quot;Should fail&quot;, async () =&gt; {
            // update smsMessageResultMock to simulate a faled response
            const smsMessageMock = {
                ...smsMessageResultMock,
                status: &quot;failed&quot;,
                errorCode: 123,
                errorMessage: &quot;lorem-ipsum&quot;,
            };
            // simulated response of secret management
            let data = {
                ARN: &quot;arn:aws:secretsmanager:us-west-2:123456789012:secret:MyTestDatabaseSecret-a1b2c3&quot;,
                Name: &quot;MyTestDatabaseSecret&quot;,
                SecretString:
                    '{&quot;TWILIO_ACCOUNT_SID&quot;: &quot;ACTWILIO_ACCOUNT_SID&quot;,&quot;TWILIO_AUTH_TOKEN&quot;: &quot;TWILIO_AUTH_TOKEN&quot;,&quot;TWILIO_PHONE_NUMBER&quot;: &quot;TWILIO_PHONE_NUMBER&quot;}',
                VersionId: &quot;EXAMPLE1-90ab-cdef-fedc-ba987SECRET1&quot;,
                VersionStages: [&quot;AWSPREVIOUS&quot;],
            };
            // simulated response of SqsEvent
            let event = {
                Records: [
                    {
                        messageId: &quot;19dd0b57-b21e-4ac1-bd88-01bbb068cb78&quot;,
                        receiptHandle: &quot;MessageReceiptHandle&quot;,
                        body: '{&quot;message&quot;: &quot;Hello world&quot;,&quot;number&quot;: &quot;(506)88888888&quot;}',
                        attributes: {
                            ApproximateReceiveCount: &quot;1&quot;,
                            SentTimestamp: &quot;1523232000000&quot;,
                            SenderId: &quot;123456789012&quot;,
                            ApproximateFirstReceiveTimestamp: &quot;1523232000001&quot;,
                        },
                        messageAttributes: {},
                        md5OfBody: &quot;{{{md5_of_body}}}&quot;,
                        eventSource: &quot;aws:sqs&quot;,
                        eventSourceARN: &quot;arn:aws:sqs:us-east-1:123456789012:MyQueue&quot;,
                        awsRegion: &quot;us-east-1&quot;,
                    },
                ],
            };
            // simulate tokens for Twilio
            const accountSid = &quot;ACfjhdskjfhdsiuy876hfijhfiudsh&quot;;
            const authToken = &quot;fjfuewfiuewfbodfiudfgifasdsad&quot;;
            //create client with mocked Twilio
            const client = new Twilio(accountSid, authToken);

            //call messages.create of Twilio client, and give it the expected result created
            client.messages.create = jest
                .fn()
                .mockResolvedValue({ ...smsMessageMock });

            console.log(await sendSms(event, data));
            //expectes the function sendSms(event, data) to throw an error
            await expect(sendSms(event, data)).rejects.toThrowError(
                `Failed to send sms message. Error Code: ${smsMessageMock.errorCode} / Error Message: ${smsMessageMock.errorMessage}`
            );
        });
    });
});

</code></pre>
<p>(event and data are simulated responses of SqsEvent and GetSecretValueResponse)</p>
<p>The problem is that when I run the npm test it throws me an error of Twilio's authentication, an it is because I'm passing self created tokens.</p>
<pre><code> Expected substring: &quot;Failed to send sms message. Error Code: 123 / Error Message: lorem-ipsum&quot;                                             
    Received message:   &quot;Authentication Error - invalid username&quot;                                                                              
                                                                                                                                               
          at success (node_modules/twilio/lib/base/Version.js:135:15)                                                                          
          at Promise_then_fulfilled (node_modules/q/q.js:766:44)                                                                               
          at Promise_done_fulfilled (node_modules/q/q.js:835:31)                                                                               
          at Fulfilled_dispatch [as dispatch] (node_modules/q/q.js:1229:9)
          at Pending_become_eachMessage_task (node_modules/q/q.js:1369:30)
          at RawTask.Object.&lt;anonymous&gt;.RawTask.call (node_modules/asap/asap.js:40:19)
          at flush (node_modules/asap/raw.js:50:29)
</code></pre>
<p>So what I suppose is that the test is connecting to internet and calling Twilio's api.</p>
<p>I appreciate if you could help me.</p>
",https://stackoverflow.com/questions/73241141/how-to-mock-twilio-using-jest-and-typescript-for-unit-testing,"['javascript', 'typescript', 'unit-testing', 'jestjs', 'twilio']",680,True,0,1
Is Android unit testing on a physical device actually a thing?,"<p>Firebase has physical devices for testing: <a href=""https://firebase.google.com/docs/test-lab/android/available-testing-devices"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/test-lab/android/available-testing-devices</a> however it's a little expensive.</p>
<p>I was wondering if testing things on a physical Android device is a real thing and if there are frameworks for that. I know that there are unit tests that are mocked and run on the computer, but some things like the Android Media Codec Decoder can only be tested on the device</p>
",https://stackoverflow.com/questions/73173155/is-android-unit-testing-on-a-physical-device-actually-a-thing,"['android', 'unit-testing', 'testing']",70,False,0,1
Unit testing for python function-using post requests and get requests,"<p>I am trying to test the below function using unit test mocks but i am not able to do it since the return type from request get/post is of type &lt;class 'requests.models.Response'&gt;. please let me know how to mock this and unit test this below function:</p>
<pre class=""lang-py prettyprint-override""><code>def response_check(base_url, headers, schedule_name, response):
    &quot;&quot;&quot;
    Function to get response from dataform API and check the job status
    &quot;&quot;&quot;
    run_url = base_url + &quot;/&quot; + response.json()[&quot;id&quot;]
    query_response = requests.get(run_url, headers=headers)
    while query_response.json()[&quot;status&quot;] == &quot;RUNNING&quot;:
        time.sleep(10)
        print(&quot;Dataform job running&quot;)
        query_response = requests.get(run_url, headers=headers)
        if query_response.json()[&quot;status&quot;] in [&quot;FAILED&quot;, &quot;CANCELLED&quot;, &quot;TIMED_OUT&quot;]:
            raise AirflowException(
                f'Dataform task {schedule_name} has been {response.json()[&quot;status&quot;]} for reason {response.json()[&quot;runLogUrl&quot;]}'
            )
        print(query_response.json())
    return &quot;Dataform job finished&quot;
</code></pre>
<p>I need to check for different response status but i am not able to mock the return type of it</p>
",https://stackoverflow.com/questions/72058196/unit-testing-for-python-function-using-post-requests-and-get-requests,"['python', 'unit-testing', 'python-unittest.mock']",661,False,0,1
React Unit Testing: TypeError: Cannot read properties of null (reading &#39;navigate&#39;),"<p>I'm doing unit testing in react for function with querySelector and select property of querySelector with logout as following. (oj-gbu-app-shell) is company internal html tag library.</p>
<pre><code>  async nextState(): Promise&lt;UserSessionState&gt; {
    const shell: any = document.querySelector('oj-gbu-app-shell');
    shell.navigate([{ path: 'logout' }]);
    UserSessionFacade.setUserSessionExpired(!this.isCancelledState());
    return new UserSessionActiveState(this.getConfig());
  }
</code></pre>
<p>When I'm doing unit testing as following code.</p>
<pre><code>  it('Should transit to Active State', async () =&gt; {
    testCase = new SessionExpiredState(testConfig, true);
    const nextState: UserSessionState = await testCase.nextState();
    expect(nextState.constructor.name).to.be.eq('UserSessionActiveState');
    expect(sessionState).to.be.false;
  });
</code></pre>
<p>It always return me error</p>
<pre><code> TypeError: Cannot read properties of null (reading 'navigate')
</code></pre>
",https://stackoverflow.com/questions/72554321/react-unit-testing-typeerror-cannot-read-properties-of-null-reading-navigate,"['reactjs', 'typescript', 'unit-testing', 'jestjs', 'preact']",990,False,0,0
Python unit testing issue with mock patch dict os env variable,"<pre><code>@mock.patch.dict(os.environ, {&quot;CONTAINER&quot;: &quot;TrUe&quot;}, clear=True)
def test_use_container_true(self):
    &quot;&quot;&quot;
    Test the env var for if a containers should be used or not.
    &quot;&quot;&quot;
    self.assertEqual(a.__container__, True, &quot;not returning python bool True&quot;)

@mock.patch.dict(os.environ, {&quot;CONTAINER&quot;: &quot;fAlSE&quot;}, clear=True)
def test_use_container_false(self):
    &quot;&quot;&quot;
    Test the env var for if a containers should be used or not.
    &quot;&quot;&quot;
    self.assertEqual(a.__container__, False, &quot;not returning python bool False&quot;)
</code></pre>
<p>Here is the code it is testing:</p>
<pre><code>#!/usr/bin/env python3

env_container = os.getenv('CONTAINER')
if env_container is None:
    __container__ = False
else:
    env_container = env_container.lower()
    if env_container == 'true':
        __container__ = True
    else:
        __container__ = False
</code></pre>
<p>I get this error:</p>
<pre><code>F......
======================================================================
FAIL: test_use_container_false (test_amadla.TestGlobalVars)
Test the env var for if a containers should be used or not.
----------------------------------------------------------------------
Traceback (most recent call last):
  File &quot;/usr/lib/python3.9/unittest/mock.py&quot;, line 1768, in _inner
    return f(*args, **kw)
  File &quot;/home/user/Projects/SiteNetSoft/Amadla/AmadlaToolServerImageBuilder/test_amadla.py&quot;, line 57, in test_use_container_false
    self.assertEqual(a.__container__, False, &quot;not returning python bool False&quot;)
AssertionError: True != False : not returning python bool False

----------------------------------------------------------------------
Ran 10 tests in 0.002s

FAILED (failures=1)
</code></pre>
<p>It seems it keeps the value <code>True</code>.</p>
<p>Is it taking the value from mock as it is supposed to do?</p>
",https://stackoverflow.com/questions/73709107/python-unit-testing-issue-with-mock-patch-dict-os-env-variable,"['python', 'python-3.x', 'unit-testing', 'python-unittest']",188,False,0,0
How to reset firestore unit testing my Cloud Functions with jest,"<p>I followed the Cloud Functions recommendation and created my unit testing in online mode, everything makes sense to me, but I am getting inconsistency when I am debugging. I just trying to reset the firestore state by resetting and seeding the database.</p>
<p>When I run my test suite separately, they work perfectly; if I run all the test suites together appear all the errors, I am pretty sure that this is related to the beforeEach hooks but idk how to fix them.</p>
<p>I have 3 test suites, I will share with you 1 of them and the function responsible of the reset of the firestore.</p>
<pre class=""lang-js prettyprint-override""><code>// eslint-disable-next-line spaced-comment
    /// &lt;reference types=&quot;jest&quot; /&gt;

    import { cleanup, getDb, initializeFirebase, makeChange, resetDb, wrap } from './util';
    initializeFirebase();

    import { streamerIsOffline, streamerIsOnline } from './__fixtures__/onStreamerUpdateSnaps';
    import { getScheduler, SchedulerClientWrapper } from './../utils/SchedulerClientWrapper';
    import onStreamerUpdate from '../onStreamerUpdate';

    const db = getDb();

    jest.mock('./../utils/SchedulerClientWrapper');

    const mockedGetScheduler = jest.mocked(getScheduler, true);

    const wrapped = wrap(onStreamerUpdate);

    const schedulerClientWrapper = new SchedulerClientWrapper();
    const mockedPause: jest.Mock = jest.fn();
    const mockedResume: jest.Mock = jest.fn();
    const mockedJobIsEnabled: jest.Mock = jest.fn();


    schedulerClientWrapper.pause = mockedPause;
    schedulerClientWrapper.resume = mockedResume;
    schedulerClientWrapper.jobIsEnabled = mockedJobIsEnabled;

    describe('onStreamerUpdate', () =&gt; {
      beforeEach(
          async () =&gt; {
            await resetDb(); //I am resetting firestore here
            mockedGetScheduler.mockClear();
            jest.resetAllMocks();
          });

      it('should resume the scheduledJob when the first streamer becomes online',
          async () =&gt; {
            await updateStreamerStatus('64522496', true); //I am preparing the setup here

            const beforeSnap = streamerIsOffline;
            const afterSnap = streamerIsOnline;

            const change = makeChange(beforeSnap, afterSnap);

            mockedGetScheduler.mockReturnValue(schedulerClientWrapper);

            mockedJobIsEnabled.mockResolvedValue(false);

            await wrapped(change);

            expect(mockedJobIsEnabled).toBeCalled();
            expect(mockedResume).toBeCalled();
            expect(mockedPause).not.toBeCalled();
          });
          
      afterAll(() =&gt; {
        cleanup();
      });
      
    });

    const updateStreamerStatus = async (streamerId: string, isOnline: boolean) =&gt; {
      const stremersRef = db.collection('streamers');

      const query = stremersRef.where('broadcasterId', '==', streamerId);
      const querySnapshot = await query.get();
      console.log('streamers', (await stremersRef.get()).docs.map((doc) =&gt; doc.data())); //I am debugging here
      const streamerDocId = querySnapshot.docs[0].id;
      await stremersRef.doc(streamerDocId).update({ isOnline });
    };
</code></pre>
<p>And you can find the functions that wipe and seed firestore below:</p>
<pre class=""lang-js prettyprint-override""><code>import firebaseFunctionsTest from 'firebase-functions-test';
import { getApp, getApps, initializeApp, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore';

const projectId = 'latamqchallengetest';

export const { wrap, cleanup, firestore: firestoreTestData, makeChange } = firebaseFunctionsTest({
  databaseURL: `https://${projectId}.firebaseio.com`,
  storageBucket: `${projectId}.appspot.com`,
  projectId: projectId,
}, './../google-credentials/latamqchallengetest-firebase-adminsdk.json');

export const initializeFirebase = () =&gt; {
  if (getApps().length &lt;= 0) {
    initializeApp({
      credential: cert('./../google-credentials/latamqchallengetest-firebase-adminsdk.json'),
    });
  }
  return getApp();
};

export const getDb = () =&gt; {
  initializeFirebase();
  const db = getFirestore();
  return db;
};

export const wipeDb = async () =&gt; {
  const db = getDb();
  const collections = await db.listCollections();
  const deletePromises = collections.map((collectionRef) =&gt;
    db.recursiveDelete(collectionRef));

  Promise.all([...deletePromises]);
};

export const seed = async () =&gt; {
  const db = getDb();
  await db.collection('streamers').add({
    broadcasterId: '64522496',
    broadcasterName: 'ITonyl',
    color: '1565C0',
    description: 'Sr. Truchita',
    isOnline: false,
    puuid: 'kRQyIDe5TfLhWtn8jXgo_4Zjlfg4rPypXWiPCXrkTMUsiQT3TYVCkVO6Au3QTdd4x-13CbluPA53dg',
    summonerId: '9bnJOmLXDjX-sgPjn4ZN1_-f6m4Ojd2OWlNBzrdH0Xk2xw',
  });
  await db.collection('streamers').add({
    broadcasterId: '176444069',
    broadcasterName: 'Onokenn',
    color: '424242',
    description: 'El LVP Player',
    isOnline: false,
    puuid: 'Gbfj8FyB6OZewfXgAwvLGpkayA6xyevFfEW7UZdrzA6saKVTyntP4HxhBQFd_EIGa_P1xC9eVdy8sQ',
    summonerId: 'pPWUsvk_67FuF7ky1waWDM_gho-3NYP4enWTtte6deR3CjxOGoCfoIjjNw',
  });
};

export const resetDb = async () =&gt; {
  await wipeDb();
  await seed();
};
</code></pre>
<p>Sometimes I find that firestore has 4 records, other times it has 0 records, 2 records and so on .. I don't know why I await the promises before each test.</p>
<p>I expect to keep the same state before each test, can you help me please?</p>
",https://stackoverflow.com/questions/73779342/how-to-reset-firestore-unit-testing-my-cloud-functions-with-jest,"['unit-testing', 'google-cloud-firestore', 'jestjs']",213,True,0,1
How to resolve console error unhandled promise rejection when unit testing?,"<p>I have a method that handles error codes:</p>
<pre><code>handleSignatureAppErrorCodes(code) {
    if (code === 10) {
      return this.handleError({
        message: 'Configuration error, contact administrator',
      });
    } else if (code === 11) {
      return this.handleError({ message: '
Certificate not available' });
    } else if (code === 20) {
      return this.handleError({ message: 'Wrong PIN, try again' });
    } else if (code === 21) {
      return this.handleError({ message: 'Key not found' });
    } else if (code === 22) {
      return this.handleError({ message: 'Certificate not found' });
    } else if (code === 23) {
      return this.handleError({ message: 'Unable to catch the key' });
    } else if (code === 99) {
      return this.handleError({
        message: 'Unknown error, contact administrator',
      });
    }
  }
 
</code></pre>
<p>handleError method:</p>
<pre><code> private handleError(error: any): Promise&lt;any&gt; {
    return Promise.reject(error.message || error);
  }
</code></pre>
<p>I am writing unit tests in Jest, and this is how I covered each if statement (example is just for one if):</p>
<pre><code>it('handleSignatureAppErrorCode 22', () =&gt; {
    const spy = jest.spyOn(service, 'handleSignatureAppErrorCodes');
    service.handleSignatureAppErrorCodes(22);
    expect(spy).toHaveBeenCalled();
  });
</code></pre>
<p>Tests pass, but I have a console error that I don't understand how to solve:</p>
<pre><code>console.error
    Unhandled Promise rejection: Certificate not found ; Zone: ProxyZone ; Task: null ; Value: Certificate not found undefined
</code></pre>
<p>I have tried using mockRejectedValue method, like this, but I would get error pointing to &quot;new Error&quot; without any message.</p>
<pre><code>it('handleSignatureAppErrorCode 22', () =&gt; {
        const spy = jest.spyOn(service, 'handleSignatureAppErrorCodes').mockRejectedValue(new Error('Certificate not found'));
        service.handleSignatureAppErrorCodes(22);
        expect(spy).toHaveBeenCalled();
      });
</code></pre>
<p>Was looking here:
<a href=""https://stackoverflow.com/questions/46042613/how-to-test-the-type-of-a-thrown-exception-in-jest"">How to test the type of a thrown exception in Jest</a>,
<a href=""https://www.guidefari.com/jest-unhandled-promise-rejection/"" rel=""nofollow noreferrer"">https://www.guidefari.com/jest-unhandled-promise-rejection/</a>
and in other places with similar examples, but with no luck. Help and guidance appreciated!</p>
",https://stackoverflow.com/questions/72348838/how-to-resolve-console-error-unhandled-promise-rejection-when-unit-testing,"['angular', 'unit-testing', 'jestjs']",2748,True,0,1
Problem with thor unit testing on boring generators open source project,"<p><a href=""https://github.com/abhaynikam/boring_generators/blob/main/test/generators/devise_install_generator_test.rb"" rel=""nofollow noreferrer"">https://github.com/abhaynikam/boring_generators/blob/main/test/generators/devise_install_generator_test.rb</a></p>
<p><a href=""https://github.com/abhaynikam/boring_generators/blob/main/lib/generators/boring/devise/install/install_generator.rb"" rel=""nofollow noreferrer"">https://github.com/abhaynikam/boring_generators/blob/main/lib/generators/boring/devise/install/install_generator.rb</a></p>
<p>I am trying to get the testing to work for the devise gem on an open source project called boring_generators.  I have tried using byebug in the middle of the devise test and I get the path of the temp file that the test is using and rails is installed but the devise gem is not.  The testing fails on the Assert_gem method and also there is not config/initializers/devise.rb. However when you run this gem from rails without testing it, it works fine.  The gem itself is not broken but the testing is broken.</p>
",https://stackoverflow.com/questions/74225625/problem-with-thor-unit-testing-on-boring-generators-open-source-project,"['ruby-on-rails', 'ruby', 'devise', 'minitest', 'thor']",23,False,0,0
Django Rest API Unit Testing returning 401 Unauthorized for endpoint tests,"<p>I created some unit tests with basic asserts checking for status codes to get a few tests done and working. The endpoints themselves work flawlessly when I test them individually outside of the Django unit tests using <code>manage.py test test_file</code>
However, I am getting a 401 Unauthorized on all endpoints when I run the tests. I have tried writing in several auth methods to correct the issue but no matter what I try, a 401 is returned.</p>
<p>I have tried adding a force auth function, changing <code>TestCase</code> to <code>APITestCase</code>, and creating a superuser manually in the <code>setUp()</code> for each of my test cases.
All of the solutions I have found online for similar problems still yield the 401, unauthorized error.</p>
<p>Using:</p>
<p>Django 3.2.14</p>
<p>Python 3.10.4</p>
<p>I have also followed the Django Rest API documentation for test cases to the letter.
I get 401 errors all the way through.</p>
",https://stackoverflow.com/questions/73125896/django-rest-api-unit-testing-returning-401-unauthorized-for-endpoint-tests,"['python', 'django', 'api', 'rest', 'unit-testing']",381,False,0,1
Mock the result of cursor.execute() when using cx_Oracle for unit testing,"<p>I am writing unit tests for a python script. I am connecting to oracle DB with cx_Oracle and then running a select query. The script does different things base don whether the query returns any rows or not. My code is something like:</p>
<pre class=""lang-py prettyprint-override""><code>import cx_Oracle
.
.
.
def main():
.
.
.
  connection = cx_Oracle.connect(conn_string)
  cursor = connection.cursor()
  cursor.execute(query)
.
.
.
  headers = [x[0] for x in cursor.description]
  d_file = open(data_file, &quot;w&quot;)
        writer = csv.writer(d_file,delimiter='|',lineterminator=&quot;\n&quot;,quoting=csv.QUOTE_NONE)
        writer.writerow(headers)
        for row in cursor:
            writer.writerow(row)
</code></pre>
<p>I would like to patch the cursor.execute() method to return 0 rows.
I have tried the following by referring to a couple of answers here on SO. But I am getting the error:</p>
<pre><code>TypeError: Need a valid target to patch. You supplied: 'cx_Oracle'
</code></pre>
<p>My test is as follows:</p>
<pre class=""lang-py prettyprint-override""><code>  @mock.patch('cx_Oracle')
  def test_invalid_data(self,mock_cx_Oracle):
    print(&quot;Starting test : Test with data file having size &lt; 100000&quot;)
    mock_cursor = mock.MagicMock()
    mock_cursor.execute.return_value = []
    mock_cx_Oracle.connect.return_value.cursor.return_value.__enter__.return_value = mock_cursor

    with self.assertRaises(SystemExit) as cm:
       dump_intexdb_n_load.main()
    self.assertEqual(cm.exception.code, 1)

</code></pre>
<p>How can I mock cursor.execute()?</p>
",https://stackoverflow.com/questions/74093779/mock-the-result-of-cursor-execute-when-using-cx-oracle-for-unit-testing,"['python', 'unit-testing', 'mocking', 'cx-oracle']",298,True,0,1
Unit testing extended AEM core component - delegate pattern null reference exception,"<p>I am trying to write a unit test for an extended AEM core component - a 'button' with an extra field. I use the delegation pattern, and Lombok to reduce implementation code.</p>
<p>My unit test is failing when attempting to get the button ID (inherited from the button super-type) - with a null reference exception - because 'button' is null.</p>
<p><strong>Why would that be? Have I set up my unit test incorrectly? Or could it be that I have used the delegation pattern for the core component incorrectly?</strong></p>
<p>It is driving me crazy!</p>
<p>INTERFACE:</p>
<pre><code>@ProviderType
public interface ExtendedButton extends Button {
    String RESOURCE_TYPE = &quot;myproject/components/extendedbutton&quot;;

    String getVariant();
}
</code></pre>
<p>IMPL:</p>
<pre><code>@Model(
    adaptables = { Resource.class, SlingHttpServletRequest.class },
    adapters = { ExtendedButton.class, Button.class, ComponentExporter.class },
    resourceType = ExtendedButton.RESOURCE_TYPE,
    defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL
)
@Exporter(name = ExporterConstants.SLING_MODEL_EXPORTER_NAME, extensions = ExporterConstants.SLING_MODEL_EXTENSION)
public class ExtendedButtonImpl implements ExtendedButton {
    @Delegate
    @Self
    @Via(type = ResourceSuperType.class)
    private Button button;

    @ValueMapValue
    @Getter
    private String variant;

    // EXAMPLE
    // without lombok, the getter for button ID would be;
    public String getId() {
        return (null != button) ? button.getId() : null;
    }
}
</code></pre>
<p>UNIT TEST CODE:</p>
<pre><code>@ExtendWith(AemContextExtension.class)
class ExtendedButtonModelTest {
    private final AemContext context = new AemContextBuilder()
            .plugin(CORE_COMPONENTS)
            .build();

    private ExtendedButton model;

    @BeforeEach
    public void setup() {
        context.create().resource(&quot;/apps/myproject/components/extendedbutton&quot;,
                PROPERTY_RESOURCE_SUPER_TYPE, &quot;core/wcm/components/button/v2/button&quot;);

        Page page = context.create().page(&quot;/content/test-page&quot;);

        context.currentResource(context.create().resource(page, &quot;extendedbutton&quot;,
                PROPERTY_RESOURCE_TYPE, ExtendedButton.RESOURCE_TYPE,
                JCR_TITLE, &quot;button text&quot;,

                &quot;variant&quot;, &quot;light&quot;,

                &quot;id&quot;, &quot;button id&quot;,
                &quot;linkURL&quot;, &quot;https://google.com&quot;,
                &quot;linkTarget&quot;, &quot;_blank&quot;,
                &quot;accessibilityLabel&quot;, &quot;button label&quot;
        ));

        model = context.request().adaptTo(ExtendedButton.class);
    }

    // UNIT TEST SUCCEEDS
    @Test
    void testGetVariant() {
        String val = model.getVariant();
        assertNotNull(val);
        assertEquals(&quot;light&quot;, val);
    }

    // UNIT TEST THROWS NULL POINTER EXCEPTION ON MODEL
    @Test
    void testGetButtonId() {
        String val = model.getId();
        assertNotNull(val);
        assertEquals(&quot;button-id&quot;, val);
    }
}
</code></pre>
",https://stackoverflow.com/questions/73487140/unit-testing-extended-aem-core-component-delegate-pattern-null-reference-excep,"['java', 'unit-testing', 'aem']",435,True,0,1
how to add client proxy as provider in my unit testing,"<p>so I'm trying to test a controller and that controller using ClientProxy as injectable , when I'm running my test it will give the error</p>
<pre><code>   Nest can't resolve dependencies of the TransactionsController (TransactionsService, ReconciliationsService, ?). Please make sure that the argument micro at index [2] is available in the RootTestModule context.
</code></pre>
<p>the controller</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>@Controller()
export class TransactionsController {
  constructor(
    private readonly transactionsService: TransactionsService,
    private readonly reconciliationsService: ReconciliationsService,
    @Inject('micro') private micro: ClientProxy,
  ) { }</code></pre>
</div>
</div>
</p>
<p>in the test</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>  const module: TestingModule = await Test.createTestingModule({
            controllers: [TransactionsController],
            providers: [TransactionsService, {
                provide: TransactionsService, useValue: mockTransactionS
            }, ReconciliationsService, {
                    provide: ReconciliationsService, useValue: mockReconS
                }, ]
        }).compile()</code></pre>
</div>
</div>
</p>
<p>any idea how I can add the ClientProxy or mock it here , any help will be much appreciate it</p>
",https://stackoverflow.com/questions/73275108/how-to-add-client-proxy-as-provider-in-my-unit-testing,"['unit-testing', 'jestjs', 'nestjs']",286,False,0,1
Unit testing in Embedded C - Testing modules with references to SDK,"<p>I create a project for a microcontroller by programming it in C language. Due to its specificity (a microcontroller with a built-in BLE core), I have to use the SDK and a specific project template. How can I test my modules when they have numerous references to other files (modules) in the SDK? (References are needed to use functions to, for example, send data via BLE) Do I have to somehow mock each of the SDK functions? I am using Unity test framework.
Module example:</p>
<h2>my_module.c</h2>
<pre><code>#include &quot;sdk_module_1.h&quot;
#include &quot;my_module.h&quot;

void init_hardware(void)
{
   //function code
}
bool send_data(int data)
{ 
   //prepare data eq.
   data++ 
   //send data using SDK function (sdk_module_1.h)
   return send_data(data);
}
</code></pre>
<h2>my_module.h</h2>
<pre><code>  void init_hardware(void)
  void send_data(int data)
</code></pre>
<h2>my_module_test.c</h2>
<pre><code>  #include &quot;my_module.h&quot;
  #include  &quot;//unity files&quot; 
  TEST_SETUP(Test)
  {   

  }
  TEST_TEAR_DOWN(Test)
  {

  }
  TEST(Test, First_test)
  {
     TEST_ASSERT_EQUAL(send_data(5),true);
  }
</code></pre>
<p>When I try to test my module, I have a problem with referencing SDK modules and their functions. How can I create tests for such software? Should I change the way my modules are written?</p>
",https://stackoverflow.com/questions/73262455/unit-testing-in-embedded-c-testing-modules-with-references-to-sdk,"['c', 'unit-testing', 'embedded', 'tdd']",548,False,0,2
Nestjs - Unit testing for a controller that is inherited from CrudController,"<p>I am doing a unit testing script for a controller file for an API called promotions.controller.ts. However, I am not sure why my controller file is not instantiating the service file that I mock using jest in its constructor and throwing the error of:</p>
<p><strong>TypeError: Cannot read property 'findOne' of undefined.</strong></p>
<p>findOne is one of the function that exist in my promotions.service.ts and it is also extended from a CrudService which is a parent class of this service.</p>
<p>I have already tried to mock a class and spyOn to mock the PromotionService but it is still not working.</p>
<p>This is the code for <strong>promotions.controller.spec.ts</strong>:</p>
<pre><code>import { PromotionsService } from &quot;../promotions.service&quot;;
import {PromotionsController} from &quot;../promotions.controller&quot;
import { Test, TestingModule } from &quot;@nestjs/testing&quot;
import {OrganizationsService} from &quot;../../organizations/organizations.service&quot;

describe('PromotionsController', () =&gt; {
    let promotionsController: PromotionsController;
    let promotionsService: PromotionsService;

    jest.mock(&quot;../promotions.service&quot;);

    const mockOrganizationsService = {
    }

    const mockPromotionsService = {
        
    };
    

    beforeEach(async () =&gt; {
      const moduleRef = await Test.createTestingModule({
          controllers: [PromotionsController],
          providers:[PromotionsService,OrganizationsService]
        }).overrideProvider(PromotionsService).useValue(mockPromotionsService)
          .overrideProvider(OrganizationsService).useValue(mockOrganizationsService)
          .compile();
  
      promotionsService = moduleRef.get&lt;PromotionsService&gt;(PromotionsService);
      promotionsController = moduleRef.get&lt;PromotionsController&gt;(PromotionsController);

      const promotions = await promotionsController.performDelete({id:'1234'});
    });
  
    describe('promotionsController', () =&gt; {

      it('controller should be defined', async () =&gt; {
        expect(promotionsController).toBeDefined();
      });

      it('service should be defined', async () =&gt; {
        expect(promotionsService).toBeDefined();
      });

      it('promotionsController should be calling performDelete', async () =&gt; {
        expect(promotionsController.performDelete({id:'1234'})).not.toEqual(null);
        expect(promotionsService.find).toHaveBeenCalled();
      })

    });
  });

</code></pre>
<p>This is the code at my <strong>promotions.controller.ts</strong>:</p>
<pre><code>import { Controller } from '@nestjs/common';
import {ApiBearerAuth} from &quot;@nestjs/swagger&quot;;
import {Crud} from &quot;../ms-common/utils/crud/crud.decorator&quot;;
import {Promotion} from &quot;./promotions.model&quot;;
import {PromotionsDto} from &quot;./dto/promotions.dto&quot;;
import {CrudController} from &quot;../ms-common/utils/crud/crud.controller&quot;;
import {PromotionsService} from &quot;./promotions.service&quot;;
import {OrganizationsService} from &quot;../organizations/organizations.service&quot;;

@ApiBearerAuth()
@Crud({
  model: Promotion,
  routes: {
    create: {dto: PromotionsDto},
    update: {dto: PromotionsDto},
  },
})

@Controller('promotions')
export class PromotionsController extends CrudController {
  constructor(public model: PromotionsService, private organization: OrganizationsService) {
    super(model);
  }

  async performDelete(id) {
    const instance = await this.model.findOne({id});
    await this.organization.sbQueue({
      type: &quot;promotion&quot;,
      ids: [id],
      delete: true,
      organization: instance.organization,
    });
    return super.performDelete(id);
  }
}

</code></pre>
<p>Anyone knows how should I resolve this issue?</p>
",https://stackoverflow.com/questions/73122762/nestjs-unit-testing-for-a-controller-that-is-inherited-from-crudcontroller,"['typescript', 'unit-testing', 'nestjs']",198,True,0,1
NestJs: Need help creating unit testing test case for database calls,"<p>I want to unit test the below function that uses Prisma and is in my service.</p>
<p>How would I go about writing the unit test case for it in the spec file?</p>
<p>Do I have to test all the prisma database(findUnique,deleteMany,createMany) calls and all the functionality within the function including the errors thrown?</p>
<pre><code>async rules(options: {
    data: UserAssociateRulesDto;
  }): Promise&lt;FetchRule&gt; {

    try {

      // Check if rule present
      const role = await this.db.rules.findUnique({
        where: {
          rule_name: options.data['rule_name'],
        },
      });

      if (!rule) {
        throw new BadRequestException('No such user role exists');
      }

      // Map Permissions to Rule
      const rulePermissionAssociations = [];

      for (const permission of options.data['permissions']) {
        rulePermissionAssociations.push({
          rule_id: rule['id'],
          permission_id: permission['permission_id'],
        });

      }

      // Delete all records 
      await this.db.rulepermission_association.deleteMany({
        where: {
          rule_id: rule['id'],
        },
      });

      // Add rule-permissions mapping
      await this.db.rule_association.createMany({
        data: rulePermissionAssociations,
      });

      return this.db.rules.findUnique();

    } catch (error) {
      throw new HttpException(error.message, error.status);
    }
  }
</code></pre>
",https://stackoverflow.com/questions/74237974/nestjs-need-help-creating-unit-testing-test-case-for-database-calls,"['javascript', 'node.js', 'unit-testing', 'nestjs', 'prisma']",125,False,0,0
Rest end point unit testing using JWT token validation in Micronaut,"<p>Using micronaut to create rest end-point which is protected by using micronaut-jwt security</p>
<pre><code>        @Post
        @IRequirement(resourceName = ClaimType.TAG_PRODUCT, permission = {ClaimValue.TAG_OWNER,ClaimValue.TAG_CREATOR,ClaimValue.TAG_MAINTAINER })
        Mono&lt;MutableHttpResponse&lt;?&gt;&gt; post(@Body @Valid ProductModel model){
        LOG.info(String.format(&quot;Creating new product&quot;));
        return _iServiceBus.&lt;ProductModel, Mono&lt;ProductModel&gt;&gt;send(model).flatMap(item -&gt; {
                    if (item != null) {
                        try {
                            return Mono.just(HttpResponse.created(item, new URI(String.format(&quot;/%s&quot;, item.id()))));
                        } catch (URISyntaxException e) {
                            return Mono.error(new GlobalException(e));
                        }
                    } else
                        return Mono.just(HttpResponse.serverError());
                }
        ).onErrorMap(throwable -&gt; {
            throw new GlobalException(throwable);
        });}
</code></pre>
<p>Security model</p>
<pre><code>@Inherited
public @interface IRequirement {
    String resourceName();
    String[] permission();
}
</code></pre>
<p>Security rules</p>
<pre><code>@Singleton
public class AuthorityHandler implements SecurityRule {
    @Override
    public Publisher&lt;SecurityRuleResult&gt; check(HttpRequest&lt;?&gt; request, @Nullable RouteMatch&lt;?&gt; routeMatch, @Nullable Authentication authentication) {
        if (routeMatch instanceof MethodBasedRouteMatch methodBasedRouteMatch) {
            if (methodBasedRouteMatch.hasAnnotation(IRequirement.class)) {
                AnnotationValue&lt;IRequirement&gt; requiredPermissionAnnotation = methodBasedRouteMatch.getAnnotation(IRequirement.class);
                Optional&lt;String&gt; resourceIdName = requiredPermissionAnnotation.stringValue( &quot;resourceName&quot;);
                String[] permissions = requiredPermissionAnnotation.stringValues(&quot;permission&quot;);
                if (permissions.length &gt; 0 &amp;&amp; resourceIdName.isPresent() &amp;&amp; authentication != null) {
                    Map&lt;String, Object&gt; identityClaims = authentication.getAttributes();
                    if (Arrays.stream(permissions).anyMatch(element -&gt;  identityClaims.containsValue(element)))
                        return Mono.just(SecurityRuleResult.ALLOWED);
                    else
                        return Mono.just(SecurityRuleResult.REJECTED);
                }
            }
        }
        return Mono.just(SecurityRuleResult.UNKNOWN);
    }
}
</code></pre>
<p>The above end-point is protected as claims <code>owner</code>,<code>creator</code> and <code>maintainer</code></p>
<p>I am using Identity server 4 (<a href=""https://github.com/IdentityServer/IdentityServer4"" rel=""nofollow noreferrer"">https://github.com/IdentityServer/IdentityServer4</a>) to manage the identity and when the user logins in it contain the following claims in the access token</p>
<pre><code>{
  &quot;nbf&quot;: 1641548846,
  &quot;exp&quot;: 1641549046,
  &quot;iss&quot;: &quot;https://localhost:5001&quot;,
  &quot;client_id&quot;: &quot;Falcon_Identity_Server&quot;,
  &quot;sub&quot;: &quot;673533cc-7c0b-40f3-80ac-222696df385d&quot;,
  &quot;auth_time&quot;: 1641548840,
  &quot;idp&quot;: &quot;local&quot;,
  &quot;http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier&quot;: &quot;673533cc-7c0b-40f3-80ac-222696df385d&quot;,
  &quot;http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name&quot;: &quot;admin@local.com&quot;,
  &quot;http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress&quot;: &quot;admin@local.com&quot;,
  &quot;AspNet.Identity.SecurityStamp&quot;: &quot;812aa4cb-b9f1-48ac-9e39-1f0dceb6f1c4&quot;,
  &quot;identityserver&quot;: &quot;owner&quot;,
  &quot;fb_product&quot;: &quot;owner&quot;,
  &quot;fb_order&quot;: &quot;owner&quot;,
  &quot;fb_payment&quot;: &quot;owner&quot;,
  &quot;jti&quot;: &quot;179683F5CCA01EB925B45B1CA6379080&quot;,
  &quot;sid&quot;: &quot;F1D9F917D34178EDAF7A5FD24948F89D&quot;,
  &quot;iat&quot;: 1641548846,
  &quot;scope&quot;: [
    &quot;openid&quot;,
    &quot;profile&quot;,
    &quot;email&quot;
  ],
  &quot;amr&quot;: [
    &quot;pwd&quot;
  ]
}
</code></pre>
<p>The above end point is looking for those attributes</p>
<pre><code>&quot;identityserver&quot;: &quot;owner&quot;,
      &quot;fb_product&quot;: &quot;owner&quot;,
      &quot;fb_order&quot;: &quot;owner&quot;,
      &quot;fb_payment&quot;: &quot;owner&quot;,
</code></pre>
<p>For running an real application, it is working fine. I am trying to write the test case using micronaut httpclient. But not sure how can I test using micronaut test framework</p>
<p>Something I tried</p>
<pre><code>@Test
@DisplayName(&quot;Should create a JWT token&quot;)
void shouldCreateAJwtToken() {
    BearerAccessRefreshToken bearerAccessRefreshToken = null;
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(&quot;sherlock&quot;, &quot;password&quot;);
    HttpRequest request = HttpRequest.POST(&quot;/login&quot;, creds);
    HttpResponse&lt;BearerAccessRefreshToken&gt; rsp = client.toBlocking().exchange(request, BearerAccessRefreshToken.class);
    bearerAccessRefreshToken = rsp.body();

}
</code></pre>
<p>It creates a token but doesn't contain all the validation required for the above access token.</p>
<p>How do we do rest endpoint unit testing that is protected by JWT token in micronaut</p>
<p><strong>Authentication provider</strong></p>
<pre><code>@Singleton
@Requires(env = Environment.TEST)
public record AuthenticationProviderUserPasswordFixture() implements AuthenticationProvider {
    @Override
    public Publisher&lt;AuthenticationResponse&gt; authenticate(HttpRequest&lt;?&gt; httpRequest, AuthenticationRequest&lt;?, ?&gt; authenticationRequest) {
        return Flux.create(emitter -&gt; {
            if (authenticationRequest.getIdentity().equals(&quot;sherlock&quot;) &amp;&amp; authenticationRequest.getSecret().equals(&quot;password&quot;)) {
                emitter.next(AuthenticationResponse.success((String) authenticationRequest.getIdentity(), List.of(&quot;roles1&quot;, &quot;roles2&quot;)));
                emitter.complete();
            } else {
                emitter.error(AuthenticationResponse.exception());
            }
        }, FluxSink.OverflowStrategy.ERROR);
    }
}
</code></pre>
",https://stackoverflow.com/questions/70619463/rest-end-point-unit-testing-using-jwt-token-validation-in-micronaut,"['java', 'micronaut', 'micronaut-client', 'micronaut-rest']",585,False,0,1
Unit Testing: Should I verify after testing section in a method?,"<p>I have just started Unit Testing and I am a little bit confused regarding to the following issues. Could you help me please?</p>
<p>Here is the sample service method that I am testing:</p>
<pre><code>public CommandDTO update(UUID uuid, Request request) {

    // case 1
    if (uuid == null) {
        throw new EntityNotFoundException(&quot;Not found&quot;);
    }

    final Employee employee = employeeService.findByUuid(uuid);
    
    // case 2
    if (employee.getDepartmentUuid == null) {
        throw new EntityNotFoundException(&quot;Not found&quot;);
    }

    employeeRepository.saveAndFlush(employee);

    triggerService.onEmployeeUpdate(uuid);

    return CommandDTO.builder().uuid(employee.getUuid()).build();
}
</code></pre>
<p><strong>1.</strong> When I create a test method for testing case 1, should I just write a test for expecting <code>EntityNotFoundException</code>? I mean should I write verify lines after testing exception as shown below? Or should I just test until the part that I am testing? Because if I verify the rest, in that case I will repeat the same lines for all the other tests.</p>
<pre><code>@Test
public void test_exception_when_update() {
    UUID uuid = null;
    Request request = new Request();

    assertThrows(EntityNotFoundException.class, () -&gt; {
        employeeService.update(uuid, request);
    });

    /// ???
    verify(employeeService, never()).findByUuid(any());
    verify(employeeRepository, never()).saveAndFlush(any());
    verify(triggerService, never()).onEmployeeUpdate(any());
}
</code></pre>
<p><strong>2.</strong> For the above service method, I think I should write the test methods for the following scenarios:</p>
<ul>
<li><p><code>uuid == null</code> --&gt; throw exception</p>
</li>
<li><p><code>employee.getDepartmentUuid</code> --&gt; throw exception</p>
</li>
<li><p>there is no exception and the other 3 operations are ok and then return <code>CommandDTO</code>. Then I will make assertions.</p>
</li>
</ul>
<p>Is that true?</p>
",https://stackoverflow.com/questions/71508073/unit-testing-should-i-verify-after-testing-section-in-a-method,"['java', 'unit-testing', 'testing', 'junit', 'mockito']",55,False,0,1
"ALSA not found - github actions unit testing, setting env/envvars correctly","<p>I have the following yaml in my .github/workflows folder.</p>
<pre class=""lang-yaml prettyprint-override""><code>name: Run Python Tests
on:
  push:
    branches:
      - main

  pull_request:
    branches:
      - main

jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: [&quot;2.7&quot;, &quot;3.6&quot;, &quot;3.7&quot;, &quot;3.8&quot;, &quot;3.9&quot;]
    steps:
      - uses: actions/checkout@v3
      - name: Install Python ${{ matrix.python-version }}
        uses: actions/setup-python@v3
        with:
          python-version: ${{ matrix.python-version }}
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt
      - name: Run tests with unittest 
        run: python -m unittest test.py 
</code></pre>
<p>when I make a PR, it runs the tests... however they fail in github and not on my local machine.</p>
<p>the error is as follows:</p>
<pre class=""lang-py prettyprint-override""><code>0s
Run python -m unittest test.py
ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4732:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4732:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4732:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5220:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM default
ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
ALSA lib conf.c:4732:(_snd_config_evaluate) function snd_func_card_driver returned error: No such file or directory
ALSA lib confmisc.c:392:(snd_func_concat) error evaluating strings
ALSA lib conf.c:4732:(_snd_config_evaluate) function snd_func_concat returned error: No such file or directory
ALSA lib confmisc.c:1246:(snd_func_refer) error evaluating name
ALSA lib conf.c:4732:(_snd_config_evaluate) function snd_func_refer returned error: No such file or directory
ALSA lib conf.c:5220:(snd_config_expand) Evaluate error: No such file or directory
ALSA lib pcm.c:2642:(snd_pcm_open_noupdate) Unknown PCM default
Traceback (most recent call last):
  File &quot;/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/runpy.py&quot;, line 194, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File &quot;/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/runpy.py&quot;, line 87, in _run_code
    exec(code, run_globals)
  File &quot;/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/unittest/__main__.py&quot;, line 18, in &lt;module&gt;
    main(module=None)
  File &quot;/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/unittest/main.py&quot;, line 100, in __init__
    self.parseArgs(argv)
  File &quot;/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/unittest/main.py&quot;, line 147, in parseArgs
    self.createTests()
  File &quot;/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/unittest/main.py&quot;, line 158, in createTests
    self.test = self.testLoader.loadTestsFromNames(self.testNames,
  File &quot;/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/unittest/loader.py&quot;, line 220, in loadTestsFromNames
    suites = [self.loadTestsFromName(name, module) for name in names]
  File &quot;/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/unittest/loader.py&quot;, line 220, in &lt;listcomp&gt;
    suites = [self.loadTestsFromName(name, module) for name in names]
  File &quot;/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/unittest/loader.py&quot;, line 154, in loadTestsFromName
    module = __import__(module_name)
  File &quot;/home/runner/work/2dshooter/2dshooter/test.py&quot;, line 5, in &lt;module&gt;
    from test_func import *
  File &quot;/home/runner/work/2dshooter/2dshooter/test/test_func.py&quot;, line 2, in &lt;module&gt;
    from func import *
  File &quot;/home/runner/work/2dshooter/2dshooter/func.py&quot;, line 6, in &lt;module&gt;
    from values import *
  File &quot;/home/runner/work/2dshooter/2dshooter/values.py&quot;, line 10, in &lt;module&gt;
    pygame.mixer.init()
pygame.error: ALSA: Couldn't open audio device: No such file or directory
pygame 2.1.2 (SDL 2.0.16, Python 3.8.12)
Hello from the pygame community. https://www.pygame.org/contribute.html
VALUE INIT
Error: Process completed with exit code 1.

</code></pre>
<p>reading through that - it looks like the culprit is the audio driver not actually existing when we</p>
<pre class=""lang-yaml prettyprint-override""><code>    runs-on: ubuntu-latest
</code></pre>
<p>does not include the audio driver?</p>
<p>I have tried adding the following to the yaml file (directly below that runs-on)</p>
<pre class=""lang-yaml prettyprint-override""><code>
    env:
      SDL_AUDIODRIVER: 'ALSA'
</code></pre>
<p>that also did not work - and produces the same error.</p>
<p>so how Do I get the container in GitHub to have the correct audio driver?</p>
",https://stackoverflow.com/questions/72311056/alsa-not-found-github-actions-unit-testing-setting-env-envvars-correctly,"['python', 'unit-testing', 'github', 'pygame', 'github-actions']",164,True,0,1
Angular unit testing Error: Expected spy getDateFormat to have been called,"<p>I'm new to unit testing and hope someone help me.
I have a angular component called StudentComponent and it has following.</p>
<pre><code>    public getAllStudents(){    
        this.apollo.query({
            query: GETALL_STUDENTS,
        }).subscribe((result: any) =&gt; {
            this.students = result?.data?.getAllStudents;
            this.students.forEach(element =&gt; {
            element.Age = this.CalculateAge(element.DateOfBirth);
            element.DateOfBirthString = this.getDateFormat(element.DateOfBirth);
            });
        });
    }

    public CalculateAge(dateOfBirth: any): number {
        let age = 0;
        if (dateOfBirth) {
            var timeDiff = Math.abs(Date.now() - new Date(dateOfBirth).getTime());
            age = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
        }
        return age;
    }

    getDateFormat(date: Date): string{
        let dateString = &quot;&quot;
        if(date){
            dateString = formatDate(date, 'yyyy/MM/dd','en_US').toString();
        }
        return dateString;
    }
</code></pre>
<p>I wrote the test case like following</p>
<pre><code>    describe('getAllStudents', () =&gt; {
        it('makes expected calls', () =&gt; {
          spyOn(component, 'getDateFormat').and.callThrough();
          spyOn(component, 'CalculateAge').and.callThrough();
          spyOn(apollo, 'query').and.callThrough();
          component.getAllStudents();
          expect(apollo.query).toHaveBeenCalled();
          expect(component.getDateFormat).toHaveBeenCalled();
          expect(component.CalculateAge).toHaveBeenCalled();
  
        });
      });
</code></pre>
<p>this gave me an error. 'Expected spy getDateFormat to have been called.' Could anyone please guide me to resolve this?</p>
",https://stackoverflow.com/questions/72768656/angular-unit-testing-error-expected-spy-getdateformat-to-have-been-called,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",529,False,-1,1
Django Unit Testing - How to test all instances in a model?,"<p>I want to test all instances in a DB using Django.</p>
<p>I have a python script that populates the DB and I want to test every single instance if it pass the test.</p>
<p>I provide here a dummy <em>tests.py</em>:</p>
<pre><code>from django.test import TestCase
from app_core.models import Item
# Item model fields are: pk, first, second

class PairTestCase(TestCase):
    def setUp(self):
        # This script populates the DB creating several Item instances
        from app_core.init import init_items

    def test_pair_elems_different(self):
        &quot;&quot;&quot;First and second fields MUST be different inside the instance&quot;&quot;&quot;
        item = Item.objects.get(pk=1)
        self.assertNotEqual(item.first, item.second)
</code></pre>
<p>As you can see, I just tested a <em>single</em> instance.
Let's suppose the DB contains 1000 Item instances, what is the best way to test them all?</p>
<p>The only solution that pops up in my mind is using a simple FOR loop inside <em>test_pair_elems_different</em>, iterating all object and comparing each instance.</p>
<p>Is this approach correct in the context of unit testing best practices/principles?</p>
",https://stackoverflow.com/questions/74099916/django-unit-testing-how-to-test-all-instances-in-a-model,"['python', 'django', 'unit-testing']",118,False,0,2
How to write Jest unit testing for Socket in node js,"<p>I am trying to write the unit testing in JEST for the socket, test cases are passed but the code is not covered on codeCoverageReport I am not sure where I have gone wrong and jest is completely new as I am in a learning stage please help me.</p>
<p>This is node js simple code of socket</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 express = require(""express"");
const app = express();
items = [];

const server = app.listen(3000, () =&gt; {
  console.log(""This is listening to the port"");
});

//Web Sockets
const io = require(""socket.io"")(server, {
  cors: {
    origin: ""http://localhost:4200"",
    methods: [""GET"", ""POST""],
  },
});
io.on(""connection"", (socket) =&gt; {
  console.log(""a user connected"");

  socket.on(""message"", (message) =&gt; {
    console.log(message);
    io.emit(""message"", `${message}`);
  });

  socket.on(""disconnect"", () =&gt; {
    console.log(""a user disconnected!"");
  });
});
module.exports = io;</code></pre>
</div>
</div>
</p>
<p>This is the test file for the Socket</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 io = require('socket.io-client')
const io_server = require('../src/socket/index');

describe('basic socket.io example', () =&gt; {

  let socket;

  beforeEach(() =&gt; {
    // Setup
    socket = io.connect('http://localhost:3000');

    socket.on('connect', () =&gt; {
      console.log('connected')
    });

    socket.on('disconnect', () =&gt; {
      console.log('disconnected...');
    });
  });

  afterEach((done) =&gt; {
    // Cleanup
    if (socket.connected) {
      socket.disconnect();
    }
    socket.close();
    done();
  });

  it('should communicate', () =&gt; {
    // once connected, emit Hello World

    // console.log(socket)
    socket.emit('echo', 'Hello World');

    socket.once('echo', (message) =&gt; {
      // Check that the message matches
      expect(message).to.equal('Hello World');
    });

    socket.on('connection', (socket) =&gt; {
      expect(socket).to.not.be.null;
    });
  });

});</code></pre>
</div>
</div>
</p>
<p>Below is the screenshot of the code coverage</p>
<p><a href=""https://i.stack.imgur.com/0s5xW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0s5xW.png"" alt=""enter image description here"" /></a></p>
<p>When I run the test case it is showing it has passed</p>
<p><a href=""https://i.stack.imgur.com/jit7O.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/jit7O.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73795747/how-to-write-jest-unit-testing-for-socket-in-node-js,"['node.js', 'unit-testing', 'jestjs', 'socket.io', 'code-coverage']",62,False,0,1
How to write unit testing friendly code in ASP.NET Core 6.0?,"<p>I tried to find the unit testing-friendly best code practice in .NET development.</p>
<p>I'm assuming that it will be painful if I got to implement unit testing for an already developed project which is not planned to do unit testing when it was developed.</p>
<ul>
<li>What are things we need to keep in mind when we develop Web API or web applications?</li>
<li>What is the best unit testing-friendly architecture?</li>
<li>What are the principles which we need to follow. eg: Interface segregation in SOLID principles.</li>
</ul>
",https://stackoverflow.com/questions/74129069/how-to-write-unit-testing-friendly-code-in-asp-net-core-6-0,"['c#', '.net', 'performance', 'unit-testing']",51,True,0,1
Unit testing a NestJS controller that has a bunch of imports,"<p>I'm trying to unit test a NestJS health-check controller. The health module has a few imports (see code below).</p>
<p>I need to mock the <code>HttpModule</code> so that I can test the scenario where the <code>payments-service</code> <strong>is down</strong> and another scenario where the <code>payments-service</code> <strong>is up</strong>.</p>
<p>I'm struggling to achieve that.</p>
<p><strong>CODE</strong></p>
<p><em>health.module.ts</em></p>
<pre><code>import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { HealthController } from './health.controller';
import { HttpModule } from '@nestjs/axios';
import { AppConfigModule } from '@app-config/app-config.module';

@Module({
  imports: [TerminusModule, HttpModule, AppConfigModule],
  controllers: [HealthController],
})
export class HealthModule {}
</code></pre>
<p><em>health.controller.ts</em></p>
<pre><code>import { Controller, Get, InternalServerErrorException } from '@nestjs/common';
import { HealthCheck, HealthCheckService, HttpHealthIndicator } from '@nestjs/terminus';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import * as moment from 'moment';
import { AppConfigService } from '@app-config/app-config-service/app-config.service';
import { HealthCheckResult } from '@nestjs/terminus/dist/health-check/health-check-result.interface';

@ApiTags('health')
@Controller('health')
export class HealthController {
  static readonly HEALTH_CHECK_FREQ = 30; // in seconds
  private healthExpiry = moment();
  private isHealthy = true;
  private healthCheckResult: HealthCheckResult;

  constructor(
    private health: HealthCheckService,
    private http: HttpHealthIndicator,
    private configService: AppConfigService
  ) {
    this.check = this.check.bind(this);
  }

  @Get()
  @ApiOperation({ summary: 'Checks the status of the service' })
  @HealthCheck()
  async check(): Promise&lt;HealthCheckResult&gt; {
    const now = moment();
    if (this.healthExpiry.isBefore(now)) {
      console.info('Checking server health...');
      const paymentsHost = this.configService.env.rooster.paymentsService.host;

      try {
        this.healthCheckResult = await this.health.check([
          async () =&gt; await this.http.pingCheck('payments-service', `https://${paymentsHost}/health`),
        ]);

        if (this.healthCheckResult.status === 'ok') {
          this.isHealthy = true;
        } else {
          this.isHealthy = false;
        }
      } catch (err) {
        console.error(err);
        this.isHealthy = false;
      }

      this.healthExpiry = now.add(HealthController.HEALTH_CHECK_FREQ, 'seconds');
      console.info('server health:', this.isHealthy);
    }

    if (!this.isHealthy) {
      throw new InternalServerErrorException(this.healthCheckResult);
    }

    return this.healthCheckResult;
  }
}
</code></pre>
<p><em>health.controller.spec.ts</em></p>
<pre><code>import { Test, TestingModule } from '@nestjs/testing';
import { HealthController } from './health.controller';
import { ConfigModule } from '@nestjs/config';
import MockEnvConfig from '../../test/resources/MockEnvConfig';
import { AppConfigModule } from '@app-config/app-config.module';
import { TerminusModule } from '@nestjs/terminus';
import { HttpService } from '@nestjs/axios';
import { of } from 'rxjs';

// mock services to avoid loading actual aws app config and ssm params
jest.mock('@rooster/node-services');

describe('HealthController', () =&gt; {
  let controller: HealthController;
  // @ts-ignore
  let httpService: HttpService;

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        ConfigModule.forRoot({
          ignoreEnvVars: true,
          ignoreEnvFile: true,
          load: [MockEnvConfig],
        }),
        AppConfigModule,
        TerminusModule,
      ],
      controllers: [HealthController],
      providers: [
        {
          provide: HttpService,
          useValue: {
            get: jest.fn(() =&gt; of({ 'payments-service': { status: 'up' } })),
            request: jest.fn(() =&gt; of({ status: 'ok' })),
          },
        },
      ],
    }).compile();

    controller = module.get&lt;HealthController&gt;(HealthController);
    httpService = module.get&lt;HttpService&gt;(HttpService);
  });

  it('should be defined', () =&gt; {
    expect(controller).toBeDefined();
  });

  describe('checkHealth()', () =&gt; {
    it('should return happy result', async () =&gt; {
      const happyResult = {
        status: 'ok',
        info: { 'payments-service': { status: 'up' } },
        error: {},
        details: { 'payments-service': { status: 'up' } },
      };

      await expect(controller.check()).resolves.toEqual(happyResult);
    });
  });
});
</code></pre>
<p><strong>UPDATE</strong></p>
<p>I made some changes to code, and I got much closer. The test now <strong>passes intermittently</strong>. In other words, sometimes the test passes, and sometimes it fails.</p>
<p>Here's a screenshot:</p>
<p><a href=""https://i.stack.imgur.com/TtZhO.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/TtZhO.png"" alt=""test passing and failing"" /></a></p>
",https://stackoverflow.com/questions/72978322/unit-testing-a-nestjs-controller-that-has-a-bunch-of-imports,"['javascript', 'unit-testing', 'nestjs']",1074,False,0,1
How to use an existing DB for unit testing in Django?,"<p>I have created a REST-API application using Django Rest Framework.</p>
<p>The API just converts the data from an existing <strong>Read-only Postgres DB</strong> to a REST- API to be consumed by the front-end.</p>
<p>Now I need to write some unit tests to test the application. <strong>Since there are lots of tables and views involved, I cannot create mock data and test.</strong></p>
<p>Is there a way to run the tests in Django using the existing DB (Postgres) without creating any mock data ?</p>
<p><em>Note: I have read a lot of SO posts related to my problem but none of them worked as they were for old versions of Django.</em></p>
",https://stackoverflow.com/questions/71047714/how-to-use-an-existing-db-for-unit-testing-in-django,"['python-3.x', 'django', 'postgresql', 'django-rest-framework', 'django-tests']",1017,False,0,2
Is there a possibility of unit testing database functions using cmocka?,"<p>I am trying to make some unit tests for database functions in C language, but i am not aware is it possible with cmocka?
I couldn't find any example on the internet for database testing using cmocka, so i wonder if someone has an example of testing database functions with cmocka. For example it could be connecting to database, reading from database, writing to database, updating database, any example would help.</p>
<p><strong>EDIT</strong>
Let's say i have the following function in a separate Base.c file:</p>
<pre><code>static  void    dbclose(int SQLnumber)
    {

    if (hDbc[SQLnumber])
        {
        SQLDisconnect(hDbc[SQLnumber]);
        SQLFreeConnect(hDbc[SQLnumber]);
        }

    hDbc[SQLnumber] = NULL;
    }
</code></pre>
<p>How to define the wrap method in CMakeLists.txt so i could use it in Tests.c file?
Also, is it possible to wrap the SQLDisconnect and SQLFreeConnect from the SQL API separately?</p>
",https://stackoverflow.com/questions/73489914/is-there-a-possibility-of-unit-testing-database-functions-using-cmocka,"['c', 'unit-testing', 'database-testing', 'cmocka']",40,False,0,0
Unit Testing Async Controller Method Returning Null with NUnit and Moq,"<p>I have a .NET Core API Framework 6.0, I'm writing tests an Async Controller method using NUnit Framework I'm getting null value returned by the Controller Authentication method. When I make a similar call from Postman there is response. I assume my Moq is missing something but I have followed documentation and cannot figure out the issue.</p>
<pre><code>//User Controller
    private readonly IUserService _userService;

    public UserController(IUserService userService)
    {
        _userService = userService;
    }

    [AllowAnonymous]
    [HttpPost(&quot;authenticate&quot;)]
    public async Task&lt;IActionResult&gt; Authenticate([FromBody] UserRequest userRequest)
    {
        try
        {
            var response = await _userService.Authenticate(userRequest); //Authenticate method is not being called, response is NULL here
            return Ok(new ApiResponse&lt;UserResponse&gt;().Success(response));
        }
        catch (Exception ex)
        {
            return betServerError(ex);
        }
    }
</code></pre>
<p>The Authenticate method is as below, the breakpoint on Line 1 is not being hit.</p>
<pre><code>public async Task&lt;UserResponse&gt; Authenticate(UserRequest userRequest)
    {
        var user = _context.Users.Where(x =&gt; x.Email == userRequest.Email).FirstOrDefault(); //Breakpoint here is not being hit
        bool valid = false;

        if (user == null)
            throw new HttpException(HttpStatusCode.Unauthorized, &quot;Username or password incorrect&quot;);

        //Other code ......
        
     return new UserResponse
        {
            Id = user.Id,
            Email = user.Email,
            Token = tokenString
        };
    }
</code></pre>
<p>UserTest.cs looks as follows:</p>
<pre><code>Mock&lt;IUserService&gt; UserServiceMock = new Mock&lt;IUserService&gt;();

    [SetUp]
    public void Setup()
    {

    }
    [Test]
    public async Task should_Login()
    {
        //Arrange
        var user = new UserResponse
        {
            Id = 1,
            Email = &quot;username@gmail.com&quot;,
            Token = &quot;TEST_TOKEN&quot;
        };
        UserServiceMock.Setup(x =&gt; x.Authenticate(new UserRequest { Email = &quot;username@gmail.com&quot;, Password = &quot;password&quot; }))
            .Returns(Task.Run(() =&gt; user));
        var UserController = new UserController(UserServiceMock.Object);

        //Act
        var result = await UserController.Authenticate(new UserRequest { Email = &quot;username@gmail.com&quot;, Password = &quot;password1&quot; }); //result here doesnot contain the response I expect, it has a null object
        
        //Assert
        Assert.IsNotNull(result);
        Assert.AreEqual(HttpStatusCode.OK, GetHttpStatusCode(result));
    }
</code></pre>
",https://stackoverflow.com/questions/71383979/unit-testing-async-controller-method-returning-null-with-nunit-and-moq,"['c#', '.net', 'multithreading', 'nunit']",750,True,0,1
Mocking and unit testing Microsoft Graph API to get users list,"<p>I am using Microsoft Graph SDK in my project to call graph API which returns a list of users in</p>
<p>I am trying to mock a call to the microsoft graph api and return a list of users that I can use to assert. I am not really getting how to use the setup method to get an object to assert on. Currently getting an null references object error.</p>
<blockquote>
<p>Interface:</p>
</blockquote>
<pre><code>public Task&lt;IGraphServiceUsersCollectionPage&gt; GetUsersAsync();
</code></pre>
<blockquote>
<p>GetUsersAsync() method calling the API:</p>
</blockquote>
<pre><code>    public Task&lt;IGraphServiceUsersCollectionPage&gt; GetUsersAsync()
    {
        return this.appClient.Users
            .Request(this.queryOptions)
            .Select(@$&quot;
            Id,
            DisplayName,
            GivenName,
            Surname,
            Mail,
            OtherMails,
            CompanyName,
            .OrderBy(&quot;DisplayName&quot;)
            .GetAsync();
    }
</code></pre>
<blockquote>
<p>MS Test: Unit testing:</p>
</blockquote>
<pre><code>public Task&lt;IGraphServiceUsersCollectionPage&gt; GetUsersAsync()
    {
        return this.appClient.Users
            .Request(this.queryOptions)
            .Select(@$&quot;
            Id,
            DisplayName,
            GivenName,
            Surname,
            Mail,
            OtherMails,
            CompanyName,&quot;
            .OrderBy(&quot;DisplayName&quot;)
            .GetAsync();
    }

    
      [TestMethod]
    public void GetUsersAsyncSuccess()
    {
        var mockAuthProvider = new Mock&lt;IAuthenticationProvider&gt;();
        var mockHttpProvider = new Mock&lt;IHttpProvider&gt;();
        var mockGraphClient = new Mock&lt;GraphServiceClient&gt;(mockAuthProvider.Object, mockHttpProvider.Object);
        User users = new User() 
        { 
            Id = &quot;1&quot;, 
            DisplayName = &quot;test&quot;,
            GivenName = &quot;test2&quot;,
            Surname = &quot;test3&quot;
        };
        var emails = Enumerable.Empty&lt;string&gt;();

        // setup the call
        mockGraphClient
          .Setup(g =&gt; g.Users
              .Request()
              .GetAsync(CancellationToken.None))
              .ReturnsAsync(users)
              .Verifiable(); 

        // Act
        var graphClient = mockGraphClient.Object;
        var user = graphClient.Users
            .Request()
            .GetAsync();

        // Assert
        // Assert.AreEqual(users.Id, users.Id);
    }
</code></pre>
",https://stackoverflow.com/questions/74432270/mocking-and-unit-testing-microsoft-graph-api-to-get-users-list,"['c#', 'asp.net-mvc', 'microsoft-graph-api', 'azure-ad-graph-api']",593,False,0,0
Unit Testing CQRS with MediatR pattern using Moq always returns null,"<p>I am working on a project and that uses CQRS with MediatR and I am trying to unit test the query handler and API controller but the result returned is always null. My query is as under:</p>
<pre><code>public class GetCustomerByIdQuery : IRequest&lt;BaseResponse&lt;CustomerDto&gt;&gt;
{
    internal int? Id { get; }

    public GetCustomerByIdQuery(int? id) =&gt; Id = id;
}
</code></pre>
<p>Query handler:</p>
<pre><code>public class GetCustomerByIdQueryHandler : BaseHandler, IRequestHandler&lt;GetCustomerByIdQuery, BaseResponse&lt;CustomerDto&gt;&gt;
{
    public GetCustomerByIdQueryHandler(IUnitOfWork unitOfWork, IMapper mapper) : base(unitOfWork, mapper)
    {
    }

    public async Task&lt;BaseResponse&lt;CustomerDto&gt;&gt; Handle(GetCustomerByIdQuery request,
        CancellationToken cancellationToken)
    {
        Customer? result = await UnitOfWork.ICustomerRepository.GetByIdAsync(request.Id);
        if (result != null)
            return new BaseResponse&lt;CustomerDto&gt;(HttpStatusCode.OK, null, Mapper.Map&lt;CustomerDto&gt;(result));
        return new BaseResponse&lt;CustomerDto&gt;(HttpStatusCode.NotFound, $&quot;No record found against id: {request.Id}&quot;);
    }
}
</code></pre>
<p>And the unit test that I am writing is as under:</p>
<pre><code>[Fact]
    public async Task GetCustomerByIdTest()
    {
        int customerId = 1;
        global::Sales.Domain.Entities.Customer customer = new global::Sales.Domain.Entities.Customer
        {
            AccountNumber = &quot;AW00000001&quot;,
            PersonId = null,
            CustomerId = 1,
            StoreId = 934,
            ModifiedDate = DateTime.Now,
            Rowguid = Guid.NewGuid()
        };
        BaseResponse&lt;CustomerDto&gt; response = new BaseResponse&lt;CustomerDto&gt;(HttpStatusCode.OK,
            &quot;Record found successfully&quot;, _mockMapper.Object.Map&lt;CustomerDto&gt;(customer));

        _mockUnitOfWork.Setup(x =&gt; x.ICustomerRepository.GetByIdAsync(customerId)).ReturnsAsync(customer);
        _handler = new GetCustomerByIdQueryHandler(_mockUnitOfWork.Object, _mockMapper.Object);

        var result = await _handler.Handle(new GetCustomerByIdQuery(1), CancellationToken.None);
    }
</code></pre>
<p>The result object in the handler is always null. Can you point me where I am making mistake in my unit test.</p>
",https://stackoverflow.com/questions/73207615/unit-testing-cqrs-with-mediatr-pattern-using-moq-always-returns-null,"['.net', 'unit-testing', 'xunit', 'cqrs', 'mediatr']",237,False,0,0
Setup Jest unit testing for Angular to easily mock dependency classes,"<p>I am trying to find a way to setup my Jest unit testing in the following manner:</p>
<ul>
<li>Every class has its stub class. We always use stub classes for unit testing.</li>
<li>Stub classes return minimal required mock values.</li>
<li>We can always overwrite default stub with test specific data.</li>
</ul>
<p>Let's have an example.</p>
<pre class=""lang-js prettyprint-override""><code>class AnotherServiceUsedWithinTestedClassStub {
  methodToOverwrite(): stirng {
    return 'mockValue';
  }
}

describe('TestClass', () =&gt; {
  let sut: ServiceUnderTest;
  let depService: AnotherServiceUsedWithinTestedClass;

  beforeAll(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        ServiceUnderTest,
        {
          provide: AnotherServiceUsedWithinTestedClass,
          useClass: AnotherServiceUsedWithinTestedClassStub,
        },
      ],
    });

    injector = getTestBed();
    sut = injector.inject(ServiceUnderTest);
    depService = injector.inject(AnotherServiceUsedWithinTestedClass);
  });

  it('should be created', () =&gt; {
    // So, now whenever AnotherServiceUsedWithinTestedClass is called it will return the values defined in AnotherServiceUsedWithinTestedClassStub.

    // Let's say, I want to overwrite this with specific dataset for this testcase:

    const spy = jest.spyOn(depService, 'methodToOverwrite').mockImplementationOnce(() =&gt; 'newMockValue');

    // ... the rest of the testcase
  });
});

</code></pre>
<p>The problem is that <code>const spy = jest.spyOn(depService, 'methodToOverwrite').mockImplementationOnce(() =&gt; 'newMockValue');</code> doesn't work at all - instead of returning <code>newMockValue</code> it returns <code>mockValue</code> from <code>AnotherServiceUsedWithinTestedClassStub</code>.</p>
<p>Using Angular <code>13.3.2</code> and Jest <code>28.1.1</code>.</p>
<p>PS.
I'm not interested in using <code>useValue</code> in <code>configureTestingModule</code>. The idea is to operate on classes using <code>useClass</code>.</p>
",https://stackoverflow.com/questions/72954608/setup-jest-unit-testing-for-angular-to-easily-mock-dependency-classes,"['angular', 'unit-testing', 'jestjs']",33,False,0,0
Unit Testing Vue 3 Component that uses Pinia with Vue Testing Library,"<p>I am struggling to understand how I can test the rendering of items based on the results of a call to a Pina getter in my Vue 3 app (using the Vue Testing Library). An example of what I want to achieve might be something like:</p>
<pre><code>&lt;div v-for=&quot;contact in store.getContacts()&quot;&gt;
      &lt;p&gt;{{contact.firstName}} {{ contact.lastName }}&lt;/p&gt;
&lt;/div&gt;
</code></pre>
<p>where I want to test that all the names of the contacts are displayed.</p>
<p>My app uses Vitest and @testing-library/vue so in my test spec for the above test I might have:</p>
<pre><code>import { cleanup, getByRole, render, screen } from &quot;@testing-library/vue&quot;;
import { describe, it, vi, beforeEach, afterEach } from &quot;vitest&quot;;
import MyComponent from &quot;@/components/MyComponent.vue&quot;;
import { createTestingPinia } from &quot;@pinia/testing&quot;;

describe(&quot;MyComponent.vue&quot;, () =&gt; {

  let getByText: any, getByRole: any;

  beforeEach(() =&gt; {
    ({ getByText } = render(MyComponent, {
      global: {
        plugins: [
          createTestingPinia({
            initialState: {
              contacts: [{firstName:&quot;Bill&quot;,lastName:&quot;Jones&quot;},{firstName:&quot;Peter&quot;,lastName:&quot;Smith&quot;}],
            },
            stubActions: false,
            createSpy: vi.fn,
          }),
        ],
      },
    }));
  });

  afterEach(() =&gt; {
    cleanup();
  });
  
  it(&quot;should display the first name&quot;, () =&gt; {
    getByText(&quot;Bill Jones&quot;);
  });

}); 
</code></pre>
<p>in the store I have the following state setup:</p>
<pre><code>interface Student {
  &quot;id&quot;: number;
  &quot;firstName&quot;: string;
  &quot;lastName&quot;: string;
  &quot;house&quot;: string;
  &quot;year&quot;: number;
  &quot;class&quot;: string;
}

interface ContactState {
  contacts: Student[];
}

export const useContactStore = defineStore({
  id: &quot;contact&quot;,
  state: ():ContactState =&gt; ({
    contacts: [],
}),
</code></pre>
<p>and a getter:</p>
<pre><code>getContacts: (state) =&gt; {
      return state.contacts;
}
</code></pre>
<p>I think I have setup the initial state of the store correctly (??) but the getter does not seem to be working - what else do I need to do here? Do I have to mock the getter or something? Or maybe I am not initialising the store correctly in the test?</p>
<p>(my app is all working fine, it's the test I cannot get to work)</p>
",https://stackoverflow.com/questions/73459595/unit-testing-vue-3-component-that-uses-pinia-with-vue-testing-library,"['javascript', 'vue.js', 'pinia', 'vue-testing-library']",2113,True,4,1
AWS CDK Boto 3 Unit Testing - How to mock Boto3 secrets manager,"<p>Anyone have ideas on how to mock a boto3 secrets manager client's get_secret_value method in a separate method without passing the client to the method? Stuck on this for days, now. Any ideas, links to possible working code on github would be appreciated.</p>
",https://stackoverflow.com/questions/71151328/aws-cdk-boto-3-unit-testing-how-to-mock-boto3-secrets-manager,"['amazon-web-services', 'unit-testing', 'boto3', 'aws-cdk', 'aws-secrets-manager']",539,True,3,1
Cannot provide equal timestamp value into time.Time variable when unit testing gorm,"<p>I attempt to write unit tests. Everything was fine until the moment when I started dealing with the time package.</p>
<pre><code>&quot;testing&quot;

&quot;github.com/DATA-DOG/go-sqlmock&quot;
&quot;github.com/stretchr/testify/require&quot;
&quot;gorm.io/driver/postgres&quot;
&quot;gorm.io/gorm&quot;

</code></pre>
<pre><code>func createDB(t *testing.T) (*DB, sqlmock.Sqlmock) {
    db, mock, err := sqlmock.New()
    require.NoError(t, err)
    require.NotNil(t, db)
    require.NotNil(t, mock)

    dialector := postgres.New(postgres.Config{
        DSN:                  &quot;sqlmock_db_0&quot;,
        DriverName:           &quot;postgres&quot;,
        Conn:                 db,
        PreferSimpleProtocol: true,
    })

    gormDB, err := gorm.Open(dialector, &amp;gorm.Config{})
    require.NoError(t, err)
    require.NotNil(t, gormDB)

    return &amp;DB{
        gorm: gormDB,
        db:   db,
    }, mock
}
</code></pre>
<pre><code>func (db *DB) CreateUser(ctx context.Context, user model.User) error {
    err := db.gorm.Create(&amp;user).Error
    return err
}
</code></pre>
<pre><code>timeTest, _ := time.Parse(&quot;2006-01-02&quot;, &quot;2021-01-14&quot;)

sourceUser := models.User{
     CreatedAt: timeTest,
     UpdatedAt: null.NewTime(timeTest, true),
 }
db, mock := createDB(t)
mock.MatchExpectationsInOrder(false)
mock.ExpectBegin()
mock.ExpectExec(regexp.QuoteMeta(`INSERT INTO &quot;user&quot; (&quot;created_at&quot;,&quot;updated_at&quot;) VALUES ($1,$2) RETURNING &quot;id&quot;`)).
 WithArgs(
     sourceUser.CreatedAt,
     sourceUser.UpdatedAt,
     ).WillReturnResult(sqlmock.NewResult(sourceUser.ID, 1))
mock.ExpectCommit()
err := db.CreateUser(context.Background(), &amp;sourceUser)

require.NoError(t, err)
</code></pre>
<blockquote>
<p>Error:        Received unexpected error:
call to Query 'INSERT INTO &quot;user&quot; (&quot;created_at&quot;,&quot;updated_at&quot;) VALUES ($1,$2) RETURNING
&quot;id&quot;' with args [{Name: Ordinal:1 Value:2021-01-14 00:00:00 +0000 UTC}{Name: Ordinal:2 Value:2021-01-14 00:00:00 +0000 UTC}
] was not expected; call to Rollback transaction was not expected</p>
<p>INSERT INTO &quot;user&quot; (&quot;created_at&quot;,&quot;updated_at&quot;) VALUES ('2021-01-14 00:00:00','2021-01-14 00:00:00')
RETURNING &quot;id&quot;</p>
</blockquote>
<p>Vars <strong>2021-01-14 00:00:00</strong> and <strong>2021-01-14 00:00:00 +0000 UTC</strong> are not the same.
I try to solve this issue in different ways, but I can't find right.
It is also not working if I edit my QuoteMeta like 'INSERT'</p>
",https://stackoverflow.com/questions/71833466/cannot-provide-equal-timestamp-value-into-time-time-variable-when-unit-testing-g,"['unit-testing', 'go', 'mocking', 'go-gorm', 'datadog']",545,False,2,0
jasmine unit-testing: Can&#39;t trigger change event in custom angular dropdown component,"<p>I am working on unit-testing with jasmine and karma an angular component. In the template-component a custom dropdown component is used:</p>
<pre><code>   &lt;div class=&quot;my-modal-body&quot;&gt;
        &lt;form [formGroup]=&quot;form&quot; class=&quot;form-horizontal&quot;&gt;
            &lt;div class=&quot;padding-dropdown&quot;&gt;
                &lt;my-form-wrapper
                    label=&quot;Dateiformat&quot;
                    labelClass=&quot;col-lg-4 two-col-label-size&quot;
                    inputClass=&quot;col-lg-8 two-col-input-size&quot;
                &gt;
                    &lt;my-dropdown
                        [items]=&quot;exportOptionen&quot;
                        formControlName=&quot;dateiTyp&quot;
                        (selectedChange)=&quot;exportFileChange($event)&quot;
                    &gt;
                    &lt;/my-dropdown&gt;
                &lt;/my-form-wrapper&gt;
            &lt;/div&gt;
</code></pre>
<p>In my testing I try to test the value change, but can't get it working. However I try to set the value, the exportFileChange is not triggered.
And I know that the component is correct, because it's already in production. So it has to be the test that errors.</p>
<p>Here is my test:</p>
<pre><code>    it('dateiTyp auswahl excel', waitForAsync(() =&gt; {
        spyOn(component, 'exportFileChange');
        dateiTyp.setValue('Excel');
        component.dateiTyp.setValue('Excel', { emitEvent: true });
        fixture.detectChanges();
        fixture.whenStable().then(
            () =&gt; {
                expect(component.exportFileChange).toHaveBeenCalled();
                let exDiv = fixture.debugElement.query(By.css(&quot;#excelExportDiv&quot;));
                expect(exDiv).not.toBeNull();
            }
        );
    }));
</code></pre>
<p>When changing the selection the exportFileChange(event) method should be called and in the template an div appears. The exportFileChange-Method in the component just changes an boolean.
I tested changing the boolean in the test and that worked, but the event still wasn't triggered.</p>
<p>Here are the most relevant parts of the setup:</p>
<pre><code>describe('ExportModalComponent', () =&gt; {
   [...]
   let dateiTyp: jasmine.SpyObj&lt;FormControl&gt;;
   let dateiTypChange: Subject&lt;string&gt;;
[...]

beforeEach( waitForAsync(() =&gt; {
[...]
  dateiTyp = jasmine.createSpyObj('dateiTyp', ['value', 'setValue']);
  formGroup.get.withArgs('dateiTyp').and.returnValue(dateiTyp);
  dateiTypChange = new Subject();
  Object.defineProperty(dateiTyp, 'valueChanges', { value: dateiTypChange });
[...]

</code></pre>
<p>and my-dropdown.component.d.ts:</p>
<pre><code>export declare class myDropdownComponent implements ControlValueAccessor, OnInit, OnChanges 
{ [...] }
</code></pre>
<p>I can change the ExportModal-template or the ExportModal-component but I can't change the implementation or use of myDropdownComponent.</p>
<p>I am grateful for every help!</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/71175706/jasmine-unit-testing-cant-trigger-change-event-in-custom-angular-dropdown-comp,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1573,True,2,1
Vue 2.7 unit testing of composition api fails with defineProps is undefined,"<p>I'm trying out vue 2.7 and the composition API to get a feel on how it's like to work with and due to it's better TS type inference.</p>
<p>Building the app works flawlessly now and linting and typechecks are all ok.</p>
<p>My issue is that when I try to run my jest unit test the component mounting fails due to
defineProps being undefined. I have no idea why that would be the case.</p>
<p>This is being run in a large rush monorepo where vue 2.7 is an allowed version, do not know if that is relevant.</p>
<blockquote>
<p>ReferenceError: defineProps is not defined</p>
</blockquote>
<pre><code>  49 | }
  50 |
&gt; 51 | const props = defineProps&lt;Props&gt;();
     | ^
  52 | const { selectedAgreement, agreements, scopeId } = props;
  53 |
  54 | const t = translateMixin.methods.t;

  at Object.&lt;anonymous&gt; (components/oe-dirigent-top-row.vue:51:1)
  at Object.&lt;anonymous&gt; (b2b-oe-dirigent.vue:7:1)
  at Object.&lt;anonymous&gt; (b2b-oe-dirigent.spec.ts:1:1)
  at TestScheduler.scheduleTests (../../../common/temp/node_modules/.pnpm/@jest+core@27.5.1/node_modules/@jest/core/build/TestScheduler.js:333:13)
  at runJest (../../../common/temp/node_modules/.pnpm/@jest+core@27.5.1/node_modules/@jest/core/build/runJest.js:404:19)
  at _run10000 (../../../common/temp/node_modules/.pnpm/@jest+core@27.5.1/node_modules/@jest/core/build/cli/index.js:320:7)
  at runCLI (../../../common/temp/node_modules/.pnpm/@jest+core@27.5.1/node_modules/@jest/core/build/cli/index.js:173:3) 
</code></pre>
<p>Running vue/test-utils@1.1.3 and @vue/vue-jest@27.0.0-alpha.4</p>
",https://stackoverflow.com/questions/74066891/vue-2-7-unit-testing-of-composition-api-fails-with-defineprops-is-undefined,"['vue.js', 'jestjs', 'ts-jest', 'vue-test-utils']",489,False,2,0
Angular unit testing Type Error: Cannot read properties of undefined (reading &#39;get&#39;),"<p>I am trying to mock the signup service, where the signup component consists of multiple form but getting the error as title(i.e. TypeError: Cannot read properties of undefined (reading 'get') at .ts file  get userRegisterGroup()).How can I validate the controles of RegisterGroup** and <strong>codeVerifyGroup</strong>  in .spec file</p>
<p><strong>signup.spec</strong></p>
<pre class=""lang-js prettyprint-override""><code>const routerSpy = jasmine.createSpyObj('Router', ['navigateByUrl']);
const signUpServiceSpy = jasmine.createSpyObj('signUpService', ['signUp']);

describe('SignIn Component Isolated Test', () =&gt; {
  let component: SignupComponent;
  let fixture: ComponentFixture&lt;SignupComponent&gt;;

  beforeEach(() =&gt; {
    component = new SignupComponent(new FormBuilder(), routerSpy, signUpServiceSpy);
  });

  it('Component successfully created', () =&gt; {
    expect(component).toBeTruthy();
  });

  it('component initial state', () =&gt; {
    expect(component.registerSubmitted).toBeFalsy();
    expect(component.userRegisterGroup()).toBeDefined();
  });
});
</code></pre>
<p><strong>singup.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>  ngOnInit() {
    this.registerForm = this.formBuilder.group({
      userRegisterGroup: this.formBuilder.group({
        name: ['', [
          Validators.required,
          Validators.minLength(3),
          Validators.maxLength(20)
        ]],
        email: ['', [Validators.required, Validators.email]],
        password: ['', [Validators.required, Validators.minLength(8), Validators.maxLength(40)]],
      }),
      codeVerifyGroup: this.formBuilder.group({
        code: ['', Validators.required]
      })
    });
  }

  get f() {
    return (&lt;FormGroup&gt;this.registerForm.get('userRegisterGroup')).controls;
  }

  get c() {
    return (&lt;FormGroup&gt;this.registerForm.get('codeVerifyGroup')).controls;
  }

  get userRegisterGroup() {
    return this.registerForm.get('userRegisterGroup');
  }

  get codeVerifyGroup() {
    return this.registerForm.get('codeVerifyGroup');
  }
</code></pre>
<p><strong>singup.html</strong></p>
<pre class=""lang-html prettyprint-override""><code>&lt;form [formGroup]=&quot;userRegisterGroup&quot; (ngSubmit)=&quot;signUp()&quot; *ngIf=&quot;!isConfirm&quot;&gt;
  &lt;div class=&quot;form-group mb-3&quot; id=&quot;username-container&quot;&gt;
    &lt;label for=&quot;name&quot; class=&quot;form-label required&quot;&gt;Username&lt;/label&gt;
    &lt;input type=&quot;name&quot; id=&quot;name&quot; formControlName=&quot;name&quot; class=&quot;form-control&quot;
           placeholder=&quot;Enter Username&quot;
           [ngClass]=&quot;{ 'is-invalid': registerSubmitted &amp;&amp; f.name.errors}&quot;/&gt;

    &lt;div id=&quot;username-error-msg&quot; *ngIf=&quot;registerSubmitted &amp;&amp; f.name.errors&quot;
         class=&quot;invalid-feedback&quot; class=&quot;errorMsg&quot;&gt;
      &lt;div id=&quot;blank-username-error&quot; *ngIf=&quot;f.name.errors.required&quot; class=&quot;errorMsg&quot;&gt;
        Please enter username.
      &lt;/div&gt;
      &lt;div id=&quot;blank-username-minlength-error&quot; *ngIf=&quot;f.name.errors.minlength&quot;
           class=&quot;errorMsg&quot;&gt;useranme sholud have minimum 3 characters.
      &lt;/div&gt;
      &lt;div id=&quot;blank-username-maxlength-error&quot; *ngIf=&quot;f.name.errors.maxlength&quot;
           class=&quot;errorMsg&quot;&gt;useranme sholud have minimum 40 characters.
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div class=&quot;form-group mb-3&quot; id=&quot;email-container&quot;&gt;
    &lt;label for=&quot;email&quot; class=&quot;form-label required&quot;&gt;Email&lt;/label&gt;
    &lt;input type=&quot;email&quot; id=&quot;email&quot; formControlName=&quot;email&quot; class=&quot;form-control &quot;
           placeholder=&quot;Enter user email address&quot; [(ngModel)]=&quot;user.email&quot;
           [ngClass]=&quot;{ 'is-invalid': registerSubmitted &amp;&amp; f.email.errors}&quot;/&gt;
    &lt;div id=&quot;email-error-msg&quot; *ngIf=&quot;registerSubmitted &amp;&amp; f.email.errors&quot;
         class=&quot;invalid-feedback&quot; class=&quot;errorMsg&quot;&gt;
      &lt;div id=&quot;blank-email-error&quot; *ngIf=&quot;f.email.errors.required&quot; class=&quot;errorMsg&quot;&gt;Please
        enter username.
      &lt;/div&gt;
      &lt;div id=&quot;blank-email-valid-error&quot; *ngIf=&quot;f.email.errors.email&quot; class=&quot;errorMsg&quot;&gt;
        Please enter a valid email address.
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;div class=&quot;form-group mb-3&quot; id=&quot;password-container&quot;&gt;
    &lt;label for=&quot;password&quot; class=&quot;form-label required&quot;&gt;Password&lt;/label&gt;
    &lt;input [type]=&quot;user.showPassword ? 'text' : 'password'&quot; id=&quot;password&quot;
           formControlName=&quot;password&quot; class=&quot;form-control &quot; id=&quot;password&quot; value=&quot;Default value&quot;
           placeholder=&quot;Enter Password&quot;
           [ngClass]=&quot;{ 'is-invalid': registerSubmitted &amp;&amp; f.password.errors}&quot;/&gt;
    &lt;div id=&quot;password-error-msg&quot; *ngIf=&quot;registerSubmitted &amp;&amp; f.password.errors&quot;
         class=&quot;invalid-feedback&quot; class=&quot;errorMsg&quot;&gt;
      &lt;div id=&quot;blank-password-error&quot; *ngIf=&quot;f.password.errors.required&quot; class=&quot;errorMsg&quot;&gt;
        Please enter password.
      &lt;/div&gt;
      &lt;div id=&quot;blank-password-passworderror&quot; *ngIf=&quot;f.password.errors.password&quot;
           class=&quot;errorMsg&quot;&gt;Please enter valid password.
      &lt;/div&gt;
      &lt;div id=&quot;blank-password-minlength&quot; *ngIf=&quot;f.password.errors.minlength&quot;
           class=&quot;errorMsg&quot;&gt;Passwprd should have mimimum 0f 8 characters.
      &lt;/div&gt;
      &lt;div id=&quot;blank-password-maxlength&quot; *ngIf=&quot;f.password.errors.minlength&quot;
           class=&quot;errorMsg&quot;&gt;Passwprd should have maximum 0f 40 characters.
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;

  &lt;div class=&quot;form-group&quot; id=&quot;signup-btn-container&quot;&gt;
    &lt;button type=&quot;submit&quot; class=&quot;form-control login-btn mb-3&quot; [disabled]=&quot;loading&quot;&gt;
                                            &lt;span class=&quot;spinner-border spinner-border-sm&quot; role=&quot;status&quot;
                                                  aria-hidden=&quot;true&quot;
                                                  *ngIf=&quot;loading&quot;&gt;&lt;/span&gt;
      Registration
    &lt;/button&gt;
  &lt;/div&gt;

  &lt;div class=&quot;signup&quot;&gt;Are you already a member? &lt;a [routerLink]=&quot;['/login']&quot;
                                                   class=&quot;text-primary&quot;&gt;Login&lt;/a&gt;
  &lt;/div&gt;
&lt;/form&gt;
&lt;!-- Code verfication --&gt;
&lt;form [formGroup]=&quot;codeVerifyGroup&quot; (ngSubmit)=&quot;confirmSignUp()&quot; *ngIf=&quot;isConfirm&quot;&gt;
  &lt;div class=&quot;form-group&quot; id=&quot;code-btn-container&quot;&gt;
    &lt;label for=&quot;code&quot; class=&quot;form-label required&quot;&gt;Code&lt;/label&gt;
    &lt;input type=&quot;text&quot; id=&quot;code&quot; formControlName=&quot;code&quot;
           class=&quot;form-control &quot; [ngClass]=&quot;{ 'is-invalid': codeSubmitted &amp;&amp; c.code.errors}&quot;
           placeholder=&quot;Enter the code...&quot;/&gt;
    &lt;div id=&quot;username-error-msg&quot; *ngIf=&quot;codeSubmitted &amp;&amp; c.code.errors&quot;
         class=&quot;invalid-feedback&quot; class=&quot;errorMsg&quot;&gt;
      &lt;div id=&quot;blank-code-error&quot; *ngIf=&quot;c.code.errors.required&quot; class=&quot;errorMsg&quot;&gt;Please
        enter code.
      &lt;/div&gt;
    &lt;/div&gt;
  &lt;/div&gt;
  &lt;div class=&quot;form-group&quot; id=&quot;codeVerify-btn-container&quot;&gt;
    &lt;button type=&quot;submit&quot; class=&quot;form-control login-btn mb-3 mt-3&quot; [disabled]=&quot;loading&quot;&gt;
                                            &lt;span class=&quot;spinner-border spinner-border-sm&quot; role=&quot;status&quot;
                                                  aria-hidden=&quot;true&quot;
                                                  *ngIf=&quot;loading&quot;&gt;&lt;/span&gt;
      Confirm
    &lt;/button&gt;
  &lt;/div&gt;
&lt;/form&gt;
</code></pre>
<p>How should I resolve it? Any code reference would help.</p>
",https://stackoverflow.com/questions/72171655/angular-unit-testing-type-error-cannot-read-properties-of-undefined-reading-g,['angular'],512,False,2,0
How to use unit testing if there are multiple outputs in java?,"<p>How can I test a class that returns the Fibonacci series?
I used an iterator for this code.
The FibonacciIteratorTest class is below.</p>
<pre><code>public class FibonacciIterator implements Iterator&lt;Integer&gt;, Iterable&lt;Integer&gt;{
    private int num1;
    private int num2;
    private int num3;
    private int count;
    private int to;

    public FibonacciIterator(int to){
        this.num1 = 0;
        this.num2 = 1;
        this.to = to;
        this.count = -1;
    }

    public static Iterable&lt;Integer&gt; to(int num){
        return new FibonacciIterator(num);
    }

    @Override
    public Iterator&lt;Integer&gt; iterator(){
        return this;
    }

    @Override
    public boolean hasNext(){
        if(count &lt; to){
            count++;
            return true;
        }
        return false;
    }

    @Override
    public Integer next(){
        if(count &lt; 2){
            return count;
        }
        num3 = num1 + num2;
        num1=num2;
        num2=num3;
        return num3;
    }
}
</code></pre>
<p>Instead of 55, the expected values should be 0 1 1 2 3 5 8 13 21 34 55.</p>
<pre><code>class FibonacciIteratorTest {
   @Test
   void shouldReturnFibonacciNumbers(){
      FibonacciIterator fibonacciNumbers= new FibonacciIterator();
      assertEquals(55,fibonacciNumbers.to());
  }
}
</code></pre>
",https://stackoverflow.com/questions/72198361/how-to-use-unit-testing-if-there-are-multiple-outputs-in-java,"['java', 'unit-testing', 'fibonacci']",70,True,2,2
Unit testing aws lambda handler that queries data from mock elasticsearch index,"<p>I am trying to test an AWS lambda function that queries and returns data from <code>elasticsearch</code>.</p>
<p>I was able to find some <a href=""https://github.com/elastic/elasticsearch-js-mock"" rel=""nofollow noreferrer"">documentation</a> on how to create a mock <code>elasticsearch</code> and add data to the mock index via the below code.</p>
<pre><code>const { Client } = require('@elastic/elasticsearch')
const Mock = require('@elastic/elasticsearch-mock')

const mock = new Mock()
const client = new Client({
  node: 'http://localhost:9200',
  Connection: mock.getConnection()
})

mock.add({
  method: 'POST',
  path: '/indexName/_search',
  body: { query: { match: { foo: 'bar' } } }
}, () =&gt; {
  return {
    hits: {
      total: { value: 0, relation: 'eq' },
      hits: []
    }
  }
})
</code></pre>
<p>My question how would I unit test an endpoint which queries the mock data? I have not been able to find much documentation on how to do this.</p>
<p>i.e. How do I modify the below unit test to use the mock elastic index created above instead of actually having to query a real <code>elasticsearch</code> index using docker or something equivalent which I am currently doing?</p>
<pre><code>const mock = (
  partial: Partial&lt;APIGatewayProxyEvent&gt;
): APIGatewayProxyEvent =&gt; partial as APIGatewayProxyEvent;
const mockContext = {} as Context;
const mockCallback: Callback&lt;APIGatewayProxyResult&gt; = () =&gt; {
  return;

describe('lambda handler', () =&gt; {



  it('returns response', async () =&gt; {
    const result = await handler(
      mockEvent({ queryStringParameters: { name: 'dave' } }),
      mockContext,
      mockCallback
    );
    if (!result) {
      fail('no result');
    } else {
      expect(result.statusCode).toEqual(200);
      expect(JSON.parse(result.body)).toEqual(mockResponse);
    }
  });
});
};
</code></pre>
",https://stackoverflow.com/questions/73333449/unit-testing-aws-lambda-handler-that-queries-data-from-mock-elasticsearch-index,"['typescript', 'amazon-web-services', 'unit-testing', 'elasticsearch', 'jestjs']",239,False,2,0
How do i set up karma/jasmine unit testing with firebase 9,"<p>I am trying to write unit tests for an app I am working on. This app relies heavily on firebase using the most recent tree-shakeable version of firebase. The issue that I am running into is that every time I try to unit test a class that has direct dependencies on firebase I get immediate errors in the afterAll that states that <code>Cannot access 'X' before initialization</code>.</p>
<p>Everything worked perfectly before I began implementing firebase. Also, files that rely on firebase but not through the constructor test properly, but if the class depends on a service that heavily uses firebase, it fails to initialize and I am unable to debug anything even if I put a breakpoint in the beforeEach methods.</p>
<p>This is in my <code>test.ts</code> file:</p>
<pre class=""lang-ts prettyprint-override""><code>// This file is required by karma.conf.js and loads recursively all the .spec and framework files

import 'zone.js/testing';
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

import {initializeApp} from 'firebase/app'
import {getAnalytics} from &quot;firebase/analytics&quot;;
import {getDatabase} from &quot;firebase/database&quot;;
import {getAuth} from &quot;firebase/auth&quot;;

declare const require: {
  context(path: string, deep?: boolean, filter?: RegExp): {
    &lt;T&gt;(id: string): T;
    keys(): string[];
  };
};

const firebaseConfig = {
  apiKey: &quot;AIzaSyCIyO6e9Rx3-PfOZUMT-HtldWlEaf6kWKI&quot;,
  authDomain: &quot;dnd-campaign-planner.firebaseapp.com&quot;,
  databaseURL: &quot;https://dnd-campaign-planner-default-rtdb.firebaseio.com&quot;,
  projectId: &quot;dnd-campaign-planner&quot;,
  storageBucket: &quot;dnd-campaign-planner.appspot.com&quot;,
  messagingSenderId: &quot;1025639363724&quot;,
  appId: &quot;1:1025639363724:web:174534281c9fd97eb7b7a9&quot;,
  measurementId: &quot;G-TZPEVT23KK&quot;
};

export const app = initializeApp(firebaseConfig);
export const analytics = getAnalytics(app);
export const database = getDatabase(app);
export const auth = getAuth(app);

// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting(),
);

// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
</code></pre>
<p>I have tried both with and without initializing in <code>test.ts</code>.</p>
<p>Side note: I have manually tested that the app does work so I know for a fact that it is not  a firebase issue.</p>
",https://stackoverflow.com/questions/70568034/how-do-i-set-up-karma-jasmine-unit-testing-with-firebase-9,"['angular', 'firebase', 'unit-testing', 'karma-jasmine']",167,False,1,0
Unit testing : TypeError: Cannot read properties of undefined (reading &#39;state&#39;) in angular,"<h2>Getting below error when I run npm test</h2>
<h2>TypeError: Cannot read properties of undefined (reading 'state') in angular</h2>
<p>service.ts file</p>
<pre><code>  constructor(private http: HttpClient, private fhirServcie: FHIRService) {
}

tokenResponse:any = this.fhirServcie.getTokenResponse();

getCarePlanDetails(): Observable&lt;any&gt; {
...
}
</code></pre>
<p>FHIR.service.ts</p>
<pre><code>   public fhirClient!: Client;
   
   setFhirClient(client: Client) {
        this.fhirClient = client
   }
   getTokenResponse() {
        return this.fhirClient.state.tokenResponse;
    }
</code></pre>
<p>service.spec.ts file</p>
<pre><code>describe('CarePlanService', () =&gt; {
  let service: CarePlanService;
  let httpTestingController: HttpTestingController;
  let mockFhirService: jasmine.SpyObj&lt;FHIRService&gt;;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule, RouterTestingModule],
      providers: [
        { provider: FHIRService, useValue: jasmine.createSpyObj('FHIRService', ['getTokenResponse']) }]
    });
    httpTestingController = TestBed.get(HttpTestingController);
    service = TestBed.get(CarePlanService);
    mockFhirService = TestBed.get(FHIRService);
  });

  afterEach(() =&gt; {
    httpTestingController.verify();
  });

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

</code></pre>
<p>sample Client object is like,</p>
<pre><code>{ &quot;state&quot;:{
 &quot;tokenResponse&quot;: {
      &quot;access_token&quot;: &quot;fsdjfhsjkfk&quot; }
  }}
</code></pre>
",https://stackoverflow.com/questions/73856514/unit-testing-typeerror-cannot-read-properties-of-undefined-reading-state,"['angular', 'unit-testing', 'karma-jasmine']",36,False,1,0
Unit testing - mocking service which has a List as a data storage,"<p>I'm new to Unit testing and I'm trying to learn how to do it.</p>
<p>I'm using Moq to Mock the dependencies.</p>
<p>Here's my Testing class:</p>
<pre><code>using Microsoft.AspNetCore.Mvc;
using Moq;
using scholarship.Controllers;
using scholarship.Services.Interface;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Xunit;

namespace Testing
{
    public class InternControllerTests
    {
        private Mock&lt;IInternService&gt; _internService = new Mock&lt;IInternService&gt;(); 

        [Theory]
        [InlineData(&quot;00000000-0000-0000-0000-000000000001&quot;)]
        [InlineData(&quot;00000000-0000-0000-0000-000000000002&quot;)]
        public void Delete_Intern(Guid id)
        {
            InternsController internsController
                = new InternsController(_internService.Object);

            var actual = internsController.DeleteIntern(id) as ObjectResult;

            Assert.True(actual is OkObjectResult);
        }

        [Theory]
        [InlineData(&quot;00000000-0000-0000-0000-000000000000&quot;)]
        [InlineData(&quot;00000000-0000-0000-0000-000000000005&quot;)]
        public void Delete_Intern_NotFound(Guid id)
        {
            InternsController internsController
                = new InternsController(_internService.Object);

            var actual = internsController.DeleteIntern(id) as ObjectResult;

            Assert.True(actual is NotFoundObjectResult);
        }
    }
}
</code></pre>
<p>the service:</p>
<pre><code>using scholarship.Models;
using scholarship.Services.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace scholarship.Services.Class
{
    public class InternCollectionService : IInternService
    {
        public static List&lt;Intern&gt; _interns = new List&lt;Intern&gt;
        {
            new Intern { ID = new Guid(&quot;00000000-0000-0000-0000-000000000001&quot;), FirstName = &quot;Octavian&quot;, LastName = &quot;Niculescu&quot;, DateOfBirth=new DateTime(2001,01,01)},
            new Intern { ID = new Guid(&quot;00000000-0000-0000-0000-000000000002&quot;), FirstName = &quot;Andrei&quot;, LastName = &quot;Popescu&quot;, DateOfBirth=new DateTime(2002,01,01)},
            new Intern { ID = new Guid(&quot;00000000-0000-0000-0000-000000000003&quot;), FirstName = &quot;Calin&quot;, LastName = &quot;David&quot;, DateOfBirth=new DateTime(2003,01,01)},
        };
        public bool Create(Intern model)
        {
            _interns.Add(model);
            return true;
        }

        public bool Delete(Guid id)
        {
            int index = _interns.FindIndex(intern =&gt; intern.ID == id);
            if (index == -1)
            {
                return false;
            }
            _interns.RemoveAt(index);
            return true;
        }

        public Intern Get(Guid id)
        {
            return (from intern in _interns
                          where intern.ID == id
                          select intern).FirstOrDefault();
        }

        public List&lt;Intern&gt; GetAll()
        {
            return _interns;
        }

        public bool Update(Guid id, Intern model)
        {
            int index = _interns.FindIndex(intern =&gt; intern.ID == id);
            if (index == -1)
            {
                return false;
            }
            model.ID = id;
            _interns[index] = model;
            return true;
        }
    }
}
</code></pre>
<p>the controller</p>
<pre><code>using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using scholarship.Models;
using scholarship.Services.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace scholarship.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    [ApiController]
    public class InternsController : ControllerBase
    {
        IInternService _internService;
        public InternsController(IInternService internService)
        {
            _internService = internService ?? throw new ArgumentNullException(nameof(internService));
        }

        [HttpGet]
        public IActionResult GetInterns()
        {
            return Ok(_internService.GetAll());
        }

        [HttpGet(&quot;{Id}&quot;, Name = &quot;GetIntern&quot;)]
        public IActionResult GetIntern([FromRoute] Guid Id)
        {
            Intern? intern = _internService.Get(Id);
            if(intern == null)
            {
                return NotFound();
            }
            return Ok(intern);
        }

        [HttpPost]
        public IActionResult AddIntern([FromBody] Intern intern)
        {
            intern.ID = Guid.NewGuid();
            _internService.Create(intern);
            return CreatedAtRoute(&quot;GetIntern&quot;, new { ID = intern.ID }, intern);
        }

        [HttpPut(&quot;{id}&quot;)]
        public IActionResult UpdateIntern([FromBody] Intern intern, Guid id)
        {
            if (intern == null)
            {
                return BadRequest(&quot;Intern cannot be null&quot;);
            }
            _internService.Update(id, intern);
            return Ok();
        }

        [HttpDelete(&quot;{id}&quot;)]
        public IActionResult DeleteIntern(Guid id)
        {
            bool deleted = _internService.Delete(id);
            if (deleted == false)
            {
                return NotFound(&quot;Intern cannot be found&quot;);
            }
            return Ok();
        }
    }
}
</code></pre>
<p>The project is a very small one, I used it to start learning .net.</p>
<p>Now I want to learn Unit Testing, and I'm trying to learn Unit Testing.</p>
<p>The Delete tests fail.</p>
<p>I think this happens because by mocking the service, there is no list with data like in the service.</p>
<p>So, how should I make the Delete tests work? Should I somehow mock that list too? (I don't know how)</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/71815076/unit-testing-mocking-service-which-has-a-list-as-a-data-storage,"['c#', 'unit-testing', 'asp.net-core-mvc']",317,True,1,1
Deno unit testing error No such file or directory (os error 2),"<p>Hey dont know if im being silly im trying to learn unit testing with deno and keep getting this error im using puppeteer if thats relevant cant figure out whats wrong it seems to be pointing to the await in this line</p>
<p>const browser = await puppeteer.launch({ headless: true })</p>
<pre><code>Deno.test('log in with invalid username/password', async test =&gt; {
    // GIVEN I am on the &quot;Log In&quot; page
            const browser = await puppeteer.launch({ headless: true })
            const page = await browser.newPage()
            await page.goto(url, { waitUntil: 'networkidle0' })
            await page.click('a[href=&quot;/login&quot;]', { waitUntil: 'networkidle0' })
    // WHEN I enter &quot;fakeuser&quot; in the username field
            await page.type('input[name=&quot;username&quot;]', 'fakeuser')
    // AND I enter &quot;fakepassword&quot; in the password field
            await page.type('input[name=&quot;password&quot;]', 'fakepassword')
    // AND I click on the login button
            await page.click('input[type=&quot;submit&quot;]', { waitUntil: 'networkidle0' })
    // THEN I should be returned to the &quot;Log In&quot; page
            const heading = await page.$eval('h1', node =&gt; node.innerText)
            await assertEquals(heading, 'Log In', 'invalid credentials dont send user back to login page')
            await browser.close()
})
</code></pre>
<p><a href=""https://i.stack.imgur.com/lE6eY.png"" rel=""nofollow noreferrer"">error code image</a></p>
",https://stackoverflow.com/questions/72842537/deno-unit-testing-error-no-such-file-or-directory-os-error-2,"['javascript', 'unit-testing', 'deno']",255,False,1,1
"Vue jest unit testing, can&#39;t test or render component from components library","<p>We have some complex forms and depending on the login we render different buttons.</p>
<p>However the  component comes from a library installed via NPM. So I'm having trouble reaching them in Jest.</p>
<p>Is there a way to render / load the components so I can test the right ones are present?</p>
<pre><code>describe('P1 buttons - show the correct buttons for credential type and registration status', () =&gt; {
  beforeEach(async () =&gt; {
    await wrapperBeforeEach();
  });
  test('expect button for OPEN_BANKING_UK_MANUAL to be visible', async () =&gt; {
    currentRegistrationDetails.credentials = institutionP1UkAutoBarclays;
    wrapper.vm.currentRegistrationDetails.platform = 'P1';
    await wrapper.vm.$nextTick();

    // wont work if Button is component
    const button = wrapper.find('[data-test-id=&quot;button-p1-download-ssa&quot;]');

    // this would work if the Button component was local to the project
    const buttomExternal = wrapper.findComponent(Button);

    const registrationP1 = wrapper.find('.registration-p1');
    console.log(registrationP1.html());

    // this fails as Button doesn't render at all.
    expect(buttomExternal.isVisible()).toBe(true);
  });
});
</code></pre>
<p>The HTML from <code>console.log(registrationP1.html());</code> is this —</p>
<pre><code>  &lt;div class=&quot;form-actions mb-5&quot;&gt;
    &lt;div class=&quot;form-actions-content&quot;&gt;
      &lt;!----&gt; 
      &lt;!----&gt;
    &lt;/div&gt;
  &lt;/div&gt;
</code></pre>
<p>The buttons should appear between the</p>
<pre><code>      &lt;!----&gt; 
      &lt;!----&gt;
</code></pre>
<p>We keep running into these issues with our applications whilst using our component library.</p>
<p>The actual button markup is</p>
<pre><code>        &lt;Button
          data-test-id=&quot;button-p1-download-ssa&quot;
          type=&quot;primary&quot;
          class=&quot;primary button&quot;
          :is-loading=&quot;savingSsa&quot;
          :on-click=&quot;downloadTheSsaFromModal&quot;
          &gt;Request the SSA&lt;/Button
        &gt;
</code></pre>
",https://stackoverflow.com/questions/71956580/vue-jest-unit-testing-cant-test-or-render-component-from-components-library,"['vue.js', 'unit-testing', 'jestjs', 'components']",726,False,1,1
FastAPI POST Pydantic method unit testing redirecting status_code 307 instead of 200,"<p>I have a test case where I am testing a <code>POST</code> service using <code>pytest</code> hosted with <code>FastAPI</code> Uvicorn. However the response is getting responded with status code <code>307</code>. But this doesn't happen on actual webservice is tested through a browser or <code>curl</code>. What is happening here?</p>
<pre><code>from fastapi.testclient import TestClient
from src.main import app
import json

client = TestClient(app)

def test_get_confidence_ws():
    data = {
        &quot;acc_id&quot;: 1234567801,
        &quot;remoteIp&quot;: &quot;127.255.255.255&quot;,
        &quot;userAgent&quot;: &quot;Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:104.0) Gecko/20100101 Firefox/104.0&quot;
    }
    response = client.post(&quot;/confidence&quot;, json=json.dumps(data))
    assert response.status_code == 200
</code></pre>
<p>Test response</p>
<pre><code>&gt;       assert response.status_code == 200
E       assert 307 == 200
E        +  where 307 = &lt;Response [307]&gt;.status_code
</code></pre>
<p>EDIT:</p>
<p>Actual endpoint that is tested:</p>
<pre><code>@app.post(&quot;/confidence/&quot;)
def get_confidence(json: LoginClassifierSchema):
    ...
    response = {
           &quot;key&quot; : &quot;value&quot;
        }
    return response
</code></pre>
",https://stackoverflow.com/questions/73867088/fastapi-post-pydantic-method-unit-testing-redirecting-status-code-307-instead-of,"['python', 'unit-testing', 'pytest', 'http-post', 'fastapi']",879,True,1,1
Does SECTION run at the same time in Unit testing C++(catch2)?,"<p>I am new to C++ and I am learning Unit testing using catch2. I am writing a testcase like this</p>
<pre><code>TEST_CASE(&quot;Sandwich::AddTopping test&quot;, &quot;[AddTopping]&quot;) {
  // your tests for Sandwich::AddTopping here
  Sandwich newsandwich;

  SECTION(&quot;adding two cheese&quot;) {
    newsandwich.AddTopping(&quot;cheese&quot;);
    REQUIRE(newsandwich.AddTopping(&quot;cheese&quot;) == false);
  }

  SECTION(&quot;adding more than 5 toppings&quot;) {
    newsandwich.AddTopping(&quot;cheese&quot;);
    newsandwich.AddTopping(&quot;lettuce&quot;);
    newsandwich.AddTopping(&quot;tomato&quot;);
    newsandwich.AddTopping(&quot;onions&quot;);
    newsandwich.AddTopping(&quot;pickles&quot;);
    REQUIRE(newsandwich.AddTopping(&quot;cheese&quot;) == false);
  }

  SECTION(&quot;adding 2 other toppings&quot;) {
    newsandwich.AddTopping(&quot;lettuce&quot;);
    REQUIRE(newsandwich.AddTopping(&quot;lettuce&quot;));
  }

  SECTION(&quot;adding in range&quot;) { REQUIRE(newsandwich.AddTopping(&quot;lettuce&quot;)); }
}
</code></pre>
<p>However, my code only create one Sandwich object at the beginning but the output of this is the same as teh one when I create objects separately for each SECTION. Can someone tell me why? Thank you~</p>
",https://stackoverflow.com/questions/71003950/does-section-run-at-the-same-time-in-unit-testing-ccatch2,"['c++', 'unit-testing', 'catch2']",199,False,1,0
Getting cannot read properties of undefined (reading:&#39;viewMode&#39;) in Angular Unit Testing,"<p>Hi I have a function which I would like to unit test. This is my function.</p>
<pre><code>let docProcess: IDocProcess;

public onCalling(args) {
    if (this.docProcess.viewMode) {
      this.makeCalls(args);
    }
}
</code></pre>
<p>This IDocProcess is an interface:</p>
<pre><code>export interface IDocProcess {
  viewMode: boolean;
  editMode: boolean;
  deleteMode: boolean;
}

</code></pre>
<p>I would like to unit test the above function. If I pass docProcess.viewMode as true, makeCalls(args) function should be called. If false, then the function must not be called.</p>
<p>The following is my Unit test code:</p>
<pre><code>
 beforeEach(async(() =&gt; {

    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [CallsComponent],
      providers: [
        MockData
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
  }));


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


  it('should call makeCalls() only on View Mode', () =&gt; {
    
    component.docProcess.viewMode = true;
    fixture.detectChanges();
    component.onCalling(mockArgsData);    
    expect(component.makeCalls).toHaveBeenCalled();

</code></pre>
<p>But the test results get failed. Getting cannot read properties of undefined (reading:'viewMode').</p>
<p>Is this because the Testing module couldn't recognize the interface. A similar situation like this, I am also getting &quot;Cannot set properties of undefined (setting: variable_name)&quot;</p>
<p>Please help me in resolving this.</p>
<pre><code></code></pre>
",https://stackoverflow.com/questions/74279565/getting-cannot-read-properties-of-undefined-readingviewmode-in-angular-unit,"['angular', 'unit-testing', 'karma-jasmine', 'angular-unit-test']",104,False,0,2
How to run unit testing on my SwiftUi app for logging in?,"<p>I am trying to run a unit test on my SwiftUi project to see if the user can log in. But I'm getting the following error in my ViewModel when I try to run the function in my unit testing:</p>
<blockquote>
<p>No such module 'Firebase'.</p>
</blockquote>
<p>Here are my test files:</p>
<pre><code>import XCTest


final class LoginTests: XCTestCase {

    func testLogginIn(){
        let vm = AuthManage()
        
        let truevalue = vm.signIn(email: &quot;test@gmail.com&quot;, password: &quot;testtest&quot;)
        let test = true
        
        XCTAssertTrue(truevalue)
    }

}

</code></pre>
<p>And I can't import Firebase in my testing files.</p>
",https://stackoverflow.com/questions/74234915/how-to-run-unit-testing-on-my-swiftui-app-for-logging-in,"['ios', 'firebase', 'unit-testing', 'swiftui', 'emulation']",40,False,0,0
"In Spring dependency injection, how does tight coupling hurt the unit testing?","<p>Somebody explained it to me once that, In spring framework, we program to the interface rather than programming to concerete class, because it leads to tight coupling, and that's problematic in unit testing while doing the mocking.</p>
<p>I understand the tight coupling part based on the example <a href=""https://stackoverflow.com/questions/2832017/what-is-the-difference-between-loose-coupling-and-tight-coupling-in-the-object-o"">here</a>, but I don't understand how tight coupling is a problem with unit testing and mocking.</p>
<p>Just like the way we mock an interface, we can mock a concerte class. So, how tight coupleing hurts the unit testing?</p>
",https://stackoverflow.com/questions/72616542/in-spring-dependency-injection-how-does-tight-coupling-hurt-the-unit-testing,"['spring', 'unit-testing', 'dependency-injection']",17,False,0,0
How to include `Eclipse Tricore Tasking` libraries in cmake for unit testing,"<p>The source code that I have written is compatible for <code>Eclipse Tricore Tasking</code> compiler, but the unit test I need to write need to written for GCC.
Some <code>tasking</code> intrinsic functions like &quot;__asm(), __nop&quot;[ note double underscore] use only single underscore in GCC.
So i want to know if I can include any tasking library, link-option in <code>CMake</code> file so that I dont get these errors</p>
",https://stackoverflow.com/questions/72976753/how-to-include-eclipse-tricore-tasking-libraries-in-cmake-for-unit-testing,"['unit-testing', 'gcc', 'eclipse-cdt']",70,False,0,0
Grails 4.0.3 Unit Testing problems when saving an entity in the database,"<p>I first started to unit test my file manager api creating a test method which tries to delete a file from a non existent owner (part), as follows.</p>
<pre><code>void &quot;Deleting a file from a non existent part&quot; (){
        when:
        request.method = 'DELETE'
        request.setParameter(&quot;partId&quot;,&quot;1234567891011&quot;)
        request.setParameter(&quot;fileId&quot;,&quot;65465654546654654&quot;)
        controller.deleteMetafiles()

        then:
        response.status == 404
        response.json.message == &quot;Part not found.&quot;
        //println(response.getJson())
    }
</code></pre>
<p>The code above works as expected.</p>
<p>Now I would like to insert a Metafile in the memory database in order to delete it. But it is not being possible.</p>
<pre><code>void &quot;Deleting a valid file from an existent part&quot; (){
        given:
        new Metafile(id: '1111111111', filename: 'test.pdf', title: '',
                description: '', uploadedOn: new Date(),
                partId: '2222222222', uploadedBy: 'Alfred', userId: '333333333').save()

        when:
        setupSpec()
        request.method = 'DELETE'
        request.setParameter(&quot;partId&quot;,&quot;2222222222&quot;)
        request.setParameter(&quot;fileId&quot;,&quot;1111111111&quot;)
        def model = controller.deleteMetafiles()

        then:
        response.status == 200


        println(&quot;response status&quot;)
        println(response.status)
        println(&quot;response status&quot;)
    }
</code></pre>
<p>Could anyone please explain me where I am doing the mistake? The response is 404 (Part not found). The same response of the first unit test. But in the second test I created  a Metafile in the given section.</p>
<p>Thanks!</p>
<p>Alfredo</p>
<p>Below my entire source code.</p>
<pre><code>package br.gov.cmb.cmbarq.tests

import br.gov.cmb.cmbarq.controllers.v1.MetafileController
import br.gov.cmb.cmbarq.domain.Metafile
import grails.testing.web.controllers.ControllerUnitTest
import spock.lang.Specification
import grails.testing.gorm.DataTest

class MetafileControllerSpec extends Specification implements ControllerUnitTest&lt;MetafileController&gt;, DataTest{
    def setupSpec() {
    }

    def cleanup() {
    }

    void &quot;Getting the amount of files from a non existent part&quot;() {
        when:
        request.method = 'GET'
        request.setParameter(&quot;partId&quot;,&quot;1234567891011&quot;)
        controller.getMetafilesAmount()

        then:
        response.status == 404

    }

    void &quot;Listing files of an non existent part&quot;() {
        when:
        request.method = 'GET'
        request.setParameter(&quot;partId&quot;,&quot;1234567891011&quot;)
        controller.listMetafiles()
        then:
        response.status == 404

    }

    void &quot;Deleting a file from a non existent part&quot; (){
        when:
        request.method = 'DELETE'
        request.setParameter(&quot;partId&quot;,&quot;1234567891011&quot;)
        request.setParameter(&quot;fileId&quot;,&quot;65465654546654654&quot;)
        controller.deleteMetafiles()

        then:
        response.status == 404
        response.json.message == &quot;Part not found.&quot;
        //println(response.getJson())
    }


    void &quot;Deleting a valid file from an existent part&quot; (){
        given:
        List &lt;Metafile&gt; sampleMetafiles = [new Metafile(id: '1111111111', filename: 'test.pdf', title: '',
                description: '', uploadedOn: new Date(),
                partId: '2222222222', uploadedBy: 'Alfred', userId: '333333333'),
                                           new Metafile(id: '1111111112', filename: 'test2.pdf', title: '',
                                                   description: '', uploadedOn: new Date(),
                                                   partId: '2222222221', uploadedBy: 'Alfred', userId: '333333334')
                ]


        when:
        request.method = 'DELETE'
        request.setParameter(&quot;partId&quot;,&quot;2222222222&quot;)
        request.setParameter(&quot;fileId&quot;,&quot;1111111111&quot;)
        controller.deleteMetafiles()

        then:
        println(model.size())
        model.size() == 1


    }   
}
</code></pre>
",https://stackoverflow.com/questions/73256348/grails-4-0-3-unit-testing-problems-when-saving-an-entity-in-the-database,"['unit-testing', 'grails']",39,True,0,1
Unit testing with Angular 12 - Unable to function call inside ngFor loop,"<p>I am new in unit testing and now I am not able to call function which inside <code>*ngFor</code> loop of an <code>angular 12</code> app. There is a observable that contains an array of objects and it works fine. Whole data is iterated properly.</p>
<p>This is my HTML code.</p>
<pre><code>&lt;div class=&quot;table-responsive&quot;&gt;
    &lt;table class=&quot;table table-striped&quot;&gt;
        &lt;thead&gt;
          &lt;tr&gt;
            &lt;th&gt;#&lt;/th&gt;
            &lt;th&gt;Name&lt;/th&gt;
            &lt;th&gt;Category&lt;/th&gt;
            &lt;th&gt;Action&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
          &lt;tr *ngFor=&quot;let item of games$ | async; let i = index&quot;&gt;
            &lt;td&gt;{{ i+1 }}&lt;/td&gt;
            &lt;td&gt;{{ item.name }}&lt;/td&gt;
            &lt;td class=&quot;badge-cell&quot;&gt;
               {{ item.categoryId }}
            &lt;/td&gt;
            &lt;td class=&quot;center action-cell&quot;&gt;
              &lt;button type=&quot;button&quot;
                class=&quot;delete-game btn&quot;
                (click)=&quot;deleteGame(item.id)&quot;&gt;Delete&lt;/button&gt;
            &lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;
&lt;/div&gt;
&lt;!-- /.table-responsive--&gt;
</code></pre>
<p>The problem rises while testing a function call inside loop. Thus, when I try to access <code>nativeElement</code> property of a <code>fixture</code> then the dynamic part of a table is <code>null</code>. Therefore <code>daleteGame</code> function is not available.</p>
<p>Here is the how <code>console.log(fixture.nativeElement)</code> look like:</p>
<pre><code>&lt;div _ngcontent-a-c74=&quot;&quot; class=&quot;table-responsive&quot;&gt;
    &lt;table _ngcontent-a-c74=&quot;&quot; id=&quot;dataTables-example&quot; class=&quot;table table-striped&quot;&gt;
        &lt;thead _ngcontent-a-c74=&quot;&quot;&gt;
            &lt;tr _ngcontent-a-c74=&quot;&quot;&gt;
                &lt;th _ngcontent-a-c74=&quot;&quot;&gt;#&lt;/th&gt;
                &lt;th _ngcontent-a-c74=&quot;&quot;&gt;Name&lt;/th&gt;
                &lt;th _ngcontent-a-c74=&quot;&quot;&gt;Category&lt;/th&gt;
                &lt;th _ngcontent-a-c74=&quot;&quot;&gt;Action&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
         //----------NO ROWS IN THE LOG------------//
        &lt;!--bindings={
          &quot;ng-reflect-ng-for-of&quot;: null
        }--&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;
&lt;/div&gt;
</code></pre>
<p>Static data is used to simulate original array(see <code>GAME_DATA</code>). This is how the tests look like:</p>
<pre><code>describe('ListGamesComponent', () =&gt; {
  let component: ListGamesComponent;
  let fixture: ComponentFixture&lt;ListGamesComponent&gt;;

  beforeEach(
    waitForAsync(() =&gt; {
      TestBed.configureTestingModule({
        imports: [HttpClientTestingModule, CommonModule],
        declarations: [ListGamesComponent],
        providers: [
          RequestService,
        ],
      })
        .compileComponents()
        .then(() =&gt; {
          fixture = TestBed.createComponent(ListGamesComponent);
          component = fixture.componentInstance as any;
          component.games$ = from([GAME_DATA]) as unknown as Observable&lt;
            IGameData[]
          &gt;;
        });
    })
  );

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

  it('should check if deleteGame was called', fakeAsync(() =&gt; {
    spyOn(component, 'deleteGame');
    
    component.games$.subscribe((data: any) =&gt; {
     // ---- logged an observable, a proper list of games is returned ----
      console.log('data: ', data);
    });
    
    fixture.detectChanges();

    let button = fixture.debugElement.query(By.css('.delete-game'));
    
    button.triggerEventHandler('click', null);
    fixture.detectChanges();
    tick();

    expect(component.deleteGame).toHaveBeenCalled();
  }));
});
</code></pre>
<p>By the way, I logged an observable inside the test and it retrieves whole data from <code>GAME_DATA</code> static file, so I don't understand why the whole table is not generated.</p>
<p><strong>UPDATE</strong></p>
<p>This is how <code>games$</code> done in component:</p>
<pre><code>export class ListGamesComponent implements OnInit {

  ngOnInit(): void {
    let pager: { index: number; size: number } = {
      index: this.pageIndex,
      size: this.pageSize,
    };
    this.games$ = this.gameService.getAllGames(pager).pipe(
      tap((data) =&gt; {
        this.totalRecords = data.totalItems;
        this.gamesList = data.games;
        
        this.setPage(1, false); // generate pagination
      }),
      pluck('games')
    );
  }
}
</code></pre>
<p>Any help is appreciated. Thanks!</p>
",https://stackoverflow.com/questions/70700401/unit-testing-with-angular-12-unable-to-function-call-inside-ngfor-loop,"['angular', 'typescript', 'unit-testing', 'jasmine', 'angular-unit-test']",950,True,0,1
How to spy OKTA authStateService.authState$ in angular unit testing using karma jasmine,"<p>I have the below authentication guard in my angular application which using OKTA to authenticate.</p>
<pre class=""lang-js prettyprint-override""><code>    export class AuthenticationGuard implements canActivate {

    iaAuthenticated: boolean;
    userDetails: any = null;

    constructor(@Inject(OKTA_AUTH) private oktaAuth: OktaAuth, public authStateService:
        OktaAuthStateServuce) { }
    canActivate = async (next: aCtivatedRouteSnapshot, state: RouterStateSnapshot): Promise&lt;any&gt;
        =&gt; {
        try {
            this.authStateService.authState$.subscribe(
                (response) =&gt; {
                    this.isAuthenticated = response.isAuthenticated;
                }
            );
            if (this.isAuthenticated) {
                this.userDetails = this.oktaAuth.getUser();
            } else { return false; }
        } catch { return false; }
     }
    }
</code></pre>
<p>and this is the spec code for the same which I written</p>
<pre class=""lang-js prettyprint-override""><code>    export class OktaAuthMock {
    isAuthenticated() {
        return true;
    }
    getUser() {
        return {
            email: ‘email@gmail.com’,
            name: ‘test’
        };
    }
    };

     authState$(){ 
       return {isAuthenticated: true}
     }

    fdescribe(‘test AuthenticationGuard’, () =&gt; {
    let service: AuthenticationGuard;
    beforeEach(() =&gt; {
        Testbed.configureTestingModule({
            Imports: [HttpClientTestingModule],
            Providers: [
                {
                    provide: OktaAuthStateService,
                    useClass: OktaAuthMock
                },
                {
                    Provide: OKTA_AUTH,
                    useValue: {}
                }
            ]
        )};
        service = Testbed.inject(AuthenticationGurad)
    });

    it(‘test canActivate method’, () =&gt; {
        const authService: OktaAuthStateService = Testbed.inject(OktaAuthStateService);
        spyOn&lt;any&gt;(authService. ‘authState$’).and.returnValue(of({ isAuthenticated: true }));
        service.canActivate(null, null);
        expect(service.canActivate).tobeTruthy();
    }); 
    )};
</code></pre>
<p>There is no error in the code but I tried to spyon the OktaAuthStateService like above and the lines of code in ts is not covered in unit test. Kindly help to do it correctly.</p>
",https://stackoverflow.com/questions/72056950/how-to-spy-okta-authstateservice-authstate-in-angular-unit-testing-using-karma,"['angular', 'karma-jasmine', 'okta']",879,False,0,1
Unit testing methods whose impact can only be confirmed using another method,"<p>Assume there are two methods in a module, <code>insert</code> and <code>print</code>. The module's inner properties are private and can only be accessed by calling <code>print()</code>.</p>
<p>In testing, <code>print</code> has its own set of tests, and now I'm trying to test <code>insert</code>. The issue is, the only way to confirm if <code>insert</code> did in fact insert any data into the model is to call <code>print()</code> and check its output. Which also means that if something were to break <code>print</code> in the future, then <code>insert</code>'s tests would also fail.</p>
<p>The most straightforward solution is to expose the inner variables that <code>insert</code> affects and assert the changes directly, but that would clutter the module's API and potentially confuse end users.</p>
<p>Is there another practice/solution to situations like this or is exposing the inner variable the way to go?</p>
",https://stackoverflow.com/questions/74752884/unit-testing-methods-whose-impact-can-only-be-confirmed-using-another-method,"['unit-testing', 'testing', 'module']",11,False,0,0
How to run Spark unit testing in parallel via pytest (and fixture)?,"<p>I am writing unit testing for a spark application. I am using pytest and I have created a fixture to load the spark session once.</p>
<p>When I run one test at a time, it is passing but when I run all the tests together I am getting unexpected behavior. Then, I realize, spark is not multi-threadable. Any way to fix this? Is running pytest in non-parallel mode is the only solution?</p>
<p>Sample code structure,</p>
<pre><code>@pytest.fixture(scope=&quot;session&quot;)
def spark() -&gt; SparkSession:
    builder = SparkSession.builder.appName(&quot;pandas-on-spark&quot;)
    builder = builder.config(&quot;spark.sql.execution.arrow.pyspark.enabled&quot;, &quot;true&quot;) 
    return builder.getOrCreate()
</code></pre>
<pre><code>def test1(spark):
   df = spark.createDataFrame(dummy_rows)
   # do some transformaton
   # assert
</code></pre>
<pre><code>def test2(spark):
   df = spark.createDataFrame(dummy_rows)
   # do some transformaton
   # assert
</code></pre>
<pre><code>def testN(spark):
   df = spark.createDataFrame(dummy_rows)
   # do some transformaton
   # assert
</code></pre>
<pre><code>pytest -s .
</code></pre>
",https://stackoverflow.com/questions/73754854/how-to-run-spark-unit-testing-in-parallel-via-pytest-and-fixture,"['python', 'apache-spark', 'pyspark', 'pytest']",336,False,0,1
Error while fetching Path locally during unit testing but not at runtime,"<p>I am trying to find the <code>path of resource using Paths</code> like below and then copying some files at runtime. While at <strong>runtime it works perfectly fine</strong>. However while running locally for <code>junit</code> testing, it throws below error at the below first line <code>while trying to get Path using URI</code>. I am <strong>not</strong> using any zip/jar file so why I am getting the below stack trace. Am I missing something?</p>
<pre><code>Path path= Paths.get(ABCD.class.resource(&quot;/&quot;).toURI());
String mockFileName=&quot;cacerts&quot;;
File mockFile= new File(path+File.seperator+mockfileName);
</code></pre>
<p><strong>Error</strong></p>
<pre><code>java.nio.file.FileSystemNotFoundException
    at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171)
    at com.sun.nio.zipfs.ZipFileSystemProvider.getPath(ZipFileSystemProvider.java:157)
    at java.nio.file.Paths.get(Unknown Source)
</code></pre>
",https://stackoverflow.com/questions/74418391/error-while-fetching-path-locally-during-unit-testing-but-not-at-runtime,"['java', 'spring', 'aws-lambda', 'junit']",12,False,0,0
How to use bcrypt in JEST Unit Testing for a FindAll() Method,"<p>I have a NestJS App that has <code>GET</code> routes. One of them, for instance, is the <code>FindAll()</code> which simply gets all the users from <code>Prisma</code>. The <code>FindAll()</code> method looks like this:</p>
<pre><code>  findAll(): Promise&lt;Users[]&gt; {
    return prisma.users.findMany();
  }
</code></pre>
<p>And in my <code>service.spec.ts</code> I have this:</p>
<pre><code>const usersMany = [
  {
    username: 'user1',
    name: 'User One',
    password: '123',
    email: 'user1@test.com',
    tasks: [],
  },
  {
    username: 'user2',
    name: 'User Two',
    password: '456',
    email: 'user2@test.com',
    tasks: [],
  },
]

  describe('findAll', () =&gt; {
    it('should return all users', async () =&gt; {
      const usersAll = service.findAll();
      expect(usersAll).resolves.toEqual(usersMany);
    });
  });
</code></pre>
<p>How would I go about running this test case if I am also encrypting the passwords using <code>bcrypt</code>? In a running application, this would result in me getting all the users currently made with their passwords <code>hashed</code> instead of plain string.</p>
",https://stackoverflow.com/questions/73731940/how-to-use-bcrypt-in-jest-unit-testing-for-a-findall-method,"['javascript', 'jestjs', 'nestjs']",26,False,-1,1
Android Geocoder returns an empty array as a response on Unit Testing,"<p>I have implemented some unit tests using:</p>
<pre><code>testImplementation &quot;junit:junit:4.13.2&quot;
testImplementation &quot;androidx.test:core-ktx:1.4.0&quot;
testImplementation &quot;org.robolectric:robolectric:4.8&quot;
</code></pre>
<p>Here is the Unit Test code:</p>
<pre><code>@RunWith(RobolectricTestRunner::class)
class NetworkAddressDataSourceTest {

    @Test
    fun test_1(): Unit = runBlocking {
        val context = getApplicationContext&lt;Context&gt;()
        val networkAddressDataSource = NetworkAddressDataSource(context)

        // Expected address = &quot;San Jose, US&quot;
        val hex = Hex(&quot;&quot;, arrayOf(), Location(37.28546527, -121.8749344))

        networkAddressDataSource.getLocationAddress(hex).map {
            assert(it == &quot;San Jose, US&quot;)
        }
        Unit
    }
}
</code></pre>
<p>And here is <code>getLocationAddress(hex: Hex)</code> function:</p>
<pre><code>override suspend fun getLocationAddress(hex: Hex): Either&lt;Failure, String?&gt; {
    return if (Geocoder.isPresent()) {
        val geocoderAddress =
            Geocoder(context).getFromLocation(hex.center.lat, hex.center.lon, 1)[0]

        Either.Right(
            if (geocoderAddress.locality != null) {
                &quot;${geocoderAddress.locality}, ${geocoderAddress.countryCode}&quot;
            } else if (geocoderAddress.subAdminArea != null) {
                &quot;${geocoderAddress.subAdminArea}, ${geocoderAddress.countryCode}&quot;
            } else if (geocoderAddress.adminArea != null) {
                &quot;${geocoderAddress.adminArea}, ${geocoderAddress.countryCode}&quot;
            } else {
                geocoderAddress.countryName
            }
        )
    } else {
        Either.Left(Failure.NoGeocoderError)
    }
}
</code></pre>
<p>The issue is that:</p>
<pre><code>val geocoderAddress = Geocoder(context).getFromLocation(hex.center.lat, hex.center.lon, 1)
</code></pre>
<p>Always returns an empty array as a response. How should I fix this? Does this happen because these tests are local unit tests so the only real solution here is to change to instrumented tests?</p>
<p>Is there a workaround?</p>
<p>Thank you in advance.</p>
",https://stackoverflow.com/questions/72315614/android-geocoder-returns-an-empty-array-as-a-response-on-unit-testing,"['android', 'unit-testing', 'junit4', 'robolectric', 'google-geocoder']",86,False,0,0
How to mock Custom Dialog in Angular for Unit Testing using Jest,"<p>I am writing test cases for unit tests and code coverage for a method that opens a dialog component on <code>isEdit = 'true'</code> which is retrieved from <code>localStorage</code>.</p>
<p>The issue here is in the first test case, I am setting the <code>isEdit = true</code> and calling the method <code>showMessagesList()</code>, then the lines inside the if are getting covered under code coverage but test case is failing with an exception <code>Cannot read property 'openModalDialog' of undefined</code>. But the second test case is not failing because I am Spying On it.
Can anyone please help me mocking the Dialog component in Jest and how it eliminate the error</p>
<p>Exception
SideBarDrawerComponent › should call show Message Items when true</p>
<pre><code>    TypeError: Cannot read property 'openModalDialog' of undefined

      49 |     this.isEdit = localStorage.getItem('isEditMode').toString()
      50 |     if (this.isEdit === 'true') {
    &gt; 51 |       this.modalDialog.openModalDialog()
         |                                ^
      52 |     } else {
      53 |       this.toggleComponent.emit(componentTypes.LIST)
      54 |     }
</code></pre>
<p>Component Method</p>
<pre><code>showMessagesList() {
    // Check if the compose componenet is in edit mode;
    this.isEdit = localStorage.getItem('isEdit').toString()
    if (this.isEdit === 'true') {
      this.modalDialog.openModalDialog() // exception when isEdit is set to 'true' in the test case
    } else {
      this.toggleComponent.emit(&quot;true&quot;)
    }
  }
</code></pre>
<p>Spect.ts file</p>
<pre><code>import { ComponentFixture, TestBed } from '@angular/core/testing'
import { By } from '@angular/platform-browser'
import {
  ModalDialogComponent,
  ModalDialogModule,
} from 'modal-dialog'

import { ContentModel } from '../../model/content.model'
import * as componentTypes from '../componentTypes'
import { ComposeComponent } from '../compose-message/compose.component'
import { MessageItemsComponent } from '../message-list/message-item.component'
import { SideBarDrawerComponent } from './side-bar-drawer.component'
import spyOn = jest.spyOn


window.ResizeObserver =
  window.ResizeObserver ||
  jest.fn().mockImplementation(() =&gt; ({
    disconnect: jest.fn(),
    observe: jest.fn(),
    unobserve: jest.fn(),
  }))

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

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [ModalDialogModule],
      declarations: [
        SideBarDrawerComponent,
        MessageItemsComponent ,
        ComposeComponent,
        ModalDialogComponent, // &lt;-- Dialog Component
      ],
      providers: [
        { provide: Window, useValue: window },
        { provide: ModalDialogComponent, useValue: {} },
      ],
    })
      .compileComponents()
      .then(() =&gt; {
        fixture = TestBed.createComponent(SideBarDrawerComponent)
        component = fixture.componentInstance
      })
  })

  beforeEach(() =&gt; {
    component.content = mockContent
  })

  it('should call show Message Items when true', () =&gt; {
    localStorage.setItem('isEditMode', 'true')
    component.showMessagesList()
    component.isEdit = localStorage.getItem('isEditMode') ?? ''
    fixture.detectChanges()
    expect(component.isEdit).toBe('true')
  })

  it('should check open dialog', () =&gt; {
    const isEdit = 'true'
    component.isEdit = isEdit.toString()
    expect(component.isEdit).toBe('true')
    jest.spyOn(component, 'showMessagesList').mockImplementationOnce(() =&gt; {
      if (isEdit === 'true') {
        expect(component.modalDialog.openModalDialog).toBeCalled()
      }
    })
  })
})
</code></pre>
",https://stackoverflow.com/questions/73470702/how-to-mock-custom-dialog-in-angular-for-unit-testing-using-jest,"['angular', 'typescript', 'unit-testing', 'jestjs']",344,False,0,1
Is no one unit testing interactions with android&#39;s generated view binding classes?,"<p>Working in new codebase that makes heavy use of Android's generated viewbinding classes. There are currently no unit tests for logic that interacts with the view binding classes. I tried adding some tests but I am unable to mock the viewbinding class unless I use the Powermock whitebox api, which uses reflection to mock out the fields on the class. Seems like a code smell so I'm wondering if no one else has run into this or if everyone else uses the whitebox tools. Makes me wonder if using <code>findViewById</code> might be the better solution for referencing views.</p>
",https://stackoverflow.com/questions/71593203/is-no-one-unit-testing-interactions-with-androids-generated-view-binding-classe,"['android', 'unit-testing', 'mockito', 'android-viewbinding']",275,False,0,0
Python Unit Testing: How is function automatically called without providing function name?,"<p>I am looking into the codes in vanilla_vae <a href=""https://github.com/AntixK/PyTorch-VAE/blob/master/models/vanilla_vae.py"" rel=""nofollow noreferrer"">here</a> and its unit test test_vae <a href=""https://github.com/AntixK/PyTorch-VAE/blob/master/tests/test_vae.py"" rel=""nofollow noreferrer"">here</a>.</p>
<p>In the code snippet of test_vae below, I am confused as to how <strong>self.model(x)</strong> portion in <strong>test_loss(self)</strong> function directly calls VanillaVAE class's forward method without mentioning the function name. Could anyone provide me insight on this?</p>
<pre><code>def setUp(self) -&gt; None:
    # self.model2 = VAE(3, 10)
    self.model = VanillaVAE(3, 10)

def test_loss(self):
    x = torch.randn(16, 3, 64, 64)

    result = self.model(x)
    loss = self.model.loss_function(*result, M_N = 0.005)
    print(loss)
</code></pre>
",https://stackoverflow.com/questions/72434643/python-unit-testing-how-is-function-automatically-called-without-providing-func,"['python', 'unit-testing']",58,True,0,2
How to do unit testing of ViewData in razor pages using Nunit?,"<p>I am trying to create a simple unit test to test this function that return data from a repository. When i comment out the Viewdata the test is working as expected. My question is how can i test this repository call with the Viewdata In it. Thanks For Your Help!</p>
<pre><code>     public async Task&lt;GridItem&gt; LoadItemDetailByItemIdAsync(int ItemId)
        {
          //calling repostiory
            var result = await _itemsQueryRepository.LoadItemDetailByItemIdAsync(ItemId);


          **setting the repository result to viewdata to be used
          this is returning NULL expception error in my test below**
            ViewData[&quot;CircuitDetails&quot;] = result;

            return result;
        }

</code></pre>
<p>This is Unit Test that i was creating but getting an error whenever it tries to test the viewdata.</p>
<pre><code>  [Test]
        public async Task LoadItemDetail_ReturnsData()
        {
            //Arrange
            int ItemId = 6;

            var ItemDetail = new ListItemContainer&lt;GridItem&gt;();
            ItemDetail.Items.Add(new GridItem()
            {
                AccountTypeId = 1,
                ItemIdStatus = 6,
                ItemTypeId = 1,
                ItemCostNumber = &quot;0504&quot;,
                Comments = &quot;Send Help&quot;
            });
          
            var tcs = new TaskCompletionSource&lt;ListItemContainer&lt;GridItem&gt;&gt;();
            tcs.SetResult(ItemDetail);
            _iItemQueryRepositoryMock.Setup(m =&gt; m.LoadItemDetailByItemIdAsync(It.IsAny&lt;int&gt;())).Returns(tcs.Task);

            //Act
            var itemModel = new itemsModel(_itemsQueryRepository,
                                                _contextAccessor, _loggerItemModel);


          **This returns a Null Exception error when it hit the Respository ViewData**

           var actionResult = await circuitModel.LoadItemDetailByItemIdAsync(ItemId);


            ////Assert
            Assert.NotNull(actionResult);
        }
</code></pre>
",https://stackoverflow.com/questions/73593460/how-to-do-unit-testing-of-viewdata-in-razor-pages-using-nunit,"['c#', '.net', 'unit-testing', 'nunit', 'razor-pages']",79,False,0,0
Unit testing component throwing transform is not a function for a pipe,"<p>in my component class i have following get method:</p>
<pre><code>get getCSVForDownload() {
    return defer(() =&gt; {
        this.downloadingData = true;
        return this.csvRepoService.getCSV(this.csvId).pipe(
            map((items: ICSV[]) =&gt; {
                let filteredItems = items;
                filteredItems = this.filterDateRangePipe.transform(filteredItems, this.timeFilterRange, 'createdDate');
                return filteredItems;
            }),
         );
    });
</code></pre>
<p>in the spec file of that component first I have created a mock pipe like this:</p>
<pre><code>@Pipe({ name: 'filter' })
class MockPipe implements PipeTransform {
 public transform(items: any[], timeFilterRange: TimeFilterRange, fieldName: string): any   {
     return items;
  }
}
</code></pre>
<p>And in the beforeEach i have provided the pipe in following way:</p>
<pre><code> beforeEach(async () =&gt; {

    await TestBed.configureTestingModule({
        declarations: [ABCComponent],
        imports: [
            HttpClientTestingModule,
        ],
        providers: [
            { provide: FilterDateRangePipe, useValue: MockPipe },
            { provide: SecurityService, useValue: mockSecurityService }
        ],
        schemas: [CUSTOM_ELEMENTS_SCHEMA]
    }).compileComponents();
    mockCsvRepoService = TestBed.inject(CsvRepoService );
    spyOn(mockCsvRepoService, 'getCSV').and.returnValue(of(testCSVs));
});
</code></pre>
<p>And the test I have written is following:</p>
<pre><code>it('Should call getCSV when downloadCSV triggered', fakeAsync(() =&gt; {
    component.getCSVForDownload.subscribe()
    expect(mockCsvRepoService.getCSV).toHaveBeenCalled()
    flush();
  }));
</code></pre>
<p>Though I have provided mock object for FilterDateRangePipe which has transform method in it, I am still getting error like following</p>
<pre><code> TypeError: this.filterDateRangePipe.transform is not a function
</code></pre>
<p>What I am missing?</p>
",https://stackoverflow.com/questions/72675291/unit-testing-component-throwing-transform-is-not-a-function-for-a-pipe,"['angular', 'karma-jasmine', 'angular-pipe', 'angular-unit-test']",488,True,0,1
How to run unit testing for an Angular app on Gitlab CI?,"<p>I want to run unit testing on my Angular library using the Gitlab CI. The tests are working and succeeding on my local machine, but they don't see to be run at all on Gitlab. I have tried editing my test script to run the steps described <a href=""https://medium.com/@JohanPujol/test-unitaires-en-angular-avec-angular-cli-et-gitlab-ci-6c6124dfe7b9"" rel=""nofollow noreferrer"">here</a>, but to no avail. Here is the log of my test stage :</p>
<pre><code>Running with gitlab-runner 14.8.0~beta.44.g57df0d52 (57df0d52)
  on blue-4.shared.runners-manager.gitlab.com/default J2nyww-s
Preparing the &quot;docker+machine&quot; executor 00:33
Using Docker executor with image node:latest ...
Pulling docker image node:latest ...
Using docker image sha256:f8c8d04432c3686347434420abcc20646237c5685b4b11a7db63df7acb866cd6 for node:latest with digest node@sha256:a0590a265b222387d756ba357c4a9875778f1a7638ac011f3fb4942d3b7ae5c0 ...
Preparing environment 00:03
Running on runner-j2nyww-s-project-33286021-concurrent-0 via runner-j2nyww-s-shared-1644574459-102eb0f3...
Getting source from Git repository 00:03
$ eval &quot;$CI_PRE_CLONE_SCRIPT&quot;
Fetching changes with git depth set to 20...
Initialized empty Git repository in /builds/xxxxx/my-project/.git/
Created fresh repository.
Checking out 6c0fbcdf as main...
Skipping Git submodules setup
Restoring cache 00:15
Checking cache for 9e7cd7eec847386573b03db5adf9ef87d7c957c2...
Downloading cache.zip from https://storage.googleapis.com/gitlab-com-runners-cache/project/xxxx/cache
Successfully extracted cache
Checking cache for main...
Downloading cache.zip from https://storage.googleapis.com/gitlab-com-runners-cache/project/xxxx/main 
Successfully extracted cache
Executing &quot;step_script&quot; stage of the job script
Using docker image sha256:f8c8d04432c3686347434420abcc20646237c5685b4b11a7db63df7acb866cd6 for node:latest with digest node@sha256:a0590a265b222387d756ba357c4a9875778f1a7638ac011f3fb4942d3b7ae5c0 ...
$ npm ci --cache .npm --prefer-offline
npm WARN deprecated flatten@1.0.3: flatten is deprecated in favor of utility frameworks such as lodash.
npm WARN deprecated source-map-resolve@0.6.0: See https://github.com/lydell/source-map-resolve#deprecated
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
added 1308 packages, and audited 1524 packages in 32s
129 packages are looking for funding
  run `npm fund` for details
43 moderate severity vulnerabilities
To address issues that do not require attention, run:
  npm audit fix
To address all issues, run:
  npm audit fix --force
Run `npm audit` for details.
$ { # collapsed multi-line command
@my-group:registry=https://gitlab.com/api/v4/packages/npm/
//gitlab.com/api/v4/packages/npm/:_authToken=[MASKED]
//gitlab.com/api/v4/projects/xxxxx/packages/npm/:_authToken=[MASKED]
$ cd projects/my-lib
$ npm test
&gt; @my-group/my-lib@1.1.6 test
&gt; ng test
Node.js version v17.5.0 detected.
Odd numbered Node.js versions will not enter LTS status and should not be used for production. For more information, please see https://nodejs.org/en/about/releases/.
- Generating browser application bundles (phase: setup)...
11 02 2022 10:16:45.662:WARN [karma]: No captured browser, open http://localhost:9876/
11 02 2022 10:16:45.765:INFO [karma-server]: Karma v6.3.15 server started at http://localhost:9876/
11 02 2022 10:16:45.772:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
11 02 2022 10:16:45.784:INFO [launcher]: Starting browser Chrome
11 02 2022 10:16:45.785:ERROR [launcher]: No binary for Chrome browser on your platform.
  Please, set &quot;CHROME_BIN&quot; env variable.
✔ Browser application bundle generation complete.
11 02 2022 10:17:09.953:WARN [karma]: No captured browser, open http://localhost:9876/
✔ Browser application bundle generation complete.
</code></pre>
<p>It then remains stuck on that last instruction.
Here is my test stage :</p>
<pre><code>test:
  stage: test
  script:
    - cd projects/my-lib
    - npm test
</code></pre>
<p>The new test script I tried :</p>
<pre><code>&quot;test&quot;: &quot;./node_modules/.bin/karma start karma.conf.js&quot;
</code></pre>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/71078867/how-to-run-unit-testing-for-an-angular-app-on-gitlab-ci,"['angular', 'unit-testing', 'testing', 'gitlab', 'gitlab-ci']",1486,False,0,0
Stenciljs autocomplete the unit testing files when the tsx files are changed,"<p>Is there a way to autocomplete the <code>.spec.tsx</code> file so that it matches the changes made in the <code>.tsx</code> file or every time it has to be done by hand. To be more precise, I would like to autocomplete <code>expect(page.root).toEqualHtml(RIGHT_HERE)</code>.</p>
<p>Here is an example:</p>
<pre><code>import { newSpecPage } from '@stencil/core/testing';
import { MyComp} from './mapc-events';

describe('my-component-name', () =&gt; {
  it('renders', async () =&gt; {
    const page = await newSpecPage({
      components: [MyComp],
      html: `&lt;my-component&gt;&lt;/my-component&gt;`,
      autoApplyChanges: true
    });
    expect(page.root).toEqualHtml(`
      &lt;my-component&gt;
        &lt;mock:shadow-root&gt;
          &lt;slot&gt;&lt;/slot&gt;
        &lt;/mock:shadow-root&gt;
      &lt;/my-component&gt;
    `);
  });
});
</code></pre>
",https://stackoverflow.com/questions/70743672/stenciljs-autocomplete-the-unit-testing-files-when-the-tsx-files-are-changed,['stenciljs'],172,True,0,1
How to use main function inside test function when unit testing Gin,"<p>I want to unit test gin controller function.</p>
<pre><code>package controllers

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

    &quot;github.com/gin-gonic/gin&quot;
    &quot;github.com/go-playground/assert/v2&quot;
)

func TestGetDivisions(t *testing.T) {
    tt := []struct {
        Name         string
        EnterpriseID string
        Code         int
    }{
        {Name: &quot;Enterprise id exists&quot;, EnterpriseID: &quot;1&quot;, Code: 200},
        {Name: &quot;Enterprise id cannot be string&quot;, EnterpriseID: &quot;string&quot;, Code: 404},
    }
    w := httptest.NewRecorder()
    c, _ := gin.CreateTestContext(w)

    for _, tc := range tt {
        c.Params = []gin.Param{
            {
                Key:   &quot;enterprise_id&quot;,
                Value: tc.EnterpriseID,
            },
        }
        GetDivisions(c) // Error from here
        assert.Equal(t, tc.Code, w.Code, tc.Name)
    }
}
</code></pre>
<p>Problem is, whenever I use GetDivision function inside a test file gives error like below:</p>
<pre><code>--- FAIL: TestGetDivisions (0.00s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
    panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x28 pc=0x43c7438]
</code></pre>
<p>Cannot find where is a problem. Can I give test context to a function as a parameter?</p>
<p>And here is my GetDivisions handler:</p>
<pre><code>// Get divisions of an enterprise by given id. Default id = &quot;1&quot;
func GetDivisions(c *gin.Context) {
    var divisions []models.Division

    if err := config.DB.Find(&amp;divisions).Error; err != nil {
        c.JSON(http.StatusInternalServerError, err.Error())
        return
    }

    c.JSON(http.StatusOK, gin.H{
        &quot;divisions&quot;: divisions,
    })
}
</code></pre>
",https://stackoverflow.com/questions/72435413/how-to-use-main-function-inside-test-function-when-unit-testing-gin,"['unit-testing', 'go', 'go-gin']",180,False,0,1
Angular Unit testing - Test case is not passing with mocking child component,"<p>When I try to pass child component @Input() Property from parent it's throwing error.
Child component input property is undefined always.</p>
<p>Please check this error:
<a href=""https://i.stack.imgur.com/9T2Ii.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/9T2Ii.png"" alt=""enter image description here"" /></a></p>
<blockquote>
<p>Expected undefined to equal Object</p>
</blockquote>
<pre><code>
@Component({
  selector: &quot;ce-customer-profile-image&quot;,
})
class MockCECustomerProfileImageComponent
{
  @Input() customer;
}

describe(&quot;CustomerProfileInfo Component&quot;, () =&gt; {
  let component: CustomerProfileInfoComponent;
  let mockComponent: MockCECustomerProfileImageComponent;

  let fixture: ComponentFixture&lt;CustomerProfileInfoComponent&gt;;

  beforeEach(waitForAsync(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [CustomerProfileInfoComponent,MockCECustomerProfileImageComponent],
      imports: [],providers: [],schemas: [CUSTOM_ELEMENTS_SCHEMA],
    })
      .overrideModule(BrowserDynamicTestingModule, {})
      .compileComponents()
      .then(() =&gt; {
        fixture = TestBed.createComponent(CustomerProfileInfoComponent);
        component = fixture.debugElement.componentInstance;
        component.customer = {
          Email: &quot;vk@test.com&quot;,
          Phone: &quot;(123) 456-7890&quot;,
          FirstName: &quot;testV&quot;,
          LastName: &quot;testK&quot;,
          CustomerId: null,
          CustomerAddress: null,
        };
        component.customerAddress = null;
        fixture.detectChanges();
      });
  }));


  it(&quot;CustomerProfileInfoComponent for anonymous customer&quot;, () =&gt; {
    
    fixture.detectChanges();

    mockComponent = TestBed.createComponent(MockCECustomerProfileImageComponent)
        .debugElement.componentInstance;
    
    expect(mockComponent.customer).toEqual(component.customer);
  });
});
</code></pre>
<p>Please help me if i'm missing something from above snippet.</p>
",https://stackoverflow.com/questions/72682930/angular-unit-testing-test-case-is-not-passing-with-mocking-child-component,"['unit-testing', 'karma-jasmine', 'angular-unit-test']",168,False,0,0
Unit testing: can expected output be considered as part of test &quot;fixture&quot;?,"<p>Not sure if it's a common norm in unit testing nomenclature, but I've been writing some of my Jest unit tests like the following, and it just doesn't feel right to group the expected output with the given input(s) as <code>fixture</code>:</p>
<pre class=""lang-js prettyprint-override""><code>describe('24-25', () =&gt; {
  test('test 24', () =&gt; {
    // given
    const fixture = {
      givenInput: 24,
      expectedOutput: 50,
    };

    // when, then
    testDoubleInc(fixture);
  });

  test('test 25', () =&gt; {
    // given
    const fixture = {
      givenInput: 25,
      expectedOutput: 52,
    };

    // when, then
    testDoubleInc(fixture);
  });

  function testDoubleInc({ givenInput, expectedOutput }) {
    expect(doubleInc(givenInput)).toEqual(expectedOutput);
  }
});

// Unit Under Test
function doubleInc(x) {
  return (x + 1) * 2;
}
</code></pre>
<p>So the question is, have I been misusing the term &quot;fixture&quot; there? And if so, would it be more precise/correct in writing it this way instead?</p>
<pre class=""lang-js prettyprint-override""><code>// given
const fixture = {
  givenInput: 24,
};
const expectedOutput = 50;

// when, then
testDoubleInc({ givenInput: fixture.givenInput, expectedOutput });
</code></pre>
",https://stackoverflow.com/questions/73938632/unit-testing-can-expected-output-be-considered-as-part-of-test-fixture,"['unit-testing', 'testing', 'jestjs']",43,False,0,0
How can I use .NET Core FirebaseAdminSdk for Unit Testing with Moq,"<p>I have been working on .NET Core FirebaseAdminSdk. I want to write unit tests for my own services that are using FirebaseApp class.
FirebaseApp is a sealed class and there is not any interface to moq it.</p>
<p>Is there any way to mock FirebaseApp instance?</p>
<pre><code>private readonly Mock&lt;IFirebaseApp&gt; firebaseApp = new Mock&lt;IFirebaseApp&gt;();
</code></pre>
<p>I need an interface something like this.</p>
",https://stackoverflow.com/questions/74315493/how-can-i-use-net-core-firebaseadminsdk-for-unit-testing-with-moq,"['unit-testing', 'mocking', 'asp.net-core-webapi', 'firebase-admin']",109,False,0,1
How do you do Unit Testing with ASP.NET Core and AWS DynamoDB?,"<p>I have written my first microservice (Web API) in ASP.NET core 3 that uses my AWS DynamoDB.
I have a repository and controller (and more but I think you only need this information):</p>
<p><strong>Controller:</strong></p>
<pre><code>[Route(&quot;[controller]&quot;)]
public class FollowersController : Controller
{
    private IFollowersRepository _repository;
    private IConfiguration _configuration;


    public FollowersController(IFollowersRepository repository, IConfiguration configuration)
    {
        _repository = repository;
        _configuration = configuration;
    }
    
    

    [HttpGet]
    public async Task&lt;IEnumerable&lt;Follower&gt;&gt; GetAllFollowers(Guid userId)
    {
        return await _repository.All(userId);
    }

    [HttpPost]
    [Route(&quot;Create&quot;)]
    public async Task&lt;ActionResult&gt; Create(FollowerInputModel model)
    {
        await _repository.Add(model);
        SQSProcessor processor = new SQSProcessor(_configuration);
        await processor.SQSPost(model);
        return Ok(model);
    }

    [HttpDelete]
    [Route(&quot;Delete&quot;)]
    public async Task&lt;ActionResult&gt; Delete(FollowerInputModel follower)
    {
        await _repository.Remove(follower);
        SQSProcessor processor = new SQSProcessor(_configuration);
        await processor.SQSRemove(follower);
        return NoContent();
    }
}
</code></pre>
<p><strong>Repository:</strong>
public class FollowersRepository : IFollowersRepository
{</p>
<pre><code>    private readonly AmazonDynamoDBClient _client;
    private readonly DynamoDBContext _context;

    public FollowersRepository()
    {

        _client = new AmazonDynamoDBClient();
        _context = new DynamoDBContext(_client);
    }

    public async Task Add(FollowerInputModel entity)
    {
        var follower = new Follower
        {
            UserId = entity.UserId,
            FollowerId = entity.FollowerId,
        };
        
         await _context.SaveAsync(follower);
    }

    public async Task&lt;IEnumerable&lt;Follower&gt;&gt; All(Guid userId)
    {
        return await _context.QueryAsync&lt;Follower&gt;(userId).GetRemainingAsync();
    }

    public async Task Remove(FollowerInputModel entity)
    {
        var follower = new Follower
        {
            UserId = entity.UserId,
            FollowerId = entity.FollowerId,
        };
        var _follower = await _context.LoadAsync&lt;Follower&gt;(follower);
        await _context.DeleteAsync(_follower);
    }
</code></pre>
<p>Now I get very confused about what to test and how to test it since there does not really happens much logic within the controller or the repository. Do I even need to write tests and if so can somebody link me to an example that has such tests for the remove and add methods of the class that I should test?</p>
<p>I have read the other post about this but could not help me really.</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/74044907/how-do-you-do-unit-testing-with-asp-net-core-and-aws-dynamodb,"['amazon-web-services', 'unit-testing', 'moq', 'xunit.net']",47,False,0,0
Spring Boot Response Entity Is Returning Null While Unit Testing Rest Controller,"<p>I'm trying to unit test my Controller which returns a ResponseEntity but when I'm testing it using restTemplate the value in <strong>response</strong> is coming as null. Please help.</p>
<p>UserControllerTest :</p>
<pre><code>@MockBean
RoleService roleService;
@Autowired
TestRestTemplate restTemplate;
@Test
public void testGetAllRoles() throws ResourceNotFoundException {
    List&lt;Role&gt; roleList = new ArrayList&lt;&gt;();
    Role role = new Role(1l, &quot;ROLE_SUPER_ADMIN&quot;, &quot;Super Admin&quot;);
    roleList.add(role);
    User user = new User(&quot;FirstName&quot;, &quot;LastName&quot;, &quot;testEmail&quot;, &quot;credential&quot;, roleList);

    when(roleService.getAllRoles()).thenReturn(Arrays.asList(role));

    ResponseEntity&lt;List&lt;Role&gt;&gt; response = restTemplate.exchange(&quot;/user/getAllRoles&quot;, GET,
            loggedInAs(&quot;testEmail&quot;, &quot;ROLE_SUPER_ADMIN&quot;), new ParameterizedTypeReference&lt;List&lt;Role&gt;&gt;() {
            });

    assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
    System.out.println(response.getBody());
    //assertEquals(response.getBody().get(0).getCode(), role.getCode());
}
</code></pre>
<p>UserController:</p>
<pre><code>@Autowired
RoleService roleService;
@GetMapping(&quot;/user/getAllRoles&quot;)
@Operation(summary = &quot;get a list of all Roles&quot;)
@PreAuthorize(&quot;hasAnyRole('ROLE_SUPER_ADMIN', 'ROLE_SYSTEM_ADMIN', 'ROLE_SALES_USER')&quot;)
public ResponseEntity&lt;List&lt;Role&gt;&gt; getAllRoles() throws ResourceNotFoundException {
    return responseHelper.response(null, roleService.getAllRoles(), HttpStatus.OK);
}
</code></pre>
<p>RoleService:</p>
<pre><code>@Override
public List&lt;Role&gt; getAllRoles() throws ResourceNotFoundException {
    List&lt;Role&gt; roles = roleRepository.findAll();
    if (CollectionUtils.isEmpty(roles)) {
        throw new ResourceNotFoundException(env.getProperty(ConstantsUtil.APP_MODULE_ROLE), env.getProperty(ConstantsUtil.ROLE_NOT_FOUND));
    }
    return roles;
}
</code></pre>
<p>Role:</p>
<pre><code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;

@Column(name = &quot;code&quot;, length = 50)
private String code;

@Column(name = &quot;description&quot;, length = 100)
private String description;

@Override
public String getAuthority() {
    return code;
}   
</code></pre>
<p>Please help</p>
",https://stackoverflow.com/questions/73181883/spring-boot-response-entity-is-returning-null-while-unit-testing-rest-controller,"['java', 'spring-boot', 'response', 'resttemplate', 'spring-boot-test']",654,False,0,1
Unit testing ( this is where I am at now in my training ),"<p>WARNING: Error parsing requirements for pywinpty: [Errno 2] No such file or directory</p>
<p>This is what I get when I try to pip install pylint</p>
<p>I am also using a pycham environment</p>
<p>I tried pip install pywinpty to see if it will work but nop..</p>
<p>I tried some directory changes but nop....</p>
",https://stackoverflow.com/questions/73660843/unit-testing-this-is-where-i-am-at-now-in-my-training,"['python', 'unit-testing', 'command-line', 'command', 'pylint']",15,False,0,1
JS: Unit testing a class function without making the actual API call?,"<p>I have a simple class <code>Foo</code> in Typescript.  What is the best way to unit test this without actually making the API call?</p>
<p>I can't think of anything to spy or stub since I don't want it actually calling my real endpoint. Are there still tests to write for it?</p>
<pre><code>class Foo {
    private _names: Array;

    constructor(private _accessToken: string, private _environment: string) {}


   async getInclusiveData(name: String) {
     
        const config = {
            method: &quot;post&quot;,
            headers: HEADER_INFO
        };

        const response = await fetch(`${baseURL}/v1/variations/match`, config);
        
        const { results } = (await response.json()) as any;

        this._names = results;

        return this._names;
}
</code></pre>
<p>All I ended up doing was:</p>
<pre><code>beforeEach(() =&gt; {
    const fakeToken = &quot;12345&quot;;
    const env = &quot;prod&quot;;

    foo = new Foo(fakeToken, env);

    getInclusiveDataSpy = sinon.spy(foo, &quot;getInclusiveData&quot;);
});
</code></pre>
<p>but in order to get that spy to run, I'd have to invoke: <code>foo.getInclusiveData()</code> so it doesn't feel like I'm really testing anything</p>
",https://stackoverflow.com/questions/72721041/js-unit-testing-a-class-function-without-making-the-actual-api-call,"['javascript', 'typescript', 'unit-testing', 'testing', 'sinon']",399,False,0,1
Swift: Unit testing delegate methods with 3rd party class as an argument,"<p>I know how to unit test with 3rd party dependencies by extending the class with your own protocol so that you can inject a mock dependency that implements that same protocol.</p>
<p>But this only seems to work if the 3rd party dependency doesn't make use of the delegate pattern, as the delegate methods tend to have arguments that have the type of the dependency:</p>
<pre><code>protocol DependencyDelegate {
  func doSomething(_ dependency: Dependency)
}
</code></pre>
<p>Ideally I'd be able to replace <code>Dependency</code> from the line above with the protocol I made the dependency conform to so that I can pass in the mock dependency during unit testing.</p>
<p>Here is the full example scenario where <code>Dependency</code> and <code>DependencyDelegate</code> are defined by a 3rd part framework:</p>
<pre><code>extension Dependency: DependencyProtocol {}

class MyClass: DependencyDelegate {
  private let dependency: DependencyProtocol

  init(dependency: DependencyProtocol) {
    self.dependency = dependency
  }

  func doSomething(_ dependency: Dependency) {

  }
}

protocol DependencyDelegate {
  func doSomething(_ dependency: Dependency) // &lt;---- How do I deal with this in unit tests?
}

class MockDependency: DependencyProtocol {
  ...
}

class MyClassTests: XCTestCase {
  func test() {
    let myClass = MyClass(dependency: MockDependency())
    myClass.doSomething(
  }
}
</code></pre>
<p>How can I unit test this delegate relationship between the dependency and my class without passing in an actual instance of <code>Dependency</code> into the delegate method of <code>MyClass</code>?</p>
",https://stackoverflow.com/questions/72036107/swift-unit-testing-delegate-methods-with-3rd-party-class-as-an-argument,"['swift', 'xcode', 'unit-testing', 'xctest']",360,False,0,1
Getting the error Cannot set properties of undefined in angular unit testing,"<p>while I am writing the unit test case for dropdown I am getting the error as
<em>TypeError: Cannot set properties of undefined (setting 'ReferralCodes')</em>
<strong>.spec.ts</strong></p>
<pre><code>it(&quot;should update the action selecting a value from category drop down&quot;, () =&gt; {
    component.actionCodesLookupData.ReferralCodes =[
      {
      Name: &quot;some data&quot;,
      Id: 3,
      ActionStatus: 126
    }
    ]
    component.setActionCodesList(&quot;Referral&quot;);
    expect(component.actionCodesList).toBe(component.actionCodesLookupData.ReferralCodes);
       });

</code></pre>
<p><strong>.component.ts</strong></p>
<pre><code> public setActionCodesList(actionType: any):void{
   this.actionCodesList = [];
 
    switch(actionType){
      case ActionRecordConstant.memberContact:
      this.actionCodesList = this.actionCodesLookupData.MemberContactCodes;
     break;
      case ActionRecordConstant.referral:
        this.actionCodesList= this.actionCodesLookupData.ReferralCodes;
      break;
//some code
</code></pre>
<p>In code it is not showing the errors but test is failing showing the error as:</p>
<p><em>TypeError: Cannot set properties of undefined (setting 'ReferralCodes')</em></p>
<p>can anyone help me on this</p>
",https://stackoverflow.com/questions/72363640/getting-the-error-cannot-set-properties-of-undefined-in-angular-unit-testing,"['angular', 'jasmine', 'karma-jasmine', 'karma-runner']",2852,False,0,1
Launching an R background process/thread/etc. using current environment for unit testing,"<p>Since <code>callr::r</code> and <code>callr::r_bg</code> launch a background process in a clean environment, they do not fit neatly into unit test paradigms. An R unit test, run via testthat, loads the current development version of the package, but any background process launched by the unit test -- a plumber API, for example, which one might want to test -- will use the system package instead. Here is some slightly obfuscated output to show what I mean:</p>
<pre><code>&gt; system.file(&quot;plumber&quot;, &quot;api&quot;, &quot;entrypoint.R&quot;, package = &quot;DemoPackage&quot;)
[1] &quot;/path/to/dev/directory/for/DemoPackage/inst/plumber/api/entrypoint.R&quot;
&gt; callr::r(function() {system.file(&quot;plumber&quot;, &quot;api&quot;, &quot;entrypoint.R&quot;, package = &quot;DemoPackage&quot;)})
[1] &quot;/home/user_directory/R/x86_64-redhat-linux-gnu-library/3.6/DemoPackage/plumber/api/entrypoint.R&quot;
</code></pre>
<p>Variations of the above (passing the system.file output to <code>plumber::plumb</code>, using <code>plumber::plumb_api</code> directory, etc.) all work out about the same, meaning that attempts to make a unit test that tests the development version of the API fail.</p>
<p>My current workaround has been to run <code>devtools::load_all()</code> from within the function run by <code>callr::r_bg</code>, and also pass in the <code>system.file(...)</code> path to the function, so that the background process loads the dev version of the package and find the dev version of the plumber script. This has mixed success -- it works as intended when running the unit tests, except when they are run by <code>devtools::check()</code> in which case there is an error (because the working directory differs and <code>devtools::load_all()</code> breaks).</p>
<p>What's the best way of getting this test setup to work? I imagine the solution would be involve getting directory or package path and passing it to callr, or passing an environment, but I'm not sure which direction to go in.</p>
<p><strong>Update</strong></p>
<p>Running into this issue again, I found my own question while searching. A new wrinkle is that I am working on measuring unit test coverage via the <code>covr</code> package, which works by modifying objects in the environment to track usage and so doesn't track usage within the background sessions. I'm not sure whether proper coverage tracking would come for free by starting a background session inheriting the current environment (for one, the coverage statistics from that session may not be communicated to the working session's statistics) but it would at least be one step closer.</p>
",https://stackoverflow.com/questions/73127213/launching-an-r-background-process-thread-etc-using-current-environment-for-unit,"['r', 'unit-testing', 'testthat', 'callr', 'covr']",143,False,5,0
Validation of submitEntities Method does not run when mocked at unit testing,"<p>I'm working on a legacy project which is created with .NET Framework 4.8, locator pattern, and business factory to instantiate businesses.</p>
<p>I'm trying to add unit tests using MSTest and MOQ.
The <code>SubmitEntities</code> method in mocked business does not run validations. I mean when I run a test that is expected to throw an exception, it passes successfully. I have no idea why is this happening.</p>
<p>Also, I don't have experience in writing unit tests and this is my first time.</p>
<p><strong>In short</strong>, I'm expecting to get exception when the test is run, but it finishes with <code>submittedBalanceMappings</code> with a count of more than zero.</p>
<p>The test class constructor is:</p>
<pre><code>private readonly BalanceMappingBusinessService _balanceMappingBusinessService;
private readonly Mock&lt;IBalanceMappingBusiness&gt; _mockBalanceMappingBusiness = new Mock&lt;IBalanceMappingBusiness&gt;();
    
public BalanceMapping()
{
     _balanceMappingBusinessService = new BalanceMappingBusinessService(_mockBalanceMappingBusiness.Object);
}
</code></pre>
<p>The test is:</p>
<pre><code>[TestMethod]
public async Task SubmitEntities_NoDataWillBeSubmitted_IfColumnSettingIdDoesNotExist()
{
    // Arrange
    await LoginWithSuperAdminAccount();

    var submittingBalanceMappings = new List&lt;BalanceMappingEntity&gt;
    {
        new BalanceMappingEntity
        {
            AdjustedBalanceDetailId = adjutedBalanceDetailId,
            ColumnSettingId = Guid.NewGuid(),
            EntityState = EntityState.Added
        }
    };

    var submittedBalanceMappings = new List&lt;BalanceMappingEntity&gt;();

    _mockBalanceMappingBusiness.Setup(
        bmb =&gt; bmb.SubmitEntities(submittingBalanceMappings))
        .Callback((List&lt;BalanceMappingEntity&gt; balanceMappings) =&gt; submittedBalanceMappings.AddRange(balanceMappings));


    var adjutedBalanceDetailId = GetAdjustedBalanceDetail();

    //Act
    _balanceMappingBusinessService.SubmitEntities(submittingBalanceMappings );

    // Assert
    Assert.IsTrue(submittedBalanceMappings.Count == 0);
}
</code></pre>
<p>The SubmitEntities method is:</p>
<pre><code>public void SubmitEntities(List&lt;BalanceMappingEntity&gt; balanceMappings)
{
    try
    {
        ValidateSubmittingBalanceMappings(balanceMappings);

        using var onlineUnitOfWork = new OnlineUnitOfWork();

        foreach (var balanceMapping in balanceMappings)
        {
            balanceMapping.AccountId = ReusableObjects.Current.CurrentAuthenticatedAccountId;

            onlineUnitOfWork.Submit(balanceMapping);
        }

        onlineUnitOfWork.SaveChanges();
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
</code></pre>
",https://stackoverflow.com/questions/71110736/validation-of-submitentities-method-does-not-run-when-mocked-at-unit-testing,"['c#', '.net', 'unit-testing', 'testing', 'moq']",40,False,0,0
Simple gORM unit testing but failed when testing multiple case using subtest,"<p>I am setting a simple unit test for my gORM function like this.</p>
<pre class=""lang-golang prettyprint-override""><code>func (o *OrderStorage) FindByID(ID uint) (*Order, error) {
    var order Order
    result := o.db.First(&amp;order, ID)

    if result.Error != nil {
        return nil, result.Error
    }

    return &amp;order, nil
}

func testOrderStorage_FindByID(o OrderService) func(t *testing.T) {
    return func(t *testing.T) {
        type args struct {
            ID uint
        }
        tests := []struct {
            name string
            args args
        }{
            {
                name: &quot;2nd Order&quot;,
                args: args{
                    ID: 2,
                },
            },
            // {
            //  name: &quot;3rd Order&quot;,
            //  args: args{
            //      ID: 3,
            //  },
            // },
            // {
            //  name: &quot;1st Order&quot;,
            //  args: args{
            //      ID: 1,
            //  },
            // },
        }
        for _, tt := range tests {
            tt := tt
            t.Run(tt.name, func(t *testing.T) {
                got, err := o.FindByID(tt.args.ID)
                if err != nil {
                    t.Errorf(&quot;OrderStorage.FindByID() error = %v ID %d&quot;, err, tt.args.ID)
                    return
                }
                t.Logf(&quot;OrderStorage.FindByID() result = %+v ID = %d&quot;, *got, tt.args.ID)
            })
        }
    }
}
</code></pre>
<p>You guys can see that I have 3 test cases. If I test them one by one, they all work correctly. But if I uncomment all of them then run the test in one time, the first test case will be passed but the rest of them will be failed. The gorm fail logs here:</p>
<pre><code>2022/01/29 12:55:50 /home/pc/backend/repository/order/order.go:28 record not found
[0.780ms] [rows:0] SELECT * FROM &quot;test_orders&quot; WHERE &quot;test_orders&quot;.&quot;id&quot; = 2 AND &quot;test_orders&quot;.&quot;deleted_at&quot; IS NULL AND &quot;test_orders&quot;.&quot;id&quot; = 3 ORDER BY &quot;test_orders&quot;.&quot;id&quot;,&quot;test_orders&quot;.&quot;id&quot; LIMIT 1
</code></pre>
<p>I have no idea why the query of the second test case have the <code>WHERE &quot;test_orders&quot;.&quot;id&quot; = 2</code> which is the ID from the first case.</p>
<p>Can anybody explain that to me? Thanks!</p>
",https://stackoverflow.com/questions/70902786/simple-gorm-unit-testing-but-failed-when-testing-multiple-case-using-subtest,"['go', 'testing', 'go-gorm']",35,False,0,0
Getting &quot;RangeError: Maximum call stack size exceeded&quot; when unit testing with mongodb-memory-server,"<p>I am trying to unit test some typescript logic with <a href=""https://github.com/facebook/jest"" rel=""noreferrer"">jest</a>. I am using <a href=""https://github.com/Automattic/mongoose"" rel=""noreferrer"">mongoose</a> in order to interact with the mongo database and <a href=""https://github.com/nodkz/mongodb-memory-server"" rel=""noreferrer"">mongo-memory-server</a> in order to mock mongodb.</p>
<p>For unclear reason, I get the following error, which seems to result from cyclic dependencies, when running the below unit test.</p>
<p>Error:</p>
<pre><code>  ● Test suite failed to run

    RangeError: Maximum call stack size exceeded

      at Object.get [as ObjectId] (node_modules/mongoose/node_modules/mongodb/src/bson.ts:38:3)
      at Object.get [as ObjectId] (node_modules/mongoose/node_modules/mongodb/src/bson.ts:38:3)
</code></pre>
<p>Unit Test:</p>
<pre><code>import mongoose, { Mongoose } from &quot;mongoose&quot;;
import { MongoMemoryServer } from &quot;mongodb-memory-server&quot;;

describe(&quot;test mongo memory server&quot;, () =&gt; {
    let client: Mongoose;
    let mongod;

    beforeAll(async () =&gt; {
      mongod = await MongoMemoryServer.create();
      client = await mongoose.connect(mongod.getUri());
    });

    afterAll(async () =&gt; {

      if (mongod) {
        await mongod.stop();
      }
    });

    it(&quot;empty test&quot;, async () =&gt; {
    });
});

</code></pre>
<p>Used Versions in <code>package.json</code>:</p>
<pre><code>...  &quot;dependencies&quot;: {
        &quot;typescript&quot;: &quot;4.6.3&quot;,
        &quot;mongoose&quot;: &quot;6.2.9&quot;, // required for mongo 5.0
     },
     &quot;devDependencies&quot;: {
        &quot;jest&quot;: &quot;27.5.1&quot;,
        &quot;mongodb-memory-server&quot;: &quot;8.4.2&quot;,
     }
</code></pre>
<p>P.S:</p>
<ol>
<li>When commenting out the connection to mongo (<code>client = await mongoose.connect(mongod.getUri());</code>), and using <code>mongo-memory-server</code> (version: 7.6.3) the below unit test passes. On the other hand, when the line is not commented out, it fails.</li>
<li>When commenting out the connection to mongo (<code>client = await mongoose.connect(mongod.getUri());</code>), but using latest <code>mongo-memory-server</code>, version 8.4.2 - the test fails.</li>
</ol>
",https://stackoverflow.com/questions/71743639/getting-rangeerror-maximum-call-stack-size-exceeded-when-unit-testing-with-mo,"['typescript', 'mongodb', 'unit-testing', 'mongoose', 'jestjs']",1933,True,9,2
Starting the instance of mongodb-memory-server failed on Unit Testing with Jest,"<p>I have a micro service running with <strong>Express</strong> and save data to <strong>MongoDB</strong> using <strong>mongoose 6.x.x</strong> version. I am trying to test it with <strong>supertest</strong> and <strong>jest</strong>.</p>
<p>I'm setting up some hooks to create an instance of <strong>Mongo Memory Server</strong> on version <strong>8.x.x</strong>, using the beforeAll hooks as showed in the example:</p>
<pre><code>import { MongoMemoryServer } from 'mongodb-memory-server';
import mongoose from 'mongoose';
 
let mongod: any;
 
beforeAll(async () =&gt; {
  mongod = await MongoMemoryServer.create();
  const uri = mongod.getUri();
  await mongoose.connect(uri);
});
</code></pre>
<p><em>The mongod variable tries to reach a global scope.</em></p>
<p>At this point I get the error:</p>
<blockquote>
<p>Starting the instance failed, enable debug for more information.</p>
</blockquote>
<p>Therefore, I cannot use the instance in tests. I have enabled debug mode. And I get this errors about the mongo instance:</p>
<blockquote>
<p>MongoMS:MongoInstance Mongo[52463]: start: Starting Processes +8ms<br />
MongoMS:MongoInstance Mongo[52463]: _launchMongod: Launching Mongod
Process +1ms   MongoMS:MongoInstance Mongo[52463]: prepareCommandArgs
+0ms   MongoMS:MongoInstance Mongo[52463]: prepareCommandArgs: final argument
array:[&quot;--port&quot;,&quot;52463&quot;,&quot;--dbpath&quot;,&quot;/var/folders/wt/d0s3lj915wd5pyvc9r7zdfx40000gn/T/mongo-mem--10268-fsntc7R8OJql&quot;,&quot;--storageEngine&quot;,&quot;ephemeralForTest&quot;,&quot;--bind_ip&quot;,&quot;127.0.0.1&quot;,&quot;--noauth&quot;] +0ms
MongoMS:MongoMemoryServer Mongo[unknown]: stop: Called .stop() method +23ms
MongoMS:MongoMemoryServer Mongo[unknown]: stop: &quot;instanceInfo&quot; is not defined (never ran?) +0ms</p>
</blockquote>
<p>The error is genereted because instance is not defined and I am trying to call mongod.stop in afterAll hooks to stop the instance.</p>
<p>Anyone has an idea of this?</p>
",https://stackoverflow.com/questions/70907062/starting-the-instance-of-mongodb-memory-server-failed-on-unit-testing-with-jest,"['node.js', 'mongodb', 'mongoose']",3415,True,3,1
How to mock system call in C++ Unit Testing during runtime using GoogleMock?,"<p>I have a module written in C. In which I have API defined as follow.</p>
<pre><code>int ReadData(void* data, int data_size, char* filename, int offset)
</code></pre>
<p>When performing unit test in order to cover full coverage I need to hit at error condition for fseek and fread system call.
Can somebody explain me How can I override fseek/fread during particular test case so instead of system call it will call mock fseek/fread for that test case ?</p>
<pre><code>ReadAPI.c
</code></pre>
<pre><code>#include&lt;stdio.h&gt;
#include&lt;stdlib.h&gt;

int readdata(void* data,int size, int offset, char* filename)
{
    if(data == NULL || size == 0 || filename == NULL)
    {
        return -1;
    }

    FILE* fp = fopen(filename,&quot;rb&quot;);
    if(fp == NULL)
    {
        return -1;
    }

    if(fseek(fp,offset,SEEK_SET) != 0)
    {
        fclose(fp);
        return -1;
    }

    fread(data,size,1,fp);

    if(ferror(fp))
    {
        fclose(fp);
        return -1;
    }   
    fclose(fp);
    return 1;
}


</code></pre>
<pre><code>readapi.h
</code></pre>
<pre><code>#include&lt;stdio.h&gt;
#include&lt;stdlib.h&gt;

int readdata(void* data,int size, int offset, char* filename)
</code></pre>
<pre><code>Test.cpp
</code></pre>
<pre><code>#include&lt;gtest/gtest.h&gt;
#include&quot;readapi.h&quot;


TEST(test, Test1fseek)
{
    // When fseek called in readdata API call mock fseek to hit fseek fail  
    // fseek(){return -1;}
    char data[10] = {0};
    int status = readdata(data,sizeof(data),0,&quot;test.txt&quot;);
    EXPECT_EQ(status, -1);  
}

TEST(test, Test2fread)
{
    //When fread called in readdata API call mock fread to hit read fail  
    // fread(){return -1;}
    char data[10] = {0};
    int status = readdata(data,sizeof(data),0,&quot;test.txt&quot;);
    EXPECT_EQ(status, -1);  
}

int main()
{
    return RUN_ALL_TEST();
}


</code></pre>
",https://stackoverflow.com/questions/71088486/how-to-mock-system-call-in-c-unit-testing-during-runtime-using-googlemock,"['c++', 'c', 'unit-testing', 'googletest', 'googlemock']",1883,True,3,2
"Symfony unit testing with loginUser(), login not working (returning 302 to login page)","<p>I'm building a test for a Symfony 5.4 application.</p>
<p>I have created a test like this:</p>
<pre><code>public function testCreateProduct() {
    $client = static::createClient();
    /** @var User $mainAdmin */
    $mainAdmin = static::getContainer()-&gt;get(UserRepository::class)-&gt;find(1);

    //$client-&gt;catchExceptions(false);
    $client-&gt;loginUser($mainAdmin);

    $crawler = $client-&gt;request('GET', '/en/product/new');

    $this-&gt;assertResponseIsSuccessful();
    $this-&gt;assertSelectorTextContains('span.username', $mainAdmin-&gt;getUsername());

}
</code></pre>
<p>But the login is not working, I get a 302 redirect to the login page, and if I set <code>catchExceptions(false)</code> I get an <code>AccessDeniedException</code>.</p>
<p>How can I debug this?</p>
<hr />
<p>Edit:
I tried to change the patch to a public route, then I did a <code>dd($this-&gt;getUser(), $request)</code></p>
<p><code>getUser()</code> is null, but the request session contains the user:</p>
<pre><code>#session: Symfony\Component\HttpFoundation\Session\Session {#16616
#storage: Symfony\Component\HttpFoundation\Session\Storage\MockFileSessionStorage {#16631
  -savePath: &quot;C:\www\project\var\cache\test/sessions&quot;
  #id: &quot;a9d00704e1a0211d06ebddadfaabbf0188e9d65d94faac05afbdc63bb9fb7caa&quot;
  #name: &quot;MOCKSESSID&quot;
  #started: true
  #closed: false
  #data: array:3 [
    &quot;_sf2_attributes&quot; =&gt; &amp;1 array:1 [
      &quot;_security_main&quot; =&gt; &quot;O:52:&quot;Symfony\Bundle\FrameworkBundle\Test\TestBrowserToken&quot;:2:{i:0;s:4:&quot;main&quot;;i:1;a:5:{i:0;C:15:&quot;App\Entity\User&quot;:118:{a:5:{i:0;i:2;i:1;s:5:&quot;admin&quot;;i:2;s:60:&quot;$2y$13$abcdefghi......&quot;;i:3;i:1;i:4;b:0;}}i:1;b:1;i:2;N;i:3;a:0:{}i:4;a:9:{i:0;s:9:&quot;ROLE_USER&quot;;i:1;s:10:&quot;ROLE_ADMIN&quot;;i:2;[...]}}}&quot;
    ]
    &quot;_sf2_meta&quot; =&gt; &amp;2 array:3 [
      &quot;u&quot; =&gt; 1645718565
      &quot;c&quot; =&gt; 1645718565
      &quot;l&quot; =&gt; 0
    ]
    &quot;_symfony_flashes&quot; =&gt; &amp;3 []
  ]
</code></pre>
<hr />
<p>I see a difference between
<code>$request-&gt;getSession()-&gt;getBag('attributes')</code>
done in dev (working) vs in test: in dev I have <code>_security_secured_area</code>, while in test I have <code>_security_main</code>. May this be the reason?</p>
",https://stackoverflow.com/questions/71254158/symfony-unit-testing-with-loginuser-login-not-working-returning-302-to-login,"['php', 'unit-testing', 'symfony', 'symfony5']",950,True,2,1
Unit testing Vue component that fetches data and sends to component as prop,"<p>This Vue3 component contains a service that fetches an array of workshops from the database and passes this array as a prop to its child component(s). I want to make sure that the data is the expected data and in the expected form. How might I test this? If I mock this data, I wouldn't get that assurance. Here is my component <code>WorkshopsView</code>:</p>
<pre><code>&lt;script setup lang=&quot;ts&quot;&gt;
import { useGetWorkshops } from '@/services/useGetWorkshops'
import WorkshopsGrid from '@/components/WorkshopsGrid.vue'

const { data: workshops, error: workshopsError } = useGetWorkshops()
&lt;/script&gt;
&lt;template&gt;
  &lt;div&gt;
    &lt;WorkshopsGrid :workshops=&quot;workshops&quot; :workshopsError=&quot;workshopsError&quot; /&gt;
  &lt;/div&gt;
&lt;/template&gt;
</code></pre>
<p>Here is the service <code>useGetWorkshops</code>:</p>
<pre><code>import axios from 'axios'
import useSWRV from 'swrv'

const useGetWorkshops = () =&gt;
  useSWRV('workshops', async () =&gt; {
    const response = await axios.get(`/api/workshops`)
    if (response.data.error) {
      return null
    }

    return response.data.data
  })

export default useGetWorkshops
</code></pre>
<p>Here is my Jest test file for <code>WorkshopsView</code> so far:</p>
<pre><code>import { shallowMount } from '@vue/test-utils'
import WorkshopsView from '@/components/WorkshopsView.vue'
import WorkshopsGrid from '@/components/WorkshopsGrid.vue'
import useGetWorkshops from '@/services/useGetWorkshops'

jest.mock('@/services/useGetWorkshops', () =&gt; {
  return jest.fn().mockImplementation(() =&gt; {
    return { data: [], error: null }
  })
})

describe('WorkshopsView', () =&gt; {
  it('calls the child component', () =&gt; {
    const wrapper = shallowMount(WorkshopsView)
    expect(wrapper.findComponent(WorkshopsGrid).exists()).toBe(true)
  })

  it('calls the service to fetch the data', () =&gt; {
    const wrapper = shallowMount(WorkshopsView)
    expect(useGetWorkshops).toHaveBeenCalled()
  }
}
</code></pre>
<p>How might it be tested that the component is getting the right data in the expected form to pass to the child component as a prop?</p>
",https://stackoverflow.com/questions/73748148/unit-testing-vue-component-that-fetches-data-and-sends-to-component-as-prop,"['unit-testing', 'jestjs', 'vuejs3']",46,False,2,0
kotlin.NoWhenBranchMatchedException under unit testing a tailrec function with arrow-kt in the mix,"<p>I'm testing a function with an external dependency inside of a <code>tailrec</code> function. The function returns an <code>Either</code>.
When mocking this dependency, I'm providing a single mock invocation. I get the following exception:
<code>kotlin.NoWhenBranchMatchedException</code></p>
<p>Why is the exception occurring and how do I fix it?</p>
",https://stackoverflow.com/questions/74470923/kotlin-nowhenbranchmatchedexception-under-unit-testing-a-tailrec-function-with-a,"['kotlin', 'mockito', 'arrow-kt']",246,True,2,1
How to raise an event when unit testing asynchronous method in my case?,"<p>I use MS-Test, moq 4.18.2 and FileSystem (System.IO.Abstractions) 17.0.24 for my tests.</p>
<p>I think I wrote a correct test for <em>InfoLoader_LoadInfoAsync</em>. But, I don't understand how to write a test for <code>MyViewModel::StartLoadInfoAsync</code> to check that <code>InfoList</code> was populated correctly. It seems that I have to duplicate instantiation and configuration of <code>InfoLoader</code> as I did in <code>InfoLoader_LoadInfoAsync</code>. Is there a way around this? How such things are usually tested?</p>
<pre><code>public abstract class IInfoLoader
{
    public event Action&lt;MyInfo&gt; InfoLoaded;
    public abstract Task LoadInfoAsync();

    protected void OnInfoLoaded(MyInfo info)
    {
        InfoLoaded?.Invoke(info);
    }
}
public class InfoLoader : IInfoLoader
{
    private readonly IFileSystem _fileSystem;
    private readonly string _path;

    public InfoLoader(string path, IFileSystem fileSystem) {...}
    
    public async override Task LoadInfoAsync()
    {
        foreach (var data in await _fileSystem.File.ReadAllLinesAsync(_path))
            OnInfoLoaded(new MyInfo(...));
    }
}
public class MyViewModel
{
    private IInfoLoader _infoLoader;
    public ObservableCollection&lt;MyInfo&gt; InfoList { get; }

    public MyViewModel(IInfoLoader infoLoader) { ... }

    public Task StartLoadInfoAsync()
    {
        _infoLoader.InfoLoaded += (info) =&gt; InfoList.Add(info);
        return _infoLoader.LoadInfoAsync();
    }
}
</code></pre>
<p><strong>Tests</strong></p>
<pre><code>[TestMethod]
public async Task InfoLoader_LoadInfoAsync_Success()
{
    var path = &quot;...&quot;;
    var lines = new string[] { &quot;name1&quot;, &quot;name2&quot; };
    var expectedInfoList = new List&lt;MyInfo&gt;();
    foreach(var line in lines)
        expectedInfoList.Add(new MyInfo(line));

    var fileSystem = new Mock&lt;IFileSystem&gt;();
    fileSystem.Setup(fs =&gt; fs.File.ReadAllLinesAsync(path, CancellationToken.None))
                .ReturnsAsync(lines);

    var actualInfoList = new List&lt;MyInfo&gt;();
    var infoLoader = new InfoLoader(path, fileSystem.Object);
    infoLoader.InfoLoaded += (info) =&gt; actualInfoList.Add(info);
    await infoLoader.LoadInfoAsync();

    // Assert that items in expectedInfoList and actualInfoList are equal
}
[TestMethod]
public async Task MyViewModel_StartLoadInfoAsync_Success()
{
    var expectedInfoList = new List&lt;MyInfo&gt;();
    
    // WHAT DO I DO HERE? DO I CREATE AND CONFIGURE infoLoader LIKE in &quot;InfoLoader_LoadInfoAsync&quot; TEST?
    
    var vm = new MyViewModel(infoLoader.Object);
    await vm.StartLoadInfoAsync();
    actualInfoList = vm.InfoList;
    
    // Assert that items in expectedInfoList and actualInfoList are equal
}
</code></pre>
",https://stackoverflow.com/questions/73348307/how-to-raise-an-event-when-unit-testing-asynchronous-method-in-my-case,"['c#', '.net', 'unit-testing', 'moq']",305,True,1,2
How can I cover Axios-retry failure unit testing using Mocha chai Nodejs?,"<p>How can we unit test the following code (axios-retry logic)</p>
<p><strong>AxiosRetryClass.ts</strong></p>
<pre><code>import { AxiosInstance, AxiosRequestConfig } from 'axios';
import axiosRetry from 'axios-retry';


export class AxiosRetryClass {
    constructor() {
    }

   public async callAxios(axiosConfig: AxiosRequestConfig): Promise&lt;any&gt; {
       const instance = new AxiosSession().getAxiosInstance();
    
          axiosRetry(instance, {
            retries: 3,
            retryCondition: (error: any) =&gt; {
                return error.response.status === 500;
            },
            retryDelay: (count: number, err: any) =&gt; {
                    return 1 * 60 * 1000;
            },
        });

      let response = { status: 0};
      try {
        response =  await instance(axiosConfig);

      } catch (error: any) {
        response = error;
        console.log(`AxiosClass: call error ${error}`);
       }

      return response;
    }
   
  }
</code></pre>
<p><strong>AxiosSession.ts</strong></p>
<pre><code>import {HttpsCookieAgent, HttpCookieAgent } from 'http-cookie-agent';
import { CookieJar } from 'tough-cookie';
import axios from 'axios';

export class AxiosSession {
   constructor() {}

 public getAxiosInstance(): Promise&lt;any&gt; {
    const agents = {
             httpAgent: new HttpCookieAgent({ new CookieJar(), true }),
             httpsAgent: new HttpsCookieAgent({ new CookieJar(), true }),
        }

    const instance = axios.create(agents);

    return instance;
   }
 }
</code></pre>
<p><strong>AxiosRetry.spec.ts</strong></p>
<pre><code>import Axios, { AxiosInstance } from 'axios';
import chai from 'chai';
import sinon, { SinonStub } from 'sinon';
import chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);

describe(‘AxiosClassTest ', () =&gt; {
   let sinonStub: sinon.SinonSandbox;

   beforeEach(() =&gt; {
    sinonStub = sinon.createSandbox();
   });

it(‘Test Axios retry’, async () =&gt; {
    let instance = {} as AxiosInstance;

    instance.get = sinonStub.stub().rejects({status: 500}); //Tried both returns and rejects

    const session = new AxiosSession();
    session.getAxiosInstance = sinonStub.stub().returns(instance);

    const axiosClass = new AxiosClass();
    const url = `dummy-error-url`

     await axiosClass.callAxios({ url, method: ‘GET’ });


    });
});
</code></pre>
<p>Note: Test case is running successfully. But axios-retry code not covered. I mean the below code</p>
<pre><code>       axiosRetry(instance, {
            retries: 3,
            retryCondition: (error: any) =&gt; {
                return error.response.status === 500;
            },
            retryDelay: (count: number, err: any) =&gt; {
                    return 1 * 60 * 1000;
            },
        });
</code></pre>
",https://stackoverflow.com/questions/72121837/how-can-i-cover-axios-retry-failure-unit-testing-using-mocha-chai-nodejs,"['node.js', 'axios', 'mocha.js', 'axios-mock-adapter', 'axios-retry']",326,False,1,0
Svelte - Not able to fetch data from JSON file during jest unit testing,"<p>During unit testing, I am getting undefined error, while executing svelte component with json file.</p>
<p><strong>Restaurant.svelte :</strong></p>
<pre><code>import data from '../Data/restaurants.json';
console.log(data);
let finalData = data.restaurants;
</code></pre>
<p><strong>restaurant.spec.js :</strong></p>
<pre><code>import Restaurant from './../routes/Restaurant.svelte';
import { render, screen, fireEvent } from &quot;@testing-library/svelte&quot;;


describe(&quot;Restaurants Home Page&quot;,()=&gt;{
    it(&quot;Tests for Header&quot;,()=&gt;{
        render(Restaurant);
        const resheader = screen.getByText(&quot;Restaurants&quot;);
        expect(resheader).toBeVisible();
    })
})
</code></pre>
<p><strong>Jest Config File :</strong></p>
<pre><code>{
    &quot;transform&quot;: {
      &quot;^.+\\.js$&quot;: &quot;babel-jest&quot;,
      &quot;^.+\\.svelte$&quot;: &quot;svelte-jester&quot;,
      &quot;.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$&quot;: &quot;jest-transform-stub&quot;
    },
    &quot;moduleFileExtensions&quot;: [&quot;svelte&quot;, &quot;js&quot;, &quot;json&quot;],
    &quot;transformIgnorePatterns&quot;: [&quot;node_modules/(?!(svelte-spa-router|svelte-i18n)/)&quot;],
    &quot;testEnvironment&quot;: &quot;jsdom&quot;,
    &quot;setupFilesAfterEnv&quot;: [&quot;@testing-library/jest-dom/extend-expect&quot;],
    &quot;moduleDirectories&quot;: [
      &quot;node_modules&quot;,
      &quot;src&quot;
    ],
    &quot;moduleNameMapper&quot;: {
      &quot;src/(.*)&quot;: &quot;&lt;rootDir&gt;/src/Data&quot;
    }    
}

</code></pre>
<p><strong>Error Msg:</strong>
TypeError: Cannot read properties of undefined (reading 'restaurants')</p>
<pre><code>   7 |
   8 |     console.log(data);
&gt;  9 |     let finalData = data.restaurants;
</code></pre>
",https://stackoverflow.com/questions/72097867/svelte-not-able-to-fetch-data-from-json-file-during-jest-unit-testing,"['unit-testing', 'jestjs', 'svelte', 'sveltekit', 'svelte-testing-library']",336,False,1,1
How do I compare two list in expect function of flutter unit testing?,"<p><code>List&lt;int&gt; l1=[1,2,3];  List&lt;int&gt; l2=[1,2,3];  expect (l1,l2);</code></p>
<p>This is the code I'm using in Flutter unit testing.</p>
<p>Eventhough both of the list has the same content I'm not able to pass the test. I'm not able to find the usecase of comparing lists using Equatable in Flutter unit testing. Can someone please help? Thanks!</p>
",https://stackoverflow.com/questions/71578026/how-do-i-compare-two-list-in-expect-function-of-flutter-unit-testing,"['flutter', 'unit-testing', 'dart', 'testing']",1854,True,1,2
How do I mock UserRecord internal class for Firebase unit testing with Moq,"<p>I want to write a unit test in C# using Moq for my code using Firebase SDK and specifically involving GetUserAsync(), e.g. UserRecord user = GetUserAsync(Uid) but am getting stuck on the Firebase UserRecord internal class. How do I mock the UserRecord class for testing given that it has read only internals?</p>
<p>What I've tried so far:</p>
<pre><code>var firebase = new Mock&lt;IFirebaseAppWrapper&gt;();
firebase
  .Setup(x =&gt; x.GetUserAsync(It.IsAny&lt;string&gt;()))
  .Returns&lt;UserRecord&gt;(usr =&gt;
  {
    var item = new Mock&lt;UserRecord&gt;(&quot;1&quot;);
    return Task.FromResult(item.Object);
  });
</code></pre>
<p>Of course this doesn't work, but it feels close. Any advice?
BTW: The FirebaseApp has been artificially wrapped in a pass through class and has a counterpart interface class.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/73405655/how-do-i-mock-userrecord-internal-class-for-firebase-unit-testing-with-moq,"['c#', 'firebase', 'unit-testing', 'moq']",177,False,1,1
Unit Testing in Jasmine: Spy on service function and call another service function,"<p>Below is my component function I want to write unit tests. I want to write a unit test to test the <code>tokenRefresh</code> function in auth service is being called when getItem returns a string to the component.</p>
<p>Component.ts</p>
<pre><code>refreshTokens(): void {
    const refreshToken = this.localStorageService.getItem('refresh_token');
    if (refreshToken) {
      this.authService.tokenRefresh(refreshToken).subscribe({
        next: (data: TokenModel) =&gt;
          this.authService.routeToDashboard(
            data.access_token,
            data.refresh_token,
            data.expires_at
          ),
      });
    } else {
      this.notificationService.openSnackBar('Please login again.');
    }
  }
</code></pre>
<p>localStorage.service.ts</p>
<pre><code>@Injectable({
  providedIn: 'root'
})
export class LocalStorageService {

  constructor() { }

  getItem(key: string): string | null {
    return localStorage.getItem(key);
  }
}
</code></pre>
<p>I have created mick services in my component.spec.ts to mock LocalStorageService and AuthService as below.</p>
<pre><code>export class LocalStorageStub {
  getItem(key: string): string | null {
    return '7677673437437';
  }
}

export class AuthorizeServiceStub {
  tokenRefresh(key: string) {
    return of({});
  }
  setItem(): void {

  }
}
</code></pre>
<p>Below is my complete component.spec.ts.</p>
<pre><code>describe('LoginComponent', () =&gt; {
  let component: LoginComponent;
  let fixture: ComponentFixture&lt;LoginComponent&gt;;
  let el: HTMLElement;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports: [
        HttpClientModule,
        RouterTestingModule,
        MatSnackBarModule,
        BrowserAnimationsModule
      ],
      providers:[
        { provide: LocalStorageService, useClass: LocalStorageStub },
        { provide: AuthorizeService, useClass: AuthorizeServiceStub}
      ]
    })
    .compileComponents();
  });

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

  it('should call token refresh if localstorage has refreshtoken', function() {
    component.refreshTokens();
    let service = fixture.debugElement.injector.get(LocalStorageService);
    let authService = fixture.debugElement.injector.get(AuthorizeService);
    service.getItem('key');
    const setPageSpy2 = spyOn(authService, 'tokenRefresh');
    expect(setPageSpy2).toHaveBeenCalled();
  });
});
</code></pre>
<p>I get the below result for my test case.</p>
<p><a href=""https://i.stack.imgur.com/qoqGt.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/qoqGt.png"" alt=""enter image description here"" /></a></p>
<p>Appreciate if someone can tell me what's the issue here.</p>
<p>Edit: The new order of unit test case</p>
<pre><code>it('should call token refresh if localstorage has refreshtoken', function() {
    let service = fixture.debugElement.injector.get(LocalStorageService);
    let authService = fixture.debugElement.injector.get(AuthorizeService);
    service.getItem('key');
    component.refreshTokens();
    const setPageSpy2 = spyOn(authService, 'tokenRefresh');
    expect(setPageSpy2).toHaveBeenCalled();
  });
</code></pre>
",https://stackoverflow.com/questions/73035679/unit-testing-in-jasmine-spy-on-service-function-and-call-another-service-functi,"['angular', 'unit-testing', 'service', 'jasmine']",4577,True,1,1
Error 404 Not Found while unit testing govmomi vapi rest client using simulator,"<p>I'm working with vSphere govmomi client to interact with vCenter.</p>
<p>I'm having problem in unit testing the govmomi vapi/rest client.
The sample code for creating rest client is:</p>
<pre><code>var insecure bool = true
type RestClient struct {
 url *url.URL
 restClient *rest.Client
}

func (c *RestClient) GetRestClient(ctx context.Context) (*rest.Client, error){
 soapClient := soap.NewClient(c.url, insecure)
 vim25Client, err := vim25.NewClient(ctx, soapClient)
 if err != nil {
  return nil, err
 }
 c.restClient = rest.NewClient(vim25Client)
 err = c.restClient.Login(ctx, c.url.User)
 if err != nil {
  return nil, err
 }
 return c.restClient, nil
}
</code></pre>
<p>To write their unit tests, I'm using govmomi simulator and vapi/simulator.</p>
<pre><code>import(
 &quot;context&quot;
 &quot;testing&quot;
 &quot;net/url&quot;
 &quot;github.com/vmware/govmomi/simulator&quot;
 _ &quot;github.com/vmware/govmomi/vapi/simulator&quot;
)

func TestGetRestClient(t *testing.T){
 ctx := context.Background()
 model := simulator.ESX()
 defer model.Remove()
 err := model.Create()
 if err != nil {
  t.Fatal(err)
 }
 server := model.Service.NewServer()
 defer server.Close()
 url := server.URL
 var client RestClient = RestClient{url: url,}
 _, err := client.GetRestClient(ctx)
 if err != nil {
  t.Errorf(&quot;err = %v&quot;, err)
  return
 }
}
</code></pre>
<p>The testcase should pass, but it returns an error</p>
<pre><code>err= POST &quot;http://127.0.0.1:34691/rest/com/vmware/cis/session: 404 Not Found
</code></pre>
<p>I'm not able to understand what I'm missing or doing wrong in unit testing. I've done similar test for creating a govmomi client using simulator and it never came across this error.</p>
<p><strong>NOTE: This rest client is created successfully as I'm able to interact with vCenter using this client.</strong></p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/72763660/error-404-not-found-while-unit-testing-govmomi-vapi-rest-client-using-simulator,"['go', 'vmware', 'vsphere', 'govmomi']",193,False,1,0
Unit testing data layer&#39;s stored functions/procedures using OrmLite without an open connection,"<p>I am trying to unit test our DB layer's stored procedures/functions using OrmLite's <code>ScalarAsync()</code>, for example, with the PostgreSQL dialect. (I tried using SqlLite in-memory but it doesn't do stored procedures or functions.)</p>
<p>I found some hints in the unit-tests for OrmLite on GitHub as well as an <a href=""https://forums.servicestack.net/t/sqlitedialect-with-sqlproc-in-unit-tests/3245"" rel=""nofollow noreferrer"">article</a> which points to them.</p>
<p>Here's what I have:</p>
<pre class=""lang-cs prettyprint-override""><code>    [Fact]
    public async Task TestMyMethod_CallsMyStoredProcedure()
    {
        // Arrange
        Mock&lt;IDashboardDbConnectionFactory&gt; mockConnFac = new();

        MockDialectProvider prov = new();
        prov.ExecFilter = new MockStoredProcExecFilter();
        
        OrmLiteConnectionFactory dbFactory =
            new(
                &quot;User ID=asdf;Password=asdf;Host=localhost;Port=5432;Database=asdf;Pooling=true;Connection Lifetime=0;&quot;,
                prov, false);

        OrmLiteConfig.ExecFilter = new MockStoredProcExecFilter();
        mockConnFac.Setup(m =&gt; m.OpenAsync(It.IsAny&lt;ISecurityContext&gt;()))
            .Returns(async () =&gt;
        {
            OrmLiteConnection asdf = new(dbFactory);
            OrmLiteConfig.ExecFilter = new MockStoredProcExecFilter();
            await asdf.OpenAsync();
            return asdf;
        });
        mockConnFac.Setup(m =&gt; m.Open(It.IsAny&lt;ISecurityContext&gt;()))
            .Returns(() =&gt;
            {
                OrmLiteConnection asdf = new(dbFactory);
                OrmLiteConfig.ExecFilter = new MockStoredProcExecFilter();
                asdf.Open();
                return asdf;
            });
        
        // Act
        MyDataLayerCLass target = new(mockConnFac.Object, new NullLoggerFactory());
        bool test1 =
            await target.ExecMyStoredProcAsync(new Mock&lt;ISecurityContext&gt;().Object, Guid.NewGuid());

        // Assert
        Assert.True(test1);
    }

    private class MockDialectProvider : PostgreSqlDialectProvider
    {
        public MockDialectProvider()
        {
            base.ExecFilter = new MockStoredProcExecFilter();
        }
        public new IOrmLiteExecFilter ExecFilter { get; set; } = new MockStoredProcExecFilter();
    }
    
    private class MockStoredProcExecFilter : OrmLiteExecFilter
    {
        public override T Exec&lt;T&gt;(IDbConnection dbConn, Func&lt;IDbCommand, T&gt; filter)
        {
            try
            {
                T val = base.Exec(dbConn, filter);
                if (dbConn.GetLastSql() == &quot;select central_data.my_stored_function(@UserId, @ParentId)&quot;)
                    return (T)(object)true;

                return val;
            }
            catch (Exception)
            {
                if (dbConn.GetLastSql() == &quot;select central_data.my_stored_function(@UserId, @ParentId)&quot;)
                    return (T)(object)true;
                throw;
            }
        }
        
        public override async Task&lt;T&gt; Exec&lt;T&gt;(IDbConnection dbConn, Func&lt;IDbCommand, Task&lt;T&gt;&gt; filter)
        {
            try
            {
                // This is where the breakpoint hits. Returns false b/c the ids
                // don't match actual records in the DB.
                T val = await base.Exec(dbConn, filter);
                if (dbConn.GetLastSql() == &quot;select central_data.my_stored_function(@UserId, @ParentId)&quot;)
                    return (T)(object)true;

                return val;
            }
            catch (Exception)
            {
                string sql = dbConn.GetLastSql();
                if (sql == &quot;select central_data.my_stored_function(@UserId, @ParentId)&quot;)
                {
                    return (T)(object)true;
                }
                throw;
            }
        }
    }
</code></pre>
<p>The problem is that it requires a valid connection to a valid database. So it's really an integration test when what I want is a unit test. Is there a way to run the dialect provider without an open connection?</p>
",https://stackoverflow.com/questions/73490085/unit-testing-data-layers-stored-functions-procedures-using-ormlite-without-an-o,"['c#', 'postgresql', 'unit-testing', 'xunit', 'ormlite-servicestack']",72,False,1,0
TypeError: undefined is not an object when unit testing with jasmine - JSON response,"<p>I added this line in an existing unit test which used to work and I'm getting an error after adding this:(BTW, this works ok on web browser.)</p>
<pre><code>onRender: function () {
    if ( _.isEmpty(this.viewData.assessment) || _.isEmpty(this.viewData.patient) || _.isEmpty(this.viewData.scoreInfo) ) {
      $(&quot;#viewAssessmentDetails&quot;).hide();
      return;
    }
    //console.log(&quot;this.viewData.scoreInfo: &quot;,JSON.stringify(this.viewData.scoreInfo));
    if (this.completedAssessment) {
      this.viewData.assessment = this.completedAssessment.toJSON();
    }
    
   //without this line, the test passes
   this.viewData.assessment.format.sections[0].questions[0].introText =
      this.viewData.assessment.format.sections[0].questions[0].introText.replace(/\|/g, '\n');
...
...

</code></pre>
<p>the error I get:</p>
<p>FAILED TESTS:</p>
<pre><code>viewAssessmentDetails
    ✖ render no completed assessment renders
      PhantomJS 2.1.1 (Mac OS 0.0.0)
    TypeError: undefined is not an object (evaluating 'this.viewData.assessment.format.sections') in src/test/view/app/view_assessment_detailsSpec.js (line 49131)
    onRender@webpack:///src/js/view/app/view_assessment_details.js:368:5 &lt;- src/test/view/app/view_assessment_detailsSpec.js:49131:72948
    webpack:///src/test/view/app/view_assessment_detailsSpec.js:253:9 &lt;- src/test/view/app/view_assessment_detailsSpec.js:50821:88
    &lt;Jasmine&gt;

    ✖ render with completed assessment renders
      PhantomJS 2.1.1 (Mac OS 0.0.0)
    TypeError: undefined is not an object (evaluating 'this.viewData.assessment.format') in src/test/view/app/view_assessment_detailsSpec.js (line 49131)
    onRender@webpack:///src/js/view/app/view_assessment_details.js:368:5 &lt;- src/test/view/app/view_assessment_detailsSpec.js:49131:72941
    webpack:///src/test/view/app/view_assessment_detailsSpec.js:265:9 &lt;- src/test/view/app/view_assessment_detailsSpec.js:50840:88
    &lt;Jasmine&gt;

</code></pre>
<p>thanks in advance,
Daniel</p>
",https://stackoverflow.com/questions/70643599/typeerror-undefined-is-not-an-object-when-unit-testing-with-jasmine-json-resp,"['javascript', 'json', 'karma-jasmine']",197,False,1,0
Angular Unit Testing: TypeError: cannot set properties of null (setting &#39;innerHtml&#39;) (Jasmine/Karma),"<h1>TypeError: cannot set properties of null (setting 'innerHtml')</h1>
<p>I have created a simple angular service that initializes the inner html of a div tag in the main component of my angular project and is called in multiple components. When I run my tests I get the above karma error. I assume this is because the component is not created in the service.spec.ts file. I have checked and the class is defined in the main html file.</p>
<h2>service.ts function:</h2>
<pre><code>onCLick(value: string): void {
   document.querySelector('div.class').innerHtml = value;
}
</code></pre>
<h2>service.spec.ts:</h2>
<pre><code>descirbe('ClickedService', () =&gt; {
   let service: ClickedService;

   beforeEach(() =&gt; {
      TestBed.configureTestingModule({});
      service = TestBed.inject(ClickedService);
   });

   to(&quot;#onClick should add to innerHtml&quot;, () =&gt; {
       service.onClick('test value'); // error is here
   });
});
</code></pre>
",https://stackoverflow.com/questions/72931850/angular-unit-testing-typeerror-cannot-set-properties-of-null-setting-innerht,"['javascript', 'angular', 'typescript', 'unit-testing', 'karma-jasmine']",927,True,1,1
Unit Testing Times Zones and a strategy to migrate to Multi-Locale TimeZones,"<p><sub>While the question <a href=""https://stackoverflow.com/questions/1384038/how-to-unit-test-timezones"">How to unit test TimeZones?</a> exists with a few answers it's more &quot;How To&quot; whereas this is a timezone conversion problem.</sub></p>
<h1>Intro &amp; Code Repo/Repro</h1>
<p>I have a problem with the practical implementation of Unit Testing TimeZones. I made a Repo to quickly repro the problem converting an Australian date to two Time Zones in UTC -4 &amp; -3: <a href=""https://github.com/MeaningOfLights/UnitTestedTimeZones"" rel=""nofollow noreferrer"">https://github.com/MeaningOfLights/UnitTestedTimeZones</a> Brief Code:</p>
<pre><code>[TestCaseSource(&quot;GetDataFromCSVTimeZonesAEST&quot;)]
public DateTime Should_Convert_From_AEST_To_OtherTimeZones(string timeZoneId, DateTime localAEST)
{
    // Act
    var foreignDateTime = TimeZoneHelper.DateFromAEST(localAEST, TimeZoneInfo.FindSystemTimeZoneById(timeZoneId));

    //Assert
    return foreignDateTime;
}

private static IEnumerable GetDataFromCSVTimeZonesAEST()
{
    CsvReader reader = new CsvReader(&quot;TestData\\TimeZones.csv&quot;);
    bool firstLineHeader = true;
    while (reader.Next())
    {
        if (firstLineHeader)
        { 
            firstLineHeader = false;
            continue;
        }
        string regionTimeZoneId = reader[1].ToString();
        DateTime BaseAEST = DateTime.Parse(reader[2]);
        DateTime foreignDateTime = DateTime.Parse(reader[3]);
        yield return new TestCaseData(regionTimeZoneId, BaseAEST).Returns(foreignDateTime);
    }
}
</code></pre>
<h1>Background</h1>
<p>I have a database with Australian dates that needs to support localized TimeZones. Since its a live system taking it offline to convert all the Australian AEST dates to UTC isn't easily possible and would need very good justification for the downtime.</p>
<p>I thought about using AEST as the base date metric instead of UTC. However, after a few tests considering Countries with/without Daylight Savings Time (DST) I'm already nervous about not using UTC as I suspect it will bite me - further.</p>
<h1>Testing</h1>
<p>Testing this theory with AEST as a base date I see 2/20 tests failing. In the repo, in the Unit Test project is Test Data csv file:</p>
<p><a href=""https://i.stack.imgur.com/tyxtS.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tyxtS.png"" alt=""enter image description here"" /></a></p>
<p>When I run the Unit Tests, the two above highlighted tests fail, in fact any TimeZones I use for UTC -4 &amp; -3 are failing.</p>
<pre><code>+---------------------------------+-----------+
|     Time Zone                   | UTCOffset |
+---------------------------------+-----------+
| Paraguay Standard Time          | -04:00:00 |
| Atlantic Standard Time          | -04:00:00 |
| Venezuela Standard Time         | -04:00:00 |
| Central Brazilian Standard Time | -04:00:00 |
| SA Western Standard Time        | -04:00:00 |
| Pacific SA Standard Time        | -04:00:00 |
| Newfoundland Standard Time      | -03:30:00 |
| Tocantins Standard Time         | -03:00:00 |
| E. South America Standard Time  | -03:00:00 |
| SA Eastern Standard Time        | -03:00:00 |
| Argentina Standard Time         | -03:00:00 |
| Greenland Standard Time         | -03:00:00 |
| Montevideo Standard Time        | -03:00:00 |
| Magallanes Standard Time        | -03:00:00 |
| Saint Pierre Standard Time      | -03:00:00 |
| Bahia Standard Time             | -03:00:00 |
+---------------------------------+-----------+
</code></pre>
<p>Just to make things more confusing, Argentina is located at a longitude that would naturally put it in the UTC−04:00 or UTC−05:00 time zone; however, <a href=""https://en.wikipedia.org/wiki/Time_in_Argentina#:%7E:text=Argentina%20is%20located%20at%20a,%E2%88%9203%3A00%20time%20zone."" rel=""nofollow noreferrer"">it actually uses the UTC−03:00 time zone</a>. Although I'm expecting UTC -4:00 from the .Net Core TimeZoneInfo.</p>
<p><a href=""https://i.stack.imgur.com/6OrQ7.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/6OrQ7.png"" alt=""enter image description here"" /></a></p>
<h1>Debugging steps</h1>
<p><a href=""https://github.com/MeaningOfLights/UnitTestedTimeZones"" rel=""nofollow noreferrer"">Clone the project</a>, open the UnitTest.cs class file and press Ctrl + R + T or click Run Tests.</p>
<h1>Results</h1>
<p>I can't work out why these two fail, I'm not sure about Daylight Saving (DST) as other TimeZones without it work fine. Can someone please give me a hand to understand what's going on?</p>
<p>Also, am I correct with my concerns about using AEST instead of UTC as the DataBase DateTime format?</p>
<p><sub>Coding on Windows 10, this UnitTest project is to test it all works on Linux Distro's. Many thanks!</sub></p>
<h1>Update</h1>
<p>I updated the TimeZones.csv with details. The problem is Brazil sits across multiple Time Zones and Argentina uses Brazils UTC -3. By recording all the DateTimes in UTC on the server (after converting AEST dates to UTC) we'll simply let the users decide the TimeZone:</p>
<p><a href=""https://i.stack.imgur.com/Nnz8l.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Nnz8l.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73850959/unit-testing-times-zones-and-a-strategy-to-migrate-to-multi-locale-timezones,"['c#', '.net', 'unit-testing', 'datetime', 'timezone']",133,False,1,0
Unit testing with Flavor keeps failing and show &#39;The events were not received&#39;,"<p>I set,</p>
<pre><code>    testOptions {
        animationsDisabled = true
        unitTests.all {
            useJUnitPlatform()
        }
    }
</code></pre>
<p>And I am using Java Home for Gradle JDK.</p>
<p>The error is here:</p>
<pre><code>Execution failed for task ':app:testDevDebugUnitTest'.
</code></pre>
<pre><code>org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:testDevDebugUnitTest'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:145)
    at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:282)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:143)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:131)
    at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
    at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
    at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
    at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
    at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73)
    at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
    at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:74)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:402)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:389)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:382)
    at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:368)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
    at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
    at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
    at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:61)
Caused by: org.gradle.api.tasks.testing.TestExecutionException: No tests found for given includes:
</code></pre>
<p>The difference was just using Flavor.</p>
<pre><code>testDevDebugUnitTest
</code></pre>
<p>My guess is adding flavor changes the path that needs while testing and this happened. So, I've changed path and also changed <code>testImplementation</code> to <code>testDevImplementation</code> but didn't work.</p>
<p>I added dev flavor this happened.. What have I been missing?</p>
",https://stackoverflow.com/questions/73045210/unit-testing-with-flavor-keeps-failing-and-show-the-events-were-not-received,"['android', 'android-studio', 'gradle', 'build.gradle', 'android-unit-testing']",239,True,0,1
How to use http.ResponseWriter and http.request as argument(Unit Testing) with Golang language,"<p>I just getting started learning Golang and PostgreSQL. For now, I tried to make Unit testing for CreateTodo function.
My CreateTodo function is</p>
<pre><code>func CreateTodo(w http.ResponseWriter, r *http.Request) {
    CreateTodo := &amp;models.Todo{}
    utils.ParseBody(r, CreateTodo)
    CreateTodoList := CreateTodo.CreateTodo()
    res, _ := json.Marshal(CreateTodoList)
    w.WriteHeader(http.StatusOK)
    w.Write(res)
}
</code></pre>
<p>I tried to make Unit Test for this function... So far I wrote some codes like</p>
<pre><code>func TestCreateTodo(t *testing.T) {
    dbData := &amp;models.Todo{
        Title: &quot;test-title-console-check&quot;,
        Description: &quot;test-description-console-check&quot;,
        Condition: true,
    }

    utils.ParseBody(r, dbData) // r should be r *http.Request

    submittedTodo := dbData.CreateTodo()
    res, _ := json.Marshal(submittedTodo)
    r.WriteHeader(http.StatusOK) // r should be r *http.Request
    r.Write(res)

    fmt.Println(&quot;res: &quot;, res)
}
</code></pre>
<p>This is ParseBodu function in utils folder</p>
<pre><code>func ParseBody(r *http.Request, x interface{}) {
    if body, err := ioutil.ReadAll(r.Body); err == nil {
        if err := json.Unmarshal([]byte(body), x); err != nil {
            return
        }
    }
}
</code></pre>
<p>Here, I have a problem with passing net/http(r *http.Request). I am not sure how to pass this function like argument... I tried to receive it in TestCreateTodo(t *testing.T, r *http.Request) but not working what I expected.</p>
<p>Is there any way to unit test for CreateTodo function??</p>
<p>I really appreciate your help!</p>
<p>Edit 1]</p>
<p>I tried to make a global variable</p>
<pre><code>var readData *http.Request
var writeData http.ResponseWriter
</code></pre>
<p>and using it in the function. The reason why I make it global variables is that I usually use it in the funcs like &lt;w http.ResponseWriter, r *http.Request&gt;, so I thought I can use as global vars too.</p>
<p>so I edit my code as</p>
<pre><code>var readData *http.Request
var writeData http.ResponseWriter

func TestCreateTodo(t *testing.T) {
    // w := httptest.NewRecorder()
    dbData := &amp;models.Todo{
        Title: &quot;test-title-console-check&quot;,
        Description: &quot;test-description-console-check&quot;,
        Condition: true,
    }

    utils.ParseBody(readData, dbData)

    submittedTodo := dbData.CreateTodo()
    res, _ := json.Marshal(submittedTodo)
    writeData.WriteHeader(http.StatusOK)
    writeData.Write(res)

    fmt.Println(&quot;res: &quot;, res)
}
</code></pre>
<p>But I got this error
<a href=""https://i.stack.imgur.com/Huuot.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Huuot.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/71262072/how-to-use-http-responsewriter-and-http-request-as-argumentunit-testing-with-g,"['unit-testing', 'go']",4761,True,0,1
angular unit testing spyOn method is not detected by storybook when running StoryBook,"<p>I have an existing big size angular application and I added storybook into it. When I run storybook I see a lot of error in the console and lot of them are related to not able detect jasmine pr spyOn method by storybook.</p>
<p>Whats going wrong? Am I missing something when running storybook?</p>
<pre><code>Error:  - error TS2304: Cannot find name 'spyOn'.

102   spyOn(xxx, 'aaaa').and.returnValue(
      ~~~~~

    at addError ...
</code></pre>
",https://stackoverflow.com/questions/74775413/angular-unit-testing-spyon-method-is-not-detected-by-storybook-when-running-stor,"['angular', 'storybook', 'angular-storybook']",70,False,0,0
Unit Testing with URLProtocol subclassing returns a 0 bytes Data instead of nil,"<p>First of all, sorry for my english, I hope it won't be a pain to read me :D</p>
<p>I'm currently building an iOS application for a project in my school and I'm facing a problem.</p>
<p>I make an API call and I test it by using the <code>URLProtocol</code> method.</p>
<p><strong>The API call :</strong></p>
<pre><code>task?.cancel()
task = exchangeSession.dataTask(with: request) { data, response, error in
     // The dataTask method will execute in a separate queue, so we 
     // get back into the main one because
     // we will modify the user interface with our exchange result
     
     DispatchQueue.main.async {
          guard let data = data, error == nil else {
               callback(false, nil, error)
               return
          }
                
          guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
               callback(false, nil, nil)
               return
          }
                
          guard let responseJSON = try? JSONDecoder().decode(ConvertResponse.self, from: data), let result = responseJSON.result else {
               callback(false, nil, nil)
               return
          }
          callback(true, result, nil)
     }
}
task?.resume()
</code></pre>
<p><strong>The MockURLProtocol :</strong></p>
<pre><code>final class MockURLProtocol: URLProtocol {
    
    // We return true in order to allow URLSession to use this protocol for any URL Request
    override class func canInit(with request: URLRequest) -&gt; Bool {
        return true
    }
    
    override class func canonicalRequest(for request: URLRequest) -&gt; URLRequest {
        return request
    }

    static var loadingHandler: ((URLRequest) -&gt; (Data?, HTTPURLResponse?, Error?))?
    
    override func startLoading() {
        guard let handler = MockURLProtocol.loadingHandler else {
            print(&quot;Loading handler is not set.&quot;)
            return
        }
        
        let (data, response, error) = handler(request)
        
        guard error == nil else {
            client?.urlProtocol(self, didFailWithError: error!)
            return
        }
        
        if let data = data {
            client?.urlProtocol(self, didLoad: data)
        }
        
        if let response = response {
            client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
        }
        
        client?.urlProtocolDidFinishLoading(self)
    }
    
    override func stopLoading() {}
}
</code></pre>
<p>As you can see, it contains a handler which will have the data / response and error.</p>
<p>In one of my tests I want to check the case where I don't have any data, so I put nil for it.</p>
<p><strong>The test :</strong></p>
<pre><code>    func testConvertShouldPostFailedCallbackIfNoData() {
        MockURLProtocol.loadingHandler = { request in
            return (nil, nil, nil)
        }
                
        let expectation = XCTestExpectation(description: &quot;Wait for queue change.&quot;)
        client.convert(from: from, to: to, amount: amount) { success, result, error in
            XCTAssertFalse(success)
            XCTAssertNil(result)
            XCTAssertNil(error)
            expectation.fulfill()
        }
        
        wait(for: [expectation], timeout: 0.01)
    }
</code></pre>
<p>Here is my problem: nil doesn't work for my data parameter, it shows me &quot;0 Bytes&quot; instead.
It works for error and response, which is strange to me.</p>
<p><strong>The result :</strong> <a href=""https://i.stack.imgur.com/kj4db.png"" rel=""nofollow noreferrer"">The result</a></p>
<p>I wanted to ask you why the data parameter isn't nil?
With 0 bytes it's not considered as nil and I'm not going in the right loop in my code.</p>
<p><em>I tried a lot of breakpoints, but I still can't figure it out.
But one thing is really strange. If I put and error in the handler with nil data, the data will be nil.
Maybe it has something to do with the <code>didFailWithError</code> function?
This function forces data to be nil somehow?</em></p>
",https://stackoverflow.com/questions/74612567/unit-testing-with-urlprotocol-subclassing-returns-a-0-bytes-data-instead-of-nil,"['ios', 'swift', 'unit-testing', 'url-scheme']",147,False,0,1
Angular &amp; Jasmin unit testing &quot;queryAll(By.css&quot; is not working with NG elements,"<p>So I have this strange problem that I need fixed in order to complete a unit test for a project I'm working on.</p>
<p>My unit test currently looks like this:</p>
<pre><code>    it('should display the navbar list', () =&gt; {

    component.courses = jsonData.hamburgerMenu[0].menuItems;

    fixture.detectChanges;
  
    const links = el.queryAll(By.css(&quot;.NavMenuItem&quot;));
    
    expect(links).toBeTruthy(&quot;Could not find links&quot;);
    
    console.log(jsonData.hamburgerMenu[0].menuItems)
    
    console.log(links);    

  });
</code></pre>
<p>with the corresponding HTML looking like this:</p>
<pre><code>&lt;div *ngFor=&quot;let appMenuItem of courses; let i=index;&quot; class=&quot;NavMenuItem&quot;&gt;
</code></pre>
<p>The problem is, when I console.log <em>links</em> with an HTML element WITHOUT an &quot;ngIf&quot; or &quot;ngFor&quot; statement, it returns a &quot;[DebugElement].&quot; If I console.log an HTML element WITH an &quot;ngIf&quot; or &quot;ngFor&quot; statement, it gives me a &quot;[ ].&quot; This is problematic because I need to include the following code for my unit test to work:</p>
<pre><code>expect(links.length).toBe(12, &quot;Unexpected number of links&quot;);   
</code></pre>
<p>but, if my <em>queryAll(By.css</em> is returning nothing when used on an HTML component with an &quot;ngFor,&quot; then that condition will not work. How do I solve this issue?</p>
<p>For those of you who are wondering, yes, the mock data is there. <em>jsonData.hamburgerMenu[0].menuItems</em> contains the following data:</p>
<p><a href=""https://i.stack.imgur.com/QeqRa.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/QeqRa.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/72916349/angular-jasmin-unit-testing-queryallby-css-is-not-working-with-ng-elements,"['angular', 'typescript', 'unit-testing', 'jasmine', 'karma-jasmine']",824,False,0,1
Angular/Jest/RxJS Unit Testing TypeError: Cannot read properties of undefined (reading &#39;pipe&#39;),"<p>I am trying to test a method which listens to a <code>keyup</code> event from an input box using RxJS's <code>fromEvent</code>.</p>
<p>I am getting an error:</p>
<pre><code>TypeError: Cannot read properties of undefined (reading 'pipe')

      67 |     this.destroy$.next();
      68 |     this.destroy$.complete();
    &gt; 69 |   }
         |    ^
      70 |
      71 |   onCreateButtonClick(): void {
      72 |     this.listModalWrapper.open({

      at ListComponent.listenToScrollEvent (src/lib/landing/lists.component.ts:69:13)
      at ListComponent.ngAfterViewInit (src/lib/landing/lists.component.ts:62:10)
      at callHook (../../../../node_modules/@angular/core/fesm2020/core.mjs:2549:22)
      at callHooks (../../../../node_modules/@angular/core/fesm2020/core.mjs:2518:17)
      at executeInitAndCheckHooks (../../../../node_modules/@angular/core/fesm2020/core.mjs:2469:9)
      at refreshView (../../../../node_modules/@angular/core/fesm2020/core.mjs:9570:21)
      at renderComponentOrTemplate (../../../../node_modules/@angular/core/fesm2020/core.mjs:9613:9)
      at tickRootContext (../../../../node_modules/@angular/core/fesm2020/core.mjs:10844:9)
      at detectChangesInRootView (../../../../node_modules/@angular/core/fesm2020/core.mjs:10869:5)
      at RootViewRef.detectChanges (../../../../node_modules/@angular/core/fesm2020/core.mjs:21465:9)
      at ComponentFixture._tick (../../../../node_modules/@angular/core/fesm2015/testing.mjs:140:32)
      at ../../../../node_modules/@angular/core/fesm2015/testing.mjs:153:22
      at _ZoneDelegate.Object.&lt;anonymous&gt;._ZoneDelegate.invoke (../../../../node_modules/zone.js/bundles/zone-testing-bundle.umd.js:409:30)
      at ProxyZoneSpec.Object.&lt;anonymous&gt;.ProxyZoneSpec.onInvoke (../../../../node_modules/zone.js/bundles/zone-testing-bundle.umd.js:3803:43)
      at _ZoneDelegate.Object.&lt;anonymous&gt;._ZoneDelegate.invoke (../../../../node_modules/zone.js/bundles/zone-testing-bundle.umd.js:408:56)
      at Object.onInvoke (../../../../node_modules/@angular/core/fesm2020/core.mjs:25574:33)
      at _ZoneDelegate.Object.&lt;anonymous&gt;._ZoneDelegate.invoke (../../../../node_modules/zone.js/bundles/zone-testing-bundle.umd.js:408:56)
      at Zone.Object.&lt;anonymous&gt;.Zone.run (../../../../node_modules/zone.js/bundles/zone-testing-bundle.umd.js:169:47)
      at NgZone.run (../../../../node_modules/@angular/core/fesm2020/core.mjs:25428:28)
      at ComponentFixture.detectChanges (../../../../node_modules/@angular/core/fesm2015/testing.mjs:152:25)
      at src/lib/landing/lists.component.spec.ts:108:13
      at _ZoneDelegate.Object.&lt;anonymous&gt;._ZoneDelegate.invoke (../../../../node_modules/zone.js/bundles/zone-testing-bundle.umd.js:409:30)
      at ProxyZoneSpec.Object.&lt;anonymous&gt;.ProxyZoneSpec.onInvoke (../../../../node_modules/zone.js/bundles/zone-testing-bundle.umd.js:3803:43)
      at _ZoneDelegate.Object.&lt;anonymous&gt;._ZoneDelegate.invoke (../../../../node_modules/zone.js/bundles/zone-testing-bundle.umd.js:408:56)
      at Zone.Object.&lt;anonymous&gt;.Zone.run (../../../../node_modules/zone.js/bundles/zone-testing-bundle.umd.js:169:47)
      at Object.wrappedFunc (../../../../node_modules/zone.js/bundles/zone-testing-bundle.umd.js:4288:34)
</code></pre>
<pre><code>private listenToFilterListsEvent(): void {
    fromEvent(this.filterLists.nativeElement, 'keyup')
      .pipe(
        takeUntil(this.destroy$),
        tap(() =&gt; {
          this.filterByText = this.filterLists.nativeElement.value ?? '';
        })
      )
      .subscribe();
  }
</code></pre>
<p>Unit Test:</p>
<pre><code>describe('listenToFilterListsEvent', () =&gt; {
    it('should listen to filterLists event and call filterLists method', () =&gt; {
      const fromEventSpy = jest
        .spyOn(rxjs, 'fromEvent')
        .mockReturnValue(of([1, 2, 3]));
      component.filterLists.nativeElement.value = 'abc';
      (component as any).listenToFilterListsEvent();
      expect(fromEventSpy).toHaveBeenCalled();
    });
  });
</code></pre>
<p>I tried to test a similar function which listens to <code>scroll</code> event of a <code>div</code> but I didn't get an error there:
Method:</p>
<pre><code>private listenToScrollEvent(): void {
fromEvent(this.listContainer.nativeElement, 'scroll')
  .pipe(
    takeUntil(this.destroy$),
    tap(() =&gt; {
      const element = this.listContainer.nativeElement;
      this.scrollStarted = this.hasScrollStarted(element.scrollTop);
    })
  )
  .subscribe();
</code></pre>
<p>}</p>
<p>Unit Test:</p>
<pre><code>describe('listenToScrollEvent', () =&gt; {
it('should listen to scroll event and call hasScrollStarted method', () =&gt; {
  const hasScrollStartedSpy = jest
    .spyOn(component as any, 'hasScrollStarted')
    .mockReturnValue(true);
  const fromEventSpy = jest
    .spyOn(rxjs, 'fromEvent')
    .mockReturnValue(of([1, 2, 3]));
  component.listContainer.nativeElement.scrollTop = 1;
  (component as any).listenToScrollEvent();
  expect(fromEventSpy).toHaveBeenCalled();
  expect(hasScrollStartedSpy).toHaveBeenCalled();
  expect(component.scrollStarted).toBeTruthy();
});
</code></pre>
<p>});</p>
<p>Both of these methods get called in <code>NgAfterViewInit</code> lifecycle hook.</p>
<pre><code>  ngAfterViewInit(): void {
    this.listenToScrollEvent();
    this.listenToFilterListsEvent();
  }

  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
</code></pre>
<p>Is there anything that is missing here?</p>
",https://stackoverflow.com/questions/72919499/angular-jest-rxjs-unit-testing-typeerror-cannot-read-properties-of-undefined-r,"['angular', 'unit-testing', 'jestjs', 'rxjs']",246,False,0,0
Unit Testing a repo class gives error System.NotSupportedException because of SqlMapper.Execute Extension methods,"<p>I'm pretty new to c# (and fwiw, moq) and I'm trying learn our product by writing unit tests.  We have the following method in a database repository class:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using Newtonsoft.Json;
using Serilog;

    public bool UpdateInactiveWidgets(List&lt;Widgets&gt; widgets)
    {
        int rowsUpdated;
        using (var conn = new SqlConnection(connectionString))
        {              
            rowsUpdated= conn.Execute(@&quot;UPDATE dbo.Widgets
                            SET [Status] = 'Inactive'
                            WHERE ID = @ID&quot;, widgets);
        }
        return rowsUpdated == widgets.Count ? true : false;         
    }
</code></pre>
<p>I'd like to write a unit test for this, but I can't seem to get the mock connection going.
Based on other posts about mocking a connection, I've added the following to my unit test:</p>
<pre><code>    [Fact]
    public void Update_Inactive_Widgets()
    {
        var repo = new WidgetRepository();
        var inActiveWidgets = new List&lt;Widgets&gt;()
        { //logic to create 2 widgets };

        var connectionMock = new Mock&lt;IDbConnection&gt;();
        connectionMock.Setup(m =&gt; m.Execute(It.IsAny&lt;string&gt;(),It.IsAny&lt;object&gt;(),null,null,null)).Returns(2);

        var result = repo.UpdateInactiveWidgets(inActiveWidgets );
        Assert.Equal(inActiveWidgets.Count,result);
</code></pre>
<p>The unit test fails on the connectionMock.Setup line with this error:</p>
<blockquote>
<p>System.NotSupportedException: 'Unsupported expression: m =&gt;
m.Execute(It.IsAny(), It.IsAny(), null, null, null)
Extension methods (here: SqlMapper.Execute) may not be used in setup /
verification expressions.'</p>
</blockquote>
<p>I've found this article and am still making my way through to see how I can apply the points to my example:  <a href=""https://taurit.pl/moq-extension-methods-may-not-be-used-in-setup-verification-expressions/"" rel=""nofollow noreferrer"">https://taurit.pl/moq-extension-methods-may-not-be-used-in-setup-verification-expressions/</a></p>
<p>But if you have any suggestions I'd appreciate it. I apologize in advance if I'm missing something basic.</p>
<p><strong>Edit 2</strong></p>
<p>If I made the connection a global variable in the class... and move the logic that connects outside the method under test would that help?</p>
<p>Sample pseudocode:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using Dapper;
using Newtonsoft.Json;
using Serilog;

    public UpdateInactiveWidgets()
    {
      var _conn;
    }
    public Connect_db()
    {
        _conn = new SqlConnection(connectionString);
    }
    public DisConnect_db()
    {
        //some logic to kill the db connection?
    }

    public bool UpdateInactiveWidgets(List&lt;Widgets&gt; widgets)
    {
        int rowsUpdated;
        //would the using() still be applicable? 
        using (_conn) 
        {              
            rowsUpdated= _conn.Execute(@&quot;UPDATE dbo.Widgets
                            SET [Status] = 'Inactive'
                            WHERE ID = @ID&quot;, widgets);
        }
        return rowsUpdated == widgets.Count ? true : false;         
    }
</code></pre>
",https://stackoverflow.com/questions/74461782/unit-testing-a-repo-class-gives-error-system-notsupportedexception-because-of-sq,"['c#', 'unit-testing']",61,True,0,2
Angular Unit Testing: Access the Observable @Input variable value passed from parent component,"<p>I'm new to testing. I'm writing a unit test for an Input variable which is being set in parent compoent.
The value is an observable which use forkJoin.</p>
<p>parent.component.ts</p>
<pre><code>public dataObj$: Observable&lt;{mixType}&gt;;

  public ngOnInit(): void {
    this.showChildComponent();
  }
private showChildComponent(): void {
    this.dataObj$ = forkJoin({
      userRoleObj: this.sessionService.sessionInfo$.pipe(take(1)),
      baseCountry: this.intlConfig.country$.pipe(take(1)),
      hasOrgEnabled: this.hasEnable$().pipe(take(1)),
      isAutoApproved: this.onlineService.isAutoApproved$().pipe(take(1)),
    });
  }
</code></pre>
<p>parent.template.html</p>
<pre><code>&lt;child-comp *ngIf=&quot;dataObj$ | async as data&quot;  [data]=&quot;data&quot; &gt;&lt;/child-comp&gt;
</code></pre>
<p>child.component.ts</p>
<pre><code>export class ChildComponent implements OnInit {
  @Input data!: Observable&lt;mixtype&gt; 
  public settings: any;
  public show = false;
  
constructor() {}
  public ngOnInit(): void {
    this.settings = this.data; // I want data  to be accessible inside the test case
    this.setValidation();
  }

  public setValidation(): void {
    const isAdmin = this.settings.userRoleObj.profile.type === UI_CONSTS.IS_ADMIN ? true : false;
    if (
      this.settings.isAutoApproved &amp;&amp;
      isAdmin &amp;&amp;
      this.settings.baseCountry === UI_CONSTS.BASE_COUNTRY
    ) {
      this.show = true;
      this.setBulletText();
    } else {
      this.show = false;

    }
  }

  public setBulletText(): void {
    // some code to set the html content
  }

}
</code></pre>
<p>child.template.html</p>
<pre><code>&lt;div *ngIf=&quot;show&quot;&gt;
    &lt;div&gt; .... &lt;/div&gt;
    &lt;h1&gt; ...&lt;/h1&gt;
&lt;/div&gt;

</code></pre>
<p>child-component.spec.ts</p>
<pre><code>const MOCK_IPD_SETTINGS: {
  baseCountry: string;
  isAutoApproved: boolean;
  userRoleObj: any;
  hasOrgEnabled: boolean;
} = {
 baseCountry: BASE_COUNTRY,
  isAutoApproved: true,
 userRoleObj: {
    profile: {
      type: '2',
    },
  },
 hasOrgEnabled: boolean;
};
describe('ChildComponent', () =&gt; {
  let component: ChildComponent;
  let fixture: ComponentFixture&lt;ChildComponent&gt;;

  function setUp({ MOCK_SETTINGS }) {
    component.data = of(MOCK_SETTINGS);
    fixture.detectChanges(); // final change
  }


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

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(InstaPayIpdComponent);
    component = fixture.componentInstance;
    // component.data = of(MOCK_SETTINGS);
    
  });


  it('onClickGetStarted', fakeAsync(() =&gt; {
    fixture.detectChanges();
    expect(component.show).toBe(true);
  }));
  it('show open modal',() =&gt; {
     setUp({...});
    expect(component.isAutoApproved).toBe(false);
   });
});
</code></pre>
<p>I'm writing unit test case for the child component. I'm not sure how to access the data or settings object inside the test case.
I'm getting this error :</p>
<pre><code>TypeError: Cannot read property 'profile' of undefined
``
</code></pre>
",https://stackoverflow.com/questions/74681488/angular-unit-testing-access-the-observable-input-variable-value-passed-from-pa,"['angular', 'unit-testing', 'testing', 'jestjs', 'observable']",293,True,0,1
Setup/Configuring unit-testing with google test in C++ using Visual Studio 2020,"<p>If you can't get your solution to compile, for example by receiving an unresolved externals error, take a look at the answer section and recreate the steps listed there.</p>
",https://stackoverflow.com/questions/73372820/setup-configuring-unit-testing-with-google-test-in-c-using-visual-studio-2020,"['c++', 'visual-studio', 'unit-testing', 'googletest']",302,True,-1,1
How can i run Microsoft Unit Testing Framework for C++ using github actions?,"<p>i'm trying to run my unit test which is using the Microsoft Unit Testing Framework for C++ using Github actions.</p>
<p>I'v tried adding the DLL with the exe of the sln but it doesn't seem to work.</p>
<p>build:</p>
<pre><code>runs-on: windows-latest

steps:
# using tmp v3 git branch 
- uses: actions/checkout@v3
# getting dependencies 
- name: getting dependencies
  working-directory: UnitTest
  run:  ./BuildTest.bat
# set up 
- name: set up
  working-directory: UnitTest
  run:  ./SetUpTest.bat
# adding msbuild path 
- name: add msbuild to PATH
  uses: microsoft/setup-msbuild@v1.1
# # building sln in release 
# - name: build release
#   run: msbuild Dare.sln /p:Configuration=Release
# building sln in debug 
- name: build debug
  run: msbuild Dare.sln /p:Configuration=Debug

# run unit test
- name: list
  working-directory: bin/Debug-windows-x86_64/DareEditor
  run : ls 

# run unit test
- name: run unit test
  working-directory: bin/Debug-windows-x86_64/DareEditor
  # run : ls 
  # run: ./DareEditor.exe /Platform:x64 ./x64\Debug\UnitTest1.dll
  # run: ./DareEditor.exe /Platform:x64 ./x64\Debug\UnitTest1.dll
  run: ./DareEditor.exe 
</code></pre>
",https://stackoverflow.com/questions/73475724/how-can-i-run-microsoft-unit-testing-framework-for-c-using-github-actions,"['c++', 'unit-testing', 'github', 'github-actions']",128,True,0,1
How to conduct C unit testing with googletest if using the _Generic macro,"<p>I am trying to use Googletest to execute unit tests on a C macro that uses the <code>_Generic</code> macro.  The purpose of using the <code>_Generic</code> macro exists in this case to ensure that the user is passing a <code>typedef struct</code> that can only be one of several different <code>typedefs</code> as a form of run time type checking on the macro.  A simple snippet is shown below.</p>
<pre><code>// This is written in the vector.h file
#include &lt;stdbool.h&gt;
#include &lt;stdio.h&gt;

#define IS_TYPE_VALID(T) _Generic( (T), SVector: true, \
                                        IVector: true, \
                                        default: false)

#define INIT_VECTOR(vec, length) do {
    bool dat_type = IS_TYPE_VALID(vec);
} while (0)



typedef struct 
{ 
    short *array;
    size_t allocated_length;
    size_t active_length;
} SVector;

typedef struct
{
    int *array;
    size_t allocated_length;
    size_t active_length;
} IVector;
</code></pre>
<p>The Googletest test case looks like the example below.</p>
<pre><code>#include &lt;gtest/gtest.h&gt;
extern &quot;C&quot; {
    #include &quot;vector.h&quot;
}
TEST (test_short_int, test_push_vector) {
    SVector vec;
    size_t length = 5;
    INIT_VECTOR(vec, length);
}
</code></pre>
<p>When I try to compile the simple code I get the following error.
<code>error: expected primary-expression before ':' token #define IS_TYPE_VALID(T) _Generic( (T), SVector: true, \</code>
This error implies that Googletest does not recognize the <code>_Generic</code> macro as legitimate code.  This may be an issue of trying to test C code with a C++ framework, but before I retool the unit tests to a C framework like CMocka, I would like to see if there is a way to fix this with Googletest.  Any help would be appreciated.</p>
",https://stackoverflow.com/questions/73534634/how-to-conduct-c-unit-testing-with-googletest-if-using-the-generic-macro,"['c', 'macros', 'googletest']",220,False,0,0
Unit testing Delete Method of API producing -&gt; Can not instantiate proxy of class,"<p>I'm trying to write a Unit test case for the delete method of the below controller</p>
<pre><code>public class AssetProxyController : Controller
    {
       
        private IRiskAssetProxyService _assetProxyService;       
       
        public AssetProxyController( IRiskAssetProxyService assetProxyService)
        {
            _assetProxyService = assetProxyService;
        }

        [HttpDelete(&quot;{assetId}&quot;)]
        public ActionResult Delete(string assetId)
        {
            if (_assetProxyService.DeleteAssetProxyMapping(assetId))
            {
                return Ok(&quot;AssetProxy Deleted&quot;);
            }
            else
            {
                return BadRequest(&quot;Unable to delete AssetProxy&quot;);
            }
        }
  }
</code></pre>
<p><em><strong>Test</strong></em></p>
<pre><code>   [TestMethod]
    public void Delete_ShouldReturnDeleteAssetProxy()
    {
        //Mock
       var mockContext = new Mock&lt;MainDBContext&gt;();
       var faker = AutoFaker.Create();
       var assetProxyMappings = faker.Generate&lt;List&lt;AssetProxyMapping&gt;&gt;();
       var mockAssetProxyDbSet = GetQueryableMockDbSet&lt;AssetProxyMapping&gt;(assetProxyMappings);  
       mockContext.Setup(c =&gt; c.AssetProxyMapping).Returns(mockAssetProxyDbSet);
       //Test
       var mocklogger = new Mock&lt;ILogger&lt;RiskDataControllerDbAccess&gt;&gt;();
       var positiondbaccess = new Mock&lt;RiskAssetProxyDbAccess&gt;(mockContext,mocklogger);
       var mockserviceLogger = new Mock&lt;ILogger&lt;RiskAssetProxyService&gt;&gt;();

        var positionService = new Mock&lt;RiskAssetProxyService&gt;(positiondbaccess, mockserviceLogger);
       var positionController = new AssetProxyController(positionService.Object);
          
        Assert.AreEqual(true, true);
    }
</code></pre>
<p>But i keep getting the exception</p>
<pre><code>Test method Risk.DataService.UnitTests.API.AssetProxyControllerTests.Delete_ShouldReturnDeleteAssetProxy threw exception: 
    Castle.DynamicProxy.InvalidProxyConstructorArgumentsException: Can not instantiate proxy of class: Risk.DataServices.RiskAssetProxyService.
    Could not find a constructor that would match given arguments:
    Moq.Mock`1[Risk.DataServices.RiskAssetProxyDbAccess]
    Moq.Mock`1[Microsoft.Extensions.Logging.ILogger`1[Risk.DataServices.RiskAssetProxyService]]
</code></pre>
",https://stackoverflow.com/questions/71792897/unit-testing-delete-method-of-api-producing-can-not-instantiate-proxy-of-clas,"['c#', 'asp.net', 'unit-testing']",484,True,0,1
EF Core 3.1 - Unit Testing a call to a context that returns null,"<p>Using Xunit and Moq, I am attempting to write a unit test to test that the following code block will log an error when the call to the context returns null.</p>
<pre><code>                var entities = await _context.Charges
                .Select(c =&gt; chargeDTO.FromEntity(c))
                .ToListAsync(cancellationToken);

            if (entities == null)
            {
                _logger.LogError($&quot;Entities not found.&quot;);
                return null;
            }
</code></pre>
<p>I'm creating an in-memory database context for the unit tests, but the issue is that I can't work out how to mock the call to the context so that it returns null. The closest I've been able to get is having it return an empty collection. Is what I'm attempting actually possible, or am I trying to force a square peg through a round hole?</p>
",https://stackoverflow.com/questions/70664366/ef-core-3-1-unit-testing-a-call-to-a-context-that-returns-null,"['entity-framework-core', 'moq', 'asp.net-core-3.1', 'xunit']",264,False,0,1
How do you set the apiversion when unit testing a versioned api controller?,"<p>I am trying to test a versioned controller and one of the routes uses <code>HttpContext.GetRequestedApiVersion</code> to make a decision. Whilst I can test for null in the controller, and thereby set a &quot;default&quot; version, I don't know how to set the api version in my unit test so that I can test the &quot;non-default&quot; path. Is this possible? Below is the code where I setup the mock controller.</p>
<pre><code>var analysisController = new AnalysisController(mockAnalyticsService.Object, mockBatchService.Object, mockConfig.Object);

addHttpContext(analysisController);
addUserContext(analysisController, mockUserContext.Object);
analysisController.HttpContext.Request.Headers.Add(&quot;Content-MD5&quot;, &quot;/F4DjTilcDIIVEHn/nAQsA==&quot;);
analysisController.HttpContext.Request.Headers.Add(&quot;Content-Type&quot;, &quot;application/octet-stream&quot;);

</code></pre>
",https://stackoverflow.com/questions/71399932/how-do-you-set-the-apiversion-when-unit-testing-a-versioned-api-controller,"['c#', 'asp.net']",364,True,0,1
How to organise test files for unit testing in Python with sub folders,"<p>I was wondering how I can setup my directory structure to enable importing any python file from <code>project</code> in the <code>tests</code> directory to test it?</p>
<p>Currently I'm getting a Module not found error when trying to import a class from <code>some_file.py</code> in <code>some_file_tests.py</code>.</p>
<pre><code>Traceback (most recent call last):
  File &quot;e:\Documents\GitHub\Project\tests\util\some_file_test.py&quot;, line 3, in &lt;module&gt;
    from project.util.some_file import SomeFile
ModuleNotFoundError: No module named 'project'
</code></pre>
<p><code>tests/util.some_file_test.py</code></p>
<pre class=""lang-py prettyprint-override""><code>from project.util.some_file import SomeClass
</code></pre>
<p>Here is the directory structure</p>
<pre><code>📦Project
 ┣ 📂project
 ┃ ┣ 📂util
 ┃ ┃ ┣ 📜some_file.py
 ┃ ┃ ┗ 📜__init__.py
 ┃ ┗ 📜__init__.py
 ┣ 📂tests
 ┃ ┣ 📂util
 ┃ ┃ ┗ 📜some_file_test.py
</code></pre>
<p>And here is an example of what the <code>__init__.py</code> files contain.</p>
<p><code>project/__init__.py</code></p>
<pre class=""lang-py prettyprint-override""><code>from . import util
</code></pre>
<p><code>project/util/__init__.py</code></p>
<pre class=""lang-py prettyprint-override""><code>from . import some_file
</code></pre>
",https://stackoverflow.com/questions/71438481/how-to-organise-test-files-for-unit-testing-in-python-with-sub-folders,"['python', 'unit-testing', 'testing']",355,True,0,2
Python unit testing that a method does not call logging.info with specific messages,"<p>I am trying to unit test method that calls <code>logging.info</code> three times – first time it's logging local variables for the method, another two times it's logging messages that get triggered in case a certain condition is fulfilled.</p>
<p>In one of my test cases, <code>logging.info</code> gets called only once – to log local variables. The other two calls are not supposed to happen. I'm trying to include that in my unit tests but using <code>unittest.mock.Mock.assert_not_called()</code> is quite naturally out of question because my <code>logging.info</code> gets called once. (However, I can't test <code>logging.info</code> message for local variables.)</p>
<pre class=""lang-py prettyprint-override""><code>class Test_create_s3_file(unittest.TestCase):
    ...
    
    def setUp(self):
        self.LOGGER = logging
        ...

    def test_success_basic(self):
        # Mocks
        self.LOGGER.info = MagicMock()
        ...
        # Calls
        ...
        self.LOGGER.info.assert_not_called()
        # Does not work because it has one call for local variables
</code></pre>
",https://stackoverflow.com/questions/73463683/python-unit-testing-that-a-method-does-not-call-logging-info-with-specific-messa,"['python', 'unit-testing', 'python-unittest.mock']",159,True,0,1
How do i do unit testing on a python class with a constructor?,"<p>I am new to Pytest and i wanted to do unit testing, but it fails saying the class has a constructor.
file app.py:</p>
<pre><code>class SQLService:
    def __init__(self):
        self.db_engine = create_engine(db_string, connect_args={'options': '-csearch_path={}'.format(&quot;schema_name&quot;)}, echo=False)
        base = declarative_base()
        session = sessionmaker(self.db_engine)
        self.session = session()
        base.metadata.create_all(self.db_engine)

    def insert_row(self, name, project_name):
        table = MyTable(
        Name=name, 
        Project=project_name, 
        )

        self.session.add(table)
        self.session.commit()
</code></pre>
<p>Same for this db_class.py:</p>
<pre><code>class MyTable(base):
    __tablename__ = &quot;table_name&quot;
    Name = Column(String)
    Project = Column(String)
</code></pre>
<p>Errors:</p>
<blockquote>
<p>PytestCollectionWarning: cannot collect test class 'SQLService'
because it has a __init_constructor (from app.py)</p>
<p>PytestCollectionWarning: cannot collect test class 'String' because it
has a __init__constructor ( from: db_class.py)</p>
</blockquote>
<p>Is there a way around this or a different tool that i can use?</p>
<p>Thank you</p>
",https://stackoverflow.com/questions/72373034/how-do-i-do-unit-testing-on-a-python-class-with-a-constructor,"['python', 'unit-testing', 'pytest']",53,False,0,0
Why sometimes second test executes after first one with Angular Jasmine Unit Testing?,"<p>I am learning how to Angular Test and something strange happens to me. Thing is, WITH THE SAME EXACT CODE, when I do <code>ng test</code> sometimes the substract IT block is executed before the add IT block, when this one is supposed to be executed the first (and sometimes it actually does):</p>
<p>This is the spec code:</p>
<pre><code>import { CalculatorService } from './calculator.service';
describe ('calculatorService',()=&gt;{

    let calculator:CalculatorService;
    let loggerSpy:any;

    beforeEach(()=&gt;{

        console.log (&quot;calling the beforeEach&quot;);

        loggerSpy=jasmine.createSpyObj('LoggerServiceSpy', ['log']);

        calculator= new CalculatorService(loggerSpy);

    });


    it('should add two numbers', ()=&gt;{


        let result=calculator.add(2,2);

        console.log (&quot;add test&quot;);

        expect(result).toBe(4);
        expect(loggerSpy.log).toHaveBeenCalledTimes(1);
    });

    it('should substract two numbers', ()=&gt;{




        let result=calculator.subtract(2,2);

        console.log (&quot;substract test&quot;);

        expect(result).toBe(0, &quot;unexpected substracion result&quot;);
        expect(loggerSpy.log).toHaveBeenCalledTimes(1);

        
    });

});
</code></pre>
<p>And this what I obtain sometimes:</p>
<p><a href=""https://i.stack.imgur.com/g2slI.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/g2slI.png"" alt=""enter image description here"" /></a></p>
<p>Other times I just kill terminal (<strong>integrated terminal in Visual Studio Code, it this helps you</strong>), execute <code>ng test</code> again, and normal flow is done... What am I doing wrong?</p>
<p><a href=""https://i.stack.imgur.com/8hyBk.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/8hyBk.png"" alt=""enter image description here"" /></a></p>
<p><strong>EDIT:</strong> I add the calculator and logger services code in case it helps (also I don´t know why <code>this.logger.log</code> test is not outputed when I do the <code>ng test</code> but I guess that is another question</p>
<p><strong>calculator-service.ts</strong></p>
<pre><code>import {Injectable} from '@angular/core';
import {LoggerService} from './logger.service';


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


  constructor(private logger: LoggerService) {

  }

  add(n1: number, n2:number) {
    this.logger.log(&quot;Addition operation called&quot;);

    return n1 + n2;
  }

  subtract(n1: number, n2:number) {
    this.logger.log(&quot;Subtraction operation called&quot;);
    return n1 - n2;
  }


}
</code></pre>
<p><strong>logger-service.ts</strong></p>
<pre><code>
import {Injectable} from '@angular/core';


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

  log(message:string) {
    console.log(message);
  }

}

</code></pre>
",https://stackoverflow.com/questions/74082206/why-sometimes-second-test-executes-after-first-one-with-angular-jasmine-unit-tes,"['angular', 'unit-testing', 'testing', 'jasmine']",306,True,0,1
Unit testing for API call which return different data in jest - React JS,"<p>I am learning more about testing React components using Jest and testing-library and have also started to implement the same in my project. i came across a scenario where a api call returns different data based on some scenarios. below are the 2 different response format from the api</p>
<pre><code>records: [{
           &quot;id&quot;: 33,
           &quot;deviceId&quot;: &quot;1234&quot;,
           &quot;status&quot;: &quot;ACTIVE&quot;
           &quot;customer&quot;: {
                    &quot;email&quot;: &quot;sams72@gmail.com&quot;,
                    &quot;firstName&quot;: &quot;Sam&quot;,
                    &quot;lastName&quot;: &quot;Dan&quot;,
                    &quot;patientId&quot;: 43
           }
           },]
</code></pre>
<p>and</p>
<pre><code> records: [{
           &quot;id&quot;: 33,
           &quot;deviceId&quot;: &quot;1234&quot;,
           &quot;status&quot;: &quot;ACTIVE&quot;
           },]
</code></pre>
<p>Now i have the mock response in my test file as below</p>
<pre><code>let mockGetDevices = jest.fn(() =&gt; {
    return Promise.resolve({
        records: [{
            &quot;id&quot;: 33,
            &quot;deviceId&quot;: &quot;1234&quot;,
            &quot;status&quot;: &quot;ACTIVE&quot;
            &quot;customer&quot;: {
                &quot;email&quot;: &quot;sams72@gmail.com&quot;,
                &quot;firstName&quot;: &quot;Sam&quot;,
                &quot;lastName&quot;: &quot;Dan&quot;,
                &quot;patientId&quot;: 43
            }
        },]
    })
});


jest.mock('..//services/device.service', () =&gt; {
    return function () {
        return { getDevices: mockGetDevices };
    };
});


test(&quot;should make getdevice calls&quot;, async () =&gt; {
        const { getByTestId } = renderDeviceDetails();
        await waitFor(async () =&gt; {
            const switch = await getByTestId('deactivated-devices');
            fireEvent.change(switch);
            expect(mockGetDevices).toHaveBeenCalledTimes(1);
        })
    }) 
</code></pre>
<p>Above test case covers the scenario where the api response have <em><strong>customer</strong></em> in the response. i also want to test scenario where the response dont have <em><strong>customer</strong></em>. How do i achieve this with jest where same api returns different dataset.</p>
<p>Note : i came across <a href=""https://jestjs.io/docs/mock-function-api#mockfnmockresolvedvalueoncevalue"" rel=""nofollow noreferrer"">mockImplementationOnce</a> but doesn't seems to be ideal solution when the number of test cases are more.</p>
",https://stackoverflow.com/questions/72015783/unit-testing-for-api-call-which-return-different-data-in-jest-react-js,"['reactjs', 'jestjs', 'react-testing-library']",1111,False,0,0
"Make a stub for Include in C# and Entity Framework (Moq,unit testing)?","<p>Currently I use the packages <code>Moq</code> and <code>EntityFrameworkCoreMock</code> for unit tests in .NET 6.0. Since I haven't found a method stub for include yet, I can't test code with include statements (I also tried several other packages that mock DbSet, but none has worked with include).</p>
<pre><code>// example
User u = await context.Users
                      .Include(i =&gt; i.Notifications)
                      .Where(s =&gt; string.Equals(s.UserId, &quot;user123&quot;))
                      .FirstOrDefaultAsync();
        
// u.Notifications = null
</code></pre>
<p>I also tried to use the following method, that I can mock then, but this only works for one include statement and not when I have <code>.Include(..).ThenInclude(..)</code></p>
<pre><code>public static System.Threading.Tasks.Task&lt;TSource&gt; FirstOrDefaultAsyncWithInclude&lt;TSource, TProperty&gt; (this System.Linq.IQueryable&lt;TSource&gt; source, System.Linq.Expressions.Expression&lt;Func&lt;TSource, TProperty&gt;&gt; path) where TSource : class 
{
    return source.Include(path).FirstOrDefaultAsync(); 
}
</code></pre>
<p>I don't want to use the In-Memory database provider, because I write unit tests and because of the performance.</p>
<p>Does anyone know a solution to the problem? Thanks in advance :)</p>
",https://stackoverflow.com/questions/74251462/make-a-stub-for-include-in-c-and-entity-framework-moq-unit-testing,"['c#', 'linq', '.net-core', 'entity-framework-core', 'moq']",140,False,0,0
Unit Testing &quot;Object reference not set to an instance of an object.&quot; error,"<p>I want to test my service, and i still have this error after hours of trying to find how should i make this right</p>
<pre><code> public async Task DeleteAsync(string entityId, IEntityRef child)
    {
        Requires.NotNull(entityId, nameof(entityId));
        Requires.NotNull(child, nameof(child));

        await using IAtomicScope atomicScope = _atomicScopeFactory.Create();
        PartnerBase parentPartner = await _partnerStore.GetAsync(entityId, atomicScope);
        IEntityRef parent = new EntityRef
        {
            Id = entityId,
            EntityType = parentPartner.EntityType
        };

        await _validator.ValidateOnDeleteLinkAsync(parent, child);
 
        IContextDetail currentContext = await _contextService.GetCurrentContextAsync();
        PersonModel person = await _verifier.GetAccessibleAsync(child, atomicScope);
        await _verifier.VerifyManagerialPermissionsAsync(currentContext, parent, atomicScope);

        IEntityMembership membership = new EntityMembership
        {
            Parent = parent.ToMembershipEntityRef(),
            Entity = child.ToMembershipEntityRef()
        };

        await _membershipService.DeleteAsync(membership, atomicScope);

        await NotifyMembershipChanged(parent, null, person.UserOpenId, atomicScope);
        await atomicScope.CommitAsync();
    }
</code></pre>
<p>and my test</p>
<pre><code>public async void DeleteAsync_ParentNotPersonCorrectCall_MembershipDeleteCalled(EntityType entityType)
    {
        IEntityRef parent = _fixture.Build&lt;EntityRef&gt;()
                                    .With(q =&gt; q.EntityType, entityType)
                                    .Create();
        IEntityRef child = _fixture.Create&lt;EntityRef&gt;();
        PersonModel person = _fixture.Create&lt;PersonModel&gt;();

        IEntity entity = _fixture.Create&lt;Department&gt;();

        _verifier.Setup(v =&gt; v.GetAccessibleAsync(child, _atomicScope.Object))
                 .ReturnsAsync(person);

        _entityReaderService.SetupGetFirstByReferenceIdAsync(parent.GetReferenceId(), entity, _atomicScope.Object);

        await _service.DeleteAsync(parent.Id, child);

        IEntityMembership membership = new EntityMembership
        {
            Parent = parent.ToMembershipEntityRef(),
            Entity = child.ToMembershipEntityRef()
        };
        _membershipService.Verify(m =&gt; m.DeleteAsync(It.Is&lt;IEntityMembership&gt;(q =&gt; q.IsEquivalentTo(membership)), _atomicScope.Object), Times.Once);
    }
</code></pre>
<p>It throws an error saying</p>
<pre><code>Object reference not set to an instance of an object.
</code></pre>
<p>PS: It's my first question, please be kind and don't let it be the last one..
Thanks!</p>
",https://stackoverflow.com/questions/74099792/unit-testing-object-reference-not-set-to-an-instance-of-an-object-error,"['c#', '.net']",22,False,0,0
Unit testing OverflowException : Maximum retries of 10000 reached without finding a unique value,"<p>So I am working on some unit testing before I implement a new feature. I run my test and it fails with <code>OverflowException : Maximum retries of 10000 reached without finding a unique value</code> This is the test I'm running.</p>
<pre><code>    public function test_job_factory()
    {
        $client = Client::factory()-&gt;create();
        $accountHandler = AccountHandler::factory()-&gt;create();
        $user = User::factory()-&gt;create();

        $this-&gt;post('/login', [
            'email' =&gt; $user-&gt;email,
            'password' =&gt; 'password',
        ]);

        $user-&gt;givePermissionTo( 'manage jobs' );
        $clientContact = ClientContact::factory()-&gt;create();
        $job = Job::factory()-&gt;create();

        $this-&gt;assertTrue($job-&gt;id &gt; 0);
    }
</code></pre>
<p>The error seems to happen while creating the job itself. Tests above this test the other factories and are working.</p>
<p>Heres the JobFactory.php file:</p>
<pre><code>&lt;?php

namespace Database\Factories;

use App\Models\AccountHandler;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Job;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory&lt;\App\Models\Job&gt;
 */
class JobFactory extends Factory
{
    protected $model = Job::class;

    /**
     * Define the model's default state.
     *
     * @return array&lt;string, mixed&gt;
     */
    public function definition()
    {
        return [
            'title'              =&gt; $this-&gt;faker-&gt;company(),
            'is_active'          =&gt; 1,
            'is_draft'           =&gt; 0,
            'client_id'          =&gt; $this-&gt;faker-&gt;unique()-&gt;numberBetween(1, Client::count()),
            'account_handler_id' =&gt; $this-&gt;faker-&gt;unique()-&gt;numberBetween(1, AccountHandler::count()),
            'eclipse_contact_id' =&gt; $this-&gt;faker-&gt;unique()-&gt;numberBetween(1, User::count()),
            'client_contact_id'  =&gt; $this-&gt;faker-&gt;unique()-&gt;numberBetween(1, ClientContact::count()),
            'description'        =&gt; $this-&gt;faker-&gt;paragraphs(1),
        ];
    }
}
</code></pre>
<p>and the migration for this (create_jobs_table.php):</p>
<pre><code>&lt;?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table-&gt;id('number');
            $table-&gt;boolean( 'is_active' )-&gt;default(true);
            $table-&gt;boolean( 'is_complete' )-&gt;default(true);
            $table-&gt;string('title', 64)-&gt;nullable();
            $table-&gt;timestamps();
            $table-&gt;foreignId('author')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('users');
            $table-&gt;text('description')-&gt;nullable();
            $table-&gt;foreignId('client_id')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('clients');
            $table-&gt;foreignId('client_contact_id')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('client_contacts');
            $table-&gt;foreignId('account_handler_id')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('account_handlers');
            $table-&gt;date('expiry_date')-&gt;nullable();
            $table-&gt;date('artwork_deadline')-&gt;nullable();
            $table-&gt;date('proof_deadline')-&gt;nullable();
            $table-&gt;integer('redirect')-&gt;nullable();
            $table-&gt;boolean( 'is_draft' )-&gt;default(true);
            $table-&gt;foreignId('eclipse_contact_id')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('users');
            $table-&gt;foreignId('subscription_id')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('subscriptions');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('jobs');
    }
};
</code></pre>
<p>So what is wrong and why this loop here? I have added the minimum data that is needed to create a job so no idea what I've missed.</p>
<p>thanks</p>
<p>*** EDIT ***
I was asked to give a link to where I found the bad practice of using unique and numberBetween here is an example <a href=""https://stackoverflow.com/questions/70841813/laravel-factory-error-maximum-retries-of-10000-reached-without-finding-a-unique"">Laravel factory error &quot;Maximum retries of 10000 reached without finding a unique value&quot; when I use unique Faker method</a> this will not work as you expect!</p>
",https://stackoverflow.com/questions/72803431/unit-testing-overflowexception-maximum-retries-of-10000-reached-without-findin,"['php', 'laravel', 'phpunit', 'factory']",477,True,0,2
Laravel 8 Notification Unit Testing not working: The expected notification was not sent,"<p><strong>Context:</strong></p>
<ul>
<li>Laravel 8.83.18</li>
<li>PHPUnit 9.5.21</li>
<li>PHP 8.1.7</li>
</ul>
<p>I'm trying to implement (it's my first time) a Unit Test for a use case that sends an email as a Laravel Notification. I am implementing my web app with a Domain-Driven Design approach and, to simplify and debug, I've checked Laravel Official Documentation (<a href=""https://laravel.com/docs/8.x/mocking#notification-fake"" rel=""nofollow noreferrer"">https://laravel.com/docs/8.x/mocking#notification-fake</a>), and I am trying to make the simplest case work, but it doesn't (without using my DDD approach that sends the notification through a use case). I will show you my code:</p>
<p><strong>Test Class:</strong></p>
<pre><code>&lt;?php

declare(strict_types=1);

namespace Tests\Unit\Modules\Test;

use App\Models\User\User;
use App\Notifications\TestNotification;
use Illuminate\Support\Facades\Notification;
use Tests\TestCase;

class ExampleTest extends TestCase
{
    public function test_orders_can_be_shipped()
    {
        Notification::fake();

        $emil = 'johndoe@domain.com';
        $user = new User();
        $user-&gt;setAttribute('email', $emil);

        // Executing notification sending...
        Notification::route('mail',  $email)-&gt;notify(new TestNotification($user));

        // Assert a notification was sent to the given users...
        Notification::assertSentTo(
            [$user], TestNotification::class
        );
    }
}

</code></pre>
<p><strong>Test Notification class:</strong></p>
<pre><code>&lt;?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class TestNotification extends Notification
{
    use Queueable;

    private $user;

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

    public function via($notifiable)
    {
        return ['mail','database'];
    }

    public function toMail($notifiable)
    {
        return (new MailMessage)
            -&gt;line('The introduction to the notification.')
            -&gt;action('Notification Action', url('/'))
            -&gt;line('Thank you for using our application!');
    }

    public function toArray($notifiable)
    {
        return [
            'some' =&gt; 'data'
        ];
    }
}

</code></pre>
<p><strong>Error Response:</strong></p>
<pre><code>The expected [App\Notifications\TestNotification] notification was not sent.
Failed asserting that false is true.
 /opt/project/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/NotificationFake.php:83
 /opt/project/vendor/laravel/framework/src/Illuminate/Support/Testing/Fakes/NotificationFake.php:67
 /opt/project/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:261
 /opt/project/tests/Unit/Modules/Test/ExampleTest.php:27
</code></pre>
<p>Of course, if I try to send the notification out of the Unit Test, it works. I'm using this and I receive the email in my Mailhog container.</p>
<pre><code>Route::get('/test-notification', function (){
    Notification::route('mail',  'johndoe@domain.com')-&gt;notify(new TestNotification(new \App\Models\User\User()));

    return 'Notification Sent';
});
</code></pre>
<p>So my question is, why the notification is not sent inside Unit Test, because my call it's the same, it does not match with Laravel says in their DOC.</p>
<p>In addition, I wonder if instead of using an instance of a Laravel model the user class, I can use another kind of object, even a Mock, I guess so, as long as I use the Trait &quot;Notifiable&quot;. Correct?</p>
<p>Thank you very much</p>
",https://stackoverflow.com/questions/72910122/laravel-8-notification-unit-testing-not-working-the-expected-notification-was-n,"['php', 'unit-testing', 'laravel-8', 'laravel-notification']",474,False,0,0
Unit testing that a method was called in another object&#39;s method in Python,"<p>Most of my unit testing experience is with Java and now I'm turning to Python. I need to test whether a method (from object B) gets called inside another method (in object A).</p>
<p>In Java the test method would have to pass a mock or spy version of B to A's constructor to be used when the B method is invoked. <strong>Do I need to do the same in Python? Or is there a simpler way?</strong> (I raise the possibility of the latter, because it seems, from what little I know, that Python is relatively relaxed about enforcing isolation between different components.)</p>
<p>Below is how I do this the &quot;Java way.&quot; There are two Python files under test (for objects A and B) and a test program. Notice that object A's constructor had to be modified to accommodate testing.</p>
<h2>obj_a.py</h2>
<pre><code>from obj_b import *

class ObjA:

    def __init__(self, *args):
        if len(args) &gt; 0:
            self.objb = args[0] # for testing
            return
        self.objb = ObjB()

    def methodCallsB(self, x, y):
        return self.objb.add(x, y)
</code></pre>
<h2>obj_b.py</h2>
<pre><code>class ObjB:

    def add(self, x, y):
        return x + y
</code></pre>
<h2>test.py</h2>
<pre><code>import unittest
from unittest.mock import patch, Mock
from obj_a import *
from obj_b import *

class TTest(unittest.TestCase):
    @patch(&quot;obj_b.ObjB&quot;)
    def test_shouldCallBThroughA(self, mockB):
        # configure mock
        mockB.add = Mock(return_value=137)
        obja = ObjA(mockB)

        # invoke test method
        res = obja.methodCallsB(4, 7)
        print(&quot;result: &quot; + str(res))

        # assess results
        self.assertEqual(137, res)
        mockB.add.assert_called_once()
        args = mockB.add.call_args[0] # Python 3.7
        print(&quot;args: &quot; + str(args))
        self.assertEqual((4, 7), args)

if __name__ =='__main__':
    unittest.main()

</code></pre>
<p><strong>Again, is there a simpler way to test that ObjB::add is called from ObjA?</strong></p>
",https://stackoverflow.com/questions/74306497/unit-testing-that-a-method-was-called-in-another-objects-method-in-python,"['python', 'unit-testing', 'mocking', 'python-unittest', 'spying']",336,True,0,1
Unit testing monkey patch in Angular (Cannot read properties of undefined (reading &#39;checkABC&#39;)),"<p>I'm attempting to unit test my setStep() method in angular using Jasmine but I keep getting <code>Cannot read properties of undefined (reading 'checkBusiness') thrown</code> which prevents me from continuing the test.</p>
<p>This is the function in the <strong>component.ts</strong>:</p>
<pre><code>
  get userBusiness(): string { return  this.auth &amp;&amp;  this.auth.user &amp;&amp; this.auth.user.Source; }

setSteps() {
    if (this.userBusiness.checkBusiness('ABC')) {
      this.items = steps['ABC'];
      if (this.application.process.onboarding.status !== 'complete') { this.show = true; }
    } else {
      this.items = steps['DEF'];
    }
  }
</code></pre>
<p><strong>checkBusiness()</strong> method is defined as a monkey patch to the String prototype class:</p>
<pre><code>Interface String {
  checkBusiness(...args: string[]): boolean;
}

String.prototype.checkBusiness = function(...args: string[]): boolean {
  let result = false;
  for (let arg of args) {
    const currentBusinessArray = business[this];
    if (!currentBusinessArray) {
      result = false;
      continue;
    }

    if (currentBusinessArray.includes(arg)) {
      result = true;
    }
  }
  return result;
};
</code></pre>
<p>Business is an array defined as:</p>
<pre><code>const lob = Object.freeze( &lt;any&gt; {
  ABC : ['ABC', 'ABC1', 'ABC2', 'ABC3'],
  DEF : ['DEF', 'DEF1', 'DEF2', 'DEF3']
});
</code></pre>
<p><strong>Testing/spec</strong> file:</p>
<pre><code>  it('should confirm that &quot;show&quot; is set to true in setSteps()', () =&gt; {
    const testUserBusiness = {...testDataSvc.userABC}
    const userBusinessSpy = spyOnProperty(component, 'userBusiness').and.returnValue(testUserBusiness);
    console.log(component['userBusiness']);
    component.setSteps();
})
</code></pre>
<p><strong>Problem::</strong>
I keep getting <code> Cannot read properties of undefined (reading 'checkBusiness') thrown</code></p>
<p>Any idea how to get past this? I've tried to search everywhere but there isn't something like this scenerio that I can follow.</p>
",https://stackoverflow.com/questions/70612909/unit-testing-monkey-patch-in-angular-cannot-read-properties-of-undefined-readi,"['javascript', 'angular', 'typescript', 'jasmine', 'karma-jasmine']",245,False,0,0
"How to test for a returned Object in Unit testing in Java, BlueJ?","<p>So let's assume I have a class in Java called ItemClass and I'm calling one of the methods in the class which returns an object of type Feedback where Feedback is another class.</p>
<p>Now, how can I test if the returned object from the ItemClass is a specific Feedback which I have created previously.</p>
<p>How can I also test if the returned Object is null if there is no Feedback?</p>
<p>I am using BlueJ JUnit testing.</p>
",https://stackoverflow.com/questions/74336117/how-to-test-for-a-returned-object-in-unit-testing-in-java-bluej,"['java', 'unit-testing', 'object', 'junit', 'bluej']",63,False,0,1
How do I solve Class Cast Exception when it comes to Unit Testing?,"<p>I have been generating Test Cases for some classes using a tool called Diff Blue. Now Diff Blue is an AI tool that can generate multiple Test Cases for some functions. I have a particular class for which I have generated Test Cases using Diff Blue but one Test Case has failed. My main goal is to get all of the Test Cases to pass. The Test Case I'm working on is for the below class with function getDashboardById.</p>
<pre><code>@RequiredArgsConstructor
@Transactional
@Service
@Slf4j
public class DashboardServiceImpl implements DashboardService {

    private final DashboardRepository dashboardRepository;
    private final PlatformDataExtractHistoryService platformDataExtractHistoryService;
    private final ShopifyService shopifyService;
    private final ModelMapper modelMapper;

    /**
     * Get Dashboard by its id
     *
     * @param id dashboard id
     * @return DashboardGetDto
     */
    @Override
    public DashboardGetDto getDashboardById(String id) {
        Dashboard dashboard = dashboardRepository.findById(id)
                .orElseThrow(() -&gt; new ResourceNotFoundException(GlobalErrorUtils.DASHBOARD_NOT_FOUND_404));
        log.info(&quot;Get dashboard details by id: {}&quot;, id);

        // convert entity to DTO
        return modelMapper.map(dashboard, DashboardGetDto.class);
    }
</code></pre>
<p>Diffblue has generated 3 Test Cases for the function getDashboardById. Two of the Test Cases passed while one failed. My goal is to get it to pass too. The below code is the code of the failed test case.</p>
<pre><code>void testGetDashboardById3() {
        DashboardGetDto dashboardGetDto = new DashboardGetDto();
        when(dashboardRepository.findById((String) any())).thenReturn(Optional.empty());
        when(modelMapper.map((Object) any(), any())).thenReturn(&quot;Map&quot;);
        when(modelMapper.map((Object) any(), (Class&lt;DashboardGetDto&gt;) any())).thenReturn(dashboardGetDto);
        assertThrows(ResourceNotFoundException.class, () -&gt; dashboardServiceImpl.getDashboardById(&quot;42&quot;));
        verify(dashboardRepository).findById((String) any());
        verify(modelMapper).map((Object) any(), (Class&lt;Object&gt;) any());
    }
</code></pre>
<p>The problem I'm experiencing is that I'm getting a Class Cast Exception.</p>
<pre><code>java.lang.ClassCastException: class java.lang.String cannot be cast to class com.unicorn.dashboard.dto.dashboard.DashboardGetDto (java.lang.String is in module java.base of loader 'bootstrap'; com.unicorn.dashboard.dto.dashboard.DashboardGetDto is in unnamed module of loader 'app')

    at com.unicorn.dashboard.serviceImpl.DashboardServiceImplTest.testGetDashboardById3(DashboardServiceImplTest.java:127)
</code></pre>
<p>Now I do understand that this occurs when you try to cast a class of one type to another. But what I'm struggling to understand is where the error is being generated and how do I solve it since this is a Test Case. The Error points at line 127 which is in the above Test Function testGetDashboardById3. For reference I'll give the line below</p>
<pre><code>when(modelMapper.map((Object) any(), (Class&lt;DashboardGetDto&gt;) any())).thenReturn(dashboardGetDto);
</code></pre>
<p>Now what I don't understand is that where exactly in the above line is the Cast occurring and what must be changed in order to get the Test Case working?</p>
<p>Edit</p>
<p>I have edited my code as per the answers and displayed it below. However there is an error within the code. What necessary changes must be done to fix the error?</p>
<p><a href=""https://i.stack.imgur.com/GgREa.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/GgREa.png"" alt=""enter image description here"" /></a></p>
<p>When I hover over the highlighted area I get this message</p>
<p><a href=""https://i.stack.imgur.com/UtWk0.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/UtWk0.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/74180454/how-do-i-solve-class-cast-exception-when-it-comes-to-unit-testing,"['spring', 'spring-boot', 'unit-testing', 'junit', 'junit5']",584,False,0,1
Django Unit Testing - How to load once a DB for multiple tests.py files?,"<p>I have a folder named &quot;test&quot; in my Django project.
Inside this folder I have multiple files named &quot;test_xyz.py&quot;.</p>
<p>My goal: loading the DB <strong>only once</strong> and share it across all test*.py files.</p>
<p>What I currently do:</p>
<pre><code>class OneTestCase(APITestCase):

    @classmethod
    def setUpTestData(cls):
        '''
        Init database
        '''
        from myapp.init import init_my_db # a python script loading the db

class TwoTestCase(APITestCase):

    @classmethod
    def setUpTestData(cls):
        '''
        Init database
        '''
        from myapp.init import init_my_db # a python script loading the db

# same goes for each test*.py file...
</code></pre>
<p>In other words I am reloading the database from scratch for each test*.py file slowing down the testing execution time.</p>
<p>Is there a way to avoid this, loading the database <strong>only one time</strong> and for all the test*.py files?</p>
",https://stackoverflow.com/questions/74279660/django-unit-testing-how-to-load-once-a-db-for-multiple-tests-py-files,"['python', 'django', 'pytest', 'pytest-django']",77,False,0,1
how to fix an error &quot;is not a function&quot; in unit testing angular 11,"<p>I saw this error lot of times but any solution for my problem,</p>
<p>my component :</p>
<pre><code>*/
@Component({
  selector: 'ngx-modal-result-training',
  templateUrl: './modal-result-training.component.html',
  styleUrls: ['./modal-result-training.component.scss'],
})
export class ModalResultTrainingComponent implements OnInit {
  @Input() results: IAttempt;
  @Input() training: ITraining;
  public validated = false;
  public opinionForm: FormGroup;
  public selectedStars = 0;
  public hasAlreadyComment = true;
  public percentageScore: number;

  constructor(
    private opinionsService: OpinionsService,
    private userService: UserService,
    private ref: NbDialogRef&lt;ModalResultTrainingComponent&gt;,
    private router: Router,
    private toastrService: NbToastrService,
    private translateService: TranslateService,
    private dialogService: DialogService
  ) {}

  public ngOnInit(): void {
    this.dialogService.refs.push(this.ref);
    this.percentageScore = Math.floor(this.results.score);
    this.validated = this.percentageScore &gt;= this.training.minimalScore;

    this.checkUserOpinion();
    this.initForm();
  }

</code></pre>
<p>My test :</p>
<pre><code>
const training = {
  id: 'ZGtz6yrEemCNTo5KAytu',
  refProject: 'JGvD1faO8L2vWb66BQ87',
  publicationDate: new Date(),
  version: 1,
  name: 'My project',
  groups: [],
  category: '',
  description: '',
  minimalScore: 80,
  previewPNG: '',
  level: 5,
  gain: 5,
  fromDate: new Date(),
  toDate: new Date(),
  totalSlides: 20,
  stars: 3,
  averageStars: 4,
  comments: 15,
  groupsHistoric: [],
} as ITraining;

const trainingResults = {
  id: 'ZDqzqg',
  version: 1,
  trainingID: 'xSOvDC6vpZTzVqXy5owQ',
  userID: 'qdZDZDqg',
  groupsIDs: [],
  date: new Date(),
  time: 10,
  score: 10,
  validated: true,
  finished: true,
  currentStep: 4,
} as IAttempt;

fdescribe('ModalResultTrainingComponent', () =&gt; {
  let component: ModalResultTrainingComponent;
  let fixture: ComponentFixture&lt;ModalResultTrainingComponent&gt;;
  let mockOpinionsService =  jasmine.createSpyObj('OpinionService', ['addOpinion']);
  let mockDialogService = jasmine.createSpyObj('DialogService', ['closeAll', 'refs', 'push']);
  let mockUserService = jasmine.createSpyObj('UserService', ['user$']);
  let mockRouter = jasmine.createSpyObj('Router', ['navigate']);
  let mockToastrService = jasmine.createSpyObj('NbToastrService ', ['success']);
  let mockTranslateService = jasmine.createSpyObj('TranslateService ', ['instant']);
  let nbAclService = jasmine.createSpyObj('NbAclService' , ['allow', 'can', 'register', 'setAccessControl']);
  let nbDialogRef = jasmine.createSpyObj('NbDialogRef', ['push']);

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [ModalResultTrainingComponent],
      providers: [
        {provide :  Router, useValue: mockRouter},
        {provide :  OpinionsService, useValue: mockOpinionsService},
        {provide :  UserService, useValue: mockUserService},
        {provide :  DialogService, useValue: mockDialogService},
        {provide :  NbToastrService, useValue: mockToastrService},
        {provide :  TranslateService, useValue: mockTranslateService},
        {provide :  NbDialogRef, useValue: nbDialogRef},
        EntityService,
        {provide : NbAclService, useValue : nbAclService},
        ],
      imports: [
        FireModule,
        RouterModule.forRoot([]),
        NbThemeModule.forRoot(),
        NbDialogModule.forRoot(),
        NbAuthModule.forRoot(),
        TranslateModule.forRoot(),
      ],
      schemas: [NO_ERRORS_SCHEMA],
    }).compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(ModalResultTrainingComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    mockOpinionsService = TestBed.inject(OpinionsService);
    mockUserService = TestBed.inject(UserService);
    mockDialogService = TestBed.inject(DialogService);
    mockRouter = TestBed.inject(Router);
    mockToastrService = TestBed.inject(NbToastrService);
    mockTranslateService = TestBed.inject(TranslateService);
    nbAclService = TestBed.inject(NbAclService);
    nbDialogRef = TestBed.inject(NbDialogRef);
    component.training = training;
    component.results = trainingResults;


  });

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

</code></pre>
<p>I don't understand why I got this error : &quot; TypeError: this.dialogService.refs.push is not a function&quot;</p>
<p>I try to replace useClass instead of useValue but I had unreachable knowing is angular 11.
I did lot of research but I found anything.</p>
<p>thanks to all for help</p>
",https://stackoverflow.com/questions/70925408/how-to-fix-an-error-is-not-a-function-in-unit-testing-angular-11,"['javascript', 'angular', 'function', 'testing', 'jasmine']",9267,True,3,1
How to fire events on multiple layers of custom components with react unit testing,"<p>I'm writing a test case for a feature I'm unit testing. I want to edit a text field that's embedded within several custom components but I can't figure out how to access it:</p>
<h1>TestFile.test.tsx</h1>
<pre><code>it('should be able to change quantity', () =&gt;{
  //Mock out dependent function with jest
  //Nothing here right now


  //Render with the props you want
  render(        
        &lt;MainComponent /&gt; );

  //Locate screen components for test
  const counter = screen.queryByTestId(&quot;counter&quot;);

  //Perform user actions
  fireEvent.change(counter, 4);   &lt;--This is the line where I'm trying to access what I want

  //Measure against expect cases
  expect(counter).toBe(4);
});
</code></pre>
<h1>MainComponent.tsx</h1>
This is the component I'm trying to access. The problem is, `fireEvent.change` won't work because it's a custom component. At least, I think that's why it doesn't work.
<pre><code>&lt;Counter
  data-testid='counter'    &lt;--data-testid is here right now
  containerMargin={{ marginTop: -5 }}
/&gt;
</code></pre>
<h1>Counter.tsx</h1>
Inside `Counter` is another custom component, `TextField`
<pre><code>&lt;TextField
     {...props}
/&gt;
</code></pre>
<h1>TextField.tsx</h1>
And inside TextField is where the text input I want to access is:
<pre><code>&lt;TextInput
  {...props}
/&gt;
</code></pre>
<h1>Error Message</h1>
When I try to run the test, I get this error:
<pre><code>  ●  Test › should be able to change quantity

Unable to fire a &quot;change&quot; event - please provide a DOM element.

  189 |
  190 |     //Perform user actions
&gt; 191 |     fireEvent.change(counter, 4);
      |               ^
  192 |
  193 |     //Measure against expect cases
  194 |     expect(counter).toBe(4);
</code></pre>
<p>I can't put the <code>data-testid</code> property inside <code>TextField</code> or the <code>TextInput</code> itself, because there's another <code>Counter</code> in the render of the page I'm testing. Any advice or troubleshooting would be helpful, thanks!</p>
",https://stackoverflow.com/questions/70838945/how-to-fire-events-on-multiple-layers-of-custom-components-with-react-unit-testi,"['reactjs', 'typescript', 'react-native', 'unit-testing', 'react-testing-library']",1092,True,3,2
VueJS Unit testing - I cannot run my tests. &quot;Command &#39;test/unit&#39; does not exists&quot;,"<p>I'm trying to setup Unit Tests with VueJS 3. Reading <a href=""https://test-utils.vuejs.org/guide/#what-next"" rel=""nofollow noreferrer"">the docs of Vue 3</a>, I Installed test-utils 2.0</p>
<p>My package.json file looks like this :</p>
<pre><code>{
  &quot;name&quot;: &quot;testsUnitVue&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;devDependencies&quot;: {

    ...

    &quot;@vue/test-utils&quot;: &quot;^2.0.0-rc.21&quot;,

    ...

  }
}
</code></pre>
<p>I try to run my the tests with:</p>
<pre><code>npm run test:unit
</code></pre>
<p>But I've the following error message:</p>
<pre><code>&gt; testsUnitVue@0.1.0 test:unit
&gt; vue-cli-service test:unit

 ERROR  command &quot;test:unit&quot; does not exist.
</code></pre>
<p>I've a similar result with <code>yarn</code> command. How can I solve this?</p>
<p>PS: If you need more informations, then just leave a comment :)</p>
",https://stackoverflow.com/questions/72086475/vuejs-unit-testing-i-cannot-run-my-tests-command-test-unit-does-not-exists,"['javascript', 'vue.js', 'unit-testing', 'npm', 'vuejs3']",1514,True,2,1
FileLoader in three.js gives ReferenceError: Request is not defined while unit testing using mocha,"<p>I am trying to write a unit test for my three js utility functions.
My Project uses CRA w TS, and mocha &amp; chai w TS for unit testing.</p>
<p><strong>GeometryUtils.spec.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>import { expect } from 'chai';
import { describe, it } from 'mocha';
import { Scene, Vector3 } from 'three';![enter image description here](https://i.stack.imgur.com/YdU7b.png)
import { extractBoundaryOf } from './GeometryUtils';
import fs from 'fs';
import * as THREE from 'three';
import { GLTF, GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

describe('GeometryUtils.extractBoundaryOf', function () {
    it('should return a Vector3[][]', function () {
        THREE.Cache.enabled = true;
        const surfaceName = 'wall_0';
        const surfaceNormal = new Vector3(0, 0, 1);
        new GLTFLoader().parse(
            fs.readFileSync('./src/services/threejs/test/room_camera_geometry.gltf').toString(),
            './src/services/threejs/test/',
            function (gltf) {
                const scene = gltf.scene as unknown as Scene;
                console.log('GLTF ', gltf);
                console.log('Scene ', gltf.scenes);
                const boundary = extractBoundaryOf(surfaceName, surfaceNormal, scene);
                expect(boundary).to.be.an('array');
            },
            function (error) {
                console.error(error);
            },
        );
    });
});
</code></pre>
<p><strong>GeometryUtil.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>import {
    Box2,
    BufferGeometry,
    Group,
    LineSegments,
    Mesh,
    Object3D,
    PerspectiveCamera,
    Raycaster,
    LineBasicMaterial,
    Scene,
    Triangle,
    Vector2,
    Vector3,
    Line,
} from 'three';
export function extractBoundaryOf(surfaceName: string, surfaceNormal: Vector3, inScene: Scene): Vector3[][] {
    // just an example
    let allVertices: Vector3[][] = [[new Vector3(0, 0, 1)]];
    return allVertices;
}
</code></pre>
<p>Error I'm facing:</p>
<pre class=""lang-sh prettyprint-override""><code>yarn run v1.22.17
$ mocha src/**/*.spec.ts
(node:34713) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)


  GeometryUtils.extractBoundaryOf
    ✔ should return a Vector3[][]
ReferenceError: Request is not defined
    at FileLoader.load (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/build/three.module.js:39258:15)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2640:11
    at new Promise (&lt;anonymous&gt;)
    at GLTFParser.loadBuffer (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2638:10)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2541:24)
    at GLTFParser.loadBufferView (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2659:15)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2535:40
    at GLTFParser._invokeOne (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2468:19)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2533:24)
    at GLTFParser.loadAccessor (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2694:34)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2529:24)
    at assignAttributeAccessor (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:4206:17)
    at addPrimitiveAttributes (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:4222:17)
    at GLTFParser.loadGeometries (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3334:24)
    at GLTFParser.loadMesh (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3377:24)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2523:34
    at GLTFParser._invokeOne (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2468:19)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2521:24)
    at GLTFParser.createNodeMesh (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3739:17)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3788:38
    at GLTFParser._invokeOne (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2468:19)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3786:31
    at GLTFParser.loadNode (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3820:4)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2517:24)
    at buildNodeHierarchy (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3985:16)
    at GLTFParser.loadScene (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3933:18)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2513:24)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2601:19
    at Array.map (&lt;anonymous&gt;)
    at GLTFParser.getDependencies (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2599:37)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2314:12
    at processTicksAndRejections (internal/process/task_queues.js:95:5)


  1 passing (64ms)

Done in 14.62s.
</code></pre>
<p>package.json:</p>
<pre class=""lang-json prettyprint-override""><code>{
   &quot;type&quot;: &quot;module&quot;,
   &quot;scripts&quot;: {
      ....
      &quot;test&quot;: &quot;mocha src/**/*.spec.ts&quot;,
      ....,
   }
}
</code></pre>
<p>tsconfig.json</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;compilerOptions&quot;: {
    &quot;types&quot;: [ &quot;node&quot;, &quot;mocha&quot;, &quot;chai&quot;, &quot;lodash&quot;],
    &quot;typeRoots&quot;: [&quot;typings&quot;, &quot;./node_modules/@types&quot;],
    &quot;target&quot;: &quot;esnext&quot;,
    &quot;lib&quot;: [
      &quot;dom&quot;,
      &quot;dom.iterable&quot;,
      &quot;esnext&quot;
    ],
    &quot;allowJs&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;strict&quot;: true,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;experimentalDecorators&quot;: true,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;resolveJsonModule&quot;: true,
    &quot;isolatedModules&quot;: true,
    &quot;noEmit&quot;: true,
    &quot;jsx&quot;: &quot;react&quot;,
    &quot;useDefineForClassFields&quot;: true
  },
  &quot;include&quot;: [
    &quot;src&quot;
  ]
}
</code></pre>
<p>.mocharc.json</p>
<pre class=""lang-json prettyprint-override""><code>{
    &quot;node-option&quot;: [
        &quot;experimental-specifier-resolution=node&quot;,
        &quot;loader=ts-node/esm&quot;
    ]
}
</code></pre>
<p>I wanna pass the GLTF object to my testing
This is my directory structure:</p>
<p>I tried to compile using commonjs too. But that didn't work either.</p>
",https://stackoverflow.com/questions/71567115/fileloader-in-three-js-gives-referenceerror-request-is-not-defined-while-unit-t,"['typescript', 'unit-testing', 'three.js', 'mocha.js', 'react-testing']",581,False,2,0
Unit testing against production database or using repository layer in ASP.NET Core Web API,"<p>I would like to unit test my service layer methods in my project, and according to Microsoft, there are <a href=""https://learn.microsoft.com/en-us/ef/core/testing/choosing-a-testing-strategy"" rel=""nofollow noreferrer"">several ways</a> to do so. I found two of them to best the best for my project: <a href=""https://learn.microsoft.com/en-us/ef/core/testing/testing-with-the-database"" rel=""nofollow noreferrer"">testing against production database</a>, and using a <a href=""https://learn.microsoft.com/en-us/ef/core/testing/testing-without-the-database"" rel=""nofollow noreferrer"">repository layer</a> to abstract EF Core statements.</p>
<p>Here is a sample of a method from my service layer:</p>
<pre><code>public async Task&lt;PostQueryDTO&gt;  GetPostByIdAsync (Guid id, CancellationToken cancellationToken)
{
   Post? post = await _dbSet
       .Include            (p =&gt; p.User)
       .FirstOrDefaultAsync(p =&gt; p.Id == id, cancellationToken);

   if (post == null)
   {
       throw new PostNotFoundException();
   }

   return post.ToPostQueryDTO();
}
</code></pre>
<p>Now if I were to add a repository layer, I would have to do the following:</p>
<p>Create a method in the repository layer to handle EF Core:</p>
<pre><code>public async Task&lt;Post&gt; GetPostByIdAsync (Guid id, CancellationToken cancellationToken)
{
    return _dbContext.Posts
                     .Include(p =&gt; p.User)
                     .FirstOrDefaultAsync(p =&gt; p.Id == id, cancellationToken);
}
</code></pre>
<p>And my service layer method would change into:</p>
<pre><code>public async Task&lt;PostQueryDTO&gt;  GetPostByIdAsync (Guid id, CancellationToken cancellationToken)
{
    Post? post = (await _postRepo.GetPostByIdAsync(id, cancellationToken)).toPostQueryDTO();

    if (post == null)
    {
        throw new PostNotFoundException();
    }

    return post.ToPostQueryDTO();
}
</code></pre>
<p>The benefit of this is that the new method would be easier to unit test since I can use something like Moq to moq the repository method, and EF Core is abstracted into another layer.</p>
<p>The downside is that I would have to create a new method in the repository layer for every method in the service layer, and testing insert methods which would be tricky.</p>
<p>Now for testing against production database, I would say that some of the pros, are the cons of adding a repository layer (i.e. it solves them). But would using a local copy of the database (in SSMS or Visual Studio) work as well, and are there any other cons? (maybe other than commands clashing and causing some tests to fail)</p>
<p>I would appreciate if you would tell me which would be more suitable in what situation and your experiences using them.</p>
",https://stackoverflow.com/questions/73309940/unit-testing-against-production-database-or-using-repository-layer-in-asp-net-co,"['c#', 'unit-testing', 'asp.net-core-webapi', '.net-6.0', 'xunit']",409,False,1,0
Unit Testing Spring Boot API RESTful endpoints generated by Open API 3 YAML files,"<p>I have an application that is using Spring Boot (latest version) and creating a back-end that has RESTful api's.   Traditionally, I have created controllers like:</p>
<pre><code>@RestController
@RequestMapping(&quot;/contacts&quot;)
public class ContactController {
    @Autowired
    private ContactService service;

        @RequestMapping(value = &quot;/contactId/{contactId}&quot;, 
         method = RequestMethod.GET, headers = &quot;Accept=application/json&quot;)
public @ResponseBody ContactEntity getContactById(@PathVariable(&quot;contactId&quot;) long contactId) {
    ContactEntity contactEntity = service.getContactById(contactId);
    return contactEntity;
}
</code></pre>
<p>And an integrated test has always been like:</p>
<pre><code>@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = ServiceContextConfiguration.class)
@ComponentScan(&quot;com.tomholmes.springboot.phonebook.server&quot;)
@Transactional
@WebAppConfiguration    
public class ContactControllerTest {
    @Test
    public void testGetContactById() throws Exception {
        MockHttpServletRequestBuilder requestBuilder = 
            MockMvcRequestBuilders.get(BASE_URL + &quot;/contactId/6&quot;);           
        this.mockMvc.perform(requestBuilder)
            .andDo(print())
            .andExpect(status().isOk());
       }
}
</code></pre>
<p>This has always worked normally for years as a 'code first' api.  Now, I am dealing with a contract-first API using OpenAPI 3 and a YAML file.   The API is generated in the same location as before, and I would expect the test to work as it did before, but it does not.</p>
<p>So one resource:<br />
[https://www.hascode.com/2018/08/testing-openapi-swagger-schema-compliance-with-java-junit-and-assertj-swagger/#API_Test]
is suggesting I use the assertj-swagger for the OpenAPI / Swagger contract testing.</p>
<p>Is this the only way to go?   Is there no way for me to use my old traditional testing which I find extremely useful as an integrated test.</p>
<p>There is a third method I am also looking into:
[https://www.testcontainers.org/modules/mockserver/]
Which I am going to try also, and I am sure it will work.</p>
<p>I'm also wondering if there is code out there to auto-generate the Test just like there is to generate the API endpoint and the model, it would make sense if the Open API 3 also had the ability to generate the test was well.</p>
<p>Ultimately, I'd like to use my old way of testing if I could, but if not, then I'll try the other ways.</p>
",https://stackoverflow.com/questions/72450061/unit-testing-spring-boot-api-restful-endpoints-generated-by-open-api-3-yaml-file,"['spring-boot', 'junit', 'openapi-generator', 'springdoc-openapi-ui', 'junit-jupiter']",1584,True,1,1
How to test Assert for base class exception implementation using Microsoft Unit testing framework?,"<p>Here is specific case. I want to test this <code>Assert.ThrowsException&lt;DbException&gt;(() =&gt; { MyMethod(0, 100); });</code></p>
<p>The problem is that exception thrown is <code>SqlException</code>. Why do I want to test base exception? Because I want a unified test for any of my 3 DB providers. The exception sometimes is <code>OracleException</code> or <code>MySqlException</code>. All 3 providers exceptions derive from <code>DbException</code></p>
<p>Is there a way to test it nicely, using the Microsoft Unit Test framework?</p>
",https://stackoverflow.com/questions/73356346/how-to-test-assert-for-base-class-exception-implementation-using-microsoft-unit,"['c#', '.net', 'unit-testing', 'microsoft-unit-testing']",181,True,1,2
Is there any Unit testing framework for(pipeline as code) GitHub actions based workflow,"<p>Is there any testing framework available to write unit tests on the configuration and conditional logic of the GitHb actions based workflow (pipeline code), by providing a mock execution of the pipeline ?</p>
",https://stackoverflow.com/questions/72868933/is-there-any-unit-testing-framework-forpipeline-as-code-github-actions-based-w,"['unit-testing', 'github', 'continuous-integration', 'github-actions']",19,False,1,0
"Problem unit testing a delete method with mock service worker (MSW), node and React","<p>I have MSW setup with React and Typescript, the code works in the browser, ie, it deletes the employee, but not in the test, the other tests are working fine. I'm stumped, there's probably something daft that I'm doing, any help would be greatly appreciated<br />
github repo <a href=""https://github.com/cherry15/cc2022react"" rel=""nofollow noreferrer"">https://github.com/cherry15/cc2022react</a><br />
handlers.ts  <br></p>
<pre><code>
  rest.delete(`${url}/:employeeId`, (req, res, ctx) =&gt; {  
    const { employeeId } = req.params
    if (employeeId) {
      const employeeIndex = EmployeesData.findIndex(
        (employee) =&gt; employee.id === employeeId.toString()
      )
      if (employeeIndex !== -1) {
        EmployeesData.splice(employeeIndex, 1)
        return res(ctx.status(200))
      } else {
        return res(ctx.status(404))
      }
    }
    return res(ctx.status(400))
  }),

employees.test.tsx

describe('Delete employee', () =&gt; {
  test('clicking on the OK button deletes the employee', async () =&gt; {
    renderWithProviders(&lt;EmployeeList /&gt;)
    await screen.findByRole('heading', { name: /ada lovelace/i })
    await screen.findAllByRole('button', { name: 'Delete employee' })

    fireEvent.click(screen.getAllByRole('button', { name: 'Delete employee' })[0])
    fireEvent.click(await screen.findByText('OK'))
    expect(screen.getByText(/ada lovelace/i)).not.toBeInTheDocument()
  })
})
</code></pre>
",https://stackoverflow.com/questions/71413758/problem-unit-testing-a-delete-method-with-mock-service-worker-msw-node-and-re,"['reactjs', 'jestjs', 'msw']",1926,True,1,1
"Why am I getting 422 status code during the post endpoint testing, unit testing?","<p>During the running test case of my application, I keep on seeing test failed even when the data is well formatted. The following are my code snippets:</p>
<p>I was able to create a new user through its application interface, but trying its behaviour, it was giving me an unexpected error status code, 422. I don't really know what was going wrong with the snippets. Here I have included all the following code for better look into the stated issue.</p>
<p><em>For the endpoint</em> /users</p>
<pre><code>@app.route('/users/, methods=['POST'])
def create_user():
    try:
         body = request.get_json((
         new_user = body get('user_name', None)
         if user_name is None:
              about(405)
         new_entry = User(new_user)
         new_entry.insert()
         return jsonify({
              'success': True
         )}
   except:
       abort(422)
</code></pre>
<p><em>Here is my</em> model_class:</p>
<pre><code>class User(db.Model):
    __tablename__='users'

    id = Column(Integer, primary_key=True)
     name = Column(String, nullable=False)
     score = Column(Integer, nullable=False)

    def __init__(self, name, score=0):
         self.name = name
         self.score = score

     def insert(self):
         db.session.add(self)
         db.session.commit()

     def format(self):
         return {
            'id': self.id,
            'name': self.name,
            'score': self.score
</code></pre>
<p><em>And here is my</em> test_case_file:</p>
<pre><code>class TriviaTestCase(unit test.TestCase):
     def setUp(self):
         self.app = create_app()
         self.client = self.app.test_client
         self.database_path = &quot;PostgreSQL://postgres:postgresspass@localhos:5432/user_test_db&quot;
         setup_db(self.app, self database_path)

     self.new_user = {
         &quot;username&quot;:&quot;P.Son&quot;,
         &quot;score&quot;: 0
     }

     def test_create_user(self):
         res = self.client().post(&quot;/users&quot;, json=self.new_user)
         data = json.loads(res.data)
         
         
    self.assertEqual(res.status_code, 200)
  
  self.assertEqual(data['success'], True)

if __name__==&quot;__main__&quot;:
    unittest.main()
</code></pre>
<p>Output of my test:</p>
<pre><code>============================
FAIL: test_create_user (__main__.TriviaTestCase)
----------------------------
Traceback (most recent call last):
   File &quot;C:\...\test_flaskr.py&quot;, line 201, in test_create_user
       self.assertEqual(res.status_code, 200)
AssertionError: 422 != 200
</code></pre>
<p><strong>Note</strong> Other endpoints pass the test but the above endpoint has been failing test. I don't know what was wrong with the snippets I have written.</p>
",https://stackoverflow.com/questions/73499968/why-am-i-getting-422-status-code-during-the-post-endpoint-testing-unit-testing,"['python', 'flask', 'python-unittest']",279,False,0,1
How can we inject a variable value in production code only for unit testing?,"<p>I have requirement to inject the value for variable <strong>data</strong>.</p>
<p><strong>index.js</strong></p>
<pre><code>const sideEffect = (arg1, arg2,...) =&gt; {
   // It perform complex tasks
   // Involves third-party call, etc
   // Returns the processed output
}

const main = async(args1, args2,...) =&gt; {
   const data = await sideEffect(args1, args2, ...);
   // Process the data and returns
   return data;
}

module.exports = {main};
</code></pre>
<p><strong>limitations</strong></p>
<ol>
<li>function <strong>data</strong> is not exported.</li>
</ol>
<p>I want to do unit testing for <strong>main</strong> function, by injecting the value of <strong>data</strong>, Can it be achieved ?</p>
",https://stackoverflow.com/questions/74001873/how-can-we-inject-a-variable-value-in-production-code-only-for-unit-testing,"['node.js', 'unit-testing', 'mocha.js', 'chai', 'mern']",30,False,0,1
Is there an example of PyFlink SQL unit testing in a self-contained repo?,"<p>Is there an example of a self-contained repository showing how to perform SQL unit testing of PyFlink (specifically 1.13.x if possible)?</p>
<p>There is a related SO question <a href=""https://stackoverflow.com/questions/69937520/pyflink-sql-local-test"">here</a>, where it is suggested to use some of the tests from PyFlink itself.  The issue I'm running into is that the PyFlink repo assumes that a bunch of things are on the Java classpath and that some Python utility classes are available (they're not distributed via PyPi apache-flink).</p>
<p>I have done the following:</p>
<ol>
<li>Copied <code>test_case_utils.py</code> and <code>source_sink_utils.py</code> from <a href=""https://github.com/apache/flink/tree/f8172cdbbc27344896d961be4b0b9cdbf000b5cd/flink-python/pyflink/testing"" rel=""nofollow noreferrer"">PyFlink</a> into my project.</li>
<li>Copy an example unit test (<a href=""https://github.com/apache/flink/blob/f8172cdbbc27344896d961be4b0b9cdbf000b5cd/flink-python/pyflink/table/tests/test_sql.py#L39"" rel=""nofollow noreferrer"">this one</a> as suggested by the related SO question.</li>
</ol>
<p>When I try to run the test, I get an error because the test case cannot determine what version of Avro jars to download (<code>download_apache_avro()</code> fails, because <a href=""https://github.com/apache/flink/blob/34e6895af8587b62a692f76591882f9a061fdb34/flink-python/pyflink/pyflink_gateway_server.py#L230-L232"" rel=""nofollow noreferrer"">this code</a> tries to evaluate the value of <code>avro.version</code> by running <code>mvn help:evaluate -Dexpression=avro.version</code>)</p>
<p>I then added a dummy <code>pom.xml</code> defining a Maven property of <code>avro.version</code> (with a value of <code>1.10.0</code>) and my unit test case is loaded.</p>
<p>I now get a new error and my test is skipped:</p>
<pre><code>'flink-table-planner*-tests.jar' is not available. Will skip the related tests.
</code></pre>
<p>I don't know how to fix this. I've tried adding <code>flink-table-planner</code> and <code>flink-table-planner-blink</code> dependencies with <code>&lt;type&gt;test-jar&lt;/type&gt;</code> to my dummy pom.xml, but it still fails.</p>
<p>This is starting to feel like a real pain to do something that should be trivial: basic TDD of a PyFlink project.  Is there a real-world example of a Python project that shows how to set up a testing environment for unit testing SQL with PyFlink?</p>
",https://stackoverflow.com/questions/71983434/is-there-an-example-of-pyflink-sql-unit-testing-in-a-self-contained-repo,"['python', 'apache-flink', 'flink-sql', 'pyflink']",238,False,0,1
How to handle failed test scenario in NodeJS unit testing using Mocha and Chai,"<p>I am using Mocha and Chai for writing test cases.I have written test case for user login so when I am passing correct credentials in test case its passing the test as on successful login my API is returning the JWT token. But when I am passing wrong email id that time API is returning</p>
<pre><code>{message:&quot;User not found&quot;} 
</code></pre>
<p>How can I handle this failed scenario so that test run passes?</p>
<p>For successful login this test is passing but for failed login this test is failing.</p>
<p>Below is my test:</p>
<p><strong>login.test.js</strong></p>
<pre><code>describe('POST /login', () =&gt; {
before((done) =&gt; {
    sequelize.sync()
             .then((result) =&gt; {
              done();
             })
             .catch((err) =&gt; {
                console.log(&quot;Error:&quot;,err);
             });
});
it('User login',async () =&gt; {

        const data = {name:&quot;Test&quot;,email:'test@gmail.com',role:'admin'};
        const result = await request(app).post('/login').send(data);
          
             const res = result.body;
           
             res.should.be.a('object');
             res.should.have.property('token');
  });
}); 
</code></pre>
",https://stackoverflow.com/questions/73557480/how-to-handle-failed-test-scenario-in-nodejs-unit-testing-using-mocha-and-chai,"['node.js', 'unit-testing', 'mocha.js', 'chai']",21,False,0,0
Unit testing + Mocking eBPF programs in python incl emulating kernel to user-space interactions,"<p>So I need to get some mocking+testing done on a very specific kind of python code: it is an eBPF(Berkely packet filter) program using python, which in essence runs a C program in kernel space through a python script via the BPF Compiler Collection BCC
eg code:</p>
<pre><code>from bcc import BPF
# define BPF program
prog = &quot;&quot;&quot;
int hello(void *ctx) {
    bpf_trace_printk(&quot;Hello, World!\\n&quot;);
    return 0;
}
&quot;&quot;&quot;
# load BPF program
b = BPF(text=prog)
b.attach_kprobe(event=b.get_syscall_fnname(&quot;clone&quot;), fn_name=&quot;hello&quot;)
# header
print(&quot;%-18s %-16s %-6s %s&quot; % (&quot;TIME(s)&quot;, &quot;COMM&quot;, &quot;PID&quot;, &quot;MESSAGE&quot;))
# format output
while 1:
    try:
        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
    except ValueError:
        continue
    print(&quot;%-18.9f %-16s %-6d %s&quot; % (ts, task, pid, msg))

</code></pre>
<p>I want to now write tests for the C and the Python code without the 2 interfering (I would even be satisfied with some basic python unit testing). Any &amp; all possible approaches to the problem are welcome, or even a general direction to look for info on this kind of testing, really just looking to address the following concerns:
<strong>Can I easily mock the kernel interactions when testing the python code?
Can I emulate a message coming from the kernel to user-space?
Can I test a message that’s just larger or just smaller than the expected message size?</strong></p>
<p>I tried looking into the topic for days, to no avail so even pointing me in the right direction would be greatly appreciated...</p>
",https://stackoverflow.com/questions/74699652/unit-testing-mocking-ebpf-programs-in-python-incl-emulating-kernel-to-user-spa,"['python', 'unit-testing', 'linux-kernel']",61,True,0,1
Is there a utPLSQL way to mock dependencies like in other unit testing frameworks?,"<p>In tSQLt, you can isolate dependencies for unit testing using procedures like FakeTable to create a dummy version of whatever your test subject depends on, that contains only data you specify. This is just like using Justmock or Moq in .NET unit testing.</p>
<p>The only thing remotely close to this that I've seen for utPLSQL is copying the dependencies to a temp version in the setup procedure, creating the dummy version manually, and then replacing it with the temp version in the teardown, all using EXECUTE IMMEDIATE.</p>
<p>Is there a more convenient way to do this, short of just creating a procedure to do this myself?</p>
",https://stackoverflow.com/questions/74793290/is-there-a-utplsql-way-to-mock-dependencies-like-in-other-unit-testing-framework,"['oracle', 'unit-testing', 'plsql', 'utplsql']",49,False,0,0
How to automatically generate unit testing routines from special syntax in method docstring / comment?,"<p>This is a mock-up of what I'm looking for:</p>
<pre class=""lang-py prettyprint-override""><code>def is_even(a, b):
    &quot;&quot;&quot;Returns True if both numbers are even.
    @AutoUnitTestTag:
    - (0,2) -&gt; True
    - (2,1) -&gt; False
    - (3,5) -&gt; False
    &quot;&quot;&quot;
    return (a % 2 == 0 and b % 2 == 0)
</code></pre>
<p>Is there a tool that could allow one to insert compact syntax-defined unit tests within a function's docstring and then automatically generate a <code>unittest_foobar.py</code> unit testing routine?</p>
<p>I'm almost sure I've seen this a while ago, but cannot find it.</p>
<p><strong>EDIT</strong>: @mkrieger1 suggested <code>doctest</code> in the comments below and after playing a bit with it, I'd say it's a pretty apt solution.
However, I'd like to let this question linger a bit longer in order to collect more suggestions, especially about more sophisticated tools.</p>
<p>If someone's interested, here's how one would use doctest in my example case:</p>
<ol>
<li>Format function in file <code>is_even.py</code> like so:</li>
</ol>
<pre><code>def is_even(a,b):
    &quot;&quot;&quot;Returns True if both numbers are even.
    &gt;&gt;&gt; is_even(0,2)
    True
    &gt;&gt;&gt; is_even(2,1)
    False
    &gt;&gt;&gt; is_even(3,5)
    False
    &quot;&quot;&quot;
    return (a % 2 == 0 and b % 2 == 0)
</code></pre>
<ol start=""2"">
<li>Then run the command <code>python3 -m doctest is_even.py</code>.
The output will look like so:</li>
</ol>
<pre><code>Trying:
    is_even(0,2)
Expecting:
    True
ok
Trying:
    is_even(2,1)
Expecting:
    False
ok
Trying:
    is_even(3,5)
Expecting:
    False
ok
1 items had no tests:
    foo2
1 items passed all tests:
   3 tests in foo2.is_even
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
</code></pre>
",https://stackoverflow.com/questions/72416363/how-to-automatically-generate-unit-testing-routines-from-special-syntax-in-metho,"['python', 'unit-testing', 'python-unittest', 'docstring']",132,True,0,1
Unit Testing - Basic Authentication: The following constructor parameters did not have matching fixture data,"<p>I am writing the test case for the BasicAuthenticationHandler but confused how should I implement it</p>
<pre><code>public class BasicAuthenticationHandler : AuthenticationHandler&lt;AuthenticationSchemeOptions&gt;
{
    private readonly BasicAuthenticationOptions _basicAuthOptions;
    private const string TOKEN_TYPE = &quot;Basic&quot;;
    public BasicAuthenticationHandler(
       IOptionsMonitor&lt;AuthenticationSchemeOptions&gt; options,
       IOptions&lt;BasicAuthenticationOptions&gt; basicAuthOptions,       
       ILoggerFactory logger,
       UrlEncoder encoder,
       ISystemClock clock
    ) : base(options, logger, encoder, clock) {
        _basicAuthOptions = basicAuthOptions.Value;
    }

    protected override Task&lt;AuthenticateResult&gt; HandleAuthenticateAsync()
    {
       var token = Request.Headers[&quot;Authorization&quot;].FirstOrDefault()?.Split().Last();

    }
}
</code></pre>
<p>BasicAuthenticationTests</p>
<pre><code>public class BasicAuthenticationTests: BasicAuthenticationHandler
{
    public BasicAuthenticationTests(
      IOptionsMonitor&lt;AuthenticationSchemeOptions&gt; options,
      IOptions&lt;BasicAuthenticationOptions&gt; basicAuthOptions,
      ILoggerFactory logger,
      UrlEncoder encoder,
      ISystemClock clock
   ) : base(options, basicAuthOptions, logger, encoder, clock) { }

    [Fact]
    public void BasicAuthenticationTests_Valid_Request()
    {
        // arrange


        // act
        var results = base.HandleAuthenticateAsync();

        // assert
    }
}
</code></pre>
<p>While trying above code, i am getting
<em><strong>The following constructor parameters did not have matching fixture data: IOptionsMonitor'1 options, IOptions'1 _basicAuthOptions, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock</strong></em></p>
<p>also how should I set <strong>Request.Headers[&quot;Authorization&quot;]</strong> in HandleAuthenticateAsync</p>
<p>Any suggestions would be helpful thank you in advance</p>
",https://stackoverflow.com/questions/73218330/unit-testing-basic-authentication-the-following-constructor-parameters-did-no,"['c#', 'unit-testing', 'nunit']",146,False,0,0
I&#39;m getting error when unit testing a method that calls empty() on an object,"<p>Test is erroring with</p>
<pre><code>dataLayerHelper
generateProductLinesDataLayer
extends the datalayer:
ReferenceError: empty is not defined
at Object.generateProductLinesDataLayer (cartridges\gtm\int_gtm_sfra_custom\cartridge\scripts\gtm\dataLayerHelper.js:42:9)
at Context.&lt;anonymous&gt; (cartridges\test\unit\gtm\int_gtm_sfra_custom\scripts\dataLayerHelper.js:59:42)
at processImmediate (internal/timers.js:464:21)
at process.callbackTrampoline (internal/async_hooks.js:131:17)
</code></pre>
<p>Here:</p>
<pre><code>if (!empty(pli.product) &amp;&amp; pli.product.isVariant()) {
    pid = pli.product.masterProduct.ID;
    variant = pli.productID;
}
</code></pre>
<p>Why would I get an error when testing a method that uses a built in empty() method that doesn't require any other reference?</p>
<p>Test:</p>
<pre><code>describe(&quot;generateProductLinesDataLayer&quot;, function () {
        it.only(&quot; extends the datalayer&quot;, function () {
            var result = dataLayerHelper.generateProductLinesDataLayer(productLineItems);
            assert.deepEqual(result, []);
        });
    });
</code></pre>
<pre><code>function generateProductLinesDataLayer(productLineItems) {
......
        if (!empty(pli.product) &amp;&amp; pli.product.isVariant()) {
            pid = pli.product.masterProduct.ID;
            variant = pli.productID;
        }
......
}
</code></pre>
<pre><code>
</code></pre>
",https://stackoverflow.com/questions/72291905/im-getting-error-when-unit-testing-a-method-that-calls-empty-on-an-object,"['javascript', 'unit-testing', 'testing', 'mocha.js']",100,False,0,0
How do I separate between integration testing and unit testing using Hapi in Node.js?,"<p>How do I separate between integration testing and unit testing using Hapi in Node.js?</p>
<p>I am trying to reduce the testing time in our automations for every time we update a unit within our API.</p>
<p>I was wondering can I just create two new folders test/unit and test/int to separate the scripts and what would the update to the package.json require?</p>
<p>I have the following in the package.json which runs the .labrc.js
package.json</p>
<pre><code>    &quot;test&quot;: &quot;npm run version-stamp &amp;&amp; lab --bail -t 80 -r html -o coverage.html -r console -o stdout -r junit -o TestResult.xml -r lcov -o coverage.dat&quot;,
    &quot;simple-test&quot;: &quot;npm run version-stamp &amp;&amp; lab&quot;,
    &quot;test-int&quot;: &quot;not sure what to put here&quot;,
</code></pre>
<p>labrc.js</p>
<pre><code>module.exports = {
    verbose: true,
    timeout: 7500,
    lint: true,
    paths: [
        &quot;test/init/aws&quot;,
        &quot;test/unit/plugins&quot;,
        &quot;test/unit/utils&quot;,
        &quot;test/unit/routes&quot;
    ],
</code></pre>
",https://stackoverflow.com/questions/74690668/how-do-i-separate-between-integration-testing-and-unit-testing-using-hapi-in-nod,"['node.js', 'unit-testing', 'jestjs', 'nunit', 'hapi.js']",52,False,0,1
React Unit testing (useLocation() may be used only in the context of a &lt;Router&gt;),"<p>im getting this error
useLocation() may be used only in the context of a  component.
while unit testing but i have never used that hook
why ? btw the Navbar.tsx is under testing</p>
<p>index.tsx</p>
<pre><code>import React from &quot;react&quot;;
import ReactDOM from &quot;react-dom/client&quot;;
import App from &quot;./App&quot;;
import reportWebVitals from &quot;./reportWebVitals&quot;;
import { BrowserRouter as Router } from &quot;react-router-dom&quot;;
import { QueryClientProvider, QueryClient } from &quot;@tanstack/react-query&quot;;
import { createRoot } from &quot;react-dom/client&quot;;

const queryClient = new QueryClient();
const container = document.getElementById(&quot;root&quot;);
const root = createRoot(container!);
root.render(
  &lt;React.StrictMode&gt;
    &lt;QueryClientProvider client={queryClient}&gt;
      &lt;App /&gt;
    &lt;/QueryClientProvider&gt;
  &lt;/React.StrictMode&gt;
);

reportWebVitals();

</code></pre>
<p>app.tsx</p>
<pre><code>import Navbar from &quot;./components/Navbar/Navbar&quot;;
import &quot;./global.css&quot;;
import Layout from &quot;./Layout/Layout&quot;;
import { BrowserRouter as Router} from &quot;react-router-dom&quot;;

function App() {
  return (
    
      &lt;div id=&quot;root&quot;&gt;
        &lt;Layout /&gt;
      &lt;/div&gt;
    
  );
}

export default App;

</code></pre>
<p>NavBar.tsx</p>
<pre><code>import React from &quot;react&quot;;
import { NavLink, BrowserRouter as Router } from &quot;react-router-dom&quot;;

import {
  StyledNavbarDiv,
  StyledPostsIcon,
  StyledNavBarHolderNav,
  StyledContainerDiv,
  StyledNavLink,
} from &quot;./Navbar.style&quot;;

const Navbar: React.FC = () =&gt; {
  return (
    &lt;Router&gt;
      &lt;StyledContainerDiv&gt;
        &lt;StyledNavLink activeclassname=&quot;selected&quot; to={&quot;posts&quot;}&gt;
          &lt;StyledNavBarHolderNav&gt;
            &lt;StyledPostsIcon&gt;&lt;/StyledPostsIcon&gt;
            &lt;StyledNavbarDiv&gt;Posts&lt;/StyledNavbarDiv&gt;
          &lt;/StyledNavBarHolderNav&gt;
        &lt;/StyledNavLink&gt;
   
      &lt;/StyledContainerDiv&gt;
    &lt;/Router&gt;
  );
};

export default Navbar;

</code></pre>
<p>NavBar.test.tsx</p>
<pre><code>import * as ReactDOM from &quot;react-dom&quot;;
import Navbar from './../Navbar';

describe(&quot;navbar component test&quot;, () =&gt; {
  let container: HTMLDivElement;

  beforeEach(() =&gt; {
    container = document.createElement(&quot;div&quot;);
    document.body.appendChild(container);
    ReactDOM.render(&lt;Navbar /&gt;, container);
  });

  afterEach(() =&gt; {
    document.body.removeChild(container);
    container.remove();
  });

  it(&quot;correctly renders the initial component&quot;, () =&gt; {
    const divs = container.querySelectorAll(&quot;div&quot;);
    expect(divs).toHaveLength(1);
  });

});

</code></pre>
<p>i tried moving the navbar component and i tried wrapping app with router inside index.ts and app.ts but none worked
or i would get another error like you cant put routes in another routes</p>
",https://stackoverflow.com/questions/73463465/react-unit-testing-uselocation-may-be-used-only-in-the-context-of-a-router,"['reactjs', 'typescript', 'unit-testing']",27,False,0,0
How to implement unit testing for a global resposeBus which emits functions in vue,"<p>I want to implement unit testing using vue-test utils for a vue component which uses a global event handler as a vue instance called responseBus. Need to implement unit test using jest.</p>
<p>Here is the code for vue component.</p>
<pre><code>    &lt;script&gt;
import NewQuestionBuilder from '@/components/NewQuestionBuilder.vue'

export default {
  inject: ['$responseBus'],
  props: {
    question: {
      type: Object,
      required: true,
    },
  },
  mounted() {
    this.$responseBus.$on('pseudo', (payload) =&gt; {
      if (payload.questionCode === this.question.questionCode) {
        this.$emit('update:initialValue', payload)
      }
    })
  },
  render(h) {
    return h('div', { class: 'pl-0 md:pl-4 w-full ' }, [
      h(NewQuestionBuilder, { props: { questionData: this.question } }),
    ])
  },
}
&lt;/script&gt;
</code></pre>
<p>Here is the unit test file.</p>
<pre><code>    import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vue from 'vue'
import Component from '../BaseComputed'

const GlobalPlugins = {
  install(v) {
    v.prototype.$eventBus = new Vue()
  },
}

const localVue = createLocalVue()
localVue.use(GlobalPlugins)

describe('BaseComputed', () =&gt; {
  const mocks = {
    $responseBus: {
      $on: jest.fn(),
      $off: jest.fn(),
      $emit: jest.fn(),
    },
  }

  it('listens to event pseudo', () =&gt; {
    const wrapper = shallowMount(Component, {
      mocks,
      propsData: {
        imageUrl: '',
        label: ``,
        initialValue: [],
        isEnabled: true,
        code: '',
        triggers: [],
        choices: [],
        question: {
          questionCode: 'HFFIN0416USOTEL',
        },
      },
    })
    wrapper.vm.$responseBus.$emit('pseudo', {
      questionCode: `HFFIN0416USOTEL`,
    })
    expect(wrapper.vm.question.questionCode).toEqual('HFFIN0416USOTEL')
    expect(wrapper.vm.$responseBus.$on).toHaveBeenCalledTimes(1)
    expect(wrapper.vm.$responseBus.$on).toHaveBeenCalledWith(
      'pseudo',
      jest.fn((payload) =&gt; {
        if (payload.questionCode === this.question.questionCode) {
          this.$emit('update:initialValue', payload)
        }
      })
    )
})
})
</code></pre>
<p>Still couldn't test the 'psuedo' method. Guys need help to achieve this.</p>
",https://stackoverflow.com/questions/72870714/how-to-implement-unit-testing-for-a-global-resposebus-which-emits-functions-in-v,"['vue.js', 'unit-testing', 'jestjs', 'vue-test-utils']",41,False,0,0
how can i pass date time in this function for unit testing usin c#,"<p>this the function i am trying to xunit test, i am new in testing. dont want to change this function</p>
<pre><code>public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(System.DateTime);
        }
</code></pre>
<p>i tried</p>
<pre><code> System.DateTime dateTime = new System.DateTime(2008, 3, 1, 7, 0, 0);
</code></pre>
<p>but cant pass this as argument</p>
<pre><code>public void testfo()
        {
            System.DateTime dateTime = new System.DateTime(2008, 3, 1, 7, 0, 0);
CanConvert(dateTime);
        }

</code></pre>
",https://stackoverflow.com/questions/73318901/how-can-i-pass-date-time-in-this-function-for-unit-testing-usin-c,['c#'],23,True,0,1
"race problem with mocha unit testing Firestore onSnapshot, test ends before onSnapshot returns data","<p>I have a function I'm testing. It's called from the constructor on an object.</p>
<pre><code>constructor(authorID: string) {
  this.loadRecipes(authorID)
}

private loadRecipes = (author_id: string) =&gt; {
    
    const first = query(collection(db, &quot;cookbook&quot;), where(&quot;author_id&quot;, &quot;==&quot;, author_id));
    this._unsubscribe = onSnapshot(first, (querySnapshot) =&gt; {
      this._recipes = [];
      querySnapshot.forEach((doc) =&gt; {
        this._recipes.push(new Recipe(doc.id, doc.data().author_id, &quot;&quot;, &quot;&quot;, -1, &quot;draft&quot;, [], [], [], 0, &quot;&quot;));
      });
    });
};
</code></pre>
<p>I'm calling it from a mocha test:</p>
<pre><code>it(&quot;Creates a recipe list by author ID&quot;, () =&gt; {
    authorRecipes = new RecipeList(author_id);
    assert(authorRecipes.list.length&gt;0);
  });
</code></pre>
<p>The code works fine, but the test fails. The problem is that the test completes running long before the onSnapshot ever fires and populates the list. Is there a way to force the query to populate - sort of like an async/await? Or a way to force mocha to wait? Setting a breakpoint &amp; debugging, the onSnapshot is eventually called so the code works.  I just cannot do any follow on tests because the data isn't there yet.</p>
",https://stackoverflow.com/questions/71149975/race-problem-with-mocha-unit-testing-firestore-onsnapshot-test-ends-before-onsn,"['google-cloud-firestore', 'mocha.js']",43,False,0,1
Angular unit testing-global variable in component is updating but not in unit test,"<p>I am not able to component.nominations, its always 0 in my unit testing. but when i log in component it is logging correctly the length. not able to verify updated component variables in unit test.</p>
<p>My component class</p>
<pre><code>@Component({
 selector: 'app-home',
 templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit, AfterViewInit {
nominations = new MatTableDataSource&lt;Nomination&gt;([]);
isLoaded: boolean;
constructor(private nominationService: NominationService) {
}

ngOnInit() {
this.nominationService.GetAllNominationByUser().then(recs =&gt; {
  this.isLoaded = true;
  console.log(&quot;here &quot;+this.nominations.data.length); //it is logging here correctly
  if (recs.length) {
      this.nominations = new MatTableDataSource(recs);
      console.log(&quot;here1 &quot;+this.nominations.data.length); //it is logging here correctly
      this.isLoaded = true;
  }
  console.log(&quot;here after&quot;+this.nominations.data.length); //it is logging here correctly
});
}
}
</code></pre>
<p>my spec file. component.nominations.data.length is  always 0 in my unit testing. but when i log in component it is logging correctly the length. not able to verify updated component variables in unit test.</p>
<pre><code>describe('HomeComponent', () =&gt; {
let component: HomeComponent;
let fixture: ComponentFixture&lt;HomeComponent&gt;;
let nominationDbServiceMock: any;
const settings: IEnvironmentSettings = null;

beforeEach(waitForAsync(() =&gt; {
    nominationDbServiceMock = jasmine.createSpyObj('NominationService', ['GetAllNominationByUser']);
    nominationDbServiceMock.GetAllNominationByUser.and.returnValue(new Promise((resolve, reject) =&gt; {
        const _reject = false;
        if (_reject) {
          reject(null);
        } else {
          resolve([
            { id: 12345 } as Nomination,
          {  id: 12346} as Nomination
          ]);
        }
      }
      ));
    TestBed.configureTestingModule({
        declarations: [HomeComponent],
        providers: [
            { provide: ENV_SETTINGS, useValue: settings },
            { provide: NominationService, useValue: nominationDbServiceMock },
            FormBuilder]
    }).compileComponents();
}));

beforeEach(() =&gt; {
   
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
});
it('should populate tax table on init', () =&gt; { 
    fixture.detectChanges();
    expect(component.nominations.data.length).toBeGreaterThan(0); //here it is always 0
});     
});
</code></pre>
",https://stackoverflow.com/questions/73368563/angular-unit-testing-global-variable-in-component-is-updating-but-not-in-unit-te,"['angular', 'unit-testing', 'jasmin']",315,False,0,0
In hardhat unit testing how do you assert multiple return values from a contract,"<p>I have this solidity contract function that returns multiple values of multiple types. How do I assert them in my unit tests?</p>
<p>I tried something like
var [x, y] = await contractA.getAll()
etc. but that doesn’t work.</p>
",https://stackoverflow.com/questions/74808408/in-hardhat-unit-testing-how-do-you-assert-multiple-return-values-from-a-contract,"['solidity', 'hardhat']",213,False,0,1
How can I keep unit testing in Unity after introducing security rules to firestore?,"<p>I am using cloud firestore + cloud functions + firestore auth to support my game.</p>
<p>I developed the main part of the app with unit tests in the app plus typescript tests for cloud functions. Now I want to add security rules to secure the data.</p>
<p>When I do so, requiring the calls to be authenticated, all my unit tests in unity (naturally) fails, as I do not authenticate a user but mocks them as data representation of the user in the db.</p>
<p>I want to keep using my unit tests in unity but still requiring the real db to demand authentication.</p>
<p>I have tried to look around for mock auth, or auth test environment, but found nothing except the library <a href=""https://firebase.google.com/docs/reference/emulator-suite/rules-unit-testing/rules-unit-testing"" rel=""nofollow noreferrer"">rules-unit-testing</a>.</p>
<p>I see the content of it with specialized logic for mocking user, making me think that I am understanding this the wrong way by trying to do this in unity. My question is, <strong>How to continue to do game tests in unity, which requires interacting with the firestore server, while keeping security rules?</strong></p>
",https://stackoverflow.com/questions/74476873/how-can-i-keep-unit-testing-in-unity-after-introducing-security-rules-to-firesto,"['unit-testing', 'authentication', 'unity-game-engine', 'google-cloud-firestore', 'firebase-security']",49,True,0,1
"Apollo Client GraphQL Unit Testing return Error: TypeError: (0 , _reactHooks.useQuery) is not a function","<p>I was trying to write unit test with react component from Apollo Client Unit Testing, but I got an error when mocking call to the GraphQL endpoint to some hook functions.</p>
<p>My unit test implement:</p>
<pre><code>import React from 'react';
import MockedProvider from '@apollo/react-testing';
import renderer from 'react-test-renderer';
import { GET_CHARACTER_DETAILS } from '../../containerHooks/useCharacterDetails';
import { UseCharacterDetails } from '../../containerHooks/useCharacterDetails';

const mocks = [
  {
    request: {
      query: GET_CHARACTER_DETAILS,
      variables: {
        id: 1,
      },
    },
    result: {
      data: {
        character: {
          id: '1',
          name: 'Rick Sanchez',
          status: 'Alive',
          gender: 'Male',
        },
      },
    },
  },
];

it('renders without error', () =&gt; {
  renderer.create(
    &lt;MockedProvider mocks={mocks} addTypename={false}&gt;
      &lt;UseCharacterDetails id='1' /&gt;
    &lt;/MockedProvider&gt;
  );
});
</code></pre>
<p>Here is my Test Component</p>
<pre><code>import gql from 'graphql-tag';
import { useQuery } from '@apollo/react-hooks';

export const GET_CHARACTER_DETAILS = gql`
  query CharacterDetails($id: ID!) {
    character(id: $id) {
      id
      name
      status
      species
      type
      gender
      origin {
        name
      }
      location {
        name
      }
      image
      episode {
        name
      }
      created
    }
  }
`;

export const UseCharacterDetails = ({ id }) =&gt; {
  const { loading, error, data } = useQuery(GET_CHARACTER_DETAILS, {
    variables: { id },
  });

  return {
    data,
    error,
    loading,
  };
};
</code></pre>
<p>When I run a test, it throws an error</p>
<blockquote>
<p>TypeError: (0 , _reactHooks.useQuery) is not a function</p>
</blockquote>
",https://stackoverflow.com/questions/71229691/apollo-client-graphql-unit-testing-return-error-typeerror-0-reacthooks-use,"['javascript', 'reactjs', 'unit-testing', 'graphql', 'apollo-client']",924,False,0,0
unit testing in Quarkus with a JAX-RS resource using the active record pattern,"<p>I have this simple OrderResource class that I would like to create unit tests for. I'm qusing Quarkus with Hibernate and Panache. What I don't understand is how do i get the function getOrders in my test? How can I mock the response without running this through a live system? I've currently added the quarkus-panache-mock dependency but i can't figure out how to mock the resource</p>
<p>Should the return values come from some service class? and then be injected into the test?</p>
<pre class=""lang-java prettyprint-override""><code>
@Entity
public class Order extends PanacheEntity {
    public Long id;
    public String summary;
    public String description;
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>@Path(&quot;orders&quot;)
public class OrderResource {

    @GET
    @Path(&quot;orders&quot;)
    public String getAllOrders() {
        return Order.listAll();
    }

    @POST
    @Transactional
    public Response create(Order order) {
        order.persist();
        return Response.created(URI.create(&quot;/orders/&quot; + order.id)).build();
    }


}
</code></pre>
<p>I tried creating a test like this:</p>
<pre class=""lang-java prettyprint-override""><code>
    @Test
    public void testCreateOrder() {
        OrderResource orderResource = new OrderResource();
        System.out.println(orderResource.getAllOrders().get(0).name); //uses the live system
    }

</code></pre>
<p>But this is not a unit test but rather an integration test since it takes data from the real database.</p>
",https://stackoverflow.com/questions/70585921/unit-testing-in-quarkus-with-a-jax-rs-resource-using-the-active-record-pattern,"['java', 'unit-testing', 'testing', 'mocking', 'quarkus']",214,False,0,1
"CS50 - PSET 3 - Tideman - lock_pairs() works when I test it, but fails unit testing","<p>I am at my wits end. I have done my own unit testng and I am getting good results. So, I don't know why check50 is returning errors.</p>
<p>Tideman problem description:
<a href=""https://cs50.harvard.edu/x/2022/psets/3/tideman/"" rel=""nofollow noreferrer"">https://cs50.harvard.edu/x/2022/psets/3/tideman/</a></p>
<p>CS50 IDE:
<a href=""https://ide.cs50.io"" rel=""nofollow noreferrer"">https://ide.cs50.io</a></p>
<p>The lock_pairs method:
<code>The function should create the locked graph, adding all edges in decreasing order of victory strength so long as the edge would not create a cycle.</code></p>
<p>Here is the error</p>
<pre><code>:( lock_pairs locks all pairs when no cycles
    lock_pairs did not lock all pairs
:) lock_pairs skips final pair if it creates cycle
:( lock_pairs skips middle pair if it creates a cycle
    lock_pairs did not correctly lock all non-cyclical pairs
</code></pre>
<p>I am hesitant to look up other similar questions because of the CS50 'honor code' on plagiarism. So, please indulge me this oft-repeated question.</p>
<p>Here is the method:</p>
<pre><code>void lock_pairs(void)
{
    // count forward
    for (int i = 0; i &lt; pair_count; i++)
    {
        int winner = pairs[i].winner;
        int loser = pairs[i].loser;

        if (check_cycle_winner(winner, loser, i) &amp;&amp; check_cycle_loser(loser, winner, i))
        {
            locked[winner][loser] = false;
        }
        else
        {
            locked[winner][loser] = true;
        }
    }
    return;
}
</code></pre>
<p>Here are the 'helper' functions:</p>
<pre><code>bool check_cycle_winner(int winner, int loser, int index)
{
    if (winner == loser) return true;

    if (index == 0) return false;

    return check_cycle_winner(winner, pairs[index - 1].loser, index -1);
}

bool check_cycle_loser(int loser, int winner, int index)
{
    if (loser == winner) return true;

    if (index == 0) return false;

    return check_cycle_loser(loser, pairs[index - 1].winner, index -1);
}
</code></pre>
<p>Full program (to test in CS50 IDE):
<a href=""https://replit.com/@A1cmae0n/PSET3-Tideman#main.c"" rel=""nofollow noreferrer"">https://replit.com/@A1cmae0n/PSET3-Tideman#main.c</a></p>
<p>Testing lock_pairs in replit:
<a href=""https://replit.com/@A1cmae0n/CS50-PSET3-Tideman-lockpairs#main.c"" rel=""nofollow noreferrer"">https://replit.com/@A1cmae0n/CS50-PSET3-Tideman-lockpairs#main.c</a></p>
<p>Any input would be appreciated. Please indulge me the request to respond Socratically to my question rather than spoil the answer :)</p>
",https://stackoverflow.com/questions/74736561/cs50-pset-3-tideman-lock-pairs-works-when-i-test-it-but-fails-unit-test,"['c', 'recursion', 'cs50']",175,False,0,1
Xcode 14 (on Ventura): &quot;Failed to prevent system sleep during UI testing&quot; when UNIT testing,"<p>I'm running Xcode 14 beta 5 on macOS Ventura (13.0 Beta (22A5321d)) and when trying to run unit tests, not UI tests, plain old unit tests, I get this super annoying dialog when starting a test.</p>
<p>This is an SPM package, not an .xcodeproj.</p>
<p><a href=""https://i.stack.imgur.com/B3yvq.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/B3yvq.png"" alt=""enter image description here"" /></a></p>
<p>If I click details, this is shown:</p>
<pre><code>Details

Failed to prevent system sleep during UI testing. Error code: -536870211
Domain: IDEFoundationErrorDomain
Code: 1
User Info: {
    DVTErrorCreationDateKey = &quot;2022-08-17 20:06:42 +0000&quot;;
}
--


System Information

macOS Version 13.0 (Build 22A5321d)
Xcode 14.0 (21330) (Build 14A5294e)
Timestamp: 2022-08-17T22:06:42+02:00
</code></pre>
<p>Sometimes deleting derived data helps, sometimes not.</p>
<p>Any clues? I did not see this error in Xcode 14 beta 1 I think.</p>
",https://stackoverflow.com/questions/73394395/xcode-14-on-ventura-failed-to-prevent-system-sleep-during-ui-testing-when-u,['xcode14'],500,False,2,1
Why unit test getting failed in spring boot,"<p>I'm working on spring boot project. All things work perfectly but while unit testing <code>saveBooking()</code> method of controller then unit testing become failure. In Failure Trace I get <code>java.lang.AssertionError: Response content expected:&lt;Saved&gt; but was:&lt;SAVED&gt;</code>. This code worke perfectly in my postman but failure in unit testing.</p>
<p>Here down is my code:</p>
<p><em>Model</em></p>
<pre><code>public class Booking {
    private String bookingId;
    private String passangerName;
    private String flightName;
    private String source;
    private String destination;
    
    // constructor, getter and setter
}
</code></pre>
<p><em>Controller</em></p>
<pre><code>@RestController
public class BookingController {

    @Autowired
    private BookingService bookingService;

    @PostMapping(&quot;/booking&quot;)
    public String saveBooking(@RequestBody Booking booking) {
        boolean saved = bookingService.saveBooking(booking);
        return &quot;SAVED&quot;;

    }
}
</code></pre>
<p><em>TestController</em></p>
<pre><code>@WebMvcTest(controllers = BookingController.class)
public class BookingControllerTest {

    @MockBean
    private BookingService bookingService;

    @Autowired
    private MockMvc mockMvc;
    
    @Test
    public void testSaveBooking() throws Exception
    {
        Mockito.when(bookingService.saveBooking(any())).thenReturn(true);
        String bookingDetails = &quot;{\r\n&quot;
                + &quot;    \&quot;bookingId\&quot;: \&quot;AA0456\&quot;,\r\n&quot;
                + &quot;    \&quot;passangerName\&quot;: \&quot;Michael\&quot;,\r\n&quot;
                + &quot;    \&quot;flightName\&quot;: \&quot;Air American\&quot;,\r\n&quot;
                + &quot;    \&quot;source\&quot;: \&quot;California\&quot;,\r\n&quot;
                + &quot;    \&quot;destination\&quot;: \&quot;Dubai\&quot;\r\n&quot;
                + &quot;}&quot;;
        RequestBuilder requestBuilder = MockMvcRequestBuilders.post(&quot;/booking&quot;).contentType(MediaType.APPLICATION_JSON).content(bookingDetails);
        mockMvc.perform(requestBuilder).andDo(print()).andExpect(status().isOk()).andExpect(content().string(&quot;Saved&quot;));
    }

}
</code></pre>
",https://stackoverflow.com/questions/72802716/why-unit-test-getting-failed-in-spring-boot,"['spring-boot', 'junit', 'mockito']",271,True,-1,1
How about writing test code for the viewmodel below?,"<p>I created a view model to handle authentication (login and register), but I'm having trouble writing unit testing code. Can anyone help me write unit testing code for the view model below?</p>
<h2>Authentication View Model :</h2>
<pre class=""lang-kotlin prettyprint-override""><code>
class AuthenticationViewModel(private val userRepository: UserRepository) : ViewModel() {
    var user = MutableLiveData&lt;Event&lt;UserModel&gt;&gt;()

    var loading = MutableLiveData&lt;Event&lt;Boolean&gt;&gt;()

    var message = MutableLiveData&lt;Event&lt;String&gt;&gt;()

    var error = MutableLiveData&lt;Event&lt;Boolean&gt;&gt;()

    fun userLogin(email: String, password: String): MutableLiveData&lt;Event&lt;UserModel&gt;&gt; {
        loading.value = Event(true)
        val client = userRepository.userLogin(email, password)
        client.enqueue(object : Callback&lt;UserResponse&gt; {
           override fun onResponse(
               call: Call&lt;UserResponse&gt;,
               response: Response&lt;UserResponse&gt;
            ) {
                Log.e(&quot;AuthenticationViewModel&quot;, &quot;onResponse: &quot; + response.body())
                loading.value = Event(false)
                if (response.isSuccessful) {
                    val responseBody = response.body()?.loginResult
                    error.value = Event(false)
                    userRepository.appExecutors.networkIO.execute {
                        Log.e(&quot;AuthenticationViewModel&quot;, &quot;userLogin: $responseBody&quot;)
                        user.postValue(Event(responseBody!!))
                    }
                } else {
                    Log.e(&quot;AuthenticationViewModel&quot;, &quot;onResponse fail: &quot;)
                    message.value = Event(response.message())
                    error.value = Event(true)
                }
            }

            override fun onFailure(call: Call&lt;UserResponse&gt;, t: Throwable) {
                Log.e(&quot;AuthenticationViewModel&quot;, &quot;onFailure: &quot; + t.message)
                loading.value = Event(false)
                message.value = Event(t.message.toString())
                error.value = Event(true)
            }
        })
        return user
    }

    fun userRegister(
        name: String,
        email: String,
        password: String
    ) {
        loading.value = Event(true)
        val client = userRepository.userRegister(name, email, password)
        client.enqueue(object : Callback&lt;UserResponse&gt; {
            override fun onResponse(
                call: Call&lt;UserResponse&gt;,
                response: Response&lt;UserResponse&gt;
            ) {
                Log.e(&quot;AuthenticationViewModel&quot;, &quot;onResponse: &quot; + response.body())
                loading.value = Event(false)
                if (response.isSuccessful) {
                    error.value = Event(false)
                } else {
                    Log.e(&quot;AuthenticationViewModel&quot;, &quot;onResponse fail: &quot;)
                    message.value = Event(response.message())
                    error.value = Event(true)
                }
            }

            override fun onFailure(call: Call&lt;UserResponse&gt;, t: Throwable) {
                Log.e(&quot;AuthenticationViewModel&quot;, &quot;onFailure: &quot; + t.message)
                loading.value = Event(false)
                message.value = Event(t.message.toString())
                error.value = Event(true)
            }
        })
    }

    fun getUserToken() = userRepository.getUserToken()

    fun saveUserToken(token: String?) {
        viewModelScope.launch {
            if (token != null) {
                userRepository.saveUserToken(token)
            }
        }
    }

    fun saveUserName(name: String?) {
        viewModelScope.launch {
            if (name != null) {
                userRepository.saveUserName(name)
            }
        }
    }

    fun saveUserEmail(email: String) {
        viewModelScope.launch {
            userRepository.saveUserEmail(email)
        }
    }

    fun logout() {
        viewModelScope.launch {
            userRepository.clearCache()
        }
    }

}

</code></pre>
<p>I've tried to write unit testing code, but failed and encountered a <strong>NullPointerException</strong></p>
<h2>AuthenticationViewModelTest :</h2>
<pre class=""lang-kotlin prettyprint-override""><code>@RunWith(MockitoJUnitRunner::class)
class AuthenticationViewModelTest {
    @get:Rule
    var instantExecutorRule = InstantTaskExecutorRule()

    @Mock
    private lateinit var repository: UserRepository
    private lateinit var viewModel: AuthenticationViewModel
    private val dummyUser = DataDummy.generateDummyUser()

    @Before
    fun setUp() {
        viewModel = AuthenticationViewModel(repository)
    }

    @Test
    fun `when userLogin should return user response when email and password are valid and error is false`() {
        val email = DataDummy.userEmail
        val password = DataDummy.userPassword

        val expectedUser = MutableLiveData&lt;Event&lt;UserModel&gt;&gt;()
        expectedUser.value = Event(dummyUser)

        val expectedError = MutableLiveData&lt;Event&lt;Boolean&gt;&gt;()
        expectedError.value = Event(false)

        `when`(viewModel.userLogin(email, password)).thenReturn(expectedUser)

        val actualUser = viewModel.userLogin(email, password).getOrAwaitValue()
        val actualError = viewModel.error.getOrAwaitValue()

        Mockito.verify(repository).userLogin(email, password)
        assertNotNull(actualUser.peekContent())
        assertFalse(actualError.peekContent())
    }
}

</code></pre>
<h2>Error Exception</h2>
<pre><code>java.lang.NullPointerException
    at com.mankart.mankgram.ui.authentication.AuthenticationViewModel.userLogin(AuthenticationViewModel.kt:32)
    at com.mankart.mankgram.ui.authentication.AuthenticationViewModelTest.when userLogin should return user response when email and password are valid and error is false(AuthenticationViewModelTest.kt:46)
    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:55)
    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.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:100)
    at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:107)
    at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:41)
    at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
    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 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.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$2.run(TestWorker.java:176)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)


com.mankart.mankgram.ui.authentication.AuthenticationViewModelTest &gt; when userLogin should return user response when email and password are valid and error is false FAILED
    java.lang.NullPointerException at AuthenticationViewModelTest.kt:46
1 test completed, 1 failed
&gt; Task :app:testDebugUnitTest FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:testDebugUnitTest'.
&gt; There were failing tests. See the report at: file:///C:/Users/asus/AndroidStudioProjects/Submission/Mankgram/app/build/reports/tests/testDebugUnitTest/index.html
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 2m 29s
</code></pre>
",https://stackoverflow.com/questions/71977816/how-about-writing-test-code-for-the-viewmodel-below,"['android', 'unit-testing', 'kotlin', 'testing', 'mockito']",47,False,0,0
How to write unit testing friendly code in ASP.NET Core 6.0?,"<p>I tried to find the unit testing-friendly best code practice in .NET development.</p>
<p>I'm assuming that it will be painful if I got to implement unit testing for an already developed project which is not planned to do unit testing when it was developed.</p>
<ul>
<li>What are things we need to keep in mind when we develop Web API or web applications?</li>
<li>What is the best unit testing-friendly architecture?</li>
<li>What are the principles which we need to follow. eg: Interface segregation in SOLID principles.</li>
</ul>
",https://stackoverflow.com/questions/74129069/how-to-write-unit-testing-friendly-code-in-asp-net-core-6-0,"['c#', '.net', 'performance', 'unit-testing']",51,True,0,1
Android: How can i unit test Rxjava Observable?,"<p>I'm studying android unit testing and i'm a bit stuck of unit testing for rxjava observable.</p>
<p>This method i'm trying to test:</p>
<pre><code>    @Override
    public Observable&lt;AuthenticationUsingSqlEntity&gt; logInUsingSql(String token, String ssid) {
        SqlRepo sqlRepo = new SqlRepo();
        return sqlRepo.authenticate(token, ssid);
    }
</code></pre>
<p>I have created simple ArgumentCaptor to test that input already the same and have been passed on unit testing what i'm trying to do is to test sql retrofit response but i can't.</p>
",https://stackoverflow.com/questions/70731616/android-how-can-i-unit-test-rxjava-observable,"['android', 'unit-testing', 'mockito']",617,False,-1,3
How to write a unit test for a React.js project?,"<p>I am doing a web-based e-commerce site. Now I need to perform unit testing. Are there any tools required for unit testing?</p>
",https://stackoverflow.com/questions/71090670/how-to-write-a-unit-test-for-a-react-js-project,['reactjs'],195,False,-1,1
How to do Unit Testing for the C++ service which performs IPC communication using Unix domain socket in linux?,"<p>I am developing an C++ service to achieve IPC using Unix domain socket in Linux.</p>
<p>How can I perform Unit Testing to test <strong>CreateSocket and RunServer class method</strong> all use case?</p>
<p>Can someone suggest a way to perform Unit Testing for such kind of IPC communication service ? I am new to Unit Testing.
I am not sure how to design class such a way that I can perform Unit Testing.</p>
<p>Need to Test following Functionality for Unit Testing:</p>
<ol>
<li>CreateSocket - success</li>
<li>CreateSocket - Failed at  unlink system call</li>
<li>CreateSocket - Failed at  socket system call</li>
<li>CreateSocket - Failed at  bind system call</li>
<li>CreateSocket - Failed at  listen system call</li>
<li>RunServer -  Success</li>
<li>RunServer -  Failed at accept system call</li>
<li>RunServer -  Failed at read system call</li>
<li>RunServer -  Failed at write system call</li>
<li>RunServer -  Failed at default switch case error case</li>
</ol>
<pre><code>
#include &lt;sys/types.h&gt;
#include &lt;sys/socket.h&gt;
#include &lt;sys/un.h&gt;
#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;errno.h&gt;
#include &lt;unistd.h&gt;
#include &lt;sys/select.h&gt;
#include &lt;sys/stat.h&gt;

#define SERVER_SOCKET       &quot;/dev/ipcserver&quot;

#define TOTAL_QUEUE_CONNECTION  10

enum message_type
{
    REQUEST,
    RESPONSE,
    DICONNECT
};

struct message 
{
    message_type type;
    char data [50];
};

class Server
{
    private:
    int server_socket_fd;
    fd_set fds, readfds;
    int fdmax;


    struct message message;

    public:
    int CreateSocket(void);
    int RunServer();

    Server()
    {
        FD_ZERO (&amp;fds);
        FD_ZERO (&amp;readfds);
    }

    ~Server()
    {

    }
};


int Server::CreateSocket()
{
    // create a unix domain socket, 
    struct stat statbuf;
    if (stat (SERVER_SOCKET, &amp;statbuf) == 0) 
    {
        if (unlink (SERVER_SOCKET) == -1)
        {
            printf (&quot;unlink failed \n&quot;);
            return -1;
        }   
    }

    if ((server_socket_fd = socket (AF_UNIX, SOCK_SEQPACKET, 0)) == -1)
    {
        printf (&quot;socket failed \n &quot;);
        return -1;
    }

    struct sockaddr_un socket_address;

    memset (&amp;socket_address, 0, sizeof (struct sockaddr_un));
    socket_address.sun_family = AF_UNIX;
    strncpy (socket_address.sun_path, SERVER_SOCKET, sizeof(socket_address.sun_path) - 1);

    if (bind (server_socket_fd, (const struct sockaddr *) &amp;socket_address, sizeof (struct sockaddr_un)) == -1)
    {
        printf (&quot;bind failed \n&quot;);
        return -1;
    }    

    if (listen (server_socket_fd, TOTAL_QUEUE_CONNECTION) == -1)
    {
        printf (&quot;listen failed \n&quot;);
        return -1;
    }    
    
    FD_SET (server_socket_fd, &amp;fds);
    fdmax = server_socket_fd;

    return 0;
}


int Server::RunServer()
{
    while (1) 
    {
        readfds = fds;
        // monitor readfds for readiness for reading
        if (select (fdmax + 1, &amp;readfds, NULL, NULL, NULL) == -1)
        {
            printf (&quot;select failed \n&quot;);
            return -1;
        }
        // Some sockets are ready. Examine readfds
        for (int fd = 0; fd &lt; (fdmax + 1); fd++) 
        {
            if (FD_ISSET (fd, &amp;readfds)) 
            {  // fd is ready for reading
                if (fd == server_socket_fd) 
                {  // request for new connection
                    int fd_new;
                    if ((fd_new = accept (server_socket_fd, NULL, NULL)) == -1)
                    {
                        printf (&quot;accept failed \n&quot;);

                    }
                    FD_SET (fd_new, &amp;fds);
                    if (fd_new &gt; fdmax)
                    {
                        fdmax = fd_new;
                    }
                }
                else  // data from an existing connection
                {
                    memset (&amp;message, '\0', sizeof (struct message));
                    ssize_t numbytes = read (fd, &amp;message, sizeof (struct message));

                    if (numbytes == -1)
                    {
                        printf (&quot;read failed \n&quot;);
                    }
                    else
                    {
                        printf (&quot;Data received from client : \n&quot;);
                        switch (message.type) 
                        {
                            case REQUEST:
                            {
                                memset (&amp;message, '\0', sizeof (struct message));
                                char data[] = {0x01,0x02,0x03,0x04,0x05,0x06};
                                memcpy(message.data,data,sizeof(data));
                                message.type = RESPONSE;
                                if (write (fd, &amp;message, sizeof (struct message)) == -1)
                                {
                                    printf (&quot;write error \n&quot;);
                                }
                                break;
                            }
                            case DICONNECT:  // clear client connection from monitored fd set
                            {
                                FD_CLR(fd,&amp;fds);
                            }
                            default:
                            {
                                printf (&quot;Unexpected message from client\n&quot;);
                                break;
                            }
                        }
                    }
                }
            } // if 
        } // for
    } // while (1)
    return 0;
}


int main()
{
    Server IPCServer;
    int status = IPCServer.CreateSocket();
    if(status == 0)
    {
        IPCServer.RunServer();
    }
    else
    {
        printf(&quot;IPCServer create fail\n&quot;);
        return -1;
    }
    return 0;
}
</code></pre>
",https://stackoverflow.com/questions/71122748/how-to-do-unit-testing-for-the-c-service-which-performs-ipc-communication-usin,"['c++', 'linux', 'googletest', 'googlemock']",289,False,0,0
Bottle - Backend testing,"<p>I am trying to test my backend functionality for my Bottle app. More specifically, I am interested in <strong>unit testing</strong>.</p>
<p>Is there any tool that can be used for this? Does Bottle provide any own unit testing tools?</p>
",https://stackoverflow.com/questions/71953724/bottle-backend-testing,"['unit-testing', 'frameworks', 'bottle']",17,False,1,0
Getting RuntimeError: command not found: initdb for testing.postgresql.Postgresql,"<p>I have following code.</p>
<pre><code>import testing.postgresql
sql = testing.postgresql.Postgresql(copy_data_from=r&quot;path_to_my_sql_file.sql&quot;)
</code></pre>
<p>I want to create dummy data for unit testing
but getting this error</p>
<pre><code>raise RuntimeError(&quot;command not found: %s&quot; % name)
RuntimeError: command not found: initdb
</code></pre>
<p>FYI: I am trying this for database mocking for unit testing
If there are better ways to do it, please share, Thanks!!</p>
",https://stackoverflow.com/questions/72464664/getting-runtimeerror-command-not-found-initdb-for-testing-postgresql-postgresq,"['python', 'postgresql', 'unit-testing']",385,False,1,1
How to do the unit testing of history.push function?,"<p>I want to unit test the following element, especially the <code>onClick</code> function, But have no idea how to do the unit testing</p>
<pre><code>const baseURL = &quot;/Security/Users/&quot;;


return (
    &lt;div&gt;
      &lt;div className=&quot;flex-between&quot;&gt;
        &lt;button
          className=&quot;bt-save&quot;
          onClick={() =&gt; history.push(baseURL + &quot;Add&quot;)}
        &gt;
          Add
        &lt;/button&gt;
       &lt;/div&gt;
    &lt;/div&gt;
  );
</code></pre>
<p>this is related to react unit testing using jest. From this, I want to unit test the Add Button <code>onClick</code> function.</p>
<p>Here is my approach to unit test this function</p>
<pre><code>it('Should run the callback function when clicked', async () =&gt; {
    const onClick = jest.fn(baseURL + &quot;Add&quot;)

    render(&lt;button push={onClick}&gt; Add &lt;/button&gt;)

    const addButton = screen.getByText('Add')
    await userEvent.click(addButton)
    expect(onClick).toHaveBeenCalled()
})
</code></pre>
<p>I'm getting the following error when I'm trying to do the testing.</p>
<p><a href=""https://i.stack.imgur.com/cH7lq.png"" rel=""nofollow noreferrer"">I'm getting this result on the console</a></p>
<p>Can anyone help me understand this <code>onClick</code> function unit testing</p>
",https://stackoverflow.com/questions/73647358/how-to-do-the-unit-testing-of-history-push-function,"['reactjs', 'jestjs']",36,False,-1,1
"Is there a way to turn off Exception Notification in Delphi while unit testing, on a particular project","<p>I am using <strong>Delphi 11</strong> with the <strong>DUnitx</strong> unit testing.  I know that I can turn off &quot;Language Exceptions&quot; in <strong>Tools/Options</strong>.  But this turns it off for all projects.</p>
<p>Is there a way to turn them off for &quot;unit testing&quot;, or &quot;per project&quot;.</p>
",https://stackoverflow.com/questions/72640014/is-there-a-way-to-turn-off-exception-notification-in-delphi-while-unit-testing,"['unit-testing', 'delphi', 'exception', 'delphi-11-alexandria']",358,True,3,3
Cpp integration tests,"<p>I'm trying to learn a methodology or some design pattern for integration testing.
I'm not talking about unit testing or using mocks for unit testing.</p>
<p>I want to test some fetcher that involve several functions or some flow E2E.</p>
",https://stackoverflow.com/questions/72748920/cpp-integration-tests,"['c++', 'unit-testing', 'integration-testing']",114,False,0,0
NestJS unit testing of service involving transactional Entity Manager,"<pre><code>I have a create function on service like this on service.service.ts file

import { Service } from './entity/service.entity';
import { EntityManager } from 'typeorm';


async create(
  transactionalEntityManager: EntityManager,
  data: any
): Promise&lt;Service&gt; {
  return transactionalEntityManager.save(Service, data);
}
</code></pre>
<pre><code>And a POST route like this on service.controller.ts 

import { EntityManager, getConnection } from 'typeorm';
import { Service } from './entity/service.entity';


@Post()
async createService(
  @Body() body: ServiceDto,
  const user = { user_id: 1, company_id: 2 }
): Promise&lt;Service&gt; {
  return getConnection().transaction(async (t: EntityManager) =&gt;
    this.service.create(t, {
      ...body,
      company_id: user.company_id,
      added_by: user.user_id,
    })
  );
}


</code></pre>
<p>I need to write unit testing for the create function on service.service.ts.
How can i write unit testing for this function?
I got stuck on transaction.</p>
<p>I tried this <a href=""https://github.com/typeorm/typeorm/issues/2586"" rel=""nofollow noreferrer"">https://github.com/typeorm/typeorm/issues/2586</a>
But none of this worked for me.</p>
",https://stackoverflow.com/questions/74298475/nestjs-unit-testing-of-service-involving-transactional-entity-manager,"['unit-testing', 'jestjs', 'transactions', 'nestjs', 'typeorm']",76,False,1,0
"When you use Simulink to generate C code, do you perform unit testing on the generated code or Simulink model or both? Does it make sense to do both?","<p>When you consider the V-model, implementation is at the bottom. If you have created your component design (detailed design) using Simulink, then your generated code can be considered as 'implementation' (right?). Now if you want to perform unit testing (first step on the right side of the V-model), do you perform unit testing on the Simulink model units or do you perform the unit testing on the generated C-code units? Or do you have to cover both?</p>
",https://stackoverflow.com/questions/71985221/when-you-use-simulink-to-generate-c-code-do-you-perform-unit-testing-on-the-gen,"['unit-testing', 'simulink', 'v-model']",132,False,0,0
How to write unit test for a function in button click in angular,"<p><strong>I write a code for unit testing but it isn't worked. I wanna know how to use it and I am new to unit testing</strong></p>
<p><strong>COMPONENT.HTML</strong></p>
<pre><code>&lt;button class=&quot;set-button&quot; (click)=&quot;clickFunction()&quot;&gt; SAVE&lt;/button&gt;
</code></pre>
<p><strong>COMPONENT.TS</strong></p>
<pre><code>clickFunction(){
console.log('WORKED');
}
</code></pre>
<p><strong>COMPONENT.SPECS.TS</strong></p>
<pre><code>    it('function on button click ', () =&gt; {
    spyOn(component, 'clickFunction');
    let btn = fixture.debugElement.nativeElement.querySelector('set-button');
    fixture.detectChanges();
    fixture.whenStable().Then(() =&gt;{
    expect(component.clickFunction).toHaveBeenCalled();
    })
  });
</code></pre>
<p><strong>I want to know what have i done wrong here.Thanks in advance</strong></p>
",https://stackoverflow.com/questions/72877216/how-to-write-unit-test-for-a-function-in-button-click-in-angular,['angular'],539,True,-1,1
How to use in memory (H2) Database in Node JS with express framework?,"<p>I have some data from oracle table. I will be using H2 database to temporary store those data for unit testing.</p>
<p>Currently I am working on express API to connect to H2 Database for unit testing. What are the steps that I need to follow ?</p>
",https://stackoverflow.com/questions/73297077/how-to-use-in-memory-h2-database-in-node-js-with-express-framework,"['node.js', 'express', 'unit-testing', 'h2', 'rdbms']",307,False,1,0
Unit testing for functions defined on databricks notebook and unit testing for pyspark DF,"<p>I have defined few functions and calling it in other notebooks, i want to create a notebook which does unit testing for all these functions in ADF and also need to do unit testing like count match between source file and data frame.</p>
<p>How to achieve this?</p>
",https://stackoverflow.com/questions/73018323/unit-testing-for-functions-defined-on-databricks-notebook-and-unit-testing-for-p,"['unit-testing', 'databricks', 'azure-databricks', 'azure-data-factory']",514,True,2,2
How to do unit testing when api call in flutter,"<pre class=""lang-js prettyprint-override""><code>class CategoryMapping extends ChangeNotifier {
   final GetCategoryMapping _mapping = GetCategoryMapping();
   List categorizationData = [];
   List get categoryList =&gt; categorizationData;

Future getDatas() async {
try {
  final response = await _mapping.mapingDatas();
  Iterable data = response[&quot;helpDetails&quot;][&quot;mappingRows&quot;];
  final list = data;
  log(data.runtimeType.toString());
  categorizationData = list.map((e) =&gt; e).toList();
  log(&quot;data ${categorizationData[0][&quot;givenCategory&quot;]} &quot;);
} catch (e) {
  log(e.toString());
}
return categorizationData; //returining a dynamic list
} }
</code></pre>
<p>How to do unit testing in this api calls.In this methods i didin't used to models. I tried some time , but it failed. I am just started to learning unit testing. So kindly request to how to test this code in properly,</p>
",https://stackoverflow.com/questions/74096550/how-to-do-unit-testing-when-api-call-in-flutter,"['flutter', 'unit-testing', 'dart', 'flutter-test', 'provider']",64,False,0,0
React Unit Testing: TypeError: Cannot read properties of null (reading &#39;navigate&#39;),"<p>I'm doing unit testing in react for function with querySelector and select property of querySelector with logout as following. (oj-gbu-app-shell) is company internal html tag library.</p>
<pre><code>  async nextState(): Promise&lt;UserSessionState&gt; {
    const shell: any = document.querySelector('oj-gbu-app-shell');
    shell.navigate([{ path: 'logout' }]);
    UserSessionFacade.setUserSessionExpired(!this.isCancelledState());
    return new UserSessionActiveState(this.getConfig());
  }
</code></pre>
<p>When I'm doing unit testing as following code.</p>
<pre><code>  it('Should transit to Active State', async () =&gt; {
    testCase = new SessionExpiredState(testConfig, true);
    const nextState: UserSessionState = await testCase.nextState();
    expect(nextState.constructor.name).to.be.eq('UserSessionActiveState');
    expect(sessionState).to.be.false;
  });
</code></pre>
<p>It always return me error</p>
<pre><code> TypeError: Cannot read properties of null (reading 'navigate')
</code></pre>
",https://stackoverflow.com/questions/72554321/react-unit-testing-typeerror-cannot-read-properties-of-null-reading-navigate,"['reactjs', 'typescript', 'unit-testing', 'jestjs', 'preact']",990,False,0,0
"In Spring dependency injection, how does tight coupling hurt the unit testing?","<p>Somebody explained it to me once that, In spring framework, we program to the interface rather than programming to concerete class, because it leads to tight coupling, and that's problematic in unit testing while doing the mocking.</p>
<p>I understand the tight coupling part based on the example <a href=""https://stackoverflow.com/questions/2832017/what-is-the-difference-between-loose-coupling-and-tight-coupling-in-the-object-o"">here</a>, but I don't understand how tight coupling is a problem with unit testing and mocking.</p>
<p>Just like the way we mock an interface, we can mock a concerte class. So, how tight coupleing hurts the unit testing?</p>
",https://stackoverflow.com/questions/72616542/in-spring-dependency-injection-how-does-tight-coupling-hurt-the-unit-testing,"['spring', 'unit-testing', 'dependency-injection']",17,False,0,0
Reactive State function unit testing in vue,"<p>I am very new to unit testing. I have reactive state usage in the component. would like to write unit testing for the component.</p>
<p>The example test component is defined below</p>
<pre><code> &lt;script setup lang=&quot;ts&quot;&gt;
 const state = reactive({ 
  isExpired: true as boolean, 
 })
 &lt;/script&gt;
&lt;template&gt;
    &lt;div class=&quot;container&quot; v-if=&quot;state.isExpired === false&quot;&gt;&lt;/div&gt;
&lt;/template&gt;
</code></pre>
<p>Here, I want to check whether the container is rendering or not. isExpired value will be dynamically changed.</p>
<p>I have tried the test cases for the component as shared below</p>
<pre><code>describe(&quot;Test suit for component&quot;,()=&gt;{
   let wrapper = shallowMount(TestComponent,{
     isExpired : false
   });
   it(&quot;its should display container style&quot;,async ()=&gt;{ 
      expect(wrapper.find('.container').exists()).toBeTruthy();
   });
});
</code></pre>
<p>I am not able to find the relevant unit testing in the online resources. Would like to know how to test the reactive state of component.</p>
",https://stackoverflow.com/questions/73189637/reactive-state-function-unit-testing-in-vue,"['vue.js', 'jestjs', 'vuejs3', 'ts-jest']",544,False,0,1
How do I compare two list in expect function of flutter unit testing?,"<p><code>List&lt;int&gt; l1=[1,2,3];  List&lt;int&gt; l2=[1,2,3];  expect (l1,l2);</code></p>
<p>This is the code I'm using in Flutter unit testing.</p>
<p>Eventhough both of the list has the same content I'm not able to pass the test. I'm not able to find the usecase of comparing lists using Equatable in Flutter unit testing. Can someone please help? Thanks!</p>
",https://stackoverflow.com/questions/71578026/how-do-i-compare-two-list-in-expect-function-of-flutter-unit-testing,"['flutter', 'unit-testing', 'dart', 'testing']",1854,True,1,2
Unit test for void method with Interface as parameter,"<p>New to Unit testing, I have below sample code and I want to create a unit test for this , Please suggest what should i do to create a unit test for this ? any link or pointers would be helpful to start</p>
<pre><code>public class UserNotification : Work
{
    public override void Execute(IWorkContext iwc)
    {
        throw new InvalidWorkException($&quot;some message:{iwc.Name} and :{iwc.Dept}&quot;);
    }
}
</code></pre>
<p>Edit: using MSTest for Unit testing</p>
",https://stackoverflow.com/questions/71306532/unit-test-for-void-method-with-interface-as-parameter,"['c#', 'unit-testing', 'mstest']",913,False,-1,3
NextRouter was not mounted Next.JS,"<p>Using <code>import { useRouter } from &quot;next/router&quot;;</code> as <code>import { useRouter } from &quot;next/navigation&quot;;</code> throws  &quot;Argument of type '{ pathname: string; query: { search: string; }; }' is not assignable to parameter of type 'string'.&quot;</p>
<pre><code>    const router = useRouter();
    const [searchInput, setSearchInput] = useState(&quot;&quot;);

    const search = (e) =&gt; {
                router.push({
                    pathname: '/search',
                    query: {
                        search: searchInput,
                    },
                })
    }
</code></pre>
<p>NextJS <a href=""https://nextjs.org/docs/api-reference/next/router#router-object"" rel=""noreferrer"">documentation </a></p>
<p>Froms docs:
&quot;A component used useRouter outside a Next.js application, or was rendered outside a Next.js application. This can happen when doing unit testing on components that use the useRouter hook as they are not configured with Next.js' contexts.&quot;</p>
",https://stackoverflow.com/questions/74421327/nextrouter-was-not-mounted-next-js,"['typescript', 'next.js', 'next-router']",54628,True,56,7
Mock acmpca interfaces of aws-sdk-go-v2,"<p>I'm using latest v1.17.15 aws-sdk-go-v2 for acmpca but this doesn't have acmpcaiface interfaces. Now how to mock these acmpca api for my unit testing?
Please help me to mock the interfaces. Currently I'm using IssueCertificate() and GetCertificate() in my code which needs to be mocked for unit testing.</p>
",https://stackoverflow.com/questions/73728758/mock-acmpca-interfaces-of-aws-sdk-go-v2,"['amazon-web-services', 'aws-acm']",166,True,0,1
Unit testing - mocking service which has a List as a data storage,"<p>I'm new to Unit testing and I'm trying to learn how to do it.</p>
<p>I'm using Moq to Mock the dependencies.</p>
<p>Here's my Testing class:</p>
<pre><code>using Microsoft.AspNetCore.Mvc;
using Moq;
using scholarship.Controllers;
using scholarship.Services.Interface;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using Xunit;

namespace Testing
{
    public class InternControllerTests
    {
        private Mock&lt;IInternService&gt; _internService = new Mock&lt;IInternService&gt;(); 

        [Theory]
        [InlineData(&quot;00000000-0000-0000-0000-000000000001&quot;)]
        [InlineData(&quot;00000000-0000-0000-0000-000000000002&quot;)]
        public void Delete_Intern(Guid id)
        {
            InternsController internsController
                = new InternsController(_internService.Object);

            var actual = internsController.DeleteIntern(id) as ObjectResult;

            Assert.True(actual is OkObjectResult);
        }

        [Theory]
        [InlineData(&quot;00000000-0000-0000-0000-000000000000&quot;)]
        [InlineData(&quot;00000000-0000-0000-0000-000000000005&quot;)]
        public void Delete_Intern_NotFound(Guid id)
        {
            InternsController internsController
                = new InternsController(_internService.Object);

            var actual = internsController.DeleteIntern(id) as ObjectResult;

            Assert.True(actual is NotFoundObjectResult);
        }
    }
}
</code></pre>
<p>the service:</p>
<pre><code>using scholarship.Models;
using scholarship.Services.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace scholarship.Services.Class
{
    public class InternCollectionService : IInternService
    {
        public static List&lt;Intern&gt; _interns = new List&lt;Intern&gt;
        {
            new Intern { ID = new Guid(&quot;00000000-0000-0000-0000-000000000001&quot;), FirstName = &quot;Octavian&quot;, LastName = &quot;Niculescu&quot;, DateOfBirth=new DateTime(2001,01,01)},
            new Intern { ID = new Guid(&quot;00000000-0000-0000-0000-000000000002&quot;), FirstName = &quot;Andrei&quot;, LastName = &quot;Popescu&quot;, DateOfBirth=new DateTime(2002,01,01)},
            new Intern { ID = new Guid(&quot;00000000-0000-0000-0000-000000000003&quot;), FirstName = &quot;Calin&quot;, LastName = &quot;David&quot;, DateOfBirth=new DateTime(2003,01,01)},
        };
        public bool Create(Intern model)
        {
            _interns.Add(model);
            return true;
        }

        public bool Delete(Guid id)
        {
            int index = _interns.FindIndex(intern =&gt; intern.ID == id);
            if (index == -1)
            {
                return false;
            }
            _interns.RemoveAt(index);
            return true;
        }

        public Intern Get(Guid id)
        {
            return (from intern in _interns
                          where intern.ID == id
                          select intern).FirstOrDefault();
        }

        public List&lt;Intern&gt; GetAll()
        {
            return _interns;
        }

        public bool Update(Guid id, Intern model)
        {
            int index = _interns.FindIndex(intern =&gt; intern.ID == id);
            if (index == -1)
            {
                return false;
            }
            model.ID = id;
            _interns[index] = model;
            return true;
        }
    }
}
</code></pre>
<p>the controller</p>
<pre><code>using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using scholarship.Models;
using scholarship.Services.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace scholarship.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    [ApiController]
    public class InternsController : ControllerBase
    {
        IInternService _internService;
        public InternsController(IInternService internService)
        {
            _internService = internService ?? throw new ArgumentNullException(nameof(internService));
        }

        [HttpGet]
        public IActionResult GetInterns()
        {
            return Ok(_internService.GetAll());
        }

        [HttpGet(&quot;{Id}&quot;, Name = &quot;GetIntern&quot;)]
        public IActionResult GetIntern([FromRoute] Guid Id)
        {
            Intern? intern = _internService.Get(Id);
            if(intern == null)
            {
                return NotFound();
            }
            return Ok(intern);
        }

        [HttpPost]
        public IActionResult AddIntern([FromBody] Intern intern)
        {
            intern.ID = Guid.NewGuid();
            _internService.Create(intern);
            return CreatedAtRoute(&quot;GetIntern&quot;, new { ID = intern.ID }, intern);
        }

        [HttpPut(&quot;{id}&quot;)]
        public IActionResult UpdateIntern([FromBody] Intern intern, Guid id)
        {
            if (intern == null)
            {
                return BadRequest(&quot;Intern cannot be null&quot;);
            }
            _internService.Update(id, intern);
            return Ok();
        }

        [HttpDelete(&quot;{id}&quot;)]
        public IActionResult DeleteIntern(Guid id)
        {
            bool deleted = _internService.Delete(id);
            if (deleted == false)
            {
                return NotFound(&quot;Intern cannot be found&quot;);
            }
            return Ok();
        }
    }
}
</code></pre>
<p>The project is a very small one, I used it to start learning .net.</p>
<p>Now I want to learn Unit Testing, and I'm trying to learn Unit Testing.</p>
<p>The Delete tests fail.</p>
<p>I think this happens because by mocking the service, there is no list with data like in the service.</p>
<p>So, how should I make the Delete tests work? Should I somehow mock that list too? (I don't know how)</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/71815076/unit-testing-mocking-service-which-has-a-list-as-a-data-storage,"['c#', 'unit-testing', 'asp.net-core-mvc']",317,True,1,1
"Angular Testing: &quot;Expected a spy, but got Function&quot; in Capacitor Browser Plugin","<p>I have many problems with unit testing in Angular, is my first time making unit testing.
Well, I have an error on Browser plugin testing:</p>
<pre><code>Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got Function.
</code></pre>
<p>On my component I just have this:</p>
<pre><code>    async goToPage(path: string) {
        let url_ = environment.apiUrl + path;
        await Browser.open({url : url_,presentationStyle: 'popover'})
    }
</code></pre>
<p>and tried to resolve this by many ways:</p>
<pre><code>it('should use In App Browser', () =&gt; {
    const browser = Browser;
    const spy = spyOn(browser,'open');
    const url = '/api/resource/TOS';
    component.goToPage(url);
    expect(spy.call).toHaveBeenCalled();
}); 

it('should use In App Browser', () =&gt; {
    spyOn(Browser,'open');
    expect(Browser.open).toHaveBeenCalled();
});
//Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got Function.


it('should use In App Browser', () =&gt; {
    const browser = Browser;
    spyOn(browser,'open');
    expect(browser.open).toHaveBeenCalled();
});
//Expected a spy, but got Function.


it('should use In App Browser', () =&gt; {
    const browser = Browser;
    spyOn(browser,'open').and.returnValue(Promise.resolve());;
    expect(browser.open).toHaveBeenCalled();
});
//Expected a spy, but got Function.


it('should use In App Browser', async() =&gt; {
    const browser = Browser;
    spyOn(browser, 'open')

    expect(browser.open).toHaveBeenCalled();
});
//Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got Function.
//Usage: expect(&lt;spyObj&gt;).toHaveBeenCalled()


it('should use In App Browser', async() =&gt; {
  const browser = Browser;
  spyOn(browser, 'open')
  expect(await browser.open).toHaveBeenCalled();
});
//Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got Function.


it('should create', (done) =&gt; {
  let browser = Browser;
  spyOn&lt;any&gt;(browser, 'open');
  const url_ = environment.apiUrl + '/api/resource/About';
  fixture.whenStable().then(() =&gt; {
      expect(browser.open).toHaveBeenCalled();   expect(browser.open).toHaveBeenCalledWith({url : url_,presentationStyle: 'popover'});
      done();
  });
});
//Unhandled promise rejection: Error: &lt;toHaveBeenCalled&gt; : Expected a spy, but got Function.
//Usage: expect(&lt;spyObj&gt;).toHaveBeenCalled()
</code></pre>
<p>Do you know some way to fix it? Thank you!</p>
",https://stackoverflow.com/questions/72637702/angular-testing-expected-a-spy-but-got-function-in-capacitor-browser-plugin,"['angular', 'unit-testing', 'capacitor']",120,True,0,1
Can we do unit testing controllers in Blazor WebAssembly using Bunit,"<p>Can we do unit testing for controllers/end point in Blazor WebAssembly using Bunit x unit?</p>
<p><a href=""https://bunit.dev/"" rel=""nofollow noreferrer"">https://bunit.dev/</a></p>
<p>like this
<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>If not what is the way to do unit test for API status code checking in Blazor WebAssembly?</p>
<p>Please guide me.</p>
",https://stackoverflow.com/questions/74828550/can-we-do-unit-testing-controllers-in-blazor-webassembly-using-bunit,"['unit-testing', 'blazor', 'xunit', 'blazor-webassembly', 'bunit']",80,False,2,0
Can I apply &#39;setupFilesAfterEnv&#39; to specific file in jest config?,"<p>I'm working on appling prisma <code>unit testing</code> and <code>Integration testing</code></p>
<p>I want to apply unit testing for <code>*.service.test.ts</code> files
and intergration testing for <code>*.test.ts</code> files.</p>
<p>I followed the Prisma document, but there is something that doesn't work.</p>
<ul>
<li>singleton.ts</li>
</ul>
<pre><code>import { mockReset, mockDeep, DeepMockProxy } from &quot;jest-mock-extended&quot;;
import { PrismaClient } from &quot;@prisma/client&quot;;
import Prisma from &quot;../src/db/prisma&quot;;

jest.mock(&quot;../src/db/prisma&quot;, () =&gt; {
  return {
    __esModule: true,
    default: mockDeep&lt;PrismaClient&gt;(),
  };
});

beforeEach(() =&gt; {
  // eslint-disable-next-line no-use-before-define
  mockReset(prismaMock);
});

export const prismaMock = Prisma as unknown as DeepMockProxy&lt;PrismaClient&gt;;

</code></pre>
<ul>
<li>jest.config.ts</li>
</ul>
<p>When turing off <code>setupFilesAfterEnv</code> option, testing <code>*.test.ts</code> files are working.</p>
<p>So I Want turn off <code>setupFilesAfterEnv</code> option in Integration testing</p>
<p>Is it applicable only when unit testing?</p>
<pre><code>...

setupFilesAfterEnv: [
 &quot;./jest/singleton.ts&quot;

]
</code></pre>
",https://stackoverflow.com/questions/73119123/can-i-apply-setupfilesafterenv-to-specific-file-in-jest-config,"['node.js', 'unit-testing', 'integration-testing', 'prisma', 'ts-jest']",739,True,0,1
What is purpose of writing a protocol for even a simple Swift App | Swift,"<p>Wondering what the benefits of writing a protocol for a function are. For example given the following simple example what could be the justification for first creating a protocol that the class conforms to? Is it generally better to always create and conform to a protocol? Better for unit testing?</p>
<p>Are their advantages for doing unit testing when writing ng</p>
<pre><code>protocol UserRepositoryProtocol {
    func fetchUser (completion: (User)-&gt; Void)
}
final class UserRepository: UserRepositoryProtocol {
    func fetchUser (completion: (User) -&gt; Void) {
    }
}
</code></pre>
",https://stackoverflow.com/questions/73846827/what-is-purpose-of-writing-a-protocol-for-even-a-simple-swift-app-swift,['swift'],33,False,0,0
How to mock the if condition statement in jasmine?,"<p>I have if block condition. I need to write test case condition using jasmine. As I am new to unit testing find it difficult to mock .
This is my code which is to be mocked.</p>
<pre><code>if (this.SC &gt; 0) {
        this.SC--;
        this.nButtonShown = false;
        this.SPCFun(this.SC);
        this.aButtonState = true;
        this.states[this.SC + 1] = 'disabled';
        this.statesColor[this.SC + 1] = '#8B9345';
        this.stateIcons[this.SC + 1] = false;
        this.statesText[this.SC] = 'Progress';
        if (this.SC == 0) {
          this.pButtonShown = true;
        } else {
          this.pButtonShown = false;
        }
        this.statesText[this.SC + 1] = 'Not yet started';
      }
</code></pre>
<p>By default value of variable SC is set to 0. which I am not able to change while unit testing.
Appreciate if anyone can help on the same!!</p>
",https://stackoverflow.com/questions/72827067/how-to-mock-the-if-condition-statement-in-jasmine,"['unit-testing', 'jasmine']",59,False,0,0
Unit testing a Facade design pattern,"<p>This is a simple python code for Facade design pattern. The code itself doesn't have any problems but I'm new to unit testing and I don't know how to do it. Also, this is not my code and I'm just trying to practice unit testing.</p>
<pre><code>class Addition:
    def __init__(self, field1: int, field2: int):
        self.field1 = field1
        self.field2 = field2

    def get_result(self):
        return self.field1 + self.field2


class Multiplication:
    def __init__(self, field1: int, field2: int):
        self.field1 = field1
        self.field2 = field2

    def get_result(self):
        return self.field1 * self.field2


class Subtraction:
    def __init__(self, field1: int, field2: int):
        self.field1 = field1
        self.field2 = field2

    def get_result(self):
        return self.field1 - self.field2


class Facade:
    @staticmethod
    def make_addition(*args) -&gt; Addition:
        return Addition(*args)

    @staticmethod
    def make_multiplication(*args) -&gt; Multiplication:
        return Multiplication(*args)

    @staticmethod
    def make_subtraction(*args) -&gt; Subtraction:
        return Subtraction(*args)


if __name__ == &quot;__main__&quot;:
    addition_obj = Facade.make_addition(5, 5)
    multiplication_obj = Facade.make_multiplication(5, 2)
    subtraction_obj = Facade.make_subtraction(15, 5)

    print(addition_obj.get_result())
    print(multiplication_obj.get_result())
    print(subtraction_obj.get_result())
</code></pre>
<p>I tried looking it up in the internet but I'm too novice to understand at all.</p>
",https://stackoverflow.com/questions/74223369/unit-testing-a-facade-design-pattern,"['python', 'unit-testing', 'facade']",55,False,0,0
mock createWriteStream jest unit testing,"<p>how to make jest unit testing this file.ts and how to mock createWriteStream</p>
<pre><code>
import { join } from 'path';
import { createWriteStream } from 'fs';
import { v4 as uuidV4 } from 'uuid';

export async function saveUpload(file: any): Promise&lt;string&gt; {
  try {
    const filePath = join(
      __dirname,
      `../../src/uploads/${uuidV4()}-${file.filename}`
    );

    await file.createReadStream().pipe(createWriteStream(filePath));

    return filePath;
  } catch (error) {
    throw error;
  }
}
</code></pre>
",https://stackoverflow.com/questions/74384968/mock-createwritestream-jest-unit-testing,"['javascript', 'typescript', 'unit-testing', 'next.js', 'jestjs']",38,False,0,0
How to write unit test for a builder design pattern?,"<p>I am using xunit for my unit testing and I am new to unit testing. I have a builder class like below,</p>
<pre><code>public class UserBuilder
{
    private User _user = new User();

    public UserBuilder UserBuilder(IDataBase db) //IDatabase is available in a different Nuget package which I don't have source code access
    {
        this._user.db = db;
    }
    
    public UserBuilder SetName(string name)
    {
        this._user.name = name.ToLower();
    }

    public UserBuilder SetRole(string role)
    {
        this._user.role = role.ToUpper();
    }

   public void Validate()
   {
       if (this._user.name == null)
           throw  new InvalidDataException();
       if (this._user.db.contains(this._user.name)
           throw new InvalidDataException();
       ......
   }

   public User Build()
   {
      this.validate();
      this._user.db.persist();
      return this._user;
}
</code></pre>
<p>I would like to unit test the <code>Build()</code>, <code>Validate()</code> and <code>SetName()</code> but I don't have DB details with me and hence, not sure how to override <code>contains</code> and <code>persist</code> steps.</p>
<pre><code>public class UserBuilderTest
{
    [Fact]
    public void Task_SetName_John()
    {
        // Arrange
        // How to Mock the IDatabase?
        var builder = new UserBuilder(FakeDatabase);

        // Act
        var actual = builder.Validate();

        // Assert
        Assert.Throws&lt;InvalidDataException&gt;(action);
    }   
}
</code></pre>
<p>Moreover, how can I check if the name is lower case after calling SetName() from the private _user field?</p>
<pre><code>public class UserBuilderTest
{
    [Fact]
    public void Task_SetName_John()
    {
        // Arrange
        // How to Mock the IDatabase?
        var builder = new UserBuilder(FakeDatabase);
        var expected = 'john&quot;;

        // Act
        var actual = builder.SetName(&quot;John&quot;);

        // Assert
        Assert.Equals(expected, actual);
    }   
}
</code></pre>
",https://stackoverflow.com/questions/73502055/how-to-write-unit-test-for-a-builder-design-pattern,"['c#', 'unit-testing', 'xunit']",432,True,0,1
Mocked interface doesn&#39;t mock,"<p>I met such a method in one project, and the similar and brief logic is shown as follows</p>
<pre class=""lang-cs prettyprint-override""><code>public void BookAClass()
{
    _eventPublisher.Publish(new BookReadyEvent());
    //Using static class Reader to
    //read a configured Storage Place
    //to retrieve an ExamResultFile object
    var examResultFile = Reader.ReadFile(&quot;xxxx&quot;);
    var examResultLevel = _analyzer.AnalyseExameFile(examResultFile);

    if(examResultLevel == ExamResultEnum.Pass)
    {
        _eventPublisher.Publish(new BookCancelEvent());
    }
    else//examResultLevel == ExamResultEnum.Failed
    {
        _eventPublisher.Publish(new BookStartingEvent());
        //TODO
    }
}
</code></pre>
<p>And I tried to implement unit testing for two conditions: Pass and Failed. Regarding the Pass condition</p>
<pre class=""lang-cs prettyprint-override""><code>[TestMethod()]
public void BookAClass_Pass_ExecuteAll()
{
    var analyzerService = new Mock&lt;AnalyzerService&gt;();
    analyzerService.Setup(analyzer =&gt;
        analyzer.AnalyseExameFile(new ExamResultFile()))
        .Returns(ExamResultEnum.Pass);

    var student = new Student(analyzerService.Object);
    student.BookAClass();
}
</code></pre>
<p>Without a doubt, the unit testing failed, because <code>AnalyseExameFile</code> will accept an object from the response of <code>Reader.ReadFile(&quot;xxxx&quot;)</code>, rather than my fake data, which causes the examResultLevel to be null every time. As a result, the Pass condition will never be triggered.</p>
<p>I knew it would be better if consider the <code>examResultFile</code> as an input parameter, other than a returned object from the method invocated in the <code>BookAClass</code>. But the real scenario is much more complex, so I cannot refactor it now.</p>
<p>I wonder if there is any solution to implement unit testing for this condition?</p>
",https://stackoverflow.com/questions/72184552/mocked-interface-doesnt-mock,"['c#', '.net', 'unit-testing', 'moq', 'mstest']",293,True,1,2
Mocha/Chai testing middleware header,"<p>I have been trying to learn Mocha/Chai unit testing libraries, and have been following NodeJS course by Maximillian on Udemy.</p>
<p>Got stuck on testing middleware based on this course.</p>
<p>My question is what is the proper way to use Mocha/Chai for unit testing middleware errors?</p>
<p>You can see my code below.</p>
<p>Auth Middleware:</p>
<pre><code>const jwt = require(&quot;jsonwebtoken&quot;);

const HttpError = require(&quot;../models/http-error&quot;);

module.exports = (req, res, next) =&gt; {
  if(req.method === 'OPTIONS'){
    return next();
  }
  try {

    const authHeader = req.get('Authorization');
    if(!authHeader){
      return next(new HttpError('Not authenticated', 401));
    }

    const token = req.headers.authorization.split(&quot; &quot;)[1]; // Authorization: 'Bearer TOKEN'
    if (!token) {
      return next(new HttpError(&quot;Authentication failed!&quot;, 401));
    }

    const decodedToken = jwt.verify(token, &quot;supersecret_dont_share&quot;);
    req.userData = { userId: decodedToken.userId };
    next();
  } catch (err) {
    return next(new HttpError(&quot;Authentication failed!&quot;, 401));
  }
};
</code></pre>
<p>HttpError:</p>
<pre><code>class HttpError extends Error{
    constructor(message, errorCode){
        super(message);
        this.code = errorCode;
    }
}

module.exports = HttpError;
</code></pre>
<p>authMiddleware.test.js:</p>
<pre><code>const expect = require('chai').expect;
const HttpError = require(&quot;../models/http-error&quot;);

const authMiddleware = require('../middleware/check-auth');

it('It should throw an error if no auth header is present', function(){
    const req = {
        get: function () {
            return null;
        }
    }

    const httpError = new HttpError('Not authenticated', 401);

    expect(authMiddleware.bind(this, req, {}, ()=&gt;{})).to.have.property('message');
});
</code></pre>
<p>Tried with:</p>
<pre><code>expect(authMiddleware.bind(this, req, {}, ()=&gt;{})).to.throw();
expect(authMiddleware.bind(this, req, {}, ()=&gt;{})).to.throw(Error);
expect(authMiddleware.bind(this, req, {}, ()=&gt;{})).to.throw(HttpError);
expect(authMiddleware.bind(this, req, {}, ()=&gt;{})).to.be.instanceOf(HttpError);
expect(authMiddleware.bind(this, req, {}, ()=&gt;{})).to.be.instanceOf(Error);
expect(authMiddleware.bind(this, req, {}, ()=&gt;{})).to.have.property('message');
</code></pre>
<p>All above fail the test.</p>
<p>Any suggestion is appreciated.</p>
",https://stackoverflow.com/questions/71416947/mocha-chai-testing-middleware-header,"['node.js', 'express', 'unit-testing', 'mocha.js', 'chai']",176,False,1,0
How to create a new csv log file every time the current log file size exceeds 10 MB in Automation Anywhere?,"<p><a href=""https://i.stack.imgur.com/HIjkt.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/HIjkt.png"" alt=""The given block of code is only generating two log files and not third one onwards"" /></a></p>
<p>While unit testing its appending to the second file and not creating a third one</p>
",https://stackoverflow.com/questions/71322835/how-to-create-a-new-csv-log-file-every-time-the-current-log-file-size-exceeds-10,"['csv', 'logic', 'logfile', 'automationanywhere']",169,False,0,1
Angular unit testing-global variable in component is updating but not in unit test,"<p>I am not able to component.nominations, its always 0 in my unit testing. but when i log in component it is logging correctly the length. not able to verify updated component variables in unit test.</p>
<p>My component class</p>
<pre><code>@Component({
 selector: 'app-home',
 templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit, AfterViewInit {
nominations = new MatTableDataSource&lt;Nomination&gt;([]);
isLoaded: boolean;
constructor(private nominationService: NominationService) {
}

ngOnInit() {
this.nominationService.GetAllNominationByUser().then(recs =&gt; {
  this.isLoaded = true;
  console.log(&quot;here &quot;+this.nominations.data.length); //it is logging here correctly
  if (recs.length) {
      this.nominations = new MatTableDataSource(recs);
      console.log(&quot;here1 &quot;+this.nominations.data.length); //it is logging here correctly
      this.isLoaded = true;
  }
  console.log(&quot;here after&quot;+this.nominations.data.length); //it is logging here correctly
});
}
}
</code></pre>
<p>my spec file. component.nominations.data.length is  always 0 in my unit testing. but when i log in component it is logging correctly the length. not able to verify updated component variables in unit test.</p>
<pre><code>describe('HomeComponent', () =&gt; {
let component: HomeComponent;
let fixture: ComponentFixture&lt;HomeComponent&gt;;
let nominationDbServiceMock: any;
const settings: IEnvironmentSettings = null;

beforeEach(waitForAsync(() =&gt; {
    nominationDbServiceMock = jasmine.createSpyObj('NominationService', ['GetAllNominationByUser']);
    nominationDbServiceMock.GetAllNominationByUser.and.returnValue(new Promise((resolve, reject) =&gt; {
        const _reject = false;
        if (_reject) {
          reject(null);
        } else {
          resolve([
            { id: 12345 } as Nomination,
          {  id: 12346} as Nomination
          ]);
        }
      }
      ));
    TestBed.configureTestingModule({
        declarations: [HomeComponent],
        providers: [
            { provide: ENV_SETTINGS, useValue: settings },
            { provide: NominationService, useValue: nominationDbServiceMock },
            FormBuilder]
    }).compileComponents();
}));

beforeEach(() =&gt; {
   
    fixture = TestBed.createComponent(HomeComponent);
    component = fixture.componentInstance;
});
it('should populate tax table on init', () =&gt; { 
    fixture.detectChanges();
    expect(component.nominations.data.length).toBeGreaterThan(0); //here it is always 0
});     
});
</code></pre>
",https://stackoverflow.com/questions/73368563/angular-unit-testing-global-variable-in-component-is-updating-but-not-in-unit-te,"['angular', 'unit-testing', 'jasmin']",315,False,0,0
Dummy Array Value for Unit Testing,"<p>If have this error in unit testing wherein it cant detect the <code>id</code>:</p>
<pre><code>claim.claimReference[claim.claimId[claim.claimants[0].id]]
</code></pre>
<p>Currently, I am trying to put a dummy value for this</p>
<pre><code>claim: {
     claimReference: [{
      claim: {
        claimId: [
          {
            claim: {
              claimants: [{
                id: &quot;CM-0000003&quot;,
              }],
            },
          },
        ],
      },
    }],
  },
</code></pre>
<p>What is my mistake in here? Thank you for your correction.</p>
<p>EDIT: OHH WAIT. I THINK MY QUESTION WAS MISUNDERSTOOD. SORRY.
PLEASE SEE THE IMAGE ATTACHED.</p>
<p><a href=""https://i.stack.imgur.com/HjdS5.png"" rel=""nofollow noreferrer"">ERROR IN UNIT TESTING</a></p>
<p>WHAT I AM TRYING TO DO IS TO HAVE A DUMMY VALUE SO THAT I COULD SATISFY THE <code>claim.claimReference[claim.claimId[claim.claimants[0].id]]</code></p>
",https://stackoverflow.com/questions/70575803/dummy-array-value-for-unit-testing,"['javascript', 'arrays', 'reactjs', 'unit-testing']",69,False,0,1
Nextjs Api unit test - difficult to mock prisma client,"<p>I am stuck since long as it is kind of difficult to mock DB calls in unit testing in Nextjs. I have used @prisma/client for database communication.
I have studied <a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""nofollow noreferrer"">https://www.prisma.io/docs/guides/testing/unit-testing</a> but this the issue is doc have just used simple method and they pass the ctx to it if I do so then the actual api call will not understand what is ctx.user.create is?</p>
<p>Here is my adduser.ts</p>
<pre><code>import type { NextApiRequest, NextApiResponse } from 'next';
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient();


export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    try {
      const user = await prisma.user.create({data: req.body});
      const user = await ctx.prisma.user.create({data: req.body});

      res.status(200).send(user);

      // if I send ctx here then the actual call will not communicate with db
      // const user = await ctx.prisma.user.create({data: req.body});
    } catch (e: unknown) {
      const message = e.message;
        res.status(500).send({ message });
    }
  } else {
    return res.status(404).json({ message: 'Request not found!' });
  }
}

</code></pre>
<p>Now what is the way to mock this prisma.user.create()????
What I have tried I will share but different ways have different issues just checkout how I have tried</p>
<pre><code>//adduser.test.ts
import adduser from &quot;../../pages/api/addUser&quot;;
const { MockContext, Context, createMockContext } = require('../../utils/context')
let mockCtx: MockContext;
let ctx: Context;

describe(&quot;Test auth api&quot;, () =&gt; {
    beforeEach(async () =&gt; {
      mockCtx = createMockContext()
      ctx = mockCtx as unknown as Context
    });

    it(&quot;should return 200 and correct response&quot;, async () =&gt; {
      let req:any = {
        body: {
            id: &quot;7e36e11e-ad4d-4504-9262-e2b95378cf00&quot;,
            first_name: &quot;Temp&quot;,
            last_name: &quot;temp&quot;,
            account_address: &quot;0x5eb128b7f43ee7768e4ddd7476a5c60bdb971111&quot;,
            email: &quot;temp@gmail.com&quot;,
            twitter_handle: &quot;temp_twitter&quot;,
            discord_handle: &quot;temp_discord&quot;
        }
      }

      req.method = &quot;POST&quot;;

      const json = jest.fn();
      const status = jest.fn(()=&gt;{
        return {
            json
        }
      });
      const res = {
        status
      }
      
      // with context
      mockCtx.prisma.user.create.mockResolvedValue(req.body);
      const response = await adduser(req, res, ctx);

      expect(true).toBe(true);
      expect(res.status).toHaveBeenCalledWith(200);
    //   expect(response.body).toHaveProperty(&quot;first_name&quot;);
    });
});
  
</code></pre>
<pre><code>//adduser.test.ts
import http from 'http';
import supertest  from &quot;supertest&quot;;
const { apiResolver } = require('next/dist/server/api-utils');
// const prisma = require('../../client')
import { MockContext, Context, createMockContext } from '../../utils/context'
import adduser from &quot;../../pages/api/addUser&quot;;
import { prismaMock } from '../../singleton';
let mockCtx: MockContext
let ctx: Context

const tempUser = {
    id: &quot;7e36e11e-ad4d-4504-9262-e2b95378cf00&quot;,
    first_name: &quot;Temp&quot;,
    last_name: &quot;temp&quot;,
    account_address: &quot;0x5eb128b7f43ee7768e4ddd7476a5c60bdb971111&quot;,
    email: &quot;temp@gmail.com&quot;,
    twitter_handle: &quot;temp_twitter&quot;,
    discord_handle: &quot;temp_discord&quot;
}

describe(&quot;Test auth api&quot;, () =&gt; {
    let server;

    beforeEach(async () =&gt; {
      const requestHandle = (request, response) =&gt;
        apiResolver(
          request,
          response,
          undefined,
          adduser,
          {},
          true,
        );
      server = http.createServer(requestHandle);
      mockCtx = createMockContext()
      ctx = mockCtx as unknown as Context
    });
    afterEach(() =&gt; {
      server.close();
    });

    it(&quot;should return 200 and correct response&quot;, async () =&gt; {
      // const body = {
      //   reqUser: tempUser,
      //   ctx
      // }
      // without context
      prismaMock.user.create.mockResolvedValue(tempUser)
      
      // with context
      // mockCtx.prisma.user.create.mockResolvedValue(tempUser);

      const response = await supertest(server).post(&quot;/api/adduser&quot;).send(tempUser);

      expect(response.statusCode).toBe(200);
      expect(response.body).toHaveProperty(&quot;first_name&quot;);
    });

});
  
</code></pre>
<p>Kindly guide me for the solution for mocking db calls in unit testing in the nextjs handler/api</p>
",https://stackoverflow.com/questions/72024587/nextjs-api-unit-test-difficult-to-mock-prisma-client,"['unit-testing', 'next.js', 'prisma']",1433,True,0,2
Azure Function: how can I improve the Unit test?,"<p>Azure function based on .Net core 3.1. Triggered when a file is uploaded into the Blob container. Any files uploaded to Azure Blob Storage are compressed, and the database is updated.</p>
<p>Below is my business logic</p>
<pre><code>public partial class FileProcessingServiceFacade : IFileProcessingServiceFacade
{
    public async Task&lt;string&gt; ProcessAsync(Stream myBlob, string name, ILogger log, ExecutionContext context)
    {   
        AppDbContext.FileRecords.Add(new FileRecords { ... });
        AppDbContext.SaveChanges();

        return await Task.FromResult($&quot;success&quot;);
    }
}

public partial class FileProcessingServiceFacade : ServiceBase&lt;FileProcessingServiceFacade&gt;
{
    public FileProcessingServiceFacade(AppDbContext appDbContext, IOptions&lt;AppConfigurator&gt; configurator) 
        : base(appDbContext, configurator) { }
}
</code></pre>
<p>I am using xUnit and MOQ for unit testing and below is my unit test</p>
<pre><code>[Fact]
public void ProcessAsync()
{
    var filename = &quot;fileName.csv&quot;;
    var stream = new MemoryStream(File.ReadAllBytes(filename));
    var log = Mock.Of&lt;ILogger&gt;();
    var executionContext = Mock.Of&lt;ExecutionContext&gt;();

    var options = new DbContextOptionsBuilder&lt;AppDbContext&gt;()
    .UseInMemoryDatabase(databaseName: &quot;Testing&quot;)
    .Options;
    var appDbContext = new AppDbContext(options);
    var appSettings = new AppConfigurator(){ ... };
    IOptions&lt;AppConfigurator&gt; configurator = Options.Create(appSettings);

    var target = new FileProcessingServiceFacade(appDbContext, configurator);
    var actual = target.ProcessAsync(stream, filename, log, executionContext);
    Assert.True(appDbContext.FileRecords.FirstAsync&lt;FileRecords&gt;().Result.FileName.Equals(filename));
    Assert.True(actual.Result.Equals(&quot;success&quot;));
    stream.Dispose();
}
</code></pre>
<p>I am trying to improve the code quality of the unit testing and I would appreciate any suggestions.</p>
",https://stackoverflow.com/questions/72428895/azure-function-how-can-i-improve-the-unit-test,"['unit-testing', 'azure-functions', 'azure-blob-storage', 'xunit.net', 'azure-blob-trigger']",398,True,0,1
&#39;Null&#39; is not a subtype of type &#39;Future&lt;String?&gt;&#39;,"<p>While unit testing by mocking secure storage using mockito this appears. any help?</p>
<pre><code>package:flutter_secure_storage/flutter_secure_storage.dart 82:19  MockFlutterSecureStorage.read
package:some_pack/storage/secure_preferences.dart 37:48           SecureStorage.getToken
test\storage\secure_preferences_test.dart 21:27                   main.&lt;fn&gt;.&lt;fn&gt;
test\storage\secure_preferences_test.dart 17:29                   main.&lt;fn&gt;.&lt;fn&gt;

type 'Null' is not a subtype of type 'Future&lt;String?&gt;'
</code></pre>
<p>Sample code</p>
<pre><code>TestWidgetsFlutterBinding.ensureInitialized();
  MockFlutterSecureStorage mockFlutterSecureStorage =
      MockFlutterSecureStorage();
  SecureStorage secureStorage =
      SecureStorage(flutterSecureStorage: mockFlutterSecureStorage);

  group('token', () {
    test('when getToken()', () async {
      // Given

      // When
      await secureStorage.getToken();

      // Then
      verify(mockFlutterSecureStorage.read(key: &quot;com.xdev.token_key&quot;));
    });
</code></pre>
<p>where</p>
<pre><code>class MockFlutterSecureStorage extends Mock implements FlutterSecureStorage {}
</code></pre>
",https://stackoverflow.com/questions/70938986/null-is-not-a-subtype-of-type-futurestring,"['flutter', 'flutter-test']",245,True,0,1
unit test coroutine nullpointerexception when mocking,"<p>I am unit testing the following class</p>
<pre><code>class LoadTrendingSearchUseCaseImp @Inject constructor(
    private val searchCriteriaProvider: SearchCriteriaProvider,
    private val coroutineDispatcherProvider: CoroutineDispatcherProvider
) : LoadTrendingSearchUseCase {

    override suspend fun execute(): List&lt;String&gt; {
        return withContext(coroutineDispatcherProvider.io()) {
            searchCriteriaProvider.provideTrendingSearch().trendingSearches
        }
    }
}

interface SearchCriteriaProvider {
    suspend fun provideTrendingSearch(): CatalogSearchPage
}

class SearchCriteriaProviderImp() : SearchCritieraProvider {
    override suspend fun provideTrendingSearch(): CatalogSearchPage {
        return withContext(coroutineDispatcherProvider.io()) {
           /* long running task */
        }
    }
}

interface CoroutineDispatcherProvider {
    fun io(): CoroutineDispatcher = Dispatchers.IO

    fun default(): CoroutineDispatcher = Dispatchers.Default

    fun main(): CoroutineDispatcher = Dispatchers.Main

    fun immediate(): CoroutineDispatcher = Dispatchers.Main.immediate

    fun unconfined(): CoroutineDispatcher = Dispatchers.Unconfined
}

class CoroutineDispatcherProviderImp @Inject constructor() : CoroutineDispatcherProvider
</code></pre>
<p>This is my actual test:</p>
<pre><code>class LoadTrendingSearchUseCaseImpTest {
    private val searchCriteriaProvider: SearchCriteriaProvider = mock()
    private val coroutineDispatcherProvider = CoroutineDispatcherProviderImp()
    private lateinit var loadTrendingSearchUseCaseImp: LoadTrendingSearchUseCaseImp

    @Before
    fun setUp() {
        loadTrendingSearchUseCaseImp = LoadTrendingSearchUseCaseImp(
            searchCriteriaProvider,
            coroutineDispatcherProvider
        )
    }

    @Test
    fun `should provide trending searches`() {
        runBlockingTest {
            // Arrange
            // EXCEPTION HERE                whenever(searchCriteriaProvider.provideTrendingSearch().trendingSearches).thenReturn(
                emptyList()
            )

            // Act
            val actualResult = loadTrendingSearchUseCaseImp.execute()

            // Assert
            assertThat(actualResult).isEmpty()
        }
    }
}
</code></pre>
<p>The actual error message:</p>
<pre><code>  java.lang.NullPointerException
    .product_search.usecase.imp.LoadTrendingSearchUseCaseImpTest$should provide trending searches$1.invokeSuspend(LoadTrendingSearchUseCaseImpTest.kt:30)
</code></pre>
",https://stackoverflow.com/questions/71396367/unit-test-coroutine-nullpointerexception-when-mocking,"['unit-testing', 'kotlin', 'mockito', 'kotlin-coroutines']",896,True,0,1
How to mock Google Cloud Storage Client which is passed as an argument o method of a class?,"<p>I'm having a trouble while mocking Google Cloud Storage Client in Python.</p>
<p>I've tried a couple solutions, but none of them seems to be working in my case. This is what I've tried:
<a href=""https://stackoverflow.com/questions/64672497/unit-testing-mock-gcs"">Unit testing Mock GCS</a>
<a href=""https://stackoverflow.com/questions/62803901/python-unittest-mock-google-storage-how-to-achieve-exceptions-notfound-as-side"">Python unittest.mock google storage - how to achieve exceptions.NotFound as side effect</a>
<a href=""https://stackoverflow.com/questions/57808461/how-to-mock-a-google-api-library-with-python-3-7-for-unit-testing"">How to Mock a Google API Library with Python 3.7 for Unit Testing</a>
So basically I have a class for downloading the decoded GCS object.
This is the class that I want to test:</p>
<pre><code>class Extract:

    def __init__(self, storage_client: storage.Client) -&gt; None:
        self.client = storage_client

    @retry.Retry(initial=3.0, maximum=60.0, deadline=240.0)
    def _get_storage_object(self, bucket: str, blob: str) -&gt; bytes:
        bucket_obj = self.client.get_bucket(bucket)
        blob_obj = bucket_obj.blob(blob)
        data = blob_obj.download_as_bytes(timeout=60)
        return data

    def get_decoded_blob(self, bucket: str, blob: str) -&gt; Union[dict, list]:
        raw_blob = self._get_storage_object(bucket=bucket, blob=blob)
        decoded_blob = decode_data(raw_blob)
        return decoded_blob
</code></pre>
<p>And this last version of code for unit testing of the class.</p>
<pre><code>def decode_data(data: bytes) -&gt; List[Dict[str, Any]]:
    decoded_blob = data.decode('utf-8')
    decoded_data = ast.literal_eval(decoded_blob)
    return decoded_data

class TestExtract:

    @pytest.fixture()
    @mock.patch('src.pipeline.extract.storage', spec=True)
    def storage_client(self, mock_storage):
        mock_storage_client = mock_storage.Client.return_value
        mock_bucket = mock.Mock()
        mock_bucket.blob.return_value.download_as_bytes.return_value = 'data'.encode('utf-8')
        mock_storage_client.bucket.return_value = mock_bucket
        return mock_storage_client

    
    def test_storage_client(self, storage_client):
        gcs = extract.Extract(storage_client)
        output = gcs._get_storage_object('bucket', 'blob')
        assert output == b'data'
</code></pre>
<p>The error for the above code is that mock does not return return_value which was assigned in the fixture. Instead, it returns the MagicMock object as below:
AssertionError: assert &lt;MagicMock na...806039010368'&gt; == b'data'</p>
<p>Anyone can help me in this case?</p>
",https://stackoverflow.com/questions/72330754/how-to-mock-google-cloud-storage-client-which-is-passed-as-an-argument-o-method,"['python', 'unit-testing', 'google-cloud-platform']",1427,False,1,0
"Unit Testing, Widget Testing and Integration Testing in a flutter?","<p>What is Unit Testing, Widget Testing and Integration Testing in a flutter? Someone can explain to me?</p>
",https://stackoverflow.com/questions/71377404/unit-testing-widget-testing-and-integration-testing-in-a-flutter,['flutter'],107,False,-2,1
STM32CubeIDE: Googletest executable build with MinGW32 in Docker Container doesn&#39;t work,"<p>this is my last try to solve this problem. I created an STM32 CMake project in STM32CubeIDE (on WIndows 10) built in a Docker container (Ubuntu Kinetic 22.10). The Googletest tests were built using the MinGW32 toolchain.
Now to my problem. I want to launch Googletest executable using STM32CubeIDE's unit testing support tool (like Eclipse). Unfortunately, the tests are not displayed in the Unit Testing Console. After launching the unit testing run configuration I get following error from eclipse.</p>
<pre><code>Unknown error during parsing Google Test module output: Unexpected test module output.
</code></pre>
<p>I have a suspicion that the toolchain used is not entirely correct. And the tool can't parse it. As next, you see the CMakeList.txt of the external googletest project and the toolchain file.</p>
<p>CMakeList.txt of main project</p>
<pre><code>cmake_minimum_required(VERSION 3.15.3)

set(CMAKE_TOOLCHAIN_FILE arm-toolchain.cmake)
project(cmake_Doku)     
set(MCU_MODEL STM32F407xx)  

enable_language(C ASM)
set(CMAKE_C_STANDARD 99)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)

set(STM32CUBEMX_GENERATED_FILES
        
        ${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/main.cpp
        ${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/stm32f4xx_it.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/stm32f4xx_hal_msp.c
        ${CMAKE_CURRENT_SOURCE_DIR}/USB_HOST/App/usb_host.c
        ${CMAKE_CURRENT_SOURCE_DIR}/USB_HOST/Target/usbh_conf.c
        ${CMAKE_CURRENT_SOURCE_DIR}/USB_HOST/Target/usbh_platform.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_hcd.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_usb.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc_ex.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash_ex.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash_ramfunc.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_gpio.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma_ex.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr_ex.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cortex.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_exti.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c_ex.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2s_ex.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_spi.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim_ex.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Core/Src/system_stm32f4xx.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Middlewares/ST/STM32_USB_Host_Library/Core/Src/usbh_core.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Middlewares/ST/STM32_USB_Host_Library/Core/Src/usbh_ctlreq.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Middlewares/ST/STM32_USB_Host_Library/Core/Src/usbh_ioreq.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Middlewares/ST/STM32_USB_Host_Library/Core/Src/usbh_pipes.c
        ${CMAKE_CURRENT_SOURCE_DIR}/Middlewares/ST/STM32_USB_Host_Library/Class/CDC/Src/usbh_cdc.c
        
        ${CMAKE_CURRENT_SOURCE_DIR}/startup_stm32f407xx.s
        )

set(EXECUTABLE ${PROJECT_NAME})

add_executable(${EXECUTABLE} ${STM32CUBEMX_GENERATED_FILES})

target_compile_definitions(${EXECUTABLE} PRIVATE
        -DUSE_HAL_DRIVER
        -D${MCU_MODEL}
        )

target_include_directories(${EXECUTABLE} PRIVATE
        
        ${CMAKE_CURRENT_SOURCE_DIR}/USB_HOST/App
        ${CMAKE_CURRENT_SOURCE_DIR}/USB_HOST/Target
        ${CMAKE_CURRENT_SOURCE_DIR}/Core/Inc
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Inc
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/STM32F4xx_HAL_Driver/Inc/Legacy
        ${CMAKE_CURRENT_SOURCE_DIR}/Middlewares/ST/STM32_USB_Host_Library/Core/Inc
        ${CMAKE_CURRENT_SOURCE_DIR}/Middlewares/ST/STM32_USB_Host_Library/Class/CDC/Inc
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/CMSIS/Device/ST/STM32F4xx/Include
        ${CMAKE_CURRENT_SOURCE_DIR}/Drivers/CMSIS/Include
        )

target_compile_options(${EXECUTABLE} PRIVATE
        -mcpu=cortex-m4         
        -mthumb
        -mfpu=fpv4-sp-d16
        -mfloat-abi=hard

        -fdata-sections
        -ffunction-sections

        -Wall

        $&lt;$&lt;CONFIG:Debug&gt;:-Og&gt;
        )

target_link_options(${EXECUTABLE} PRIVATE
        -T${CMAKE_SOURCE_DIR}/STM32F407VGTx_FLASH.ld
        -mcpu=cortex-m4
        -mthumb
        -mfpu=fpv4-sp-d16
        -mfloat-abi=hard
        -specs=nano.specs
        -lc
        -lm
        -lnosys
        -Wl,-Map=${PROJECT_NAME}.map,--cref
        -Wl,--gc-sections
        )

# Print executable size
add_custom_command(TARGET ${EXECUTABLE}
        POST_BUILD
        COMMAND arm-none-eabi-size $&lt;TARGET_FILE:${EXECUTABLE}&gt;)

# Create hex file
add_custom_command(TARGET ${EXECUTABLE}
        POST_BUILD
        COMMAND arm-none-eabi-objcopy -O ihex $&lt;TARGET_FILE:${EXECUTABLE}&gt; ${PROJECT_NAME}.hex
        COMMAND arm-none-eabi-objcopy -O binary $&lt;TARGET_FILE:${EXECUTABLE}&gt; ${PROJECT_NAME}.bin)

include(ExternalProject)
        ExternalProject_Add(unitTests
            PREFIX gtest
            SOURCE_DIR &quot;${CMAKE_CURRENT_SOURCE_DIR}/unitTests/&quot;
            BINARY_DIR &quot;${CMAKE_BINARY_DIR}/unitTests&quot;
            CMAKE_CACHE_ARGS
                -DCMAKE_POSITION_INDEPENDENT_CODE:BOOL=TRUE
                -DCMAKE_INSTALL_PREFIX:PATH=${CMAKE_CURRENT_BINARY_DIR}/Debug/gtest
                -DCMAKE_TOOLCHAIN_FILE:PATH=gtest-toolchain.cmake
        )
</code></pre>
<p>CMakeList.txt of googletest folder</p>
<pre><code>project(unitTests)

set(CMAKE_TOOLCHAIN_FILE gtest-toolchain.cmake)

Include(FetchContent)
FetchContent_Declare(
    googletest
    GIT_REPOSITORY https://github.com/google/googletest.git
    GIT_TAG release-1.11.0 # release-1.11.0
)

set(gtest_force_shared_crt ON CACHE BOOL &quot;&quot; FORCE)
set(BUILD_GMOCK OFF CACHE BOOL &quot;&quot; FORCE)
set(BUILD_GTEST ON CACHE BOOL &quot;&quot; FORCE)

FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
  FetchContent_Populate(googletest)
  add_subdirectory(${googletest_SOURCE_DIR} ${googletest_BINARY_DIR})
endif()
FetchContent_MakeAvailable(googletest)

set(TEST_FILES      
    unitGTests.cpp
)

add_executable(unitTests ${TEST_FILES})

target_link_libraries(unitTests PRIVATE
  GTest::gtest_main
)

include(GoogleTest)

gtest_add_tests(
  TARGET        unitTests
  TEST_PREFIX   GTest
  TEST_LIST     unitTestsList
  )

include_directories(
       ${GTEST_INCLUDE_DIRS}
       ${CMAKE_CURRENT_SOURCE_DIR}/../Core/Inc
)
</code></pre>
<p>gtest-toolchain.cmake</p>
<pre><code>#the name of the target operating system
set(CMAKE_SYSTEM_NAME Windows)
set(TOOLCHAIN_PREFIX x86_64-w64-mingw32)

#SET(CMAKE_CXX_FLAGS &quot;-pthread&quot;)

# cross compilers to use for C, C++ and Fortran
set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc)
set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++)

# target environment on the build host system
set(CMAKE_FIND_ROOT_PATH /usr/${TOOLCHAIN_PREFIX})

# modify default behavior of FIND_XXX() commands
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
</code></pre>
<p>I hope, anybody can help me. Thanks.</p>
",https://stackoverflow.com/questions/73743188/stm32cubeide-googletest-executable-build-with-mingw32-in-docker-container-doesn,"['docker', 'cmake', 'containers', 'googletest', 'stm32cubeide']",150,False,0,0
Test Type-Graphql with mongoose,"<p>I am pretty new in unit testing, I want to test my application that is written in node, the technologies I use are express.js, type-graphql, and type-goose, I searched a lot on the web to find some articles to help me about how to do unit testing for a resolver that is written in type-graphql or how to do unit testing for a schema that is written in type-goose but unfortunately, I couldn't find any, now please help me solve the problem and at least pass me some useful links</p>
<p>this is the input:</p>
<pre><code>import { Field, InputType } from 'type-graphql'

@InputType()
export class AdminLoginInput {
  @Field(() =&gt; String)
  email: string

  @Field(() =&gt; String)
  password: string
}
</code></pre>
<p>This is the Resolver:</p>
<pre><code>import { Arg, Ctx, Mutation, Query, Resolver } from 'type-graphql'
import { AdminLoginInput } from '../../Inputs/Admins/admin.input'
import { Admin } from '../../schema/Admins/admin.schema'
import AdminService from '../../service/Admin/admin.service'
import { IContext } from '../../../interface/context'

@Resolver()
export default class AdminResolver {
  constructor(private adminService: AdminService) {
    this.adminService = new AdminService()
  }

  @Mutation(() =&gt; String)
  loginAdmin(@Arg('input') input: AdminLoginInput, @Ctx() context: IContext) {
    return this.adminService.loginAdmin(input, context)
  }

  @Query(() =&gt; Admin, { nullable: true })
  meAdmin(@Ctx() context: IContext) {
    return context.admin
  }
}
</code></pre>
<p>this is the schema</p>
<pre><code>import { ObjectType, Field } from 'type-graphql'
import { getModelForClass, prop, pre, index } from '@typegoose/typegoose'
import bcrypt from 'bcrypt'

@pre&lt;Admin&gt;('save', async function () {
  if (!this.isModified('password')) {
    return
  }

  const salt = await bcrypt.genSalt(10)
  const hash = await bcrypt.hashSync(this.password, salt)

  this.password = hash
})
@ObjectType()
export class Admin {
  @Field(() =&gt; String, { nullable: true })
  _id: string

  @Field(() =&gt; String)
  @prop()
  firstname: string

  // @Field(() =&gt; String)
  // @prop()
  // name: string

  @Field(() =&gt; String)
  @prop({ unique: true })
  email: string

  @Field(() =&gt; String, { nullable: true })
  @prop()
  gender: string

  @Field(() =&gt; String, { nullable: true })
  @prop()
  language: string

  @Field(() =&gt; String, { nullable: true })
  @prop({ default: Date.now() })
  created: string

  @Field(() =&gt; String, { nullable: true })
  @prop()
  lastlogin: string

  @Field(() =&gt; String, { nullable: true })
  @prop()
  updated: string

  @prop()
  password: string

  @Field(() =&gt; [String], { nullable: true })
  @prop()
  messages: [string]
}

export const AdminModel = getModelForClass&lt;typeof Admin&gt;(Admin)
</code></pre>
<p>This is the service:</p>
<pre><code>import { ApolloError } from 'apollo-server-express'
import bcrypt from 'bcrypt'
import { AdminLoginInput } from '../../Inputs/Admins/admin.input'
import { AdminModel } from '../../schema/Admins/admin.schema'
import { IContext } from '../../../interface/context'
import { signJwt, verifyJwt } from '../../../../scripts/jwt'
import nodemailer from 'nodemailer'

class AdminService {
  async loginAdmin(input: AdminLoginInput, context: IContext) {
    try {
      const error = 'Invalid Email or Password'
      const admin: any = await AdminModel.findOne({ email: input.email }).lean()

      if (!admin) {
        throw new ApolloError(error)
      }

      const passwordIsValid = await bcrypt.compare(
        input.password,
        admin.password,
      )

      if (!passwordIsValid) {
        throw new ApolloError(error)
      }

      const token = signJwt({ userId: admin._id.toString() })

      context.res.cookie('accessToken', token, {
        // domain: process.env.CLIENT_URL,
        // path: '/',
        sameSite: 'none',
        httpOnly: true,
        secure: true,
        // process.env.NODE_ENV === 'production' ||
        // process.env.NODE_ENV === 'staging',
        maxAge: 3.154e10,
      })

      return token
    } catch (error) {
      console.log(error)
    }
  }
}
</code></pre>
<p>export default AdminService</p>
<p>a full image and its folder structure
<a href=""https://i.stack.imgur.com/Y2112.png"" rel=""nofollow noreferrer"">a complete image that contains files and folder structure</a></p>
",https://stackoverflow.com/questions/72907604/test-type-graphql-with-mongoose,"['node.js', 'graphql', 'ts-jest', 'typegraphql', 'typegoose']",92,False,0,0
how do you mock out node_modules package in jest unit test?,"<p>I have an Nx workspace with a library it in that has a unit test that needs to mock a node_module package.</p>
<p>One example is unit testing our interface with Stripe. I have built a mock implementation of the stripe-js that I have npm added to my project.</p>
<p>Without Nx, I would put the stripe-js.ts mock file in the <strong>mock</strong> folder that is next to the top level src file.</p>
<p>I have tried putting this <strong>mock</strong> folder beside the workspace folder, but it isn't being picked up by jest.</p>
<p>Where should this <strong>mock</strong> folder be placed when unit testing in a library?</p>
<pre><code>myorg/
 ├── __mocks__/
 |    ├── stripe-js.js
 ├── apps/
 |    ├── myapp
 ├── libs/
 |    └── lib1
 |        ├── test.spec.js
 ├── node_modules
</code></pre>
<p>Without Nx, it should be placed in the diagram above, but I am not sure where it should be placed when unit testing lib1.</p>
",https://stackoverflow.com/questions/72297211/how-do-you-mock-out-node-modules-package-in-jest-unit-test,"['unit-testing', 'jestjs', 'nrwl-nx']",520,True,0,1
ASP.Net Core 6 SignInManager PasswordSignInAsync throws provider null exception,"<p><code>SignInManager</code> <code>PasswordwordSignInAsync</code> throws <code>&quot;Value cannot be null. (Parameter 'provider')&quot;</code> exception when I am unit-testing MVC Razor with ASP.Net Core 6 Identity.</p>
<pre><code>var httpContextMock = new Mock&lt;HttpContext&gt;();
var httpContextAccessorMock = new Mock&lt;IHttpContextAccessor&gt;();
httpContextAccessorMock.Setup(x =&gt; x.HttpContext).Returns(httpContextMock.Object);
var httpContextMockObject = httpContextAccessorMock.Object;
IServiceCollection services = new ServiceCollection();
services.AddScoped(x =&gt; httpContextAccessorMock);
services.AddScoped(x =&gt; httpContextMockObject);
services.AddAuthentication();
services.AddScoped&lt;SignInManager&lt;MyUser&gt;&gt;();
</code></pre>
<p>What do I miss?</p>
",https://stackoverflow.com/questions/74002344/asp-net-core-6-signinmanager-passwordsigninasync-throws-provider-null-exception,"['asp.net-core', 'dependency-injection', 'asp.net-identity', 'razor-pages']",61,False,0,0
Moq returns null and BadRequestObjectResult,"<p>I'm new to unit testing, and trying to mock <code>postContinent</code>. But gives <code>null</code> and <code>BadRequestObjectResult</code>.</p>
<h3>ContinentControllerTests</h3>
<pre class=""lang-cs prettyprint-override""><code> public class ContinentControllerTests {
 // RepoMocks
 private readonly Mock&lt;IContinentRepository&gt; _continentRepoMock = new Mock&lt;IContinentRepository&gt;();
 private readonly Mock&lt;ICountryRepository&gt; _countryRepoMock = new Mock&lt;ICountryRepository&gt;();
 private readonly Mock&lt;ICityRepository&gt; _cityRepoMock = new Mock&lt;ICityRepository&gt;();

 // Controller
 private readonly ContinentController _continentController;

     public ContinentControllerTests() {
     _continentServiceMock = new ContinentService(_continentRepoMock.Object);
     _continentController = new ContinentController(new ContinentService(_continentRepoMock.Object), new CountryService(_countryRepoMock.Object), new CityService(_cityRepoMock.Object));
     }
     [Fact]
     public void PostContinent_ValidInput_ReturnsCreateAtAction() {
     // Arrange
     _continentRepoMock
        .Setup(repo =&gt; repo.HeeftContinent(&quot;Test&quot;))
        .Returns(false);
    _continentRepoMock
       .Setup(repo =&gt; repo.BestaatContinent(new Continent(&quot;Test&quot;, new List&lt;Country&gt;())))
       .Returns(false);
     _continentRepoMock
       .Setup(repo =&gt; repo.VoegContinentToe(new Continent(&quot;Test&quot;, new List&lt;Country&gt;())))
       .Returns(new Continent(1, &quot;Test&quot;, new List&lt;Country&gt;()));
     // Act
     var response = _continentController.PostContinent(new ContinentInputDTO { Name = &quot;Test&quot; });

     // Assert
     Assert.IsType&lt;CreatedAtActionResult&gt;(response.Result);
     }
 }
</code></pre>
<h3>ContinentController</h3>
<pre class=""lang-cs prettyprint-override""><code> public class ContinentController : ControllerBase {
     private string _hostURL = $&quot;http://localhost:5000/api/continent&quot;;
     private string _riverURL = $&quot;http://localhost:5000/api/river&quot;;

     private ContinentService _continentService;
     private CountryService _countryService;
     private CityService _cityService;

     public ContinentController(ContinentService continentService, CountryService countryService, CityService cityService) {
         _continentService = continentService;
         _countryService = countryService;
         _cityService = cityService;
     }

     [HttpPost]
     public ActionResult&lt;ContinentOutputDTO&gt; PostContinent([FromBody] ContinentInputDTO continentDto) {
         try {
             if (_continentService.HeeftContinent(continentDto.Name)) { return BadRequest(&quot;Continent naam moet unique zijn!&quot;); }
             var mappedContinent = MapToDomain.MapToContinentDomain(continentDto);
             Continent continent = _continentService.VoegContinentToe(mappedContinent);
             return CreatedAtAction(nameof(GetContinent), new { continentId = continent.Id },
             MapFromDomain.MapFromContinentDomain(_hostURL, continent));
         }
         catch (Exception ex) { return BadRequest(ex.Message); }
     }
 }
</code></pre>
<h3>ContinentService</h3>
<pre class=""lang-cs prettyprint-override""><code>public class ContinentService {
     private readonly IContinentRepository _repo;
     public ContinentService(IContinentRepository repo) { _repo = repo;}

      public Continent VoegContinentToe(Continent c) {
         if (c == null) throw new ContinentServiceException(&quot;VoegContinentToe : continent is null&quot;);
         if (_repo.BestaatContinent(c)) throw new ContinentServiceException(&quot;VoegContinentToe : continent bestaat reeds&quot;);
         try {return _repo.VoegContinentToe(c);}
         catch (Exception ex) { throw new ContinentServiceException(&quot;VoegContinentToe: &quot;, ex);}
    }
}
</code></pre>
<p>Error:</p>
<blockquote>
<p>Message: 
Assert.IsType() Failure<br />
Expected: <code>Microsoft.AspNetCore.Mvc.CreatedAtActionResult</code><br />
Actual:  <code>Microsoft.AspNetCore.Mvc.BadRequestObjectResult</code></p>
</blockquote>
",https://stackoverflow.com/questions/70613855/moq-returns-null-and-badrequestobjectresult,"['c#', 'asp.net', 'api', 'unit-testing', 'moq']",581,True,2,1
Set Up Development Environment for Unit Testing C,"<p>I'm new to unit testing and have mostly programmed using IDEs, therefore I haven't created and/or modified makefiles before.</p>
<p>Now that I'm exploring Unit Testing and TDD in general; I'm not sure how to set up the development environment so that my unit tests automatically run on every build.</p>
<p>Please help. A general procedure to achieve this would do wonders.</p>
<p>I have not tried anything yet as I'm not very familiar with modifying C Make files.</p>
",https://stackoverflow.com/questions/74587051/set-up-development-environment-for-unit-testing-c,"['c', 'unit-testing', 'cmake', 'ide', 'development-environment']",154,True,0,1
Module &#39;&quot;@angular/router/testing&quot;&#39; has no exported member &#39;SpyNgModuleFactoryLoader&#39;,"<p>I am facing this error in angular unit testing.How can I import SpyNgModuleFactoryLoader in Jasmine-Karma angular unit testing?</p>
",https://stackoverflow.com/questions/74124148/module-angular-router-testing-has-no-exported-member-spyngmodulefactoryloa,"['karma-jasmine', 'modulenotfounderror', 'angular-unit-test']",96,False,0,0
How to authenticate a user in django unit test when rest framework&#39;s DEFAULT_AUTHENTICATION_CLASSES is &#39;JWTStatelessUserAuthentication&#39;?,"<p>I had a Django project with the following settings:</p>
<pre><code>'DEFAULT_AUTHENTICATION_CLASSES': [
    'rest_framework.authentication.TokenAuthentication',
]
</code></pre>
<p>and in the unit testing phase, I used to assign a Token to an existing user to authenticate the user:</p>
<pre><code>def setUp(self):
    self.user = User.objects.create(username='u1')
    self.client = APIClient()
    token = Token.objects.create(user=self.user)
    self.client.credentials(HTTP_AUTHORIZATION=&quot;Token &quot; + token.key)
</code></pre>
<p>but now, in my current project, I don't authenticate users, instead, I use these settings:</p>
<pre><code>'DEFAULT_AUTHENTICATION_CLASSES': [
    'rest_framework_simplejwt.authentication.JWTStatelessUserAuthentication',
],
SIMPLE_JWT = {
    'ALGORITHM': '...',
    'SIGNING_KEY': '...',
}
</code></pre>
<p>and user authentication stuff is in another project and authentication tokens have an expiration time!
How can I authenticate a user in my unit testing?! Is there any solution to this issue?</p>
",https://stackoverflow.com/questions/74078150/how-to-authenticate-a-user-in-django-unit-test-when-rest-frameworks-default-aut,"['django', 'unit-testing', 'django-rest-framework', 'jwt']",126,False,0,0
Babel-jest compiles preact and reports an error,"<p>I use typescript+jest+preact for unit testing,
but encountered a problem</p>
<p><a href=""https://i.stack.imgur.com/ADWYD.png"" rel=""nofollow noreferrer"">error msg</a></p>
<p><a href=""https://i.stack.imgur.com/hHusO.png"" rel=""nofollow noreferrer"">jest.config.ts config1</a></p>
<p><a href=""https://i.stack.imgur.com/Ome4x.png"" rel=""nofollow noreferrer"">jest.config.ts config2</a></p>
<p><a href=""https://i.stack.imgur.com/bdZJr.png"" rel=""nofollow noreferrer"">.babelrc config</a></p>
",https://stackoverflow.com/questions/72950084/babel-jest-compiles-preact-and-reports-an-error,"['ts-jest', 'babel-jest']",82,False,0,0
Coil unit testing - how to do this?,"<p>Is it possible to mock coil network level when unit testing? With <code>MockWebServer</code>? Or test it somehow else? I can't find information on the Internet about it.</p>
",https://stackoverflow.com/questions/72920606/coil-unit-testing-how-to-do-this,"['android', 'unit-testing', 'coil']",184,True,5,1
"Unit Test For Infrastructure Layer CQRS with Moq and xUnit, How to write tests using In-Memory Db","<p>I am new to unit testing and I have been using the CQRS mediatR pattern. I want to add unit tests for <code>GetAllAsync()</code> and <code>GetByGameNameAsync()</code> methods using Moq and xUnit. The code runs fine as intended but I need unit testing for it.</p>
<p>There is no connected database, I need to be able to write tests that will check both <code>GetAllAsync()</code> and <code>GetByGameNameAsync()</code> methods to see if it is working as intended.</p>
<p>How can i use inmemoryDb to write tests for the two methods?</p>
<pre><code>public class IGenericRepository&lt;TContext, TEntity&gt; : IGenericRepository&lt;TEntity&gt;

 where TContext: DbContext
where TEntity: class
{
private readonly TContext _gameDbContext;

private readonly DbSet&lt;TEntity&gt; _gameDbSet;

public IGenericRepository(TContext dbContext)
{
_gameDbContext = dbContext;
_gameDbSet = dbContext.Set&lt;TEntity&gt;();
}

public async Task&lt;IReadOnlyList&lt;TEntity&gt;&gt; GetAllAsync()
{
var getBack = await _gameDbSet.ToListAsync();
return getBack;
}
</code></pre>
<p>GameDbContext.cs</p>
<pre><code>public class GamesDbContext : DbContext
{
public GameDbContext(DbContextOptions&lt;GamesDbContext&gt; options) :base(options)
{
}
public DbSet&lt;GamesEntity&gt; GamesEntity =&gt; Set&lt;GamesEntity&gt;():
</code></pre>
<p>GamesEntity.cs</p>
<pre><code>public int Id {get; set;}
public string gameName {get; set;} =null!;
public string gameDescription {get; set;}=null!;
</code></pre>
<p>GamesRepository.cs</p>
<pre><code>public class GamesRepository: GenericRepository&lt;GamesDbContext, GamesEntity&gt;, IGamesRepository
{
private readonly GamesDbContext _gamesDbContext;
private readomly GamesDbSet&lt;GamesEntity&gt; _gamesDbSet;

public GamesRepository( GamesDbContext dbContext) : base(dbContext)
{
_gamesDbContext - dbContext;
_gamesDbSet = dbContext.Set&lt;GamesEntity&gt;();
}

public async Task&lt;ReadOnlyList&lt;GamesEntity&gt;&gt; GetByGameNameAsync(string gameName)
{
var gameEntities = await _gamesDbContext.GamesEntity.
                     Where(v =&gt; v.Entity == gameName)
                      .ToListAsync();

return gameEntities;
}
</code></pre>
",https://stackoverflow.com/questions/74101004/unit-test-for-infrastructure-layer-cqrs-with-moq-and-xunit-how-to-write-tests-u,"['c#', 'entity-framework-core', 'moq', 'xunit', 'cqrs']",331,False,0,1
How test a ViewModel function that launch a viewModelScope coroutine? Android Kotlin,"<p>I´m trying to figure out the simplest way to test this kind on function members, I´ve seen more complex cases like <a href=""https://stackoverflow.com/questions/55765190/coroutines-unit-testing-viewmodelscope-launch-methods"">Coroutines - unit testing viewModelScope.launch methods</a> but didn´t solved</p>
<blockquote>
<p>ListScreenViewModel.kt</p>
</blockquote>
<pre><code>@HiltViewModel
class ListScreenViewModel @Inject constructor(): ViewModel() {

    private var _itemsNumber = mutableStateOf(0)

    private var _testList = mutableStateOf(listOf&lt;String&gt;())
    val testList = _testList

    fun addItem() {
        viewModelScope.launch {
            _itemsNumber.value++
            _testList.value += (
                &quot;Item ${_itemsNumber.value}&quot;
                )
        }
    }
}
</code></pre>
<blockquote>
<p>ListScreenViewModelTest.kt</p>
</blockquote>
<pre><code>class ListScreenViewModelTest{

    private lateinit var viewModel: ListScreenViewModel

    @Before
    fun setup(){
        viewModel = ListScreenViewModel()
    }

    @Test
    fun `add an item to the list of items`(){
        val numberOfItems = viewModel.testList.value.size
        viewModel.addItem()
        assert(viewModel.testList.value.size == numberOfItems+1)
    }
}
</code></pre>
<blockquote>
<p>Error message</p>
</blockquote>
<pre><code>Exception in thread &quot;Test worker&quot; java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used

</code></pre>
",https://stackoverflow.com/questions/71807957/how-test-a-viewmodel-function-that-launch-a-viewmodelscope-coroutine-android-ko,"['android', 'unit-testing', 'kotlin', 'viewmodel', 'kotlin-coroutines']",9615,True,14,1
How to create nsubsitute for sitecore hyperlink field and override ToLookupField() method,"<p>I am trying to write unit test cases using X-Unit and Nsubstitute. While creating mock items with fields I created Synthesis TestHyperlinkField in unit tests.</p>
<p>Below is the sample code to Unit Test:</p>
<pre><code>public string GetLinkFieldUrl(IHyperlinkField myLink)
{
var internalLinkTargetUrl = myLink.ToLinkField()
return linkToReturn = LinkManager.GetItemUrl(internalLinkTargetUrl.TargetItem, 
urlBuilderOptions);
}
</code></pre>
<p>During unit testing, created TestHyperlinkField with mock data and I am facing an error while executing above method at myLink.ToLinkField() with below error &quot;Test date fields cannot return Sitecore item objects&quot;</p>
<p>Please let me on how to process unit testing without changing actual method.</p>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/72632086/how-to-create-nsubsitute-for-sitecore-hyperlink-field-and-override-tolookupfield,"['unit-testing', 'sitecore', 'xunit', 'nsubstitute', 'synthesis']",75,False,0,0
How to prepare or mock JsonParser to test custom StdDeserializer,"<p>I have custom <code>StdDeserializer&lt;Date&gt;</code>, how can i unit test the overridden <code>deserialize</code> method here?</p>
<p>or how can i prepare or mock <code>JsonParser</code> here for unit testing desterilize method?</p>
<pre><code>public class StringToDateDeserializer extends StdDeserializer&lt;Date&gt; {

    protected StdDateFormat df = new StdDateFormat();

    public StringToDateDeserializer() {
        this(null);
    }

    protected StringToDateDeserializer(Class&lt;?&gt; T) {
        super(T);
    }

    @Override
    public Date deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
        String dateStr = jsonParser.getText();
        if (StringUtils.isEmpty(dateStr)) {
            return null;
        }
        try {
            return df.parse(dateStr);
        } catch (ParseException e) {
            throw new MyCustomException(&quot;Invalid date passed, ISO 8601 is expected&quot;);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/73053093/how-to-prepare-or-mock-jsonparser-to-test-custom-stddeserializer,"['java', 'junit', 'jackson', 'json-deserialization', 'jackson-databind']",385,True,3,1
Next.js Cannot use import statement outside a module in third party library,"<p><strong>Summary</strong></p>
<p>I'm using Next.js to create both API and and Frontend app. Frontend uses react. To unit testing I'm using <code>next/jest</code> preset and jest as an unit testing library. I'm using <code>@tenstack/react-query</code> to state management and when I want to test page, it throws an error. In tests where I'm using <code>jsdom</code> environment I add</p>
<pre class=""lang-js prettyprint-override""><code>/**
 * @jest-environment jsdom
 */
</code></pre>
<p>in tests to API I'm using <code>babel-jest</code> that is default and no need anything</p>
<p><strong>error that throws</strong></p>
<pre class=""lang-bash prettyprint-override""><code>
    /path/to/project/node_modules/@tanstack/react-query/src/QueryClientProvider.tsx:1
    ({&quot;Object.&lt;anonymous&gt;&quot;:function(module,exports,require,__dirname,__filename,jest){import * as React from 'react'
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module
</code></pre>
<p>The error appers in test where I want to render page that uses <code>react-query</code></p>
<p><strong>jest.config.js</strong></p>
<pre class=""lang-js prettyprint-override""><code>// jest.config.js
const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './'
});

const customJestConfig = {
  moduleDirectories: ['node_modules', '&lt;rootDir&gt;/'],
  transform: {
    '^.+\\.[t|j]sx?$': 'ts-jest'
  }
};

module.exports = createJestConfig(customJestConfig);
</code></pre>
<p><strong>.babelrc</strong></p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;presets&quot;: [&quot;next/babel&quot;,&quot;@babel/preset-env&quot;, &quot;@babel/preset-typescript&quot;],
  &quot;plugins&quot;: [
    &quot;babel-plugin-transform-typescript-metadata&quot;,
    [&quot;@babel/plugin-proposal-decorators&quot;, { &quot;legacy&quot;: true }],
    &quot;babel-plugin-parameter-decorator&quot;
  ]
}
</code></pre>
<p>I've tried <a href=""https://stackoverflow.com/questions/70916761/next-js-and-jest-syntaxerror-cannot-use-import-statement-outside-a-module"">these answers</a> but unfortunatelly it didn't help.</p>
",https://stackoverflow.com/questions/73353953/next-js-cannot-use-import-statement-outside-a-module-in-third-party-library,"['javascript', 'reactjs', 'next.js', 'jestjs', 'ts-jest']",338,True,2,1
JUnit CRUD: Why assuming that you use findById instead of existsById?,"<p>I took the following code from <a href=""https://codefiction.net/unit-testing-crud-endpoints-of-a-spring-boot-java-web-service-api"" rel=""nofollow noreferrer"">https://codefiction.net/unit-testing-crud-endpoints-of-a-spring-boot-java-web-service-api</a></p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class DeleteUserServiceTest {

    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private DeleteUserService deleteUserService;

    @Test
    public void whenGivenId_shouldDeleteUser_ifFound(){
        User user = new User();
        user.setName(&quot;Test Name&quot;);
        user.setId(1L);

        when(userRepository.findById(user.getId())).thenReturn(Optional.of(user));

        deleteUserService.deleteUser(user.getId());
        verify(userRepository).deleteById(user.getId());
    }
}
</code></pre>
<p>In <code>deleteUserService.deleteUser</code> to test if a user exists, we could have also used <code>existsById</code> instead of <code>findById</code>. In this case, the unit test would fail.</p>
<p>I am new to unit testing, but this does not seem right. But also I cannot find a good solution: I mean, when I write the test I should mock all the possible methods that could test the existence? It seems too heavy.</p>
",https://stackoverflow.com/questions/71887930/junit-crud-why-assuming-that-you-use-findbyid-instead-of-existsbyid,"['java', 'junit', 'mockito']",199,False,0,0
Setup Jest unit testing for Angular to easily mock dependency classes,"<p>I am trying to find a way to setup my Jest unit testing in the following manner:</p>
<ul>
<li>Every class has its stub class. We always use stub classes for unit testing.</li>
<li>Stub classes return minimal required mock values.</li>
<li>We can always overwrite default stub with test specific data.</li>
</ul>
<p>Let's have an example.</p>
<pre class=""lang-js prettyprint-override""><code>class AnotherServiceUsedWithinTestedClassStub {
  methodToOverwrite(): stirng {
    return 'mockValue';
  }
}

describe('TestClass', () =&gt; {
  let sut: ServiceUnderTest;
  let depService: AnotherServiceUsedWithinTestedClass;

  beforeAll(() =&gt; {
    TestBed.configureTestingModule({
      providers: [
        ServiceUnderTest,
        {
          provide: AnotherServiceUsedWithinTestedClass,
          useClass: AnotherServiceUsedWithinTestedClassStub,
        },
      ],
    });

    injector = getTestBed();
    sut = injector.inject(ServiceUnderTest);
    depService = injector.inject(AnotherServiceUsedWithinTestedClass);
  });

  it('should be created', () =&gt; {
    // So, now whenever AnotherServiceUsedWithinTestedClass is called it will return the values defined in AnotherServiceUsedWithinTestedClassStub.

    // Let's say, I want to overwrite this with specific dataset for this testcase:

    const spy = jest.spyOn(depService, 'methodToOverwrite').mockImplementationOnce(() =&gt; 'newMockValue');

    // ... the rest of the testcase
  });
});

</code></pre>
<p>The problem is that <code>const spy = jest.spyOn(depService, 'methodToOverwrite').mockImplementationOnce(() =&gt; 'newMockValue');</code> doesn't work at all - instead of returning <code>newMockValue</code> it returns <code>mockValue</code> from <code>AnotherServiceUsedWithinTestedClassStub</code>.</p>
<p>Using Angular <code>13.3.2</code> and Jest <code>28.1.1</code>.</p>
<p>PS.
I'm not interested in using <code>useValue</code> in <code>configureTestingModule</code>. The idea is to operate on classes using <code>useClass</code>.</p>
",https://stackoverflow.com/questions/72954608/setup-jest-unit-testing-for-angular-to-easily-mock-dependency-classes,"['angular', 'unit-testing', 'jestjs']",33,False,0,0
What will be the unit testing for this code?,"<p>What will be the unit testing code for the given code below...
Got stuck for a while so please help me find the solution...</p>
<pre class=""lang-cs prettyprint-override""><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DemoAppCore
{
    public class Program
    {
        public static string CacluateGrade(float mark)
        {
            string grade = &quot;&quot;;
            if (mark &lt; 40)
                grade = &quot;FAIL&quot;;
            else if (mark &gt;= 40)
                grade = &quot;PASS&quot;;
            return grade;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/72327155/what-will-be-the-unit-testing-for-this-code,"['c#', 'unit-testing']",45,False,-2,1
How to test composable function,"<p>I am trying to Jest unit testing in Vue 3.</p>
<pre><code>// Home.vue
...
&lt;script lang=&quot;ts&quot;&gt;
import { defineComponent, ref, watch } from 'vue'
import { useStore } from 'vuex'
...
import useTaskList from '@/composables/useTaskList'

export default defineComponent({
  name: 'TaskHome',
  components: {
    ...
  },
  setup() {
    const {
      fetchTaskList,
    } = useTaskList()
    fetchTaskList()
    ...
})
&lt;/script&gt;
</code></pre>
<pre><code>// Home.spec.ts
import Home from '../Home.vue'
import TestUtils from '@/lib/testing/TestUtils'

jest.mock('@/composables/useTaskList')

describe('Home', () =&gt; {
  describe('when component is mounted', () =&gt; {
    it('should fetch task list', async () =&gt; {
      const wrapper = await TestUtils.safeMount(Home)
      expect(wrapper.vm.fetchTaskList).toHaveBeenCalled()
    })
  })
</code></pre>
<p>But this fails and I get this error message.</p>
<pre><code>    expect(received).toHaveBeenCalled()

    Matcher error: received value must be a mock or spy function

    Received has value: undefined

    &gt; 19 |       expect(wrapper.vm.fetchTaskList).toHaveBeenCalled()
</code></pre>
<p>How can I fix this issue?</p>
",https://stackoverflow.com/questions/71714653/how-to-test-composable-function,"['typescript', 'vue.js', 'unit-testing', 'jestjs', 'vuejs3']",817,False,1,0
I&#39;m getting the following deprecation warning when running unit tests in a brand new Angular 11 application:,"<p><a href=""https://i.stack.imgur.com/tyLqj.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
<p>This is the error that I was getting</p>
<p>Unit Testing (This type  of error occurs when I run ng test)</p>
",https://stackoverflow.com/questions/74441464/im-getting-the-following-deprecation-warning-when-running-unit-tests-in-a-brand,"['angular', 'unit-testing']",184,True,-2,1
Mock carbon now and make code a little more clean,"<p>I want to reduce if else statements and write unit testing for the case holiday. I want to mock and use <code>shouldReceive('isHoliday')</code> but I don't know.</p>
<pre><code>if ($request-&gt;isVip == 1) {
    $fee = 0;
} else {
    if (in_array($now-&gt;format('l'), ['Saturday','Sunday']) || $now-&gt;isHoliday()) {
        $fee = 110;
    } else {
        $fee = $now-&gt;gte(Carbon::parse('8:45')) &amp;&amp; $now-&gt;lt(Carbon::parse('18:00')) ? 0 : 110;
    }
}
</code></pre>
",https://stackoverflow.com/questions/73136101/mock-carbon-now-and-make-code-a-little-more-clean,"['laravel', 'unit-testing']",40,False,-1,1
I have an error starting unit testing in android studio Execution failed for task &#39;:app:testDebugUnitTest&#39;,"<p>Please, I have a problem. When I start unit testing in Android Studio, this error appears, knowing that everything is fine in the project. However, when I start the test, this error appears, and it prevents me from conducting tests on applications or projects. Note that when I open a new project, this error does not appear and it works. unit testing well, while if I close the project, even if I don't do anything, the same error appears for no reason.<a href=""https://i.stack.imgur.com/d0q5B.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
<p>[<a href=""https://i.stack.imgur.com/BjXd8.png"" rel=""nofollow noreferrer"">enter image description here</a>]</p>
<p>(<a href=""https://i.stack.imgur.com/xPuvI.png"" rel=""nofollow noreferrer"">https://i.stack.imgur.com/xPuvI.png</a>)</p>
",https://stackoverflow.com/questions/74893585/i-have-an-error-starting-unit-testing-in-android-studio-execution-failed-for-tas,"['android-studio', 'unit-testing', 'gradle', 'error-handling']",34,False,0,0
Create Dynamic table with datasource.json as data for table and a angular tree build using schema.json to turn on and off table column using checkbox,"<p>I have an assignment i am having hard time completing.</p>
<ol>
<li>Bind right side tables fields using checkbox tree from attached schema.json (fields can be
add/remove/show/hide during unit testing)</li>
<li>Use angular material data-table.</li>
<li>Render/Prepare dynamic data-table data on the basis of fields selection(check/un-check) from right
side table.</li>
<li>Use attached datasource.json file for prepare data-table data(we can add more data during unit
testing).</li>
<li>Apply search, sorting and paging(4,8,12) on dynamic data table.<a href=""https://i.stack.imgur.com/Dp4CQ.png"" rel=""nofollow noreferrer"">example photo</a></li>
</ol>
<p>datasource.json
<div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>[
  {
    id: ""d0e2959d-ddff-4676-bce7-01d3647ee84a"",
    name: ""BaChangeTransactions"",
    content: {
      fileInformation: {
        fileType: ""Change Transaction Report"",
        dateTime: ""2021-10-03T22:19:27.6209847+00:00"",
        locale: ""en-AU"",
        version: 1,
        creationTrigger: 1,
        
      },
      machineInformation: {
        machineNumber: ""314811"",
        serialNumber: ""017321"",
        machineType: ""CRM1"",
        
      },
      data: {
        transactionDateTime: ""2020-12-02T13:43:15"",
        reportNumber: ""0000"",
        acknowledgementNumber: ""314811012012020005"",
        acknowledgementIssued: ""I"",
        accessType: ""Screen Access"",
        cardNumber: """",
        notesRetractedFlag: false,
        orderedTotal: 2000,
        insertedTotal: 3000,
        receivedTotal: 4000,
        creditValue: 0,
        counterfeitNotesInsertedNumber: 0,
        totalCommissionAmount: 0,
        sortCode: ""314811"",
        
      },
      
    }
  },
  {
    id: ""d0e2959d-ddff-4676-bce7-01d3647ee84b"",
    name: ""BaChangeTransactions"",
    content: {
      fileInformation: {
        fileType: ""Change Transaction Report"",
        dateTime: ""2021-10-03T22:19:27.6209847+00:00"",
        locale: ""en-AU"",
        version: 1,
        creationTrigger: 1,
        
      },
      machineInformation: {
        machineNumber: ""314811"",
        serialNumber: ""017324"",
        machineType: ""CRM2"",
        
      },
      data: {
        transactionDateTime: ""2020-12-02T13:43:15"",
        reportNumber: ""0000"",
        acknowledgementNumber: ""314811012012020005"",
        acknowledgementIssued: ""I"",
        accessType: ""Screen Access"",
        cardNumber: """",
        notesRetractedFlag: false,
        orderedTotal: 4000,
        insertedTotal: 4000,
        receivedTotal: 4000,
        creditValue: 0,
        counterfeitNotesInsertedNumber: 0,
        totalCommissionAmount: 0,
        sortCode: ""314811"",
        
      },
      
    }
  },
  {
    id: ""d0e2959d-ddff-4676-bce7-01d3647ee84c"",
    name: ""BaChangeTransactions"",
    content: {
      fileInformation: {
        fileType: ""Change Transaction Report"",
        dateTime: ""2021-10-03T22:19:27.6209847+00:00"",
        locale: ""en-AU"",
        version: 1,
        creationTrigger: 1,
        
      },
      machineInformation: {
        machineNumber: ""314812"",
        serialNumber: ""017322"",
        machineType: ""CRM2"",
        
      },
      data: {
        transactionDateTime: ""2020-12-02T13:43:15"",
        reportNumber: ""0000"",
        acknowledgementNumber: ""314811012012020005"",
        acknowledgementIssued: ""I"",
        accessType: ""Screen Access"",
        cardNumber: """",
        notesRetractedFlag: false,
        orderedTotal: 2000,
        insertedTotal: 3000,
        receivedTotal: 4000,
        creditValue: 0,
        counterfeitNotesInsertedNumber: 0,
        totalCommissionAmount: 0,
        sortCode: ""314811"",
        
      },
      
    }
  },
  {
    id: ""d0e2959d-ddff-4676-bce7-01d3647ee84d"",
    name: ""BaChangeTransactions"",
    content: {
      fileInformation: {
        fileType: ""Change Transaction Report"",
        dateTime: ""2021-10-03T22:19:27.6209847+00:00"",
        locale: ""en-AU"",
        version: 1,
        creationTrigger: 1,
        
      },
      machineInformation: {
        machineNumber: ""314813"",
        serialNumber: ""017323"",
        machineType: ""CRM3"",
        
      },
      data: {
        transactionDateTime: ""2020-12-02T13:43:15"",
        reportNumber: ""0000"",
        acknowledgementNumber: ""314811012012020005"",
        acknowledgementIssued: ""I"",
        accessType: ""Screen Access"",
        cardNumber: """",
        notesRetractedFlag: false,
        orderedTotal: 2000,
        insertedTotal: 3000,
        receivedTotal: 4000,
        creditValue: 0,
        counterfeitNotesInsertedNumber: 0,
        totalCommissionAmount: 0,
        sortCode: ""314811"",
        
      },
      
    }
  },
  {
    id: ""d0e2959d-ddff-4676-bce7-01d3647ee84e"",
    name: ""BaChangeTransactions"",
    content: {
      fileInformation: {
        fileType: ""Change Transaction Report"",
        dateTime: ""2021-10-03T22:19:27.6209847+00:00"",
        locale: ""en-AU"",
        version: 1,
        creationTrigger: 1,
        
      },
      machineInformation: {
        machineNumber: ""314814"",
        serialNumber: ""017324"",
        machineType: ""CRM4"",
        
      },
      data: {
        transactionDateTime: ""2020-12-02T13:43:15"",
        reportNumber: ""0000"",
        acknowledgementNumber: ""314811012012020005"",
        acknowledgementIssued: ""I"",
        accessType: ""Screen Access"",
        cardNumber: """",
        notesRetractedFlag: false,
        orderedTotal: 2000,
        insertedTotal: 3000,
        receivedTotal: 4000,
        creditValue: 0,
        counterfeitNotesInsertedNumber: 0,
        totalCommissionAmount: 0,
        sortCode: ""314811"",
        
      },
      
    }
  },
  {
    id: ""d0e2959d-ddff-4676-bce7-01d3647ee84f"",
    name: ""BaChangeTransactions"",
    content: {
      fileInformation: {
        fileType: ""Change Transaction Report"",
        dateTime: ""2021-10-03T22:19:27.6209847+00:00"",
        locale: ""en-AU"",
        version: 1,
        creationTrigger: 1,
        
      },
      machineInformation: {
        machineNumber: ""314814"",
        serialNumber: ""017324"",
        machineType: ""CRM4"",
        
      },
      data: {
        transactionDateTime: ""2020-12-02T13:43:15"",
        reportNumber: ""0000"",
        acknowledgementNumber: ""314811012012020005"",
        acknowledgementIssued: ""I"",
        accessType: ""Screen Access"",
        cardNumber: """",
        notesRetractedFlag: false,
        orderedTotal: 2000,
        insertedTotal: 3000,
        receivedTotal: 4000,
        creditValue: 0,
        counterfeitNotesInsertedNumber: 0,
        totalCommissionAmount: 0,
        sortCode: ""314811"",
        
      },
      
    }
  },
  {
    id: ""d0e2959d-ddff-4676-bce7-01d3647ee84g"",
    name: ""BaChangeTransactions"",
    content: {
      fileInformation: {
        fileType: ""Change Transaction Report"",
        dateTime: ""2021-10-03T22:19:27.6209847+00:00"",
        locale: ""en-AU"",
        version: 1,
        creationTrigger: 1,
        
      },
      machineInformation: {
        machineNumber: ""314814"",
        serialNumber: ""017324"",
        machineType: ""CRM4"",
        
      },
      data: {
        transactionDateTime: ""2020-12-02T13:43:15"",
        reportNumber: ""0000"",
        acknowledgementNumber: ""314811012012020005"",
        acknowledgementIssued: ""I"",
        accessType: ""Screen Access"",
        cardNumber: """",
        notesRetractedFlag: false,
        orderedTotal: 2000,
        insertedTotal: 3000,
        receivedTotal: 4000,
        creditValue: 0,
        counterfeitNotesInsertedNumber: 0,
        totalCommissionAmount: 0,
        sortCode: ""314811"",
        
      },
      
    }
  },
  {
    id: ""d0e2959d-ddff-4676-bce7-01d3647ee84h"",
    name: ""BaChangeTransactions"",
    content: {
      fileInformation: {
        fileType: ""Change Transaction Report"",
        dateTime: ""2021-10-03T22:19:27.6209847+00:00"",
        locale: ""en-AU"",
        version: 1,
        creationTrigger: 1,
        
      },
      machineInformation: {
        machineNumber: ""314814"",
        serialNumber: ""017324"",
        machineType: ""CRM4"",
        
      },
      data: {
        transactionDateTime: ""2020-12-02T13:43:15"",
        reportNumber: ""0000"",
        acknowledgementNumber: ""314811012012020005"",
        acknowledgementIssued: ""I"",
        accessType: ""Screen Access"",
        cardNumber: """",
        notesRetractedFlag: false,
        orderedTotal: 2000,
        insertedTotal: 3000,
        receivedTotal: 4000,
        creditValue: 0,
        counterfeitNotesInsertedNumber: 0,
        totalCommissionAmount: 0,
        sortCode: ""314811"",
        
      },
      
    }
  },
  {
    id: ""d0e2959d-ddff-4676-bce7-01d3647ee84i"",
    name: ""BaChangeTransactions"",
    content: {
      fileInformation: {
        fileType: ""Change Transaction Report"",
        dateTime: ""2021-10-03T22:19:27.6209847+00:00"",
        locale: ""en-AU"",
        version: 1,
        creationTrigger: 1,
        
      },
      machineInformation: {
        machineNumber: ""314814"",
        serialNumber: ""017324"",
        machineType: ""CRM4"",
        
      },
      data: {
        transactionDateTime: ""2020-12-02T13:43:15"",
        reportNumber: ""0000"",
        acknowledgementNumber: ""314811012012020005"",
        acknowledgementIssued: ""I"",
        accessType: ""Screen Access"",
        cardNumber: """",
        notesRetractedFlag: false,
        orderedTotal: 2000,
        insertedTotal: 3000,
        receivedTotal: 4000,
        creditValue: 0,
        counterfeitNotesInsertedNumber: 0,
        totalCommissionAmount: 0,
        sortCode: ""314811"",
        
      },
      
    }
  },
  {
    id: ""d0e2959d-ddff-4676-bce7-01d3647ee84j"",
    name: ""BaChangeTransactions"",
    content: {
      fileInformation: {
        fileType: ""Change Transaction Report"",
        dateTime: ""2021-10-03T22:19:27.6209847+00:00"",
        locale: ""en-AU"",
        version: 1,
        creationTrigger: 1,
        
      },
      machineInformation: {
        machineNumber: ""314814"",
        serialNumber: ""017324"",
        machineType: ""CRM4"",
        
      },
      data: {
        transactionDateTime: ""2020-12-02T13:43:15"",
        reportNumber: ""0000"",
        acknowledgementNumber: ""314811012012020005"",
        acknowledgementIssued: ""I"",
        accessType: ""Screen Access"",
        cardNumber: """",
        notesRetractedFlag: false,
        orderedTotal: 2000,
        insertedTotal: 3000,
        receivedTotal: 4000,
        creditValue: 0,
        counterfeitNotesInsertedNumber: 0,
        totalCommissionAmount: 0,
        sortCode: ""314811"",
        
      },
      
    }
  },
  
  {
    ""id"": ""9e577424-7317-4e40-97bb-38f1f2abed61"",
    ""name"": ""BoxMessages"",
    ""content"": {
        ""id"": ""ROLL03-NOTE-AUD-500"",
        ""name"": ""ROLL03"",
        ""description"": ""Note RecyclerROLL03"",
        ""contentAt"": ""2021-10-18T07:49:01.878"",
        ""contentAtUtc"": ""2021-10-17T20:49:01.878Z"",
        ""value"": {
            ""currency"": ""AUD"",
            ""denomination"": 5,
            ""decimals"": 2,
            ""quantity"": 61,
            ""mediaType"": ""NOTE"",
            ""value"": 5,
            ""total"": 305
        },
        ""vendorDependentFields"": {
            ""MESSAGE_SEQUENCE"": 2437214,
            ""LINE_NUMBER"": 506
        }
    }   
    },
    {
    ""id"": ""9e577424-7317-4e40-97bb-38f1f2abed62"",
    ""name"": ""BoxMessages"",
    ""content"": {
        ""id"": ""ROLL03-NOTE-AUD-500"",
        ""name"": ""ROLL03"",
        ""description"": ""Note RecyclerROLL03"",
        ""contentAt"": ""2021-10-18T07:49:01.878"",
        ""contentAtUtc"": ""2021-10-17T20:49:01.878Z"",
        ""value"": {
            ""currency"": ""AUD"",
            ""denomination"": 5,
            ""decimals"": 2,
            ""quantity"": 61,
            ""mediaType"": ""NOTE"",
            ""value"": 5,
            ""total"": 305
        },
        ""vendorDependentFields"": {
            ""MESSAGE_SEQUENCE"": 2437214,
            ""LINE_NUMBER"": 506
        }
    }   
    },
    {
    ""id"": ""9e577424-7317-4e40-97bb-38f1f2abed63"",
    ""name"": ""BoxMessages"",
    ""content"": {
        ""id"": ""ROLL03-NOTE-AUD-500"",
        ""name"": ""ROLL03"",
        ""description"": ""Note RecyclerROLL03"",
        ""contentAt"": ""2021-10-18T07:49:01.878"",
        ""contentAtUtc"": ""2021-10-17T20:49:01.878Z"",
        ""value"": {
            ""currency"": ""AUD"",
            ""denomination"": 5,
            ""decimals"": 2,
            ""quantity"": 61,
            ""mediaType"": ""NOTE"",
            ""value"": 5,
            ""total"": 305
        },
        ""vendorDependentFields"": {
            ""MESSAGE_SEQUENCE"": 2437214,
            ""LINE_NUMBER"": 506
        }
    }   
    },
    {
    ""id"": ""9e577424-7317-4e40-97bb-38f1f2abed64"",
    ""name"": ""BoxMessages"",
    ""content"": {
        ""id"": ""ROLL03-NOTE-AUD-500"",
        ""name"": ""ROLL03"",
        ""description"": ""Note RecyclerROLL03"",
        ""contentAt"": ""2021-10-18T07:49:01.878"",
        ""contentAtUtc"": ""2021-10-17T20:49:01.878Z"",
        ""value"": {
            ""currency"": ""AUD"",
            ""denomination"": 5,
            ""decimals"": 2,
            ""quantity"": 61,
            ""mediaType"": ""NOTE"",
            ""value"": 5,
            ""total"": 305
        },
        ""vendorDependentFields"": {
            ""MESSAGE_SEQUENCE"": 2437214,
            ""LINE_NUMBER"": 506
        }
    }   
    },
    {
    ""id"": ""9e577424-7317-4e40-97bb-38f1f2abed65"",
    ""name"": ""BoxMessages"",
    ""content"": {
        ""id"": ""ROLL03-NOTE-AUD-500"",
        ""name"": ""ROLL03"",
        ""description"": ""Note RecyclerROLL03"",
        ""contentAt"": ""2021-10-18T07:49:01.878"",
        ""contentAtUtc"": ""2021-10-17T20:49:01.878Z"",
        ""value"": {
            ""currency"": ""AUD"",
            ""denomination"": 5,
            ""decimals"": 2,
            ""quantity"": 61,
            ""mediaType"": ""NOTE"",
            ""value"": 5,
            ""total"": 305
        },
        ""vendorDependentFields"": {
            ""MESSAGE_SEQUENCE"": 2437214,
            ""LINE_NUMBER"": 506
        }
    }   
    }

  
  
]</code></pre>
</div>
</div>
</p>
<p>schema.json</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>[
{
    ""name"": ""BaChangeTransactions"",
    ""id"": ""86e5968c-8548-4011-91fd-d64b774b5151"",
    ""displayName"": ""Change Transaction Report"",
    ""isVisible"": true,
    ""fields"": [
        {
            ""displayName"": ""Machine Number"",
            ""column"": ""content.machineInformation.machineNumber"",
            ""datatype"": ""Text"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Serial Number"",
            ""column"": ""content.machineInformation.serialNumber"",
            ""datatype"": ""Text"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Machine Type"",
            ""column"": ""content.machineInformation.machineType"",
            ""datatype"": ""Text"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""DateTime"",
            ""column"": ""content.data.transactionDateTime"",
            ""datatype"": ""dateTime"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Ordered Total"",
            ""column"": ""content.data.orderedTotal"",
            ""datatype"": ""Number"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Inserted Total"",
            ""column"": ""content.data.insertedTotal"",
            ""datatype"": ""Number"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Recieved Total"",
            ""column"": ""content.data.receivedTotal"",
            ""datatype"": ""Number"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Credit Value"",
            ""column"": ""content.data.creditValue"",
            ""datatype"": ""Number"",
            ""isVisible"": false
        },
        {
            ""displayName"": ""Total Commissioned Amount"",
            ""column"": ""content.data.totalCommissionedAmount"",
            ""datatype"": ""Number"",
            ""isVisible"": false
        },
        {
            ""displayName"": ""Sort Code"",
            ""column"": ""content.data.sortCode"",
            ""datatype"": ""Text"",
            ""format"": """",
            ""isVisible"": false
        }
    ]
},
{
    ""name"": ""BoxMessages"",
    ""id"": ""5e6e5f44-6d79-43ae-a5f5-d442ed095bac"",
    ""displayName"": ""Box Messages"",
    ""isVisible"": true,
    ""fields"": [
        {
            ""displayName"": ""Id"",
            ""column"": ""content.id"",
            ""datatype"": ""Text"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Name"",
            ""column"": ""content.name"",
            ""datatype"": ""Text"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Description"",
            ""column"": ""content.description"",
            ""datatype"": ""Text"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Date"",
            ""column"": ""content.contentAt"",
            ""datatype"": ""dateTime"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Date UTC"",
            ""column"": ""content.contentAtUtc"",
            ""datatype"": ""dateTime"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""quantity"",
            ""column"": ""content.value.quantity"",
            ""datatype"": ""Number"",
            ""isVisible"": false
        },
        {
            ""displayName"": ""Media Type"",
            ""column"": ""content.value.mediaType"",
            ""datatype"": ""Text"",
            ""isVisible"": false
        },
        {
            ""displayName"": ""Value"",
            ""column"": ""content.value.value"",
            ""datatype"": ""Number"",
            ""isVisible"": false
        },
        {
            ""displayName"": ""Total"",
            ""column"": ""content.value.total"",
            ""datatype"": ""Number"",
            ""isVisible"": false
        },
        {
            ""displayName"": ""Message Sequence"",
            ""column"": ""content.vendorDependentFields.MESSAGE_SEQUENCE"",
            ""datatype"": ""Number"",
            ""isVisible"": true
        },
        {
            ""displayName"": ""Line Number"",
            ""column"": ""content.vendorDependentFields.LINE_NUMBER"",
            ""datatype"": ""Number"",
            ""isVisible"": true
        }
    ]
}
]</code></pre>
</div>
</div>
</p>
<p>how am i supposed to achieve this?</p>
",https://stackoverflow.com/questions/72616213/create-dynamic-table-with-datasource-json-as-data-for-table-and-a-angular-tree-b,"['javascript', 'angular', 'dynamic', 'angular-material', 'angular-material-table']",239,False,0,0
Cannot read properties of undefined (reading &#39;save&#39;) + TypeORM + Unit Testing,"<p>I'm still new to Unit Testing, TypeOrm, and NestJs. I currently have a user registration repository I'm trying to unit test. The feature works perfectly fine and I can register a user. But when I'm unit testing the repository I get the error <strong>Cannot read properties of undefined (reading 'save')</strong>.</p>
<p>This is my <strong>user.repository.ts</strong> file</p>
<pre><code>import {
  ConflictException,
  InternalServerErrorException,
} from '@nestjs/common';
import { EntityRepository, Repository } from 'typeorm';
import { genSalt, hash } from 'bcryptjs';
import { omit } from 'lodash';
import { generate } from 'randomstring';
import { CreateUserDto } from 'src/dtos/user/create-user-dto';
import { User } from './user.entity';

@EntityRepository(User)
export class UserRepository extends Repository&lt;User&gt; {
  async register(createUserDto: CreateUserDto): Promise&lt;object&gt; {
    const {
      firstName,
      ... //other destructured fields here
    } = createUserDto;
    const salt = await genSalt();
    const user = this.create();
    user.firstName = firstName;
    ... // created user here
    try {
      await this.save(user);
    } catch (error) {
      if (error.code === '23505') { //duplicate error
        console.log(error.message);
        // throw new ConflictException('Username or Password is Taken');
      } else {
        throw new InternalServerErrorException('THIS IS A 500 ERROR');
      }
    }
    let omitPasswordFromReturn = omit(user, ['password']);
    return omitPasswordFromReturn;
  }

  private async hashPassword(password: string, salt: string): Promise&lt;string&gt; {
    return hash(password, salt);
  }
}
</code></pre>
<p>And this is the <strong>user.repository.spec.ts</strong> file</p>
<pre><code>import { ConflictException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { CreateUserDto } from 'src/dtos/user/create-user-dto';
import { UserRepository } from './user.repository';

const mockCreateUserDto: CreateUserDto = {
  firstName: 'Muhammad',
  ...
};

describe('UserRepository', () =&gt; {
  let userRepository;

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      providers: [UserRepository],
    }).compile();

    userRepository = await module.get&lt;UserRepository&gt;(UserRepository);
  });

  describe('user registration', () =&gt; {
    let save;

    beforeEach(() =&gt; {
      save = jest.fn();
      userRepository.create = jest.fn().mockReturnValue({ save });
    });  

    it('should be defined', () =&gt; {
      expect(userRepository.register).toBeDefined();
    })

    it('should sucessfully register user', async () =&gt; {
      save.mockResolvedValue(undefined);
      await expect(
        userRepository.register(mockCreateUserDto),
      ).resolves.not.toThrow();
    });

  });
});
</code></pre>
<p>I have searched typeOrm docs and on here at StackOverflow but nothing is helping.
I've really run out of ideas to try. any form of help is welcome</p>
",https://stackoverflow.com/questions/72977323/cannot-read-properties-of-undefined-reading-save-typeorm-unit-testing,"['unit-testing', 'jestjs', 'repository', 'nestjs', 'typeorm']",442,False,0,0
&quot;Schema validation failed with the following errors: Data path &quot;&quot; should have required property &#39;karmaConfig&#39; error on running &quot;ng test&quot; - angular,"<p>I have been developing with angular with quite some time now but I have never ever written unit tests for any of my angular applications. I'm new to unit testing and was looking to get started with unit testing when I came across this issue.</p>
<p>With my angular application setup and based on the documentation I ran &quot;ng test&quot; to explore how the test works but I'm running in to the following error:
&quot;</p>
<pre><code>Schema validation failed with the following errors:
  Data path &quot;&quot; should have required property 'karmaConfig'.
</code></pre>
<p>&quot;
I'm unable to run anything or move forward because of this
<a href=""https://i.stack.imgur.com/chmfj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/chmfj.png"" alt=""enter image description here"" /></a></p>
<p>Any help would be appreciated!</p>
",https://stackoverflow.com/questions/74829129/schema-validation-failed-with-the-following-errors-data-path-should-have-re,"['javascript', 'angular', 'jasmine', 'karma-jasmine', 'karma-runner']",342,True,0,1
Wait for the delegates to be executed before return of the object of a class,"<p>I am unit testing a class. The class is responsible for connecting to a peripheral and then discovering its services and characteristics using the delegates.</p>
<pre><code>    func setupLightController() -&gt; HueBTLightController
    {
        let btLight = HueBTLight(identifier: &quot;093FB4B8-82E6-A124-3888-4F25C19CFDB7&quot;)
        btLight.name = &quot;Hue Bloom&quot;
        let lightController = HueBTLightController(light: btLight)
        weak var bluetoothManager = BluetoothManager.sharedInstance
        bluetoothManager?.selectLight(lightController.light!)
        bluetoothManager?.delegate += lightController
        return lightController
    }
</code></pre>
<p>In my test methods, I am getting the object of this class and unit testing the respective functions of that class.</p>
<pre><code>    func testSetColorModel()
    {
       let lightController = setupLightController()
    }
</code></pre>
<p>Basically, the problem is that the object is returned before the delegate methods of HueBTLightController are executed. How can I wait for the delegate calls to be finished and then return the object in the test method? Please help me solve this.</p>
",https://stackoverflow.com/questions/72364040/wait-for-the-delegates-to-be-executed-before-return-of-the-object-of-a-class,"['ios', 'swift', 'xcode', 'delegation']",66,False,0,0
Invariant Violation: TurboModuleRegistry.getEnforcing(...): &#39;FileReaderModule&#39; could not be found. (React native),"<p>Getting error while unit testing :</p>
<blockquote>
<p>Invariant Violation: TurboModuleRegistry.getEnforcing(...): 'FileReaderModule' could not be found. Verify that a module by this name is registered in the native binary.</p>
</blockquote>
<p>Payslip.test.js</p>
<pre class=""lang-js prettyprint-override""><code>import {render} from '@testing-library/react-native';
import Payslip from '../Payslip';

jest.mock('@react-native-async-storage/async-storage', () =&gt; {   
  return {
    multiSet: jest.fn(),
    multiRemove: jest.fn(),
    multiMerge: jest.fn(),
  };
});

jest.mock('@react-native-community/netinfo', () =&gt; {
  return {
    configure: jest.fn(),
    fetch: jest.fn(),
    addEventListener: jest.fn(),
    useNetInfo: jest.fn(),
  };
});

test('form submits two answers', () =&gt; {
  const {getByTestId} = render(&lt;Payslip /&gt;);

  let Header = getByTestId('header');
  expect(Header).toBeTruthy();
});

</code></pre>
",https://stackoverflow.com/questions/70603148/invariant-violation-turbomoduleregistry-getenforcing-filereadermodule-c,"['react-native', 'jestjs']",344,False,1,0
How to test socket io from vue jest?,"<p>this is my code from vue.js:</p>
<pre><code>async getUserInformation(user_id){
   return await new Promise((resolve, reject) =&gt; {
      this.$socket.client.emit('getUserInfo', user_id, (err,res) =&gt; {
         err ? reject(err) : resolve(res)
      })
   })
},
async selectAction() {
  let getReponse= await this.getUserInformation(this.user_id)
  this.userInformation = getResponse
}
</code></pre>
<p>this is my code from vue jest</p>
<pre><code>describe('editUser.vue', () =&gt; {
    let wrapper
  
    beforeEach(() =&gt; {
        wrapper = shallowMount(editUser, {
            mixins: [global]
        })
    });
    

    it('trigger submit button w/o data input from text fields', async () =&gt; {
        await wrapper.find('[data-testid=&quot;get_user_button&quot;]').trigger('click')
    });
});
</code></pre>
<p>Picture below is the error message I received after I run unit testing
<a href=""https://i.stack.imgur.com/uAoX2.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/uAoX2.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/71136236/how-to-test-socket-io-from-vue-jest,"['vue.js', 'socket.io', 'vue-jest']",136,False,0,0
typeorm RAW is not covered in jest,"<p>Unit testing using jest is done in the code. But Raw of typeorm is not covered</p>
<pre><code>queryobj.where.name = Raw(
         () =&gt;
           `( &quot;Tag__templateTag__template&quot;.&quot;state&quot; = '${TemplateState.Published}')`,
       )
</code></pre>
<p>Raw is tried mock using jest.fn()
but</p>
<pre><code> () =&gt;
            `( &quot;Tag__templateTag__template&quot;.&quot;state&quot; = '${TemplateState.Published}')`,
        )
</code></pre>
<p>is not covered</p>
",https://stackoverflow.com/questions/74797644/typeorm-raw-is-not-covered-in-jest,"['javascript', 'unit-testing', 'jestjs', 'typeorm', 'raw']",55,False,0,0
any solutions for this (SassError: File to import not found or unreadable: colors.),"<p><a href=""https://i.stack.imgur.com/mBH9I.png"" rel=""nofollow noreferrer"">this is the error</a></p>
<p>this error occurs while I am testing the project. I have run (ng test) for unit testing this error appears to me</p>
",https://stackoverflow.com/questions/74455485/any-solutions-for-this-sasserror-file-to-import-not-found-or-unreadable-color,"['angular', 'unit-testing']",16,False,0,0
Mock base class function called in derived class; to unit test derived class method. Base class instantiated in derived class constructor,"<p>I m new to unit testing and need some help with this. I would like to test my Derived class function which has dependency on base class method.</p>
<pre><code>class Base {
  Base(int a_, int b_){
     a = a_;
     b = b_;
  }
  int a;
  int b;

  int GetBaseValue(){
   return a + b;
  }
}

class Derived: public Base {
      Derived(int c,int a,int b): 
              c_(c),
              Base(a,b){}

      int GetDerivedValue(){
         return c + GetBaseValue();
      }
}

</code></pre>
",https://stackoverflow.com/questions/72849675/mock-base-class-function-called-in-derived-class-to-unit-test-derived-class-met,"['c++', 'unit-testing', 'testing', 'googlemock']",412,False,1,1
jest.createMockFromModule vs jest.mock,"<p>I'm learning unit testing with jest. I can not understand the difference between the jest.createMockFromModule and jest.mock. Seems that they do the same? Can someone please explain me the difference?</p>
",https://stackoverflow.com/questions/71651076/jest-createmockfrommodule-vs-jest-mock,"['unit-testing', 'jestjs', 'mocking']",2436,True,3,1
assert that all fields in 2 objects are the same c#,"<p>I am doing unit testing, and basically want to check that the data that 2 objects hold is the same</p>
<pre><code>Assert.AreEqual(object1, object2);   
Assert.IsTrue(object1.Equals(object2)); //this of course doesn't work
</code></pre>
<p>I am searching for the C# equivalent of <a href=""https://joel-costigliola.github.io/assertj/core/api/org/assertj/core/api/AbstractObjectAssert.html#isEqualToComparingFieldByField(java.lang.Object)"" rel=""nofollow noreferrer"">assertJ</a></p>
<pre><code>Assert.That(object1).isEqualToComparingFieldByField(object2)
</code></pre>
",https://stackoverflow.com/questions/71793327/assert-that-all-fields-in-2-objects-are-the-same-c,"['c#', 'unit-testing']",439,True,2,2
Is there any easy way to get current list from AsyncListDiffer after Diff calculation finished?,"<p>I want to get the current list from AsyncListDiffer after the diff calculation finishes, for the sake of Unit Testing. Is there any way to do that?</p>
",https://stackoverflow.com/questions/70859580/is-there-any-easy-way-to-get-current-list-from-asynclistdiffer-after-diff-calcul,"['android', 'android-asynclistdiffer']",104,False,0,0
Flutter unit testing with provider,"<p>I am not able to use the provider in unit testing
I am using the following code. I am getting this error</p>
<pre><code>00:02 +2 -1: test student controller with add and remove student test controller for add new set [E]                                            
  Null check operator used on a null value
  package:provider/src/provider.dart 274:20  Provider.of
  test/student_controller_test.dart 53:22    main.&lt;fn&gt;.&lt;fn&gt;
  test/student_controller_test.dart 36:53    main.&lt;fn&gt;.&lt;fn&gt;
</code></pre>
<p>class MockBuildContext extends Mock implements BuildContext {}</p>
<pre><code>void main() {
  late MockBuildContext _mockContext;

  setUpAll(() {
    _mockContext = MockBuildContext();
  });


test('test student controller for add new student', () async {
      List&lt;Students&gt; sts = [
        Students(
            name: 'Barbels',
            age: 21,
            weight: 70,
          ),
         Students(
            name: 'Hazel',
            age: 31,
            weight: 60,
          ),
      ];
      var id = '1';
      print(_mockContext);
      MyController.saveStuden(_mockContext, id, sets);
      print(Provider.of&lt;StudentProvider&gt;(_mockContext, listen: false)
          .items
          .length);
});
</code></pre>
",https://stackoverflow.com/questions/74501192/flutter-unit-testing-with-provider,"['flutter', 'unit-testing', 'dart', 'flutter-provider']",75,False,1,1
How to raise a shutil.SameFileError?,"<p>I am trying to raise a <code>shutil.SameFileError</code> for unit testing but could not succeed. The problem is the error is not raised.</p>
<pre><code>import unittest
class TestErrors(unittest.TestCase):
    &quot;&quot;&quot;Unit testing of errors&quot;&quot;&quot;
    def test_copy_file(self):
        &quot;&quot;&quot;Error tests for copy_file&quot;&quot;&quot;
        with self.assertRaises(shutil.SameFileError):
           copy_file_tester(
               f&quot;{mpath}{os.sep}tests{os.sep}assets{os.sep}runs{os.sep}{get_fake_project()}{os.sep}i1{os.sep}C.fdf&quot;,
               f&quot;{mpath}{os.sep}tests{os.sep}assets{os.sep}runs{os.sep}{get_fake_project()}{os.sep}i1{os.sep}C.fdf&quot;
           )
</code></pre>
<p>The code for <code>copy_file_tester</code>:</p>
<pre><code>def copy_file_tester(sourcefile, destinationfile):
    &quot;&quot;&quot;Tester function for copy_file&quot;&quot;&quot;
    copy_file(sourcefile, destinationfile)
    return list(glob.glob(destinationfile))
</code></pre>
<p>The code for <code>copy_file</code>:</p>
<pre><code>def copy_file(sourcefile, destinationfile):
    &quot;&quot;&quot;Copy and paste a file&quot;&quot;&quot;
    if not os.path.isfile(sourcefile):
        raise FileNotFoundError(f&quot;ERROR: {sourcefile} is not found&quot;)
    try:
        print(f&quot;Copying {sourcefile} to {destinationfile}&quot;)
        if not os.path.exists(destinationfile):
            shutil.copy(sourcefile, destinationfile)
            print(f&quot;{sourcefile} is copied to {destinationfile} successfully&quot;)
        else:
            print(f&quot;{destinationfile} exists&quot;)
    except shutil.SameFileError:
        print(f&quot;ERROR: {sourcefile} and {destinationfile} represents the same file&quot;)
    except PermissionError:
        print(f&quot;ERROR: Permission denied while copying {sourcefile} to {destinationfile}&quot;)
    except (shutil.Error, OSError, IOError) as e:
        print(f&quot;ERROR: An error occurred while copying {sourcefile} to {destinationfile} ({e})&quot;)
</code></pre>
",https://stackoverflow.com/questions/73852127/how-to-raise-a-shutil-samefileerror,"['python', 'python-3.x', 'python-unittest', 'shutil', 'raise']",91,False,0,1
How to raise an AttributeError?,"<p>I am trying to raise an <code>AttributeError</code> for unit testing but could not succeed. The problem is the error is not raised.</p>
<pre><code>import unittest
class TestErrors(unittest.TestCase):
    &quot;&quot;&quot;Unit testing of errors&quot;&quot;&quot;
    def test_get_it(self):
        &quot;&quot;&quot;Error tests for get_it&quot;&quot;&quot;
        with self.assertRaises(AttributeError):
            get_it_tester(&quot;Foo&quot;, &quot;Bar&quot;)
</code></pre>
<p>The code for <code>get_it_tester</code>:</p>
<pre><code>def get_it_tester(path, cont):
    &quot;&quot;&quot;Tester function for get_it&quot;&quot;&quot;
    files = glob.glob(f&quot;{path}{os.sep}i*&quot;)
    files += glob.glob(f&quot;{path}{os.sep}i*{os.sep}{cont}*&quot;)
    return get_it(files)
</code></pre>
<p>The code for <code>get_it</code>:</p>
<pre><code>def get_it(files):
    &quot;&quot;&quot;Get a list of iterations&quot;&quot;&quot;
    try:
        return [int(re.search(f&quot;{os.sep}i([0-9]+)&quot;, f).groups(0)[0]) for f in files]
    except AttributeError:
        print(f&quot;ERROR: The path must be in format of 'path{os.sep}to{os.sep}i1'&quot;)
</code></pre>
",https://stackoverflow.com/questions/73853413/how-to-raise-an-attributeerror,"['python', 'python-3.x', 'python-unittest', 'attributeerror', 'raise']",322,False,0,1
How to do fuzz test in node.js,"<p>I'm trying to do unit testing in node.js with Typescript.
I want to know how other do fuzz test.
Is it possible?
What library do you usually used?</p>
",https://stackoverflow.com/questions/74637346/how-to-do-fuzz-test-in-node-js,"['node.js', 'typescript', 'fuzz-testing']",148,False,0,0
iOS Debugging failed to load on Xcode due library security of CoreData module,"<p>I was trying to simply debug my app while unit testing, but the variables weren't accessible. The error I was encountering was:</p>
<pre><code>error: warning: Failed to load linked library Security of module CoreData - errors: Looking for &quot;@rpath/Security.framework/Security&quot;, error: (null)
</code></pre>
<p>How can this error be fixed?</p>
",https://stackoverflow.com/questions/73894510/ios-debugging-failed-to-load-on-xcode-due-library-security-of-coredata-module,"['ios', 'xcode', 'core-data']",155,False,0,1
Error 404 Not Found while unit testing govmomi vapi rest client using simulator,"<p>I'm working with vSphere govmomi client to interact with vCenter.</p>
<p>I'm having problem in unit testing the govmomi vapi/rest client.
The sample code for creating rest client is:</p>
<pre><code>var insecure bool = true
type RestClient struct {
 url *url.URL
 restClient *rest.Client
}

func (c *RestClient) GetRestClient(ctx context.Context) (*rest.Client, error){
 soapClient := soap.NewClient(c.url, insecure)
 vim25Client, err := vim25.NewClient(ctx, soapClient)
 if err != nil {
  return nil, err
 }
 c.restClient = rest.NewClient(vim25Client)
 err = c.restClient.Login(ctx, c.url.User)
 if err != nil {
  return nil, err
 }
 return c.restClient, nil
}
</code></pre>
<p>To write their unit tests, I'm using govmomi simulator and vapi/simulator.</p>
<pre><code>import(
 &quot;context&quot;
 &quot;testing&quot;
 &quot;net/url&quot;
 &quot;github.com/vmware/govmomi/simulator&quot;
 _ &quot;github.com/vmware/govmomi/vapi/simulator&quot;
)

func TestGetRestClient(t *testing.T){
 ctx := context.Background()
 model := simulator.ESX()
 defer model.Remove()
 err := model.Create()
 if err != nil {
  t.Fatal(err)
 }
 server := model.Service.NewServer()
 defer server.Close()
 url := server.URL
 var client RestClient = RestClient{url: url,}
 _, err := client.GetRestClient(ctx)
 if err != nil {
  t.Errorf(&quot;err = %v&quot;, err)
  return
 }
}
</code></pre>
<p>The testcase should pass, but it returns an error</p>
<pre><code>err= POST &quot;http://127.0.0.1:34691/rest/com/vmware/cis/session: 404 Not Found
</code></pre>
<p>I'm not able to understand what I'm missing or doing wrong in unit testing. I've done similar test for creating a govmomi client using simulator and it never came across this error.</p>
<p><strong>NOTE: This rest client is created successfully as I'm able to interact with vCenter using this client.</strong></p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/72763660/error-404-not-found-while-unit-testing-govmomi-vapi-rest-client-using-simulator,"['go', 'vmware', 'vsphere', 'govmomi']",193,False,1,0
Issue with unit testing a unzip method node/jest,"<p>I have a small function designed to unzip a file using 'unzipper' and extract to a given location.</p>
<p>when unit testing the function times out, for unit testing I am using jest.</p>
<p>see below code :</p>
<pre><code>    exports.unzipFile = async (folderPath) =&gt; {
    return new Promise((resolve, reject) =&gt; {
    fs.createReadStream(folderPath)
      .pipe(unzipper.Extract({ path: tmpPath+ path.parse(folderPath).name })).on('close', () =&gt; resolve()).on('error', (error) =&gt; reject(error))
    })
</code></pre>
<p>The function itself works as expected. I have tried some changes to the function but this seems to break the function. I need this function to execute fully as the unzipped file is then relied on later in the program.</p>
<p>The program is written in node 16.
Any help would be appreciated thanks</p>
<p>EDIT: this is my current unit test- I have tried various things :</p>
<pre><code>const { PassThrough } = require('stream')
const os = require('os');
const unzipper = require(&quot;unzipper&quot;)
const fs = require(&quot;fs&quot;)

let tmpdir, mockReadStream
    
beforeEach(() =&gt; {

tmpdir = os.tmpdir() + &quot;/uploadFolder/&quot;;
 if (!fs.existsSync(tmpdir)){
     fs.mkdirSync(tmpdir);
 }
 fs.writeFileSync(tmpdir+&quot;tempfile.zip&quot;, &quot;file to be used&quot;)

mockReadStream = new PassThrough()
})
afterEach(() =&gt; {
  // Restore mocks
  jest.clearAllMocks()

})

describe('Test helper.js unzip method', () =&gt; {
  test('should be able to unzip file  ', async () =&gt; {


         jest.isolateModules(() =&gt; {
             helper = require('helper')
         })

     const result = await helper.unzipFile(tmpdir+&quot;tempfile.zip&quot;)
    console.log(result)
  })
})
</code></pre>
",https://stackoverflow.com/questions/73991213/issue-with-unit-testing-a-unzip-method-node-jest,"['node.js', 'unit-testing', 'jestjs', 'node-modules', 'nodejs-stream']",223,True,1,1
Angular11 unit testing for formBuilder for valueChanges,"<p>Unable to cover search() function in unit testing.</p>
<p>I am not sure how to mock fomBuilder and FormControl.
Also the service needs to return data so how to mock it.</p>
<pre><code>ngOnInit() {
    this.search()
  }
 searchForm = this.fb.group({
    searchText: new FormControl()
  });
  subscription$: any;
  search() {
    this.subscription$ = this.searchForm.controls['searchText'].valueChanges
      .pipe(
        debounceTime(200),
        tap(() =&gt; {
          this.errorMsg = '';
          this.filteredOptions = [];
          this.isLoading = true;
        }),
        switchMap((value: string) =&gt; {
          this.toHighlight = value;
          this.searchKeyword = value;
          if (value != '' &amp;&amp; value !== undefined) {value = value.toUpperCase();  this._assetService.setSearchKey(this.toHighlight);}
          this.isLoading = true;
          return this._assetService.fetchVlmSearch(value).pipe((finalize(() =&gt; {
            this.isLoading = false;
          })))
        })
      ).subscribe((data: any) =&gt; {
        if (data.rows.length &gt; 0) {
          this.filteredOptions = data.rows;
        }
        else {
          this.errorMsg = 'No Data Found';
          this.filteredOptions = [];
          this.searchKeyword = '';
        }

      })
  }

</code></pre>
",https://stackoverflow.com/questions/73397643/angular11-unit-testing-for-formbuilder-for-valuechanges,"['angular', 'unit-testing', 'karma-jasmine']",66,False,1,0
How to write unit test for Google Signin functions in iOS swift,"<p>I am new to unit testing and want to know is unit test necessary for delegate functions of google signin or facebook signin.
If yes how can one write it?</p>
<pre><code>func btnGoogleLogin(_ sender: UIButton) {
        startLoader()
        
        GIDSignIn.sharedInstance().delegate = self
        //        GIDSignIn.sharedInstance().uiDelegate=self
        GIDSignIn.sharedInstance().signIn()
    }
    
    
    func signInWillDispatch(signIn: GIDSignIn!, error: NSError!) {
        self.stopLoader()
        
    }
    
    // Present a view that prompts the user to sign in with Google
    func sign(_ signIn: GIDSignIn!,
              present viewController: UIViewController!) {
        self.present(viewController, animated: true, completion: nil)
    }
    
    // Dismiss the &quot;Sign in with Google&quot; view
    func sign(_ signIn: GIDSignIn!,
              dismiss viewController: UIViewController!) {
        self.dismiss(animated: true, completion: nil)
        self.stopLoader()
    }
    
</code></pre>
",https://stackoverflow.com/questions/70967029/how-to-write-unit-test-for-google-signin-functions-in-ios-swift,"['ios', 'swift', 'unit-testing']",106,False,1,0
Svelte - Not able to fetch data from JSON file during jest unit testing,"<p>During unit testing, I am getting undefined error, while executing svelte component with json file.</p>
<p><strong>Restaurant.svelte :</strong></p>
<pre><code>import data from '../Data/restaurants.json';
console.log(data);
let finalData = data.restaurants;
</code></pre>
<p><strong>restaurant.spec.js :</strong></p>
<pre><code>import Restaurant from './../routes/Restaurant.svelte';
import { render, screen, fireEvent } from &quot;@testing-library/svelte&quot;;


describe(&quot;Restaurants Home Page&quot;,()=&gt;{
    it(&quot;Tests for Header&quot;,()=&gt;{
        render(Restaurant);
        const resheader = screen.getByText(&quot;Restaurants&quot;);
        expect(resheader).toBeVisible();
    })
})
</code></pre>
<p><strong>Jest Config File :</strong></p>
<pre><code>{
    &quot;transform&quot;: {
      &quot;^.+\\.js$&quot;: &quot;babel-jest&quot;,
      &quot;^.+\\.svelte$&quot;: &quot;svelte-jester&quot;,
      &quot;.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$&quot;: &quot;jest-transform-stub&quot;
    },
    &quot;moduleFileExtensions&quot;: [&quot;svelte&quot;, &quot;js&quot;, &quot;json&quot;],
    &quot;transformIgnorePatterns&quot;: [&quot;node_modules/(?!(svelte-spa-router|svelte-i18n)/)&quot;],
    &quot;testEnvironment&quot;: &quot;jsdom&quot;,
    &quot;setupFilesAfterEnv&quot;: [&quot;@testing-library/jest-dom/extend-expect&quot;],
    &quot;moduleDirectories&quot;: [
      &quot;node_modules&quot;,
      &quot;src&quot;
    ],
    &quot;moduleNameMapper&quot;: {
      &quot;src/(.*)&quot;: &quot;&lt;rootDir&gt;/src/Data&quot;
    }    
}

</code></pre>
<p><strong>Error Msg:</strong>
TypeError: Cannot read properties of undefined (reading 'restaurants')</p>
<pre><code>   7 |
   8 |     console.log(data);
&gt;  9 |     let finalData = data.restaurants;
</code></pre>
",https://stackoverflow.com/questions/72097867/svelte-not-able-to-fetch-data-from-json-file-during-jest-unit-testing,"['unit-testing', 'jestjs', 'svelte', 'sveltekit', 'svelte-testing-library']",336,False,1,1
I&#39;m trying to unit test this service but keep getting a Error: connect ECONNREFUSED 127.0.0.1:80,"<p>My test describe block is the following</p>
<pre><code>describe('WorkrampService', () =&gt; {
  let workrampService: WorkrampService;
  let phdbService: PhdbService;

  beforeEach(async () =&gt; {
    const module = await Test.createTestingModule({
      providers: [WorkrampService, PhdbService],
    }).compile();

    workrampService = module.get(WorkrampService);
    phdbService = module.get(PhdbService);
  });

  describe('getWorkrampUsers', () =&gt; {
    it('calls WorkrampService.getWorkrampsUsers and returns the result', async () =&gt; {
      const result = await workrampService.getWorkrampUsers()
      console.log(result);
      expect(result).toBeDefined();
    });
  });
});
</code></pre>
<p>and this is what the original service looks like</p>
<pre><code>async getWorkrampUsers() {
    try {
      const { data } = await this.workrampAPI.get('/users?includeDeleted=true');
      return data;
    } 
    catch (e) {
      this.logger.error(e);
      throw new NotFoundException('Could not fetch Workramp users.');
    }
  }
</code></pre>
<p>when i run the endpoint for that function it works as it should but i keep getting the connection error message when running the spec.ts file. my goal is to compare the resulting array of users but right now i'm just looking to console.log the result and make sure that it is defined</p>
<p>I'm new to unit testing and could really use some help, I've seen a few videos of unit testing nestjs but they always mock a repository which my project doesn't have.</p>
",https://stackoverflow.com/questions/74404776/im-trying-to-unit-test-this-service-but-keep-getting-a-error-connect-econnrefu,"['unit-testing', 'jestjs', 'nestjs']",9,False,0,0
Testing Vue.js With Jasmine Not Using JS Modules,"<p>I've been asked to research unit testing Javascript on a legacy app that does not use JS modules (import/export). The app has JS object/prototypes in external .js files that are included via script src and more recently some Vue 2 components in .vue files using PHP include('mycomponent.vue').</p>
<p>All the examples for various unit testing frameworks assume JS modules are used. Can Vue be tested without modules?</p>
<p>I'm a bit lost and I am looking for direction, advice, and/or code examples of tests.</p>
<p>Thanks. Your help is much appreciated.</p>
<p>Here is a sample component:</p>
<p>PHP view (.phtml)</p>
<pre><code>&lt;?php include 'mycomponent.vue' ?&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
    Vue.use(Vuex);
    Vue.use(BootstrapVue);
    Vue.component('v-select', VueSelect.VueSelect);

    const i18n = new VueI18n({
        locale: 'en',
        dateTimeFormats: {
            en: {
                long: {
                    year: 'numeric', month: 'long', day: 'numeric',
                    hour: 'numeric', minute: 'numeric',
                    timezone: 'EST',
                },
            },
        },
        messages: {
            en: &lt;?= json_encode([
                'messages' =&gt; 'etc'
            ]) ?&gt;,
        }
    });

    const store = new Vuex.Store({
        state: {
            //etc
        }
    });

    new Vue({
        el: '#wrapper',
        store,
        i18n,
        data() {
            return &lt;?= json_encode([
                'something' = [
                bits: 'Bob'
                ]
            ]) ?&gt;;
        },
    });
&lt;/script&gt;

&lt;div id=&quot;wrapper&quot; v-cloak&gt;
    &lt;mycomponent
        :something=&quot;something&quot;
    &gt;&lt;/mycomponent&gt;
&lt;/div&gt;
</code></pre>
<p>mycomponent.vue</p>
<pre><code>&lt;template id=&quot;mycomponent_tmpl&quot;&gt;
  &lt;div&gt;
    {{currentMessage}}
  &lt;/div&gt;
&lt;/template&gt;



&lt;script&gt;
Vue.component('mycomponent', {
  template: '#mycomponent_tmpl',

  props: {
    something: {
      type: Object,
      required: true,
    }
  },

  data() {
    return {
        this.message = 'Hello World'
    }
  },

  created() {
    
  },

  mounted() {

  },

  watch: {

  },

  computed: {
    currentMessage() {
        return this.message + ' ' + this.something.bits;
    }
  },

  methods: {
    
  }
});
&lt;/script&gt;
</code></pre>
",https://stackoverflow.com/questions/73080408/testing-vue-js-with-jasmine-not-using-js-modules,"['javascript', 'vue.js', 'testing', 'jasmine']",81,True,0,1
how to call async function assinged to object in node.js,"<p>In value of below AWS Lambda code the call of options.ensurePrivateKeyForApi should wait for a return value but looks like it is not. Turns out the code is not waiting but using await in front gives error.<br />
Logic is as follows: If the global variable apiKey is not holding a value it should go to AWS SecretsManager and pick up the secret and move it to the global variable (in order to avoid frequent calls to SecretsManager).<br />
For unit testing purposes I moved the async function to the options object that will be replaced for unit testing.</p>
<p>How can I make it wait?</p>
<pre><code>var apiPrivateKey;

function setPrivateKey(secretString) {
  apiPrivateKey = secretString;
}

async function ensurePrivateKeyForApi() {
  if (!(typeof apiPrivateKey === &quot;string&quot; || apiPrivateKey instanceof String) {
    let secret = await secretsManager.getSecretValue({
      SecretId: process.env.JWT_SECRET_NAME
    }).promise();
    setPrivateKey(secret.SecretString);
  }
}
var options = {
  ensurePrivateKeyForApi
};

function handler(event, context, callback) {
  //...
  
  options.ensurePrivateKeyForApi(); // that line should wait but compiler complains about await
  console.log(&quot;secret &quot; + apiPrivateKey); // secret is always undefined
}

module.exports = {
  handler,
  options,
  setPrivateKey
};
</code></pre>
",https://stackoverflow.com/questions/71377920/how-to-call-async-function-assinged-to-object-in-node-js,['node.js'],25,False,0,0
Can I mock tensorflow import while testing?,"<p>Importing TensorFlow can take quite a while. Is there a way to mock or ignore TensorFlow while unit-testing functions on the same file that does not depend on TensorFlow?</p>
",https://stackoverflow.com/questions/72617073/can-i-mock-tensorflow-import-while-testing,"['unit-testing', 'tensorflow', 'testing', 'pytest']",124,False,0,0
What is the function of unit test in jira software,"<p><a href=""https://i.stack.imgur.com/zlKZs.jpg"" rel=""nofollow noreferrer"">enter image description here</a></p>
<p>While working on the team project, I saw that cumin software has an option called unit testing. I want to know how to work with this option.</p>
",https://stackoverflow.com/questions/70570392/what-is-the-function-of-unit-test-in-jira-software,"['reactjs', 'babeljs', 'create-react-app', 'babel-loader']",90,False,1,1
sortableData break the testing,"<p>I have next snippet in my html</p>
<pre><code>&lt;tbody [sortableData]=&quot;myData&quot;&gt;...&lt;/tbody&gt;
</code></pre>
<p>receiving next error on unit testing</p>
<pre><code> Template parse errors:
    Can't bind to 'sortableData' since it isn't a known property of 'tbody'. (&quot;
                  &lt;/tr&gt;
                &lt;/thead&gt;
              &lt;tbody [ERROR -&gt;][sortableData]=&quot;myData&quot; &gt; ...
</code></pre>
<p>It looks like I need to import some module, but I don't understand which one. Any thoughts?</p>
",https://stackoverflow.com/questions/72636703/sortabledata-break-the-testing,"['angular', 'unit-testing', 'angular-test']",15,False,-1,1
php unit testing problem in phpunit.xml file,"<p>working with php unit testing and My phpunit.xml file is like this</p>
<pre><code>&lt;?xml version=&quot;1.0&quot;  encording=&quot;UTF-8&quot; ?&gt;

&lt;phpunit bootstrap=&quot;vendor/autoload.php&quot;&gt;

    &lt;testsuits&gt;
    
         &lt;testsuit name=&quot;unit&quot;&gt;
         
             &lt;directory&gt;tests&lt;/directory&gt;
         
         &lt;/testsuit&gt;
    
    &lt;/testsuits&gt;

&lt;/phpunit&gt;
</code></pre>
<p>but when i execute following running command <code>vendor/bin/phpunit</code> compiler got following error messages
<code>Could not load &quot;C:\Users\Orukawa\Desktop\phpunittest\phpunit.xml&quot;.</code>
<code>parsing XML declaration: '?&gt;' expected</code></p>
<p>how could I fix this prob?</p>
",https://stackoverflow.com/questions/70549706/php-unit-testing-problem-in-phpunit-xml-file,"['php', 'xml', 'phpunit']",316,False,-2,1
React this.inputReference?.current?.click(); testcase,"<p>I am working on Unit testing in react. I need to write test case for</p>
<pre><code>private onClick = () =&gt; {
    this.inputReference?.current?.click();
  };
</code></pre>
<p>I am calling this function in my custom button</p>
<pre><code>&lt;CustomButtons
 text='Browse'
 onClick={this.onClick}/&gt;
</code></pre>
<p>Please guide me how to do that.</p>
",https://stackoverflow.com/questions/74152312/react-this-inputreference-current-click-testcase,"['unit-testing', 'jestjs', 'react-tsx']",10,False,0,0
Writing data using Moq.EntityFrameworkCore,"<p>I'm attempting to use <a href=""https://github.com/MichalJankowskii/Moq.EntityFrameworkCore"" rel=""nofollow noreferrer"">Moq.EntityFrameworkCore</a> for unit testing. I'm having no problem with query operations that read the pre-seeded data. However write operations initially appear to work without throwing any exceptions but the underlying <code>DbSet</code>'s don't reflect any newly added records. Any ideas what I may be missing to moq the write operations?</p>
<p>My moq db context setup code:</p>
<pre><code>var dbContextMock = new Mock&lt;MyDbContext&gt;();

var submitterOperators = new List&lt;SubmitterOperator&gt;();
submitterOperators.Add(
    fixture.Build&lt;SubmitterOperator&gt;()
        .With(e =&gt; e.Deleted, false)
        .Without(e =&gt; e.Operation)
        .Create()
);
dbContextMock.Setup(x =&gt; x.SubmitterOperators).ReturnsDbSet(submitterOperators);

return dbContextMock.Object;
</code></pre>
<p>Code that tries to insert a new entity, that works successfully against an actual non-moq'd database:</p>
<pre><code>await _dataContext.SubmitterOperators.AddAsync(entity);
await _dataContext.SaveChangesAsync();
</code></pre>
<p>But doesn't actually change the moq'd <code>DbSet&lt;SubmitterOperator&gt;</code> when unit testing.</p>
<p>I imagine I'm missing some scaffolding somewhere setting up my <code>dbContextMock</code> but I haven't found any examples to follow online around moq'ing data writes.</p>
",https://stackoverflow.com/questions/70935354/writing-data-using-moq-entityframeworkcore,"['c#', '.net', 'moq', 'xunit']",404,False,2,0
How can i define and declare value for JsonReader reader in the below function for unit testing,"<p>this is the function i am trying to test</p>
<pre><code>   /// &lt;summary&gt;
        ///     Reads the JSON representation of the object.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;reader&quot;&gt;The &lt;see cref=&quot;T:Newtonsoft.Json.JsonReader&quot; /&gt; to read from.&lt;/param&gt;
        /// &lt;param name=&quot;objectType&quot;&gt;Type of the object.&lt;/param&gt;
        /// &lt;param name=&quot;existingValue&quot;&gt;The existing value of object being read.&lt;/param&gt;
        /// &lt;param name=&quot;serializer&quot;&gt;The calling serializer.&lt;/param&gt;
        /// &lt;returns&gt;
        ///     The object value.
        /// &lt;/returns&gt;
        /// &lt;exception cref=&quot;NotImplementedException&quot;&gt;&lt;/exception&gt;
        public override object ReadJson(
            JsonReader reader,
            Type objectType,
            object existingValue,
            JsonSerializer serializer)
        {
            return System.DateTime.Parse(reader.Value.ToString());
        }
</code></pre>
<p>this is what i have tried to write for unit testing.
please explain and write how do i define and declare <strong>JsonReader reader</strong></p>
<pre><code>public void DateTimeConverterTests()
        {
            string json = @&quot;{ &quot;&quot;Date&quot;&quot; : &quot;&quot;09/12/2013&quot;&quot; }&quot;;

            object obj = JsonConvert.DeserializeObject&lt;Object&gt;(json,
                new IsoDateTimeConverter { DateTimeFormat = &quot;dd/MM/yyyy&quot; });
            System.DateTime dateTime = new System.DateTime(2008, 3, 1, 7, 0, 0);
            
          
            JsonReader reader;// this one because it give error without declaration
            JsonSerializer serializer;
            serializer = new JsonSerializer();
            existingValue = Substitute.For&lt;object&gt;();

        
            ReadJson(reader, dateTime.GetType(), obj, serializer);
           
        }
</code></pre>
",https://stackoverflow.com/questions/73320050/how-can-i-define-and-declare-value-for-jsonreader-reader-in-the-below-function-f,"['c#', 'json']",129,False,0,0
Assert.AreSame is not working for okObject result even when the objects are same,"<p>I have the following code for a Unit test.I'm using <code>Mock</code> library for unit testing.
Even when the objects are the same, the assert call fails.</p>
<pre><code>  var service = new Mock&lt;IRiskAssetProxyService&gt;();
            var controller = new AssetProxyController(service.Object);
            List&lt;AssetProxyWrapper&gt; mockAssetProxyMappings = new List&lt;AssetProxyWrapper&gt;();
            AssetProxyWrapper awrapper1 = new AssetProxyWrapper
            {

                assetProxyMapping = new AssetProxyMapping
                {
                    AssetId = &quot;testasset&quot;,
                    IsActive = true,
                    ProxyAssetId = &quot;testproxy&quot;,
                    AssetIdType = &quot;testtype&quot;,
                    testcode= &quot;testcode&quot;,
                    ProxyAssetIdType = &quot;testproxytype&quot;
                },
                myCodes = new List&lt;string&gt; { &quot;test&quot;}
            };
            mockAssetProxyMappings.Add(awrapper1);

            OkObjectResult okResult = new OkObjectResult(mockAssetProxyMappings);            
            service.Setup(service =&gt; service.GetAllAssetProxyMapping()).Returns(mockAssetProxyMappings);

            var result = controller.GetAll() ;
     
            Assert.AreSame(okResult, result);
</code></pre>
<p>What i'm i doing wrong? Please advice.</p>
",https://stackoverflow.com/questions/71778684/assert-aresame-is-not-working-for-okobject-result-even-when-the-objects-are-same,"['c#', 'asp.net', 'unit-testing']",127,False,0,0
"xUnit general repository testing of add, update, delete","<p>Is it worth unit testing the repository add, update or delete methods, please?</p>
<pre><code>public void Update(TEntity entity)
{
    dbSet.Update(entity);
}
</code></pre>
<p>and usage:</p>
<pre><code>UnitOfWork.NeakReports.Update(neakReport);
</code></pre>
<p>I ask because everything is moqed so I do not know if it is a must then how.</p>
",https://stackoverflow.com/questions/70698115/xunit-general-repository-testing-of-add-update-delete,"['c#', 'repository', 'moq', 'xunit']",162,True,1,1
"xUnit general repository testing of add, update, delete","<p>Is it worth unit testing the repository add, update or delete methods, please?</p>
<pre><code>public void Update(TEntity entity)
{
    dbSet.Update(entity);
}
</code></pre>
<p>and usage:</p>
<pre><code>UnitOfWork.NeakReports.Update(neakReport);
</code></pre>
<p>I ask because everything is moqed so I do not know if it is a must then how.</p>
",https://stackoverflow.com/questions/70698115/xunit-general-repository-testing-of-add-update-delete,"['c#', 'repository', 'moq', 'xunit']",162,True,1,1
Angular Jasmine testing - substring remove from number,"<p>I have some difficulties in unit testing a function. I'm new in these things and I don't know what I can do.
I have to those 2 if.</p>
<p>Any advice? Thank you.</p>
",https://stackoverflow.com/questions/72138561/angular-jasmine-testing-substring-remove-from-number,"['angular', 'unit-testing', 'testing', 'jasmine', 'karma-jasmine']",244,True,0,1
Avoiding circular template,"<p>I am unit-testing a class <code>TestingThis</code>, containing a socket which is templated on <code>TestingThis</code> (for callbacks):</p>
<pre><code>class TestingThis
{
    TestingThis() : _socket(*this){}

    Socket&lt;SocketType, TestingThis&gt; _socket;
};
</code></pre>
<p>However, for unit testing I'd like to mock the socket, so make the socket type a template parameter of <code>TestingThis</code>:</p>
<pre><code>template&lt;class SOCKET&gt;
class TestingThis
{
    TestingThis() : _socket(*this){}

    SOCKET _socket;
};
</code></pre>
<p>but because the production socket is already templated on <code>TestingThis</code>, when I instantiate <code>TestingThis</code> it will have an infinite recursion in the template parameters:</p>
<pre><code>TestingThis&lt;Socket&lt;SocketType, TestingThis&lt;Socket&lt;.......repeats forever......&gt;&gt;&gt;&gt; productionInstance;

                                               ^ this is the problem
</code></pre>
<p>What's the best way to handle this?</p>
<p>UPDATE</p>
<p>Okay I've managed to get to a point where I can do:</p>
<pre><code>TestingThis&lt;Socket, NoSSL&gt; production;
TestingThis&lt;Socket, OpenSSL&gt; production;
TestingThis&lt;Socket, AnotherSSL&gt; production;
</code></pre>
<p>However, for testing the implementation doesn't really matter and it would make more sense to instantiate like this:</p>
<pre><code>TestingThis&lt;MockSocket&gt; testing;
</code></pre>
<p>with production passing the socket implementation as a further parameter:</p>
<pre><code>TestingThis&lt;Socket&lt;NoSSL&gt;&gt; production;
TestingThis&lt;Socket&lt;OpenSSL&gt;&gt; production;
TestingThis&lt;Socket&lt;AnotherSSL&gt;&gt; production;
</code></pre>
",https://stackoverflow.com/questions/73094868/avoiding-circular-template,"['c++', 'templates']",33,True,1,1
What exactly to unit test in frontend frameworks? Template vs class,"<p>I have a general question regarding unit testing of modern frontend frameworks with example in Angular.</p>
<p>I have a bunch of methods which return boolean, which are used both in the class and in the template.</p>
<pre><code>amICo3pmCompany({ company3pmid }: Request3pmResponse.AsObject): boolean {
    return company3pmid === this.userService.getUserInfo()?.company?.id;
}

noActiveAgreement(request: Request3pmResponse.AsObject) {
    return (
        !request.id ||
        (!this.amICo3pmCompany(request) &amp;&amp;
            ![Request3pmStatus.INVITED, Request3pmStatus.CONFIRMED].includes(request.status) &amp;&amp;
            this.wallet.mandatory3pmstatus !== Mandatory3pmStatus.AWAITING_FUNDS)
    );
}
</code></pre>
<p>and template:</p>
<pre><code>&lt;atm-third-party-mandate-agreement
    *ngIf=&quot;noActiveAgreement(request); else requestExists&quot;
&gt;&lt;/atm-third-party-mandate-agreement&gt;

&lt;ng-template #requestExists&gt;
    &lt;ng-container *ngIf=&quot;amICo3pmCompany(request); else non3pmCompany&quot;&gt;
        &lt;atm-third-party-mandate-company-co3pm
        &gt;&lt;/atm-third-party-mandate-company-co3pm&gt;
    &lt;/ng-container&gt;

    &lt;ng-template #non3pmCompany&gt;
        &lt;atm-third-party-mandate-company-c
        &gt;&lt;/atm-third-party-mandate-company-c&gt;
    &lt;/ng-template&gt;
&lt;/ng-template&gt;
</code></pre>
<p>What exactly should I unit test? Unit testing by the definition means we should test the atomic parts of the app, hence class methods. But frontend apps' main goal is to show user some stuff, so it's important to check whether components are rendered properly, based on some combination of methods and checks.</p>
<p>So should I test only the template, only the component class or both of them in my unit test?</p>
",https://stackoverflow.com/questions/72740674/what-exactly-to-unit-test-in-frontend-frameworks-template-vs-class,"['angular', 'unit-testing']",51,False,1,1
vue.config.js configureWebpack not used in unit tests (vue 3),"<p>In my vue config I have the following:</p>
<pre><code>configureWebpack: {
  resolve: {
    alias: {
      react: path.resolve(__dirname, 'composition/react'),
      hooks: path.resolve(__dirname, 'composition'),
    },
  },
},
</code></pre>
<p>In my component I have the following:</p>
<pre><code>import { useEffect, useState } from 'react';
</code></pre>
<p>This is so I can re use some of the Vue code in React projects. This works when running and building the project but not when testing. When unit testing I get the error: <code>Cannot find module 'react' from 'useCategories.js'</code>, the above import is from useCategories.</p>
<p>The following is in the jest.config.js:</p>
<pre><code>module.exports = {
  preset: '@vue/cli-plugin-unit-jest',
  transform: {
    '^.+\\.vue$': 'vue-jest'
  }
}
</code></pre>
<p>If unit testing in vue is ignoring values from vue.config.js then how can I set the webpack path resolve values for testing. I would rather not repeat these values but if it's a JavaScript file I guess I can import it from the same file in different configs.</p>
",https://stackoverflow.com/questions/71155594/vue-config-js-configurewebpack-not-used-in-unit-tests-vue-3,"['javascript', 'vue.js', 'vuejs3', 'vue-test-utils']",394,True,1,1
How to unit test newrelic go agent,"<p>I am new to golang and newrelic.</p>
<p>as part of my work i am migrating newrelic go agent to V3 Version.</p>
<p>But I am facing the problem in the below situation.</p>
<p>while doing unit testing<br />
existing go agent
1.we are able to fake application and fake newrelic transcation.
2.so we were able to count the number of calls to StartSegmentNow</p>
<p>but with the new version of the go agent</p>
<ol>
<li>I am unable to fake the transaction so I can't count on the StartSegment</li>
<li>how to mock the newrelic go agent for unit-testing?
could you please help me with how can I unit test the newrelic transaction using golang</li>
</ol>
",https://stackoverflow.com/questions/72378426/how-to-unit-test-newrelic-go-agent,"['go', 'newrelic']",352,False,1,0
Refactoring multiple if-else,"<p>I'm performing a business logic but the way I have implemented it, looks a bit convoluted and makes unit testing harder. How do I break down this logic into easier unit-testable tiny methods?</p>
<pre><code>public async Task&lt;ResultTypes&gt; ValidatePinAsync(int id, string pin)
{
    ICustomer customer = await _repository.GetCustomer(id);

    if (customer.PinDisabled)
        return ResultTypes.PinDisabled;

    if (string.IsNullOrEmpty(customer.PinNumber))
    {
        customer.PinNumber = customer.DoB.ToString();

        //perform repository call to update PIN here?

        if (customer.PinNumber == pin)
        {
            return ResultTypes.Success;
        }
        else
        {
            //perform repository call to update failure count and then return disabled or invalid
            return ResultTypes.InvalidPinEntered;
        }
    }

    if (customer.PinNumber == pin)
    {
        return ResultTypes.Success;
    }
    else
    {
        //perform repository call to update failure count and then return disabled or invalid
    }

    return ResultTypes.Success;
}
</code></pre>
",https://stackoverflow.com/questions/74809734/refactoring-multiple-if-else,"['c#', 'refactoring']",65,True,1,2
Unit testing dynamic imports in node js using jest,"<p>Does anybody know how to unit test the dynamic import in node js application. Iam unable to cover the function statement while unit testing using jest.</p>
<p>And the dynamic import statement looks like this:<br></p>
<p><code>fetch = (...args) =&gt; import('node-fetch').then(({ default: fetch }) =&gt; fetch(...args));</code></p>
",https://stackoverflow.com/questions/72432754/unit-testing-dynamic-imports-in-node-js-using-jest,"['node.js', 'unit-testing', 'jestjs', 'code-coverage', 'dynamic-import']",624,False,1,0
Jest encountered an unexpected token,"<p>I am new to unit testing. I use <code>react typescript</code>
I wrote a unit test that fails at the first line, because of <code>import</code>.
How can I config this to work ?</p>
<p><strong>error</strong> :</p>
<pre><code>Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

Details:

/app/node_modules/axios/index.js:1
({&quot;Object.&lt;anonymous&gt;&quot;:function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';                                                                                  ^^^^^^

SyntaxError: Cannot use import statement outside a module

&gt; 1 | import {AxiosError, AxiosInstance, AxiosResponse} from &quot;axios&quot;;
</code></pre>
<p><strong>config</strong> :
package.json</p>
<pre><code>&quot;devDependencies&quot;: {
        &quot;@babel/core&quot;: &quot;^7.20.7&quot;,
        &quot;@testing-library/dom&quot;: &quot;^8.19.1&quot;,
        &quot;@testing-library/react&quot;: &quot;^13.4.0&quot;,
        &quot;@types/testing-library__react&quot;: &quot;^10.2.0&quot;,
        &quot;autoprefixer&quot;: &quot;^10.4.13&quot;,
        &quot;babel-jest&quot;: &quot;^29.3.1&quot;,
        &quot;eslint&quot;: &quot;8.30.0&quot;,
        &quot;eslint-config-react-app&quot;: &quot;^7.0.1&quot;,
        &quot;jest&quot;: &quot;^29.3.1&quot;,
        &quot;jest-environment-jsdom&quot;: &quot;^29.3.1&quot;,
        &quot;postcss&quot;: &quot;^8.4.20&quot;,
        &quot;postcss-import&quot;: &quot;^15.1.0&quot;,
        &quot;prettier&quot;: &quot;^2.8.1&quot;,
        &quot;prettier-plugin-tailwindcss&quot;: &quot;^0.2.1&quot;,
        &quot;react-test-renderer&quot;: &quot;^18.2.0&quot;,
        &quot;tailwindcss&quot;: &quot;^3.2.4&quot;,
        &quot;ts-jest&quot;: &quot;^29.0.3&quot;
    }
</code></pre>
<p>balel.config.js:</p>
<pre><code>module.exports = {
    presets: [
        [
            '@babel/preset-env',
            {
                targets: {
                    node: 'current',
                },
            },
        ],
    ],
};

</code></pre>
<p>jest.config.js</p>
<pre><code>/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
    preset: &quot;ts-jest&quot;,
    testEnvironment: &quot;jsdom&quot;,
    transform: {
        '^.+\\.ts?$': 'ts-jest',
    },
    transformIgnorePatterns: ['&lt;rootDir&gt;/node_modules/'],
};

</code></pre>
",https://stackoverflow.com/questions/74952120/jest-encountered-an-unexpected-token,"['reactjs', 'typescript', 'jestjs']",711,True,0,2
dependency injection for creating knex instance enabling db access to be mocked in tests,"<p>Looking for typescript sample code for creating knex database instance through dependency injection. Goal is to mock knex in unit testing and not hardwiring knex instance in the DAO files for data acccess</p>
",https://stackoverflow.com/questions/71218836/dependency-injection-for-creating-knex-instance-enabling-db-access-to-be-mocked,"['dependency-injection', 'jest-fetch-mock', 'knex.js']",128,False,0,1
Unit Testing in Asp.Net MVC project,"<p>I am a newbie to write a unit testing please provide the guidance on what is the unit test for  the following simple structure which may be passed in TestResult in VS 2019???</p>
<pre><code>public ActionResult About()
{
    ViewBag.Message = &quot;Your application description page.&quot;;
    return View();
}
</code></pre>
",https://stackoverflow.com/questions/72839248/unit-testing-in-asp-net-mvc-project,"['c#', 'unit-testing', 'asp.net-core-mvc']",43,True,0,1
Unit Testing for EventEmitter with Jest,"<p>I'm new to unit testing as a whole and especially new with javascript. I'm working on some unit testing with Jest and I came across this one script that doesn't make much sense to me. But, I figured I'd try to write a test for it.</p>
<p>I am completely new to this so even learning about EventEmitter is throwing me off. I did read that you have to call, in this case, newCommandEmitter but this script doesn't have that at all. It's just three lines.</p>
<p>Code is below, but I want to know, is this even worth writing a test for?</p>
<pre><code>const EventEmitter = require('events')
const newCommandEmitter = new EventEmitter()
module.exports = newCommandEmitter
</code></pre>
<p>My test script is as follows:</p>
<pre><code>const newCommandEmitter = require(&quot;./newCommandEmitter.js&quot;);
const events = require(&quot;events&quot;);

jest.mock(&quot;./newCommandEmitter.js&quot;);
jest.mock(&quot;events&quot;)

describe(&quot;Testing for events if command is used for events.&quot;, () =&gt; {

    test(&quot;First test to see if we get events data.&quot;, async () =&gt; {

        expect(newCommandEmitter).toBeTruthy();
    });
});
</code></pre>
",https://stackoverflow.com/questions/72737898/unit-testing-for-eventemitter-with-jest,"['javascript', 'node.js', 'jestjs', 'eventemitter']",336,True,0,1
Is there a utPLSQL way to mock dependencies like in other unit testing frameworks?,"<p>In tSQLt, you can isolate dependencies for unit testing using procedures like FakeTable to create a dummy version of whatever your test subject depends on, that contains only data you specify. This is just like using Justmock or Moq in .NET unit testing.</p>
<p>The only thing remotely close to this that I've seen for utPLSQL is copying the dependencies to a temp version in the setup procedure, creating the dummy version manually, and then replacing it with the temp version in the teardown, all using EXECUTE IMMEDIATE.</p>
<p>Is there a more convenient way to do this, short of just creating a procedure to do this myself?</p>
",https://stackoverflow.com/questions/74793290/is-there-a-utplsql-way-to-mock-dependencies-like-in-other-unit-testing-framework,"['oracle', 'unit-testing', 'plsql', 'utplsql']",49,False,0,0
Unit Tests Mock ControllerContext HttpContext No service for type &#39;Microsoft.AspNetCore.Mvc.View...ITempDataDictionaryFactory&#39; has been registered,"<p>In my test project i am using xUnit with Moq.</p>
<p>now i want to unit test these piece of code in the controller:</p>
<pre><code>[HttpGet]
[AllowAnonymous]
public async Task&lt;IActionResult&gt; Login(string returnUrl = null)
{
    await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

    ViewData[&quot;ReturnUrl&quot;] = returnUrl;
    return View();
}
</code></pre>
<p>As you see it uses the <code>SignOutAsync</code> of the <code>HttpContext</code>.</p>
<p>I tried so many solution such as <a href=""https://stackoverflow.com/questions/3661722/asp-net-mvc-unit-testing-mocking-httpcontext-without-using-any-mock-framework"">ASP.NET MVC - Unit testing, mocking HttpContext without using any mock framework</a> but didn't work for me, since i dont have access to the <code>HttpRequestBase</code></p>
<p>Using Moq, i am trying to mock this <code>HttpContext</code>, so i tried this:</p>
<pre><code>public static Mock&lt;HttpContext&gt; GenerateFakeHttpContext()
{
   var mockHttpContext = new Mock&lt;HttpContext&gt;();
   var authServiceMock = new Mock&lt;IAuthenticationService&gt;();
   authServiceMock.Setup(_ =&gt; _.SignOutAsync(
                                   It.IsAny&lt;HttpContext&gt;(), 
                                   It.IsAny&lt;string&gt;(), 
                                   It.IsAny&lt;AuthenticationProperties&gt;()))
       .Returns(Task.FromResult((object)null));

   var serviceProviderMock = new Mock&lt;IServiceProvider&gt;();

   serviceProviderMock.Setup(_ =&gt; _.GetService(typeof(IAuthenticationService)))
           .Returns(authServiceMock.Object);

   mockHttpContext.Setup(x =&gt; x.RequestServices)
           .Returns(serviceProviderMock.Object);

   return mockHttpContext;
}
</code></pre>
<p>inspired from this question :
<a href=""https://stackoverflow.com/questions/71168289/mstest-unit-testing-httpcontext-signoutasync-for-the-logout/71168290#71168290"">MSTest: Unit Testing HttpContext.SignoutAsync for the logout</a>, after a multiple research.</p>
<p>The test method is like this:</p>
<pre><code>public async Task Login_ShouldSignOutToClearCoockies_WhenReturnUrlIsNullOrNotNull()
{
    //Arrange
    _sutAccountController
    .ControllerContext.HttpContext = TestsHelper.GenerateFakeHttpContext().Object;

    //Act
    var result = await _sutAccountController.Login(null);

    //Assert
    result.Should().NotBeNull();
}
</code></pre>
<p>but in runtime i get this exception:</p>
<pre><code>   Duration: 367 ms

  Message: 
System.InvalidOperationException : No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has been registered.

  Stack Trace: 
ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
Controller.get_TempData()
Controller.View(String viewName, Object model)
Controller.View(String viewName)
Controller.View()
AccountController.Login(String returnUrl) line 38
AccountControllerTests.Login_ShouldSignOutToClearCoockies_WhenReturnUrlIsNullOrNotNull() line 46
--- End of stack trace from previous location ---
</code></pre>
<p>if there's a better way to mock the <strong>HttpContext</strong>.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/73149914/unit-tests-mock-controllercontext-httpcontext-no-service-for-type-microsoft-asp,"['c#', 'asp.net', 'unit-testing', 'moq', 'xunit']",818,True,0,1
What is the difference between &#39;describe&#39; and &#39;test&#39; in Jest?,"<p>I have just start learning unit testing in <strong>Vue.js</strong> using <strong>Jest</strong>, and I want to know when to use <strong>describe</strong> and when to use <strong>test</strong> ?</p>
<p><strong>TodoApp.vue</strong> Component :</p>
<pre><code>&lt;template&gt;
  &lt;div&gt;
    &lt;h1&gt;TodoApp Componenent&lt;/h1&gt;
    &lt;div v-for=&quot;todo in todos&quot; :key=&quot;todo.id&quot; data-test=&quot;todo&quot;&gt;
      {{ todo.text }}
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default {
  name: &quot;TodoApp&quot;,
  data() {
    return {
      todos: [
        {
          id: 1,
          text: 'Learn Vue.js 3',
          completed: false
        }
      ]
    }
  }
};
&lt;/script&gt;

&lt;style scoped&gt;
&lt;/style&gt;
</code></pre>
<p><strong>TodoApp.spec.js</strong></p>
<p><strong>1#</strong> Unit test using <code>test</code></p>
<pre><code>import { mount } from '@vue/test-utils'
import TodoApp from '@/components/TodoApp'

test('renders a todo', () =&gt; {
  const wrapper = mount(TodoApp)

  const todo = wrapper.get('[data-test=&quot;todo&quot;]')

  expect(todo.text()).toBe('Learn Vue.js 2')
})
</code></pre>
<p><strong>2#</strong> Unit test using <code>describe</code></p>
<pre><code>import { mount } from '@vue/test-utils'
import TodoApp from '@/components/TodoApp'

describe('TodoApp', () =&gt; {
  it('renders a todo', () =&gt; {
    const wrapper = mount(TodoApp)

    const todo = wrapper.get('[data-test=&quot;todo&quot;]')
  
    expect(todo.text()).toBe('Learn Vue.js 2')
  })
})
</code></pre>
",https://stackoverflow.com/questions/73571462/what-is-the-difference-between-describe-and-test-in-jest,"['javascript', 'vue.js', 'unit-testing', 'jestjs']",579,True,2,2
Prisma Jest tests return undefined,"<p>I'm transitioning from TypeORM to Prisma. All of my until test Prisma functions are returning <code>undefined</code>. I'm using dependency injection from <a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""nofollow noreferrer"">https://www.prisma.io/docs/guides/testing/unit-testing</a></p>
<pre><code>      const mockCtx2 = createMockContext()
      const ctx2 = mockCtx2 as unknown as Context
      console.log(&quot;createDummyUser&quot;)
      console.log(ctx2)
      console.log(ctx2.prisma)
      console.log(ctx2.prisma.users)
</code></pre>
<p>returns</p>
<pre><code>  console.log
    { prisma: { _isMockObject: true } }

      at test/userService.test.ts:889:15

  console.log
    { _isMockObject: true }

      at test/userService.test.ts:890:15

  console.log
    [Function: mockConstructor] {
      _isMockFunction: true,
      getMockImplementation: [Function (anonymous)],
      mock: [Getter/Setter],
      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)],
      calledWith: [Function (anonymous)],
      _isMockObject: true
    }

</code></pre>
<p>All of my requests return <code>undefined</code></p>
<pre><code>const allUsers1 = await ctx2.prisma.users.findMany()
      console.log(allUsers1)
</code></pre>
<p><strong>UPDATE</strong></p>
<pre><code>import prisma from '../client'

const u = await prisma.users.findMany()
console.log(&quot;****&quot;)
console.log(u)
</code></pre>
<p>client.ts</p>
<pre><code>import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()
export default prisma
</code></pre>
",https://stackoverflow.com/questions/74103837/prisma-jest-tests-return-undefined,"['jestjs', 'prisma']",27,False,1,0
Using toString() in Hardhat,"<pre><code>
function rewardPerToken() public view returns (uint) {
        if (totalSupply == 0) {
            return rewardPerTokenStored;
        }
        return
            rewardPerTokenStored +
            (((block.timestamp - lastUpdateTime) * rewardRate * 1e18) / totalSupply);
    }

</code></pre>
<pre><code>      describe(&quot;rewardPerToken&quot;, () =&gt; {
            it(&quot;Returns the reward amount of 1 share based off the locked up time&quot;, async () =&gt; {
                
                await mockWETH.connect(player1).approve(mutuals.address, amount0)
                await achiever.connect(player1).approve(mutuals.address, amount1)
                await mutuals.connect(player1).addLiquidity(amount0, amount1)
                // await moveTime(SECONDS_IN_A_DAY)
                // await moveBlocks(1)
                // let reward = await mutuals.rewardPerToken()
                // let expectedReward = &quot;86&quot;
                // assert.equal(reward.toString(), expectedReward)

                await moveTime(SECONDS_IN_A_YEAR)
                await moveBlocks(1)
                reward = await mutuals.rewardPerToken()
                expectedReward = &quot;31536&quot;
                console.log(ethers.utils.formatEther(reward))
                assert.equal(reward.toString(), expectedReward)
            })
        })
</code></pre>
<pre><code>    rewardPerToken
Moving blocks...
Moved forward in time  seconds
Moving blocks...
Moved  blocks
0.000000000000031536
      ✓ Returns the reward amount of 1 share based off the locked up time
</code></pre>
<p>I was doing some unit testing and notice that reward.toString() would simply ignore the factor of 1e18. The display result in Remix would include 1e18 though.</p>
<p>Is that how Javacript interpret Big Number? Thanks.</p>
",https://stackoverflow.com/questions/72958032/using-tostring-in-hardhat,"['javascript', 'hardhat']",42,False,0,0
unable to run test using tox.ini file,"<p>I am using <code>unittest</code> as the library for the unit testing purposes. I was trying to run the below test via <code>tox.ini</code> file.</p>
<pre><code>from services.snowflake_api import SnowflakeApi
from unittest import TestCase
from mock import patch


class SnowflakeDbTest(TestCase):

    @patch('services.SnowflakeAPI.snowflake.connector')  # Decorator where  database object is configured...
    def test_get_database_connection(self, mock_connection):
        mock_connection.connect.return_value = &quot;dbconnection&quot;  # Setting up the mock value that would be returned after calling db get connection method...
        self.assertEqual(&quot;dbconnection&quot;,
                         SnowflakeApi.get_database_connection(&quot;user&quot;, &quot;password&quot;, &quot;account&quot;, &quot;warehouse&quot;,
                                                              database=None, schema=None))
</code></pre>
<p><strong><code>tox.ini:</code></strong></p>
<pre><code>[tox]
envlist = py310

[testenv]
deps = pytest
commands = pytest
</code></pre>
<p><code>Error</code>:</p>
<pre><code>/Users/abc/IdeaProjects/python_project/venv/bin/python /Users/abc/Library/Application Support/JetBrains/IdeaIC2022.2/plugins/python-ce/helpers/pycharm/_jb_tox_runner.py 
Testing started at 8:24 pm ...
GLOB sdist-make: /Users/abc/IdeaProjects/project/abc/module/setup.py
py310 inst-nodeps: /Users/abc/IdeaProjects/project/abc/module/.tox/.tmp/package/1/dm-snowflake-1.0.0.zip
WARNING: Discarding $PYTHONPATH from environment, to override specify PYTHONPATH in 'passenv' in your configuration.
py310 installed: asn1crypto==1.4.0,attrs==22.1.0,certifi==2021.10.8,cffi==1.15.0,charset-normalizer==2.0.9,cryptography==35.0.0,distlib==0.3.4,dm-snowflake==1.0.0,filelock==3.4.2,idna==3.3,iniconfig==1.1.1,oscrypto==1.2.1,packaging==21.3,platformdirs==2.4.1,pluggy==1.0.0,py==1.11.0,pycparser==2.21,pycryptodomex==3.15.0,PyJWT==2.3.0,pyOpenSSL==21.0.0,pyparsing==3.0.6,pytest==6.2.5,pytz==2021.3,requests==2.27.1,six==1.16.0,snowflake-connector-python==2.7.2,toml==0.10.2,tox==3.25.1,urllib3==1.26.7,virtualenv==20.13.2
py310 run-test-pre: PYTHONHASHSEED='2295913608'
py310 run-test: commands[0] | /Users/abc/IdeaProjects/project/abc/module/.tox/py310/bin/python '/Users/abc/Library/Application Support/JetBrains/IdeaIC2022.2/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py' --offset 1 --
Launching pytest with arguments --no-header --no-summary -q in /Users/abc/IdeaProjects/project/abc/module

============================= test session starts ==============================
collecting ... collected 0 items

============================ no tests ran in 0.01s =============================
ERROR: InvocationError for command /Users/abc/IdeaProjects/project/abc/module/.tox/py310/bin/python '/Users/abc/Library/Application Support/JetBrains/IdeaIC2022.2/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py' --offset 1 -- (exited with code 5)

commands failed
___________________________________ summary ____________________________________
ERROR:   py310: commands failed

Process finished with exit code 1
</code></pre>
<p>I am also sharing my project structure below:</p>
<p><a href=""https://i.stack.imgur.com/QV6pC.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/QV6pC.png"" alt=""enter image description here"" /></a></p>
<p><code>Error</code>:</p>
<pre><code>============================= test session starts ==============================
collecting ... 
tests/snowflake/test_example_01.py:None (tests/snowflake/test_example_01.py)
ImportError while importing test module '/Users/abc/IdeaProjects/project/abc/module/tests/snowflake/test_example_01.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
.tox/py310/lib/python3.10/site-packages/_pytest/python.py:608: in _importtestmodule
    mod = import_path(self.path, mode=importmode, root=self.config.rootpath)
.tox/py310/lib/python3.10/site-packages/_pytest/pathlib.py:533: in import_path
    importlib.import_module(module_name)
/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
&lt;frozen importlib._bootstrap&gt;:1050: in _gcd_import
    ???
&lt;frozen importlib._bootstrap&gt;:1027: in _find_and_load
    ???
&lt;frozen importlib._bootstrap&gt;:1006: in _find_and_load_unlocked
    ???
&lt;frozen importlib._bootstrap&gt;:688: in _load_unlocked
    ???
.tox/py310/lib/python3.10/site-packages/_pytest/assertion/rewrite.py:168: in exec_module
    exec(co, module.__dict__)
tests/snowflake/test_example_01.py:3: in &lt;module&gt;
    from mock import patch
E   ModuleNotFoundError: No module named 'mock'
</code></pre>
<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/74183160/unable-to-run-test-using-tox-ini-file,"['python', 'pytest', 'python-unittest', 'tox']",368,False,0,1
Can AAA be used in Automation Tests?,"<p>I have a smoke test suite, which will be automated. Can I use during code process Act Arrange Assert Pattern? Or Is it only for unit testing? Or is there better pattern for automation testing?</p>
",https://stackoverflow.com/questions/74592929/can-aaa-be-used-in-automation-tests,"['automation-testing', 'smoke-testing', 'arrange-act-assert']",18,False,0,0
Authorization filter test failed webapi,"<p>I am writing unit test for Authorization filter to validate the request/ token. However, it return null. not sure what is wrong.</p>
<p><a href=""https://programmium.wordpress.com/2020/04/30/unit-testing-custom-authorization-filter-in-net-core/"" rel=""nofollow noreferrer"">https://programmium.wordpress.com/2020/04/30/unit-testing-custom-authorization-filter-in-net-core/</a></p>
<pre><code>public class UserAuthorizationTests
{
    private readonly Mock&lt;ILogger&lt;UserAuthorizationFilter&gt;&gt; _mocklogger;
    private readonly Mock&lt;IOptions&lt;UserAuthorisationOptions&gt;&gt; _mockOption;
    public UserAuthorizationTests()
    {
         _mocklogger = new Mock&lt;ILogger&lt;UserAuthorizationFilter&gt;&gt;();
         _mockOption = new Mock&lt;IOptions&lt;UserAuthorisationOptions&gt;&gt;(); 
    }
    
    [Fact]
    public void UserAuthorizationTest()
    {
        var httpContextMock = new Mock&lt;HttpContext&gt;();
        httpContextMock.Setup(a =&gt; a.Request.Headers[&quot;UserAuthorization&quot;]).Returns(&quot;test&quot;);
        
        ActionContext fakeActionContext =
            new ActionContext(httpContextMock.Object, 
                new Microsoft.AspNetCore.Routing.RouteData(), 
                new Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor());            
            
        AuthorizationFilterContext fakeAuthFilterContext =
            new AuthorizationFilterContext(fakeActionContext, 
                new List&lt;IFilterMetadata&gt;());
        
        UserAuthorizationFilter userAuthorizationFilter = 
            new UserAuthorizationFilter(_mockOption.Object, _mocklogger.Object);
        userAuthorizationFilter.OnAuthorization(fakeAuthFilterContext);
        
        Assert.NotEqual(typeof(UnauthorizedResult), userAuthorizationFilter.GetType());
    }
}
</code></pre>
",https://stackoverflow.com/questions/72200846/authorization-filter-test-failed-webapi,"['asp.net-core', 'jwt', 'asp.net-core-webapi']",311,True,0,1
unit test web api actionresult index(),"<p>I am new to unit testing web api in .net. I want to test an api controller, which returns different responses when the numbers and dates match.</p>
<pre><code>[HttpGet]
[Produces(&quot;application/json&quot;)]

public ActionResult&lt;NumLookup&gt; Index(string numA, string? numB, string? numDate)
        {
         NumLookup response = new NumLookup();
           
         List&lt;NumLookupRecord&gt; searchResult = new List&lt;NumLookupRecord&gt;();

         DateTime CheckNumDate;
         try
         {
              CheckNumDate = DateTime.ParseExact(NumDate, &quot;yyyyMMdd&quot;, CultureInfo.InvariantCulture);
         }
         catch
         {
               response.InfoCode = &quot;Invalid&quot;;
               response.InvalidInfoCode = &quot;Nill&quot;;
                
               return Ok(response);
          }

}
 return Ok(response);
</code></pre>
<p>I'm not sure if the setup is correct.</p>
<pre><code> public class DefaultControllerTests
    {
        [Fact]
        public void ReturnCorrectResponseCode()
        {
            DefaultController defaultController = new CreateDefaultController();
             var result = defaultController.Index(&quot;34534524&quot;, &quot;467478678&quot;, &quot;20251112&quot;);

            Assert.NotNull(result);
            Assert.IsAssignableFrom(typeof(ContentResult), result);
            Assert.AreEqual(&quot;Invalid&quot;, result.Content);

        }
    }
</code></pre>
",https://stackoverflow.com/questions/73029067/unit-test-web-api-actionresult-index,"['c#', 'asp.net', 'asp.net-core', 'asp.net-web-api']",101,False,0,0
How can we inject a variable value in production code only for unit testing?,"<p>I have requirement to inject the value for variable <strong>data</strong>.</p>
<p><strong>index.js</strong></p>
<pre><code>const sideEffect = (arg1, arg2,...) =&gt; {
   // It perform complex tasks
   // Involves third-party call, etc
   // Returns the processed output
}

const main = async(args1, args2,...) =&gt; {
   const data = await sideEffect(args1, args2, ...);
   // Process the data and returns
   return data;
}

module.exports = {main};
</code></pre>
<p><strong>limitations</strong></p>
<ol>
<li>function <strong>data</strong> is not exported.</li>
</ol>
<p>I want to do unit testing for <strong>main</strong> function, by injecting the value of <strong>data</strong>, Can it be achieved ?</p>
",https://stackoverflow.com/questions/74001873/how-can-we-inject-a-variable-value-in-production-code-only-for-unit-testing,"['node.js', 'unit-testing', 'mocha.js', 'chai', 'mern']",30,False,0,1
Mock AWS SES using jest in typeorm,"<p>Need to test AWS SES using jest unit testing
But showing different errors, also tried solutions in another stackoverflow question
The actual code to be tested is :</p>
<pre><code>public async sentMail(params: ObjectLiteral) {

 // Create the promise and SES service object
    const sendPromise = new AWS.SES({ apiVersion: '2010-12-01' })
      .sendEmail(params)
      .promise();

    // Handle promise's fulfilled/rejected states
    sendPromise
      .then(function (data) {
        console.log(data.MessageId);
      })
      .catch(function (err) {
        console.error(err, err.stack);
      });
</code></pre>
<p>the test file is :</p>
<pre><code>import SES from 'aws-sdk/clients/ses';
const mSES = {
    sendEmail: jest.fn().mockReturnThis(),
    promise: jest.fn().mockReturnThis(),
    catch: jest.fn(),
  };
  jest.mock('aws-sdk/clients/ses', () =&gt; {
    return jest.fn(() =&gt; mSES);
  });

it('should send aws sesemail', async () =&gt; {
      // const spy = jest.spyOn(AWS, 'SES');
      const mSes = new SES() as unknown as {
        sendEmail: jest.Mock;
        promise: jest.Mock;
      };
      mSes
        .sendEmail()
        .promise.mockRejectedValueOnce(new Error('This is an SES error'));
      const res = await sesMailService.sentMail(
        {
          toName: 'Name',
          webUrl: 'webUrl',
        },
      );
      expect(mSes.sendEmail).toBeCalledWith({
          toName: 'Name',
          webUrl: 'webUrl',
        }
);
    });
</code></pre>
<p>Its giving error message as:</p>
<pre><code>TypeError: mSes.sendEmail(...).promise.mockRejectedValueOnce is not a function

      94 |       mSes
      95 |         .sendEmail()
    &gt; 96 |         .promise.mockRejectedValueOnce(new Error('This is an SES error'));
</code></pre>
",https://stackoverflow.com/questions/74727830/mock-aws-ses-using-jest-in-typeorm,"['javascript', 'unit-testing', 'jestjs', 'typeorm', 'amazon-ses']",144,True,0,1
Masstransit V8 Testing How to config UseDelayedMessageScheduler(),"<p>I just upgrade my state machine saga projects to DotNet6 and Masstransit version 8.0.5.</p>
<p>Some how I can't find any way to config delay message schedule in my unit testing.</p>
<p>version 7.3.0</p>
<pre><code>var provider = new ServiceCollection()
        .AddMassTransitInMemoryTestHarness(cfg =&gt;
        {
            cfg.AddSagaStateMachine&lt;OldSaga, OldState&gt;()
                .InMemoryRepository();
            cfg.AddSagaTestHarness&lt;OldState&gt;();
        })
        .BuildServiceProvider(true);
var harness = provider.GetRequiredService&lt;InMemoryTestHarness&gt;();
        harness.OnConfigureInMemoryBus += configurator =&gt;
        {
            configurator.UseDelayedMessageScheduler();
        };
var sagaHarness = provider.GetRequiredService&lt;ISagaTestHarness&lt;OldState&gt;&gt;();
</code></pre>
<p>Version 8.0.5</p>
<pre><code>var provider = new ServiceCollection().AddMassTransitTestHarness(cfg =&gt;
        {
            cfg.AddSagaStateMachine&lt;NewSaga, NewState&gt;();
        })
        .BuildServiceProvider(true);
var harness = provider.GetTestHarness();
var sagaHarness = harness.GetSagaStateMachineHarness&lt;NewSaga,NewState&gt;();


**cfg.AddSagaTestHarness&lt;NewState&gt;(); is obsolete**
</code></pre>
<p>and can't <code>GetRequiredService&lt;InMemoryTestHarness&gt;();</code></p>
",https://stackoverflow.com/questions/73220648/masstransit-v8-testing-how-to-config-usedelayedmessagescheduler,"['testing', '.net-6.0', 'masstransit', 'state-machine']",174,False,0,1
Why there&#39;s no &quot;Create Test&quot; Option when I click Alt + enter in my Maven Intellij project?,"<p>I'm trying to implement a unit testing for my rest controller but when I click Alt + Enter
I can't see the create Test option
I tried to reinstall the dependencies, Invalid caches but it didn't work</p>
<p><img src=""https://i.stack.imgur.com/flAr0.png"" alt=""1"" /></p>
<p><img src=""https://i.stack.imgur.com/JJThQ.png"" alt=""2"" /></p>
",https://stackoverflow.com/questions/73423166/why-theres-no-create-test-option-when-i-click-alt-enter-in-my-maven-intelli,"['java', 'spring', 'maven', 'intellij-idea', 'boot']",47,False,0,0
Xcode: PosterBoard quit unexpectedly,"<p>On macOS Monterey (12.5.1 (21G83)), using Xcode 14.0 beta 6 (14A5294g), when unit testing vs iOS simulator, I get a lot of <code>PosterBoard quit unexpectedly</code> warnings.</p>
<p>This is a project with many SPM packages and then I have an Xcode Proj using these local SPM packages as dependecy. I've set the <code>testTarget</code> from Package.swift (the tests of the local SPM packages) to run when unit testing the app (the scheme for the Xcode Proj). maybe that setup is causing issues?</p>
<p><a href=""https://www.reddit.com/r/Xcode/comments/wcd9wc/xcode_14_beta_4_simulator_crashing_posterboard/"" rel=""nofollow noreferrer"">Also seen on Reddit /r/Xcode</a> but non of the comments fixed the issue for me. I cannot set deployment to iOS 16, because need to support iOS 15 (some comment in the Reddit thread suggested that might solve it).</p>
<p><a href=""https://i.stack.imgur.com/45GPu.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/45GPu.jpg"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73699535/xcode-posterboard-quit-unexpectedly,['xcode'],191,False,1,0
Xunit Testing on a DivideByZeroException,"<p>I am a beginner at C# and Xunit testing. I have this body of code that denotes a Division method.</p>
<pre><code> public void Divide(CalculatorData calculate)
    {
        calculate.Operator = CalculatorOperator.Divide;
        calculate.calculatorResult = calculate.inputNumbers[0];
        for (int i = 1; i &lt; calculate.inputNumbers.Length; i++)
        {
            decimal item = calculate.inputNumbers[i];
            try
            {
                calculate.calculatorResult /= item;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
</code></pre>
<p>I tried this unit testing, but it doesn't pass. Anyone knows how should I approach this?</p>
<pre><code> public void Divide_DivByZero()
    {
        //Arrange
        calculatorData.inputNumbers = new List&lt;decimal&gt;() { 5, 0 }.ToArray();

        Assert.Throws&lt;DivideByZeroException&gt;(() =&gt;
        {

            //Act
            calculatorManager.Divide(calculatorData);
            var result = calculatorData.calculatorResult;

            //Assert
            Assert.IsType&lt;decimal&gt;(result);
        });
    }
</code></pre>
",https://stackoverflow.com/questions/73855633/xunit-testing-on-a-dividebyzeroexception,"['c#', 'testing', 'xunit', 'dividebyzeroexception']",74,False,0,1
"Unit testing controller error. When I try to use the controller in the unit test, I get this error","<p>When I try to use the controller in the unit testing, I get this error. I am using MS Testing for the unit tests.</p>
<p>Testing code</p>
<pre><code>[TestMethod]
public async Task PostDataReturnOk()
{
        var data = _fixture.Create&lt;ProductCat&gt;();
        _categoryRepository.Setup(re =&gt; re.AddCat(It.IsAny&lt;ProductCat&gt;())).Returns(data);
        _Controller = ProductCatsController(_Controller.Object);
}
</code></pre>
<p><a href=""https://i.stack.imgur.com/a4LZ8.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/a4LZ8.png"" alt=""Testing Code"" /></a></p>
<p>Controller</p>
<pre><code>public ProductCatsController(IProCatRepository repository, IMapper mapper)
{
    _ProCatService = repository;
    _mapper = mapper;
}
</code></pre>
<p><a href=""https://i.stack.imgur.com/bO1Cp.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/bO1Cp.png"" alt=""Constructor"" /></a></p>
<pre><code>[HttpPost]
[Authorize(Roles = &quot;Admin&quot;)]
public ActionResult&lt;CategoryDto&gt; CreateCategory(CreateCatDto Categ)
{
    var catEntity = _mapper.Map&lt;ProductCat&gt;(Categ);
    var NewCategory = _ProCatService.AddCat(catEntity);

    var CatForReturn = _mapper.Map&lt;CategoryDto&gt;(NewCategory);

    return CreatedAtRoute(&quot;GetCat&quot;, new { id = CatForReturn.Id }, CatForReturn);
}
</code></pre>
<p>Post method - this is what I need to test</p>
<p><a href=""https://i.stack.imgur.com/xDO0e.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/xDO0e.png"" alt=""Post Method"" /></a></p>
",https://stackoverflow.com/questions/73968405/unit-testing-controller-error-when-i-try-to-use-the-controller-in-the-unit-test,"['c#', 'asp.net', 'visual-studio', 'unit-testing', '.net-6.0']",180,True,-1,1
undefined reference to `WinMain&#39; in eclipse IDE with cygwin (setup-x86_64),"<p>I am currently doing unit testing for a project of c/c++ in eclipse IDE (Version: Luna Service Release 2 (4.4.2)) and I have recently upgraded my cygwin to cygwin64 to make it compatible with c++17 standard and my g++ version is g++ (GCC) 10.2.0, But I am not able to build my testsuites in eclipse, I have set the environment path to &quot;C:\cygwin64\bin&quot;, But still I am getting the below error. Could you please help me with the below error:
Console output after building my project :
make all
Building file:</p>
<pre><code>   C:/Accurev/AngioJet_Development_ver1/CS/AngioJet/Firmware/src/ClinicalFeatures/door.cpp
   Invoking: Cygwin C++ Compiler
   g++ -DUNIT_TESTING -        &quot;C:/Accurev/AngioJet_Development_ver1/CS/ut/testsuites/Firmware/hell/../../../../AngioJet/Firmware/build/PicoZed_FSBL_bsp/ps7_cortexa9_0/include&quot; -I&quot;C:/Accurev/AngioJet_Development_ver1/CS/ut/testsuites/Firmware/hell/../../../testsupport/&quot; -I&quot;C:/Accurev/AngioJet_Development_ver1/CS/ut/testsuites/Firmware/hell/../../../testsupport/Source&quot; -I&quot;C:/Accurev/AngioJet_Development_ver1/CS/ut/testsuites/Firmware/hell/../../../../AngioJet/Firmware/src/Platform/Zynq7000&quot; -      I&quot;C:/Accurev/AngioJet_Development_ver1/CS/ut/testsuites/Firmware/hell/../../../../AngioJet/Firmware/src/HostInterface&quot; -I&quot;C:/Accurev/AngioJet_Development_ver1/CS/ut/testsuites/Firmware/hell/../../../../AngioJet/Firmware/soup/treck/6_0_1_56/include&quot; -I&quot;C:/Accurev/AngioJet_Development_ver1/CS/ut/testsuites/Firmware/hell/../../../../Einstein/src/Platform/Zynq7000&quot; -I&quot;C:/Accurev/AngioJet_Development_ver1/CS/ut/testsuites/Firmware/hell/../../../../Einstein/src/Common&quot; -I&quot;C:/Accurev/AngioJet_Development_ver1/CS/ut/testsuites/Firmware/hell/../../../../AngioJet/Firmware/src/Common&quot; -I&quot;C:/Accurev/AngioJet_Development_ver1/CS/ut/testsuites/Firmware/hell/../../../../AngioJet/Firmware/src/ClinicalFeatures&quot; -O0 -g -fprofile-arcs -ftest-coverage -Wall -c -fmessage-length=0 -MMD -MP -MF&quot;src/door.d&quot; -MT&quot;src/door.d&quot; -o &quot;src/door.o&quot; &quot;C:/Accurev/AngioJet_Development_ver1/CS/AngioJet/Firmware/src/ClinicalFeatures/door.cpp&quot;
Finished building: C:/Accurev/AngioJet_Development_ver1/CS/AngioJet/Firmware/src/ClinicalFeatures/door.cpp
 
Building target: helll.exe
Invoking: Cygwin C++ Linker
g++ -fprofile-arcs -o &quot;helll.exe&quot; ./src/door.o   -lgcov -lbfd
/usr/lib/gcc/x86_64-pc-cygwin/10/../../../../x86_64-pc-cygwin/bin/ld: /usr/lib/gcc/x86_64-pc-cygwin/10/../../../../lib/libcygwin.a(libcmain.o): in function `main':
/usr/src/debug/cygwin-3.3.6-1/winsup/cygwin/lib/libcmain.c:37: undefined reference to `WinMain'
collect2: error: ld returned 1 exit status
make: *** [makefile:47: helll.exe] Error 1

07:05:17 Build Finished (took 4s.531ms)
`*

</code></pre>
<p>I have uninstalled and reinstalled the softwares. Also I have built a new project from scratch which is building fine but whenever i try to build my project it is not building.</p>
<p>While doing unit testing in eclipse we create the project as c++ project and  import the source files mentioned below and the structure is as follow:
Source file  -  door.cpp, door.h
door.h:</p>
<pre><code>#include &quot;global.h&quot;
</code></pre>
<p><code>namespace lDOOR { void close( BasicTypes::UInt8 mode ); }</code></p>
<p>door.cpp:</p>
<pre><code>#include &quot;door.h&quot;

    void lDOOR::close(void)
{
   //Normal Mode
   close(BscMsg::NORMAL);
}
</code></pre>
<p>and we do the unit testing for the above functions present in .cpp file in the file created by us door_testsuite.h which is as follows:</p>
<pre><code>#include &lt;cxxtest/TestSuite.h&gt;
class door_TestSuite: public CxxTest::TestSuite {
public:
    void setUp(){}
    void teardown(){}
    void testDoorLDoorClose()
    {
         BscMsg::UInt8 mode = 2;

         lDOOR::close(mode);
      TS_ASSERT_EQUALS();
}};
</code></pre>
<p>And when I test the above code in cygwin terminal it executes completely fine.</p>
",https://stackoverflow.com/questions/74262036/undefined-reference-to-winmain-in-eclipse-ide-with-cygwin-setup-x86-64,"['c++', 'eclipse', 'unit-testing', 'cygwin', 'winmain']",155,False,0,1
Permission to Clipboard When Unit Testing in Angular&#39;s Karma Framework,"<p>I was wondering how I can grant permission to clipboard when unit testing in the Angular's Karma framework. I'm currently unit testing the copy-and-paste functionality in the frontend with the system clipboard, and I am not sure if there is a way to configure Karma so that the permission to the clipboard is granted when pasting something from the clipboard. This is easy to do if I want to do the testing in my own browser where I can simply toggle on the permission, but since Karma is an automated system, I wonder if there's a way to go about that. I used the Clipboard API by the way to implement the pasting, i.e., navigator.clipboard.readText().</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/73270630/permission-to-clipboard-when-unit-testing-in-angulars-karma-framework,"['angular', 'unit-testing']",108,False,0,0
how can I do stres test asynchronous functions with loop on swift,"<p>I'm new in the unit testing.</p>
<p>and I had an issue about asynchronous function testing.</p>
<pre><code>func test_Repository()
{
    let properEmail = &quot;&quot;
    let properPassword = &quot;&quot;
    let improperEmail = &quot;&quot;
    let improperPassword = &quot;&quot;
    let testArray = [(username : &quot;&quot;, password : &quot;&quot;), // both empty
                     (username : &quot;&quot;, password : properPassword), // empty email
                     (username : properEmail, password : &quot;&quot;), // empty password
                     (username : improperEmail, password : properPassword), // wrong email
                     (username : properEmail, password : improperPassword) // wrong password
            ]
    let repo = UserRepository()
    let exp =
          expectation(description: &quot;Wait for async signIn to complete&quot;)
    
   for data in testArray
    {
       print(data.username)
       print(data.password)
       repo.createNewUser(data.username, password: data.password) {[weak self] email, error in
           XCTAssertNotNil(error)
           exp.fulfill()
       }
       sleep(5)
   }
    wait(for: [exp], timeout: 200.0)
   
}
</code></pre>
<p>as you can see, I want to test all improve possibilities but it didn't work.</p>
<p>and also my asynchronous create function is here</p>
<pre><code>func createNewUser(_ email : String, password   : String,result: @escaping (_ email : String, _ error : Error?)-&gt;())
{
    auth.createUser(withEmail: email, password: password) { [weak self] authResult, error in
        if let error = error
        {
            self?.userCreationError = true
            self?.userCreationErrorText = error.localizedDescription
            result(&quot;&quot;,error)
        }
        else
        {
            if let authresult = authResult
            {
                self?.user.email = authresult.user.email ?? &quot;&quot;
                self?.createNewUserTable(user: self!.user)
                result((self?.user.email)!,nil)
               
            }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/73816832/how-can-i-do-stres-test-asynchronous-functions-with-loop-on-swift,"['swift', 'unit-testing', 'testing']",90,False,1,2
"for elixir, vscode&#39;s outline can&#39;t list defp function after adding `private do`","<p>package <code>private</code> has been used for unit-testing defp function.
But in vscode the functions in the <code>private do ... end</code> scope can't be listed.
Is it possible to solve it or just accept it?</p>
<p><a href=""https://hexdocs.pm/private/Private.html"" rel=""nofollow noreferrer"">private module reference</a></p>
<p>private package
<a href=""https://i.stack.imgur.com/4oDAU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4oDAU.png"" alt=""private scope function"" /></a></p>
<p>outline view
<a href=""https://i.stack.imgur.com/hUGK2.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/hUGK2.png"" alt=""outline view image"" /></a></p>
",https://stackoverflow.com/questions/73258645/for-elixir-vscodes-outline-cant-list-defp-function-after-adding-private-do,"['visual-studio-code', 'elixir']",80,True,0,1
Vector VRL Unit testing returning undefined fuction for strlen,"<p><a href=""https://vector.dev/docs/reference/vrl/functions/#strlen"" rel=""nofollow noreferrer"">https://vector.dev/docs/reference/vrl/functions/#strlen</a>
Hello everyone
I have a transform containing this field and everything is working well and logs are good :</p>
<pre><code>    .msg = slice(.message, start: int!(strlen(join!(arrayvar, separator: &quot; &quot;))) , end: int!(strlen(.message))) ?? &quot;undefined&quot;
</code></pre>
<p>BUT unit testing return <code>undefined function did you mean &quot;string&quot;?</code> on strlen function.</p>
<p>Anyone has an idea please?</p>
",https://stackoverflow.com/questions/72363119/vector-vrl-unit-testing-returning-undefined-fuction-for-strlen,"['logging', 'yaml', 'datadog', 'vector-vrl']",261,True,0,1
Rest Controller Unit testing Java Spring Boot,"<p>while mocking the controller class, i am unable to cover the catch block in my unit testing,</p>
<p>here is the code -
Controller Class -</p>
<pre><code>public ResponseEntity&lt;ResponseSentence&gt; getText(@RequestBody Text text) throws IOException {

    try {
        return new ResponseEntity&lt;&gt;(serviceImpl.getText(text), HttpStatus.OK);

    } catch (IOException e) {
        return new ResponseEntity&lt;&gt;(HttpStatus.BAD_REQUEST);
    }

}
</code></pre>
<p>this is my test class</p>
<pre><code>  @Autowired
private MockMvc mockMvc;

@MockBean
private Service service;

@MockBean
private ServiceImpl serviceImp;
@Autowired
private ObjectMapper objectMapper;



@Test
void getText() throws Exception {
    Text text = new Text();
    text.setText(&quot;&quot;);

    //given(service.getText(text)).willThrow(new IOException(&quot;boom&quot;));
    when(serviceImp.getText(text)).thenThrow(new IOException());

    ResultActions response = mockMvc.perform(post(&quot;/opennlp/v1/sentence&quot;)
            .contentType(MediaType.APPLICATION_JSON).content(objectMapper.writeValueAsString(text)));


    response.andDo(print()).
            andExpect(status().isBadRequest());

    Mockito.verify(serviceImp).getText(any());

}
</code></pre>
<p>while code coverage the catch block is not covered.</p>
",https://stackoverflow.com/questions/73643655/rest-controller-unit-testing-java-spring-boot,"['spring-boot', 'unit-testing', 'junit', 'mockito', 'spring-restcontroller']",549,True,-1,1
"springboot jpa repository.save(obj) must not be null, NullPointerException in test","<p>I am having issues in writing unit testing for my Kotlin project where my actual usage is working fine. However, my unit testing will throw an unusual error. When I call my save service in my test, it will throw a <code>java.lang.NullPointerException: movieRepository.save(movie) must not be null</code>. I am unsure what item that 'must not be null' is referring to as I logged both movieRepository and movie to have some value.</p>
<p>Additional Info: Only when I am adding a new entry, it will throw NPE error. However, when I am performing an update (also uses <code>.save(movie)</code>), the test goes through fine. Testing with other functionality such as .findAll() and .deleteById() works fine.</p>
<p>Here are the code snippets:</p>
<p>Movie.kt</p>
<pre><code>@Table(name=&quot;movie&quot;)
@Entity
data class Movie(
  @Id
  @Column(name=&quot;id&quot;)
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  val id: Int? = null,

  val name: String,

  val type: String,
)
</code></pre>
<p>MovieService.kt</p>
<pre><code>@Service
class MovieService {
  @Autowired
  private lateinit var movieRepository: MovieRepository;

  fun addMovie(movie: Movie): Movie {
    return movieRepository.save(movie)
  }
}
</code></pre>
<p>MovieServiceTest.kt</p>
<pre><code>@ExtendWith(MockitoExtension::class)
@MockitoSettings(strictness = Strictness.LENIENT)
internal class MovieServiceTest {

  @Mock
  private lateinit var mockMovieRepository: MovieRepository;

  @InjectMocks
  private lateinit var movieServiceTest: MovieService;

  // Mock Values
  val mockName = &quot;mockName&quot;;
  val mockType = &quot;mockType&quot;;
  val mockMovie = Movie(name = mockName, type = mockType);

  @Test
  fun addMovie() {
    val result = movieServiceTest.addMovie(mockMovie);

    val movieArgumentCaptor: ArgumentCaptor&lt;Movie&gt; = ArgumentCaptor.forClass(Movie::class.java);
    verify(mockMovieRepository).save(movieArgumentCaptor.capture());

    val capturedMovie = movieArgumentCaptor.value;
    verify(mockMovieRepository).save(capturedMovie);

    verify(result.name == mockName)
  }
}
</code></pre>
<p>Error message</p>
<pre><code>java.lang.NullPointerException: movieRepository.save(movie) must not be null

    at com.example.stackoverflow.MovieService.addMovie(MovieService.kt:18)
    at com.example.stackoverflow.MovieServiceTest.addMovie(MovieServiceTest.kt:43)
    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.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
    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$7(TestMethodTestDescriptor.java:214)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    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:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    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)


Process finished with exit code 255
</code></pre>
",https://stackoverflow.com/questions/70561121/springboot-jpa-repository-saveobj-must-not-be-null-nullpointerexception-in-te,"['spring-boot', 'kotlin', 'spring-data-jpa', 'junit5', 'spring-boot-test']",2069,True,0,1
Unit testing angular custom validator,"<p>I'm just starting to learn unit testing and I have this problem that causes unit tests not to run.
after running ng test it says Executed 0 out of 0 Success
here's my code</p>
<p>validator</p>
<pre><code>export function validateUrl(control: FormControl): ValidationErrors | null {
  let valid = true;
  try{
   let str = control.value;
   if(str.indexOf('://') === -1){
    str = `http://${str}`
    new URL(str);
    control.setValue(str);
  }else{
    new URL(control.value);
  }
 }catch{
   valid = false
 }
  return valid ? null : { invalidUrl: true }
}
</code></pre>
<p>spec file</p>
<pre><code>import { TestBed} from &quot;@angular/core/testing&quot;;
import { FormControl } from &quot;@angular/forms&quot;;
import { validateUrl } from &quot;./web-page-details.component&quot;;
describe('maxTextLength', () =&gt; {
  beforeEach(() =&gt; TestBed.configureTestingModule({}))
   const control = new FormControl();
  it('should return null if input string contains protocol', () =&gt; {
   control.setValue('http://test.com');
   expect(validateUrl(control)).toBeNull();
 });
  it('should return null if url doesnt contain protocol', () =&gt; {
   control.setValue('test.com');
   expect(validateUrl(control)).toBeNull();
 });
});
</code></pre>
",https://stackoverflow.com/questions/71607145/unit-testing-angular-custom-validator,"['angular', 'typescript', 'unit-testing', 'validation']",976,False,0,0
get value v-model(vue bind) after trigger click component using jest,"<p>i am so confused what happens with my code. i am new in jest and unit testing, while developing i use bootstrap-vue, nuxt and vue test utils (jest) for unit testing.</p>
<p>Shortly, i have custom component (CheckboxInput). this component use b-form-checkbox-group from bootstrap vue it's my code.</p>
<pre><code>  props : {
    ...another props,
    value : {default : () =&gt; ({}),
  },
  computed : {
    local_value: {
      get: function () {
        return this.value
      },
      set: function (value) {
        this.$emit('input', value)
      }
    },
  }
  --------
  &lt;b-form-checkbox-group
    :id=&quot;id&quot;
    :ref=&quot;id&quot;
    :class=&quot;additional_class&quot;
    v-model=&quot;local_value&quot;
    :size=&quot;size&quot;
    :indeterminate=&quot;is_indeterminate&quot;
    :disabled=&quot;is_disabled&quot;
    :stacked=&quot;is_vertical&quot;
  &gt;
    &lt;b-form-checkbox
      v-for=&quot;(option, index) in options&quot;
      :key=&quot;index&quot;
      :value=&quot;option.value&quot;
      :disabled=&quot;option.is_disabled&quot;
      :checked=&quot;is_force_unchecked&quot;
      :unchecked-value=&quot;option.unchecked_value ? option.unchecked_value : false&quot;
    &gt;
      {{ option.text }}
    &lt;/b-form-checkbox&gt;
  &lt;/b-form-checkbox-group&gt;

</code></pre>
<p>I want to create simple test for make sure user select options DOM value is matched. it's my test</p>
<pre><code>it(&quot;select one option&quot;, async () =&gt; {
    // options value is =&gt; [{list}, {of}, {object}]

    const random = Math.floor(Math.random() * options.length)
    const input = wrapper.find(`#${checkbox_id}`)
    let opt = input.find(`input[value='${options[random].value}']`)
    opt.trigger(&quot;click&quot;)

    // this wrapper still contain default value, but i can find that component properly
    console.log(wrapper.vm.local_value)
    console.log(options[random])
    console.log(opt.html())

</code></pre>
<p>idk what happens with my code and how to trigger properly. please help me if you have any solution for me, also i have another question. &quot;How to check or try catch the test is work or not in jest/vue test utils&quot;</p>
<p>Thank you for your time.</p>
",https://stackoverflow.com/questions/71307211/get-value-v-modelvue-bind-after-trigger-click-component-using-jest,"['javascript', 'vue.js', 'unit-testing', 'jestjs', 'vue-test-utils']",902,False,0,0
How can i run Microsoft Unit Testing Framework for C++ using github actions?,"<p>i'm trying to run my unit test which is using the Microsoft Unit Testing Framework for C++ using Github actions.</p>
<p>I'v tried adding the DLL with the exe of the sln but it doesn't seem to work.</p>
<p>build:</p>
<pre><code>runs-on: windows-latest

steps:
# using tmp v3 git branch 
- uses: actions/checkout@v3
# getting dependencies 
- name: getting dependencies
  working-directory: UnitTest
  run:  ./BuildTest.bat
# set up 
- name: set up
  working-directory: UnitTest
  run:  ./SetUpTest.bat
# adding msbuild path 
- name: add msbuild to PATH
  uses: microsoft/setup-msbuild@v1.1
# # building sln in release 
# - name: build release
#   run: msbuild Dare.sln /p:Configuration=Release
# building sln in debug 
- name: build debug
  run: msbuild Dare.sln /p:Configuration=Debug

# run unit test
- name: list
  working-directory: bin/Debug-windows-x86_64/DareEditor
  run : ls 

# run unit test
- name: run unit test
  working-directory: bin/Debug-windows-x86_64/DareEditor
  # run : ls 
  # run: ./DareEditor.exe /Platform:x64 ./x64\Debug\UnitTest1.dll
  # run: ./DareEditor.exe /Platform:x64 ./x64\Debug\UnitTest1.dll
  run: ./DareEditor.exe 
</code></pre>
",https://stackoverflow.com/questions/73475724/how-can-i-run-microsoft-unit-testing-framework-for-c-using-github-actions,"['c++', 'unit-testing', 'github', 'github-actions']",128,True,0,1
Unit Testing of an API in Kotlin?,"<p>I am new to this unit testing, can somebody help me in writing a unit for an API that is used for logging. I don't know where to start and how to start writing tests for an API.</p>
",https://stackoverflow.com/questions/72372689/unit-testing-of-an-api-in-kotlin,"['api', 'unit-testing', 'kotlin', 'junit']",187,False,0,1
how can I assign real/fake object to binding context for Xunit test (Model Binding)?,"<p>this is the method i want to test</p>
<pre><code>
     public class DataRequestQueryBinder : IModelBinder
        {
            public Task BindModelAsync(ModelBindingContext bindingContext)
            {
                var jsonString = bindingContext.ActionContext.HttpContext.Request.Query[&quot;request&quot;];
                if (string.IsNullOrWhiteSpace(jsonString))
                {
                    throw new ArgumentNullException(&quot;request&quot;);
                }
    
                var result = JsonConvert.DeserializeObject&lt;DataRequestQuery&gt;(jsonString);
                bindingContext.Result = ModelBindingResult.Success(result);
                return Task.CompletedTask;
            }
        }

</code></pre>
<p>i am new in unit testing below is my attempt for Xunit test but i want to give it the real object manually by code , or just prepare <code>bindingContext.ActionContext.HttpContext.Request.Query[&quot;request&quot;];</code> if required.</p>
<pre><code>  public class DataRequestQueryBinderTest
    {
        [Fact]
        public async Task BindingModleAsyncTest()
        {
            DataRequestQueryBinder dta = new DataRequestQueryBinder();
            ModelBindingContext bindingContext = Substitute.For&lt;ModelBindingContext&gt;();
            //await dta.BindModelAsync(bindingContext);
                   

            //bindingContext.ActionContext.HttpContext
            var value1 = dta.BindModelAsync(bindingContext);

            //var value = Task.Run(async () =&gt; await dta.BindModelAsync(bindingContext));
            Assert.True(dta.BindModelAsync(bindingContext).IsCompleted);
            Assert.NotNull(value1);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/73218749/how-can-i-assign-real-fake-object-to-binding-context-for-xunit-test-model-bindi,"['c#', 'asp.net', 'httprequest', 'model-binding', 'binding-context']",290,True,0,1
lateinit property fakeAuthRepository has not been initialized unit testing,"<p>I am using unit testing when I run test I am getting following exception</p>
<p>ateinit property fakeAuthRepository has not been initialized
kotlin.UninitializedPropertyAccessException: lateinit property fakeAuthRepository has not been initialized</p>
<p>below my ViewModel test where test giving an exception</p>
<pre><code>internal class SignInViewModelTest{
    private val _login =  MutableStateFlow&lt;UiStateObject&lt;SignInResponse&gt;&gt;(UiStateObject.EMPTY)

         @Mock
        lateinit var backendApi:BackendApi

    lateinit var fakeAuthRepository: FakeAuthRepository
    lateinit var authRepository: AuthRepository
    private lateinit var viewModel: SignInViewModel
    @Before
    fun setUp() {

        MockitoAnnotations.initMocks(this)
        fakeAuthRepository = FakeAuthRepository(backendApi)
        authRepository = AuthRepository(backendApi)
        viewModel = SignInViewModel(authRepository)

    }

    var login = _login

    @Test
    fun `testing repository`() = runBlockingTest {

        val fake = fakeAuthRepository.login(&quot;kyodgorbek@gmail.com&quot;, &quot;12345678&quot;, &quot;android&quot;, &quot;123455&quot;)
        val real = authRepository.login(&quot;kyodgorbek@gmail.com&quot;, &quot;12345678&quot;, &quot;android&quot;, &quot;123455&quot;)
        assertEquals(fake, real)


    }



}
</code></pre>
",https://stackoverflow.com/questions/73787027/lateinit-property-fakeauthrepository-has-not-been-initialized-unit-testing,"['android', 'unit-testing', 'kotlin', 'mockito', 'android-viewmodel']",814,True,0,1
MSTest: Unit Testing HttpContext.SignoutAsync for the logout,"<p>Simply passing Mock HttpContext to the controller context while unit testing logout functionality will throw following error
<strong>HttpContext.Signout + value can not be null (Parameter 'provider')</strong></p>
<pre><code>var mockHttpContext = new Mock&lt;HttpContext&gt;();

       
</code></pre>
<p>//set the controller HttpContext</p>
<pre><code>_controller.ControllerContext.HttpContext = mockHttpContext.Object;
</code></pre>
<p>// Now call the Logout action method and Test result</p>
",https://stackoverflow.com/questions/71168289/mstest-unit-testing-httpcontext-signoutasync-for-the-logout,"['mstest', 'httpcontext']",456,True,0,1
Unit Testing Combine,"<p>I'm having difficulties testing Combine. I'm following:</p>
<ul>
<li><a href=""https://www.swiftbysundell.com/articles/unit-testing-combine-based-swift-code/"" rel=""nofollow noreferrer"">https://www.swiftbysundell.com/articles/unit-testing-combine-based-swift-code/</a></li>
</ul>
<p>Which tests:</p>
<pre class=""lang-swift prettyprint-override""><code>final class ViewModel {
    @Published private(set) var tokens = [String]()
    @Published var string = &quot;&quot;
 
    private let tokenizer = Tokenizer()

    init () {
        $string
            .flatMap(tokenizer.tokenize)
            .replaceError(with: [])
            .assign(to: &amp;$tokens)
    }
}

struct Tokenizer {
    func tokenize(_ string: String) -&gt; AnyPublisher&lt;[String], Error&gt; {
        let strs = string.components(separatedBy: &quot; &quot;)
        return Just(strs)
            .setFailureType(to: Error.self)
            .eraseToAnyPublisher()
    }
}
</code></pre>
<p>with the following:</p>
<pre><code>func testTokenizingMultipleStrings() throws {
    let viewModel = ViewModel()
    let tokenPublisher = viewModel.$tokens
        .dropFirst()
        .collect(2)
        .first()
    viewModel.string = &quot;Hello @john&quot;
    viewModel.string = &quot;Check out #swift&quot;
    let tokenArrays = try awaitPublisher(tokenPublisher)
    XCTAssertEqual(tokenArrays.count, 2)
    XCTAssertEqual(tokenArrays.first, [&quot;Hello&quot;, &quot;john&quot;])
    XCTAssertEqual(tokenArrays.last, [&quot;Check out&quot;, &quot;swift&quot;])
}
</code></pre>
<p>And the following helper function:</p>
<pre class=""lang-swift prettyprint-override""><code>extension XCTestCase {
    func awaitPublisher&lt;T: Publisher&gt;(
        _ publisher: T,
        timeout: TimeInterval = 10,
        file: StaticString = #file,
        line: UInt = #line
    ) throws -&gt; T.Output {
        var result: Result&lt;T.Output, Error&gt;?
        let expectation = self.expectation(description: &quot;Awaiting publisher&quot;)
        let cancellable = publisher.sink(
            receiveCompletion: { completion in
                switch completion {
                case .failure(let error):
                    result = .failure(error)
                case .finished:
                    break
                }
                expectation.fulfill()
            },
            receiveValue: { value in
                result = .success(value)
            }
        )
        waitForExpectations(timeout: timeout)
        cancellable.cancel()
        let unwrappedResult = try XCTUnwrap(
            result,
            &quot;Awaited publisher did not produce any output&quot;,
            file: file,
            line: line
        )
        return try unwrappedResult.get()
    }
}
</code></pre>
<p>Here <code>receiveValue</code> is never called so the test doesn't complete.
How can I get this test to pass?</p>
",https://stackoverflow.com/questions/71276105/unit-testing-combine,"['swift', 'xctest', 'combine']",2440,True,3,2
Is Moles Framework supported in visual studio 2019? If yes how to set it up?,"<p>Recently I started writing Nunit code for unit testing my MVC c# code. So I am facing the difficulty to mock static classes and methods.
Is Moles Framework supported in visual studio 2019? If yes how to set it up?</p>
",https://stackoverflow.com/questions/72123881/is-moles-framework-supported-in-visual-studio-2019-if-yes-how-to-set-it-up,"['c#', 'nunit', 'moles']",337,False,1,0
Fluent assertions event monitoring does not work,"<p>I try to using following features for my unit testing
<a href=""https://fluentassertions.com/eventmonitoring/"" rel=""nofollow noreferrer"">https://fluentassertions.com/eventmonitoring/</a></p>
<p>But I catch a strange exception on execution line.</p>
<pre><code> Message: 
System.InvalidProgramException : Common Language Runtime detected an invalid program.

 Stack Trace: 
Func`2DynamicHandler(EventRecorder , InternalOrder )
EventExtensions.Raise[T](Func`2 handlers, T arg) line 42
InternalOrderProcessor.CreateInternalOrder(SkuDemand skuDemand, PickLevelDestinationStateInfo pickLevelDestinationStateInfo) line 199
InternalOrderProcessor.CreateInternalOrders(IList`1 skuDemands, PickLevelDestinationStateInfo pickLevelDestinationStateInfo) line 86
InternalOrderProcessorTests.CreateInternalOrder_MultiDemandCoveredWithOneSku_OrderForOneSkuCreatedAndSent()
GenericAdapter`1.GetResult()
AsyncToSyncAdapter.Await(Func`1 invoke)
TestMethodCommand.RunTestMethod(TestExecutionContext context)
TestMethodCommand.Execute(TestExecutionContext context)
&lt;&gt;c__DisplayClass1_0.&lt;Execute&gt;b__0()
DelegatingTestCommand.RunTestMethodInThreadAbortSafeZone(TestExecutionContext context, Action action)
</code></pre>
<p>This is my test code.</p>
<pre><code>var monitor = this.service.Monitor();

await this.service.CreateOrder(); // exception here

monitor.Should().Raise(nameof(this.service.OrderCreated));
</code></pre>
<p>Beside, if I use my solution for check event raised - everything works.</p>
<pre><code>var isRaised = false;
this.service.OrderCreated += order =&gt;
{
  isRaised = true;
  return Task.CompletedTask;
};

await this.service.CreateOrder(); // without exception

isRaised.Should().BeTrue();
</code></pre>
",https://stackoverflow.com/questions/74930089/fluent-assertions-event-monitoring-does-not-work,"['c#', 'unit-testing', 'event-handling', 'nunit', 'fluent-assertions']",95,False,0,1
Problems with Unit_Tests,"<p>I am trying to write UNIT Test for my controller in MVC - Spring Boot , actually i am new to it . I have added dependency of Unit testing in <code>pom/xml</code>.
Here is my controller :</p>
<pre><code>@GetMapping(&quot;/showFormForUpdate/{id}&quot;)
    public String showFormForUpdate(@PathVariable ( value = &quot;id&quot;) long id, Model model) {
        
        // get employee from the service
        Employee employee = employeeService.getEmployeeById(id);
        
        // set employee as a model attribute to pre-populate the form
        model.addAttribute(&quot;employee&quot;, employee);
        return &quot;update_employee&quot;;
    }
</code></pre>
<p>Here is what i did:</p>
<p>public class ControllerTests {</p>
<pre><code>@Test
void hello(){
    EmployeeController controller = new EmployeeController();//Arrange
    String response = controller.showFormForUpdate( long id);

}
</code></pre>
<p>}</p>
<pre><code>How could i write a good Unit test for this?
</code></pre>
",https://stackoverflow.com/questions/72456585/problems-with-unit-tests,"['java', 'spring', 'spring-boot', 'unit-testing', 'spring-mvc']",48,True,0,1
error TS2552: Cannot find name &#39;xdescribe&#39;. Did you mean &#39;describe&#39;?,"<p>I am working on unit testing in angular application. And I have skipped some test suites by using <code>xdescrie</code>. Unfortunately, it is showing errors like <code>error TS2552: Cannot find name 'xdescribe'. Did you mean 'describe'?</code> when running the test by using the command <code>ng test</code>.</p>
<p>I have installed the package <code>@types/jasmine</code> as a Dev dependencies</p>
",https://stackoverflow.com/questions/71567757/error-ts2552-cannot-find-name-xdescribe-did-you-mean-describe,"['angular', 'unit-testing', 'jasmine', 'jasmine-node', 'angular-unit-test']",1357,False,0,1
Autofac.Core.DependencyResolutionException : An exception was thrown while activating CommunDataManager,"<p>I'm new at unit testing, I'm trying to test the data manager this is the class to test:</p>
<pre><code> public sealed class CommunDataManager : IDisposable
    {
        private readonly ISharedLogService _log;
        private readonly ISensitiveData _iSensitiveData;
        private readonly BadisRepository _badisRepository;
        public CommunDataManager()
        {
            _log = ModuleSharedServices.Instance.GetService&lt;ISharedLogService&gt;();
            _iSensitiveData = ModuleSharedServices.Instance.GetService&lt;ISensitiveData&gt;();
            _badisRepository = new BadisRepository(_iSensitiveData.DbPath, _iSensitiveData.DbKey);
        }
        private static CommunDataManager _instance;

        public static CommunDataManager GetInstance()
        {
            if (_instance == null)
            {
                _instance = new CommunDataManager();
            }
            return _instance;
        }

       public List&lt;Article_Famille&gt; GetArticleFamilleByCriteria(string libelle)
        {
            _log.Write(&quot;GetArticleFamilleByCriteria : recherche famille par critère&quot;,            System.Diagnostics.TraceEventType.Information);
            var predicate = QueryableBuilderExtensions.BuildPredicate&lt;Article_Famille&gt;(_ =&gt; _
                          .Contains(x =&gt; x.Libelle, libelle));
            return _badisRepository.GetRepository&lt;Article_Famille&gt;().GetMuliple(predicate);
        }
</code></pre>
<p>and this is the test method:</p>
<pre><code>[Test]
        public void test1()
        {
            using (var mock = AutoMock.GetLoose())
            {
                var cls = mock.Create&lt;CommunDataManager&gt;();
                var expected = cls.GetArticleFamilleByCriteria(&quot;Pharmacie&quot;);
                var actual = cls.Equals(expected);
                Assert.True(actual != null);
            }
            
        }
</code></pre>
<p>But after executing the test I got this Error:</p>
<blockquote>
<p>Autofac.Core.DependencyResolutionException : An exception was thrown while activating CommunDataManager.</p>
</blockquote>
",https://stackoverflow.com/questions/74718476/autofac-core-dependencyresolutionexception-an-exception-was-thrown-while-activ,"['c#', 'wpf', 'unit-testing', 'nunit', 'moq']",23,False,0,0
How do i mock RestTemplate exchange in Springboot,"<p>I use Junit5 for API unit testing.</p>
<p>My sourse is below</p>
<pre><code> String Url=&quot;/abc/test/{proPar}&quot;.replace(&quot;{proPar}&quot;,xxxDto.getPropar());
    Map&lt;String,Object&gt; responseMap1=
           restTemple.exchange(Url,HttpMethod.get,null,new ParameterizedTypeReference&lt;Map&lt;String,object&gt;&gt;(){}).getBody()
    
    if((boolean)responseMap1.get(&quot;core&quot;)){.....}

</code></pre>
<p>And My Mock is below:</p>
<pre><code>    Map&lt;String,object&gt; r1=new HashMap&lt;String,object&gt;();
    r1.put(&quot;core&quot;,true);
    ResponseEntity result=new ResponseEntity(r1,new HttpHeaders(),HttpStatus.ok);
    when(restTemple.exchange(Mockito.any(),Mockito.any(),Mockito.isNull(),Mockito.eq(new ParameterizedTypeReference&lt;Map&lt;String,object&gt;&gt;(){}))).thenReturn(result)
</code></pre>
<p>It didn' t work.I am trying to write the Junit test case for exchange method.</p>
<p>if any inputs required pls comment.
Thanks for the support.</p>
",https://stackoverflow.com/questions/74459033/how-do-i-mock-resttemplate-exchange-in-springboot,"['java', 'spring-boot', 'unit-testing', 'mockito', 'junit5']",153,False,0,0
how to get python unit test overwrite variable from imported package,"<p>Trying to figure out how to overwrite a variable during unit testing:</p>
<pre><code>#mainscript.py
import json

org_file = 'unitfile.json'

def load_json (file_name):
    with open ('{0}'.format(org_file)) as f:
       json_object =  json.load(f)
    return json_object

new_file = load_json(org_file)

def print_me():
    return (new_file['text'])

def main():
    print_me()

if __name__ == '__main__':
    main()
</code></pre>
<p>Unit test:</p>
<pre><code>#test_mainscript.py
import json
import mainscript
import unittest
from  unittest.mock import patch

class Testmainscript(unittest.TestCase):
    # def setUp(self):
        # Not needed when using mock
    @patch('mainscript.org_file','unitfile2.json')
    def test_print_me(self):
        self.assertEqual(mainscript.org_file, 'unitfile2.json') # Correctly overwrites file
        self.assertEqual(mainscript.print_me(),'Bye World') #does not pass, still reading unitfile.json instead of unitfile2.json
if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>This test should fail because because I'm overwriting org_file with <code>unitestfile2.json</code> (which contains <code>{'text':'Bye World'}</code>) instead of unittestfile.json (which contains <code>{'text':'Hello World'}</code>)</p>
<p>But its currently passing because the variable isn't being overwritten</p>
",https://stackoverflow.com/questions/72065112/how-to-get-python-unit-test-overwrite-variable-from-imported-package,"['python', 'python-3.x', 'unit-testing', 'python-unittest']",221,True,0,2
How Maven Provided scope interacts with Test scope,"<p>My project has a dependency (<code>Provided Scope</code>), then If I run my project under <code>Test Scope</code> for unit tests, then how does Maven find this dependency it needs during unit testing?
Would Maven just use the one in local maven repository (if exists)?
Thank you.</p>
",https://stackoverflow.com/questions/71342125/how-maven-provided-scope-interacts-with-test-scope,['maven'],313,True,0,1
How to mock Mongodb nested functions in side function with parameters req and response with jest?,"<p>this is the user service function I want to get 100% coverage of that code with unit testing which includes the nested MongoDB functions. As you can see I have getUser, addUser and then add user function in another service.</p>
<pre><code>async  getUser(req: Request, res: Response) {
            try {
                const db = DBFactory.getUserDB();
                const token = await this.getAuthToken(); //`Basic ${config.AUTH_DIGEST}` //req.headers['aps-token'] as string;
    
                let user = await db.getUser(+req.params.userId);
                if (!user) {
                    user = Object.assign({});
                    user.userId = +req.params.userId;
                    user.preferences = Object.assign({});
    
                    user = await db.addUser(Object.assign(user));
                    res.status(200).send(user);
                }
    
                const resp = Object.assign({}, user, (await ApsUserSvc.getUser(+req.params.userId, token))?.data)
              return res.status(200).send(resp);
            }
            catch (err) {
                logger.info(err);
                res.status(500).send()
            }
    
        }
</code></pre>
",https://stackoverflow.com/questions/74251048/how-to-mock-mongodb-nested-functions-in-side-function-with-parameters-req-and-re,"['node.js', 'mongodb', 'express', 'mocking', 'ts-jest']",30,False,0,0
of([]) not considered an array,"<p>I currently have an rxjs data stream in my component:</p>
<pre><code>items$ = of([]) as Observable&lt;Item[]&gt;;

ngOnInit(){
  this.items$ = this.httpService.getPokemonList();
}
</code></pre>
<p>However when I do the following in my unit testing it doesn't consider it an array:</p>
<pre><code>component.items$.push({&quot;slot&quot;: 1, &quot;pokemon&quot;: {&quot;name&quot;: &quot;my test name pokemon&quot;, &quot;url&quot;: &quot;a url&quot;}});

Error: Property 'push' does not exist on type 'Observable&lt;Item[]&gt;'
</code></pre>
<p>I'm assuming for this scenerio I can't use <code>of([]) as Observable&lt;Item[]&gt;</code>, is there another way to declare it?</p>
",https://stackoverflow.com/questions/72570859/of-not-considered-an-array,"['angular', 'rxjs']",43,True,-1,1
How to do unit testing using sinon library mocks following the Arrange Act Assert rule?,"<p>How to do unit testing using sinon library mocks following the Arrange Act Assert rule?</p>
<p>First tried stubbing an asynchronous function then tries resolving the function with a response and finally tried to check. But not understanding order of execution.</p>
<pre><code>  const req = httpMocks.createRequest({
                url: path,
                params: {},
                path: path,
                headers: {
                    'a': 'A',
                    'bla': 'blah',
                    'b': 'B',
                    Authorization: 'token blahblahblah'
                }
            });
            const res = {
                body: { foo: 'bar' },
                statusCode: 200,
                statusMessage: 'OK'
            };
            stub.resolves(res);


            // Execute
            await fun.callEndpoint(req, path,res.body);

            // Assert
            sinon.assert.calledOnce(stub);


</code></pre>
",https://stackoverflow.com/questions/74458182/how-to-do-unit-testing-using-sinon-library-mocks-following-the-arrange-act-asser,"['javascript', 'mocha.js', 'chai', 'sinon', 'stub']",16,False,0,0
how does unit testing works in django? (with coverage),"<p>i am finding it kinda confusing to do unit testing especially with fields that has blank=True attribute or unique=True</p>
<p>look at this for example:</p>
<pre class=""lang-py prettyprint-override""><code>class TagTest(TestCase):
    def create(self):
        tag = models.Tag.objects.create(name='test')
        return tag
    def test_get(self):
        tag = self.create()
        self.assertIsInstance(tag, models.Tag)
        self.assertEqual(tag.name, tag.__str__())
        self.assertEqual(len(tag.name),4)class TagTest(TestCase):
    def create(self):
        tag = models.Tag.objects.create(name='test')
        return tag
    def test_get(self):
        tag = self.create()
        self.assertIsInstance(tag, models.Tag)
        self.assertEqual(tag.name, tag.__str__())
        self.assertEqual(len(tag.name),4)
</code></pre>
<p>look at coverage for example, it is telling me i am not covering the test case at all</p>
<p><a href=""https://i.stack.imgur.com/BtmkD.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/BtmkD.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73263758/how-does-unit-testing-works-in-django-with-coverage,"['python', 'django', 'unit-testing', 'code-coverage']",49,False,3,1
gcov is invoking gtest sources and unit-tests. how can I avoid this?,"<p>I am working on creating a Jenkins pipeline for unit-testing maybe with GTest.
My plan is to use the following tools:
GTest for Unit-Testing, gcov for generating gcda and gcno Files and gcovr for xml or Html outputs of the unit-testing results.
It's working well till now with the help from the internet and particularly stack overflow.</p>
<p>But I am struggling with 3 issues.</p>
<ol>
<li>gcov is creating gcda and gcno files for gtest sources and my unit-tests. Because gcovr is invoking them and I see them in the HTML files. how can I avoid this? I only want my production code in the HTML files.</li>
<li>I can only see code coverage for template classes if gcov is generating gcda and gcno files for my unit-tests. So I need a simple idea for 1) Maybe can I use an exclude flag in gcovr?</li>
<li>Unused functions in template classes (inline functions) are not covered. Code coverage is always 100% but I tried with different flags, and nothing helped.
-fprofile-abs-path --coverage -fno-inline -fno-inline-small-functions -fno-default-inline -fkeep-inline-functions</li>
</ol>
<p><img src=""https://i.stack.imgur.com/3KYHm.jpg"" alt=""enter image description here"" /></p>
<p>I added a picture to show, what I am talking about. UnitTests and GTests covering results should not appear in gcovr HTML...</p>
",https://stackoverflow.com/questions/72845994/gcov-is-invoking-gtest-sources-and-unit-tests-how-can-i-avoid-this,"['jenkins', 'googletest', 'googlemock', 'gcov', 'gcovr']",593,True,1,1
How to write unit test for button component title using material ui in react,"<p>I'm beginner to unit testing, i'm trying to test name for button component using material ui framework.</p>
<pre><code>import Button from '@mui/material/Button';
import { screen } from '@testing-library/react';
import {render} from 'react-dom';

test(&quot;display button title&quot;, () =&gt; {
render(&lt;Button/&gt;);
const button = screen.getByRole('button', {name:/create user/i});
expect(button).toBeInTheDocument();
})
</code></pre>
<p>Can anyone help me in this. It is showing failed. I don't know where i'm writing wrong.</p>
<p>I'm expecting that the button component name should pass</p>
",https://stackoverflow.com/questions/74934446/how-to-write-unit-test-for-button-component-title-using-material-ui-in-react,"['reactjs', 'unit-testing', 'testing', 'material-ui']",154,True,1,1
Java - Constructor Unit testing,"<p>I have following Java configuration class which I need to unit test using JUnit:</p>
<pre><code>public class Config {

private static final String AMQ_CONNECTION_URL_TEMPLATE = &quot;failover:(%s)&quot;;
private final String awsAmqUrl;

public Config(String url, Optional&lt;String&gt; amqConnectionOptions, PropertiesManager propertiesManager) {
    String urlParameter = propertiesManager.getStringParameter(url);
    this.awsAmqUrl = constructAmqConnectionString(urlParameter, amqConnectionOptions);
}

private String constructAmqConnectionString(String urlParameter, Optional&lt;String&gt; connectionOptions) {
    if (connectionOptions.isPresent()) {
        urlParameter = Stream.of(urlParameter.split(&quot;,&quot;))
                .map(url -&gt; url + &quot;?&quot; + connectionOptions.get())
                .collect(Collectors.joining(&quot;,&quot;));
    }
    return String.format(AMQ_CONNECTION_URL_TEMPLATE, urlParameter);
}

public ConnectionFactory getConnectionFactory() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(awsAmqUrl);
    return connectionFactory;
}
}
</code></pre>
<p>I am struggling to find an optimal solution for <code>constructAmqConnectionString</code> method unit testing as it's marked as private.
There are 3 scenarios I am trying to cover:</p>
<ul>
<li><code>urlParameter</code> - comprises comma separated URLs (url1,url2),
<code>connectionOptions</code> is not empty;</li>
<li><code>urlParameter</code> - comprises comma
separated URLs (url1,url2), <code>connectionOptions</code> is empty;</li>
<li><code>urlParameter</code> - comprises single URL (url1), <code>connectionOptions</code> is
not empty.</li>
</ul>
<p>Current solution is to add a getter into Config class for <code>awsAmqUrl</code> field so that logic of constructor's call can be verified/tested:</p>
<pre><code>public String getAwsAmqUrl() {
    return this.awsAmqUrl;
}
</code></pre>
<p>Tests itself have following logic:</p>
<pre><code>@Test
public void verifyConstructorWithoutMqOptionsMultiBroker() {
    when(propertiesManager.getStringParameter(any())).thenReturn(&quot;url1,url2&quot;);
    Optional&lt;String&gt; amqConnectionOptions = Optional.empty();
    config = new Config(&quot;url1,url2&quot;, amqConnectionOptions, propertiesManager);
    assertEquals(String.format(&quot;failover:(url1,url2)&quot;),config.getAwsAmqUrl());
}

@Test
public void verifyConstructorWithMqOptionsMultiBroker() {
    when(propertiesManager.getStringParameter(any())).thenReturn(&quot;url1,url2&quot;);
    Optional&lt;String&gt; amqConnectionOptions = Optional.of(&quot;optionTest=1&quot;);
    config = new Config(&quot;url1,url2&quot;, amqConnectionOptions, propertiesManager);        
    assertEquals(String.format(&quot;failover:(url1?%1$s,url2?%1$s)&quot;,amqConnectionOptions.get()),config.getAwsAmqUrl());
}

@Test
public void verifyConstructorWithMqOptionsSingleBroker() {
    when(propertiesManager.getStringParameter(any())).thenReturn(&quot;url1&quot;);
    Optional&lt;String&gt; amqConnectionOptions = Optional.of(&quot;optionTest=1&quot;);
    config = new Config(&quot;url1&quot;, amqConnectionOptions, propertiesManager);                
    assertEquals(String.format(&quot;failover:(url1?%1$s)&quot;,amqConnectionOptions.get()),config.getAwsAmqUrl());
}
</code></pre>
<p>Adding a getter just for Unit testing purposes doesn't feel the right thing to do as it's breaking encapsulation.
Is there a better way to approach testing in such scenario?</p>
",https://stackoverflow.com/questions/72454451/java-constructor-unit-testing,"['java', 'unit-testing', 'junit']",62,True,0,1
xUnit GET results returning null,"<p>I'm new to unit testing and have been working on some simple tests but, am having issues trying to use <code>count()</code> to check the returned data.</p>
<p>Here is my test</p>
<pre><code>        [Fact]
        public async void Should_Call_Controller_Get_Return_200()
        {
            // Arrange
            var context = new HotelListingDbContext(dbContextOptions);
            var countriesService = new CountriesRepository(context, _mapper);
            var controller = new CountriesController(_mapper, countriesService);

            // Act
            var data = await controller.GetCountries();

            // Assert
            Assert.IsType&lt;OkObjectResult&gt;(data.Result);  
            data.Result.Should().NotBeNull();
            data.Value.Count.Should().Be(3);  // &lt;&lt;&lt; Object reference not set to an instance of an object.
        }
</code></pre>
<p>When I debug, <code>data</code> contains 3 items as per below:</p>
<p><a href=""https://i.stack.imgur.com/xgxVl.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/xgxVl.png"" alt=""results of getCountries()"" /></a></p>
<p>Could someone please explain what I should do? I can see that <code>Value</code> is null.</p>
<p>I have tried <code>data.Result.Value.Count</code> but the error states: &quot;ActionResult does not contain a definition for Value&quot; which is confusing me. I have also looked at using <code>Assert.Collection</code> but not sure this is relevant.</p>
<p>I have been looking at the MS docs for unit testing trying to apply it to my project, but am stuck here. I guess it's something to do with the ActionResult and a step I am missing.</p>
",https://stackoverflow.com/questions/74218416/xunit-get-results-returning-null,"['c#', 'xunit']",79,True,0,1
Unit testing an Exec stdout event NodeJS,"<p>I have below code.</p>
<pre><code>//utils.js
const cp = require('child_process');

module.exports.execuateBashCommand = ()=&gt; {
    return new Promise((resolve, reject)=&gt; {
        try {
            cp.exec('bash bash.sh').stdout.on('data', (response)=&gt; {
                if (response.toString().indexOf(&quot;Success&quot;) &gt; -1) {
                    //Some business logic
                    const result = &quot;working&quot;;
                    resolve(result);
                }
            });
        } catch (error) {
            console.log(&quot;Error&quot;, error);
            reject(error);
        }
    })
}
</code></pre>
<p>Here, there is an anonymous function that gets fired when a data event is emitted by stdout of exec process. I have no control over the output of bash.js, the desired response may take 5 to 10 seconds. Also I cannot add a timer and wait for this event to fire as I have mocked the exec response using sinon. So there is no real call to bash.js. So how can I emit this event manually and see if the business logic get computed? I am new to unit testing in Javascript. Currently I am using mocha and sinon for my unit testing requirements.</p>
<p>I have following test case, but it is not working as expected..</p>
<pre><code>//utils.test.js
 it(&quot;1. test case&quot;, (done)=&gt; {
        try {
            const mockStdout = new events.EventEmitter();
            mockStdout.on('data', ()=&gt; {
                return &quot;Success&quot;;
            });
            mockStdout.emit('data');
            sandbox.stub(cp.exec('test test'), 'stdout').returns(mockStdout);
            utils.execuateBashCommand().then((result)=&gt; {
                assert(data, &quot;working&quot;);
                done();
            });
        } catch (error) {
            console.log(&quot;Error in test cases: &quot;, error);
        }
    })
</code></pre>
<p>Please advice.</p>
",https://stackoverflow.com/questions/71570247/unit-testing-an-exec-stdout-event-nodejs,"['javascript', 'node.js', 'events', 'chai', 'sinon']",318,True,0,1
Having a common YAML file for PUSH and TAG based trigger in Google cloud build,"<p>I am trying to build a common YAML file for both push and tag-based triggers. I can build two YAML files and pass them to the triggers setting page in Google cloud build, but I want to have a common file for both of them.</p>
<p>In the push trigger, the YAML consists of unit testing and in the tag-based trigger, the YAML consists of unit testing and containerizing the application to be pushed to the artifact registry. As YAML is a text-formatting language and if/else conditions cannot be incorporated in it, how can I do this in one single file?</p>
<p>If you want any other information, please let me know and looking forward to help, thanks in advance</p>
",https://stackoverflow.com/questions/71031552/having-a-common-yaml-file-for-push-and-tag-based-trigger-in-google-cloud-build,"['python', 'google-cloud-platform', 'yaml', 'google-cloud-build']",301,True,0,1
Getting error while using useHeaderHeight() in unit-testing,"<p>Using <code>@react-navigation/stack</code> library in my project, while doing unit testing (using jest) I am getting this error</p>
<blockquote>
<p>Couldn't find the header height. Are you inside a screen in Stack?</p>
</blockquote>
<p>index.spec.js</p>
<pre><code>  it('should have a title and subtitle', () =&gt; {
  const { getByText } = render(&lt;Otp {...props} /&gt;);      });
</code></pre>
<p>Otp component</p>
<pre><code>&lt;SafeAreaView style={styles.mainContainer}&gt;
  &lt;KeyboardAvoidingView
    keyboardVerticalOffset={useHeaderHeight()} --&gt; getting error at this line
  &gt;
    &lt;Text&gt;...&lt;/Text&gt;
  &lt;/KeyboardAvoidingView&gt;
&lt;/SafeAreaView&gt;
</code></pre>
<p>Also tried a solution in which I mocked a navigator but got no success.</p>
",https://stackoverflow.com/questions/70894700/getting-error-while-using-useheaderheight-in-unit-testing,"['react-native', 'jestjs', 'react-navigation']",424,False,2,1
How to test Jackson CsvSchema library?,"<p>I would like to do a unit test of this example here:</p>
<p><a href=""https://huongdanjava.com/convert-json-to-csv-using-jackson-library.html"" rel=""nofollow noreferrer"">https://huongdanjava.com/convert-json-to-csv-using-jackson-library.html</a></p>
<p>I'm new to unit testing I don't understand much about it.</p>
<p>I would like to test this example to get coverage of Jacoco.</p>
",https://stackoverflow.com/questions/70654075/how-to-test-jackson-csvschema-library,"['java', 'jackson', 'junit5', 'quarkus', 'jacoco']",134,False,2,0
How to use mockito to test retrofit2 response?,"<p>With mockito, I want to test a retrofit response.
Can you guide me in this..
I am new in unit testing with mockito so if you can guide me try to explain your answer a little bit.</p>
<p>viewModel</p>
<pre><code>fun loginUser() {
        repository.loginUser(this, &quot;john@mail.com&quot;, &quot;changeme2&quot;)
    }
</code></pre>
<p>Repository class</p>
<pre><code>open class LoginRepository @Inject constructor() {
    fun loginUser(loginResponse: LoginResponse, email: String, password: String) {
        val result = RetrofitClient.getAPI(RetrofitClient.getInstance())
        var call = result.loginUser(email, password)
        call.enqueue(object : Callback&lt;JsonObject&gt; {
            override fun onResponse(call: Call&lt;JsonObject&gt;, response: Response&lt;JsonObject&gt;) {
                loginResponse.onSuccess()
            }

            override fun onFailure(call: Call&lt;JsonObject&gt;, t: Throwable) {
                loginResponse.onFail()
            }
        })
    }
}
</code></pre>
<p>Test class</p>
<pre><code>@RunWith(MockitoJUnitRunner::class)
class LoginViewModelMockTest {
    lateinit var loginViewModel: LoginViewModel
    lateinit var repository: LoginRepository
    lateinit var loginResponse: LoginResponse

    @Before
    fun setUp() {
        loginResponse=mock(LoginResponse::class.java)
        repository = mock(LoginRepository::class.java)
        loginViewModel = LoginViewModel(repository)
    }

    @Test
    fun loginUser_loginUserCalled_onSuccessShouldCalled() {
        loginViewModel.loginUser()
        `when`(repository.loginUser(loginResponse, &quot;john@mail.com&quot;, &quot;changeme2&quot;)).then{
            (it.getArgument(2) as LoginResponse).onSuccess()
        }
        verify(loginResponse).onSuccess()
    }


}
</code></pre>
",https://stackoverflow.com/questions/74244237/how-to-use-mockito-to-test-retrofit2-response,"['unit-testing', 'mockito', 'retrofit2', 'android-testing', 'mockito-kotlin']",52,False,0,0
How to Unit Test CrudRepository without @DataJpaTest in Spring Framework,"<p>I wanted to write unit test for the following UserRepository in Spring Framework application:</p>
<pre><code>@Repository
public interface UserRepository extends CrudRepository&lt;User, Long&gt; {
    User findByEmail(String email);
}
</code></pre>
<p>But canFindUserByEmail() test fails because underTest is null</p>
<pre><code>@ExtendWith(MockitoExtension.class)
public class UserRepositoryTest {

    @Autowired
    private UserRepository underTest;


    @Test
    public void canFindUserByEmail() {
        // given
        User expectedUser = new User();
        expectedUser.setEmail(&quot;user@gmail.com&quot;);
        underTest.save(expectedUser);

        // when
        final User actualUser = underTest.findByEmail(expectedUser.getEmail());

        // then
        assertThat(actualUser).isEqualTo(expectedUser);
    }
}
</code></pre>
<p>When I add the next annotations it works, but are they intended for integration testing, not for unit testing?</p>
<pre><code>@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = {SpringConfig.class})
@WebAppConfiguration()
</code></pre>
<p>Thanks!</p>
",https://stackoverflow.com/questions/71936676/how-to-unit-test-crudrepository-without-datajpatest-in-spring-framework,"['java', 'spring', 'junit', 'spring-data-jpa', 'crud-repository']",1081,False,0,0
How to mock setting static class property in legacy Java code for JUnit 4 unit testing,"<p>I am writing unit tests using JUnit 4.13 and Mockito core 4.9.0. Following is a simplified version of the class being tested which is part of a legacy code that I don't want to refactor:</p>
<pre><code>//JAR com.ibm.mq-8.0.jar
import com.ibm.mq.MQEnvironment;
public class LegacyCodeToTest
  public void doSomething() {
    ...some other code
    MQEnvironment.sslCipherSuite = &quot;some-cipher-value&quot;;
    ...some other code
  }
}
</code></pre>
<p>Following is the unit test:</p>
<pre><code>@RunWith(MockitoJUnitRunner.class)
public class TestLegacyCodeToTest {
  @Test
  public void testDoSomething() {
    LegacyCodeToTest someVar = new LegacyCodeToTest();
    mock(MQEnvironment.class);
    when(MQEnvironment.sslCipherSuite).thenReturn(null);
    someVar.doSomthing();
  }
}
</code></pre>
<p>The problem I am facing is that the unit I am working with needs many other dependencies I cannot provide during unit testing and the line of code <code>MQEnvironment.sslCipherSuite = &quot;some-cipher-value&quot;</code> or even just referencing <code>MQEnvironment.sslCipherSuite</code> in the test is causing the run to crash due to missing dependencies which I cannot troubleshoot. I want to mock this line of code so that it has no effect as if it doesn't exist and I don't care about it during unit testing. Now I had to comment out this line to let it work.</p>
<p>Also, I know there is something wrong with the way I implemented mocking but I could not even reach that point since the test is crashing due to missing dependencies.</p>
<p>So, the bottom line is how I can mock such a line of code:</p>
<pre><code>MQEnvironment.sslCipherSuite = &quot;some-cipher-value&quot;;
</code></pre>
<p>Mind you, I don't want to refactor the class as this will raise the need to trigger writing a lot of other unit testing and it won't be allowed.</p>
",https://stackoverflow.com/questions/74847806/how-to-mock-setting-static-class-property-in-legacy-java-code-for-junit-4-unit-t,"['java', 'unit-testing', 'mockito', 'junit4', 'static-members']",106,True,0,1
unit test cases for databricks notebook,"<p>I have  5 files which I'm fetching and using it to create a dataframe, I'm using these dataframes to create table and left join tables.
I wanted to know what all unit testing should be done and how to write unit test case</p>
",https://stackoverflow.com/questions/73048518/unit-test-cases-for-databricks-notebook,"['azure-databricks', 'azure-data-factory']",1227,False,0,1
Jest mocking Prisma client with connection string,"<p>I made a client that is more flexible when it comes to providing connections using the Prisma ORM. I want to mock this service and produce mock values during testing.</p>
<p><strong>prismaService.ts</strong></p>
<pre><code>import { PrismaClient } from '@prisma/client'

const client = (connectionString?: string): PrismaClient =&gt;
  new PrismaClient({
    datasources: {
      db: {
        url: connectionString || process.env.DATABASE_URL,
    },
  },
})

export default client
</code></pre>
<p><strong>prismaMock.ts</strong></p>
<pre><code>import { PrismaClient } from '@prisma/client'
import { mockDeep, mockReset, DeepMockProxy } from 'jest-mock-extended'

import PrismaService from '../clients/prismaService'

jest.mock('../clients/prismaService', () =&gt; ({
  __esModule: true,
  default: jest.fn().mockImplementation(PrismaClient as any),
}))


const prismaMock = PrismaService as unknown as DeepMockProxy&lt;PrismaClient&gt;

beforeEach(() =&gt; {
  mockReset(prismaMock)
})

export default prismaMock
</code></pre>
<p><strong>Test</strong></p>
<pre><code>import { randomUUID } from 'crypto'

import prismaMock from '../prismaMock'
import PrismaService from '../../clients/prismaService'

describe('Prisma Mock Database Table Test', () =&gt; {
  it('should mock resolved value', async () =&gt; {
    const client = PrismaService()

    const customer = {
      id: randomUUID(),
      name: 'Customer 1',
      status: null,
      data: {},
      createdAt: new Date(),
      updatedAt: new Date(),
    }

    prismaMock.customer.create.mockResolvedValue(customer)

    const x = await client.customer.create({ data: customer })
    expect(x).toEqual(customer)
  })
})
</code></pre>
<p><strong>Error</strong></p>
<pre><code>      TypeError: Cannot read properties of undefined (reading 'create')

      17 |     }
      18 |
    &gt; 19 |     prismaMock.customer.create.mockResolvedValue(customer)
         |                         ^
      20 |
      21 |     const x = await client.customer.create({ data: customer })
      22 |     expect(x).toEqual(customer)
</code></pre>
<p>References Used:</p>
<ul>
<li><a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""nofollow noreferrer"">https://www.prisma.io/docs/guides/testing/unit-testing</a></li>
</ul>
",https://stackoverflow.com/questions/73361646/jest-mocking-prisma-client-with-connection-string,"['node.js', 'unit-testing', 'jestjs', 'prisma', 'ts-jest']",551,False,0,0
@vue/cli and unit tests,"<p>I am running @vue/cli it is version 4.5.15. I am wanting to write some tests for my components when I run,</p>
<p><code>yarn test:unit</code></p>
<p>I get an error</p>
<blockquote>
<p>ERROR command &quot;test:unit&quot; does not exist.</p>
</blockquote>
<p>Is there some further setup I need to get unit testing running?</p>
",https://stackoverflow.com/questions/70968464/vue-cli-and-unit-tests,"['javascript', 'vue.js', 'tdd', 'vue-cli']",191,True,1,1
Why do I need verify() when I already have expectOne()?,"<p>I am learning Angular unit testing from some online courses.</p>
<p>Here is a part of the code.</p>
<pre><code>  it(&quot;should find a course by id&quot;, () =&gt; {
    coursesService.findCourseById(12).subscribe((course) =&gt; {
      expect(course).toBeTruthy();
      expect(course.id).toBe(12);
    });
    const req = httpTestingController.expectOne(&quot;/api/courses/12&quot;);

    expect(req.request.method).toEqual(&quot;GET&quot;);
    req.flush(COURSES[12]);

    httpTestingController.verify(); 

  });
</code></pre>
<p>The definition of <code>verify()</code> on the angular document is:</p>
<blockquote>
<p>Verify that no unmatched requests are outstanding.</p>
</blockquote>
<p>I was wondering why I need to call <code>verify()</code> when I already called <code>expectOne()</code>.</p>
",https://stackoverflow.com/questions/73781136/why-do-i-need-verify-when-i-already-have-expectone,"['angular', 'unit-testing']",48,True,1,1
Ktor - Unit testing is throwing 404,"<p>I have a simple program in Ktor. It runs perfectly, but when I run the unit testing class it only throws this error: &quot;expected:&lt;200 OK&gt; but was:&lt;404 Not Found&gt;&quot;</p>
<p>This is my unit test code:</p>
<pre><code>class ApplicationTest {
@Test
fun testRoot() = testApplication {
    val response = client.get(&quot;/&quot;)
    assertEquals(HttpStatusCode.OK, response.status)
}

@Test
fun testStart() = testApplication {
    val response = client.post(&quot;/start&quot;)
    assertEquals(HttpStatusCode.OK, response.status)
}
}
</code></pre>
<p>This is my Application.kt:</p>
<pre><code>const val enableHTTPS = false
const val portHTTP = 80
const val portHTTPS = 7001


lateinit var environment: ApplicationEngineEnvironment
fun main() {
    initEnvironment()

    embeddedServer(Netty, environment = environment).start(wait = true)
}

</code></pre>
<p>My routing file is:</p>
<pre><code>fun Application.configureRouting() {
    routing {
        get {
            call.respond(ApiDetails())
        }

        post(&quot;/start&quot;) {
            call.response.status(HttpStatusCode.OK)
        }

        post(&quot;/move&quot;) {
            val gameDetails: GameDetails = call.receive()
            val move = BasicStrategy().move(gameDetails, application)

            call.respond(move)
        }

        post(&quot;/end&quot;) {
        }
    }
}

</code></pre>
",https://stackoverflow.com/questions/72317906/ktor-unit-testing-is-throwing-404,"['unit-testing', 'kotlin', 'junit', 'httprequest', 'ktor']",727,True,1,1
What is difference between factory and factoryboy package?,"<p>I am new to the factoryboy package i want to use this for unit testing of my django app, previously i used factory package,</p>
<p>i want to know the exact difference between this 2 package becuase syntax and structure is almost same in both package</p>
",https://stackoverflow.com/questions/74822766/what-is-difference-between-factory-and-factoryboy-package,"['django', 'factory', 'factory-boy']",23,False,1,0
The above error occurred in the &lt;ScrollView&gt; component,"<p>console.error
The above error occurred in the  component:</p>
<pre><code>      at ScrollViewMock (/Users/arqum/Desktop/support/faveo-support-app/node_modules/react-native/jest/mockScrollView.js:21:52)
      at _class (/Users/arqum/Desktop/support/faveo-support-app/node_modules/react-native-keyboard-aware-scroll-view/lib/KeyboardAwareHOC.js:199:47)
      at View
      at Component (/Users/arqum/Desktop/support/faveo-support-app/node_modules/react-native/jest/mockComponent.js:28:18)
      at ChangePasswordScreen (/Users/arqum/Desktop/support/faveo-support-app/src/components/functionality/LoginUser/ChangePassword/ChangePassword.js:17:24)
  
  Consider adding an error boundary to your tree to customize error handling behavior.
  Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

  at logCapturedError (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:10989:23)
  at update.callback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11022:5)
  at callCallback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:3662:12)
  at commitUpdateQueue (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:3683:9)
  at commitLifeCycles (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11855:11)
  at commitLayoutEffects (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14443:7)
  at Object.invokeGuardedCallbackProd (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11308:10)
  at invokeGuardedCallback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11499:31)
</code></pre>
<p>● Language Screen Components and Unit Testing › Get Update Language Component</p>
<pre><code>TypeError: Cannot read properties of undefined (reading 'major')

  at Object.extractNativeRef (node_modules/react-native-keyboard-aware-scroll-view/lib/KeyboardAwareHOC.js:135:93)
  at _this._handleRef (node_modules/react-native-keyboard-aware-scroll-view/lib/KeyboardAwareHOC.js:508:52)
  at commitAttachRef (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11992:7)
  at commitLayoutEffects (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14448:9)
  at Object.invokeGuardedCallbackProd (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11308:10)
  at invokeGuardedCallback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11499:31)
  at commitRootImpl (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14172:9)
  at unstable_runWithPriority (node_modules/scheduler/cjs/scheduler.development.js:468:12)
  at runWithPriority (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2486:10)
  at commitRoot (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14011:3)
</code></pre>
<p>Test Suites: 1 failed, 1 passed, 2 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        1.379 s, estimated 2 s
Ran all test suites.</p>
",https://stackoverflow.com/questions/71173114/the-above-error-occurred-in-the-scrollview-component,"['javascript', 'react-native', 'jestjs', 'scrollview']",440,False,2,1
How to write a makefile that uses a common library and build subdirectories?,"<p>I have a project that has multiple subdirectories and I have a unit testing framework (UnitTest++) in the following folder structure:</p>
<pre><code>root_dir
├── sub_dir1
│   ├── main.cpp
│   ├── some_class.hpp
│   └── test.cpp
├── sub_dir2
│   ├── another_class.hpp
│   ├── main.cpp
│   └── test.cpp
├── UnitTest++
│   ├── libUnitTest++.a
└── makefile
</code></pre>
<p>I plan to have more <code>sub_dir#</code> in the future.
How do I use <code>make</code> in the root directory so that it would compile all the subdirectories?</p>
",https://stackoverflow.com/questions/72933603/how-to-write-a-makefile-that-uses-a-common-library-and-build-subdirectories,"['c++', 'makefile']",29,False,0,0
Unit testcases for data present in side the &lt;h1&gt; tag,"<p>I wan to do testing for the element which are present in my react code using Unit testing through  mocha in Istanbul tool.</p>
<p>writing a unit testcases for h1 tag which consist of some heading, how we caan write aunit test case for this</p>
",https://stackoverflow.com/questions/71320834/unit-testcases-for-data-present-in-side-the-h1-tag,"['javascript', 'unit-testing', 'mocha.js', 'istanbul']",337,False,0,0
how to mock http headers and body using junit?,"<p>I am working on a spring api gateway. There is a class <code>LoggingMethods</code> which i want to test.
It contains two methods  <code>appendBodyRequest</code> and <code>logRequestNoBody</code>.</p>
<pre><code>Public class LoggingMethods{

  LoggingMethods(ServerHttpRequest request){
  }
  void appendBodyrequest(ByteBuffer byteBuffer , ServerHttpRequest request){
   Log.info(&quot;Headers:[{}] , Body:[{}]&quot; , request.getHeaders().toSingleValueMap(),
   StandardCharsets.UTF_8.decode(byteBuffer)); 
  }
   
  void logRequestNoBody(ServerHttpRequest request){
  Log.info(&quot;{} response has no body.&quot;,request.getMethod());
  }
}

</code></pre>
<p>I am not sure how to implement unit testing with JUnit with mock headers and body.
Appreciate your help and suggestions!
Thanks.</p>
",https://stackoverflow.com/questions/72618306/how-to-mock-http-headers-and-body-using-junit,"['java', 'spring-boot', 'unit-testing', 'junit', 'mockito']",3148,True,0,1
python unittest : test adressing non existent properly does not fail as expected,"<p>I am learning Python unit testing using <strong>unittest</strong> module.<br />
I stumbled accross a strange behavior.
Consider this code :</p>
<pre><code>import unittest
class Foo:
    pass
    
class FooTest(unittest.TestCase):
    def test_non_existent_property(self):
        foo = Foo()
        self.assertTrue(0, len(foo.class_name))
        
    def test_assigning_name(self):
        foo = Foo()
        foo.class_name = 'bar'
        self.assertEqual('bar', foo.class_name)
    
unittest.main()
</code></pre>
<p>The tests results are :</p>
<pre><code>ERROR: test_non_existent_property (__main__.FooTest)  
----------------------------------------------------------------------  
Traceback (most recent call last):  
    File &quot;&lt;pyshell#28&gt;&quot;, line 4, in test_non_existent_property  
AttributeError: 'Foo' object has no attribute 'class_name'  
----------------------------------------------------------------------  
Ran 2 tests in 0.037s  

FAILED (errors=1)  
</code></pre>
<p>The first test fails as expected.<br />
But the second test passes, and this puzzles me.<br />
Shouldn't it fail too ? Why doesn't it fail ?</p>
",https://stackoverflow.com/questions/71537660/python-unittest-test-adressing-non-existent-properly-does-not-fail-as-expected,"['python', 'python-unittest']",39,True,0,1
jest.toThrow unable to catch exception?,"<p>I have a simple function as below</p>
<pre class=""lang-js prettyprint-override""><code>function foo({ platform }) {
  if (platform === 'all') {
    throw new Error('Platform value can only be android or ios');
  }
  
  return `${platform}`;
}
</code></pre>
<p>Then I wrote unit testing as below</p>
<pre class=""lang-js prettyprint-override""><code>it('should return correct result with platform', () =&gt; {
    expect(foo({ platform: 'ios' })).toBe('ios');
    expect(foo({ platform: 'android' })).toBe('android');
    expect(foo({platform: 'all'})).toThrow(new Error('Platform value can only be android or ios'));
  });
</code></pre>
<p>The test actually failed due to last test case without any useful information</p>
<pre class=""lang-sh prettyprint-override""><code> FAIL  src/utils/__test__/foo.test.ts
  ● foo() › should return correct result with platform

    Platform value can only be android or ios

      16 | }) {
      17 |   if (platform === 'all') {
    &gt; 18 |     throw new Error('Platform value can only be android or ios');
         |           ^
      19 |   }
      20 |   
      21 |   return `${platform}`;

      at xx (src/utils/foo.ts:18:11)
</code></pre>
<p>I've also tried to wrapped the entire <code>expect</code> with try catch block but the test is not passing either</p>
",https://stackoverflow.com/questions/70828182/jest-tothrow-unable-to-catch-exception,"['javascript', 'typescript', 'jestjs']",704,True,-1,1
"TypeError: json() missing 1 required positional argument: &#39;self&#39; Python, Github API","<p>I need to get all the GitHub branches of a certain repository. Using the GitHub API as documented here, <a href=""https://developer.github.com/v3/repos/branches/#list-branches"" rel=""nofollow noreferrer"">https://developer.github.com/v3/repos/branches/#list-branches</a> I try to use the GET request documented.</p>
<p>However, when I try unit testing, I get <code>TypeError: json() missing 1 required positional argument: 'self'</code> at <code>if len(response.json()) == 0:</code></p>
<pre><code>class GithubService:

    @staticmethod
    def get_branches(git_base, org, repo):

        github_repo_url = f&quot;https://api.github.com/repos/{org}/{repo}&quot;
        collected_all_branches: bool = False
        page = 1
        github_branches = []
        # collect all branches in repo
        while not collected_all_branches:
            response = (requests.get(f&quot;{github_repo_url}/branches/?per_page=100&amp;page={page}&quot;,
                                     headers=HEADERS))
            print(&quot;response&quot;)
            print(response)
            if len(response.json()) == 0:
                collected_all_branches = True
            else:
                github_branches.extend([response[&quot;name&quot;] for response in response.json()])
            page = page + 1
        return github_branches
</code></pre>
<p>Unit Test:</p>
<pre><code>    @patch.object(requests, &quot;get&quot;, return_value=Response)
    def test_get_branches(self, mock_get):

        GithubService.get_branches(&quot;test&quot;, &quot;test&quot;, &quot;test&quot;)
        mock_get.assert_called_with(&quot;test&quot;, &quot;test&quot;, &quot;test&quot;)

</code></pre>
",https://stackoverflow.com/questions/73251629/typeerror-json-missing-1-required-positional-argument-self-python-github,"['python', 'python-3.x', 'github-api']",225,False,0,0
Laravel API Testing always returning middleware error,"<p>I have created laravel backend related few of end points. how ever when I trying to test it using unit testing always returning 'Get the application's route middleware groups' error. Please help me to resolve this.</p>
<p><strong>my test file is</strong></p>
<pre><code>&lt;?php

namespace Tests\Feature;

use App\Models\User;
use Exception;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class FetchDamageRequestListTest extends TestCase
{
public function test_fetch_damage_request_list()
{
    $this-&gt;withoutExceptionHandling();

    $payload = [
    ];
    $headers = [
        'Accept' =&gt; 'application/json',
        'Content-Type' =&gt; 'application/json'
    ];

    $user = Sanctum::actingAs(User::factory()-&gt;create(),['*']);

    $response = $this-&gt;actingAs($user)- 
    &gt;post('/api/web/v1/fetch_dashboard_info',$payload, $headers);
    $response-&gt;assertStatus(200);
   }
 }
</code></pre>
<p><strong>my routes</strong></p>
<pre><code>&lt;?php

 use App\Http\Controllers\API\V1\DamageReportController;
 use App\Http\Controllers\API\V1\DashboardController;
 use App\Http\Controllers\API\V1\UserController;
 use Illuminate\Support\Facades\Route;

 Route::post('login', [UserController::class, 'login'])-&gt;name('login');
 Route::post('logout', [UserController::class, 'logout'])-&gt;name('logout');

 Route::group(['middleware' =&gt; ['auth:sanctum']], function () {
   Route::post('save_damage_request', [DamageReportController::class, 
   'saveDamageReportRequest'])-&gt;name('save_damage_request');
   Route::post('fetch_damage_request', [DamageReportController::class, 
   'fetchDamageReportRequest'])-&gt;name('fetch_damage_request');
   Route::post('fetch_damage_request_details', [DamageReportController::class, 
   'fetchDamageReportRequestDetails']);
   Route::post('approve_damage_request', [DamageReportController::class, 
   'approveDamageReportRequest']);
   Route::post('fetch_damage_request_reason', [DamageReportController::class, 
   'fetchDamageReportReason']);
   Route::post('reject_damage_request', [DamageReportController::class, 
   'rejectDamageReportRequest']);

   Route::post('fetch_dashboard_info', [DashboardController::class, 
   'fetchDashboardInfo']);
});
</code></pre>
<p><strong>The error is</strong>
<a href=""https://i.stack.imgur.com/AX6Q1.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/AX6Q1.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73919462/laravel-api-testing-always-returning-middleware-error,"['laravel', 'phpunit', 'laravel-8', 'laravel-sanctum']",233,False,0,1
Vitest monaco-editor &#39;document.createElement(...).getContext is not a function&#39;,"<p>I've been building editor on <code>monaco-editor</code> and Vue, and trying unit testing.
<br />
This is my utility <code>useMonaco.ts</code></p>
<pre><code>import { editor } from 'monaco-editor';
import type { editor as Editor } from 'monaco-editor';

function useMonaco(
  element: HTMLElement,
  language: string,
  args?: Editor.IStandaloneEditorConstructionOptions
) {

  const monacoEditor = editor.create(element, {
    language,
    theme: 'vs-dark',
    minimap: {
      enabled: false,
    },
    ...args,
  });

  return monacoEditor;
}
</code></pre>
<p>But when it comes to testing this utility, Vitest warns <code>'document.createElement(...).getContext is not a function'</code>.
The error is from <code>monaco-editor</code> source below.</p>
<pre><code>  _getPixelRatio() {
        const ctx = document.createElement('canvas').getContext('2d');
        const dpr = window.devicePixelRatio || 1;
        const bsr = ctx.webkitBackingStorePixelRatio ||
            ctx.mozBackingStorePixelRatio ||
            ctx.msBackingStorePixelRatio ||
            ctx.oBackingStorePixelRatio ||
            ctx.backingStorePixelRatio || 1;
        return dpr / bsr;
    }
</code></pre>
<p>But I've already register <code>environment: 'happy-dom'</code> in <code>vite.config.js</code>. Has Anyone ever encountered this? appreciate in advance.</p>
",https://stackoverflow.com/questions/74410899/vitest-monaco-editor-document-createelement-getcontext-is-not-a-function,"['unit-testing', 'vuejs3', 'monaco-editor', 'vitest']",190,False,0,0
Mockito - Test Nested Loop with functions within inner loop,"<p>I am beginer in unit testing. I use JUnit and Mockito. This is one example method which I want to test.</p>
<pre><code>public Void getPeopleNumbersList(List&lt;Aggregate&lt;Person&gt;&gt; aggregateList) {
    for (List&lt;Person&gt; person : peopleList) {
        List&lt;PhoneNumber&gt; phoneNumbersList = getPhoneNumbers(person);
        for (PhoneNumber phoneNumber : phoneNumbersList) {
            //Some functions to do some DB operations. 
            DynamoDB.update(phoneNumber); // Just an example

        }
    }
    
}
</code></pre>
<p>How do I test if operation/function (here, it is update call) is called for each phone number of each person in Mockito?</p>
",https://stackoverflow.com/questions/73030159/mockito-test-nested-loop-with-functions-within-inner-loop,"['unit-testing', 'testing', 'junit', 'mockito', 'junit5']",128,False,0,2
Owner of smart contract on hardhat development network is being returned 0x00000,"<p>I was trying to deploy my smart contract through unit testing using hardhat. The owner upon deployment is being returned as 0x0000.. although when writing my js script i assign a certain address from the hardhat network as the owner.</p>
<pre><code>const  hre = require('hardhat')
const { expect, assert } = require('chai')

describe('ProperSubsetFund', async function () {
  // Initialize Contract Var
  let deployERC20, deployer, user1, user2, trader1, trader2
  let signers

  beforeEach(async function () {
    // Getting all the signers
    signers = await hre.ethers.getSigners()
    // console.log(signers.map(item =&gt; item.address));

    // Assign addresses to roles for later use
    deployer = signers[0].address
    user1 = signers[1].address
    user2 = signers[2].address
    trader1 = signers[3].address
    trader2 = signers[4].address

    // Read Contract ERC20
    const contractERC20 = await hre.ethers.getContractFactory('ProperSubsetERC20')
    // Read Contract Launchpad
    const contractLaunchpad = await hre.ethers.getContractFactory('ProperSubsetFactory')
    // Read Contract Funds
    const contractFunds = await hre.ethers.getContractFactory('ProperSubsetFund')

    // Deploy the three contracts
    deployERC20 = await contractERC20.connect(signers[0]).deploy(true)
    
  });

  describe('Deployment and Ownership', function () {
    it('Check if the owner is the deployer', async function () {

        expect(await deployERC20.owner()).to.equal(deployer)
    });
  });
})

</code></pre>
<p>These are the results</p>
<pre><code> ProperSubsetFund
       Deployment and Ownership
         Deployment
           Should set the right owner:

      AssertionError: expected '0x00000000000000000000000000000000000…' to equal '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb…'
      + expected - actual

      -0x0000000000000000000000000000000000000000
      +0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266
      
      at Context.&lt;anonymous&gt; (test/ProperSubsetFund.test.js:71:49)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)

</code></pre>
",https://stackoverflow.com/questions/74386781/owner-of-smart-contract-on-hardhat-development-network-is-being-returned-0x00000,"['unit-testing', 'solidity', 'smartcontracts', 'hardhat']",152,True,0,1
"how to do Unit testing in flutter,Mockito when we make a post request using Dio package?","<p><strong>Dio request for login authentication</strong></p>
<pre><code> Future&lt;String?&gt; authentication(String mobileNumber, String password, Dio dio) async {
    dynamic data = {
      &quot;username&quot;: mobileNumber,
      &quot;password&quot;: password,
      &quot;grant_type&quot;: &quot;password&quot;,
      &quot;client_id&quot;: &quot;client_id&quot;
    };

    try {
      final response = await _dio.post(baseurl,
          data: data,
          options: Options(headers: {
            &quot;Content-Type&quot;: &quot;application/x-www-form-urlencoded&quot;
          })); //'Authorization': 'Bearer $token
      if (response.statusCode == 200) {
        accessToken = response.data[&quot;access_token&quot;];
        refreshToken = response.data[&quot;refresh_token&quot;];
        Fluttertoast.showToast(msg: &quot;Successfully Logged in&quot;);
        return accessToken;
      }
    }on DioError catch (e) {
      Fluttertoast.showToast(msg: &quot;Something went wrong&quot;);
      return e.toString();
  }
  return accessToken;
  }


</code></pre>
<p>**Unit testing **</p>
<pre><code>
 MockDio mockDio = MockDio();

 test(&quot;if authentication successfull token will return  &quot;, () async {
 

when(mockDio.post(Apiservices().baseurl)).thenAnswer((_)async =&gt;*need return a response????*
  );

      expect(await service.authentication(&quot;username&quot;, &quot;password&quot;, mockDio),
          isA&lt;String&gt;());
    });
</code></pre>
<p>I need to check the login auth testing using dio and mockito packages.
It will return a token.
I am not able to do the mocking.</p>
<p>Please give a details example of this.
or give me some reference</p>
",https://stackoverflow.com/questions/74597402/how-to-do-unit-testing-in-flutter-mockito-when-we-make-a-post-request-using-dio,"['java', 'android', 'flutter', 'unit-testing', 'testing']",301,True,0,1
How to unit test firestore rules with token.firebase.identities,"<p>Just trying to test rules with google login and phone login e.g. <code>request.auth.token.firebase.identities[&quot;google.com&quot;]</code>, But I can't find any document about <code>firebase.initializeTestApp</code> from '@firebase/rules-unit-testing' package. The offical <a href=""https://www.youtube.com/watch?v=VDulvfBpzZE"" rel=""nofollow noreferrer"">video</a> only mentioned about initialize with userId and email. Anyone know How to test this kind of rules?</p>
",https://stackoverflow.com/questions/73148643/how-to-unit-test-firestore-rules-with-token-firebase-identities,"['firebase', 'google-cloud-firestore', 'firebase-security']",116,True,0,1
Jest Unit Test to see if Function is defined with specific argument,"<p>Brand new to JS and Unit Testing. Trying to test if <code>getPrices()</code> has the argument <code>taxBoolean</code> defined. So all I'm trying to test is that the following would be true:</p>
<pre><code>function getPrices(){ //add code here };
</code></pre>
<p>Here is what I have tried based off an example I found.
<strong>The funcitons</strong></p>
<pre><code>function getPrices() {

}


// Implement getDiscount()
function getDiscount() {
    
}

// Call getDiscount()

module.exports = {getPrices, getDiscount};
</code></pre>
<p><strong>The Unit Tests</strong></p>
<pre><code>const {getPrices, getDiscount} = require(`./finalProject`);

test('returns true if getPrices exists', () =&gt; {
    expect(getPrices).toBeDefined();
})

test('returns true if getDiscount exists', () =&gt; {
    expect(getDiscount).toBeDefined();
})

test('test console log inside getPrices', () =&gt; {
    expect(getPrices(taxBoolean)).toBe(true)
})
</code></pre>
",https://stackoverflow.com/questions/73841907/jest-unit-test-to-see-if-function-is-defined-with-specific-argument,"['javascript', 'unit-testing', 'jestjs']",53,False,0,1
Karma Unit Test for Modals in Bootstrap,"<p>I am new to unit testing in angular.
I have to write unit test for Modal from ‘angular2-modal/plugins/bootstrap’</p>
<p>constructor(private modal : Modal)</p>
<p>this.modal.alert().size(‘lg’).title(‘’).body(‘’).open().then()</p>
<p>can any one please help me in writting test case for this?</p>
",https://stackoverflow.com/questions/74106186/karma-unit-test-for-modals-in-bootstrap,"['angular', 'unit-testing', 'bootstrap-modal']",27,False,0,0
Unit Test: Should I write test for branch or called methods?,"<p>When I write Unit Test, sometimes I faced situations as shown below. There is a method <code>createOrUpdate</code> that calls another methods based on a condition. In this scene, I have 2 options:</p>
<p><strong>1.</strong> I can write a test for all of 3 methods and in the first test method (<code>createOrUpdate</code>), just verify if the other methods (<code>create</code> or <code>update</code>) is called. In the other test methods, I write test as usually written.</p>
<p><strong>2.</strong> I can write multiple tests just for the first method (<code>createOrUpdate</code>) and test the other 2 methods based on the condition. Then I think I could test all of these 3 methods.</p>
<p>As I am new in Unit Testing, I just wanted to be clarified which approach is a proper or suitable approach for Unit Testing. Any help would be appreciated.</p>
<p><em><strong>countryService:</strong></em></p>
<pre><code>public CountryDTO createOrUpdate(UUID uuid) {
    if (countryRepository.existsByUuid())
        return update(uuid);
    else
        return create(uuid);
}


public CountryDTO create(UUID uuid) {
    // ...    
}


public CountryDTO update(UUID uuid) {
    // ...
}
</code></pre>
",https://stackoverflow.com/questions/71642982/unit-test-should-i-write-test-for-branch-or-called-methods,"['java', 'unit-testing', 'testing', 'junit', 'mockito']",298,False,1,2
Writing an instance of Eq for Fix (Haskell),"<p>I'm using <code>Fix</code> to define some datatypes for a project I'm working on. I need those datatypes to be instances of the equality typeclass <code>Eq</code> for unit testing. I'm stumped on how to write an instance of <code>Eq</code> for <code>Fix</code> or more specifically <code>List</code> defined in terms of <code>Fix</code>.</p>
<p>My <code>Fix</code>:</p>
<pre><code>-- Fixed point of a Functor  
newtype Fix f = In (f (Fix f))                                                               
                                                                                             
out :: Fix f -&gt; f (Fix f)                                                                    
out (In f) = f  
</code></pre>
<p>My <code>List</code> in terms of <code>Fix</code>:</p>
<pre><code>data ListF a r = NilF | ConsF a r 

instance Functor (ListF a) where                                                          
       fmap _ NilF = NilF                                                                
       fmap f (ConsF a r) = ConsF a (f r)                                                
                                                                                            
type ListF' a = Fix (ListF a) 
</code></pre>
",https://stackoverflow.com/questions/73318416/writing-an-instance-of-eq-for-fix-haskell,"['haskell', 'functor']",214,True,3,2
"custom hook testing: when testing, code that causes React state updates should be wrapped into act(...):","<p>Following this tutorial <a href=""https://www.richardkotze.com/coding/mocking-react-hooks-unit-testing-jest"" rel=""nofollow noreferrer"">https://www.richardkotze.com/coding/mocking-react-hooks-unit-testing-jest</a>, but getting this error even though the test passes, why is this error occurring and is there something missing from the test? code copied here for convenience</p>
<pre><code> PASS  src/use-the-fetch.spec.js
  ● Console

    console.error
      Warning: An update to TestComponent inside a test was not wrapped in act(...).
      
      When testing, code that causes React state updates should be wrapped into act(...):
      
      act(() =&gt; {
        /* fire events that update state */
      });
      /* assert on the output */
      
      This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
          at TestComponent (~/Documents/projects/my-app/node_modules/@testing-library/react-hooks/lib/helpers/createTestHarness.js:22:5)
          at Suspense
          at ErrorBoundary (~/Documents/projects/my-app/node_modules/react-error-boundary/dist/react-error-boundary.cjs.js:59:35)

       5 |   async function fetchData() {
       6 |     const data = await getStarWars(path); // being mocked
    &gt;  7 |     setResult({ loading: false, data });
         |     ^
       8 |   }
       9 |   useEffect(() =&gt; {
      10 |     fetchData();

      at console.error (node_modules/@testing-library/react-hooks/lib/core/console.js:19:7)
      at printWarning (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:68:30)
      at error (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:44:5)
      at warnIfNotCurrentlyActingUpdatesInDEV (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:15034:9)
      at setResult (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:7129:9)
      at fetchData (src/use-the-fetch.js:7:5)
</code></pre>
<p>use-the-fetch.spec.js</p>
<pre><code>import { renderHook } from &quot;@testing-library/react-hooks&quot;;
import { useTheFetch } from &quot;./use-the-fetch&quot;;
import { getStarWars } from &quot;./base-fetch&quot;;
jest.mock(&quot;./base-fetch&quot;);

describe(&quot;use the fetch&quot;, () =&gt; {
  it(&quot;initial data state is loading and data empty&quot;, () =&gt; {
    const { result } = renderHook(() =&gt; useTheFetch(&quot;people&quot;));

    expect(result.current).toStrictEqual({ loading: true, data: null });
  });

  it(&quot;data is fetched and loading is complete&quot;, async () =&gt; {
    const fakeSWData = { result: [{ name: &quot;Luke Skywalker&quot; }] };
    getStarWars.mockResolvedValue(fakeSWData);

    const { result, waitForNextUpdate } = renderHook(() =&gt;
      useTheFetch(&quot;people&quot;)
    );

    await waitForNextUpdate();

    expect(getStarWars).toBeCalledWith(&quot;people&quot;);
    expect(result.current).toStrictEqual({
      loading: false,
      data: fakeSWData,
    });
  });
});
</code></pre>
<p>use-the-fetch.js</p>
<pre><code>import { useState, useEffect } from &quot;react&quot;;
import { getStarWars } from &quot;./base-fetch&quot;;
export function useTheFetch(path) {
  const [result, setResult] = useState({ loading: true, data: null });
  async function fetchData() {
    const data = await getStarWars(path); // being mocked
    setResult({ loading: false, data });
  }
  useEffect(() =&gt; {
    fetchData();
  }, []);

  return result;
}
</code></pre>
<p>base-fetch.js</p>
<pre><code>const BASE_URL = &quot;https://swapi.co/api/&quot;;

export async function baseFetch(url, options = {}) {
  const response = await fetch(url, options);
  return await response.json();
}

export const getStarWars = async (path) =&gt; baseFetch(BASE_URL + path);
</code></pre>
",https://stackoverflow.com/questions/71875761/custom-hook-testing-when-testing-code-that-causes-react-state-updates-should-b,"['javascript', 'reactjs', 'react-hooks', 'react-testing-library', 'react-test-renderer']",2117,False,1,0
TypeError: Invalid value used in weak set at WeakSet.add (&lt;anonymous&gt;),"<ul>
<li><p>I have been trying to write a test file for a vue component but i am not uderstanding where am
i going wrong.Im new to this unit testing but i have been searching the internet for a while
without result*</p>
<p><a href=""https://i.stack.imgur.com/DRK1O.png"" rel=""nofollow noreferrer"">vue component file</a>
<a href=""https://i.stack.imgur.com/rIL7p.png"" rel=""nofollow noreferrer"">test file</a>
<a href=""https://i.stack.imgur.com/vw1Vq.png"" rel=""nofollow noreferrer"">error</a></p>
</li>
</ul>
",https://stackoverflow.com/questions/72051022/typeerror-invalid-value-used-in-weak-set-at-weakset-add-anonymous,"['vue.js', 'unit-testing', 'jestjs', 'wrapper', 'mount']",755,False,1,0
Github add folder from repository to other repository,"<p>I have a python project I have split into 4 parts, each of these parts uses the same base module which I have also created as a separate repository.</p>
<p>As its a package module i had to create it in a src folder for unit testing.</p>
<p>However now my issue is i have a src folder rather than the folder name I need.</p>
<p>example:</p>
<pre><code>Part-main
    ~(submodule): module @ 6aef21 (random number)
        pyproject.toml
        ...etc
        src
            __init__.py
            code.py

</code></pre>
<p>I need that src folder to be as the main folder so it can be correctly imported</p>
<pre class=""lang-py prettyprint-override""><code>from module.code import classfunction
</code></pre>
<p>How can I achieve this so if I update the module each part will get these updates (I don't need unit test on each module when I make commits to the submodule either)</p>
<p>My project is for windows only so unit testing is created for windows only as well for now.</p>
",https://stackoverflow.com/questions/72983948/github-add-folder-from-repository-to-other-repository,"['python-3.x', 'github', 'github-actions']",16,False,0,0
Independence of Jest tests,"<p>I'm doing unit testing with React, and we use jest for unit testing. We have <code>&quot;jest-environment-jsdom-sixteen&quot;: &quot;^1.0.3&quot; in devDependencies and &quot;jest&quot;: {&quot;collectCoverageFrom&quot;: [(insert directories)]}</code> in our package.json file.</p>
<p>My question is: in the absence of any further configurations set, are the tests truly run independently of one another? I want to ensure that running one test.js file has NO effect on running another test.js file.</p>
<p>The reason I am asking this is because I have a <code>Component.test.js</code> that tests for a <code>Component.js</code> file, and within that file, I have the lines <code>delete window.location</code> and <code>window.location = {reload: jest.fn()};</code>, due to the fact that in the <code>Component.js</code> file I am actually doing window.location.reload, which does not exist in Jest's Node.js environment and therefore has to be mocked. I fear that setting <code>window.location = {reload: jest.fn()};</code> will also affect other files being tested.</p>
<p>Any help is appreciated. I find <code>&quot;clearMocks&quot;: true, &quot;resetMocks&quot;: true, &quot;resetModules&quot;: true</code> to be quite promising to set in package.json.</p>
",https://stackoverflow.com/questions/74851541/independence-of-jest-tests,"['javascript', 'reactjs', 'jestjs']",92,False,0,0
PHP unit testing without Composer,"<p>Does anyone know of a basic unit testing framework for PHP that does <em>not</em> require Composer in order to use it?  The project's testing requirements are simple, and I expect any framework would be fine. I'd be very happy with <a href=""https://phpunit.de/"" rel=""nofollow noreferrer"">PHPUnit</a> if there's a way of using that without Composer, though I don't think that's possible.  The alternative is to roll my own, but I'd rather not do that unless it's necessary.</p>
<p>I know Composer is a perfectly good system, and if the decision were mine, we'd be using it.  But it's not my decision, and it has been made clear that the project leader would rather not have any unit testing if the alternative is to use Composer.  That's wholly irrational, I know, but it's not a battle I have time to fight.</p>
",https://stackoverflow.com/questions/70897553/php-unit-testing-without-composer,"['php', 'unit-testing']",309,True,0,1
Cannot read properties of null (reading &#39;checked&#39;) Error in React testing,"<p>I wrote code for radio button unit testing. Getting Error &quot;Cannot read properties of null (reading 'checked')&quot;.</p>
<p><a href=""https://i.stack.imgur.com/znjtC.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/znjtC.png"" alt=""enter image description here"" /></a></p>
<p>Index.test.tsx</p>
<pre><code>describe(&quot;Radio group test cases&quot;, ()=&gt;{
    test(&quot;Radio group change value and new value updated and last value no more checked&quot;, () =&gt; {

        render(&lt;RadioGroupWrapper touched={true} /&gt;);
    
        // Before change selection
        const radionButtonMale = screen.queryByLabelText('Male') as HTMLInputElement;
        //expect(radionButtonMale).toHaveProperty(&quot;checked&quot;, true);
        expect(radionButtonMale.checked).toEqual(true); //Here it fails
    
        // Change selection
        const radionButtonFemale = screen.queryByLabelText('Female') as HTMLInputElement;
        fireEvent.click(radionButtonFemale, { target: { checked: true }});
        expect(radionButtonFemale.checked).toEqual(true);
    
        // Old value is no more checked
        expect(radionButtonMale.checked).toEqual(false);
    });
})
</code></pre>
<p>Index.tsx</p>
<pre><code>return (
    &lt;&gt;
      &lt;FormControl fullWidth&gt;
        &lt;FormLabel id=&quot;buttons-group-label&quot;&gt;{placeholder}&lt;/FormLabel&gt;
        &lt;RadioGroup
        aria-labelledby=&quot;buttons-group-label&quot;
          value={!value ? defaultValue : value}
         // onChange={onChange}
         
          // label={placeholder}
          name=&quot;radio-buttons-group&quot;
          {...otherprops}
        &gt;
          {fieldConfig?.options?.map((option) =&gt; (
            &lt;FormControlLabel key={option.displayValue} value={option.displayValue} control={&lt;Radio /&gt;} label={option.displayValue} /&gt;
                        ))}
          
        &lt;/RadioGroup&gt;
      &lt;/FormControl&gt;
      {!valid &amp;&amp; touched &amp;&amp; &lt;ErrorMessage&gt;{errorMessage}&lt;/ErrorMessage&gt;}
    &lt;/&gt;
  );
}
</code></pre>
<p>It looks like test is executed before radio buttons render that why It is giving &quot;property of null&quot; error. I applied set time out but test case failed.</p>
",https://stackoverflow.com/questions/74013115/cannot-read-properties-of-null-reading-checked-error-in-react-testing,"['javascript', 'reactjs', 'jestjs', 'react-testing-library']",738,False,0,0
How to add Header to Avro Kafka Message,"<p>We are using Avro Datum Reader and Datum Writer to build Kafka messages in Scala.</p>
<p>Code :</p>
<pre><code>def AvroKafkaMessage(schemaPath : String, dataPath: String): Array[Byte] = 
{
  val schema = Source.fromFile(schemaPath).mkString
  val schemaObj = new Schema.Parser().parse(schema)
  val reader= new GenericDatumReader[GenericRecord](schemaObj)
  val dataFile = new File(dataPath)
  val dataFileReader = new DataFileReader[GenericRecord](dataFile, reader)  
  val datum = dataFileReader.next()
  val writer = new SpecificDatumWriter[GenericRecord](schemaObj) 
  val out = new ByteArrayOutputStream()
  val encoder : BinaryEncoder= EncoderFactory.get().binaryEncoder(out, null)
  writer.write(datum,encoder) 
  encoder.flush()
  out.close()
  out.toByteArray()
}
</code></pre>
<p>Since there would we multiple events per kafka topic, we need to add header to avro messages for unit testing.</p>
<p>How to add headers in avro file and produce kakfa messages ?</p>
",https://stackoverflow.com/questions/74371290/how-to-add-header-to-avro-kafka-message,"['scala', 'apache-spark', 'apache-kafka', 'avro']",617,True,0,1
How do I create DTOs for nested entities referencing each other?,"<p>Lets say if I have two entities like this,</p>
<p>Users Entity:</p>
<pre><code>public class Users {
  @Basic
  @Column(name = &quot;USER_NAME&quot;)
  private String name;

  @Basic
  @Column(name = &quot;USER_ADDRESS&quot;)
  private String address;

  @ManyToOne
  @JsonBackReference
  @JoinColumn(name = &quot;PERSON_ID&quot;)
  private Person personData;
}
</code></pre>
<p>Person Entity:</p>
<pre><code>public class Person {
  @Id
  @Column(name = &quot;PERSON_ID&quot;)
  private Long personId

  @Basic
  @Column(name = &quot;USER_ADDRESS&quot;)
  private String address;

  @OneToMany(mappedBy=&quot;personData&quot;, cascase = CascadeType.ALL, orphanRemoval = true)
  @JsonManagedReference
  List&lt;Users&gt; users;
}
</code></pre>
<p>Now, how do I create DTOs for these two entities when I am doing unit testing? Also, when I try to access these entities in my service, it gives me StackOverflow Exception because of nested entities.</p>
",https://stackoverflow.com/questions/73124408/how-do-i-create-dtos-for-nested-entities-referencing-each-other,"['java', 'spring', 'spring-boot']",41,True,2,1
What is the proper way to Mock or MagicMock logging in Python unit tests?,"<p>When unit testing Python code with the unittest standard library, what is the proper way to Mock or MagicMock logging from the code that is being tested? Would the approach outlined in the stripped down, simplified example below be considered Pythonically correct?</p>
<p>Tested code:</p>
<pre class=""lang-py prettyprint-override""><code>
class FooOperator:
    def __init__(self, ..., logging=logging):
        self.logging = logging
        ...

    def __get_logging(self):
        return self.logging

    ...

    def some_function(self, arg1, arg2):
        self.logging.info(&quot;First info message&quot;)
        result = self.some_other_function(arg1=arg1, arg2=arg2)
        if result &gt; 0:
            # Processing records
            ...
        else:
            self.logging.warning(
                 f&quot;Warning message: No records found for {arg1}, {arg2}&quot;
                                )
        ...
        self.logging.info(&quot;Second logging message&quot;)
        return True

</code></pre>
<p>Unit test:</p>
<pre class=""lang-py prettyprint-override""><code>import unittest
from unittest.mock import MagicMock
import logging

from libraries.foo_operator import FooOperator

class Test_some_function(unittest.TestCase):
    def setUp(self):
        self.logging = logging
        self.dag_info = dict(
                             name=&quot;valid_dag_name&quot;,
                             run_id=&quot;valid_dag_run_id&quot;,
                             task=&quot;valid_dag_task&quot;,
                             description=&quot;valid_dag_description&quot;
                            )
        ...

    def test_success_logging_warning(self):
        sf_op = FooOperator(None, self.dag_info, logging)
        sf_op._FooOperator__set_logging(self.logging)
        ...
        expected_result = &quot;something&quot;
        self.logging.warning = MagicMock()
        ...
        result = some_function(arg1=&quot;valid_arg1&quot;, arg2=&quot;valid_arg2&quot;)
        self.assertEqual(result, expected_result)
        # Assert for logging WARNING
        self.logging.warning.assert_called_once_with(
             f&quot;Warning message: No records found for {arg1}, {arg2}&quot;
                                                    )

    def test_success_logging_info(self):
        sf_op = FooOperator(None, self.dag_info, logging)
        sf_op._FooOperator__set_logging(self.logging)
        ...
        expected_result = &quot;something&quot;
        self.logging.info = MagicMock()
        ...
        result = some_function(arg1=&quot;valid_arg1&quot;, arg2=&quot;valid_arg2&quot;)
        self.assertEqual(result, expected_result)
        # Assert for logging INFO
        self.logging.info.assert_has_calls([
                                            call(&quot;First info message&quot;),
                                            call(&quot;Second info message&quot;)
                                           ])
</code></pre>
",https://stackoverflow.com/questions/73579005/what-is-the-proper-way-to-mock-or-magicmock-logging-in-python-unit-tests,"['python', 'python-unittest', 'python-unittest.mock']",46,False,0,0
AttributeError: &#39;str&#39; object has no attribute &#39;as_plain_ordered_dict&#39;,"<p>I am trying to mock &quot;ConfigFactory.parse_file&quot; for unit testing purpose and getting the following error.</p>
<pre><code>AttributeError: 'str' object has no attribute 'as_plain_ordered_dict'
</code></pre>
<p>I tried mocking the attribute as_plain_ordered_dict to resolve the issue, but still getting the same error.</p>
<pre><code>class Testt2StatsExporter(unittest.TestCase):

    @patch('t2.client.OverlayClient')
    @patch('pyhocon.ConfigFactory.parse_file')
    @patch('oci.auth.signers.instance_principals_security_token_signer.InstancePrincipalsSecurityTokenSigner')
    def test_create_telemetry_client(self, mock_config_factory, mock_security_token_signer, mock_client):
        test_config = Mock()
        test_config.json.return_value = {'metricsConfig': 'test_config'}
        path_to_local_config = Mock()
        type(path_to_local_config).as_plain_ordered_dict = PropertyMock(return_value=test_config)
        mock_security_token_signer.return_value = &quot;test_token&quot;
        mock_config_factory.return_value = test_config
        mock_client.return_value = True
        self.assertEqual(True, _create_telemetry_client(path_to_local_config))

</code></pre>
<p>and here is the main code base that I am testing.</p>
<pre><code>path_to_local_config = '/etc/dlp/t2_config.conf'


def _create_telemetry_client(path_to_local_config: str):
    t2config = ConfigFactory.parse_file(path_to_local_config).as_plain_ordered_dict()
    common_config = t2config['metricsConfig']
    t2_client_config = {'metricsConfig': common_config}
    auth_provider = InstancePrincipalsSecurityTokenSigner()
    return client.OverlayClient(t2_client_config, authentication_provider=auth_provider)

</code></pre>
<p>What can I try next?</p>
",https://stackoverflow.com/questions/73433286/attributeerror-str-object-has-no-attribute-as-plain-ordered-dict,"['python', 'python-unittest', 'python-unittest.mock']",197,False,0,0
Angular + jasmine test nested ViewChild components,"<p>I have some problem with unit testing of <code>ionViewDidLeave</code> function on DashboardPage:</p>
<pre class=""lang-js prettyprint-override""><code>@Component({
  template: '&lt;app-dashboard-slider #dashboardSlider&gt;&lt;/app-dashboard-slider&gt;',
  selector: 'app-dashboard',
})
export class DashboardPage {
  @ViewChild('dashboardSlider', { static: false }) dashboardSlider?: DashboardSliderComponent;

  ionViewDidLeave(): void {
    this.dashboardSlider?.swiper?.swiperRef.disable();
  }
}
</code></pre>
<p>The <code>DashboardSliderComponent</code> contain <code>SwiperComponent</code></p>
<pre class=""lang-js prettyprint-override""><code>@Component({
  template: '&lt;swiper #swiper&gt;&lt;/swiper&gt;',
  selector: 'app-dashboard-slider',
})
export class DashboardSliderComponent {
  @ViewChild('swiper', { static: false }) swiper?: SwiperComponent;
}
</code></pre>
<p>and I have no idea, how I can reach the <code>disable()</code> function with mocking</p>
<pre class=""lang-js prettyprint-override""><code>// stub component
  @Component({
    selector: 'app-dashboard-slider',
    template: '',
  })
  class DashboardSliderStubComponent {
    swiper: SwiperComponent = {} as SwiperComponent;
  }


beforeEach(waitForAsync(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [DashboardPage, DashboardSliderStubComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      providers: [
        // {
        //   provide: DashboardSliderComponent,
        //   useClass: DashboardSliderStubComponent,
        // },
      ],
    }).compileComponents();

    fixture = TestBed.createComponent(DashboardPage);
    component = fixture.componentInstance;

    // populate childComponent with an instance of the stub
    component.dashboardSlider = TestBed.createComponent(DashboardSliderStubComponent).componentInstance as DashboardSliderComponent;

    fixture.detectChanges();
  }));


  fdescribe('Test ionViewDidLeave', () =&gt; {
    it('t1', () =&gt; {
      const swiperRefSpy = jasmine.createSpyObj('swiperRef', ['disable'], ['autoplay']);

      spyOn&lt;any&gt;(component.dashboardSlider, 'swiper').and.returnValue({ swiperRef: swiperRefSpy });

      component.ionViewDidLeave();
      fixture.detectChanges();

      expect(swiperRefSpy.disable).toHaveBeenCalled();
    });
  });
</code></pre>
<p>currently, I have an error:</p>
<blockquote>
<p>TypeError: Cannot read properties of undefined (reading 'disable')</p>
</blockquote>
<p>Can you please help me to understand?</p>
",https://stackoverflow.com/questions/72830233/angular-jasmine-test-nested-viewchild-components,"['angular', 'unit-testing', 'jasmine', 'karma-runner', 'viewchild']",665,False,0,1
React-testing-library show error because of axios,"<p>Learning unit-testing on the react with typescript, encountered an error when tests fall when importing axios.
<a href=""https://i.stack.imgur.com/dFxJU.png"" rel=""nofollow noreferrer"">screenshot error in the terminal</a>](<a href=""https://i.stack.imgur.com/dFxJU.png"" rel=""nofollow noreferrer"">https://i.stack.imgur.com/dFxJU.png</a>)</p>
<p>Code component</p>
<pre><code>import axios from &quot;axios&quot;;
import React, { FC, useEffect, useState } from &quot;react&quot;;
import { IUser } from &quot;../../types/IUsers&quot;;

const Users: FC = () =&gt; {
  const [users, setUsers] = useState&lt;IUser[]&gt;([]);
  useEffect(() =&gt; {
    getUsers();
  }, [users]);

  const getUsers = async () =&gt; {
    try {
      const response = await axios.get(
        &quot;https://jsonplaceholder.typicode.com/users/&quot;
      );
      const res = response.data;
      setUsers(res);
    } catch (error) {
      console.log(error);
    }
  };
  return (
    &lt;div data-testid=&quot;users-wrapper&quot;&gt;
      {users.map((user) =&gt; (
        &lt;div&gt;{user.name}&lt;/div&gt;
      ))}
    &lt;/div&gt;
  );
};

export default Users;
</code></pre>
<p>Code test</p>
<pre><code>import React from &quot;react&quot;;
import { render, screen } from &quot;@testing-library/react&quot;;
import userEvent from &quot;@testing-library/user-event&quot;;
import Users from &quot;./Users&quot;;
import axios from &quot;axios&quot;;

jest.mock(&quot;axios&quot;);
describe(&quot;Testing user component&quot;, () =&gt; {
  test(&quot;Show title&quot;, () =&gt; {
    render(&lt;Users /&gt;);
    const usersWrapper = screen.getByTestId(&quot;users-wrapper&quot;);
    expect(usersWrapper).toBeInTheDocument();
  });
});
</code></pre>
<p>Tried install types for axios, create babel-config, create .babelrc, add `</p>
<pre><code>--transformIgnorePatterns \&quot;node_modules/(?!axios)/\&quot;&quot;
</code></pre>
<p>` on the package-json. Help me please.</p>
",https://stackoverflow.com/questions/74317260/react-testing-library-show-error-because-of-axios,"['reactjs', 'typescript', 'axios', 'jestjs', 'react-testing-library']",1020,False,0,2
Mockito and PanacheMockito Missing method invocation exception,"<p>Hello all I'm trying to learn java unit-testing with Mockito and PanacheMock.</p>
<p>I'm getting the following error</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);
</code></pre>
<p>From the following test</p>
<pre><code>    @Test
public void testGetAllFruits() {
    PanacheMock.mock(Fruit.class);
    PanacheMock.mock(FruitResource.class);
    FruitResource fruitResource = new FruitResource();

    List&lt;Fruit&gt; fruitList = new ArrayList&lt;&gt;();
    fruitList.add(new Fruit());

    Mockito.when(fruitResource.getAllFruits())
            .thenReturn(fruitList);

    Assertions.assertSame(fruitList, fruitResource.getAllFruits());


}
</code></pre>
<p>The method this test is testing is the following:</p>
<pre class=""lang-java prettyprint-override""><code>    @Path(&quot;/fruits&quot;)
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public class FruitResource {
        @GET
        public List&lt;Fruit&gt; getAllFruits() {
            List&lt;Fruit&gt; fruitList = new ArrayList&lt;&gt;();
            if (0 == 0) { // terrible bugg
                return fruitList;
            }
            return Fruit.listAll();
        }
    }
</code></pre>
<p>How can I fix this test so it detected the bugg in FruitResources getAllFruits method?</p>
",https://stackoverflow.com/questions/70592496/mockito-and-panachemockito-missing-method-invocation-exception,"['java', 'unit-testing', 'testing', 'mockito']",204,False,0,0
Laravel: Feature test json validations unique rule issue,"<p>I recently started implementing the unit testing in <code>Laravel 9.x</code> framework. So far, I was able to write some basic rules without any complications. However, in my application I am validating the forms using <code>ajax</code> and <code>From Request</code> for validation rules.</p>
<h3><code>CategoryRequest.php</code></h3>
<pre class=""lang-php prettyprint-override""><code>class CategoryRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            // ...

            'title' =&gt; [
                'required',
                'max:255',
                function($attributes, $value, $fails) {
                    $Category = Category::where([
                        'user_id' =&gt; request()-&gt;user_id,
                        'title'   =&gt; request()-&gt;title,
                    ])-&gt;first();

                    if($Category) {
                        $fails('`Category` is already taken');
                    }
                }
            ],

        // ...
        ];
    }
}
</code></pre>
<h3><code>CategoryTest.php</code></h3>
<pre class=""lang-php prettyprint-override""><code>class CategoryTest extends TestCase
{
    use RefreshDatabase;

    // ...

    public function test_new_category_with_unique_validation()
    {
        $user = $this-&gt;__user();
        $arrayPost = [
            'user_id' =&gt; $user-&gt;id,
            'uuid'    =&gt; Str::uuid(),
            'title'   =&gt; 'title',
            'status'  =&gt; STATUS['active'],
        ];

        Category::factory()-&gt;create($arrayPost);

        $response = $this
            -&gt;actingAs($user)
            -&gt;post('/console/categories', $arrayPost);

        $response-&gt;assertJsonValidationErrorFor('title');
        $response-&gt;assertJsonValidationErrorFor('status');
        $response-&gt;assertJsonValidationErrorFor('uuid');
        $response-&gt;assertJsonValidationErrorFor('user_id');
    }

    private function __user(): object
    {
        return User::factory()-&gt;create();
    }
}
</code></pre>
<p>I am getting the following error...</p>
<p><a href=""https://i.stack.imgur.com/jolz9.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/jolz9.png"" alt=""error"" /></a></p>
<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/72145967/laravel-feature-test-json-validations-unique-rule-issue,"['laravel', 'testing', 'phpunit', 'unique', 'rules']",517,False,0,1
Using mock.patch + parametrize in a Pytest Class Function,"<p>I have been working on fastAPI and have some async methods to generate an auth token</p>
<p>Writting the unit testing I'm getting the following error:</p>
<pre><code>TypeError: test_get_auth_token() missing 2 required positional arguments: 'test_input' and 'expected_result'
</code></pre>
<p>my unit test looks like:</p>
<pre><code>class TestGenerateAuthToken(IsolatedAsyncioTestCase):
    &quot;&quot;&quot;
    &quot;&quot;&quot;
    
    @pytest.mark.parametrize(
        &quot;test_input,expected_result&quot;,
        [(&quot;user&quot;, &quot;user_token&quot;), (&quot;admin&quot;, &quot;admin_token&quot;)],
    )
    @mock.patch(&quot;myaauth.get_token&quot;, new_callable=AsyncMock)
    async def test_get_auth_token(self, get_token_mock, test_input, expected_result):
        &quot;&quot;&quot;
        Test get_auth_header
        &quot;&quot;&quot;
        def mock_generate_user_token(_type):
            return f&quot;{_type}_token&quot;

        get_token_mock.side_effect = mock_generate_user_token
        assert await myaauth.get_token(test_input) == expected_result
</code></pre>
<p>I know is as simple as to just remove the parametrize, but I wanna know if is possible to do so</p>
",https://stackoverflow.com/questions/73954438/using-mock-patch-parametrize-in-a-pytest-class-function,"['python', 'python-3.x', 'unit-testing', 'pytest']",317,False,3,1
Destructure using useContext breaks Jest,"<p>I am using Jest for unit testing and finding that functions I imported using <code>useContext</code> appear to break my Jest.</p>
<p>I am getting this error for example:</p>
<pre><code>TypeError: Cannot destructure property 'loginUser' of '(0 , _react.useContext)(...)' as it is undefined.
</code></pre>
<p>This is the test I am running:</p>
<pre><code>test('Login page renders with no errors', () =&gt; {
    render(&lt;Router&gt;&lt;Login/&gt;&lt;/Router&gt;)
});
</code></pre>
<p>and my jest.config:</p>
<pre><code>module.exports = {
    preset: &quot;ts-jest/presets/js-with-ts&quot;,
    transform: {
        '^.+\\.(js|jsx|ts|tsx)$': '&lt;rootDir&gt;/node_modules/react-scripts/config/jest/babelTransform.js',
        '^.+\\.css$': '&lt;rootDir&gt;/node_modules/react-scripts/config/jest/cssTransform.js',
        '^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': '&lt;rootDir&gt;/node_modules/react-scripts/config/jest/fileTransform.js',
        &quot;^.+\\.(js|jsx)$&quot;: &quot;&lt;rootDir&gt;/node_modules/babel-jest-amcharts&quot;,
        &quot;\\.[jt]sx?$&quot;: &quot;babel-jest&quot;,
        &quot;^.+\\.css$&quot;: &quot;jest-transform-css&quot;,
        &quot;node_modules/variables/.+\\.(j|t)sx?$&quot;: &quot;ts-jest&quot;,
    },
    transformIgnorePatterns: [
//      '[/\\\\]node_modules[/\\\\].+\\.(js|jsx|ts|tsx)$',
        '^.+\\.module\\.(css|sass|scss)$',
        &quot;[/\\\\]node_modules[/\\\\](?!(@amcharts)\\/).+\\.(js|jsx|ts|tsx)$&quot;,
        &quot;/node_modules/(?!react-file-drop)&quot;,
        &quot;node_modules/(?!variables/.*)&quot;
    ],
    moduleNameMapper: {
        '^react-native$': 'react-native-web',
        '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
        &quot;\\.(jpg|ico|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$&quot;: &quot;&lt;rootDir&gt;/mocks/fileMock.js&quot;,
        &quot;\\.(css|less)$&quot;: &quot;&lt;rootDir&gt;/mocks/fileMock.js&quot;,
        &quot;^.+\\.(css|less|scss)$&quot;: &quot;babel-jest&quot;,
    },
    moduleDirectories: [&quot;node_modules&quot;, &quot;src&quot;],
}
</code></pre>
<p>This is my implementation of loginUser:</p>
<pre><code>const loginUser = async (tokens) =&gt; {
    let response = await axios.post('http://127.0.0.1:8000/api/token/',tokens)
    try {
        setAuthTokens(authTokens =&gt; ({
            ...response.data
        }))
        const decoded = jwt_decode(response.data.access)
        setUser(user =&gt; ({
            ...decoded
        }))            localStorage.setItem('authTokens',JSON.stringify(response.data))
        history.push('/')
    }
    catch(err) {
        alert(response.data.user);
    }
}
</code></pre>
<p>Any help would be greatly appreciated</p>
",https://stackoverflow.com/questions/73571362/destructure-using-usecontext-breaks-jest,"['javascript', 'reactjs', 'jestjs']",46,False,1,0
In Sveltekit we can access FormData on they body. But how to create FormData in unit-test?,"<p>I'm trying to unit test a function that expect's a <code>FormData</code> type as described in <code>'@sveltejs/kit/types/helper'</code>.</p>
<p>My question is, how can I create such a <code>FormData</code> type when unit-testing the function?</p>
<p>I tried using the npm <code>form-data</code> package, but did not work as <code>.entries()</code> was missing (and the interface was also completely different).</p>
",https://stackoverflow.com/questions/70891302/in-sveltekit-we-can-access-formdata-on-they-body-but-how-to-create-formdata-in,['sveltekit'],379,False,1,0
NOT ABLE TO PASS jwt token from header using golang fiber app.test,"<p>can anyone help me im trying to create function unit testing but i cant get pass jwt auhtentication because fiber app.test didnt pass any jwt value from authorization header
i can get data if im using param but i cant use bearer if i use that</p>
<p>my code :</p>
<pre><code>app := fiber.New()
urlvalue, _ := url.Parse(&quot;/test&quot;)
values := urlvalue.Query()
//values.Add(&quot;id&quot;, strconv.Itoa(2))
urlvalue.RawQuery = values.Encode()

log.Println(urlvalue.String())

app.Get(&quot;/test&quot;, func(c *fiber.Ctx) error {
    return GetProject(c)
})
req := httptest.NewRequest(&quot;GET&quot;, urlvalue.String(), nil)
req.Header.Set(&quot;Authorization&quot;, fmt.Sprintf(&quot;Bearer %v&quot;, jwt))

r, err := app.Test(req)

log.Println(&quot;Request : &quot;, req)

log.Println(r)

assert.Nil(t, err, &quot;There is error&quot;)

body, _ := ioutil.ReadAll(r.Body)

log.Println(string(body))

//err := json.NewDecoder(r.Body).Decode(&amp;data)
assert.NotNil(t, req, &quot;No value passed &quot;) 
</code></pre>
",https://stackoverflow.com/questions/74012380/not-able-to-pass-jwt-token-from-header-using-golang-fiber-app-test,"['unit-testing', 'go', 'httprequest', 'fibers']",393,False,1,0
How to Write UnitTest on TypeOrm DataSource,"<p>I want to write a unit test on <code>typeorm Datasource</code> but couldn't figure out a way to do it because I'm a newbie to unit testing. I already have spy on the entity. but I had to use the data for some custom queries, here is my code.</p>
<p><strong>company.entity.ts</strong></p>
<pre><code>export class CompanyEntity {
  @PrimaryGeneratedColumn('uuid', {
    name: 'company_id',
  })
  id: string;

  @ManyToOne(() =&gt; StoreEntity, (store) =&gt; store.storeId, {
    onDelete: 'SET NULL',
  })
  @JoinColumn({ name: 'store_id', referencedColumnName: 'storeId' })
  store: StoreEntity;

  @Column({
    name: 'owner_name',
    type: 'varchar',
  })
  ownername: string;
}
</code></pre>
<p><strong>comapany.service.ts</strong></p>
<pre><code>@Injectable()
export class CompanyService {
  constructor(
    @InjectRepository(CompanyEntity)
    private _companyRepository: Repository&lt;CompanyEntity&gt;,
    @InjectRepository(StoreEntity)
    private _storeEntityRepository: Repository&lt;StoreEntity&gt;,
    private readonly dataSource: DataSource,
  ) {}

  async findAll(offset = 0, size = 50) {
    try {
      return await this.dataSource
        .getRepository('company')
        .createQueryBuilder('company')
        .leftJoinAndSelect('company.store', 'store')
        .select([
          'company.company_id AS id',
          'company.owner_name AS ownername',
          'store.name AS store',
        ])
        .skip(offset)
        .take(size)
        .execute();
    } catch (error) {
      throw new Error(error);
    }
  }
}
</code></pre>
<p><strong>service.spec.ts</strong></p>
<pre><code>describe('UsersService', () =&gt; {
  let service: CompanyService;
  let repository: Repository&lt;CompanyEntity | CompanyEntity[]&gt;;

  beforeEach(async () =&gt; {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        CompanyService,
        {
          provide: getRepositoryToken(CompanyEntity),
          useClass: Repository,
        },
      ],
    }).compile();

    service = module.get&lt;CompanyService&gt;(CompanyService);
    repository = module.get&lt;Repository&lt;CompanyEntity | CompanyEntity[]&gt;&gt;(
      getRepositoryToken(CompanyEntity),
    );
  });

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

  it('find all should return array company objects', async () =&gt; {
    ---------- wants to write the data source test here ----------
  });
});
</code></pre>
",https://stackoverflow.com/questions/73625892/how-to-write-unittest-on-typeorm-datasource,"['unit-testing', 'jestjs', 'nestjs', 'typeorm']",33,False,0,0
Angular unit testing Error: Expected spy getDateFormat to have been called,"<p>I'm new to unit testing and hope someone help me.
I have a angular component called StudentComponent and it has following.</p>
<pre><code>    public getAllStudents(){    
        this.apollo.query({
            query: GETALL_STUDENTS,
        }).subscribe((result: any) =&gt; {
            this.students = result?.data?.getAllStudents;
            this.students.forEach(element =&gt; {
            element.Age = this.CalculateAge(element.DateOfBirth);
            element.DateOfBirthString = this.getDateFormat(element.DateOfBirth);
            });
        });
    }

    public CalculateAge(dateOfBirth: any): number {
        let age = 0;
        if (dateOfBirth) {
            var timeDiff = Math.abs(Date.now() - new Date(dateOfBirth).getTime());
            age = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
        }
        return age;
    }

    getDateFormat(date: Date): string{
        let dateString = &quot;&quot;
        if(date){
            dateString = formatDate(date, 'yyyy/MM/dd','en_US').toString();
        }
        return dateString;
    }
</code></pre>
<p>I wrote the test case like following</p>
<pre><code>    describe('getAllStudents', () =&gt; {
        it('makes expected calls', () =&gt; {
          spyOn(component, 'getDateFormat').and.callThrough();
          spyOn(component, 'CalculateAge').and.callThrough();
          spyOn(apollo, 'query').and.callThrough();
          component.getAllStudents();
          expect(apollo.query).toHaveBeenCalled();
          expect(component.getDateFormat).toHaveBeenCalled();
          expect(component.CalculateAge).toHaveBeenCalled();
  
        });
      });
</code></pre>
<p>this gave me an error. 'Expected spy getDateFormat to have been called.' Could anyone please guide me to resolve this?</p>
",https://stackoverflow.com/questions/72768656/angular-unit-testing-error-expected-spy-getdateformat-to-have-been-called,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",529,False,-1,1
Sonar coverage is showing zero percentage even though jest coverage is showing correctly,"<p>I am using jest for unit testing, jest is showing code coverage as expected but while I run the sonar the coverage is showing zero only.
package.json is like this below.</p>
<pre><code>&quot;devDependencies&quot;: {
    &quot;jest-sonar-reporter&quot;: &quot;^2.0.0&quot;
  },
  &quot;jestSonar&quot;: {
    &quot;sonar56x&quot;: true,
    &quot;reportPath&quot;: &quot;coverage&quot;,
    &quot;reportFile&quot;: &quot;test-report.xml&quot;,
    &quot;indent&quot;: 4
  }
</code></pre>
<p>sonar-project.properties is like below.</p>
<pre><code>sonar.javascript.lcov.reportPaths=coverage/lcov.info
sonar.testExecutionReportPaths=coverage/test-report.xml
sonar.genericcoverage.unitTestReportPaths=coverage/test-report.xml
</code></pre>
<p>remaining config is available jest.config.js.</p>
<p>why the coverage is not exposing to sonar?</p>
",https://stackoverflow.com/questions/72527200/sonar-coverage-is-showing-zero-percentage-even-though-jest-coverage-is-showing-c,"['angular', 'jestjs', 'sonarqube']",508,True,0,1
React unit test getting TypeError: Cannot read properties of undefined (reading &#39;Component&#39;),"<p>I'm new to React and React unit testing. I'm trying to create a simple test and am getting the following error: &quot;TypeError: Cannot read properties of undefined (reading 'Component')&quot; Here's my code.</p>
<p><strong>HelloWorld.js</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import React from ""react"";

class HelloWorld extends Component {
  render() {
    return ( &lt; h1 &gt; My First ReactJS Core App! &lt; /h1&gt;);
    }
  }
  export default HelloWorld</code></pre>
</div>
</div>
</p>
<p><strong>test.js</strong></p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>import React from ""react"";
import {
  HelloWorld
} from ""../wwwroot/src/react/HelloWorld""
import {
  render,
  screen
} from ""@testing-library/react"";

describe(""apptest"", () =&gt; {
  it(""works"", () =&gt; {
    render( &lt; HelloWorld / &gt; );
    screen.getByText(""My First ReactJS Core App!"");
  });
});</code></pre>
</div>
</div>
</p>
<p>When I run &quot;npm test&quot;, I get the following:</p>
<p><a href=""https://i.stack.imgur.com/s0SGj.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/s0SGj.png"" alt=""enter image description here"" /></a></p>
<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/72710119/react-unit-test-getting-typeerror-cannot-read-properties-of-undefined-reading,"['reactjs', 'unit-testing']",1406,True,0,3
Error: VM Exception while processing transaction: reverted with reason string &#39;You need to spend more ETH!&#39;,"<p>At the unit testing section on solidity course Lesson7 around 11：23</p>
<p><a href=""https://youtu.be/gyMwXuJrbJQ?t=41004%E3%80%82"" rel=""nofollow noreferrer"">https://youtu.be/gyMwXuJrbJQ?t=41004。</a>
Failed the test &quot;updated the amount funded data structure&quot;.
Seems like sendValue failed
but I declared the sendValue for 1 Ether and pass the args of sendvalue.</p>
<p>Error Information</p>
<pre><code>FundMe
fund
updated the amount funded data structure:
Error: VM Exception while processing transaction: reverted with reason string 'You need to spend more ETH!'
at FundMe.fund (contracts/FundMe.sol:40)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at runNextTicks (node:internal/process/task_queues:65:3)
</code></pre>
<p>test script - fundme.test.js</p>
<pre><code>const sendValue = ethers.utils.parseEther(&quot;1&quot;)

describe(&quot;fund&quot;, async function () {
    it(&quot;Fails if you don't send enough ETH&quot;, async function () {
        await expect(fundMe.fund()).to.be.revertedWith(
            &quot;You need to spend more ETH!&quot;
        )
    })

    it(&quot;updated the amount funded data structure&quot;, async function () {
        // 执行fund，获取funder的地址=&gt;金额映射，和fund的金额做对比
        await fundMe.fund({ value: sendValue })
        const response = await fundMe.addressToAmountFunded(deployer)
        assert.equal(response.toString(), sendValue.toString())
    })
</code></pre>
",https://stackoverflow.com/questions/74303484/error-vm-exception-while-processing-transaction-reverted-with-reason-string-y,"['javascript', 'deployment', 'ethereum', 'solidity', 'hardhat']",124,False,0,1
Python unit testing with VSCode behaves weird,"<p>I am using VSCode for my Python project. Unit testing (<a href=""https://code.visualstudio.com/docs/python/testing"" rel=""nofollow noreferrer"">https://code.visualstudio.com/docs/python/testing</a>) works fine, but every time I execute a test (via panel or in code editor), the panel jumps from <code>Test Explorer</code> to <code>Explorer</code>.</p>
<p><a href=""https://i.stack.imgur.com/Cbfh2.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Cbfh2.png"" alt=""enter image description here"" /></a></p>
<p>This started a couple of days ago out of the blue. Any idea?</p>
",https://stackoverflow.com/questions/73171301/python-unit-testing-with-vscode-behaves-weird,"['python', 'visual-studio-code', 'python-unittest']",68,False,0,0
Assert.Equal() Failure,"<p>during unit testing have some problem using Assert.Equels(expected, actual).
I have the next message</p>
<p>Expected: MyClass { Id = 1, Name = &quot;Vasia Vasiliew&quot;, Value = 10 }</p>
<p>Actual:   MyClass { Id = 1, Name = &quot;Vasia Vasiliew&quot;, Value = 10 }</p>
<p>but the Assert.Equal() Failure</p>
<p>Assert.True(actual.equels(expected)) is failure too</p>
<p>How can I fix it?</p>
",https://stackoverflow.com/questions/72747038/assert-equal-failure,"['c#', 'xunit']",25,False,0,0
How do I dynamically create a callable method generated at runtime?,"<p>Here is a simplified example that I am using to practice:</p>
<pre><code>import sys

def generate_subprocess_runner(funcname: str=None, cred_path: str=None):
    if funcname is None:
        raise ValueError(&quot;\&quot;funcname\&quot; cannot be None.&quot;)

    if cred_path is None:
        raise ValueError(&quot;\&quot;cred_path\&quot; cannot be None.&quot;)

    #This function is simple.
    str_buff = []
    str_buff.append(&quot;def {:s}():\n&quot;.format(funcname))
    str_buff.append(&quot;\ttry:\n&quot;)
    str_buff.append(&quot;\t\tprint(\&quot;{:s}\&quot;)\n&quot;.format(
            cred_path
        ))
    str_buff.append(&quot;\t\texit(0)\n&quot;)
    str_buff.append(&quot;\texcept BaseException as exception:\n&quot;)
    str_buff.append(&quot;\t\texit(1)\n&quot;)

    str_func = ''.join(str_buff)
    exec(str_func)
</code></pre>
<p>What I hope to achieve is to pass the generated Callable to multiprocessing.Process().
The real code will be for unit testing, wherein we set an environment variable and evaluate code that should be checking that variable for anomalies.</p>
",https://stackoverflow.com/questions/71129485/how-do-i-dynamically-create-a-callable-method-generated-at-runtime,"['python-3.x', 'dynamically-generated']",55,False,0,1
How to write test for react-splide in react with jest correctly?,"<p><strong>Problem:</strong></p>
<p>I am new to react unit testing world. I have a component like this that is showing a report component that is using <code>@splidejs/react-splide</code>.</p>
<pre><code>const Incident = () =&gt; {
    const { t } = useTranslation()
    const navigate = useNavigate()
    const { Id } = useParams()
    const theme = useTheme()
    const { fetch, ...dataFetchResult } =
        useReportDataFetch(&quot;incidents/GetById&quot;)

    useEffect(() =&gt; {
        fetch({ id: Id })

        return ()=&gt;{
            localStorage.removeItem(&quot;vehicle&quot;)
        }
    }, [Id, fetch])

    const data = dataFetchResult.data
    const photos = useMemo(
        () =&gt;
            data?.photos
                ? data.photos.map(photo =&gt; ({
                        ...photo,
                        original: `${process.env.REACT_APP_PHOTO_SOURCE}${photo.fileName}.jpg`,
                        thumbnail: `${process.env.REACT_APP_PHOTO_SOURCE}${photo.thumbnail}.jpg`,
                  }))
                : [],
        [data.photos]
    )
    const location = useLocation()
    const from = location.state?.from?.pathname || &quot;/&quot;

    const renderLink = () =&gt; {
        if (from === &quot;/Incidents&quot;) {
            return (
                &lt;Grid
                    container
                    justifyContent=&quot;space-between&quot;
                    alignContent=&quot;center&quot;
                    alignItems=&quot;center&quot;
                    sx={{ paddingRight: theme.spacing(3) }}
                &gt;
                    &lt;Grid item lg=&quot;auto&quot;&gt;
                        &lt;Link
                            style={{ fontWeight: &quot;bold&quot; }}
                            href=&quot;#&quot;
                            onClick={() =&gt; navigate(-1)}
                            underline=&quot;none&quot;
                        &gt;
                            {t(&quot;incident.all_incidents&quot;)}
                        &lt;/Link&gt;
                    &lt;/Grid&gt;
                    &lt;Grid item&gt;
                        &lt;TopIconButtonContainer&gt;
                            &lt;TopIconLabelContainer&gt;
                                &lt;TopIconContainer&gt;
                                    &lt;TopIcon icon={faShareFromSquare} /&gt;
                                &lt;/TopIconContainer&gt;
                                &lt;Box sx={{ fontWeight: &quot;500&quot; }}&gt;
                                    {t(&quot;incident.share&quot;)}
                                &lt;/Box&gt;
                            &lt;/TopIconLabelContainer&gt;
                            &lt;TopIconLabelContainer&gt;
                                &lt;TopIconContainer&gt;
                                    &lt;TopIcon icon={faClock} /&gt;
                                &lt;/TopIconContainer&gt;
                                &lt;Box sx={{ fontWeight: &quot;500&quot; }}&gt;
                                    {t(&quot;incident.schedule&quot;)}
                                &lt;/Box&gt;
                            &lt;/TopIconLabelContainer&gt;
                            &lt;TopIconLabelContainer&gt;
                                &lt;TopIconContainer&gt;
                                    &lt;TopIcon icon={faPrint} /&gt;
                                &lt;/TopIconContainer&gt;
                                &lt;Box sx={{ fontWeight: &quot;500&quot; }}&gt;
                                    {t(&quot;incident.print&quot;)}
                                &lt;/Box&gt;
                            &lt;/TopIconLabelContainer&gt;
                            &lt;TopIconLabelContainer&gt;
                                &lt;TopIconContainer&gt;
                                    &lt;TopIcon icon={faDownToLine} /&gt;
                                &lt;/TopIconContainer&gt;
                                &lt;Box sx={{ fontWeight: &quot;500&quot; }}&gt;
                                    {t(&quot;incident.export&quot;)}
                                &lt;/Box&gt;
                            &lt;/TopIconLabelContainer&gt;
                            &lt;TopIconLabelContainer&gt;
                                &lt;TopIconContainer&gt;
                                    &lt;TopIcon icon={faQuestion} /&gt;
                                &lt;/TopIconContainer&gt;
                                &lt;Box sx={{ fontWeight: &quot;500&quot; }}&gt;
                                    {t(&quot;incident.help&quot;)}
                                &lt;/Box&gt;
                            &lt;/TopIconLabelContainer&gt;
                        &lt;/TopIconButtonContainer&gt;
                    &lt;/Grid&gt;
                &lt;/Grid&gt;
            )
        }
    }

    return (
        &lt;&gt;
            &lt;ErrorBoundary&gt;
                &lt;ReportDataLayout dataFetchResult={dataFetchResult} noCancel&gt;
                    &lt;Container&gt;{renderLink()}&lt;/Container&gt;
                    &lt;Grid container sx={{ paddingRight: theme.spacing(3) }}&gt;
                        &lt;Grid item xs={12} lg={6} md={6} xl={6} sm={12}&gt;
                            &lt;BoxContainer&gt;
                                &lt;Box&gt;
                                    &lt;h4&gt;{t(&quot;incident.incident_details&quot;)}&lt;/h4&gt;
                                    &lt;DataContainer&gt;
                                        {dataFetchResult.hasData &amp;&amp; (
                                            &lt;AssetLabel asset={data.asset} /&gt;
                                        )}
                                    &lt;/DataContainer&gt;
                                    &lt;DataContainer&gt;
                                        {dataFetchResult.hasData &amp;&amp; (
                                            &lt;span&gt;
                                                {shortDateTime(
                                                    data.dateAndTime
                                                )}
                                            &lt;/span&gt;
                                        )}
                                    &lt;/DataContainer&gt;
                                    &lt;DataContainer&gt;
                                        &lt;span&gt;Driver {data.driver}&lt;/span&gt;
                                    &lt;/DataContainer&gt;
                                    &lt;DataContainer&gt;
                                        &lt;div&gt;{data.details}&lt;/div&gt;
                                    &lt;/DataContainer&gt;
                                &lt;/Box&gt;
                                &lt;Box&gt;
                                    &lt;h4&gt;
                                        {t(&quot;incident.other_driver_details&quot;)}
                                    &lt;/h4&gt;
                                    &lt;DataContainer&gt;
                                        &lt;span&gt;{data?.otherDriver?.driver}&lt;/span&gt;
                                    &lt;/DataContainer&gt;
                                    &lt;DataContainer&gt;
                                        {data?.otherDriver?.registration}
                                    &lt;/DataContainer&gt;
                                    &lt;DataContainer&gt;
                                        {data?.otherDriver?.insurance}
                                    &lt;/DataContainer&gt;
                                &lt;/Box&gt;
                            &lt;/BoxContainer&gt;
                        &lt;/Grid&gt;
                        &lt;Grid item xs={12} lg={6} md={6} xl={6} sm={12}&gt;
                            &lt;MapContainer&gt;
                                &lt;h4&gt;{t(&quot;incident.incident_location&quot;)}&lt;/h4&gt;
                                {dataFetchResult.hasData &amp;&amp; (
                                    &lt;Map
                                        center={{
                                            lat: data.locationLat,
                                            lng: data.locationLong,
                                        }}
                                        zoom={8}
                                        defaultZoom={8}
                                        onZoomChange={(lat, lng, scale) =&gt; {}}
                                    &gt;
                                        &lt;IncidentMapMarker
                                            data={data}
                                        &gt;&lt;/IncidentMapMarker&gt;
                                    &lt;/Map&gt;
                                )}
                                &lt;LocationContainer sx={{ display: &quot;flex&quot; }}&gt;
                                    &lt;LocationIconContainer
                                        color={theme.palette.primary.main}
                                        icon={faLocationDot}
                                    /&gt;
                                    &lt;div&gt;{data?.location}&lt;/div&gt;
                                &lt;/LocationContainer&gt;
                            &lt;/MapContainer&gt;
                        &lt;/Grid&gt;
                    &lt;/Grid&gt;
                    &lt;PhotoTitleContainer&gt;
                        &lt;h4 style={{ marginTop: 70 }}&gt;
                            {t(&quot;incident.photos&quot;)}
                        &lt;/h4&gt;
                        &lt;div
                            style={{
                                flexDirection: &quot;row&quot;,
                                display: &quot;flex&quot;,
                                flexWrap: &quot;wrap&quot;,
                            }}
                        &gt;
                            {photos.length &gt;= 1 &amp;&amp;
                                photos?.map((item, index) =&gt; (
                                    &lt;img
                                        style={{
                                            width: 100,
                                            margin: 10,
                                            height: 75,
                                        }}
                                        key={index}
                                        src={item?.thumbnail}
                                        alt={`Image ${index}`}
                                    /&gt;
                                ))}
                        &lt;/div&gt;
                    &lt;/PhotoTitleContainer&gt;
                    &lt;PhotoContainer&gt;
                        &lt;Splide
                            options={{
                                rewind: true,
                                gap: &quot;1rem&quot;,
                                perPage: 2,
                                fixedWidth: &quot;50%&quot;,
                                snap: true,
                                lazyLoad: &quot;nearby&quot;,
                            }}
                        &gt;
                            {photos.length &gt;= 1 &amp;&amp;
                                photos?.map((item, index) =&gt; (
                                    &lt;SplideSlide key={index}&gt;
                                        &lt;img
                                            style={{
                                                width: &quot;100%&quot;,
                                                height: 400,
                                            }}
                                            src={item?.original}
                                            alt={`Image ${index}`}
                                        /&gt;
                                    &lt;/SplideSlide&gt;
                                ))}
                        &lt;/Splide&gt;
                    &lt;/PhotoContainer&gt;
                &lt;/ReportDataLayout&gt;
            &lt;/ErrorBoundary&gt;
        &lt;/&gt;
    )
}
</code></pre>
<p>Error boundary component is like this.</p>
<pre><code>class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props)
        this.state = { hasError: false }
    }

    static getDerivedStateFromError(error) {
        return { hasError: true }
    }

    //  Not used at the moment but for logging etc...
    //  We might be able to store it for &quot;raise a support case&quot;

    componentDidCatch(error, errorInfo) {}

    render() {
        if (this.state.hasError) {
            return &lt;Error /&gt;
        }

        return this.props.children
    }
}
</code></pre>
<p>And report data layout is look like this.</p>
<pre><code>const ReportDataLayout = ({
    dataFetchResult,
    noCancel,
    noDataMessage,
    children,
}) =&gt; {
    if (dataFetchResult.isError) throw new Error()

    if (dataFetchResult.isFetching) {
        if (noCancel) {
            return (
                &lt;Container&gt;
                    &lt;Progress size=&quot;large&quot; /&gt;
                &lt;/Container&gt;
            )
        } else {
            return (
                &lt;Container&gt;
                    &lt;ProgressWithCancel
                        size=&quot;large&quot;
                        onCancel={dataFetchResult.cancel}
                    /&gt;
                &lt;/Container&gt;
            )
        }
    }
    if (dataFetchResult.isCanceled) {
        return (
            &lt;Container&gt;
                &lt;UserCanceled /&gt;
            &lt;/Container&gt;
        )
    }
    if (!dataFetchResult.hasData &amp;&amp; !dataFetchResult.isIdle) {
        return (
            &lt;Container&gt;
                &lt;NoData message={noDataMessage} /&gt;
            &lt;/Container&gt;
        )
    }
    return &lt;div&gt;{children}&lt;/div&gt;
}
</code></pre>
<p>After that I wrote an unit testing for this component like this.</p>
<p>Before I adding splideJs it was working like charm after I added that package when I run unit test it is failing. This is how I have wrote it.</p>
<pre><code>import React from &quot;react&quot;
import {
    render,
    screen,
    fireEvent,
    waitFor,
    within,
} from &quot;@testing-library/react&quot;
import axios from &quot;axios&quot;
import MockAdapter from &quot;axios-mock-adapter&quot;
import { BrowserRouter, Routes, Route } from &quot;react-router-dom&quot;
import * as HTTP_STATUS from &quot;../../../data-fetch/constants/httpStatuses&quot;
import Incident from &quot;./Incident&quot;

jest.mock(&quot;react-i18next&quot;, () =&gt; ({
    useTranslation: () =&gt; {
        return {
            t: str =&gt; str,
        }
    },
}))

const mock_refresh = jest.fn()
jest.mock(&quot;../../../framework/useApplication&quot;, () =&gt; ({
    useApplication: () =&gt; {
        return {
            refresh: () =&gt; mock_refresh(),
        }
    },
}))

jest.mock(&quot;../../../utilities/date-formats&quot;, () =&gt; ({
    mediumDateTime: dateTime =&gt; dateTime.toString(),
}))

const renderTestDom = () =&gt; {
    window.history.pushState({}, &quot;Incident&quot;, &quot;/Incident&quot;)
    render(
        &lt;BrowserRouter&gt;
            &lt;Routes&gt;
                &lt;Route path=&quot;/Incident&quot; element={&lt;Incident /&gt;} /&gt;
            &lt;/Routes&gt;
        &lt;/BrowserRouter&gt;
    )
}

const reportData = {
    id: 1,
    driver: &quot;David Smith&quot;,
    locationLat: 52.504897,
    locationLong: -2.080205,
    location: &quot;Prospect Row, Dudley&quot;,
    dateAndTime: &quot;2022-07-12T09:06:18.47&quot;,
    details: &quot;The car was hit by another driver while being parked&quot;,
    otherDriver: {
        driver: &quot;Jack Smith&quot;,
        registration: &quot;Vehicle registration&quot;,
        insurance: &quot;Name of insurance&quot;,
    },
    asset: {
        id: 471319,
        description: &quot;170633 Ginsters&quot;,
        icon: &quot;largevan_green&quot;,
        aspectRatio: 2.5,
        site: 0,
        groups: [],
    },
    photos: [
        {
            fileName: &quot;VehAccident-1&quot;,
            thumbnail: &quot;VehAccident-1-thumb&quot;,
        },
        {
            fileName: &quot;VehAccident-2&quot;,
            thumbnail: &quot;VehAccident-2-thumb&quot;,
        },
    ],
}

describe(&quot;Incident&quot;, () =&gt; {
    let mock_axios
    beforeAll(() =&gt; {
        mock_axios = new MockAdapter(axios)
        Object.defineProperty(window, &quot;matchMedia&quot;, {
            writable: true,
            value: jest.fn().mockImplementation(query =&gt; ({
                matches: false,
                media: query,
                onchange: null,
                addListener: jest.fn(), // Deprecated
                removeListener: jest.fn(), // Deprecated
                addEventListener: jest.fn(),
                removeEventListener: jest.fn(),
                dispatchEvent: jest.fn(),
            })),
        })
    })

    beforeEach(() =&gt; {
        mock_axios
            .onGet(&quot;incidents/GetById&quot;, {
                params: {
                    id: 1,
                },
            })
            .reply(HTTP_STATUS.OK, reportData)
    })

    test(&quot;should render title&quot;, async () =&gt; {
        renderTestDom()
        await waitFor(async () =&gt; {
            expect(screen.getByText(/incident.incident_details/)).not.toBeNull()
        })
    })
})
</code></pre>
<p>But After I wruuning this test it is showing me this issue.</p>
<pre><code>console.error
      Error: Uncaught [TypeError: Cannot read properties of undefined (reading 'matches')]
          at reportException (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\helpers\runtime-script-errors.js:66:24)
          at innerInvokeEventListeners (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:341:9)
          at invokeEventListeners (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:274:3)
          at HTMLUnknownElementImpl._dispatch (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:221:9)
          at HTMLUnknownElementImpl.dispatchEvent (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:94:17)
          at HTMLUnknownElement.dispatchEvent (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\generated\EventTarget.js:231:34)
          at Object.invokeGuardedCallbackDev (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:3994:16)
          at invokeGuardedCallback (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:4056:31)
          at commitRootImpl (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:23151:9)
          at unstable_runWithPriority (E:\Freelance\webclient-fleettacking\node_modules\scheduler\cjs\scheduler.development.js:468:12) TypeError: Cannot read properties of undefined (reading 'matches')
          at E:\Freelance\webclient-fleettacking\node_modules\@splidejs\react-splide\dist\js\react-splide.cjs.js:537:38
          at Array.reduce (&lt;anonymous&gt;)
          at update (E:\Freelance\webclient-fleettacking\node_modules\@splidejs\react-splide\dist\js\react-splide.cjs.js:536:26)
          at Object.setup (E:\Freelance\webclient-fleettacking\node_modules\@splidejs\react-splide\dist\js\react-splide.cjs.js:521:5)
          at E:\Freelance\webclient-fleettacking\node_modules\@splidejs\react-splide\dist\js\react-splide.cjs.js:2471:36
          at forOwn (E:\Freelance\webclient-fleettacking\node_modules\@splidejs\react-splide\dist\js\react-splide.cjs.js:154:13)
          at _Splide2.mount (E:\Freelance\webclient-fleettacking\node_modules\@splidejs\react-splide\dist\js\react-splide.cjs.js:2468:5)
          at Splide2.componentDidMount (E:\Freelance\webclient-fleettacking\node_modules\@splidejs\react-splide\dist\js\react-splide.cjs.js:2691:19)
          at commitLifeCycles (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:20663:24)
          at commitLayoutEffects (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:23426:7)
          at HTMLUnknownElement.callCallback (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:3945:14)
          at HTMLUnknownElement.callTheUserObjectsOperation (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\generated\EventListener.js:26:30)
          at innerInvokeEventListeners (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:338:25)
          at invokeEventListeners (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:274:3)
          at HTMLUnknownElementImpl._dispatch (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:221:9)
          at HTMLUnknownElementImpl.dispatchEvent (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:94:17)
          at HTMLUnknownElement.dispatchEvent (E:\Freelance\webclient-fleettacking\node_modules\jsdom\lib\jsdom\living\generated\EventTarget.js:231:34)
          at Object.invokeGuardedCallbackDev (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:3994:16)
          at invokeGuardedCallback (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:4056:31)
          at commitRootImpl (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:23151:9)
          at unstable_runWithPriority (E:\Freelance\webclient-fleettacking\node_modules\scheduler\cjs\scheduler.development.js:468:12)
          at runWithPriority$1 (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:11276:10)
          at commitRoot (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:22990:3)
          at performSyncWorkOnRoot (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:22329:3)
          at scheduleUpdateOnFiber (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:21881:7)
          at updateContainer (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:25482:3)
          at E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:26021:7
          at unbatchedUpdates (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:22431:12)
          at legacyRenderSubtreeIntoContainer (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:26020:5)
          at Object.render (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:26103:10)
          at E:\Freelance\webclient-fleettacking\node_modules\@testing-library\react\dist\pure.js:101:25
          at batchedUpdates$1 (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom.development.js:22380:12)
          at act (E:\Freelance\webclient-fleettacking\node_modules\react-dom\cjs\react-dom-test-utils.development.js:1042:14)
          at render (E:\Freelance\webclient-fleettacking\node_modules\@testing-library\react\dist\pure.js:97:26)
          at renderTestDom (E:\Freelance\webclient-fleettacking\src\reports\incident\incidentDetailPage\Incident.test.js:38:2)
          at Object.&lt;anonymous&gt; (E:\Freelance\webclient-fleettacking\src\reports\incident\incidentDetailPage\Incident.test.js:110:3)
          at Promise.then.completed (E:\Freelance\webclient-fleettacking\node_modules\jest-circus\build\utils.js:391:28)
          at new Promise (&lt;anonymous&gt;)
          at callAsyncCircusFn (E:\Freelance\webclient-fleettacking\node_modules\jest-circus\build\utils.js:316:10)
          at _callCircusTest (E:\Freelance\webclient-fleettacking\node_modules\jest-circus\build\run.js:218:40)
          at processTicksAndRejections (node:internal/process/task_queues:96:5)
          at _runTest (E:\Freelance\webclient-fleettacking\node_modules\jest-circus\build\run.js:155:3)
          at _runTestsForDescribeBlock (E:\Freelance\webclient-fleettacking\node_modules\jest-circus\build\run.js:66:9)
          at _runTestsForDescribeBlock (E:\Freelance\webclient-fleettacking\node_modules\jest-circus\build\run.js:60:9)
          at run (E:\Freelance\webclient-fleettacking\node_modules\jest-circus\build\run.js:25:3)
          at runAndTransformResultsToJestFormat (E:\Freelance\webclient-fleettacking\node_modules\jest-circus\build\legacy-code-todo-rewrite\jestAdapterInit.js:170:21)
          at jestAdapter (E:\Freelance\webclient-fleettacking\node_modules\jest-circus\build\legacy-code-todo-rewrite\jestAdapter.js:82:19)
          at runTestInternal (E:\Freelance\webclient-fleettacking\node_modules\jest-runner\build\runTest.js:389:16)
          at runTest (E:\Freelance\webclient-fleettacking\node_modules\jest-runner\build\runTest.js:475:34)
          at Object.worker (E:\Freelance\webclient-fleettacking\node_modules\jest-runner\build\testWorker.js:133:12)

      at VirtualConsole.&lt;anonymous&gt; (node_modules/jsdom/lib/jsdom/virtual-console.js:29:45)
      at reportException (node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:70:28)
      at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:341:9)
      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)

    console.error
      The above error occurred in the &lt;Splide2&gt; component:

          at Splide2 (E:\Freelance\webclient-fleettacking\node_modules\@splidejs\react-splide\dist\js\react-splide.cjs.js:2681:5)
          at div
          at I (E:\Freelance\webclient-fleettacking\node_modules\styled-components\src\models\StyledComponent.js:252:3)
          at div
          at ReportDataLayout (E:\Freelance\webclient-fleettacking\src\data-fetch\ReportDataLayout.js:14:2)
          at ErrorBoundary (E:\Freelance\webclient-fleettacking\src\framework\elements\ErrorBoundary.js:10:3)
          at Incident (E:\Freelance\webclient-fleettacking\src\reports\incident\incidentDetailPage\Incident.js:114:19)
          at Routes (E:\Freelance\packages\react-router\index.tsx:336:3)
          at Router (E:\Freelance\packages\react-router\index.tsx:256:13)
          at BrowserRouter (E:\Freelance\packages\react-router-dom\index.tsx:136:3)

      React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
</code></pre>
<p>I tried a lot to find out a solution for this one but I was unable to do so. Can someone help me to solve this. This issue was stopping me for two days now. It would be great if anyone could help me regarding this issue.Thank you</p>
",https://stackoverflow.com/questions/73724933/how-to-write-test-for-react-splide-in-react-with-jest-correctly,"['reactjs', 'jestjs']",159,False,1,0
Getting Error in Unit Testing TeamsFx app,"<p>Is there any recommended framework to be used for unit testing the application built using TeamsFx tab app that can be integrated in a CI/CD pipeline.</p>
<p>I've tried using Jest and Enzyme but was getting errors. Are there any sample projects that can be referred for this?</p>
",https://stackoverflow.com/questions/71651401/getting-error-in-unit-testing-teamsfx-app,"['microsoft-graph-teams', 'teams-toolkit']",113,False,0,1
"Combination of Vue 3 + Vuetify 3 + vue/test-utils, results in &quot;Could not find injected Vuetify layout&quot; error","<p>Does anyone know how to do component testing in <code>@vue/test-utils v2</code> library, while using <code>Vuetify 3 Beta</code> version? I am also using <code>Vue3 composition API</code> to define my components. The documentation that i found here <a href=""https://vuetifyjs.com/en/getting-started/unit-testing/#spec-tests"" rel=""noreferrer"">https://vuetifyjs.com/en/getting-started/unit-testing/#spec-tests</a> is not working, since it is for <code>Vuetify v2</code> and <code>@vue/test-utils v1</code></p>
<p>This is my plugins/vuetify.js</p>
<pre><code>import '@mdi/font/css/materialdesignicons.css';
import 'vuetify/styles';
import { createVuetify } from 'vuetify';

export default createVuetify();
</code></pre>
<p>This is my code in NavBar.spec.js</p>
<pre><code>import { mount } from '@vue/test-utils';
import NavBar from '../NavBar.vue';
import Vuetify from '../../plugins/vuetify';

describe('NavBar', () =&gt; {
    it('No properties [correct]', () =&gt; {
        mount(NavBar, {
            props: {},
            global: {
                plugins: [Vuetify]
            }
        });
        // check if navbar renders
        cy.get('.main')
            .first();

    });
});
</code></pre>
<p>This is the error i receive:
<code>Could not find injected Vuetify layout</code></p>
",https://stackoverflow.com/questions/72350551/combination-of-vue-3-vuetify-3-vue-test-utils-results-in-could-not-find-in,"['components', 'vuetify.js', 'vuejs3', 'vue-test-utils']",4510,True,9,4
Unit testing the login method with firebase in android studio,"<p>I'm carrying out a university project. I need to know if the unit test I did of the login method with firebase in android studio is correct. I'm a beginner with unit testing. Below I indicate the method and the test carried out.</p>
<pre><code>public void signUp(String nickname, String email, String password,String dataOfBirth, String gender){
        auth = FirebaseAuth.getInstance();
        referenceDb = FirebaseDatabase.getInstance().getReference();
        auth.createUserWithEmailAndPassword(email,password)
                .addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
                    @Override
                    public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                        if (task.isSuccessful()) {

                            String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

                            UserDao userDao = new UserDao();
                            User currUser = new User(uid, nickname, email, password, dataOfBirth, gender);

                            referenceDb.child(&quot;Users&quot;).child(uid).setValue(currUser).addOnCompleteListener(new OnCompleteListener&lt;Void&gt;() {
                                @Override
                                public void onComplete(@NonNull Task&lt;Void&gt; task) {
                                    if (task.isSuccessful()) {

                                       Toast.makeText(singUp_fragment.getActivity(), &quot;SingUp successful&quot;, Toast.LENGTH_SHORT).show();
                                        openHomeFragment();
                                    } else {
                                        Toast.makeText(singUp_fragment.getActivity(), &quot;SingUp failed. Please try again&quot;, Toast.LENGTH_SHORT).show();
                                        singUp_fragment.progressBar.setVisibility(View.GONE);
                                    }
                                }
                            });
                        } else {
                            Resources resources = singUp_fragment.getStartActivity().getResources();
                            singUp_fragment.cleanTextInputErrors();
                            try {
                                throw task.getException();
                            } catch (NoInternetConnectionException e) {
                                MotionToast.display(
                                        singUp_fragment.getStartActivity(),
                                        R.string.toast_warning_internet_connection,
                                        MotionToastType.WARNING_MOTION_TOAST
                                );
                            } catch (FirebaseAuthInvalidUserException e) {
                                singUp_fragment.setTextInputNicknameError(
                                        resources.getString(R.string.fragment_sign_up_invalid_nickname)
                                );
                            } catch (FirebaseAuthUserCollisionException e) {
                                singUp_fragment.setTextInputEmailError(
                                        resources.getString(R.string.fragment_sign_up_invalid_login)
                                );
                            } catch (Exception e) {
                                MotionToast.display(
                                        singUp_fragment.getStartActivity(),
                                        R.string.toast_error_unknown_error,
                                        MotionToastType.ERROR_MOTION_TOAST
                                );
                            }
                        }
                        singUp_fragment.progressBar.setVisibility(View.GONE);
                        singUp_fragment.setEnabledButtonSignUp(true);
                    }
                });
    }
</code></pre>
<p>I tested it like this:</p>
<pre><code>public class SingIn_Test {
    FirebaseAuth auth;
    boolean test;

    @Test
    public void ValidEmailPasswordTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;annal@live.it&quot;, &quot;Annamaria2222&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidEmptyEmailPasswordTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;&quot;, &quot;&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidEmptyEmailTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;&quot;, &quot;Annamaria2222&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidEmptyPasswordTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;annal@live.it&quot;, &quot;&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidFormatEmailPasswordTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;annal@live&quot;, &quot;Annamaria&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidFormatPasswordTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;annal@live.it&quot;, &quot;Annamaria&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

    @Test(expected = IllegalArgumentException.class)
    public void InvalidFormatEmailTest(){

        test = false;
        auth = FirebaseAuth.getInstance();

        auth.signInWithEmailAndPassword(&quot;annal@live&quot;, &quot;Annamaria2222&quot;).addOnCompleteListener(new OnCompleteListener&lt;AuthResult&gt;() {
            @Override
            public void onComplete(@NonNull Task&lt;AuthResult&gt; task) {
                if (task.isSuccessful()) {
                    Assert.assertTrue(true);

                } else {
                    Assert.assertFalse(false);
                }
                test = true;
            }
        });
        while(!test){

        }
    }

}
</code></pre>
<p>it's correct?</p>
",https://stackoverflow.com/questions/74795167/unit-testing-the-login-method-with-firebase-in-android-studio,"['android', 'firebase', 'unit-testing']",77,False,1,0
CLI app test fails if `cargo build` is not run first,"<p>I have a pure Rust CLI app that I'm unit testing, and if I run</p>
<pre><code>cargo clean
cargo test --release
</code></pre>
<p>it fails to find the binary, but if I run</p>
<pre><code>cargo clean
cargo build --release
cargo test --release
</code></pre>
<p>it works.  Is there a way to tell cargo not to run the test until the binary app has been built?</p>
<p>Here's my test harness:</p>
<pre><code>#[cfg(test)]
pub mod tests {
    use std::process::Command;

    use assert_cmd::prelude::{CommandCargoExt, OutputAssertExt};
    use predicates::prelude::predicate;

    #[test]
    fn test_that_cli_app_produces_result() -&gt; Result&lt;(), Box&lt;dyn std::error::Error&gt;&gt; {
        let mut cmd = Command::cargo_bin(&quot;fastsim-cli&quot;)?;
        let mut cyc_file = project_root::get_project_root().unwrap();
        cyc_file.push(&quot;../fastsim/resources/cycles/udds.csv&quot;);
        assert!(cyc_file.exists());
        let mut veh_file = project_root::get_project_root().unwrap();
        veh_file.push(&quot;../fastsim/resources/vehdb/2012_Ford_Fusion.yaml&quot;);
        assert!(veh_file.exists());

        cmd.args([
            &quot;--cyc-file&quot;,
            cyc_file.to_str().unwrap(),
            &quot;--veh-file&quot;,
            veh_file.to_str().unwrap(),
        ]);
        cmd.assert()
            .success()
            .stdout(predicate::str::contains(&quot;32.4&quot;));

        Ok(())
    }
}
</code></pre>
",https://stackoverflow.com/questions/73574457/cli-app-test-fails-if-cargo-build-is-not-run-first,"['unit-testing', 'rust', 'command-line-interface']",104,True,1,1
Looking for documentation setup jest for unit test of admin plugin,"<p>my project was created with the <code>swdc create-project ...</code></p>
<p>Is there a <strong>documentation</strong>, a <strong>tutorial</strong> or <strong>description</strong> for the right <strong>setup/configuration</strong> <strong>unit testing</strong> with <strong>JEST</strong> for custom plugin in administration?</p>
<p><a href=""https://developer.shopware.com/docs/guides/plugins/plugins/testing/jest-admin"" rel=""nofollow noreferrer"">This tutorial</a> describes only how to write a test</p>
<p>But i think there must be a official setup documentation because of versions etc.</p>
",https://stackoverflow.com/questions/74031407/looking-for-documentation-setup-jest-for-unit-test-of-admin-plugin,"['unit-testing', 'jestjs', 'shopware6', 'shopware6-api']",73,True,1,2
Deno unit testing error No such file or directory (os error 2),"<p>Hey dont know if im being silly im trying to learn unit testing with deno and keep getting this error im using puppeteer if thats relevant cant figure out whats wrong it seems to be pointing to the await in this line</p>
<p>const browser = await puppeteer.launch({ headless: true })</p>
<pre><code>Deno.test('log in with invalid username/password', async test =&gt; {
    // GIVEN I am on the &quot;Log In&quot; page
            const browser = await puppeteer.launch({ headless: true })
            const page = await browser.newPage()
            await page.goto(url, { waitUntil: 'networkidle0' })
            await page.click('a[href=&quot;/login&quot;]', { waitUntil: 'networkidle0' })
    // WHEN I enter &quot;fakeuser&quot; in the username field
            await page.type('input[name=&quot;username&quot;]', 'fakeuser')
    // AND I enter &quot;fakepassword&quot; in the password field
            await page.type('input[name=&quot;password&quot;]', 'fakepassword')
    // AND I click on the login button
            await page.click('input[type=&quot;submit&quot;]', { waitUntil: 'networkidle0' })
    // THEN I should be returned to the &quot;Log In&quot; page
            const heading = await page.$eval('h1', node =&gt; node.innerText)
            await assertEquals(heading, 'Log In', 'invalid credentials dont send user back to login page')
            await browser.close()
})
</code></pre>
<p><a href=""https://i.stack.imgur.com/lE6eY.png"" rel=""nofollow noreferrer"">error code image</a></p>
",https://stackoverflow.com/questions/72842537/deno-unit-testing-error-no-such-file-or-directory-os-error-2,"['javascript', 'unit-testing', 'deno']",255,False,1,1
How Can I Setup mock object for unit test with Moq and Xunit in ASP.NET MVC Application?,"<p>I am new to unit testing and was trying to write unit tests for controllers' action methods using Moq Library and Xunit framework. I created a list of departments as mock data and tried testing it by passing in Returns() method with the Setup() method of the Moq. But it shows error</p>
<p>&quot;Cannot convert type 'System.Collections.Generic.List&lt;DotNetMvcDemo.Models.Department&gt;' to 'System.Web.Mvc.ActionResult' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion&quot;.</p>
<pre><code>public ActionResult Index()
    {
        //var departments = db.Departments.Include(d =&gt; d.CreatorUser).Include(d =&gt; d.UpdaterUser);
        var departments = new List&lt;Department&gt;();
        using (var db = new ApplicationDbContext())
        {
            departments = db.Departments.ToList();
        }

        var departmentsViewList = new List&lt;DepartmentViewModel&gt;();
        

        foreach (var department in departments)
        {
            var departmentView = new DepartmentViewModel();
            departmentView.Id = department.Id;
            departmentView.Name = department.Name;
            departmentView.Description = department.Description;
            
            
            departmentsViewList.Add(departmentView);
        }

        return View(departmentsViewList);
    }
</code></pre>
<pre><code>public Mock&lt;DepartmentsController&gt; mock = new Mock&lt;DepartmentsController&gt;();

        private readonly DepartmentsController _controller;
        public DepartmentControllerTest()
        {
            _controller = new DepartmentsController();
        }
        private static List&lt;Department&gt; GetTestDepartments()
        {
            var mockDepartments = new List&lt;Department&gt;
            {
                new Department()
                {
                    Id = 1,
                    Name = &quot;test one&quot;,
                    Description = &quot;test desc&quot;
                },
                new Department()
                {
                    Id = 2,
                    Name = &quot;test two&quot;,
                    Description = &quot;test desc&quot;
                },
                new Department()
                {
                    Id = 3,
                    Name = &quot;test three&quot;,
                    Description = &quot;test desc&quot;
                }
            };
            return mockDepartments;
        }

        [Fact]
        public void Can_Get_Department()
        {
            //Arrange
            mock.Setup(m =&gt; m.Index()).Returns(GetTestDepartments() as ActionResult);

            //Act
          
            //Assertion
        }
</code></pre>
<p>I looked for solution how to write unit test with Moq and xunit in ASP.NET MVC application. But I could not relate to my problem as most of the tutorials used Interface/ Repository Pattern to do unit testing and I have only controllers to work with. Can I get a suggestion or a guideline how can I properly write unit test for CRUD operations?</p>
",https://stackoverflow.com/questions/74557471/how-can-i-setup-mock-object-for-unit-test-with-moq-and-xunit-in-asp-net-mvc-appl,"['asp.net', 'asp.net-mvc', 'unit-testing', 'moq', 'xunit']",626,True,0,1
Correct initialization of state for properties without a setter in unit tests,"<p>I have problems setting the correct state before unit testing. The simplified model below examplifies my problem. A <code>Student</code> entity has a property <code>Courses</code> of type <code>IReadOnlyCollection</code> and only a getter.</p>
<pre><code>public class Course : ICourse
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection&lt;Student&gt; Students { get; set; }
}

public class Student : IStudent
{
    public int Id { get; set; }
    public string Name { get; set; }
    public IReadOnlyCollection&lt;Course&gt; Courses { get; }
}
</code></pre>
<p>Before deletion of a <code>Student</code> the entity is eager loaded from a Repository and any <code>Course</code> the student is assigned to are also eager loaded (Using <code>Include</code>) into <code>Courses</code>.
<code>StudentService</code> must check if any <code>Course</code> exists before performing delete of <code>Student</code></p>
<pre><code>public class StudentService : IStudentService
{
    public async Task&lt;bool&gt; DeleteStudent(int id)
    {
        Student student = await myRepository.GetStudent(id);
        if !student.Courses.Any()

            await myRepository.DeleteStudent(id);

        throw Exception;
    }
}
</code></pre>
<p>To Unit test this functionality I have created the test below, but I cannot bring <code>Student</code> to the correct state as the Courses property has no setter.
I can of cause change the setter to public, but I don´t want the programmer to add <code>Courses</code> to a <code>Student</code>, <code>Student</code> shall  only be added to <code>Courses</code>. But this breaks encapsulation and is also considered bad pratice for unit testing.</p>
<pre><code>public class StudentServiceTest
{
    [Fact]
    public void DeleteStudent_Success()
    {
        // Arrange
        Student student = new Student
        {
            Id = 1,
            Name = &quot;Test Name&quot;,
            Courses = new List&lt;Course&gt; { new Course { Id = 1 } }
        };

        Mock&lt;IMyRepository&gt; mockRepo = new Mock&lt;IMyRepository&gt;();
        mockRepo.Setup(repos =&gt; repos.GetStudent(It.Is&lt;int&gt;(i =&gt; i == 1).Result).Returns(student).Verifiable();
        mockRepo.Setup(repos =&gt; repos.DeleteStudent(It.Is&lt;int&gt;(i =&gt; i == 1).Result).Verifiable();

        IMyRepository studentRepos = mockRepo.Object;

        IStudentService studentService = new StudentService(studentRepos);

        // Act
        Func&lt;Task&gt; act = () =&gt; studentRepos.DeleteStudent(entry);

        // Assert
        act().Should().ThrowAsync&lt;Exception&gt;();
        mockRepo.Verify(repos =&gt; repos.GetStudent(It.Is&lt;int&gt;(i =&gt; i == 1), Times.Once);
        mockRepo.Verify(repos =&gt; repos.DeleteStudent(It.Is&lt;int&gt;(i =&gt; i == 1), Times.Never);
    }
}
</code></pre>
<p>Any good idea or hint on how to set the correct state of <code>Student</code>?</p>
",https://stackoverflow.com/questions/72909284/correct-initialization-of-state-for-properties-without-a-setter-in-unit-tests,"['c#', 'initialization', 'xunit', 'getter-setter']",160,True,0,1
Cannot find module or its corresponding type declaration,"<p>I am setting up a typescript vue3 project at the moment and wanted to use jest for some unit testing, however I am running into the following error when running my test file:</p>
<blockquote>
<p>Cannot find module '@/app/views/main/result.vue' or its corresponding type declarations.</p>
</blockquote>
<p>This is my test file:</p>
<pre><code>import { mount } from &quot;@vue/test-utils&quot;;
import { createTestingPinia } from &quot;@pinia/testing&quot;;
import { useShoppingCartStore } from &quot;@/app/store/shopping-cart&quot;;
import Result from &quot;@/app/views/main/result.vue&quot;

const cartStore = useShoppingCartStore();

const wrapper = mount(Result, {
    global: {
        plugins: [createTestingPinia()],
    },
});

describe(&quot;Test&quot;, () =&gt; {
    it(&quot;is two&quot;, () =&gt; {
        // expect(something).to[matcher](value)
        console.log(cartStore.shoppingCart)
        expect(1 + 1).toBe(2);
    });
});

</code></pre>
<p>tsconfig:</p>
<pre><code>{
    &quot;compilerOptions&quot;: {
        &quot;target&quot;: &quot;ESNext&quot;,
        &quot;module&quot;: &quot;ESNext&quot;,
        &quot;jsx&quot;: &quot;preserve&quot;,
        &quot;moduleResolution&quot;: &quot;node&quot;,
        &quot;baseUrl&quot;: &quot;.&quot;,
        &quot;types&quot;: [&quot;jest&quot;, &quot;node&quot;, &quot;vite/client&quot;],
        &quot;paths&quot;: {
            &quot;@/*&quot;: [&quot;./src/*&quot;],
            &quot;@shared/*&quot;: [&quot;./src/shared/*&quot;],
            &quot;@controls/*&quot;: [&quot;./src/app/components/controls/*&quot;]
        },
        &quot;outDir&quot;: &quot;./dist&quot;,
        &quot;strict&quot;: true,
        &quot;importHelpers&quot;: true,
        &quot;experimentalDecorators&quot;: true,
        &quot;skipLibCheck&quot;: true,
        &quot;esModuleInterop&quot;: true,
        &quot;allowSyntheticDefaultImports&quot;: true,
        &quot;sourceMap&quot;: true,
        &quot;noImplicitAny&quot;: false,
        &quot;lib&quot;: [&quot;esnext&quot;, &quot;dom&quot;, &quot;dom.iterable&quot;, &quot;scripthost&quot;],
        &quot;emitDecoratorMetadata&quot;: true
    },
    &quot;include&quot;: [&quot;src/app/**/*.ts&quot;, &quot;src/app/**/*.vue&quot;],
    &quot;exclude&quot;: [&quot;src/server/**/*&quot;, &quot;node_modules&quot;, &quot;dist&quot;]
}

</code></pre>
<p>jestconfig:</p>
<pre><code>module.exports = {
    preset: '@vue/cli-plugin-unit-jest/presets/typescript-and-babel',
    transform: {
        &quot;^.+\\.vue$&quot;: &quot;@vue/vue3-jest&quot;,
        &quot;^.+\\.(t|j)s$&quot;: &quot;ts-jest&quot;,
    },
    &quot;moduleDirectories&quot;: [&quot;src&quot;, &quot;node_modules&quot;],
    &quot;moduleFileExtensions&quot;: [&quot;js&quot;, &quot;json&quot;, &quot;ts&quot;],
    &quot;testMatch&quot;: [&quot;**/__tests__/*.{j,t}s?(x)&quot;, &quot;**/tests/unit/**/*.spec.{j,t}s?(x)&quot;, &quot;**/*.spec.{j,t}s?(x)&quot;],
    &quot;rootDir&quot;: &quot;src&quot;,
    &quot;collectCoverageFrom&quot;: [&quot;**/*.(t|j)s&quot;],
    &quot;coverageDirectory&quot;: &quot;../coverage&quot;,
    //testEnvironment should be jsdom for frontend, could cause issues with server tests
    &quot;testEnvironment&quot;: &quot;jsdom&quot;,
    &quot;moduleNameMapper&quot;: {
        &quot;@shared/(.*)&quot;: &quot;&lt;rootDir&gt;/shared/$1&quot;,
        &quot;@server/(.*)&quot;: &quot;&lt;rootDir&gt;/server/$1&quot;,
        &quot;@/(.*)&quot;: &quot;&lt;rootDir&gt;/$1&quot;,
        &quot;@controls/(.*)&quot;: &quot;&lt;rootDir&gt;/app/components/controls/$1&quot;,
        &quot;\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$&quot;: &quot;&lt;rootDir&gt;/tests/mockUtils/fileImport.js&quot;,
        &quot;\\.(css|less)$&quot;: &quot;&lt;rootDir&gt;/tests/mockUtils/styleImport.js&quot;,
    },
    globals: {
        &quot;ts-jest&quot;: {
            tsConfig: &quot;tsconfig.server.json&quot;,
        },
    },
};

</code></pre>
",https://stackoverflow.com/questions/73854896/cannot-find-module-or-its-corresponding-type-declaration,"['typescript', 'jestjs', 'vuejs3']",838,False,2,0
Should we need to mock mongoose validate() method while unit testing?,"<p>I am unit testing my node application with Jest. Should we need to mock the mongoose validate() method?</p>
<p>I want to test my mongoose model which is this:</p>
<pre><code>const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, &quot;Please enter your name&quot;],
  },
  email: {
    type: String,
    required: [true, &quot;Please enter your email address&quot;],
  },
  password: {
    type: String,
    required: [true, &quot;Please enter password for your account&quot;]
  },
  createdAt: {
    type: Date,
    default: Date.now,
  },
});

export default mongoose.model(&quot;User&quot;, userSchema);
</code></pre>
<p>And I have written unit test like this.</p>
<pre><code>describe(&quot;User Model&quot;, () =&gt; {
  it(&quot;should throw validation error for required fields&quot;, async () =&gt; {
    const user = new User();

    try {
      await user.validate();
    } catch (err) {
      expect(err.errors.name).toBeDefined();
      expect(err.errors.email).toBeDefined();
      expect(err.errors.password).toBeDefined();
    }
  });

  it(&quot;should create a new user&quot;, async () =&gt; {
    const user = new User({
      name: &quot;Test&quot;,
      email: &quot;test@gmail.com&quot;,
      password: &quot;123456&quot;,
    });

    expect(user).toHaveProperty(&quot;_id&quot;);
  });
});
</code></pre>
<p>Please let me know is this correct way to unit test it? Thank You!</p>
",https://stackoverflow.com/questions/74411941/should-we-need-to-mock-mongoose-validate-method-while-unit-testing,"['javascript', 'node.js', 'unit-testing', 'jestjs']",20,False,0,0
Smoke testing on Spring Rest,"<p>I need to implement smoke testing for a Spring Rest app, the ST concept I know.
But is hard to find a code example.</p>
<p>So I was wondering whether the Unit Testing on Controllers level can be considered a Smoke Testing. Otherwise, any code snippet or Gitlab will help.
Thanks</p>
",https://stackoverflow.com/questions/72796995/smoke-testing-on-spring-rest,"['java', 'spring', 'smoke-testing']",468,False,0,0
UNIT Test Error: No Contract deployed with name Raffle,"<p>This is the section of my unit testing... I've been working on this problem for the last few hours. I couldn't, however... I think the error is in
<code>const { deployer } = await getNamedAccounts()</code> this line. Raffle contract isn't recognized... (Note- All the deployments are working correctly... )</p>
<pre><code>    !developmentChains.includes(network.name)
        ? describe.skip()
        : describe(&quot;Raffle UNIT test&quot;, async () =&gt; {
              let raffle, vrfCoordinatorV2Mock
              const chainId = network.config.chainId
              beforeEach(async () =&gt; {
                  const { deployer } = await getNamedAccounts()
                  await deployments.fixture([&quot;all&quot;])
                  raffle = await ethers.getContract(&quot;Raffle&quot;, deployer)
                  vrfCoordinatorV2Mock = await ethers.getContract(&quot;VRFCoordinatorV2Mock&quot;, deployer)
              })
              describe(&quot;Constructor function&quot;, async () =&gt; {
                  it(&quot;Initializes the raffle correctly.&quot;, async () =&gt; {
                      const raffleState = await raffle.getRaffleState()
                      const interval = await raffle.getInterval()
    
                      assert.equal(raffleState.toString(), &quot;0&quot;)
                      assert.equal(interval.toString(), networkConfig[chainId][&quot;interval&quot;])
                  })
              })
          })

</code></pre>
<p>ERROR that I got...</p>
<pre><code> ~/b/JSweb3_2/smart-contract_lottery  on main !2  hh test                                                      ✔  took 5s  system    at 07:27:25 am 


  Raffle UNIT test
    Constructor function
Development chain detected! Deploying mocks
Mocks deployed!!!...
---------------------!--!--!---------------------
      1) &quot;before each&quot; hook for &quot;Initializes the raffle correctly.&quot;
  0 passing (428ms)
  1 failing

  1) Raffle UNIT test
       &quot;before each&quot; hook for &quot;Initializes the raffle correctly.&quot;:
     Error: No Contract deployed with name Raffle
      at Object.getContract (node_modules/@nomiclabs/hardhat-ethers/src/internal/helpers.ts:447:11)
      at processTicksAndRejections (node:internal/process/task_queues:96:5)
      at runNextTicks (node:internal/process/task_queues:65:3)
      at listOnTimeout (node:internal/timers:528:9)
      at processTimers (node:internal/timers:502:7)
      at Context.&lt;anonymous&gt; (test/unit/Raffle.test.js:16:24)
</code></pre>
<p>I AM FOLLOWING A CORDING TUTOTIAL.</p>
",https://stackoverflow.com/questions/72739047/unit-test-error-no-contract-deployed-with-name-raffle,"['javascript', 'unit-testing', 'solidity']",600,True,0,1
How write unit test cases for service file with rxjs next method,"<p>I am new to angular unit testing and I have tried to write test cases for service file. I need to write test cases for below code</p>
<pre><code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class EmployeeDetailsService {
  private readonly employeeRoles = new BehaviorSubject&lt;any&gt;([]);
  private readonly isEmployeeData = new BehaviorSubject&lt;boolean&gt;(true);

  employeeRolesData = this.employeeRoles.asObservable();
  isEmployee = this.isEmployeeData.asObservable();

  addEmployeeRoles(data: string) {
    this.employeeRoles.next(data);
  }

  checkIsEmployee(data: boolean) {
    this.isEmployeeData.next(data);
  }
}
</code></pre>
<p>what I have tried is</p>
<pre><code>import { TestBed } from '@angular/core/testing';
import { EmployeeDetailsService } from './EmployeeDetails.service';

describe('EmployeeDetailsService', () =&gt; {
    let service: EmployeeDetailsService;

    beforeEach(() =&gt; {
        TestBed.configureTestingModule({});
        service = TestBed.inject(EmployeeDetailsService);
    });

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

    it('addEmployeeRoles', () =&gt; {
        service.addEmployeeRoles.subscribe(data =&gt; {
            expect(data).toEqual(data);
        })
    });

    it('checkIsEmployee', () =&gt; {
        service.checkIsEmployee.subscribe(data=&gt;{
            expect(data).toEqual(data)
        })
    });

})
</code></pre>
<p>Unit test cases are passing, but code coverage is not improving. So please help me to solve this.</p>
",https://stackoverflow.com/questions/70711019/how-write-unit-test-cases-for-service-file-with-rxjs-next-method,"['angular', 'angular-unit-test']",596,False,0,1
Angular unit test - property in mock service is undefined,"<p>I am unit testing a presentational component. One of its services I am mocking has a getter property, user. This component derives from another. On the ngOnInit of its parent the sessionService's user property is accessed and it fails as it finds it undefined. What's another approach to try here?</p>
<pre><code>describe('MyComponent', () =&gt; {
let component: MyComponent, fixture: ComponentFixture&lt;MyComponent&gt;, el: DebugElement;

beforeEach(
    waitForAsync(() =&gt; {
        const sessionService = jasmine.createSpyObj('SessionService', ['']);
        Object.defineProperty(sessionService, 'user', {
            value: of(
                new User()
            )
        });
        TestBed.configureTestingModule({
            declarations: [MyComponent],
            imports: [...],
            providers: [                    
                { provide: SessionService, useValue: sessionService }
            ]
        })
            .compileComponents()
            .then(() =&gt; {
                fixture = TestBed.createComponent(MyComponent);
                component = fixture.componentInstance;
                el = fixture.debugElement;
            });
    })
);

it('should have prev/next buttons', () =&gt; {        
    fixture.detectChanges();
    console.log(el.nativeElement.outerHTML);
  });
});
</code></pre>
",https://stackoverflow.com/questions/71839464/angular-unit-test-property-in-mock-service-is-undefined,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1212,True,0,2
groovy is not finding annotated tests,"<p>Still new to Groovy and trying to figure out unit testing.  I'm trying to use the Junit4 style of testing.</p>
<pre><code>import org.junit.Test
import junit.framework.*
import junit.textui.TestRunner

class DegenerateTestCase {
    @Test
    void testAlwaysTrue() {
        assert true
    }

    @Test
    void someMethodName() {
        assert true
    }
}

TestRunner.run(DegenerateTestCase)
</code></pre>
<p>But when I run the script, I get</p>
<blockquote>
<p>There was 1 failure:</p>
<ol>
<li>warning(junit.framework.TestSuite$1)junit.framework.AssertionFailedError:&gt; No tests found in DegenerateTestCase</li>
</ol>
</blockquote>
<p>This has to be something simple that I'm missing.</p>
",https://stackoverflow.com/questions/72045791/groovy-is-not-finding-annotated-tests,"['groovy', 'junit']",69,False,0,1
How to do integration testing,"<pre><code>
def customer_menu():
    print(&quot;&gt;&gt; Customer MENU:\n&quot;)
    print(&quot;1. Deposit\n2. Withdrawal\n3. View Transaction\n4. Logout&quot;)
    opt_customer_menu=int(input(&quot;&gt; Please select your option (1/2/3/4): &quot;))
    while(opt_customer_menu !='4'):
        if (opt_customer_menu==1):
            customer_deposit()
        elif(opt_customer_menu==2):
            customer_withdraw()
        elif(opt_customer_menu==3):
            customer_view()
        elif(opt_customer_menu==4):
            print(&quot;*** Good bye! Have a nice day! ***\n\n&quot;)
            main_menu()
        else:
            print(&quot;!!! Invalid Option! Please read the option carefully! !!!\n&quot;)
        opt_customer_menu=int(input(&quot;&gt; Please select your option (1/2/3/4): &quot;))
        
def customer_deposit():
    print(&quot;\nYou choose '1. Deposit'&quot;)
    print(&quot;----------------------------------&quot;)
    deposit_id = str(input(&quot;&gt; Enter your Customer ID: &quot;))
    deposit_balance = str(input(&quot;&gt; Enter the BALANCE to be deposit: &quot;))
    deposit_pass = str(input(&quot;&gt; Enter your Password: &quot;))
    customer_file = open(&quot;customer_db.txt&quot;,&quot;r&quot;)
    transaction_file = open(&quot;transaction_db.txt&quot;,&quot;a&quot;)
    for line in customer_file:
        cust_deposit = line.strip().split(&quot;,&quot;)
        if (deposit_id == cust_deposit[0] and deposit_pass == cust_deposit[4]):
            transaction_file.write(deposit_id+&quot;,&quot;+deposit_balance+&quot;,Deposit\n&quot;)
            transaction_file.close()
            print(&quot;*** BALANCE SUCSSESFULLY DEPOSIT! ***&quot;)
            print(&quot;--- Return to Customer Menu ---\n&quot;)
            customer_menu()
            return True
    print(&quot;!!! You enter wrong ID or Password !!!&quot;)
    print(&quot;--- Return to Customer Menu ---\n\n&quot;)
    customer_menu()
    return False
    

#Customer withdraw transaction
def customer_withdraw():
    print(&quot;\nYou choose '2. Withdrawal'&quot;)
    print(&quot;----------------------------------&quot;)
    withdrawal_id = str(input(&quot;&gt; Enter your Customer ID: &quot;))
    withdrawal_balance = str(input(&quot;&gt; Enter the BALANCE to be withdraw: &quot;))
    withdrawal_pass = str(input(&quot;&gt; Enter your Password: &quot;))
    customer_file = open(&quot;customer_db.txt&quot;,&quot;r&quot;)
    transaction_file = open(&quot;transaction_db.txt&quot;,&quot;a&quot;)
    for line in customer_file:
        cust_withdrawal = line.strip().split(&quot;,&quot;)
        if (withdrawal_id == cust_withdrawal[0] and withdrawal_pass == cust_withdrawal[4]):
            transaction_file.write(withdrawal_id+&quot;,-&quot;+withdrawal_balance+&quot;,Withdrawal\n&quot;)
            transaction_file.close()
            print(&quot;*** WITHDRAWAL SUCCESS! ***&quot;)
            print(&quot;--- Return to Customer Menu ---\n&quot;)
            customer_menu()
            return True
    print(&quot;!!! You enter wrong ID or Password !!!&quot;)
    print(&quot;--- Return to Customer Menu ---\n\n&quot;)
    customer_menu()
    return False
    
)
    
customer_menu()
</code></pre>
<p>I'm do the unit test with using pytest successfully but I cant do the integration test. I can't imagine how to make a code for do integration test.I have no idea about that so.This is a simple banking app.need a testing code.i combine unit testing codes .but not working.please help me.</p>
",https://stackoverflow.com/questions/74547971/how-to-do-integration-testing,"['python', 'pytest']",28,False,0,0
"Laravel PHPUnit failed to load file on first try, but worked on second try","<p>I'm working on Laravel 9 running on PHP 8.1, doing some Unit Testing to load files under the <code>tests</code> directory</p>
<p>It's always failed on the first try since the code test is created. But it will work normally on the second try.</p>
<p><a href=""https://i.stack.imgur.com/2HeVT.gif"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2HeVT.gif"" alt=""enter image description here"" /></a></p>
<p>Is this have something to do with the <code>phpunit.xml</code> configuration?</p>
",https://stackoverflow.com/questions/73030942/laravel-phpunit-failed-to-load-file-on-first-try-but-worked-on-second-try,"['laravel', 'unit-testing', 'phpunit', 'php-8.1']",175,False,0,1
Angular unable to test router event,"<p>I am trying to perform unit testing for the router events mentioned in my component file. Here is the respective code:</p>
<pre><code>this.router.events.pipe(filter(event =&gt; event instanceof NavigationEnd)).subscribe((val: NavigationEnd) =&gt; {
        // code here
    });
</code></pre>
<p>For unit tesing, I have added a mock class as:</p>
<pre><code>class MockServices {
   public events = of( new NavigationEnd(0, 'http://localhost:4200/', 'http://localhost:4200/'));
}
</code></pre>
<p>and injected as provider:</p>
<pre><code>{ provide: Router, useClass: MockServices }
</code></pre>
<p>Getting the below error:
<a href=""https://i.stack.imgur.com/KBkEN.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/KBkEN.png"" alt=""enter image description here"" /></a></p>
<p>Can some please help me to resolve this. Thanks in advance</p>
",https://stackoverflow.com/questions/72948883/angular-unable-to-test-router-event,"['angular', 'karma-jasmine', 'angular-test', 'karma-coverage']",35,False,0,0
Unit test running forever for call back method in C#,"<p>Following is the method to receive the message on RabbitMq Queue. Method works fine but the unit testing this method has problem mentioned below</p>
<pre><code>      public void GetMessage(Action&lt;string&gt; action)
    {
        //create a connection factory
        var factory = new ConnectionFactory();

        if (_connectionString != null)
        {
            //assign connection string of rabbitmq
            factory.Uri = new Uri(_connectionString);
        }

        //create connection and channel from connectionfactory
        using (var connection = factory.CreateConnection())
        using (var channel = connection.CreateModel())
        {

            //declare the queque on the channel
            channel.QueueDeclare(queue: _queque,
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            //create consumer using the channel
            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =&gt;
            {
                //When message is recieved on the consumer this will be triggered
                var body = ea.Body.ToArray();
                _message = Encoding.UTF8.GetString(body);

                //call the method passed by the caller method
                action(_message);
            };

            //add the consumer on this channel
            channel.BasicConsume(queue: _queque,
                                 autoAck: true,
                                 consumer: consumer);

            Console.ReadLine();
        }

    }
</code></pre>
<p>How to write a unit test test above message. Below unit test loading forever inside the call back method and the execution never goes to Assert.Equal line.</p>
<pre><code>      [Fact]
    public async Task AddMessageAsync_ShouldAddToQueue()
    {
        //Arrange
        string messageToSend = &quot;Test&quot;;
        string recievedMessage = null;
        var queue = GetQueueManager();

        queue.Message = messageToSend;

        await queue.AddMessageAsync();

        //Act
        queue.GetMessage((string message) =&gt;
        {
            //Hit here and recieved the message but does not exist from this method
            recievedMessage = message;
        });

        //Assert
        Assert.Equal(messageToSend, recievedMessage);
    }
</code></pre>
",https://stackoverflow.com/questions/71046474/unit-test-running-forever-for-call-back-method-in-c,"['c#', 'unit-testing', 'asynchronous', 'rabbitmq']",180,True,0,1
Jest: branch not getting covered with &#39;?&#39; operator,"<p>I am using <code>angular</code> V12 with <code>jest</code> for unit testing. Across the application I am using <code>?</code> operator to avoid null exception. Though the code works fine but jest always shows <code>?</code> (yellow highlight) as <code>branch not covered</code>. Please guide me how to increase the branch coverage while using <code>?</code>. My code as below:</p>
<pre><code>notCovered() {
        if(this.form.get('anything.something')?.value !== '') {
            // do something
        }
    }
</code></pre>
<p>and the coverage as below:</p>
<p><a href=""https://i.stack.imgur.com/2IRQo.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/2IRQo.png"" alt=""enter image description here"" /></a>
<a href=""https://i.stack.imgur.com/7R8wL.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7R8wL.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73878173/jest-branch-not-getting-covered-with-operator,"['angular', 'unit-testing', 'ts-jest', 'angular-test']",280,False,0,0
Should invalid cases be in one test?,"<p>I recently got introduced to unit testing and I have been doing some exercises. My question is regarding this image:</p>
<p><a href=""https://i.stack.imgur.com/QTb3b.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/QTb3b.png"" alt=""Picture in question"" /></a></p>
<p>Should I write two individual tests to check if both the exceptions are being thrown or is it ok to bundle them in one test? What is the right way?</p>
",https://stackoverflow.com/questions/71578399/should-invalid-cases-be-in-one-test,"['c#', 'unit-testing', 'nunit']",14,False,0,0
How to unit test a function that creates a connection object assuming there will not be internet access?,"<p>I have a python function that creates a Client object from the aiosnow module, which is an API wrapper for ServiceNow like this:</p>
<pre><code>from aiosnow import Client


def create_snow_client(url: str, user_name: str, pwd: str) -&gt; Client:
    &quot;&quot;&quot;Creates ServiceNow client object for interacting with the API.&quot;&quot;&quot;

    client = Client(
        url,
        basic_auth=(user_name, pwd),
    )

    return client
</code></pre>
<p>Assuming I will not have internet connection during unit testing, how or what part am I supposed to make the unit test for, which part am I supposed to mock?</p>
",https://stackoverflow.com/questions/74873916/how-to-unit-test-a-function-that-creates-a-connection-object-assuming-there-will,"['python', 'unit-testing']",48,True,1,1
Jest testing with react-flow-renderer,"<p>How can I find &amp; test a node from <code>react-flow-renderer</code>?</p>
<p>For example: I would like to test the <code>OnElementClick</code> provided by <code>react-flow-renderer</code>, but i don't know how to locate the node.
The official documentation for unit testing with react-flow-renderer does not exist, unfortunately.</p>
<p>Is there a way to unit test methods like <code>OnElementClick</code>, <code>OnConnect</code> or <code>OnElementsRemove</code>?</p>
",https://stackoverflow.com/questions/70849539/jest-testing-with-react-flow-renderer,"['javascript', 'reactjs', 'unit-testing', 'testing', 'jestjs']",487,False,1,0
Getting UnsatisfiedDependencyException Exception in spring,"<p>I am currently learning how to do unit testing in spring, I am getting the following error while running the test although I checked everything is fine every <strong>@Component</strong> is being scanned, I think I am getting this error because of <strong>@DataJpaTest</strong> can someone help me with it? thanks.</p>
<p><strong>Error :</strong></p>
<pre><code>Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-07-16 12:46:11.516 ERROR 3492 --- [           main] o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceScriptDatabaseInitializer' defined in class path resource [org/springframework/boot/autoconfigure/sql/init/DataSourceInitializationConfiguration.class]: Unsatisfied dependency expressed through method 'dataSourceScriptDatabaseInitializer' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Failed to replace DataSource with an embedded database for tests. If you want an embedded database please put a supported one on the classpath or tune the replace attribute of @AutoConfigureTestDatabase.
</code></pre>
<p><strong>Test Class</strong></p>
<pre><code>package com.example.SpringBootBasics.repository;

import com.example.SpringBootBasics.entity.Department;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;

import static org.junit.jupiter.api.Assertions.*;

@DataJpaTest
class DepartmentRepositoryTest {

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private TestEntityManager entityManager;

    @BeforeEach
    void setUp() {
        Department department =
                Department.builder()
                        .departmentName(&quot;ME&quot;)
                        .departmentAddress(&quot;Bangalore&quot;)
                        .departmentCode(&quot;ME-07&quot;)
                        .departmentId(1L)
                        .build();

        entityManager.persist(department);
    }

    @Test
    public void whenFindById_thenReturnDepartment(){
        Department department = departmentRepository.findById(1L).get();

        assertEquals(department.getDepartmentName(), &quot;ME&quot;);

    }
}
</code></pre>
",https://stackoverflow.com/questions/73002506/getting-unsatisfieddependencyexception-exception-in-spring,"['java', 'spring', 'spring-boot', 'jpa', 'spring-data-jpa']",315,True,1,1
C++/doctest throws compiler warning when using namespaces,"<p>I am using the C++ <a href=""https://github.com/doctest/doctest"" rel=""nofollow noreferrer"">doctest</a> framework for unit testing and stumbled upon an issue.
Whenever I try using the <code>CHECK_EQ()</code> macro for objects not in the general namespace I get compiler error messages.</p>
<p>This compiles fine (<a href=""https://godbolt.org/z/G55Y9914Y"" rel=""nofollow noreferrer"">godbolt</a>)</p>
<pre><code>#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN

#include &lt;doctest.h&gt;

struct Foo {
  int i;
};

bool operator==(const Foo&amp; lhs, const Foo&amp; rhs) { return lhs.i == rhs.i; }

TEST_CASE(&quot;Foo&quot;) {
  const auto f0 = Foo{};
  const auto f1 = Foo{};
  CHECK(f0 == f1);
  CHECK_EQ(f0, f1);
}
</code></pre>
<p>But moving the struct inside a namespace breaks the compilation (<a href=""https://godbolt.org/z/h1sPorYnz"" rel=""nofollow noreferrer"">godbolt</a>)</p>
<pre><code>#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN

#include &lt;doctest.h&gt;

namespace internal {
struct Bar {
  int i;
};
}  // namespace internal

bool operator==(const internal::Bar&amp; lhs, const internal::Bar&amp; rhs) {
  return lhs.i == rhs.i;
}

TEST_CASE(&quot;internal::Bar&quot;) {
  const auto b0 = internal::Bar{};
  const auto b1 = internal::Bar{};
  CHECK(b0 == b1);
  CHECK_EQ(b0, b1); // breaks code
}
</code></pre>
<p>The lengthy error messages:</p>
<pre><code>In file included from &lt;source&gt;:3:
/opt/compiler-explorer/libs/doctest/trunk/doctest/doctest.h: In instantiation of 'bool doctest::detail::eq(const L&amp;, const R&amp;) [with L = internal::Bar; R = internal::Bar]':
/opt/compiler-explorer/libs/doctest/trunk/doctest/doctest.h:1485:5:   required from 'bool doctest::detail::RelationalComparator&lt;0, L, R&gt;::operator()(const L&amp;, const R&amp;) const [with L = internal::Bar; R = internal::Bar]'
/opt/compiler-explorer/libs/doctest/trunk/doctest/doctest.h:1502:65:   required from 'bool doctest::detail::ResultBuilder::binary_assert(const L&amp;, const R&amp;) [with int comparison = 0; L = internal::Bar; R = internal::Bar]'
&lt;source&gt;:19:3:   required from here
/opt/compiler-explorer/libs/doctest/trunk/doctest/doctest.h:1292:5: error: no match for 'operator==' (operand types are 'const internal::Bar' and 'const internal::Bar')
 1292 |     DOCTEST_RELATIONAL_OP(eq, ==)
      |     ^
In file included from &lt;source&gt;:3:
/opt/compiler-explorer/libs/doctest/trunk/doctest/doctest.h:3583:6: note: candidate: 'bool doctest::operator==(const doctest::String&amp;, const doctest::String&amp;)'
 3583 | bool operator==(const String&amp; lhs, const String&amp; rhs) { return lhs.compare(rhs) == 0; }
      |      ^~~~~~~~
/opt/compiler-explorer/libs/doctest/trunk/doctest/doctest.h:3583:31: note:   no known conversion for argument 1 from 'const internal::Bar' to 'const doctest::String&amp;'
 3583 | bool operator==(const String&amp; lhs, const String&amp; rhs) { return lhs.compare(rhs) == 0; }
      |                 ~~~~~~~~~~~~~~^~~
/opt/compiler-explorer/libs/doctest/trunk/doctest/doctest.h:3765:6: note: candidate: 'bool doctest::operator==(double, const doctest::Approx&amp;)'
 3765 | bool operator==(double lhs, const Approx&amp; rhs) {
      |      ^~~~~~~~
/opt/compiler-explorer/libs/doctest/trunk/doctest/doctest.h:3765:24: note:   no known conversion for argument 1 from 'const internal::Bar' to 'double'
 3765 | bool operator==(double lhs, const Approx&amp; rhs) {
      |                 ~~~~~~~^~~
/opt/compiler-explorer/libs/doctest/trunk/doctest/doctest.h:3770:6: note: candidate: 'bool doctest::operator==(const doctest::Approx&amp;, double)'
 3770 | bool operator==(const Approx&amp; lhs, double rhs) { return operator==(rhs, lhs); }
      |      ^~~~~~~~
/opt/compiler-explorer/libs/doctest/trunk/doctest/doctest.h:3770:31: note:   no known conversion for argument 1 from 'const internal::Bar' to 'const doctest::Approx&amp;'
 3770 | bool operator==(const Approx&amp; lhs, double rhs) { return operator==(rhs, lhs); }
</code></pre>
",https://stackoverflow.com/questions/72076582/c-doctest-throws-compiler-warning-when-using-namespaces,"['c++', 'unit-testing']",103,False,1,1
React - Jest testing - TypeError: refetch is not a function,"<p>I'm using a <code>useFocusEffect()</code> hook in my component, which uses <code>refetch</code> from <code>react-query</code>. Code is working fine in the app. Issue I'm facing is with unit testing. I'm using <code>Jest</code> and getting an error that <code>TypeError: refetch is not a function</code>.</p>
<p>I've defined a mock function <code>const refetchFunc = jest.fn();</code> and have provided it to <code>refetch</code> as a <code>mockReturnValue</code>, but still the error persist.</p>
<h2>App.js:</h2>
<pre><code>const { data, refetch } = useStudents(
  student?.id
);

useFocusEffect(
  React.useCallback(() =&gt; {
    refetch();
  }, [refetch])
);
</code></pre>
<h2>Jest Test:</h2>
<pre><code>import { Home } from './Home';

jest.mock('hooks/Auth/useLoadAuthStudentsData', () =&gt; ({
  useLoadAuthStudentData: jest.fn()
}));

jest.mock('hooks/Student/useStudents', () =&gt; ({
  useStudents: jest.fn()
}));

jest.mock('@react-navigation/core', () =&gt; {
  return {
    ...jest.requireActual('@react-navigation/core'),
    useNavigation: jest.fn(() =&gt; ({}))
  };
});

const useLoadAuthStudentsData = userHook as ReturnType&lt;typeof jest.fn&gt;;
const useStudents = tasksHook as ReturnType&lt;typeof jest.fn&gt;;

const navContext = {
  isFocused: () =&gt; true,
  addListener: jest.fn(() =&gt; jest.fn())
};

const mockParams = {
  params: {
    studentId: 'studentId'
  }
};
  
  describe('Home', () =&gt; {
  beforeEach(() =&gt; {
    const refetchFunc = jest.fn();
    useStudents.mockReturnValue({
      data: Student.deserializeAsList(studentsStub),
      isLoading: false,
      isSuccess: true,
      isError: false,
      refetch:refetchFunc
    });
    useLoadAuthStudentData.mockReturnValue({ data: studentStub });
  });

  const component = (
    &lt;NavigationContext.Provider value={navContext}&gt;
    &lt;Home route={mockParams} navigation={{ goBack: jest.fn() }} /&gt;
    &lt;/NavigationContext.Provider&gt;
  );

  it('should render app without error', () =&gt; {
    expect(render(component)).toBeTruthy();
  });
</code></pre>
<h2>Error:</h2>
<pre><code>● Home › should render screen without error

    TypeError: refetch is not a function

      54 |   useFocusEffect(
      55 |     React.useCallback(() =&gt; {
    &gt; 56 |       refetch();
         |       ^
      57 |     }, [refetch])
      58 |   );
      59 |
</code></pre>
",https://stackoverflow.com/questions/73719411/react-jest-testing-typeerror-refetch-is-not-a-function,"['reactjs', 'jestjs']",640,False,0,2
How to get started with C++ unit tests,"<p>I am just starting with c++ unit testing. I want to create simple tests (without using any framework) using assert commands. How can I start with that?</p>
<p>Should I make different functions for tests and call them in the main in a single file or should I make separate file for each test?</p>
",https://stackoverflow.com/questions/72587590/how-to-get-started-with-c-unit-tests,"['c++', 'unit-testing', 'testing']",877,True,-1,1
How I can create mocked views for my database that app has no migration scripts for it?,"<p>I have the following architecture of my application:</p>
<p><a href=""https://i.stack.imgur.com/8TYWV.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/8TYWV.png"" alt=""2 Applications named App1 and App2 app1 connects with 2 databases whilst appi2 contains with one. App1 has migration scripts for the one of the databases whilst app2 has fot the another."" /></a></p>
<p>As you can see App1 is able to migrate Db1 whilst App2 is able to migrate Db2. App1 accesses only the views <code>my_view1</code> and <code>my_view2</code> from Db2.</p>
<p>Upon unit testing at App1 how I can create &quot;fake&quot; views with mock data that represent the actual views <code>my_view1</code> and <code>my_view2</code>.</p>
",https://stackoverflow.com/questions/74561063/how-i-can-create-mocked-views-for-my-database-that-app-has-no-migration-scripts,"['postgresql', 'unit-testing']",12,False,0,1
how to test @ConfigProperty variable of a class,"<p>Kindly let me know how we can test below piece of code in junit.
ConfigProperty is reading the values from application.property file. now i have to write an unit test case how i can writ kindly help me.</p>
<pre><code>@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = &quot;type&quot;)
@JsonTypeName(&quot;ProcessMessageDedup&quot;)
public class ProcessMessageDedup extends ProcessMessage {
    @ConfigProperty(name = &quot;dedupAppName&quot;, defaultValue = &quot;dedup&quot;)
    public String appName;
    @ConfigProperty(name = &quot;dedupProcessURL&quot;)
    public String processURL;
    @ConfigProperty(name = &quot;callbackURL&quot;)
    public String callbackURL;
    @ConfigProperty(name = &quot;dedupCallbackEndpoint&quot;)
    public String callbackEndpoint;
    @ConfigProperty(name = &quot;callbackUser&quot;)
    public String callbackUser;
    @ConfigProperty(name = &quot;callbackPass&quot;)
    public String callbackPass;

    public ProcessMessageDedup() {
        setProperties();
    }

    private void setProperties() {
        appName = ConfigProvider.getConfig().getValue(&quot;dedupAppName&quot;, String.class);
        processURL = ConfigProvider.getConfig().getValue(&quot;dedupProcessURL&quot;, String.class);
        callbackURL = ConfigProvider.getConfig().getValue(&quot;callbackURL&quot;, String.class);
        callbackEndpoint = ConfigProvider.getConfig().getValue(&quot;dedupCallbackEndpoint&quot;, String.class);
        callbackUser = ConfigProvider.getConfig().getValue(&quot;callbackUser&quot;, String.class);
        callbackPass = ConfigProvider.getConfig().getValue(&quot;callbackPass&quot;, String.class);
    }

    public void process() throws Exception {
        try {
            logger.info(&quot;Processing &quot; + appName + &quot; tid: &quot; + tid);
            logger.info(&quot;Processing &quot; + appName + &quot; queryparams: &quot; + queryParams.toString());
            setProperties();
            new CallbackUtils().callProcess(this.getData(), this.processURL, tid, fileId, &quot;&quot;, queryParams, appName,
                    callbackURL, callbackEndpoint, callbackUser, callbackPass);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        } finally {
            this.deleteFile();
        }
    }
  
    @Override
    public void callback() {
        // TODO Auto-generated method stub

    }
}
</code></pre>
<p>please let me know how we can write a unit testing of this class.</p>
",https://stackoverflow.com/questions/72268900/how-to-test-configproperty-variable-of-a-class,"['java', 'junit', 'mockito', 'quarkus', 'quarkus-rest-client']",1645,False,0,2
Better way to test if a job is dispatched in Laravel,"<p>I found 2 ways of testing whether a job is dispatched or not while doing phpUnit based unit testing in Laravel -</p>
<p>1.
<code>$this-&gt;expectsJobs(JobClassName::class);</code></p>
<p>2.</p>
<pre><code>Bus::fake();
Bus::assertDispatched(JobClassName::class);
</code></pre>
<p>After scrutinizing Laravel docs, I am not able to figure out which one of the above is a better approach and what is the functional difference between these two approaches.</p>
",https://stackoverflow.com/questions/74212317/better-way-to-test-if-a-job-is-dispatched-in-laravel,"['laravel', 'testing', 'phpunit', 'laravel-9', 'laravel-jobs']",1068,True,0,1
What is the correct syntax to Verify a mock logger call in F#?,"<p>I'm unit testing an F# function that calls <code>ILogger.LogInformation</code>. I'm attempting to verify that the function made the call as expected. Here is the verify statement I have so far:</p>
<pre class=""lang-ml prettyprint-override""><code>let mockLogger = Mock&lt;ILogger&lt;MyFunction&gt;&gt;()

// call function that uses ILogger.LogInformation.

mockLogger.Verify(fun x -&gt; x.Log(
    LogLevel.Information,
    It.IsAny&lt;EventId&gt;(),
    It.IsAny(),
    It.IsAny&lt;Exception&gt;(),
    It.IsAny&lt;Func&lt;It.IsAnyType, Exception, string&gt;&gt;()), Times.Once)
</code></pre>
<p>When I try this I get the following error:</p>
<pre><code>System.ArgumentException: Expression of type 'System.Void' cannot be used for constructor parameter of type 'Microsoft.FSharp.Core.Unit' (Parameter 'a...

System.ArgumentException
Expression of type 'System.Void' cannot be used for constructor parameter of type 'Microsoft.FSharp.Core.Unit' (Parameter 'arguments[0]')
   at System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, String methodParamName, String argumentParamName, Int32 index)
   at System.Dynamic.Utils.ExpressionUtils.ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ReadOnlyCollection`1&amp; arguments, String methodParamName)
   at System.Linq.Expressions.Expression.New(ConstructorInfo constructor, IEnumerable`1 arguments)
   at Microsoft.FSharp.Linq.RuntimeHelpers.LeafExpressionConverter.ConvExprToLinqInContext(ConvEnv env, FSharpExpr inp) in D:\a\_work\1\s\src\fsharp\FSharp.Core\Linq.fs:line 616
   at Microsoft.FSharp.Linq.RuntimeHelpers.LeafExpressionConverter.ConvExprToLinqInContext(ConvEnv env, FSharpExpr inp) in D:\a\_work\1\s\src\fsharp\FSharp.Core\Linq.fs:line 599
   at Microsoft.FSharp.Linq.RuntimeHelpers.LeafExpressionConverter.QuotationToLambdaExpression[T](FSharpExpr`1 e) in D:\a\_work\1\s\src\fsharp\FSharp.Core\Linq.fs:line 698
</code></pre>
<p>The exception is thrown when it calls the Verify method. How can I change this to get past this error?</p>
",https://stackoverflow.com/questions/74424640/what-is-the-correct-syntax-to-verify-a-mock-logger-call-in-f,"['f#', 'moq']",69,True,3,1
Update text field in vue test utils (jest) not working,"<p>Hi i am new in jest and unit testing. i want to ask how to set value text input using vue test utils.</p>
<p>shortly I have custom component for text input, its my code</p>
<pre><code>&lt;input
    v-model=&quot;local_value&quot;
    @keyup.enter=&quot;submitToParent&quot;
    :class=&quot;input_class&quot;
    :id=&quot;id&quot;
    :disabled=&quot;is_disabled&quot;
    :maxlength=&quot;max_length&quot;
    :placeholder=&quot;placeholder&quot;
    :autocomplete=&quot;(is_autocomplete) ? 'on' : 'off'&quot;
    :name=&quot;id&quot;
    :ref=&quot;id&quot;
  /&gt;
</code></pre>
<p>and it's my test</p>
<pre><code>it(&quot;type something on field&quot;, async () =&gt; {
        const wrapper = shallowMount(TextInput, {
            propsData: {
                id: &quot;my_input&quot;,
            }
        })

        // find component (its work properly) and I want to try inserting some text
        const input = wrapper.findComponent({ref: &quot;my_input&quot;})
        input.element.value = &quot;sample text&quot;
        input.setValue(&quot;sample text&quot;)

        // the value still empty string (&quot;&quot;), idk what happens with my code
        console.log(wrapper.vm.local_value)
        expect(wrapper.vm.local_value).toBe(&quot;sample text&quot;)


</code></pre>
<p>please tell me if you known solution for this problem, thank you for your time</p>
",https://stackoverflow.com/questions/71319755/update-text-field-in-vue-test-utils-jest-not-working,"['javascript', 'vue.js', 'unit-testing', 'jestjs', 'vue-test-utils']",1683,True,0,2
Unit testing ag-grid OnGridReady,"<p>I am trying to write unit testing for OnGridReady method in ag-grid. But I am stucked on how to pass params : GridReadyEvent to OnGridReady method. I tried mocking it but as it does not have data, My method is failing with some assigning undefined error. Need help in covering OnGridReady method.</p>
",https://stackoverflow.com/questions/74059948/unit-testing-ag-grid-ongridready,"['angular', 'unit-testing', 'jasmine', 'ag-grid']",51,False,0,0
Unit Testing with Viper - Swift &amp; iOS,"<p>Unit testing with Viper - Swift</p>
<p>Hello,</p>
<p>I have an Login module(LoginViewController,LoginPresenter,LoginInteractor,LoginRouter)
that I wrote with Viper.
I want to write a unit test for this module but I'm not sure exactly where to start.
Can I get suggestions from people who write unit tests with Viper?
Thank you,</p>
",https://stackoverflow.com/questions/74276540/unit-testing-with-viper-swift-ios,"['ios', 'swift', 'unit-testing']",107,True,-2,2
Unmount wrapper automatically,"<p>I am using Vitest along with Testing Library - Vue for unit testing my frontend code. I have been following this pattern:</p>
<pre><code>describe(&quot;LoadingSpinner&quot;, () =&gt; {
  const defaultWidth = &quot;4rem&quot;;
  const defaultHeight = &quot;4rem&quot;;

  it(&quot;should have a default height of 4rem when no props are passed&quot;, async () =&gt; {
    const wrapper = render(LoadingSpinner);

    const component = await screen.findByRole(&quot;status&quot;);

    expect(component.style.height).toBe(defaultHeight);

    wrapper.unmount();
  });

  //etc...
}
</code></pre>
<p>I am wondering if there is a better way to automatically unmount the wrapper, rather than manually calling <em>wrapper.unmount()</em>? If I don't unmount the wrapper, each test creates a new LoadingSpinner and thus <em>screen.findByRole()</em> fails.</p>
",https://stackoverflow.com/questions/73828916/unmount-wrapper-automatically,"['vue.js', 'unit-testing', 'vitest']",556,True,3,1
RuntimeError: Model doesn&#39;t declare an explicit app_label and isn&#39;t in an application in INSTALLED_APPS,"<p>I am writing an app in Django and I'm trying to do some unit testing
but I can't seem to find why the test is failing
that is the test page:</p>
<pre><code>import re
from django.test import TestCase
from django.urls import reverse
from . import models



class BasicTests(TestCase):

    def test_firstname(self):
        print('test11')
        acc = models.Accounts()
        acc.first_name = 'Moran'
        self.assertTrue(len(acc.id) &lt;= 9, 'Check name is less than 50 digits long')
        self.assertFalse(len(acc.id) &gt; 50, 'Check name is less than 50 digits long')
</code></pre>
<p>the error i get is :</p>
<blockquote>
<p>RuntimeError: Model class DoggieSitter.accounts.models.Accounts
doesn't declare an explicit app_label and isn't in an application in
INSTALLED_APPS</p>
</blockquote>
<p>thats my installed app:</p>
<pre><code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'accounts'
]
</code></pre>
",https://stackoverflow.com/questions/71987652/runtimeerror-model-doesnt-declare-an-explicit-app-label-and-isnt-in-an-applic,"['django', 'django-models', 'django-testing', 'django-settings', 'django-tests']",4663,False,3,1
"Setting up Vue 3, Typescript for unit testing","<p>I created a TodoApp in vue-typescript but I get an error as shown below when doing unit testing. Any idea why I get the error?  Here's my <a href=""https://github.com/isogunro/vuets-to-do-app"" rel=""nofollow noreferrer"">repo</a> to see my setup.</p>
<p><a href=""https://i.stack.imgur.com/kducU.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/kducU.png"" alt=""enter image description here"" /></a></p>
<p>I did go through the documentation but unable to rid the error.  <strong>vue-jest</strong> is in the transform option of my package.</p>
",https://stackoverflow.com/questions/73955041/setting-up-vue-3-typescript-for-unit-testing,"['vue.js', 'unit-testing', 'vuejs3']",53,False,1,1
How do I stub default void method of Mapstruct interface for Unit testing a class that is calling that default method?,"<p>I am unit testing a class in Java 8 that is calling a default method of a mapstruct interface and that method returns void. I am not able to stub the method call using Mockito.doNothing()...When(object).method(). The execution enters the actual method (in mapstruct interface) Pls provide your inputs to solve this problem.</p>
",https://stackoverflow.com/questions/74828977/how-do-i-stub-default-void-method-of-mapstruct-interface-for-unit-testing-a-clas,"['junit', 'java-8', 'spring-test', 'mapstruct']",82,False,1,0
Are unit tests only manually executed or auto executed when building out a project?,"<p>I have a few questions when it comes to unit testing using Jest in React Native.</p>
<ol>
<li><p>I run my tests now with <code>npm test</code>, is this the only way to run it or are the tests also being executed when building out the project? If so, can I disable auto testing?</p>
</li>
<li><p>If a test fails, will that prevent the app from building or executing?</p>
</li>
<li><p>Is there any difference in behaviour if a test fails or succeeds on iOS and Android?</p>
</li>
</ol>
<p><strong>Example</strong></p>
<p>Below code just tests if AsyncStorage works as expected.  If the following test fails - sure AsyncStorage will not work if I am using it within the app, but will it prevent the app from being used entirely?</p>
<pre><code>beforeEach(() =&gt; {
 AsyncStorage.clear();
});

it('Test - Read AsyncStorage', async () =&gt; {
  await AsyncStorage.setItem('username', 'testUser')
  let usernameValue = await AsyncStorage.getItem('username')
  expect(usernameValue).toBe('testUser')
});
</code></pre>
<p>I am happy to get any further tips - I just can't find specific answers to the above so thanks in advance, and I haven't really been doing much unit testing so quite new to this.</p>
",https://stackoverflow.com/questions/72257421/are-unit-tests-only-manually-executed-or-auto-executed-when-building-out-a-proje,"['react-native', 'testing', 'mobile', 'jestjs']",70,True,0,1
How to unit test a method which calls a void method?,"<p>I am stuck with a basic issue for unit testing a scenario and will appreciate help.</p>
<p>I have a class <code>MyService</code> which calls <code>MyRemovalService</code> to set a flag to true in the DB.</p>
<pre><code>
@Slf4j
@Service
@RequiredArgsConstructor
public class MyService {

    private final MyRemovalService myRemovalService;
    private final MyRepository myRepository;

    public void setFlag() {
        final List&lt;String&gt; records = myRepository.getData(ENUM_1, ENUM_2, ENUM_3);
        records.forEach(MyRemovalService::removeData);
    }

}


</code></pre>
<p>MyTest:</p>
<pre><code>@ExtendWith(MockitoExtension.class)
class MyServiceTest {

    @Mock
    private MyRemovalService myRemovalService;

    @Mock
    private MyRepository myRepository;

    @InjectMocks
    private MyService myService;

    @Test
    void testMyUseCase() {
        when(myRepository.getData(any(), any(), any())).thenReturn(List.of(&quot;Test1&quot;, &quot;Test2&quot;));
        myService.setFlag();
    }

}
</code></pre>
<p>I have been asked to test and check if <code>(MyRemovalService::removeData)</code> is being called with relevant data.</p>
<p>How can I test this since the return type is void ?</p>
",https://stackoverflow.com/questions/71768036/how-to-unit-test-a-method-which-calls-a-void-method,"['java', 'unit-testing', 'junit']",3374,True,2,2
Read images from simulator and get array of images metadata android unit tests,"<p>I am working on unit testing in android whereby I am reading images from a folder in an emulator, fetching metadata of the array of images.</p>
<p>I have a few challenges:</p>
<ol>
<li>I cant locate the path of the images in the emulator.</li>
<li>Whats the best way to read these images? Any resource for that?</li>
</ol>
",https://stackoverflow.com/questions/73966482/read-images-from-simulator-and-get-array-of-images-metadata-android-unit-tests,"['unit-testing', 'kotlin']",39,False,0,0
Want to mock a method which is calling another class method,"<p>I am new to mockito using it for unit testing. I need some help to understand mock a method.I have a method - method1() of class A  which needs to be tested .Here i want to verify that execute() is executed (Interaction testing).Below is the method.</p>
<pre><code>class A{
void method1(){

  B b = new B(org_id);

  b.execute();


 }
}
</code></pre>
<hr />
<pre><code> Class B {
    B(String orgId){
    this.orgId = org_id;
    }
    
    void execute(){
     String x = Dependency.m1();
    
     String y = Dependency.m2();
    
     }
    
     static class Dependency{
    
     public String m1(){

       return K.someText();

      }
    
     public String m2(){

      return K.someText();

     }
    }
   }
</code></pre>
<p>Could anyone help me how to achieve it?TIA</p>
",https://stackoverflow.com/questions/73262815/want-to-mock-a-method-which-is-calling-another-class-method,"['java', 'unit-testing', 'mockito']",974,False,0,3
How to mock private native methods in Junit/mockito/powermock,"<p>I am new to Junit and trying to write unit testing for a class which has native methods.</p>
<pre><code>public class TokenProvider {
    static {
        System.loadLibrary(&quot;mylib&quot;);
    }

    public Token list(String key) {
        TokenProvider tokenprovider = new TokenProvider();
        Token token = tokenprovider.listTokens(key);
        return token;
    }
    private native Token listTokens(String key); 
}
</code></pre>
<p><strong>private native Token listTokens(String key);</strong> This method logic is there in mylib library which is written in CPP. I tried like this</p>
<pre><code>public class TestTokenProvider {

    @Test
    public void testList() {
        TokenProvider tokenProvider = new TokenProvider();
        Token actual = tokenProvider.list(&quot;&quot;); // key is passing as empty as it is not requested for this usecase
        Token expected = // need to get list of tokens eg: [{name: &quot;token1&quot;, id: &quot;123&quot;}, {name: &quot;token2&quot;, id: &quot;1234&quot;}]
        assertEquals(actual, expected);
    }
}
</code></pre>
<p>I am getting <strong>&quot;java.lang.unsatisifiedLinkError&quot;</strong> Error. Also help me to improve code coverage for TokenProvider.</p>
",https://stackoverflow.com/questions/73625756/how-to-mock-private-native-methods-in-junit-mockito-powermock,"['java', 'junit', 'mockito', 'java-native-interface', 'powermock']",172,False,0,0
Unit testing Spring Boot Rest Controller with JPA Repositories,"<p>I have ,probably a basic question,related to unit testing a spring boot application that uses RestControllers,JPA repositories.Oracle is used in the backend.Now to unit test the JPA repositories using junit,mockito and probably DataJPA,do the tables that are present in the backend,need to be recreated in the H2 in-memory db?</p>
",https://stackoverflow.com/questions/70986522/unit-testing-spring-boot-rest-controller-with-jpa-repositories,"['java', 'spring-boot', 'spring-data-jpa', 'mockito', 'junit5']",488,False,0,0
Mac Command Line Tool Swift Unit Tests,"<p>I want to unit test a command line tool.
I go through the following progress</p>
<p>Create a new project using the macOS &gt; Command Line Tool template. Call it &quot;MyProject&quot;</p>
<pre class=""lang-swift prettyprint-override""><code>import Foundation

class MyCode {
    func hello() {
        print(&quot;hello&quot;)
    }
}

let code = MyCode()
code.hello()
</code></pre>
<p>Choose File &gt; New &gt; Target.
Select the macOS Unit Testing Bundle template. Call it &quot;MyTests&quot;</p>
<pre class=""lang-swift prettyprint-override""><code>import XCTest
@testable import MyProject

class MyTests: XCTestCase {

    func testCode() {
        let sol = MyCode()
        sol.hello()
    }

}
</code></pre>
<p>Switch to test target.</p>
<p>Build failed.</p>
<p>How can I test this?</p>
",https://stackoverflow.com/questions/73813148/mac-command-line-tool-swift-unit-tests,"['swift', 'xcode']",104,False,0,0
Unit Testing a Controller method returns null,"<p>I'm trying to learn Unit testing in .NET 6 by testing a controller function <code>GetProduct</code>. The problem is I get null returned in the variable <code>var product = await _productController.GetProduct(productId);</code>. As you can see in the picture below, the <code>Result</code> is ok but the <code>Value</code>, where the <code>ServiceResponse&lt;Product&gt;</code> was suppose to be is null.</p>
<p><a href=""https://i.stack.imgur.com/QkrYB.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/QkrYB.png"" alt=""enter image description here"" /></a></p>
<p>Here is the controller function:</p>
<pre><code>public class ProductController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet(&quot;{productId}&quot;)]
    public async Task&lt;ActionResult&lt;ServiceResponse&lt;Product&gt;&gt;&gt; GetProduct(int productId)
    {
        var result = await _productService.GetProductAsync(productId);
        return Ok(result);
    }
}
</code></pre>
<p>Here is the Test:</p>
<pre><code>public class ProductControllerTest
{
    private readonly ProductController _productController;
    private readonly Mock&lt;IProductService&gt; _productService = new Mock&lt;IProductService&gt;();

    public ProductControllerTest()
    {
        _productController = new ProductController(_productService.Object);
    }    

    [Test]
    public async Task GetProducts_ReturnsProduct_IfProductExists()
    {
        //Arange
        var productId = 1;
        var prodData = new Product
        {
            Id = productId,
            Title = &quot;null&quot;            
        };
        var prductResponse = new ServiceResponse&lt;Product&gt;
        {
            Data = prodData,
            Success = true ,
            Message = &quot;&quot;
        };

        _productService.Setup(x =&gt; x.GetProductAsync(productId)).ReturnsAsync(prductResponse);

        //Act
        var product = await _productController.GetProduct(productId);

        //Assert
        Assert.That(product?.Value?.Data?.Id, Is.EqualTo(productId));
    }

}
</code></pre>
",https://stackoverflow.com/questions/73139320/unit-testing-a-controller-method-returns-null,"['c#', '.net', 'unit-testing']",383,True,0,2
Does SECTION run at the same time in Unit testing C++(catch2)?,"<p>I am new to C++ and I am learning Unit testing using catch2. I am writing a testcase like this</p>
<pre><code>TEST_CASE(&quot;Sandwich::AddTopping test&quot;, &quot;[AddTopping]&quot;) {
  // your tests for Sandwich::AddTopping here
  Sandwich newsandwich;

  SECTION(&quot;adding two cheese&quot;) {
    newsandwich.AddTopping(&quot;cheese&quot;);
    REQUIRE(newsandwich.AddTopping(&quot;cheese&quot;) == false);
  }

  SECTION(&quot;adding more than 5 toppings&quot;) {
    newsandwich.AddTopping(&quot;cheese&quot;);
    newsandwich.AddTopping(&quot;lettuce&quot;);
    newsandwich.AddTopping(&quot;tomato&quot;);
    newsandwich.AddTopping(&quot;onions&quot;);
    newsandwich.AddTopping(&quot;pickles&quot;);
    REQUIRE(newsandwich.AddTopping(&quot;cheese&quot;) == false);
  }

  SECTION(&quot;adding 2 other toppings&quot;) {
    newsandwich.AddTopping(&quot;lettuce&quot;);
    REQUIRE(newsandwich.AddTopping(&quot;lettuce&quot;));
  }

  SECTION(&quot;adding in range&quot;) { REQUIRE(newsandwich.AddTopping(&quot;lettuce&quot;)); }
}
</code></pre>
<p>However, my code only create one Sandwich object at the beginning but the output of this is the same as teh one when I create objects separately for each SECTION. Can someone tell me why? Thank you~</p>
",https://stackoverflow.com/questions/71003950/does-section-run-at-the-same-time-in-unit-testing-ccatch2,"['c++', 'unit-testing', 'catch2']",199,False,1,0
How can i create a unit test for a function that asks user for input,"<p>I'm new to unit testing. I'm working on an ATM program. I want to make a unit test for the deposit operation. I have checked online but i am not getting an answer to my problem. This is my first time of posting here. Thank you for the assistance in advance</p>
<p>This is my code below</p>
<pre><code>def deposit_operation(user):

    amount_to_deposit = int(input('ENTER AMOUNT YOU WANT TO DEPOSIT: ')
    # amount should be in multiples of 1,000
    if amount_to_deposit % 1000 != 0:
        print('AMOUNT YOU WANT TO DEPOSIT MUST BE IN MULTIPLES OF 1000 NAIRA NOTES')
        deposit_operation(user)
    else:
        user[4] = user[4] + amount_to_deposit
        print(f'*** YOUR NEW BALANCE IS: {user[4]} NAIRA ****')

        perform_another_operation(user)
</code></pre>
",https://stackoverflow.com/questions/73790120/how-can-i-create-a-unit-test-for-a-function-that-asks-user-for-input,"['python', 'function', 'unit-testing', 'user-input']",436,True,1,1
Use @jest-environment jsdom and @jest-environment node both in the same project [Jest-ReactJS],"<p>We are using &quot;Jest with React Testing Library&quot; for unit testing in our project. In the same project we have some cases those needs &quot;@jest-environment jsdom&quot; and some cases needs @jest-environment node. How can we switch this in a Test Case file.</p>
<p>We have below jest.config.js file:</p>
<pre><code> /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
    module.exports = {
      preset: 'ts-jest',
      testEnvironment: 'node'
    };
</code></pre>
<p>I have tried below approach, but it didn't work in my experience.</p>
<pre><code>/**
 * @jest-environment jsdom
 */

test('use jsdom in this test file', () =&gt; {
  const element = document.createElement('div');
  expect(element).not.toBeNull();
});

/**
 * @jest-environment node
 */

test('do not use jsdom in this test file', () =&gt; {
  console.log(window); // this will fail as node doesn't have a window object
});
</code></pre>
",https://stackoverflow.com/questions/73865763/use-jest-environment-jsdom-and-jest-environment-node-both-in-the-same-project,"['javascript', 'reactjs', 'jestjs', 'ts-jest']",516,False,4,0
How to mock the Mongoose model for find with populate,"<p>I am having the below Node JS with mongoose code. I have to mock this query to throw an error in my JEST unit testing. Can anyone help me with how to achieve it?</p>
<pre><code>return new Promise(async (resolve, reject) =&gt; {
        try {
            const data = await users
                .find(filter, porjectFields)
                .populate({
                    path: 'user.address',
                    populate: {
                        path: 'location'
                    }
                })
                .lean();
            resolve(data);
        } catch (err) {
            logger.error(
                `Error in user : ${err}`
            );
            reject(err);
        }
    });
</code></pre>
<p>I tried to mock like below, but i am getting error on lean function.</p>
<pre><code>users.find = jest.fn().mockImplementation(() =&gt; ({
                populate: jest.fn().mockReturnValue({ name: 'hello' }),
                lean: true
            }));
</code></pre>
<p><strong>Error:</strong></p>
<p><em>TypeError: users.find(...).populate(...).lean is not a function</em></p>
",https://stackoverflow.com/questions/71883043/how-to-mock-the-mongoose-model-for-find-with-populate,"['mongoose', 'jestjs']",397,True,1,1
How test eventChannel in redux-sagas?,"<p>I am new with unit testing and redux/sagas. I would like to know the proper way to test a eventChannel.</p>
<p>I created a project in react-native where I have an authentication flow with firebase. I would like to have some guidance of What is need to be tested and how addressed?</p>
<p>Here is my saga:</p>
<pre><code>export function createAuthListener() {
  return eventChannel(emit =&gt; {
    const listener = (user: any) =&gt; {
      emit({ user });
    };

    const suscribe = auth.authListener(listener);

    return suscribe;
  });
}

export function* handleAuthChange({ payload }: { payload: any }) {
  try {
    const { user } = payload;

    if (user) {
      console.log({ user }, user.email);
      const profile = {
        email: user.email,
        name: user.displayName,
        profileImg: user.photoURL
      };
      yield put(profileActions.setData(profile as unknown as ProfileType));
      yield call(navigatorDispatch, StackActions.replace('Home'));
      return;
    }

    yield put(profileActions.setData(null));
    yield call(navigatorDispatch, StackActions.replace('Auth'));
  } catch (error) {
    console.error(AUTH_TAG_LOG, 'Error::signIn', { error });
  }
}

export function* onAuthStateChange() {
  const chan = yield call(createAuthListener);
  try {
    while (true) {
      // take(END) will cause the saga to terminate by jumping to the finally block
      let payload = yield take(chan);
      yield call(handleAuthChange, { payload });
    }
  } catch (error) {
    console.log(AUTH_TAG_LOG, 'Error:onAuthStateChange', { error });
  } finally {
    console.log(AUTH_TAG_LOG, 'Finally onAuthStateChange');
  }
}

export default function* () {
  yield call(onAuthStateChange);
}
</code></pre>
",https://stackoverflow.com/questions/71486539/how-test-eventchannel-in-redux-sagas,"['reactjs', 'react-native', 'unit-testing', 'redux', 'redux-saga']",274,False,1,0
Javascript unit testing framework that doesn&#39;t work in strict mode,"<p>Is there a way to unit test code from not strict mode. Most of the testing frameworks, mocha, jest, etc are strict mode only. My code involves use of eval that needs non-strict mode scope that I cannot rewrite into strict mode compatible form. Any idea or do I need to write my own unit testing framework.</p>
",https://stackoverflow.com/questions/71093181/javascript-unit-testing-framework-that-doesnt-work-in-strict-mode,"['javascript', 'node.js', 'unit-testing']",73,True,1,1
Flutter unit testing firestore,"<p>I'm new to unit testing in general. I'm trying to test simple method from my DataRepository.</p>
<p>Following this link but seems deprecated: <a href=""https://utkarshkore.medium.com/writing-unit-tests-in-flutter-with-firebase-firestore-72f99be85737"" rel=""nofollow noreferrer"">https://utkarshkore.medium.com/writing-unit-tests-in-flutter-with-firebase-firestore-72f99be85737</a></p>
<pre><code>class DataRepository {
  final CollectionReference collection =
      FirebaseFirestore.instance.collection('notes');

  //Retour de models a la place de snapshots
  Stream&lt;QuerySnapshot&gt; getStream() {
    return collection.snapshots();
  }

  Stream&lt;QuerySnapshot&gt; getStreamDetail(String id) {
    return collection.doc(id).collection('tasks').snapshots();
  }

  Stream&lt;List&lt;Note&gt;&gt; noteStream() {
    final CollectionReference collection =
        FirebaseFirestore.instance.collection('notes');

    try {
      return collection.snapshots().map((notes) {
        final List&lt;Note&gt; notesFromFirestore = &lt;Note&gt;[];
        for (var doc in notes.docs) {
          notesFromFirestore.add(Note.fromSnapshot(doc));
        }
        return notesFromFirestore;
      });
    } catch (e) {
      rethrow;
    }
  }
</code></pre>
<p>So far this is what my test file look like:</p>
<pre><code>import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';

class MockFirestore extends Mock implements FirebaseFirestore {}
class MockCollectionReference extends Mock implements CollectionReference {}

void main() {
  MockFirestore instance = MockFirestore();
  MockCollectionReference mockCollectionReference = MockCollectionReference();

  test('should return data when the call to remote source is succesful.',
      () async {
    when(instance.collection('notes')).thenReturn(mockCollectionReference);
  });
}
</code></pre>
<p>First instance throw me this error</p>
<pre><code>The argument type 'MockCollectionReference' can't be assigned to the parameter type 'CollectionReference&lt;Map&lt;String, dynamic&gt;&gt;'
</code></pre>
<p>I would really appreciate the help for testing the method.</p>
<p>new edit:</p>
<pre><code>void main() {
  test('should return data when the call to remote source is succesful.',
      () async {
    final FakeFirebaseFirestore fakeFirebaseFirestore = FakeFirebaseFirestore();
    final DataRepository dataRepository = DataRepository();
    final CollectionReference mockCollectionReference =
        fakeFirebaseFirestore.collection(dataRepository.collection.path);

    final List&lt;Note&gt; mockNoteList = &lt;Note&gt;[];

    for (Note mockNote in mockNoteList) {
      await mockCollectionReference.add(mockNote.toJson());
    }

    final Stream&lt;List&lt;Note&gt;&gt; noteStreamFromRepository =
        dataRepository.noteStream();

    final List&lt;Note&gt; actualNoteList = await noteStreamFromRepository.first;
    final List&lt;Note&gt; expectedNoteList = mockNoteList;

    expect(actualNoteList, expectedNoteList);
  });
}
</code></pre>
",https://stackoverflow.com/questions/71370219/flutter-unit-testing-firestore,"['firebase', 'flutter', 'unit-testing', 'google-cloud-firestore', 'mockito']",2261,True,4,2
Is there a JUnit equivalent of Jest&#39;s expect.assertions(number)?,"<p>In JavaScript, the library Jest has a delightful semantic - <a href=""https://jestjs.io/docs/expect#expectassertionsnumber"" rel=""nofollow noreferrer""><code>expect.assertions(number)</code></a> which verifies that a certain number of assertions are called during a test, for example of <a href=""https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function"" rel=""nofollow noreferrer"">async</a> code:</p>
<pre><code>test('doAsync calls both callbacks', () =&gt; {
  expect.assertions(2);
  function callback1(data) {
    expect(data).toBeTruthy();
  }
  function callback2(data) {
    expect(data).toBeTruthy();
  }

  doAsync(callback1, callback2);
});
</code></pre>
<p>Is there a similar semantic available in JUnit or other Java unit testing libraries?</p>
<p>If so, please feel very welcome to give an example, such as <a href=""https://stackoverflow.com/questions/39588658/asynchronous-unit-testing-in-java-junit-a-very-simple-yet-unsuccessful-example"">using CompleteableFuture</a> or as appropriate.</p>
",https://stackoverflow.com/questions/74354703/is-there-a-junit-equivalent-of-jests-expect-assertionsnumber,"['java', 'unit-testing', 'asynchronous', 'junit']",47,False,0,0
How to run unit testing on my SwiftUi app for logging in?,"<p>I am trying to run a unit test on my SwiftUi project to see if the user can log in. But I'm getting the following error in my ViewModel when I try to run the function in my unit testing:</p>
<blockquote>
<p>No such module 'Firebase'.</p>
</blockquote>
<p>Here are my test files:</p>
<pre><code>import XCTest


final class LoginTests: XCTestCase {

    func testLogginIn(){
        let vm = AuthManage()
        
        let truevalue = vm.signIn(email: &quot;test@gmail.com&quot;, password: &quot;testtest&quot;)
        let test = true
        
        XCTAssertTrue(truevalue)
    }

}

</code></pre>
<p>And I can't import Firebase in my testing files.</p>
",https://stackoverflow.com/questions/74234915/how-to-run-unit-testing-on-my-swiftui-app-for-logging-in,"['ios', 'firebase', 'unit-testing', 'swiftui', 'emulation']",40,False,0,0
"Apollo Client GraphQL Unit Testing return Error: TypeError: (0 , _reactHooks.useQuery) is not a function","<p>I was trying to write unit test with react component from Apollo Client Unit Testing, but I got an error when mocking call to the GraphQL endpoint to some hook functions.</p>
<p>My unit test implement:</p>
<pre><code>import React from 'react';
import MockedProvider from '@apollo/react-testing';
import renderer from 'react-test-renderer';
import { GET_CHARACTER_DETAILS } from '../../containerHooks/useCharacterDetails';
import { UseCharacterDetails } from '../../containerHooks/useCharacterDetails';

const mocks = [
  {
    request: {
      query: GET_CHARACTER_DETAILS,
      variables: {
        id: 1,
      },
    },
    result: {
      data: {
        character: {
          id: '1',
          name: 'Rick Sanchez',
          status: 'Alive',
          gender: 'Male',
        },
      },
    },
  },
];

it('renders without error', () =&gt; {
  renderer.create(
    &lt;MockedProvider mocks={mocks} addTypename={false}&gt;
      &lt;UseCharacterDetails id='1' /&gt;
    &lt;/MockedProvider&gt;
  );
});
</code></pre>
<p>Here is my Test Component</p>
<pre><code>import gql from 'graphql-tag';
import { useQuery } from '@apollo/react-hooks';

export const GET_CHARACTER_DETAILS = gql`
  query CharacterDetails($id: ID!) {
    character(id: $id) {
      id
      name
      status
      species
      type
      gender
      origin {
        name
      }
      location {
        name
      }
      image
      episode {
        name
      }
      created
    }
  }
`;

export const UseCharacterDetails = ({ id }) =&gt; {
  const { loading, error, data } = useQuery(GET_CHARACTER_DETAILS, {
    variables: { id },
  });

  return {
    data,
    error,
    loading,
  };
};
</code></pre>
<p>When I run a test, it throws an error</p>
<blockquote>
<p>TypeError: (0 , _reactHooks.useQuery) is not a function</p>
</blockquote>
",https://stackoverflow.com/questions/71229691/apollo-client-graphql-unit-testing-return-error-typeerror-0-reacthooks-use,"['javascript', 'reactjs', 'unit-testing', 'graphql', 'apollo-client']",924,False,0,0
How to write a Unit testing for Azure Function app?,"<p>I have an azure function based on .Net core 3.1. It triggers when a file is uploaded into the Azure Blob Container, processes the CSV file and updates the database</p>
<p>Below is the code excerpt</p>
<p><strong>FileTrigger.cs</strong></p>
<pre><code>namespace aspnetcore_azurefun_blob
{
    [StorageAccount(&quot;AzureWebJobsStorage&quot;)]
    public class FileTrigger
    {
        #region Property
        private readonly IFileProcessor fileProcessor;
        #endregion

        #region Constructor
        public FileTrigger(IFileProcessor fileProcessor)
        {
            this.fileProcessor = fileProcessor;
        }
        #endregion

        [FunctionName(&quot;FileTrigger&quot;)]
        public void ProcessFilesFromSamplesContainer([BlobTrigger(&quot;samples-workitems/{name}&quot;)]Stream myBlob, string name, ILogger log, ExecutionContext context)
        {
            log.LogInformation(&quot;Function: ProcessFilesFromSamplesContainer is called&quot;);
            log.LogInformation($&quot;C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes&quot;);

            var result = fileProcessor.ProcessAsync(myBlob, name, log, context);

            log.LogInformation($&quot;Function Completed {result.Result} on {DateTime.Now.ToLongDateString()} @ {DateTime.Now.ToShortTimeString()}.\n.&quot;);
        }
    }
}
</code></pre>
<p><strong>FileProcessor.cs</strong></p>
<pre><code>namespace ClientCore.Processor
{
    public interface IFileProcessor
    {
        Task&lt;string&gt; ProcessAsync(Stream myBlob, string name, ILogger log, ExecutionContext context);
    }

    public class FileProcessor : IFileProcessor
    {
        #region Property
        private readonly IFileProcessingServiceFacade fileProcessingService;
        #endregion

        #region Constructor
        public FileProcessor(IFileProcessingServiceFacade fileProcessingService)
        {
            this.fileProcessingService = fileProcessingService;
        }
        #endregion

        #region Public Methods
        public async Task&lt;string&gt; ProcessAsync(Stream myBlob, string name, ILogger log, ExecutionContext context)
        {
            var processingResult = fileProcessingService.ProcessAsync(myBlob, name, log, context);

            return await Task.FromResult($&quot;{processingResult.Result}&quot;);
        }
        #endregion

    }
}
</code></pre>
<p><strong>FileProcessingService.cs</strong></p>
<pre><code>namespace BusinessService.Services
{
    public interface IFileProcessingServiceFacade
    {
        Task&lt;string&gt; ProcessAsync(Stream myBlob, string name, ILogger log, ExecutionContext context);
    }

    partial class FileProcessingServiceFacade : IFileProcessingServiceFacade
    {
        #region Public Methods
        public async Task&lt;string&gt; ProcessAsync(Stream myBlob, string name, ILogger log, ExecutionContext context)
        {
            // Get the Contents from the CSV File
            var csvData = GetCSVData(myBlob);

            AppDbContext.FileRecords.Add(new FileRecords
            {
                FileName = name,
                IsCompleted = DefaultValues.IsCompleted
            });
            AppDbContext.SaveChanges();

            log.LogInformation($&quot;Reading configuration from the configuration settings file: {Configurator.AzureSQLServerConfigurator.ConnnectionString}&quot;);
            log.LogInformation(&quot;Database is updated..!&quot;);

            return await Task.FromResult($&quot;success&quot;);
        }
        #endregion

    }

    partial class FileProcessingServiceFacade : ServiceBase&lt;FileProcessingServiceFacade&gt;
    {
        #region Constructor
        public FileProcessingServiceFacade(AppDbContext appDbContext, IOptions&lt;AppConfigurator&gt; configurator) 
            : base(appDbContext, configurator) { }
        #endregion

        #region Extract Data from CSV
        protected static List&lt;dynamic&gt; GetCSVData(Stream jobData)
        {
            try
            {
                #region CsvHelper Mapping and Conversion
                var csvHelperConfig = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    NewLine = Environment.NewLine,
                    PrepareHeaderForMatch = args =&gt; args.Header.ToUpper().Replace(&quot; &quot;, &quot;&quot;),
                    HasHeaderRecord = true
                };
                using var reader = new StreamReader(jobData);
                using var csvHelper = new CsvReader(reader, CultureInfo.InvariantCulture);
                csvHelper.Context.RegisterClassMap&lt;StudentDetailsMap&gt;();
                var csvHelperRrecords = csvHelper.GetRecords&lt;StudentDetails&gt;()
                    .Where(x =&gt; !string.IsNullOrWhiteSpace(x.Name))
                    .OrderBy(x =&gt; x.ID);

                return csvHelperRrecords.Cast&lt;dynamic&gt;().ToList();
                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        #endregion
    }
}
</code></pre>
<p>How to write a Unit testing for the above Azure Function app? Just a head start is required.</p>
",https://stackoverflow.com/questions/72420799/how-to-write-a-unit-testing-for-azure-function-app,"['unit-testing', '.net-core', 'nunit', 'mstest', '.net-core-3.1']",1013,False,0,0
Flutter testing : when testing server failure returns null,"<p>I'm using flutter test to do unit testing. The package use to mocking is mocktail package (<a href=""https://pub.dev/packages/mocktail"" rel=""nofollow noreferrer"">https://pub.dev/packages/mocktail</a>). When I run the test which is to test the server failure scenario, the actual result I get from this is <strong>null</strong>.
But the expected result is &lt;Instance of 'Failure'&gt;.
How can I fix this issue?</p>
<pre><code>import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';

class MockHttpService extends Mock implements HttpService {}

class MockAthleteEnv extends Mock implements AthleteEnv {}

class MockSharedPrefsService extends Mock implements SharedPrefsService {}

class MockAthleteContactDetailsReq extends Mock implements AthleteContactDetailsReq{}

  void main() {
  late ContactDetailsService contactDetailsService;
  late MockHttpService mockHttpService;
  late MockAthleteEnv mockAthleteEnv;
  late MockSharedPrefsService mockStorageService;
  late MockAthleteContactDetailsReq mockAthleteContactDetailsReq;

  setUp(() {
    mockHttpService = MockHttpService();
    mockAthleteEnv = MockAthleteEnv();
    mockStorageService = MockSharedPrefsService();
    mockAthleteContactDetailsReq = MockAthleteContactDetailsReq();
    contactDetailsService = ContactDetailsService(
        httpService: mockHttpService,
        athleteEnv: mockAthleteEnv,
        storageService: mockStorageService);
  });

  group('add athlete contact details', () {
    const tAthleteId = 001;
    const tAthleteEndpoint = 'https://endpoint/';
    const tData = {
      'firstName':'John',
      'lastName':'Doe',
      'contactNumber': '0932445178',
      'areaCode':'94',
      'email':'johndoe3@mailinator.com',
    };

 
    test(
        'should return server failure when the call to remote data source is unsuccessful',
            () async {
          // Arrange
          when(() =&gt; mockStorageService.getFromDisk(any()))
              .thenAnswer((_) =&gt; tAthleteId);
          when(() =&gt; mockAthleteEnv.API_ATHLETE_ENDPOINT)
              .thenAnswer((_) =&gt; tAthleteEndpoint);
          when(() =&gt; mockAthleteContactDetailsReq.toJson()).thenAnswer((_) =&gt; tData );
          when(() =&gt; mockHttpService.post(any(), any())).thenThrow(
               DioError(
                response: Response(
                  statusCode: 400,
                  requestOptions: RequestOptions(path: &quot;&quot;),
                ),
                requestOptions: RequestOptions(path: &quot;&quot;),
              )
          );

          // Act
          final result = await contactDetailsService.addAthleteContactDetails(mockAthleteContactDetailsReq);
         
          // Assert
          expect(result, throwsA(const TypeMatcher&lt;Failure&gt;()));
        });
  });
}

</code></pre>
",https://stackoverflow.com/questions/74527109/flutter-testing-when-testing-server-failure-returns-null,"['flutter', 'unit-testing', 'flutter-test']",48,False,0,0
Get all images metadata from Input String Android,"<p>I have a resources folder where I added some images that I am using for unit testing. I am able to locate the path of the resources folder via <code>InputStream</code>. However, I need to access these images somehow and get their metadata. Is there a way I can run a filter loop inside the resources folder to get all images?</p>
<pre><code>   fun readImagesMetadata(inputStream: InputStream): Array&lt;ImageMetadata&gt;{
      println(&quot;Reading images&quot;)
      try {
        val builder = StringBuilder()
        val reader = BufferedReader(InputStreamReader(inputStream))

        var str: String? = reader.readLine()
        while (str != null) {
          builder.append(str)
          str = reader.readLine()
          print(str)
        }
        return emptyArray()
      } finally {
        inputStream.close()
      }
    }
</code></pre>
",https://stackoverflow.com/questions/73969870/get-all-images-metadata-from-input-string-android,"['android', 'kotlin']",32,False,0,0
How to test firebase callable function with firestore,"<p>I have a firebase callable function like</p>
<pre><code>exports.getUserInfo = functions.https.onCall(async (data, context) =&gt; {
        const userIdRef = store.collection('UserID').doc('Document');
        let res = null;
        try {
            res = await store.runTransaction(async t =&gt; {
                const doc = await t.get(userIdRef);
                currentUserId = doc.data().ID;


                const newUserIdNum = currentUserId + 1;
                await t.update(userIdRef, {ID: newUserIdNum});
                let initUserData = {
                    'userID': newUserId,
                }
                return initUserData ;
            });
            console.log('Transaction success');
        } catch (e) {
            console.error('Transaction failure:', e);
        }

        return res;
})
</code></pre>
<p>but I am not sure how to create unit test about this. I want to mock UserID/Documment before I call
test.wrap(getUserInfo), like</p>
<pre><code>const myFunctions = require('../index.js')
const getUserInfoWrapped = test.wrap(myFunctions.getUserInfo);

var assert = require('assert');
describe('User', function() {
        describe('getUserInfo()', function() {
                it('should create user', async function() {
                        // sample code, this won't work
                        const snapshot = test.firestore.makeDocumentSnapshot({ID: 1001}, 'UserID/Document');
                        const data = {}
                        const result = await getUserInfoWrapped (data, {});
                        assert.equal(result.userID, &quot;1002&quot;);
                });
        });
});
</code></pre>
<p>seems this case not covered by firebase document</p>
<p>Reference:</p>
<ul>
<li><a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a></li>
<li><a href=""https://github.com/firebase/firebase-functions-test/blob/c77aa92d345b8e4fb5ad98534989eb8dcf7d9bc4/spec/providers/https.spec.ts"" rel=""nofollow noreferrer"">https://github.com/firebase/firebase-functions-test/blob/c77aa92d345b8e4fb5ad98534989eb8dcf7d9bc4/spec/providers/https.spec.ts</a></li>
</ul>
",https://stackoverflow.com/questions/72669689/how-to-test-firebase-callable-function-with-firestore,"['javascript', 'firebase', 'google-cloud-firestore', 'google-cloud-functions']",80,False,0,0
In the loop vs. A-SPICE processes,"<p>Can the HIL,SIL, and MIL tests be matched with SWE4,SWE5,SWE6(static analysis, unit testing, integration testing, qualification testing)  processes? For instance can Unit Tests(ceedling, Google tests) be considered as MIL test?</p>
<p>I am trying to compare in the loop tests and regular automotive based software tests to understand better in the loop testing.</p>
",https://stackoverflow.com/questions/74221127/in-the-loop-vs-a-spice-processes,"['unit-testing', 'testing', 'model-based-testing']",25,False,0,0
Undefined Symbol: SwiftyJSON - Unit Testing,"<p>I've been looking at how to fix this bug extensively without success. Currently, I'm using Xcode 14. I don't know if this has something to do with these errors.</p>
<p>Basically, they appear when I try to execute the test so doesn't compile the project.</p>
<p><a href=""https://i.stack.imgur.com/12hwi.png"" rel=""nofollow noreferrer"">These are the errors</a></p>
<pre><code>Undefined symbol: :$s10SwiftyJSON0B0V17dictionaryLiteralACSS_yptd_tcfC

Undefined symbol: _$s10SwiftyJSON0B0VMn
</code></pre>
<h4>My code</h4>
<h5>Mock (just using the <em>createReport</em> function):</h5>
<pre><code>import Foundation
@testable import PurchHist
import SwiftyJSON

struct JsonObject: Codable {
    let subject: String
    let detail: String
}

class MockErrorReport: ReportIssuesServiceProtocol {
    
    var error: ErrorKind?
    let json = JSON()
    
    func createReport(withParams params: JSON, completion: @escaping ReportIssueResponse) {
        completion(error, nil)
    }
    
    func uploadImage(uploadData: UploadData, completion: @escaping ReportIssueImageResponse) {
    }
}
</code></pre>
<h5>Unit Testing:</h5>
<pre><code> func testSendReport() {
    let mock = MockErrorReport()
    viewModel = .init(reportService: mock)
    
    var capturedResult: Any?
    var capturedError: Error?

    let promise = expectation(description: &quot;Completion handler has been invoked&quot;)
    viewModel.reportService.createReport(withParams: mock.json, completion: { error, errors in
        if error == nil &amp;&amp; errors == nil {
            capturedResult = true
        } else {
            capturedError = error
        }
        promise.fulfill()
    })
    waitForExpectations(timeout: 5)

    XCTAssertEqual(capturedResult as! Bool, true)
    XCTAssertNil(capturedError)
}
</code></pre>
",https://stackoverflow.com/questions/73988874/undefined-symbol-swiftyjson-unit-testing,"['swift', 'unit-testing', 'swifty-json', 'undefined-symbol', 'xcode14']",81,True,0,1
MSW unit testing API in success &amp; error scenario,"<p>I am using MSW for local development and unit testing.</p>
<pre><code>#API fetch
const { loading, error, data } = useFetch('https://made.up/api/usage')

</code></pre>
<pre><code>#handler.js
import { rest } from 'msw'

export const handlers = [
  rest.get('https://made.up/api/usage', (req, res, ctx) =&gt; {
    return res(
      ctx.status(301),
      ctx.json({
        id: 1,
        firstName: 'John',
      }),
    )
  }),
]

</code></pre>
<pre><code>#server.js
import { setupServer } from 'msw/node'
import { handlers } from './handlers'

export const server = setupServer(...handlers)
</code></pre>
<pre><code>#setupTests.js
beforeAll(() =&gt; {
    server.listen({
      onUnhandledRequest: 'warn',
    })
  })

  afterEach(() =&gt; {
    server.resetHandlers()
  })

  afterAll(() =&gt; {
    server.close()
  })
</code></pre>
<pre><code>#App.test.js
import React from &quot;react&quot;;
import { rest } from &quot;msw&quot;;
import { render, screen } from &quot;@testing-library/react&quot;;
import { server } from &quot;../src/mocks/server&quot;;

import App from &quot;../src/App&quot;;

test(&quot;passes&quot;, async () =&gt; {
  render(&lt;App /&gt;);

  expect(
    // Expect the mocked response to be present in the DOM.
    await screen.findByText(`{&quot;id&quot;:1,&quot;firstName&quot;:&quot;John&quot;}`)
  ).toBeInTheDocument();
});

test(&quot;error&quot;, async () =&gt; {
  server.use(
    rest.get(&quot;https://made.up/api/usage&quot;, (req, res, ctx) =&gt; {
      return res(
        ctx.status(500),
        ctx.json({
          error: &quot;error&quot;
        })
      );
    })
  );
  render(&lt;App /&gt;);

  expect(
    // Expect the mocked error response to be present in the DOM.
    await screen.findByText(&quot;Error: error}&quot;)
  ).toBeInTheDocument();
});
</code></pre>
<p>I am overriding the API handler to test the error scenario. Both the tests do not pass when run together. If I run them individually, they work fine.</p>
<p>Am I missing any step? or we can test the same API for different responses in some other way using MSW?</p>
",https://stackoverflow.com/questions/71764462/msw-unit-testing-api-in-success-error-scenario,"['reactjs', 'unit-testing', 'msw']",1843,False,0,1
Unit (real unit test) of test laravel relationship,"<h1>Background</h1>
<ul>
<li>Framework: laravel 9.x</li>
<li>PHP 8.0</li>
<li>Continuous integration (Travis CI etc)</li>
</ul>
<p>I am working on a project that is legally very sensitive, so testing is vital.</p>
<p>Due to project requirements, the project requires 100% unit testing and code coverage. This is a project requirement, even if it is relatively pointless in a few % of the cases. Just to be clear: the relationships work as expected in the functional/feature testing, however... this is for Unit testing. Traditional, no dependencies (mocks etc) unit tests.</p>
<p>To be clear: this is an exercise in reaching 100% coverage NOT necessarily &quot;good&quot; testing.
Adding a &quot;testing ignore&quot; line needs to be justified, so this &quot;suboptimal test&quot; is still the best option for the project.</p>
<h1>Question</h1>
<p>How is it possible to UNIT test the following function:</p>
<pre class=""lang-php prettyprint-override""><code>use Illuminate\Database\Eloquent\Model;

// declaration: normal laravel model 
class Product extends Model
</code></pre>
<pre class=""lang-php prettyprint-override""><code>    /**
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        return $this-&gt;belongsTo(User::class);
    }
</code></pre>
<p>This needs to be a Unit test.
This testing will be run without a database connection, preferably without any other classes (except for mocks).</p>
",https://stackoverflow.com/questions/72228271/unit-real-unit-test-of-test-laravel-relationship,"['php', 'laravel', 'unit-testing']",419,True,1,1
Unit tests run as scalatest in intellij but the same fails in build,"<p>I am using scalatest for unit testing my scala code with intellij, gradle, mockito.</p>
<p>There are few testcases which run absolutely fine when run as scalatests ,however fail when running as part of gradle build.</p>
<p>I have added scalatest dependencies,maiflai scalatest ,mockito and other dependencies into my build.gradle.</p>
<p>Can anyone let me know if I am missing anything.</p>
",https://stackoverflow.com/questions/71936583/unit-tests-run-as-scalatest-in-intellij-but-the-same-fails-in-build,"['scala', 'unit-testing', 'gradle', 'mockito', 'scalatest']",108,False,0,0
"Django Unit Test Case for Models, Serializers, URL&#39;s &amp; Views","<p>I'm a newbie to Unit testing. As I need to perform test case for following models, serializers, views &amp; urls. Can anyone please help.</p>
<p>Models.py</p>
<pre><code>from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth import get_user_model
# Create your models here.

class User(AbstractUser):
    &quot;&quot;&quot;This Class is used to extend the in-build user model &quot;&quot;&quot;
    ROLE_CHOICES = (('CREATOR','CREATOR'),('MODERATOR','MODERATOR'),('USERS','USERS'))
    GENDER_CHOICES = (('MALE','MALE'),('FEMALE',&quot;FEMALE&quot;),('OTHER','OTHER'))
    date_of_birth = models.DateField(verbose_name='Date of Birth', null=True)
    profile_image = models.ImageField(upload_to='media/profile_images', verbose_name='Profile Image', default='media/profile_images/default.webp', blank=True)
    bio = models.TextField(verbose_name='Bio')
    role = models.CharField(max_length=10, verbose_name='Role', choices=ROLE_CHOICES)
    gender = models.CharField(max_length=6, verbose_name='Gender', choices=GENDER_CHOICES)
</code></pre>
<p>Serializers.py</p>
<pre><code>class UserSerializer(serializers.ModelSerializer):
    following = serializers.SerializerMethodField()
    followers = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('first_name','last_name','username','password','email','date_of_birth',
                  'profile_image','bio','role','gender', 'following','followers')
        extra_kwargs = {'is_active':{'write_only':True},
                        'password':{'write_only':True}}

    def create(self, validated_data):
        logger.info('Information Incoming!')
        return User.objects.create_user(**validated_data)

    def update(self, *args, **kwargs):
        user = super().update( *args, **kwargs)
        p = user.password
        user.set_password(p)
        user.save()
        return user

    
    def get_following(self, obj):
        return FollowingSerializer(obj.following.all(), many=True).data

    def get_followers(self, obj):
        return FollowersSerializer(obj.followers.all(), many=True).data
</code></pre>
<p>Views.py</p>
<pre><code>class UserAPI(viewsets.ModelViewSet):
    serializer_class = UserSerializer
    queryset = User.objects.all()
    # permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]
</code></pre>
<p>I tried implementing unit test case but getting an error <code>self.assertEquals(user.get_last_name(), &quot;Johnson&quot;)</code> - <code>AttributeError: 'User' object has no attribute 'get_last_name' </code></p>
<p>tests.py</p>
<pre><code>class UserTests(TestCase):
    def setUp(self):
        User.objects.create(
            first_name='Louis',last_name='Johnson',username='louis.johnson',
            email='louis@mail.com',date_of_birth='1994-12-12', bio='Hello I am Louis',
            role='MODERATOR',gender='MALE')

    def test_users_model(self):
        user = User.objects.get(first_name='Louis')
        self.assertEquals(user.get_last_name(), &quot;Johnson&quot;)
        self.assertEquals(user.get_username(), &quot;louis.johnson&quot;)
</code></pre>
<p>Can anyone please help in sorting out these. Any detailed documentation or help from your end would be a great support.</p>
",https://stackoverflow.com/questions/70606896/django-unit-test-case-for-models-serializers-urls-views,"['python', 'django', 'unit-testing', 'django-models', 'django-views']",181,False,0,1
When to choose Example based testing and property based for Stateful Testing,"<p>I'm doing unit testing mostly these days for Android SDK in Android Studio and using <a href=""https://github.com/jlink/jqwik"" rel=""nofollow noreferrer"">Jqwik</a> which is a Property-Based testing tool on the JUnit Platform.</p>
<p>While exploring the different test techniques approach with my seniors, I learned about example-based testing and property-based testing. I want to know when to choose which one.</p>
",https://stackoverflow.com/questions/72359149/when-to-choose-example-based-testing-and-property-based-for-stateful-testing,"['unit-testing', 'testing', 'property-based-testing', 'jqwik']",180,True,0,2
Couldnt cover the (If) path while writting the spec file for unit testing in Angular (Karma Jasmin),"<pre><code>&gt; loadProducts() {
&gt; this.isLoading = true;
&gt; this.isProductEmpty = false;
&gt; const observer = this.shopService.getProducts().subscribe(
&gt; (categories: ShopReducer) =&gt; {
&gt; if (size(categories.products) &gt; 0) {
&gt; **this.categories = categories.products;**
&gt; } else {
&gt; this.isProductEmpty = true;
&gt; }
&gt; this.isLoading = false;
&gt; },
&gt; (error) =&gt; {
&gt; this.isProductEmpty = true;
&gt; this.isLoading = false;
&gt; this.categories = [];
&gt; this.toast.error(error.message);
&gt; }
&gt; );
&gt; this.subscriptions.add(observer);
&gt; }
</code></pre>
<p>I couldn't cover this specific line during the unit testing in angular.</p>
<pre><code>  this.categories = categories.products;
</code></pre>
<pre><code>  describe('#loadProducts', () =&gt; {
    it('should load products', () =&gt; {
      const errorMessages = {
        isProductEmpty: true,
        categories: [],
      };
      shopServiceMock.getProducts.and.returnValue(throwError(errorMessages));
      component.loadProducts();

      expect(component.categories.length).toEqual(0);
    });
  });

</code></pre>
<p>The above code snippet is the spec file code for the error message which giver below.</p>
<pre><code>   (error) =&gt; {
        this.isProductEmpty = true;
        this.isLoading = false;
        this.categories = [];
        this.toast.error(error.message);
      }
    );
    this.subscriptions.add(observer);
</code></pre>
<p>But I have to cover the whole function. Now the main problem to write a spec file in angular for this function</p>
<p><strong>loadProducts()</strong> whis is given at the top.</p>
<p>Thank you :)</p>
",https://stackoverflow.com/questions/74884450/couldnt-cover-the-if-path-while-writting-the-spec-file-for-unit-testing-in-ang,"['angular', 'angularjs', 'unit-testing', 'karma-jasmine', 'code-coverage']",20,False,0,0
Unit Testing Firebase Realtime Database Android,"<p>I am using Firebase Realtime database. I want to unit test my repository.
I am new to unit testing. I was doing normally like this:</p>
<pre><code> @Test
public void Insert(){
     DataRepository dataRepository = new DataRepository();
     int prevSize = dataRepository.getAllData().size();
}
</code></pre>
<p>.</p>
<pre><code> @Override
    public List&lt;UserData&gt; getAllData() {
        mDataRef = FirebaseDatabase.getInstance().getReference(&quot;UserData&quot;);

        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                //  List&lt;UserData&gt; userDataList = new ArrayList&lt;UserData&gt;();
                userDataList.clear();

                for (DataSnapshot noteSnapshot : snapshot.getChildren()) {
                    UserData userData = noteSnapshot.getValue(UserData.class);
                    // userDataList.add(userData);
                    userDataList.add(0, userData);
                }
                Log.d(&quot;SIZE OF USELIST&quot;, userDataList.size() + &quot;&quot;);

                ;

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Log.d(&quot;loadData:onCancelled&quot;, error.getMessage());

            }



        };

        mDataRef.addValueEventListener(valueEventListener);

        mDataEventListener = valueEventListener;

        return userDataList;
    }
</code></pre>
<p>But this was giving error at <strong>FirebaseDatabase.getInstance()</strong> saying it was not instantiate.
So what is the solution or there is other process to unit test my repository.</p>
<p>The error giving me is that:</p>
<pre><code>java.lang.ExceptionInInitializerError
    at com.google.firebase.FirebaseApp.&lt;clinit&gt;(FirebaseApp.java:97)
    at com.google.firebase.database.FirebaseDatabase.getInstance(FirebaseDatabase.java:56)
    at com.pialroni.mycardi.DataRepository.getAllData(DataRepository.java:97)
    at com.pialroni.mycardi.DataPresenterTest.Insert(DataPresenterTest.java:31)
    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.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.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 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.$Proxy2.processTestClass(Unknown Source)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker$2.run(TestWorker.java:176)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
Caused by: java.lang.RuntimeException: Method getMainLooper in android.os.Looper not mocked. See http://g.co/androidstudio/not-mocked for details.
    at android.os.Looper.getMainLooper(Looper.java)
    at com.google.firebase.FirebaseApp$UiExecutor.&lt;clinit&gt;(FirebaseApp.java:696)
    ... 48 more
</code></pre>
",https://stackoverflow.com/questions/73005413/unit-testing-firebase-realtime-database-android,"['java', 'android', 'unit-testing', 'firebase-realtime-database']",63,False,0,0
How to use docker secret/environment variable in golang dockertest.resource instead of hardcoded password,"<p>We use the below code for unit testing the services that talk to a database system.</p>
<p><a href=""https://sergiocarracedo.es/integration-tests-in-golang-with-dockertest/"" rel=""nofollow noreferrer"">https://sergiocarracedo.es/integration-tests-in-golang-with-dockertest/</a></p>
<p>MySQL root password is hardcoded in the particular line and creates security issues. Is there any way we can pass that as env variable or docker secret ?</p>
<p>resource, err := pool.Run(&quot;mysql&quot;, &quot;5.7&quot;, []string{&quot;MYSQL_ROOT_PASSWORD=secret&quot;})</p>
",https://stackoverflow.com/questions/71676635/how-to-use-docker-secret-environment-variable-in-golang-dockertest-resource-inst,"['docker', 'go']",1167,True,-1,1
Mocking dataframe reader keep running at mockedReader.json(any()),"<p>i have a scala code that reads from json file and converts to dataframe.
while unit testing the code i wasnt able to figure out a way to mock the spark.read option.</p>
<pre><code>val primary_topic_offset = spark.read.json(primaryTopic_offset).as[PartitionOffset].collect()
</code></pre>
<p>my unit test logic is ..</p>
<pre><code>    test(&quot;Test 1 : testReadOffsets&quot;) {
    val array = Array(&quot;topic1&quot;,&quot;topic2&quot;)
    val sparkSession = mock[SparkSession]
    val mockReader = mock[DataFrameReader]
    val mockDf = mock[DataFrame]
    val spark = sparkse;
    import spark.implicits._
    val row_df = Seq(PartitionOffset(0, 123)).toDF()
    when(sparkSession.read).thenReturn(mockReader)
    when(mockReader.json(anyString())).thenReturn(mockDf)
    val ds: Dataset[PartitionOffset] = row_df.as[PartitionOffset]
    when(mockDf.as[PartitionOffset]).thenReturn(ds);

    var map :Map[TopicPartition, Long]=readOffsets(spark,array,&quot;groupid&quot;,config)

  }
</code></pre>
<p>the issue i am facing is my test keep running without a result, it keeps running at mockedReader.json(any()) part.</p>
",https://stackoverflow.com/questions/72631368/mocking-dataframe-reader-keep-running-at-mockedreader-jsonany,"['scala', 'scalatest']",117,False,0,0
Error in unit test in service of my angular apollo application,"<p>I am unit testing my angular apollo app. I always get the same error:</p>
<pre><code>Error: Expected one matching operation for criteria &quot;Match DocumentNode&quot;, found none.
            at ApolloTestingBackend.expectOne (node_modules/apollo-angular/fesm2020/ngApolloTesting.mjs:135:19)
            at UserContext.apply (src/app/my-service.service.spec.ts:66:35)
            at _ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:372:26)
            at ProxyZoneSpec.onInvoke (node_modules/zone.js/fesm2015/zone-testing.js:287:39)
            at _ZoneDelegate.invoke (node_modules/zone.js/fesm2015/zone.js:371:52)
            at Zone.run (node_modules/zone.js/fesm2015/zone.js:134:43)
            at runInTestZone (node_modules/zone.js/fesm2015/zone-testing.js:582:34)
            at UserContext.&lt;anonymous&gt; (node_modules/zone.js/fesm2015/zone-testing.js:597:20)
            at &lt;Jasmine&gt;
Chrome 103.0.5060.53 (Linux x86_64): Executed 1 of 1 (1 FAILED) (0.108 secs / 0.092 secs)
</code></pre>
<p>This error occurs on the line:</p>
<pre><code>const op = apolloController.expectOne(QUERY_GQL);
</code></pre>
<p>I have already reviewed all the related posts and none of them solve the problem. Someone could help me?</p>
<p>I am waiting for a response from someone who can solve my problem. Thank you very much.</p>
<p>Greetings.</p>
",https://stackoverflow.com/questions/73783147/error-in-unit-test-in-service-of-my-angular-apollo-application,"['angular', 'unit-testing', 'graphql', 'apollo', 'apollo-angular']",94,False,0,0
How to implement unit testing for a global resposeBus which emits functions in vue,"<p>I want to implement unit testing using vue-test utils for a vue component which uses a global event handler as a vue instance called responseBus. Need to implement unit test using jest.</p>
<p>Here is the code for vue component.</p>
<pre><code>    &lt;script&gt;
import NewQuestionBuilder from '@/components/NewQuestionBuilder.vue'

export default {
  inject: ['$responseBus'],
  props: {
    question: {
      type: Object,
      required: true,
    },
  },
  mounted() {
    this.$responseBus.$on('pseudo', (payload) =&gt; {
      if (payload.questionCode === this.question.questionCode) {
        this.$emit('update:initialValue', payload)
      }
    })
  },
  render(h) {
    return h('div', { class: 'pl-0 md:pl-4 w-full ' }, [
      h(NewQuestionBuilder, { props: { questionData: this.question } }),
    ])
  },
}
&lt;/script&gt;
</code></pre>
<p>Here is the unit test file.</p>
<pre><code>    import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vue from 'vue'
import Component from '../BaseComputed'

const GlobalPlugins = {
  install(v) {
    v.prototype.$eventBus = new Vue()
  },
}

const localVue = createLocalVue()
localVue.use(GlobalPlugins)

describe('BaseComputed', () =&gt; {
  const mocks = {
    $responseBus: {
      $on: jest.fn(),
      $off: jest.fn(),
      $emit: jest.fn(),
    },
  }

  it('listens to event pseudo', () =&gt; {
    const wrapper = shallowMount(Component, {
      mocks,
      propsData: {
        imageUrl: '',
        label: ``,
        initialValue: [],
        isEnabled: true,
        code: '',
        triggers: [],
        choices: [],
        question: {
          questionCode: 'HFFIN0416USOTEL',
        },
      },
    })
    wrapper.vm.$responseBus.$emit('pseudo', {
      questionCode: `HFFIN0416USOTEL`,
    })
    expect(wrapper.vm.question.questionCode).toEqual('HFFIN0416USOTEL')
    expect(wrapper.vm.$responseBus.$on).toHaveBeenCalledTimes(1)
    expect(wrapper.vm.$responseBus.$on).toHaveBeenCalledWith(
      'pseudo',
      jest.fn((payload) =&gt; {
        if (payload.questionCode === this.question.questionCode) {
          this.$emit('update:initialValue', payload)
        }
      })
    )
})
})
</code></pre>
<p>Still couldn't test the 'psuedo' method. Guys need help to achieve this.</p>
",https://stackoverflow.com/questions/72870714/how-to-implement-unit-testing-for-a-global-resposebus-which-emits-functions-in-v,"['vue.js', 'unit-testing', 'jestjs', 'vue-test-utils']",41,False,0,0
Angular - How to test Guards with ActivatedRouteSnapshot RouterStateSnapshot and GlobalState,"<p>I'm creating unit test for my Angular app but i don'k know create tests for my custom guard that use Redux.</p>
<p>This is my code of the guard</p>
<pre><code>import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanLoad, Route, Router, RouterStateSnapshot, UrlSegment, UrlTree } from '@angular/router';
import { first, map, Observable, tap } from 'rxjs';
import { GlobalState } from '../state/app.reducer';
import { Store } from '@ngrx/store';
import { RolesAccount } from 'src/app/pages/auth/interfaces/auth.constant';
 
@Injectable({
  providedIn: 'root'
})
export class AdministratorGuard implements CanActivate, CanLoad {
 
  constructor(private route: Router,private store: Store&lt;GlobalState&gt;) {}
 
  canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable&lt;boolean | UrlTree&gt; | Promise&lt;boolean | UrlTree&gt; | boolean | UrlTree {
    return this.isAdmin()
  }
  canLoad( route: Route, segments: UrlSegment[]): Observable&lt;boolean | UrlTree&gt; | Promise&lt;boolean | UrlTree&gt; | boolean | UrlTree {
    return this.isAdmin()
  }
 
  isAdmin():Observable&lt;true | UrlTree&gt;{    
    return this.store.select('authentication').pipe( 
      first(), // take of first value
      map(userStore =&gt; userStore.userLogged?.role || ''), 
      //TODO we hardcode the email of administrator until role is in JWT
      map(role =&gt; role === RolesAccount.ADMIN ? true : this.route.createUrlTree(['/home']))
    );    
  }
}
</code></pre>
<p>I run <code>npm run coverage</code></p>
<p>And this is the uncovered block (I need create unit test for <code>canActivate, canLoad, and isAdmin</code></p>
<p><a href=""https://i.stack.imgur.com/uZSyD.jpg"" rel=""nofollow noreferrer"">Uncovered block</a></p>
<p>And this is my unit testing file (default testing)</p>
<pre><code>import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { MockStore, provideMockStore } from '@ngrx/store/testing';
import { AuthComponent } from 'src/app/pages/auth/auth.component';
import { IUserState } from 'src/app/pages/auth/interfaces/auth.interfaces';

import { AdministratorGuard } from '../administrator.guard';

fdescribe('AdministratorGuard', () =&gt; {
  let guard: AdministratorGuard;
  let store: MockStore&lt;IUserState&gt;;  

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports:[
        RouterTestingModule.withRoutes(
          [
            {
              path: 'auth',
              component: AuthComponent
            },
          ]
        ),
      ],
      providers:[
        provideMockStore({}),
      ]
    });
    guard = TestBed.inject(AdministratorGuard);
    store = TestBed.inject(MockStore);
  });

  it('should be created', () =&gt; {
    expect(guard).toBeTruthy();
  });
});
</code></pre>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/72720241/angular-how-to-test-guards-with-activatedroutesnapshot-routerstatesnapshot-and,"['angular', 'testing', 'redux', 'guard', 'karma-coverage']",552,True,0,2
Unit test fails on build from Intellij but passes from terminal,"<p>I have a big java project. Using maven to automate the build and manage dependencies and JUnit for the unit testing.</p>
<p>When i'm running <code>mvn clean install</code> from Intellij the build fails because of one unit test that fails.
The test succeeds when ran manually.</p>
<p>Also, executing <code>mvn clean install</code> from the terminal succeeds. (all tests pass)</p>
<p>I'm not sure where to look for the problem here.</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/73769576/unit-test-fails-on-build-from-intellij-but-passes-from-terminal,"['java', 'maven', 'intellij-idea', 'junit', 'build']",791,False,3,1
How to seed data and test one to many relationship with EF Core SQlite in memory?,"<p>I am unit testing an EF Core MVC project using in memory Sqlite and have a one to many
relationship between the two tables below. Where ResourceRequest has an ICollection of
Resourcetags. How would I go about seeding data when adding a new Resourcetag in the test
method? Are there any contstraints for this using in memory testing?</p>
<pre><code>    public DbSet&lt;ResourceRequest&gt;? Resources { get; set; }
    public DbSet&lt;ResourceTags&gt;? ResourceTags { get; set; }

     [TestMethod]
    public void AddResourceTagsSavesAResourceTagsViaContext()
    {
        using (var factory = new PrismContextFactory())
        { 
            // Arrange values
            Random rnd = new Random();
            var id = new byte[32];
            rnd.NextBytes(id);
            var text = &quot;tagtext&quot;;
            string convertedId = Convert.ToBase64String(id);

            var reourceTag = new ResourceTags()
            {
                ResourceId = id,
                Tag = text,
                ResourceRequest = new ResourceRequest 
                { 
                   SubscriptionID = &quot;&quot;,
                   TenantID = &quot;&quot;,
                   Name = &quot;&quot;,
                   ID = &quot;&quot;,
                   ResourceGroup = &quot;&quot;
                },
            };

            // Get a context
            using (var context = factory.CreateContext())
            {
                context.Add(reourceTag);
                context.SaveChanges();
            }

            // Get another context using the same connection
            using (var context = factory.CreateContext())
            {
                var count = context.ResourceTags?.Count();
                Assert.AreEqual(1, count);

                var tagText = context.ResourceTags?.
                FirstOrDefaultAsync(r =&gt; r.Tag == reourceTag.Tag);

                var tagId = context.ResourceTags?.
                FirstOrDefaultAsync(r =&gt; r.ResourceId == reourceTag.ResourceId);

                Assert.IsNotNull(tagText);
                Assert.IsNotNull(id);
            }
        } 
    }
</code></pre>
",https://stackoverflow.com/questions/73401973/how-to-seed-data-and-test-one-to-many-relationship-with-ef-core-sqlite-in-memory,"['c#', 'unit-testing', 'model-view-controller', 'entity-framework-core']",205,False,0,0
Class vs Instance attribute in unit test,"<p>In unit testing a class,</p>
<pre><code>class Product:

    def __init__(self, name, price):
        self.name = name
        self.price = price

</code></pre>
<p>what is the rationale for setting up a class attribute (#1) instead of an instance attribute (#2)? The difference between class vs static vs instance attributes are clear to me (and are illustrated in many other SO posts), but what's not immediately obvious what the pros/cons or use-cases for each.</p>
<p>(1)</p>
<pre><code>import unittest

class TestProduct(unittest.TestCase):
    
    @classmethod
    def setUp(cls):
        cls.product = Product(&quot;book&quot;, 30)
</code></pre>
<p>(2)</p>
<pre><code>import unittest

class TestProduct(unittest.TestCase):

    def setUp(self):
        self.product = Product(&quot;book&quot;, 30)
</code></pre>
",https://stackoverflow.com/questions/70776156/class-vs-instance-attribute-in-unit-test,"['python', 'unit-testing', 'oop']",276,True,-1,2
ngx-translate Problems with unit testing,"<p>0</p>
<p>I'm using ngx-translate library and having some issues with unit testing because it wont find certain provides. The issue its that even tho i place a provider, it keeps asking for another one and it never solves the issue.</p>
<p>So basically im unit testing mi auth component, which uses in its constructor the translate service.</p>
<p>Tests ask me (like im showing on the next picture) that they need &quot;TraslateService&quot; as providers, so im adding them.</p>
<pre><code>  providers:[
    TranslateService
  ]
</code></pre>
<p>But once i add this, it asks for another thing from the translate, and it goes on in on. I believe that the solution should be another way.</p>
<p><em>Error image</em>
<img src=""https://i.stack.imgur.com/GAH1K.png"" alt=""Error image"" /></p>
<p><strong>app.module</strong></p>
<pre><code>  return new TranslateHttpLoader(http);
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    ...
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
       },
    defaultLanguage: 'en'
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code></pre>
<p>Quiero destacar que el sharedModule, ya exporta el translateModule que se usa en otros lugares de la app.</p>
<p>I wanna remark that on the sharedModule, TranslateModule it's already being exported which is used in other places on the app.</p>
<p><strong>Shared Module</strong></p>
<pre><code>@NgModule({
  imports: [
    ...,
    TranslateModule,
  ],
  exports: [
    ...,
    TranslateModule
  ],
  providers:[
  ]
})
export class SharedModule { }
</code></pre>
<p>** Also, the auth is a lazy module too.</p>
<p>auth.module**</p>
<pre><code>@NgModule({
  declarations: [
    AuthComponent
  ],
  imports: [
    CommonModule,
    AuthRoutingModule,
    SharedModule
  ]
})
export class AuthModule { }
</code></pre>
<p><strong>auth.component.ts</strong></p>
<pre><code>export class AuthComponent implements OnInit { 

  constructor(public translate: TranslateService)
}
</code></pre>
<p><strong>Spect.ts</strong></p>
<pre><code>describe('AuthComponent', () =&gt; {
  let component: AuthComponent;
  let fixture: ComponentFixture&lt;AuthComponent&gt;;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports:[
        HttpClientTestingModule,
        SharedModule,
      ],
      providers:[
        TranslateService,
      ],
      declarations: [ AuthComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
    })
    .compileComponents();
  });

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

</code></pre>
<p>Any idea on how to fix this?</p>
",https://stackoverflow.com/questions/72221197/ngx-translate-problems-with-unit-testing,"['angular', 'angularjs', 'typescript', 'unit-testing', 'angular-test']",499,True,0,1
FileLoader in three.js gives ReferenceError: Request is not defined while unit testing using mocha,"<p>I am trying to write a unit test for my three js utility functions.
My Project uses CRA w TS, and mocha &amp; chai w TS for unit testing.</p>
<p><strong>GeometryUtils.spec.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>import { expect } from 'chai';
import { describe, it } from 'mocha';
import { Scene, Vector3 } from 'three';![enter image description here](https://i.stack.imgur.com/YdU7b.png)
import { extractBoundaryOf } from './GeometryUtils';
import fs from 'fs';
import * as THREE from 'three';
import { GLTF, GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';

describe('GeometryUtils.extractBoundaryOf', function () {
    it('should return a Vector3[][]', function () {
        THREE.Cache.enabled = true;
        const surfaceName = 'wall_0';
        const surfaceNormal = new Vector3(0, 0, 1);
        new GLTFLoader().parse(
            fs.readFileSync('./src/services/threejs/test/room_camera_geometry.gltf').toString(),
            './src/services/threejs/test/',
            function (gltf) {
                const scene = gltf.scene as unknown as Scene;
                console.log('GLTF ', gltf);
                console.log('Scene ', gltf.scenes);
                const boundary = extractBoundaryOf(surfaceName, surfaceNormal, scene);
                expect(boundary).to.be.an('array');
            },
            function (error) {
                console.error(error);
            },
        );
    });
});
</code></pre>
<p><strong>GeometryUtil.ts</strong></p>
<pre class=""lang-js prettyprint-override""><code>import {
    Box2,
    BufferGeometry,
    Group,
    LineSegments,
    Mesh,
    Object3D,
    PerspectiveCamera,
    Raycaster,
    LineBasicMaterial,
    Scene,
    Triangle,
    Vector2,
    Vector3,
    Line,
} from 'three';
export function extractBoundaryOf(surfaceName: string, surfaceNormal: Vector3, inScene: Scene): Vector3[][] {
    // just an example
    let allVertices: Vector3[][] = [[new Vector3(0, 0, 1)]];
    return allVertices;
}
</code></pre>
<p>Error I'm facing:</p>
<pre class=""lang-sh prettyprint-override""><code>yarn run v1.22.17
$ mocha src/**/*.spec.ts
(node:34713) ExperimentalWarning: --experimental-loader is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)


  GeometryUtils.extractBoundaryOf
    ✔ should return a Vector3[][]
ReferenceError: Request is not defined
    at FileLoader.load (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/build/three.module.js:39258:15)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2640:11
    at new Promise (&lt;anonymous&gt;)
    at GLTFParser.loadBuffer (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2638:10)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2541:24)
    at GLTFParser.loadBufferView (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2659:15)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2535:40
    at GLTFParser._invokeOne (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2468:19)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2533:24)
    at GLTFParser.loadAccessor (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2694:34)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2529:24)
    at assignAttributeAccessor (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:4206:17)
    at addPrimitiveAttributes (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:4222:17)
    at GLTFParser.loadGeometries (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3334:24)
    at GLTFParser.loadMesh (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3377:24)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2523:34
    at GLTFParser._invokeOne (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2468:19)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2521:24)
    at GLTFParser.createNodeMesh (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3739:17)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3788:38
    at GLTFParser._invokeOne (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2468:19)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3786:31
    at GLTFParser.loadNode (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3820:4)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2517:24)
    at buildNodeHierarchy (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3985:16)
    at GLTFParser.loadScene (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:3933:18)
    at GLTFParser.getDependency (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2513:24)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2601:19
    at Array.map (&lt;anonymous&gt;)
    at GLTFParser.getDependencies (file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2599:37)
    at file:///home/subhankar/workspace/trisetra/trisetra-decor/node_modules/three/examples/jsm/loaders/GLTFLoader.js:2314:12
    at processTicksAndRejections (internal/process/task_queues.js:95:5)


  1 passing (64ms)

Done in 14.62s.
</code></pre>
<p>package.json:</p>
<pre class=""lang-json prettyprint-override""><code>{
   &quot;type&quot;: &quot;module&quot;,
   &quot;scripts&quot;: {
      ....
      &quot;test&quot;: &quot;mocha src/**/*.spec.ts&quot;,
      ....,
   }
}
</code></pre>
<p>tsconfig.json</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;compilerOptions&quot;: {
    &quot;types&quot;: [ &quot;node&quot;, &quot;mocha&quot;, &quot;chai&quot;, &quot;lodash&quot;],
    &quot;typeRoots&quot;: [&quot;typings&quot;, &quot;./node_modules/@types&quot;],
    &quot;target&quot;: &quot;esnext&quot;,
    &quot;lib&quot;: [
      &quot;dom&quot;,
      &quot;dom.iterable&quot;,
      &quot;esnext&quot;
    ],
    &quot;allowJs&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;strict&quot;: true,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;experimentalDecorators&quot;: true,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;resolveJsonModule&quot;: true,
    &quot;isolatedModules&quot;: true,
    &quot;noEmit&quot;: true,
    &quot;jsx&quot;: &quot;react&quot;,
    &quot;useDefineForClassFields&quot;: true
  },
  &quot;include&quot;: [
    &quot;src&quot;
  ]
}
</code></pre>
<p>.mocharc.json</p>
<pre class=""lang-json prettyprint-override""><code>{
    &quot;node-option&quot;: [
        &quot;experimental-specifier-resolution=node&quot;,
        &quot;loader=ts-node/esm&quot;
    ]
}
</code></pre>
<p>I wanna pass the GLTF object to my testing
This is my directory structure:</p>
<p>I tried to compile using commonjs too. But that didn't work either.</p>
",https://stackoverflow.com/questions/71567115/fileloader-in-three-js-gives-referenceerror-request-is-not-defined-while-unit-t,"['typescript', 'unit-testing', 'three.js', 'mocha.js', 'react-testing']",581,False,2,0
Trouble Writing to Jest Mocked Prisma Database,"<p>I have two databases that I need to interact with in my code.  I have a simple function that takes an object and writes it to my PostgreSQL database using Prisma.  I've tested the function with Postman, and it works perfectly, but when I try to execute it using a Jest mock (using the singleton pattern found in the <a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""nofollow noreferrer"">Prisma unit testing guide</a>), it returns undefined indicating that it didn't interact with the database and create the new record.  Here's my code:</p>
<h4>/prisma/clinical-schema.prisma</h4>
<pre><code>generator client {
  provider = &quot;prisma-client-js&quot;
  output   = &quot;./generated/clinical&quot;
}

datasource clinicalDatabase {
  provider = &quot;postgresql&quot;
  url      = &quot;postgresql://postgres:postgres@localhost:5432/clinical-data?schema=public&quot;
}

model pcc_webhook_update {
  id                  Int                       @id @default(autoincrement())
  event_type          String
  organization_id     Int
  facility_id         Int
  patient_id          Int
  resource_id         String?
  webhook_date        DateTime                  @default(now()) @clinicalDatabase.Timestamptz(6)
  status              pcc_webhook_update_status @default(pending)
  status_changed_date DateTime?                 @clinicalDatabase.Timestamptz(6)
  error_count         Int                       @default(0)

  @@unique([organization_id, facility_id, patient_id, resource_id, event_type, status])
}

enum pcc_webhook_update_status {
  pending
  processing
  processed
  error
}

</code></pre>
<h4>/prisma/clinical-client.ts</h4>
<pre class=""lang-js prettyprint-override""><code>import { PrismaClient } from './generated/clinical';

const prismaClinical = new PrismaClient();

export default prismaClinical;
</code></pre>
<h4>/testing/prisma-clinical-mock.ts</h4>
<pre class=""lang-js prettyprint-override""><code>import { PrismaClient } from '../prisma/generated/clinical';
import { mockDeep, mockReset, DeepMockProxy } from 'jest-mock-extended';
import prisma from '../prisma/clinical-client';

jest.mock('../prisma/clinical-client', () =&gt; ({
  __esModule: true,
  default: mockDeep&lt;PrismaClient&gt;()
}));

beforeEach(() =&gt; {
  mockReset(prismaClinicalMock);
});

export const prismaClinicalMock = prisma as unknown as DeepMockProxy&lt;PrismaClient&gt;;
</code></pre>
<p>Everything up to this point follows the conventions outlined by the Prisma unit testing docs.  The only modification I made was to make it database specific.  Below is my function and tests.  The request object in <code>handle-pcc-webhooks.ts</code> is a sample http request object, the body of which contains the webhook data I care about.</p>
<h4>/functions/handle-pcc-webhooks/handler.ts</h4>
<pre class=""lang-js prettyprint-override""><code>import prismaClinical from '../../../prisma/clinical-client';
import { pcc_webhook_update } from '../../../prisma/generated/clinical';
import { requestObject } from './handler.types';

export const handlePccWebhook = async (request: requestObject) =&gt; {

  try {

    const webhook = JSON.parse(request.body);

    // if the webhook doesn't include a resource id array, set it to an array with an empty string to ensure processing and avoid violating
    // the multi-column unique constraint on the table
    const { resourceId: resourceIds = [''] } = webhook;

    let records = [];

    for (const resourceId of resourceIds) {

      // update an existing record if one exists in the pending state, otherwise create a new entry
      const record: pcc_webhook_update = await prismaClinical.pcc_webhook_update.upsert({
        where: {
          organization_id_facility_id_patient_id_resource_id_event_type_status: {
            organization_id: webhook.orgId,
            facility_id: webhook.facId,
            patient_id: webhook.patientId,
            resource_id: resourceId,
            event_type: webhook.eventType,
            status: 'pending'
          }
        },
        update: {
          webhook_date: new Date()
        },
        create: {
          event_type: webhook.eventType,
          organization_id: webhook.orgId,
          facility_id: webhook.facId,
          patient_id: webhook.patientId,
          resource_id: resourceId,
          status: 'pending' // not needed
        }
      });

      records.push(record);
    }

    return records;

  } catch (error) {

    console.error(error);
  }
};
</code></pre>
<h4>/functions/handle-pcc-webhooks/handler.spec.ts</h4>
<pre class=""lang-js prettyprint-override""><code>import fs from 'fs';
import path from 'path';
import MockDate from 'mockdate';
import { prismaClinicalMock } from '../../../testing/prisma-clinical-mock';
import { createAllergyAddRecord } from './__mocks__/allergy';
import { requestObject } from './handler.types';
import { handlePccWebhook } from './handler';

describe('allergy.add', () =&gt; {

  let requestObject: requestObject;
  let allergyAddRecord: any;

  beforeAll(() =&gt; {
    requestObject = getRequestObject('allergy.add');
  });

  beforeEach(() =&gt; {
    MockDate.set(new Date('1/1/2022'));
    allergyAddRecord = createAllergyAddRecord(new Date());
  });

  afterEach(() =&gt; {
    MockDate.reset();
  });

  test('should create an allergy.add database entry', async() =&gt; {

    prismaClinicalMock.pcc_webhook_update.create.mockResolvedValue(allergyAddRecord);

    // this is where I would expect handlePccWebhook to return the newly created database
    // record, but instead it returns undefined.  If I run the function outside of this
    // unit test, with the same input value, it functions perfectly
    await expect(handlePccWebhook(requestObject)).resolves.toEqual([allergyAddRecord]);
  });
});

// This just builds a request object with the current webhook being tested
function getRequestObject(webhookType: string) {

  // read the contents of request object file as a buffer, then convert it to JSON
  const rawRequestObject = fs.readFileSync(path.resolve(__dirname, '../../sample-data/handle-pcc-webhook-request.json'));
  const requestObject: requestObject = JSON.parse(rawRequestObject.toString());

  // read the contents of the webhook file as a buffer, then convert it to a string
  const rawWebhook = fs.readFileSync(path.resolve(__dirname, `../../sample-data/${webhookType}.json`));
  const webhookString = rawWebhook.toString();

  // set the body of the request object to the contents of the target webhook
  requestObject.body = webhookString;

  return requestObject;
}
</code></pre>
<p>Finally, here is the result of running the unit test:</p>
<p><a href=""https://i.stack.imgur.com/KYAxH.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/KYAxH.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/72929391/trouble-writing-to-jest-mocked-prisma-database,"['unit-testing', 'jestjs', 'prisma', 'jest-mock-extended']",1176,True,0,1
Learning unit testing in C#,"<p>So I'm trying to learn unit testing in C# with a sample project I found online. The project is <a href=""https://github.com/swarooprooney/MoqSample/tree/dev/MoqTest"" rel=""nofollow noreferrer"">here</a>.</p>
<p>This is my first time doing unit testing so, I am still learning and have come across some errors. Here is the code I am trying to test:</p>
<p><code>IRoosterService</code>:</p>
<pre><code>namespace MoqBusiness
{    
    public interface IRoosterService
    {
        IList&lt;Player&gt; GetPlayersFromRepo();
    }
}
</code></pre>
<p><code>RoosterService</code>:</p>
<pre><code>namespace MoqBusiness
{
    public class RoosterService : IRoosterService
    {
        private readonly IPlayersRepo _players;

        public RoosterService(IPlayersRepo players)
        {
            _players = players;
        }
        
        public IList&lt;Player&gt; GetPlayersFromRepo()
        {
            return _players.GetPlayerList();
        }
    }
}
</code></pre>
<p><code>IPlayersRepo</code>:</p>
<pre><code>namespace MoqDataRepos
{
    public interface IPlayersRepo
    {
        IList&lt;Player&gt; GetPlayerList();
    }
}
</code></pre>
<p><code>PlayersRepo</code>:</p>
<pre><code>namespace MoqDataRepos
{
    public class PlayersRepo:IPlayersRepo
    { 
        public IList&lt;Player&gt; GetPlayerList()
        {
            var playerList = new List&lt;Player&gt; {
                new Player { Name = &quot;Swaroop&quot;, Age = 28 ,PlayersClub = new Club{ ClubName = &quot;Manchester United&quot;,CountryName = &quot;GB&quot;,Position = 7} },
                new Player { Name = &quot;Seema&quot;, Age = 30 ,PlayersClub = new Club{ ClubName = &quot;Manchester United&quot;,CountryName = &quot;GB&quot;,Position = 7}},
                new Player { Name = &quot;Jay&quot;, Age = 35 ,PlayersClub = new Club{ ClubName = &quot;Arsenal&quot;,CountryName = &quot;GB&quot;,Position = 4}},
                new Player { Name = &quot;Don&quot;, Age = 30 ,PlayersClub = new Club{ ClubName = &quot;Manchester City&quot;,CountryName = &quot;GB&quot;,Position = 1}}
            };
            return playerList;
        }
    }
}
</code></pre>
<p>So I am trying to test this <code>RoosterService</code> class to start with, using Moq and XUnit.</p>
<p>My thinking was I am testing to see if the <code>GetPlayersFromRepo</code> method returns the players that are in <code>PlayersRepo</code> - <code>GetPlayerList</code> so I would first use <code>GetPlayersFromRepo</code> method, then call <code>PlayersRepo</code> - <code>GetPlayerList</code> method and compare the two to see if they are equal.</p>
<p>Here is my code for this Test:</p>
<pre><code>namespace MoqTests
{
    public class RoosterServiceTests
    {
        private readonly RoosterService _service;
        private readonly Mock&lt;IPlayersRepo&gt; playersRepoMock = new Mock&lt;IPlayersRepo&gt;();

        public RoosterServiceTests()
        {
            _service = new RoosterService(playersRepoMock.Object);
        }
        
        [Fact]
        public void GetPlayersFromRepo_ShouldReturnPlayers()
        {
            //Arrange
            var expected = playersRepoMock.Setup(p =&gt; p.GetPlayerList()).Returns(new List&lt;Player&gt;());
            
            //Act
            var players = _service.GetPlayersFromRepo();

            //Assert
            Assert.Equal(players, expected);
        }

    }
}
</code></pre>
<p>However this does not work as the following error message comes up</p>
<blockquote>
<p>Argument 2: cannot convert from 'Moq.Language.Flow.IReturnsResult&lt;MoqDataRepos.IPlayersRepo&gt;' to 'System.Collections.Generic.IEnumerable&lt;MoqDataModel.Player&gt;'</p>
</blockquote>
<p>I don't understand why this is happening as both methods return a list so not sure why this error occurs. Since this is my first test I guess I may be setting it up wrong too? Any advice appreciated.</p>
",https://stackoverflow.com/questions/74933572/learning-unit-testing-in-c,"['c#', 'unit-testing', 'moq', 'xunit']",74,True,-1,2
Custom testthat expectation that performs calculations,"<p>I am trying to test if the off-diagonal values of a table in R are non-zero using the <code>{testthat}</code> package, and would like to apply this test to multiple different tables e.g. may load different data and/or variables to create the tables. I currently have this working using a function that is called in <code>test_that()</code>, and itself calls <code>expect_equal(sum(table), 0)</code>, but I think this is probably bad practice and I should instead define a custom <code>expect_*</code> function.</p>
<p>As <code>quasi_label()</code> states <a href=""https://testthat.r-lib.org/reference/quasi_label.html"" rel=""nofollow noreferrer"">&quot;... you can not use unquoting for other purposes&quot;</a>, I tried to use data masking with a <a href=""https://dplyr.tidyverse.org/articles/programming.html#indirection"" rel=""nofollow noreferrer"">character env-variable</a>, but it doesn't seem to work.</p>
<p>It's very possible that I'm missing something obvious as this is my first stab at unit testing, so please feel free to correct anything about this approach (even if unrelated to the question and just pointing out better unit testing practices).</p>
<p>Thanks,</p>
<pre class=""lang-r prettyprint-override""><code>library(tidyverse)
library(testthat)
#&gt; 
#&gt; Attaching package: 'testthat'
#&gt; The following object is masked from 'package:dplyr':
#&gt; 
#&gt;     matches
#&gt; The following object is masked from 'package:purrr':
#&gt; 
#&gt;     is_null
#&gt; The following objects are masked from 'package:readr':
#&gt; 
#&gt;     edition_get, local_edition
#&gt; The following object is masked from 'package:tidyr':
#&gt; 
#&gt;     matches

# This works - provide label to allow for debugging when using multiple times in single test_that() call
function_test &lt;- function(data, var_1, var_2, label) {
    data &lt;- {{data}}

    var_1_str &lt;- rlang::as_string(rlang::ensym(var_1))
    var_2_str &lt;- rlang::as_string(rlang::ensym(var_2))

    data_table &lt;- table(
        data[[var_1_str]],
        data[[var_2_str]],
        useNA = &quot;always&quot;
    )

    diag(data_table) &lt;- NA

    expect_equal(sum(data_table, na.rm = TRUE), 0, label = label)
}

test_that(&quot;Result variables match&quot;, {
    function_test(
        data = mtcars,
        var_1 = am,
        var_2 = gear
    )
})
#&gt; ── Failure (&lt;text&gt;:23:5): Result variables match ───────────────────────────────
#&gt; sum(data_table, na.rm = TRUE) not equal to 0.
#&gt; 1/1 mismatches
#&gt; [1] 9 - 0 == 9
#&gt; Backtrace:
#&gt;  1. global function_test(data = mtcars, var_1 = am, var_2 = gear)
#&gt;  2. testthat::expect_equal(sum(data_table, na.rm = TRUE), 0)
#&gt; Error in `reporter$stop_if_needed()`:
#&gt; ! Test failed

# These don't work
expect_zero_non_diagonal_1 &lt;- function(data, var_1, var_2) {
  # 1. Capture object and label
    actual_data &lt;- quasi_label(rlang::enquo(data), arg = &quot;data&quot;)
    var_1_str &lt;- rlang::as_string(rlang::ensym(var_1))
    var_2_str &lt;- rlang::as_string(rlang::ensym(var_2))

    act &lt;- actual_data$val
    data_table &lt;- table(
        act[[var_1_str]],
        act[[var_2_str]],
        useNA = &quot;always&quot;
    )

    diag(data_table) &lt;- NA

    # 2. Call expect()
    expect(
        sum(data_table) == 0,
        glue::glue(&quot;{actual_data$lab} has non-zero entries in the non-diagonal elements&quot;)
    )

    # 3. Invisibly return the value
    invisible(act)
}

test_that(&quot;Result variables match&quot;, {
    expect_zero_non_diagonal_1(mtcars, am, gear)
})
#&gt; ── Error (&lt;text&gt;:58:5): Result variables match ─────────────────────────────────
#&gt; Error in `if (ok) &quot;success&quot; else &quot;failure&quot;`: missing value where TRUE/FALSE needed
#&gt; Backtrace:
#&gt;  1. global expect_zero_non_diagonal_1(mtcars, am, gear)
#&gt;  2. testthat::expect(sum(data_table) == 0, glue::glue(&quot;{actual_data$lab} has non-zero entries in the non-diagonal elements&quot;))
#&gt; Error in `reporter$stop_if_needed()`:
#&gt; ! Test failed
</code></pre>
<p><sup>Created on 2022-06-29 by the <a href=""https://reprex.tidyverse.org"" rel=""nofollow noreferrer"">reprex package</a> (v2.0.1)</sup></p>
",https://stackoverflow.com/questions/72799364/custom-testthat-expectation-that-performs-calculations,"['r', 'unit-testing', 'rlang', 'testthat', 'quosure']",15,False,0,0
Android unit testing kotlin: LiveData value was never set,"<p>I'm getting this error while unit testing: &quot;LiveData value was never set.&quot;</p>
<p>I'm trying to test the getStudents() method of my viewmodel that looks like this:</p>
<p>StudentViewModel:</p>
<pre><code>@HiltViewModel
class StudentViewModel @Inject constructor(
    private val getStudentsUseCase: GetStudentsUseCase
) : ViewModel() {
    private val _studentLD = MutableLiveData&lt;List&lt;Student&gt;&gt;()
    val studentLD: LiveData&lt;List&lt;Student&gt;&gt; = _studentLD

    private val _errorLD = MutableLiveData&lt;String&gt;()
    val errorLD: LiveData&lt;String&gt; = _errorLD

    fun getStudents() {
        viewModelScope.launch {
            var result = getStudentsUseCase.execute()
            result.onSuccess {
                _studentLD.value = it
            }.onFailure {
                _errorLD.value = it.message.toString()
            }
        }
    }
}
</code></pre>
<p>StudentViewModelTest:</p>
<pre><code>@OptIn(ExperimentalCoroutinesApi::class)
class StudentViewModelTest {

    private lateinit var viewModel: StudentViewModel

    @get:Rule
    var instantExecutorRule = InstantTaskExecutorRule()

    @get:Rule
    var mainCoroutineRule = MainCoroutineRule()

    @Mock
    private lateinit var getStudentsUseCase: GetStudentsUseCase

    private var studentList = listOf(
        Student(&quot;Max&quot;, &quot;122d&quot;),
        Student(&quot;Steven&quot;, &quot;012s&quot;)
    )

    @Before
    fun setUp() {
        MockitoAnnotations.initMocks(this)
        viewModel = StudentViewModel(getStudentsUseCase)
    }

    @Test
    fun getStudentsSuccess() = runTest {
        Mockito.`when`(getStudentsUseCase.execute()).thenReturn(Result.success(studentList))

        viewModel.getStudents()
        val value = viewModel.studentLD.getOrAwaitValueTest()
        assertEquals(value, studentList)
    }
}
</code></pre>
<p>What Am I doing wrong? I also have a class for LiveDataTest with the method getOrAwaitValueTest() defined in there. Thank you in advance</p>
<p>Edit: Also, the getOrAwaitValueTest() method is defined here as follow:</p>
<pre><code>@VisibleForTesting(otherwise = VisibleForTesting.NONE)
fun &lt;T&gt; LiveData&lt;T&gt;.getOrAwaitValueTest(
    time: Long = 2,
    timeUnit: TimeUnit = TimeUnit.SECONDS,
    afterObserve: () -&gt; Unit = {}
): T {
    var data: T? = null
    val latch = CountDownLatch(1)
    val observer = object : Observer&lt;T&gt; {
        override fun onChanged(o: T?) {
            data = o
            latch.countDown()
            this@getOrAwaitValueTest.removeObserver(this)
        }
    }
    this.observeForever(observer)

    try {
        afterObserve.invoke()

        // Don't wait indefinitely if the LiveData is not set.
        if (!latch.await(time, timeUnit)) {
            throw TimeoutException(&quot;LiveData value was never set.&quot;)
        }

    } finally {
        this.removeObserver(observer)
    }

    @Suppress(&quot;UNCHECKED_CAST&quot;)
    return data as T
}
</code></pre>
",https://stackoverflow.com/questions/73292145/android-unit-testing-kotlin-livedata-value-was-never-set,"['android', 'android-studio', 'unit-testing', 'kotlin', 'junit']",2507,True,1,1
Unit testing void function in Swift,"<p>I am new to unit testing. I am using MVVM in my project. I also use RxSwift to pass data or communicate between view and ViewModel. I don't understand how I can write unit tests in my case. Any suggestions are appreciable. I really appreciate any help you can provide.</p>
<pre><code>class MovieListViewModel: ViewModel {
       private let moviesSubject: PublishSubject&lt;[Movie]&gt; = PublishSubject()
    private let errorSubject: PublishSubject&lt;Error&gt; = PublishSubject()
    

    public var movies: Observable&lt;[Movie]&gt; {
        return moviesSubject.asObservable()
    }
    
    public var errors: Observable&lt;Error&gt; {
        return errorSubject.asObservable()
    }
    
    init(httpMovieService: MovieApiService, cachedMovieService: LocalMovieService) {
        self.httpMovieService = httpMovieService
        self.cachedMovieService = cachedMovieService
    }
    
    func searchMovies(keyword: String, page: Int, type: String) {

        self.httpMovieService
            .searchMovies(keyword: keyword, page: page, type: type)
            .subscribe(onSuccess: { [weak self] movies in
                self?.moviesSubject.onNext(movies)
            }, onFailure: { [weak self] error in
                self?.errorSubject.onNext(error)
            }).disposed(by: disposeBag)
    }
</code></pre>
<p>Note: <code>httpMovieService.searchMovies()</code> provide a Single type object</p>
<p>Here is my MockService ..</p>
<pre><code>class MockMovieApiService: MovieApiService {
    func searchMovies(keyword: String, page: Int, type: String) -&gt; Single&lt;[Movie]&gt; {
        let posterUrl = &quot;https://m.media-amazon.com/images/M/MV5BOGE4NzU1YTAtNzA3Mi00ZTA2LTg2YmYtMDJmMThiMjlkYjg2XkEyXkFqcGdeQXVyNTgzMDMzMTg@._V1_SX300.jpg&quot;
        let movie = Movie(title: &quot;Title&quot;,
                          year: &quot;2022&quot;,
                          imdbID: &quot;tt0800369&quot;,
                          type: &quot;movie&quot;,
                          poster: posterUrl)
        let movie2 = Movie(title: &quot;Title2&quot;,
                          year: &quot;2022&quot;,
                          imdbID: &quot;tt0800368&quot;,
                          type: &quot;movie&quot;,
                          poster: posterUrl)

        return Single.just([movie, movie2])
    }
    
    func getMovieDetails(imdbId: String) -&gt; Single&lt;MovieDetails&gt; {
        let posterUrl = &quot;https://m.media-amazon.com/images/M/MV5BOGE4NzU1YTAtNzA3Mi00ZTA2LTg2YmYtMDJmMThiMjlkYjg2XkEyXkFqcGdeQXVyNTgzMDMzMTg@._V1_SX300.jpg&quot;
        let movieDetails = MovieDetails(title: &quot;Thor&quot;, year: &quot;2022&quot;, rated: &quot;PG-13&quot;, released: &quot;Nov, 2022&quot;, runtime: &quot;134 min&quot;, genre: &quot;Horror, Comedy&quot;, director: &quot;Director&quot;, writer: &quot;Writer&quot;, actors: &quot;salman khan&quot;, plot: &quot;When thor sleeps..&quot;, language: &quot;English&quot;, country: &quot;Germany&quot;, awards: &quot;Oscar&quot;, poster: posterUrl, ratings: [], metascore: &quot;5&quot;, imdbRating: &quot;4.5&quot;, imdbVotes: &quot;566&quot;, imdbID: &quot;tt1981115&quot;, type: &quot;type&quot;, dvd: &quot;dvd&quot;, boxOffice: &quot;box&quot;, production: &quot;prod&quot;, website: &quot;n/a&quot;, response: &quot;True&quot;)
        return Single.just(movieDetails)
    }
    
    
}
</code></pre>
",https://stackoverflow.com/questions/74920108/unit-testing-void-function-in-swift,"['swift', 'unit-testing', 'mvvm', 'rx-swift']",331,True,1,2
repoistory.save() getting invoked with invalid entry when unit testing,"<p>I'm using java validation API to validate fields in my Note class:</p>
<pre class=""lang-java prettyprint-override""><code>@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = &quot;note&quot;)
public class Note {

    @Id
    @Column(name = &quot;id&quot;, nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = &quot;date&quot;, columnDefinition = &quot;DATE&quot;)
    private LocalDate date;

    @NotBlank(message = &quot;Enter a topic&quot;)
    @Column(name = &quot;topic&quot;)
    private String topic;

    @NotBlank(message = &quot;Content can't be empty&quot;)
    @Column(name = &quot;content&quot;)
    private String content;

    @Column(name = &quot;type&quot;)
    private NoteType noteType;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinColumn(name = &quot;user_id&quot;)
    @JsonIgnore
    private User user;
}
</code></pre>
<p>NoteService:</p>
<pre class=""lang-java prettyprint-override""><code>@Service
@AllArgsConstructor
public class NoteService {

    @Autowired
    private NoteRepository noteRepository;

    @Autowired
    private UserRepository userRepository;


    public void addNote(@Valid Note note) {
        note.setUser(getLoggedInUser());
        if (validateNote(note)) {
            noteRepository.save(note);
        }
    }

    public List&lt;Note&gt; getNotes() {
        return getLoggedInUser().getNotes();
    }

    public Note editNote(Note newNote, Long id) {
        noteRepository.editNoteById(newNote, id);
        return newNote;
    }

    public List&lt;Note&gt; getNotesByTopic(String topic) {
        List&lt;Note&gt; notes = noteRepository.getNotesByTopicAndUser(topic, getLoggedInUser());
        return notes;
    }

    public boolean validateNote(Note note) {
        return  validateNoteType(note.getNoteType())
                &amp;&amp; note.getDate() != null;
    }

    public boolean validateNoteType(NoteType type) {
        return type.equals(NoteType.NOTE)
                || type.equals(NoteType.SKILL);
    }

    public User getLoggedInUser() {
        return userRepository.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName());
    }
}
</code></pre>
<p>Test:</p>
<pre class=""lang-java prettyprint-override""><code>@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
class NoteServiceTest {

    @Mock
    private NoteRepository noteRepositoryMock;
    @Mock
    private UserRepository userRepositoryMock;
    @Mock
    SecurityContext mockSecurityContext;
    @Mock
    Authentication authentication;
    private NoteService noteService;

    @BeforeEach
    void setUp() {
        noteService = new NoteService(noteRepositoryMock, userRepositoryMock);
        Mockito.when(mockSecurityContext.getAuthentication()).thenReturn(authentication);
        SecurityContextHolder.setContext(mockSecurityContext);
    }

    @Test
    void shouldAddNote() {
        LocalDate date = LocalDate.now();
        Note note = new Note(0L, date, &quot;test&quot;, &quot;&quot;, NoteType.NOTE, null);
        noteService.addNote(note);
        Mockito.verify(noteRepositoryMock).save(note);
    }
}
</code></pre>
<p>The field user in the Note class is annotated with @NotNull and I'm passing a null user to this note but the note is still getting saved. Same thing when I pass an empty string. Any idea why that is happening? I'm new to unit testing</p>
",https://stackoverflow.com/questions/71233788/repoistory-save-getting-invoked-with-invalid-entry-when-unit-testing,"['java', 'unit-testing', 'validation', 'mockito']",220,False,1,3
How to test public functions in Typescript with react-testing-library?,"<p>I'm having below setup in my project, whenever I extends the httpService and use the 'this.instance' in any service I'm getting the error.</p>
<p>If I use axios.get directly without any interceptors in my service files its working fine.</p>
<p>Im new to the unit testing and badly stuck with this. Please share your comments below. It'll be really helpful.</p>
<p>httpClient.ts</p>
<pre><code> import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
 import { DEFAULT_HEADERS, HOST } from './ApiHelper';
    
    export abstract class HttpService {
      protected readonly instance: AxiosInstance;
    
      public constructor(requestConfig: AxiosRequestConfig) {
        this.instance = axios.create(requestConfig);
    
        this.instance.interceptors.request.use((request) =&gt; {
          request.baseURL = HOST;
          request.headers = { ...DEFAULT_HEADERS };
          return request;
        });
    
        this.instance.interceptors.response.use(
          (response) =&gt;
            response,
          (error) =&gt;
            new Promise((resolve, reject) =&gt; {
              reject(error.response);
            }),
        );
      }
    }
    
    export default HttpService;
</code></pre>
<p>someService.ts</p>
<pre><code>    import HttpService from './HttpService';
    
    const warningListUrl = 'some/url';
    
    class SomeService extends HttpService {
      public constructor() {
        super({
        });
      }
    
      public async getSomething(params: any) {
        this.instance({
          method: 'GET',
          url: warningListUrl,
          params,
        }).then((res) =&gt;
          res.data);
      }
    }

export default SomeService;
</code></pre>
<p>ReactComponent.tsx</p>
<pre><code>const fetchList = async () =&gt; {
    try {
      setIsLoading(true);
      const someService = new SomeService();
      const response: any = await someService.getSomething({});
      setWarnings(response.content);
      setTotalPages(response.totalPages);
    } catch (error) {
      console.log(error);
    } finally { setIsLoading(false); }
  };

  useEffect(() =&gt; {
    fetchList();
  }, []);
</code></pre>
<p>ReactComponent.test.tsx</p>
<pre><code>jest.mock('../../services/SomeService');
const someService = new SomeService();


describe('page tests', () =&gt; {
  test('page renders without crashing', async () =&gt; {
    (someService.getWarningList as jest.Mock).mockResolvedValue(someMatchingData);
    await act(async () =&gt; {
      render(&lt;ReactComponent /&gt;);
    });
    const text = screen.getByText('Warning 1');
    expect(text).toBeInTheDocument();
  });
}
</code></pre>
<p>Error:</p>
<pre><code>TestingLibraryElementError: Unable to find an element with the text: Warning 1. 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.

render(&lt;Warning /&gt;);
});
-&gt; const text = screen.getByText('Warning 1');
 expect(text).toBeInTheDocument();
});
</code></pre>
",https://stackoverflow.com/questions/72767700/how-to-test-public-functions-in-typescript-with-react-testing-library,"['reactjs', 'typescript', 'axios', 'jestjs', 'react-testing-library']",571,True,1,2
How to mock material-table?,"<p>I am new to React Unit Testing.
I am supposed to create unit tests for a file that uses an API to fetch data and then display it in MaterialTable and uses TablePagination (from Material UI) for pages.</p>
<p>Here's the code for reference:</p>
<pre><code>import React, { useState, useEffect } from 'react';
import clsx from 'clsx';
import { useHistory } from 'react-router-dom';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/styles';
import MaterialTable from 'material-table';
import {
    MuiThemeProvider,
    createTheme,
    TablePagination,
} from '@material-ui/core';
import UserModel from '../../../models/UserModel';

const useStyles = makeStyles((theme) =&gt; ({
    root: {},
    content: {
        padding: 0,
    },
    inner: {
        minWidth: 800,
    },
    statusContainer: {
        display: 'flex',
        alignItems: 'center',
    },
    status: {
        marginRight: theme.spacing(1),
    },
    actions: {
        justifyContent: 'flex-end',
    },
}));

const VehicleTypesData = (props) =&gt; {
    const [vehicleTypesData, setVehicleTypesData] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    var [paramObj, setParamObj] = useState({});
    const [params, setParams] = useState({
        page: 1,
        offset: 0,
    });

    const numberOfVehicleTypes = Object.keys(vehicleTypesData).length;
    const ROWS_PER_PAGE = 10;

    const columnDescription = [
        { title: 'Name', field: 'name' },
        {
            title: 'Capacity (Volume)',
            field: 'capacity',
            type: 'numeric',
            align: 'left',
            emptyValue: () =&gt; &lt;&gt;-&lt;/&gt;,
        },
        { title: 'Weight', field: 'weight' },
    ];

    const fetchDataFromAPI = async (paramObj, newOffset, newPage) =&gt; {
        setIsLoading(true);
        UserModel.getInstance().getVehicleTypes(
            paramObj,
            async (data) =&gt; {
                let vehicleTypesArray = [];
                await data.forEach((obj) =&gt; {
                    vehicleTypesArray.push({
                        id: obj.id,
                        title: obj.name,
                        capacity: obj.capacity,
                        weight: obj.weight,
                    });
                });
                setVehicleTypesData(vehicleTypesArray);
                setIsLoading(false);
                newPage &amp;&amp; setParams({ ...params, offset: newOffset, page: newPage });
            },
            (err) =&gt; {
                setIsLoading(false);
            },
        );
    };

    const handleNextPage = async () =&gt; {
        const newOffset = params.offset + 20;
        let newParamObj = { ...paramObj };
        newParamObj = { ...newParamObj, offset: newOffset };
        setParamObj(newParamObj);
        const newPage = params.page + 1;
        setIsLoading(true);
        fetchDataFromAPI(newParamObj, newOffset, newPage);
    };

    const handlePreviousPage = async () =&gt; {
        if (params.offset &gt; 0) {
            const newOffset = params.offset - 20;
            var newParamObj = { ...paramObj, offset: newOffset };
            newParamObj = { ...newParamObj, page: newPage };
            setParamObj(newParamObj);
            const newPage = params.page - 1;
            setIsLoading(true);
            fetchDataFromAPI(newParamObj, newOffset, newPage);
        }
    };

    const filterChange = (data) =&gt; {
        if (params.page !== 1) {
            setParams({
                ...params,
                page: 1,
                offset: 0,
            });
        }
        let paramObj = {};
        let newParamobj = { ...paramObj };
        data.forEach((x) =&gt; {
            newParamobj = {
                ...newParamobj,
                [x.column.searchKey]: x.value.toLowerCase(),
            };
        });
        setIsLoading(true);
        setParamObj(newParamobj);
        fetchDataFromAPI(newParamobj);
    };

    useEffect(() =&gt; {
        fetchDataFromAPI();
    }, []);

    let history = useHistory();
    const classes = useStyles();

    const { className, ...rest } = props;

    const theme = createTheme({
        typography: {
            fontFamily: 'Nunito Sans, Roboto, sans-serif',
        },
    });

    return (
        &lt;MuiThemeProvider theme={theme}&gt;
            &lt;MaterialTable
                title=&quot;Vehicle Types&quot;
                columns={columnDescription}
                data={vehicleTypesData}
                isLoading={isLoading}
                onFilterChange={filterChange}
                className={clsx(classes.root, className)}
                editable={
                    {
                    }
                }
                options={{
                    search: false,
                    paging: false,
                    debounceInterval: 1000,
                    maxBodyHeight: 'calc(100vh - 285px)',
                    headerStyle: {
                        paddingTop: 0,
                        paddingBottom: 0,
                    },
                }}
                actions={[
                    {
                        icon: 'add',
                        tooltip: 'Add Vehicle Type',
                        isFreeAction: true,
                        onClick: () =&gt; {
                        },
                    },
                    {
                        icon: 'edit',
                        tooltip: 'Edit',
                        onClick: (event, data) =&gt; {
                        },
                    },
                    {
                        icon: 'delete',
                        tooltip: 'Delete',
                        onClick: (event, data) =&gt; {
                    },
                    },
                ]}
            /&gt;
            &lt;TablePagination
                component=&quot;div&quot;
                count={-1}
                rowsPerPage={ROWS_PER_PAGE}
                rowsPerPageOptions={[ROWS_PER_PAGE]}
                page={params.page}
                backIconButtonProps={{
                    'aria-label': 'Previous Page',
                    onClick: handlePreviousPage,
                    disabled: isLoading || params.page === 1,
                }}
                nextIconButtonProps={{
                    'aria-label': 'Next Page',
                    onClick: handleNextPage,
                    disabled: isLoading || numberOfVehicleTypes &lt;= ROWS_PER_PAGE,
                }}
                labelDisplayedRows={() =&gt; {
                    return `Page ${params.page}`;
                }}
            /&gt;
        &lt;/MuiThemeProvider&gt;
    );
};

VehicleTypesData.propTypes = {
    className: PropTypes.string,
};

export default VehicleTypesData;


</code></pre>
<p>Fairly simple component, here's what I have got so far, which is just an attempt at Mocking the API fetch</p>
<pre><code>import { render, screen } from '@testing-library/react';
import { async } from 'validate.js';
import VehicleTypesData from './component/index';

describe('Vehicle Types Component', () =&gt; {
    test('renders table data if request succeeds', async () =&gt; {
        window.fetch = jest.fn();
        window.fetch.mockResolvedValueOnce({
            json: async () =&gt; [
                { id: '1', name: 'Pickup', capacity: '1000', weight: '3000 kg' },
            ],
        });

        render(&lt;VehicleTypesData /&gt;);
    });
});

</code></pre>
",https://stackoverflow.com/questions/73211715/how-to-mock-material-table,"['reactjs', 'unit-testing', 'material-ui', 'automated-tests', 'material-table']",315,False,1,0
flutter unit testing stubbed method returns null,"<p>I,m unit testing flutter class using mockito. I stubbed one method using 'when()' but it returns null. is there something wrong in my testing?. I have used freezed union to generate Result class. My Repository is an abstract class</p>
<p>this is my test class</p>
<pre><code>class MockRepository extends Mock implements Repository {}

void main() {
  late CryptoUseCases useCases;
  late MockRepository repository;

  final Result&lt;List&lt;Crypto&gt;, Exception&gt; data = const Result.success([
    Crypto(
      id: 1,
      name: 'Bitcoin',
      symbol: 'BTC',
      priceUsd: 4000,
      availableSupply: 879787908,
      logo: '',
      volumeUsd24h: 786876,
      totalSupply: 876587,
      marketCapUsd: 698,
      maxSupply: 867987,
      rank: 1,
    ),
    Crypto(
      id: 3,
      name: 'Euthereum',
      symbol: 'ETH',
      priceUsd: 134,
      availableSupply: 879787908,
      logo: '',
      volumeUsd24h: 786876,
      totalSupply: 876587,
      marketCapUsd: 698,
      maxSupply: 867987,
      rank: 2,
    ),
  ]);
  setUp(() {
    repository = MockRepository();
    useCases = CryptoUseCases(repository);
  });

  test('getCryptos return a list of crypto', () async {
    //arrange
    when(repository.getCryptos()).thenAnswer((_) async =&gt; data);

    //act

    final result = await useCases.getCryptos();

    //assert
    expect(result, equals(data));
    verify(repository.getCryptos()).called(1);
    verifyNoMoreInteractions(repository);
  });
}
</code></pre>
<p>this is my class</p>
<pre><code>class CryptoUseCases {
  final Repository repository;

  CryptoUseCases(this.repository);

  Future&lt;Result&lt;List&lt;Crypto&gt;, Exception&gt;&gt; getCryptos() async {
    final result = await repository.getCryptos();
    result.when(success: (data) {
      return Result.success(data);
    }, error: (e) {
      return Result.error(e);
    });
    return Result.error(Exception());
  }
}
</code></pre>
<p>i'm using freezed here. is that a problem?</p>
<p>this is the error</p>
<pre><code>type 'Null' is not a subtype of type 'Future&lt;Result&lt;List&lt;Crypto&gt;, Exception&gt;&gt;'
package:crypto_app/src/domain/repositories/repository.dart 6:43  MockRepository.getCryptos
test\use_cases_test.dart 51:21                                   main.&lt;fn&gt;
test\use_cases_test.dart 49:46 
</code></pre>
",https://stackoverflow.com/questions/71510631/flutter-unit-testing-stubbed-method-returns-null,"['flutter', 'flutter-test', 'flutter-freezed']",460,True,0,1
react testing jest - cannot set properties of null (setting innerhtml),"<p>I am new to unit testing. I keep getting this error shows up and I'm not sure why. The other cases I have seen aren't related to jest. So, what is the solution for me? Is it within the component or have i just written the test wrong?</p>
<p>This is the fetch call in the component</p>
<pre><code>const [data, setData] = useState(null);
  const [isLoading, setLoading] = useState(false);

  useEffect(() =&gt; {
    setLoading(true)


const fetchList = async () =&gt; {    
  
  const newList  =  await fetch(&quot;https://api.github.com/search/repositories?q=created:%3E2017-01-10&amp;sort=stars&amp;order=desc&quot;)
    .then((res) =&gt; res.json())
      .then((data) =&gt; {
        setData(data)
        setLoading(false)
      })
    }
    fetchList()
  }, [500]);

  if (isLoading) return &lt;p className='text-white text-3xl text-center'&gt;Loading...&lt;/p&gt;
  if (!data) return &lt;p className='text-white text-3xl text-center'&gt;No profile data&lt;/p&gt;
</code></pre>
<p>This is the test</p>
<pre><code>import RepoList from '../components/RepoList'
import {render, screen, act} from '@testing-library/react'

import '@testing-library/jest-dom/extend-expect'


global.fetch = jest.fn(()=&gt; 
Promise.resolve({
    json: () =&gt; 
    Promise.resolve({
        name : &quot;name&quot; , 
        value: &quot;Repo Name&quot;
    })
})
);

describe(&quot;RepoList&quot;, ()=&gt; {
    it(&quot;loads the data on click&quot;, async () =&gt; {
      await act( async () =&gt; render(&lt;RepoList/&gt;))
        expect(screen.getByText(&quot;Repo Name&quot;)).toBeInTheDocument()
    })
});
</code></pre>
",https://stackoverflow.com/questions/71093028/react-testing-jest-cannot-set-properties-of-null-setting-innerhtml,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",529,False,0,0
How to mock settings in Django Unit testing,"<p>I am new to Django Unit testing and am trying to write unit test for a simple function which is like below:</p>
<pre><code>utils.py
#some import statements
from django.conf import settings

if platform.system() == 'Linux':
    cx_Oracle.init_oracle_client(lib_dir=settings.GAP_DB_LIB_DIR)
else:
    cx_Oracle.init_oracle_client(lib_dir=settings.LOCAL_DB_LIB_DIR)
db_password = settings.DB_PASS
db_user = settings.DB_USER
db_connection_dsn = settings.DB_CONNECTION_DSN

def project(repo):
    pieces = parse.urlsplit(repo)
    return pieces.path.rstrip('/').split('/')[-1]
</code></pre>
<p>I am writing unit tests in test.py fie as below</p>
<pre><code>from django.test import TestCase
from common import utils
from utils import project
from django.test import override_settings

# Create your tests here.
class UtilsTest(TestCase):
    def setUp(self):
        self.repo = &quot;http://test/testrepo&quot;

    @override_settings(LOCAL_DB_LIB_DIR=&quot;c:/testdir&quot;)
    def test_project(self):
        response = utils.project(self.repo)
        self.assertEqual(response,&quot;testrepo&quot;)
</code></pre>
<p>When I run tests am getting below error:
AttributeError: 'Settings' object has no attribute 'LOCAL_DB_LIB_DIR'
Please help me where I am doing wrong and correct my coding. Thanks in advance.</p>
",https://stackoverflow.com/questions/74150869/how-to-mock-settings-in-django-unit-testing,"['python', 'django', 'django-unittest']",47,False,0,0
Govmomi Rest/Vapi API does not support ESX() simulators to create Rest clients?,"<p>I was doing some unit testing with vSphere Govmomi/vapi REST client used to interact with V Center.</p>
<pre><code>var insecure bool = true
type RestClient struct {
 url *url.URL
 restClient *rest.Client
}

func (c *RestClient) GetRestClient(ctx context.Context) (*rest.Client, error){
 soapClient := soap.NewClient(c.url, insecure)
 vim25Client, err := vim25.NewClient(ctx, soapClient)
 if err != nil {
  return nil, err
 }
 c.restClient = rest.NewClient(vim25Client)
 err = c.restClient.Login(ctx, c.url.User)
 if err != nil {
  return nil, err
 }
 return c.restClient, nil
}
</code></pre>
<p>I used simulator.ESX() to simulate the model.</p>
<pre><code>func TestGetRestClient(t *testing.T){
 ctx := context.Background()
 model := simulator.ESX()
 defer model.Remove()
 err := model.Create()
 if err != nil {
  t.Fatal(err)
 }
 server := model.Service.NewServer()
 defer server.Close()
 url := server.URL
 var client RestClient = RestClient{url: url,}
 _, err := client.GetRestClient(ctx)
 if err != nil {
  t.Errorf(&quot;err = %v&quot;, err)
  return
 }
}
</code></pre>
<p>But after creating the rest client and trying to login(), I get</p>
<pre><code>error= POST http://127.0.0.1:36655/rest/com/vmware/cis/session: 404 Not Found
</code></pre>
<p>Am I doing something wrong? Am I supposed to use a different simulator for vapi/rest clients in vmware's govmomi. Any help would be highly appreciated</p>
",https://stackoverflow.com/questions/72815309/govmomi-rest-vapi-api-does-not-support-esx-simulators-to-create-rest-clients,"['go', 'vmware', 'vsphere', 'govmomi']",145,True,0,1
unable to resolve the flock error encountered when executing,"<p>encountered below error when executing the automated unit testing in cpp that invoked the perl interpreter and calls the perl subroutine
this is the code snippet :-</p>
<pre><code>sub perlflock {
my $xsptr = shift;
my $self = shift;
my ($file, $use_locking) = @_;
logcroak &quot;not a reference&quot; unless ref($self);
logcroak &quot;wrong argument number&quot; unless @_ == 2;    # No @foo in arglist
local *FILE;
if ($use_locking) {
    open(FILE, &quot;&gt;&gt;&quot;, $file) || logcroak &quot;can't write into $file: $!&quot;;
    unless (1) {
        logcarp
          &quot;Storable::lock_store: fcntl/flock emulation broken on $^O&quot;;
        return undef;
    }
    flock(FILE, LOCK_SH | LOCK_NB) ||
      logcroak &quot;can't get exclusive lock on $file: $!&quot;;
    truncate FILE, 0;
    # Unlocking will happen when FILE is closed
} else {
    open(FILE, &quot;&gt;&quot;, $file) || logcroak &quot;can't create $file: $!&quot;;
}
</code></pre>
<p>frl-plugin:perlscript: ERROR: 'flock' trapped by operation mask at /usr/lib64/perl5/vendor_perl/Storable.pm line 271.
Compilation failed in require at /usr/share/perl5/vendor_perl/Const/Fast.pm line 15.
Compilation failed in require.
BEGIN failed--compilation aborted.</p>
",https://stackoverflow.com/questions/72869483/unable-to-resolve-the-flock-error-encountered-when-executing,['perl'],64,False,0,1
How to unit test with complex object,"<p>For unit testing, I need to create a fairly complex object, is there an easy way to approach this problem? This is the object I'm looking to create: <code>StreamingQueryListener.QueryProgressEvent</code> - <a href=""https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/streaming/StreamingQueryListener.QueryProgressEvent.html"" rel=""nofollow noreferrer"">Documentation</a></p>
<p>I read mockito can work, but I don't think it handles this object in particular. I have a json string I'd like to create the <code>QueryProgressEvent</code> object with. Any guidance is appreciated!</p>
",https://stackoverflow.com/questions/72793545/how-to-unit-test-with-complex-object,"['java', 'scala', 'apache-spark', 'mockito', 'spark-streaming']",81,False,0,0
Mocking of methods present the in the main method,"<p>I am new to Unit testing and using Mockito framework.</p>
<p>I have a Java class and have the main() method in it. In my Main() method I have several other methods that I need to Unit test.</p>
<p><strong>This is my class to test</strong></p>
<pre><code>public class client{
  public static void main(String[] args) {
         Ip ip  =  createIpEvent();
   .
   .
   .
   }
   private static Ip createIpEvent(){
    Ip ip = new Ip();
    ip.setters(); // various setters
    return ip;
    }
 }
</code></pre>
<p><strong>This is my Test class that I am making.</strong></p>
<pre><code>public class clientTest{
  
 client clientMock = mock(client.class);
 
 @Test
 public void testCreateIpEvent(){
  Ip ip = new Ip();

  //setters....
  try(MockedStatic&lt;client&gt; utils = Mockito.mockStatic(client.class)){
        utils.when(() -&gt; client.main()....)
    //here I am only able to access the main() method and not the method createIpEvent()

 }


}
</code></pre>
<p>Please some one help me out on this.</p>
",https://stackoverflow.com/questions/70558128/mocking-of-methods-present-the-in-the-main-method,"['java', 'spring', 'oop', 'mocking', 'powermockito']",55,False,0,1
How do I detect if a port is currently in use? (c#),"<p>I have been working on unit testing my network library, which involves starting up and closing many network connections (client and server both running on the same machine). I'm trying to wait for the port to become available after closing a previous socket, before opening a new connection.</p>
<p>I've tried this code, but it doesn't seem to work for me.</p>
<pre class=""lang-cs prettyprint-override""><code>
public static int WaitForPort(int port)
{
    IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
    
    while (ipGlobalProperties.GetActiveTcpConnections().Where(pr =&gt; pr.LocalEndPoint.Port == port).Any()) 
            ;
    
    return port;
}
</code></pre>
<p>Any suggestions?</p>
",https://stackoverflow.com/questions/74481987/how-do-i-detect-if-a-port-is-currently-in-use-c,"['c#', 'unit-testing', 'networking']",25,False,0,0
How can we write the test cases in Moqui using Junit at beginners level?,"<p>I want to write test cases in the Moqui framework using Junit please can I get a brief idea how to write test cases in the Moqui framework using JUnit?</p>
<p>I explored the existing components to find out the example of unit testing but I didn't find examples to help me that how to write the test cases in the moqui.</p>
",https://stackoverflow.com/questions/74303972/how-can-we-write-the-test-cases-in-moqui-using-junit-at-beginners-level,"['unit-testing', 'junit4', 'moqui']",31,False,0,0
How to compare two objects but skip values and just compare keys and key types?,"<p>I want to write unit testing using Jest for my Node.js functions and need to test if response object has some specific keys or not. Something like this:</p>
<pre><code>expect(await mokChannelsService.getChannel(inputDto)).toEqualKeys(outputDto);

// Or just a normal function

const result = await mokChannelsService.getChannel(inputDto);
const equal = isEqualKeys(result, outputDto);
</code></pre>
<p>This <code>toEqualKeys</code> function should check equality just for keys not values. And these objects are not instances of a class. for example these two objects should be equal:</p>
<pre><code>const object1 = {
  names: {
    firstName: '',
    lastName: '',
  },
  phone: 1,
};

const object2 = {
  names: {
    firstName: 'John',
    lastName: 'Due',
  },
  phone: 1234567890,
};

const object3 = {
  names: {
    firstName: 'John',
    lastName: 12,
  },
  mobile: '12345',
};

const result1 = toEqualKeys(object1, object2); // true
const result1 = toEqualKeys(object1, object3); // false
</code></pre>
<p>Is there any NPM packages available for this?</p>
",https://stackoverflow.com/questions/73685891/how-to-compare-two-objects-but-skip-values-and-just-compare-keys-and-key-types,"['javascript', 'node.js', 'jestjs']",176,True,-1,1
How to overload / override static method to return an other value?,"<p>Basically I'm trying to mock a static class for unit testing.</p>
<p>Example:</p>
<pre><code>class Library {
    public static boolean isActivated() {
        return false;
    }
}

class Test {
    public static void main(String[] args) {
        // some magic
        
        if (Library.isActivated()) {
            System.out.println(&quot;'some magic' works!&quot;);
        } else {
            System.out.println(&quot;fail&quot;);
        }
    }
}
</code></pre>
<p>What would <code>some magic</code> need to be, to make <code>Library.isActivated()</code> return <code>true</code>.</p>
<p>Is there some special way to do this without changing the source code of <code>Library</code>?</p>
<p>As far as I know this is not possible in java but I'm not very familiar with Reflection I thought this might be possible with it.</p>
",https://stackoverflow.com/questions/70776722/how-to-overload-override-static-method-to-return-an-other-value,"['java', 'overriding', 'overloading', 'static-methods']",1022,True,0,2
How to create phpunit testcase for file upload functionality in laravel,"<p><strong>Controller.php</strong></p>
<pre><code>public function uploadDocument($request,$profileId)
{
   $s3Bucket = 's3.' . $request-&gt;input('fileType');
   $file = $request-&gt;file('document');
   $name = $file-&gt;hashName();
}
</code></pre>
<p><strong>Testcase.php</strong></p>
<pre><code>
use Illuminate\Http\Request;
use Mockery;
use Illuminate\Http\UploadedFile;
use PHPUnit\Framework\TestCase;

public function testUploadDocumentSuccess()
{
   $test = new \Illuminate\Http\UploadedFile(public_path('laravel-test-img.jpg'), 'laravel-test-img.jpg', 'image/jpg', 
            filesize(public_path() . '/laravel-test-img.jpg'), true);

   $request = new Request([
      'fileType' =&gt; 'profile',    
      'document' =&gt; $test
   ]);
    
   $response = $this-&gt;documentService-&gt;uploadDocument($request, 1);
   $this-&gt;assertIsArray($response);
}

</code></pre>
<p>For doing unit testing, using mock object to call the every class. Not calling endpoint directly by passing route name.</p>
<p><strong>Query</strong></p>
<p>Always getting null from <code>$request-&gt;file('docuemnt')</code> when accessing file data by request object passing from testcase function.</p>
<p>I have tried many ways and find out the solution on web but most of all gives solution by calling the route personally like</p>
<pre><code>$response = $this-&gt;action(
   'POST',
   'FileStorageController@store',
   $values,
   ['file' =&gt; $uploadedFile]
);
</code></pre>
",https://stackoverflow.com/questions/72948674/how-to-create-phpunit-testcase-for-file-upload-functionality-in-laravel,"['php', 'laravel', 'phpunit', 'testcase', 'mockery']",295,True,-1,1
How do I test a function inside a component by using jest?,"<p>I have a unit testing coverage report for a component MyCheckbox.js.</p>
<p><a href=""https://i.stack.imgur.com/VC5hK.png"" rel=""nofollow noreferrer"">coverage</a></p>
<p>How do I test the onCheckmarkPress() function in MyCheckbox.js?</p>
<p>Here is the implementation of MyCheckbox.js:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>import * as React from 'react';

import { Pressable, StyleSheet } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useState } from 'react';

/**
 *
 * @param {() =&gt; void} props.onUpdate called when checkbox is pressed
 * @return {JSX.Element}
 * @constructor
 */
const MyCheckbox = (props) =&gt; {
  const [checked, onChange] = useState(false);
  function onCheckmarkPress() {
    onChange((prev) =&gt; {
      let checked = !prev;
      props.onUpdate(checked);
      return checked;
    });
  }

  return (
    &lt;Pressable
      style={[styles.checkboxBase, checked &amp;&amp; styles.checkboxChecked]}
      onPress={onCheckmarkPress}
    &gt;
      {checked &amp;&amp; &lt;Ionicons name=""checkmark"" size={24} color=""black"" /&gt;}
    &lt;/Pressable&gt;
  );
};

const styles = StyleSheet.create({
  checkboxBase: {
    width: 35,
    height: 35,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 4,
    borderWidth: 2,
    borderColor: 'white',
    backgroundColor: 'white',
  },

  checkboxChecked: {
    backgroundColor: '#C4C4C4',
  },
});

export default MyCheckbox;</code></pre>
</div>
</div>
</p>
<p>This is how I attempt the test case:</p>
<pre class=""lang-js prettyprint-override""><code>import React from 'react'
import MyCheckbox from '../MyCheckbox';
import {fireEvent, render, screen} from &quot;@testing-library/react-native&quot;;
import '@testing-library/jest-dom';

it(&quot;works&quot;, () =&gt; {
    const onUpdateMock = jest.fn();
    render(&lt;MyCheckbox onUpdate={onUpdateMock} /&gt;);

    expect(onUpdateMock).toHaveBeenCalledTimes(0);
    expect(screen.queryByTestId(&quot;checkIcon&quot;)).toBeNull();

    const pressable = screen.getByRole(&quot;pressable&quot;);
    fireEvent.press(pressable);

    expect(onUpdateMock).toHaveBeenCalledTimes(1);
    expect(screen.queryByTestId(&quot;checkIcon&quot;)).toBeInTheDocument(); // check that the icon is rendered
});
</code></pre>
<p>However, I am getting the error &quot;Unable to find an element with accessibilityRole: pressable&quot;. And will this cover the red lines marked in the coverage report?</p>
",https://stackoverflow.com/questions/74022933/how-do-i-test-a-function-inside-a-component-by-using-jest,"['javascript', 'react-native', 'unit-testing', 'jestjs']",788,True,0,1
How to mock knex using jest with NestJS,"<p>I just got started with unit testing and successfully mocked prisma database and other providers for my service just stuck with knex database don't know how to provide knex module
for mocking knex query</p>
<p><strong>app.service.spec.ts</strong></p>
<pre><code>import { getKnexConnectionToken, InjectKnex, KnexModule } from 'nestjs-knex'

beforeEach(async () =&gt; { 
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        KnexModule.forRoot({
          config: {
            client: 'pg',
            useNullAsDefault: true,
            connection: process.env.DATABASE_URL,
            pool: { min: 150, max: 150 },
            searchPath: ['public'],
          },
        }),
      ],
      providers: [
        AppService,
        {//what to provide for knex &amp; value
        },
        {
          provide: PrismaService,
          useValue: dbServiceMock,
        },
        {
          provide: HttpService,
          useValue: {},
        },
        {
          provide: ModuleRef,
          useValue: {
            get: jest.fn(function () {
              return this;
            }),
            generateFilters: jest.fn(() =&gt; []),
            getColumnDatatypes: jest.fn(() =&gt; ({})),
          },
        },
})
</code></pre>
<p>what should I provide for knex.
By importing the module knexModule.forRoot got rid of the error but I don't want to access the database</p>
<p><strong>app.service.ts</strong></p>
<pre><code>import { InjectKnex, Knex } from 'nestjs-knex';

constructor(
    private readonly moduleRef: ModuleRef,
    private readonly db: PrismaService,
    @InjectKnex() private readonly query: Knex,
    private httpService: HttpService,
  ) {}
</code></pre>
",https://stackoverflow.com/questions/74262968/how-to-mock-knex-using-jest-with-nestjs,"['nestjs', 'knex.js', 'ts-jest']",227,False,0,0
Customizing Angular ng g c to create multiple spec files,"<p>I'd like to generate two spec files for each component, one to test the TS file and one for testing the HTML file (some might say unit testing and integration testing)</p>
<p>So something like this:</p>
<pre><code>components
    └──credit-card
        ├── credit-card.component.css
        ├── credit-card.component.html
        ├── credit-card.component.spec.ts
        ├── credit-card.component.unit.spec.ts
        └── credit-card.component.ts
</code></pre>
<p>Generally, <code>ng g c</code> will create a <code>spec</code> file by default, but I'm interested in modifying the command somehow to create multiple spec files by default. Is this possible?</p>
",https://stackoverflow.com/questions/74633703/customizing-angular-ng-g-c-to-create-multiple-spec-files,"['angular', 'angular-cli']",301,True,0,1
What does TypeError: stream.listeeners is not a function mean?,"<p>I am unit testing firebase onRequest cloud function with jest</p>
<p>This is the test code:</p>
<pre><code>const index = require ('./index')

describe ('test function', () =&gt; {
  it('positive case', async () =&gt; {
    let req = { &quot;usn&quot;: &quot;cmu2010&quot;}
    let res = { &quot;response&quot;: &quot;hi cmu&quot;}
    index.myCloudFunction(req, res)
  });
});
</code></pre>
<p>This is my index.js file:</p>
<pre><code>const admin = require('firebase-admin')
admin.initializeApp();
const importFile = require('./myCloudFunction')
exports.myCloudFunction = importFile.myCloudFunction
</code></pre>
<p>Inside myCloudFunction.js, I have my cloud function written in express</p>
<pre><code>const functions = require (&quot;firebase-functions&quot;)
myCloudFunction.post(&quot;/&quot;, async(request, response) =&gt; {
  // 
})
exports.myCloudFunction = functions.https.onRequest(myCloudFunction)
</code></pre>
<p>I am getting TypeError: stream.listeners is not a function
What does it mean and where am I going wrong? I have searched for this error but there aren't any good explanation available.</p>
",https://stackoverflow.com/questions/74770144/what-does-typeerror-stream-listeeners-is-not-a-function-mean,"['node.js', 'firebase', 'unit-testing', 'jestjs', 'google-cloud-functions']",72,False,0,0
Errors when unit testing nestjs,"<p>When unit testing the nestjs file:
yandex-ndd-api-client.controller.spec.ts
there are errors like this (many):</p>
<pre><code>  Cannot find module 'src/sync.service' from 'yandex-ndd-api-client/yandex-ndd-api-client.controller.spec.ts'
</code></pre>
<p>I'm trying to change to a relative path:</p>
<pre><code>import { SyncService } from './../../src/sync.service';
</code></pre>
<p>In the test file itself, it stops swearing, but when I do the same in the project files, the project itself gives an error when launched:</p>
<pre><code>Error: Cannot find module './../../src/sync.service'
</code></pre>
<p>In tsconfig.json:
&quot;baseUrl&quot;: &quot;./&quot;,</p>
<p>How to make friends tests with the application?</p>
",https://stackoverflow.com/questions/74194267/errors-when-unit-testing-nestjs,"['testing', 'nestjs']",118,False,0,0
How to unit test this prisma.service,"<p>I'm having trouble unit testing a <strong>prisma.service.ts</strong> file:</p>
<pre><code>import { INestApplication, Injectable } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient {
  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () =&gt; {
      await app.close();
    });
  }
}
</code></pre>
<p>The <strong>prisma.service.spec.ts</strong> I have currently looks like this:</p>
<pre><code>import { INestApplication } from '@nestjs/common';
import { NestFastifyApplication } from '@nestjs/platform-fastify';
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from './prisma.service';

const MockApp = jest.fn&lt;Partial&lt;INestApplication&gt;, []&gt;(() =&gt; ({
  close: jest.fn(),
}));

describe('PrismaService', () =&gt; {
  let service: PrismaService;
  let app: NestFastifyApplication;

  beforeEach(async () =&gt; {
    app = MockApp() as NestFastifyApplication;
    const module: TestingModule = await Test.createTestingModule({
      providers: [PrismaService],
    }).compile();

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

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

  describe('enableShutdownHooks', () =&gt; {
    it('should call $on and successfully close the app', async () =&gt; {

      const spy = jest.spyOn(PrismaService.prototype, '$on')
      .mockImplementation(async () =&gt; {
        await app.close();
      });

      await service.enableShutdownHooks(app);

      expect(spy).toBeCalledTimes(1);
      expect(app.close).toBeCalledTimes(1);
      spy.mockRestore();
    });
  });
});
</code></pre>
<p>However, this does not test line 8 of <strong>prisma.service.ts</strong>:</p>
<pre><code>await app.close();
</code></pre>
<p>because I am mocking the implementation of <strong>this.$on('beforeExit', callback)</strong>, with a copy of its original implementation.
Even if I don't mock it, <strong>app.close()</strong> never gets called.</p>
<p>Is there a way to test this line?</p>
",https://stackoverflow.com/questions/74329089/how-to-unit-test-this-prisma-service,"['typescript', 'unit-testing', 'jestjs', 'nestjs']",426,True,0,1
"How to mock wrap().assign() of MikroORM when using with NestJS, the objective is unit testing a update method","<p>I have a method like this</p>
<pre><code>const user = await this.userRepository.findOneOrFail({ id });
wrap(user).assign(userData);
await this.userRepository.flush();
return await this.readById(user.id);
</code></pre>
<p>Similar to the one available in this <a href=""https://github.com/mikro-orm/nestjs-realworld-example-app/blob/master/src/user/user.service.ts"" rel=""nofollow noreferrer"">official example</a>, the example also implements <a href=""https://github.com/mikro-orm/nestjs-realworld-example-app/blob/master/src/user/test/user.service.spec.ts"" rel=""nofollow noreferrer"">unit testing</a> for the service, but it doesn't implement a test for the update method.</p>
<p>I'd like to implement a unit test for the mentioned method, but when I try I get the following error</p>
<pre><code>(0 , core_1.wrap)(...).assign is not a function
TypeError: (0 , core_1.wrap)(...).assign is not a function
    at UserService.updateUser (C:\Users\DanielMendesSechisnk\Projects\nestjs-rest-api\src\users\user.service.ts:37:16)
    at processTicksAndRejections (node:internal/process/task_queues:95:5)
    at Object.&lt;anonymous&gt; (C:\Users\DanielMendesSechisnk\Projects\nestjs-rest-api\src\users\tests\user.service.spec.ts:89:12)
</code></pre>
<p>What should I do to fix this problem?</p>
",https://stackoverflow.com/questions/74523868/how-to-mock-wrap-assign-of-mikroorm-when-using-with-nestjs-the-objective-is,"['unit-testing', 'nestjs', 'mikro-orm']",322,True,0,2
Stubbing two methods exported from the same file using Sinon,"<p>I'm a newbie to JavaScript and need help in unit-testing my code.
There is an existing file <code>F1.js</code> whose methods I'm using in my implementation. The file looks like this:</p>
<p><strong>F1.js :</strong></p>
<pre><code>
function A({p1, p2}, callback) {

}

function B(q1, q2) {

}

module.exports = A;
module.exports.B = callbackify(B);
</code></pre>
<p>My file <code>Sol.js</code> uses these functions as,</p>
<p><strong>Sol.js:</strong></p>
<pre><code>
const A = require('/F1');
const {
  B 
} = require('/F1');


somefunction() {



   B( param1, param2, (err, result) =&gt; {
      A( {anotherParam, result}, 
         function (err, result2) {
             // do something with result2

         }
      ) 
   })

}

</code></pre>
<p>I'm trying to unit test the method <code>somefunction</code> and struggling with the stubbing. Here is how I mock the functions</p>
<p><strong>Sol_Test.js</strong></p>
<pre><code>B_stub = sinon
      .stub()
      .callsFake((param1, param2, callback) =&gt; callback(null, result1));

A_stub = sinon
      .stub()
      .callsFake(({ param1, param2 }, cb) =&gt; cb(null, result2));

return proxyquire(
   'F1' : {
        A_stub,
        B : B_stub,
   }
)
</code></pre>
<p>I'm getting the error :  <code>B is not a function</code></p>
",https://stackoverflow.com/questions/72638238/stubbing-two-methods-exported-from-the-same-file-using-sinon,"['javascript', 'node-modules', 'sinon']",102,False,0,1
Storybook axe script returns with an error: page.evaluate: TypeError: Cannot read properties of undefined (reading &#39;add&#39;),"<p>Has anyone encountered a similar issue or may have a solution?</p>
<p>We're using axe-storybook-testing to run unit testing with the following script:</p>
<pre><code>&quot;storybook:axe&quot;: &quot;npm run build-storybook &amp;&amp; axe-storybook --build-dir storybook-static --failing-impact critical --timeout 3000 &gt; a11y_log.text&quot;
</code></pre>
<p>All unit tests fail with the following error:</p>
<pre><code>   Error: page.evaluate: TypeError: Cannot read properties of undefined (reading 'add')
       at runAxe (eval at evaluate (:190:30), &lt;anonymous&gt;:2:26)
       at UtilityScript.evaluate (&lt;anonymous&gt;:192:17)
       at UtilityScript.&lt;anonymous&gt; (&lt;anonymous&gt;:1:44)
</code></pre>
<p>I was only able to find a similar issue on Github, with <em>reading 'reduce'</em>, without a solution.</p>
<p>axe package used: &quot;@chanzuckerberg/axe-storybook-testing&quot;: &quot;^5.0.0&quot;</p>
<p>Would really appreciate your help.</p>
",https://stackoverflow.com/questions/74133244/storybook-axe-script-returns-with-an-error-page-evaluate-typeerror-cannot-rea,"['unit-testing', 'vuejs2', 'storybook', 'axe']",65,False,0,0
How to write a unit test for serverless function in dynamodb using jest,"<p>I wish to write a unit test for following code but I am not sure where to start and what to mock from the code,</p>
<p>I am totally new to unit testing for dynamodb so I have zero idea where to start writing a unit test</p>
<pre><code>import { v4 as uuidv4 } from 'uuid';
import { dynamodb } from '../libs/dynamodb';
import { validate } from './validate';

export const create = (event, context, callback) =&gt; {
    const timestamp = new Date().getTime();
    const data = JSON.parse(event.body);
    const validation = validate(data);

    if (!validation.ok) {
        console.error('Validation Failed');
        callback(null, {
            statusCode: 400,
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': true,
            },
            body: &quot;Couldn't create the connection. \n - &quot; + validation.message,
        });
        return;
    }

    const params = {
        TableName: process.env.CONNECTIONS_TABLE ?? '',
        Item: {
            id: uuidv4(),
            providerName: data.providerName,
            apiKey: data.apiKey,
            apiSecret: data.apiSecret,
            search: data.search,
            attributes: data.attributes,
            createdAt: timestamp,
            updatedAt: timestamp,
        },
    };

    // write the connection to the database
    dynamodb.put(params, (error) =&gt; {
        // handle potential errors
        if (error) {
            console.error(error);

            callback(null, {
                statusCode: error.statusCode || 501,
                headers: {
                    'Access-Control-Allow-Origin': '*',
                    'Access-Control-Allow-Credentials': true,
                },
                body: &quot;Couldn't create the connection.&quot;,
            });

            return;
        }

        // create a response
        const response = {
            statusCode: 200,
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': true,
            },
            body: JSON.stringify(params.Item),
        };
        callback(null, response);
    });
};
</code></pre>
<p>Please help me understand the procedure to write a unit test for this</p>
<p>Thank you</p>
",https://stackoverflow.com/questions/73786530/how-to-write-a-unit-test-for-serverless-function-in-dynamodb-using-jest,"['typescript', 'unit-testing', 'aws-lambda', 'amazon-dynamodb']",92,False,0,0
An updated approach to testing vuex actions,"<p>In the <a href=""https://vuex.vuejs.org/guide/testing.html#testing-actions"" rel=""nofollow noreferrer"">&quot;Testing Actions&quot;</a> documentation, there is a recommendation to use <a href=""https://github.com/plasticine/inject-loader"" rel=""nofollow noreferrer"">inject-loader</a> in order to mock entire module imports, and their respective dependencies, when unit testing.</p>
<p>For example, you can mock the <code>../api/shop</code> import found inside the <code>./actions</code> file with the following:</p>
<pre><code>const actionsInjector = require('inject-loader!./actions')

// create the module with our mocks
const actions = actionsInjector({
  '../api/shop': {
    getProducts (cb) {
      setTimeout(() =&gt; {
        cb([ /* mocked response */ ])
      }, 100)
    }
  }
})
</code></pre>
<p>Unfortunately, that package does not support Webpack 5.</p>
<p>Is there an updated approach, or alternative package, that is recommended?</p>
",https://stackoverflow.com/questions/72317291/an-updated-approach-to-testing-vuex-actions,"['vue.js', 'unit-testing', 'webpack', 'mocking', 'vuex']",87,True,0,1
How to make &quot;Choose Destination Directory&quot; dialog appear after &quot;Create Test&quot; in Android Studio,"<p>I am studying unit-testing from Google codelab.</p>
<p><a href=""https://developer.android.com/codelabs/advanced-android-kotlin-training-testing-basics#5"" rel=""nofollow noreferrer"">https://developer.android.com/codelabs/advanced-android-kotlin-training-testing-basics#5</a></p>
<p>There is one step to choose the folder in AndroidTest/Test destination dialog
<a href=""https://i.stack.imgur.com/gk7TF.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
<p>But my Android Studio doesn't show this dialog so I need to drag my file into test package everytime.</p>
<p>How to set the Android Studio to let this dialog open?</p>
",https://stackoverflow.com/questions/73288956/how-to-make-choose-destination-directory-dialog-appear-after-create-test-in,"['java', 'android-studio', 'unit-testing', 'kotlin']",283,False,3,2
Mocking React higher-order components (HOC) with Jest,"<p>i am trying to run a unit testing for my react-native component. My component seems complex. i tired all possible ways to get it done.</p>
<p><strong>My CheckBox component wrapped with HOC withTheme</strong></p>
<pre><code>import { View, Text, Pressable, StyleSheet } from 'react-native'
import React, { useState } from 'react'
import { scale } from 'react-native-size-matters'
import MaterialIcons from 'react-native-vector-icons/dist/MaterialIcons'
import withTheme from 'Theme/withTheme'
import Label from 'Components/Label'
import testID from 'Utils/common'


function CheckBox({ theme: { colors }, label }) {
    const styles = style(colors)
    const [checked, setChecked] = useState(false)
    const onPress = () =&gt; {
        setChecked(!checked)
    }
    return (
        &lt;Pressable onPress={onPress} style={styles.wrapper} {...testID(`CheckBox wrapper`)}&gt;
            &lt;View style={styles.iconWrapper} {...testID(`CheckBox wrapper check`)}&gt;
                {checked &amp;&amp; &lt;MaterialIcons name=&quot;done&quot; size={scale(15)} color={colors.black} /&gt;}
            &lt;/View&gt;
            &lt;View style={{ paddingHorizontal: scale(10) }} {...testID(`CheckBox Label Wrapper`)}&gt;
                &lt;Label text={label} style={{ fontSize: scale(14) }}  {...testID(`CheckBox label ${label}`)}/&gt;
            &lt;/View&gt;
        &lt;/Pressable&gt;
    )
}

export default withTheme(CheckBox)
const style = StyleSheet.create((colors) =&gt; ({
    wrapper: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    iconWrapper: {
        backgroundColor: colors.primary,
        height: scale(25),
        width: scale(25), borderRadius: scale(4),
        justifyContent: &quot;center&quot;,
        alignItems: 'center'
    }

}))
</code></pre>
<p><strong>withTheme HOC Code</strong></p>
<blockquote>
<p>withTheme has hook useTheme</p>
</blockquote>
<pre><code>import React, { forwardRef } from 'react';
import { useTheme } from './ThemeProvider';

function withTheme(WrappedComponent, props) {

  return forwardRef(function (someProps, ref) {
    const { theme  } = useTheme(); 
    return (
      &lt;WrappedComponent ref={ref} {...someProps} {...props} theme={theme} /&gt;
    );
  });
}

export default withTheme;

</code></pre>
<blockquote>
<p>What i tried
Tried mockcing HOC
Tried mockcing withTheme hook
<a href=""https://medium.com/tarmac/mocking-react-higher-order-components-hoc-with-jest-36fd52a891b3"" rel=""nofollow noreferrer"">Refered this Blog</a></p>
</blockquote>
<p><strong>test written</strong></p>
<pre><code>/* ---------- Packages Import ---------- */
import React from 'react';
import {render, cleanup, fireEvent} from '@testing-library/react-native';
import CheckBox from '../index';
import testID from 'Utils/common';

/* ---------- Components Import ---------- */
jest.mock('@react-native-async-storage/async-storage', () =&gt;
  require('@react-native-async-storage/async-storage/jest/async-storage-mock'),
);
jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter');
jest.mock('Theme/__mock__/withTheme'); 
jest.mock('Theme/__mock__/useTheme');

afterEach(cleanup);

describe('&lt;CheckBox /&gt;', () =&gt; {
  it('should match the snapshot', () =&gt; {
    const rendered = render(&lt;CheckBox  /&gt;).toJSON();
    expect(rendered).toMatchSnapshot();
  });

});

</code></pre>
<p><strong>Error i am getting</strong>
<a href=""https://i.stack.imgur.com/xMmIg.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/xMmIg.png"" alt=""error i am getting"" /></a></p>
<p><strong>Any help would be appricated, Thank in advance</strong></p>
",https://stackoverflow.com/questions/74738500/mocking-react-higher-order-components-hoc-with-jest,"['reactjs', 'react-native', 'jestjs', 'babel-jest', 'testing-libraryreact-native']",252,False,3,0
Support for the experimental syntax &#39;flow&#39; isn&#39;t currently enabled (5:8): react/typescript,"<p>I am very new to unit testing and everytime I fix one thing it throws a new error, before this it said React is not defined. Before this it said document is not defined. As you can imagine i've had to go in change a lot of different things. Can somebody tell me what is going on ?</p>
<p>The new error is as the title suggests-</p>
<pre><code>export type UsersList = {
        |        ^
      6 |   first: string;
</code></pre>
<p>AND...</p>
<pre><code>ReferenceError: regeneratorRuntime is not defined

      23 |     setLoading(true);
      24 |
    &gt; 25 |     const fetchList = async (): Promise&lt;UsersList&gt; =&gt; {
         |                    ^
      26 |       const result: any = await fetch(&quot;https://randomuser.me/api/?results=20&quot;)
      27 |         .then((res) =&gt; res.json())
      28 |         .then((data) =&gt; {
</code></pre>
<p>package.json</p>
<pre><code>{
  &quot;name&quot;: &quot;template-junior-frontend&quot;,
  &quot;version&quot;: &quot;0.1.0&quot;,
  &quot;private&quot;: true,
  &quot;dependencies&quot;: {
    &quot;@emotion/react&quot;: &quot;^11.7.1&quot;,
    &quot;@emotion/styled&quot;: &quot;^11.6.0&quot;,
    &quot;@fortawesome/fontawesome-svg-core&quot;: &quot;^1.3.0&quot;,
    &quot;@fortawesome/free-regular-svg-icons&quot;: &quot;^6.0.0&quot;,
    &quot;@fortawesome/free-solid-svg-icons&quot;: &quot;^6.0.0&quot;,
    &quot;@fortawesome/react-fontawesome&quot;: &quot;^0.1.17&quot;,
    &quot;@material-ui/core&quot;: &quot;^5.0.0-beta.5&quot;,
    &quot;@mui/icons-material&quot;: &quot;^5.4.2&quot;,
    &quot;@mui/material&quot;: &quot;^5.4.2&quot;,
    &quot;@testing-library/jest-dom&quot;: &quot;^5.16.1&quot;,
    &quot;@testing-library/react&quot;: &quot;^12.1.2&quot;,
    &quot;@testing-library/user-event&quot;: &quot;^13.5.0&quot;,
    &quot;@types/node&quot;: &quot;^16.11.20&quot;,
    &quot;@types/react&quot;: &quot;^17.0.38&quot;,
    &quot;@types/react-dom&quot;: &quot;^17.0.11&quot;,
    &quot;react&quot;: &quot;^17.0.2&quot;,
    &quot;react-dom&quot;: &quot;^17.0.2&quot;,
    &quot;react-scripts&quot;: &quot;5.0.0&quot;,
    &quot;react-string-replace&quot;: &quot;^0.4.4&quot;,
    &quot;regenerator-runtime&quot;: &quot;^0.13.9&quot;,
    &quot;typescript&quot;: &quot;^4.5.4&quot;,
    &quot;web-vitals&quot;: &quot;^2.1.3&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 --watch&quot;,
    &quot;eject&quot;: &quot;react-scripts eject&quot;
  },
  &quot;eslintConfig&quot;: {
    &quot;extends&quot;: [
      &quot;react-app&quot;,
      &quot;react-app/jest&quot;
    ]
  },
  &quot;browserslist&quot;: {
    &quot;production&quot;: [
      &quot;&gt;0.2%&quot;,
      &quot;not dead&quot;,
      &quot;not op_mini all&quot;
    ],
    &quot;development&quot;: [
      &quot;last 1 chrome version&quot;,
      &quot;last 1 firefox version&quot;,
      &quot;last 1 safari version&quot;
    ]
  },
  &quot;devDependencies&quot;: {
    &quot;@babel/preset-typescript&quot;: &quot;^7.16.7&quot;,
    &quot;@types/jest&quot;: &quot;^27.4.0&quot;,
    &quot;jest&quot;: &quot;jest&quot;,
    &quot;jest-environment-jsdom&quot;: &quot;^27.5.1&quot;,
    &quot;ts-jest&quot;: &quot;^27.1.3&quot;
  }
}
</code></pre>
<p>jest.config.ts</p>
<pre><code>import {defaults} from 'jest-config'
module.exports = {
  roots: [&quot;&lt;rootDir&gt;/src&quot;],  
  testEnvironment: 'jsdom',
  moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'],
  setupFilesAfterEnv: [ require.resolve('regenerator-runtime/runtime') ]
};
</code></pre>
<p>babel.config.json</p>
<pre><code>{
    &quot;presets&quot;: [
      [&quot;@babel/preset-react&quot;, {
        &quot;runtime&quot;: &quot;automatic&quot;
     }]
    ]
  }
</code></pre>
<p>setupTests.ts</p>
<pre><code>import '@testing-library/jest-dom';
import 'regenerator-runtime/runtime'
</code></pre>
",https://stackoverflow.com/questions/71207760/support-for-the-experimental-syntax-flow-isnt-currently-enabled-58-react,"['reactjs', 'typescript', 'jestjs', 'babel-jest']",1539,False,5,0
Test case fail for method returning from soap.createClientAsync function,"<p>I have a soap RestAPI to call for excecuting a function from a service for which i have used soap lib with async await. The code is working fine. When comes to unit testing the test case fails at the callback method returning from the client. The code and UT error follows.</p>
<p><strong>Function to call Soap Client - Code - Helper.ts</strong></p>
<pre><code>class soapHelper {
    public async registerInSoap(
            uploadRequest: ImportExperimentRequestDto,
        ): Promise&lt;{ RegisterExperimentResult: IffManPublishResponseDto }&gt; {
            const url = &quot;http://test.com/Services/Req.svc?wsdl&quot;;
            const client = await soap.createClientAsync(flavourUrl);
            return client.RegisterExperimentAsync({ upload: uploadRequest});
        }
}
</code></pre>
<p><strong>Test Case - Code</strong></p>
<pre><code>describe(&quot;**** Register via soap service ****&quot;, () =&gt; {
        it(&quot;** should excecute register method **&quot;, async () =&gt; {
            const request = cloneDeep(MOCK.API_PAYLOAD);
            const clientResponse = {
                RegisterExperimentAsync: jest.fn(),
            };
            jest.spyOn&lt;any, any&gt;(soap, &quot;createClientAsync&quot;).mockReturnValueOnce(() =&gt; Promise.resolve(clientResponse));
            const result= await soapHelper.registerInSoap(request);
            expect(result).toEqual({ Result: AFB_MOCK_RESPONSE.API_RESPONSE });
        });
    });
</code></pre>
<p><strong>Error</strong></p>
<pre><code>TypeError: client.RegisterExperimentAsync is not a function
</code></pre>
<p><a href=""https://i.stack.imgur.com/0yDCG.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
",https://stackoverflow.com/questions/72604110/test-case-fail-for-method-returning-from-soap-createclientasync-function,"['unit-testing', 'soap', 'jestjs', 'nestjs', 'soap-client']",105,False,1,1
Jest Unit Testing fails in soap.createClientAsync returning function,"<p>I have a soap RestAPI to call for excecuting a function from a service for which i have used soap lib with async await. The code is working fine. When comes to unit testing the test case fails at the callback method returning from the client. The code and UT error follows.</p>
<p><strong>Function to call Soap Client - Code - Helper.ts</strong></p>
<pre><code>class soapHelper {
    public async registerInSoap(
            uploadRequest: ImportExperimentRequestDto,
        ): Promise&lt;{ RegisterExperimentResult: IffManPublishResponseDto }&gt; {
            const url = &quot;http://test.com/Services/Req.svc?wsdl&quot;;
            const client = await soap.createClientAsync(flavourUrl);
            return client.RegisterExperimentAsync({ upload: uploadRequest});
        }
}
</code></pre>
<p><strong>Test Case - Code</strong></p>
<pre><code>describe(&quot;**** Register via soap service ****&quot;, () =&gt; {
        it(&quot;** should excecute register method **&quot;, async () =&gt; {
            const request = cloneDeep(MOCK.API_PAYLOAD);
            const clientResponse = {
                RegisterExperimentAsync: jest.fn(),
            };
            jest.spyOn&lt;any, any&gt;(soap, &quot;createClientAsync&quot;).mockReturnValueOnce(() =&gt; Promise.resolve(clientResponse));
            const result= await soapHelper.registerInSoap(request);
            expect(result).toEqual({ Result: AFB_MOCK_RESPONSE.API_RESPONSE });
        });
    });
</code></pre>
<p><strong>Error</strong></p>
<pre><code>TypeError: client.RegisterExperimentAsync is not a function
</code></pre>
<p><a href=""https://i.stack.imgur.com/0yDCG.png"" rel=""nofollow noreferrer"">UT Error</a></p>
",https://stackoverflow.com/questions/72610667/jest-unit-testing-fails-in-soap-createclientasync-returning-function,"['node.js', 'nestjs', 'soap-client', 'ts-jest', 'jest-fetch-mock']",518,False,1,1
[Jest Unit Testing]: TypeError: component.setState is not a function,"<p>We are using Jest for Unit Testing. We have a common file that contains the common OnChange() function definition. While writing unit test case for OnChange, it's throwing below error:</p>
<p><a href=""https://i.stack.imgur.com/fGlcu.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fGlcu.png"" alt=""enter image description here"" /></a></p>
<p>e.g.</p>
<p><strong>CommonFunctions.tsx</strong></p>
<pre><code>export const OnChange = (component: any, property: any, event: any) =&gt; {
  property[event.target.name] = event.target.value;
  component.setState({
    ...component.state,
  });
};
</code></pre>
<p><strong>Calling for OnChange from a class Component:</strong></p>
<pre><code>this.onChangeHandler = (event: any) =&gt; OnChange(this, this.state, event);
</code></pre>
<p><strong>Jest Unit Test Case for OnChange: CommonFunctions.test.tsx</strong></p>
<pre><code>test('should call function &quot;OnChange&quot;', () =&gt; {
const property = {
  name: 'test',
};
const component = jest.fn();
const event = {
    preventDefault() {},
    target: { name: 'name', value: 'the-value' }
  };
expect(OnChange(component,property,event)).toBeCalledWith('the-value');
</code></pre>
<p>});</p>
<p>Please suggest a better or newer approach for this use case.</p>
<p><strong>Versions:</strong>
&quot;react&quot;: &quot;^18.1.0&quot;,
&quot;react-dom&quot;: &quot;^18.1.0&quot;,
&quot;jest&quot;: &quot;^29.0.3&quot;,</p>
",https://stackoverflow.com/questions/73816128/jest-unit-testing-typeerror-component-setstate-is-not-a-function,"['reactjs', 'unit-testing', 'jestjs', 'ts-jest', 'babel-jest']",924,True,1,1
How to mock function on unit test actix web,"<p>I have an api service that has 2 layer: api and repository. The api layer is where the request handling and business logic defined, while repository is a database call functions. I want to mock the database call function on the unit testing of my api layer, is there any way i can do it with actix web?</p>
<pre class=""lang-rust prettyprint-override""><code>pub fn login(db: web::Data&lt;Pool&gt;, payload: Json&lt;LoginInput&gt;) -&gt; Result&lt;Token, Error&gt; {

    // Function i want to mock:
    let user =
        match get_user_by_email(&amp;db.get().unwrap(), payload.email.to_string()) {
            // This return status code of bad request
            Err(e) =&gt; return Error::InvalidUser,
            Ok(user) =&gt; user,
        };

    let user_claims = UserClaims {
        id: user.id,
        email: user.email
    };

    match verify(payload.password.to_string(), &amp;user.password) {
        Err(e) =&gt; return Error::BadRequest(e),
        Ok(result) =&gt; match result {
            false =&gt; return Error::InvalidUser,
            _ =&gt; {}
        },
    };

    let token = generate_access_and_refresh_token(user_claims);

    token
}
</code></pre>
<p>The test:</p>
<pre class=""lang-rust prettyprint-override""><code>#[actix_web::test]
async fn test_login() {
    let payload = create_mock_login_payload();
    let req = test::TestRequest::default()
        .set_json(payload)
        .to_http_request();

    let resp = login(req).await.unwrap();
    assert_eq!(resp.status(), StatusCode::BadRequest);
}
</code></pre>
<p>The mock function behavior that i want:</p>
<pre class=""lang-rust prettyprint-override""><code>fn get_user_by_email(db: Pool, email: String) -&gt; Result&lt;User, Error&gt; {
   if !email_valid(email) {
       return Err(Error::InvalidEmail);
   }
   Ok(create_mock_user())
}
</code></pre>
",https://stackoverflow.com/questions/71888779/how-to-mock-function-on-unit-test-actix-web,"['unit-testing', 'rust', 'mocking', 'actix-web']",502,False,1,0
Unit testing nuxt fetch hook,"<p>I'm trying to unit test with Nuxt. Everything's going smoothly, but my problem lies with unit testing fetch. It seems that since this.$axios isn't a library (well, it is, but is injected to the context), there's no easy way to jest.mock it. I've the few posts that there are on this, but they have not worked.</p>
<pre><code>async fetch() {
    try {
        this.maxSpace = await this.$axios.$get('/api/system/max-space')
    }
    catch (err) {
        this.maxSpace = 0
    }
},
</code></pre>
<p>This is the simple code I'm attempting to unit test</p>
",https://stackoverflow.com/questions/71503482/unit-testing-nuxt-fetch-hook,"['jestjs', 'nuxt.js', 'vue-test-utils']",575,False,1,0
What is a good way to unit test assembly code?,"<p>Automated unit testing is considered a staple of modern software development.  Unit testing is hard to do in assembly, because we often don't have the scaffolding needed.  Depending on our asm environment, we may or may not have the ability to:</p>
<ul>
<li>Call library functions</li>
<li>Write to stdout or stderr</li>
<li>Associate messages with test cases</li>
</ul>
<p>Even incrementing counters for passed and failed tests isn't simple in asm, as we must avoid clobbering registers.</p>
<p>Consequently, when I test asm, I usually use a debugger and inspect it manually (<em>shudder</em>).  I may do something like:</p>
<pre><code>cmp rbx, expected_test1
jne .failed_test1
...
.failed_test1:
    int3
    db `FAIL: Failed test1\0`
</code></pre>
<p>If <code>test1</code> fails, the debugger will stop, and I'll see the bytes &quot;FAIL: Failed test1&quot; in the display.  A hack, but easier and less invasive than the other methods I can think of.</p>
<p>A better approach would be:</p>
<ul>
<li>Automated: Run and get a count of pass and failed tests</li>
<li>Diagnostic: Print messages for failed tests</li>
<li>Non-invasive: Don't clobber regs or mem.</li>
<li>Minimal assumptions: Don't assume a platform.  Often my asm doesn't even load glibc.</li>
</ul>
<p>Given the above: <strong>What's an effective way to unit test asm?</strong></p>
",https://stackoverflow.com/questions/70561382/what-is-a-good-way-to-unit-test-assembly-code,"['unit-testing', 'assembly']",595,False,2,0
How to upload files when unit testing firebase storage security rules?,"<p>I have a bucket into which users can upload audio files, and my goal is to test that it is working as expected. But when I try to use the &quot;@firebase/rules-unit-testing&quot; library to upload a test file into the emulator the upload gets stuck and makes no progress.</p>
<p><strong>Rules</strong></p>
<pre><code>rules_version = '2';
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if false;
    }
    match /audio/{audioFileID} {
      allow create: if request.auth != null &amp;&amp; request.resource.contentType.matches('audio/(flac|wav)');
    }
  }
}

</code></pre>
<p><strong>Test code</strong></p>
<pre class=""lang-js prettyprint-override""><code>import {
  assertFails,
  assertSucceeds,
  initializeTestEnvironment,
  RulesTestEnvironment,
} from &quot;@firebase/rules-unit-testing&quot;;
import { test, beforeAll, beforeEach, afterAll } from &quot;vitest&quot;;
import fs from &quot;fs&quot;;

const createTestFile = (size: number) =&gt; Buffer.alloc(size);
let testEnv: RulesTestEnvironment;

beforeAll(async () =&gt; {
  testEnv = await initializeTestEnvironment({
    projectId: &quot;stst-et-interviewer-dev&quot;,
    hub: {
      host: &quot;localhost&quot;,
      port: 4400,
    },
  });
});

beforeEach(async () =&gt; {
  await testEnv.clearStorage();
  await testEnv.clearFirestore();
});

afterAll(async () =&gt; await testEnv.cleanup());

const loadStepStoneImage = () =&gt;
  fs.readFileSync(&quot;./public/images/stepstoneLogo.svg&quot;);

test(&quot;Storage does not allow you to read files&quot;, async () =&gt; {
  const rouge = testEnv.unauthenticatedContext();
  const alice = testEnv.authenticatedContext(&quot;alice&quot;);
  await assertFails(
    rouge.storage().ref(&quot;audio/test-interview.flac&quot;).getDownloadURL()
  );
  await assertFails(
    alice.storage().ref(&quot;audio/test-interview.flac&quot;).getDownloadURL()
  );
  await assertFails(alice.storage().ref(&quot;audio/&quot;).listAll());
});

test(&quot;Storage does not allow you to upload a file if you are not logged in&quot;, async () =&gt; {
  const rouge = testEnv.unauthenticatedContext();
  const upload = rouge
    .storage(&quot;stst-et-interviewer-dev.appspot.com&quot;)
    .ref(&quot;audio/logo.svg&quot;)
    .put(createTestFile(200), { contentType: &quot;audio/flac&quot; });
  
  await assertFails(upload.then()); // &lt;- GETS STUCK HERE
  console.log(&quot;this does not happen&quot;);
});
</code></pre>
<p>What are the possible reasons for this happening? Are there any simple ways of debugging?</p>
",https://stackoverflow.com/questions/72815018/how-to-upload-files-when-unit-testing-firebase-storage-security-rules,"['node.js', 'firebase-storage', 'firebase-security']",159,False,4,0
Is there a way to mock the state in react for unit testing without using enzyme,"<p>I've been using jest and have been reading through the @testing-library/react docs but so far found nothing relating to mocking state in react. I know mocking state in react is possible with enzyme. But I'm using react 18 and there is no enzyme-adapter for this version. I'm quite new to unit testing and would love to get some suggestions on this.</p>
",https://stackoverflow.com/questions/72499490/is-there-a-way-to-mock-the-state-in-react-for-unit-testing-without-using-enzyme,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",578,False,1,0
Error: &#39;ansi_hyperlink_types&#39; is not an exported object from &#39;namespace:cli&#39;,"<p>I am exploring unit testing in R based on <a href=""https://stirlingcodingclub.github.io/code_testing/testing_notes.html#"" rel=""nofollow noreferrer"">this</a>.</p>
<p>So I installed the <code>testthat</code> package and wrote a simple function and a test as mentioned in the above link. Here is the code</p>
<pre><code>library(testthat)

f_to_c &lt;- function(F_temp){
  C_temp &lt;- (F_temp - 32) * 5/9
  return(C_temp)
}

#test
test_that(desc = &quot;Fahrenheit to Celsius&quot;, code = {
  
  temp &lt;- f_to_c(50)
  expect_that( object = temp, condition = equals(10) )
  expect_that( object = is.numeric(temp), condition = equals(TRUE) )
})
</code></pre>
<p>Here is what I am getting</p>
<pre><code>Error: 'ansi_hyperlink_types' is not an exported object from 'namespace:cli'
</code></pre>
<p>What could be the reason for this error and how to solve this? Or, is there a different way to run tests in R? Thanks in advance.</p>
",https://stackoverflow.com/questions/74401936/error-ansi-hyperlink-types-is-not-an-exported-object-from-namespacecli,"['r', 'unit-testing', 'testing', 'testthat']",633,True,1,1
Getting SyntaxError: Name argument is not a valid custom element name,"<p>I am trying to do unit testing of my React app using Enzyme with Jest but getting this error</p>
<p>` FAIL  src/components/XYZ/<strong>tests</strong>/ABC.test.js</p>
<p>● Test suite failed to run</p>
<pre><code>SyntaxError: Name argument is not a valid custom element name.
</code></pre>
<p>Test Suites: 2 failed, 2 total
Tests:       0 total
Snapshots:   0 total
Time:        3.224 s
Ran all test suites.`</p>
<p>My Jest Config file is as following</p>
<pre><code>&quot;jest&quot;: {
    &quot;moduleNameMapper&quot;: {
      &quot;d3&quot;: &quot;&lt;rootDir&gt;/node_modules/d3/dist/d3.min.js&quot;,
      &quot;\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$&quot;: &quot;&lt;rootDir&gt;/__mocks__/fileMock.js&quot;,
      &quot;^.+\\.(css|less|scss)$&quot;: &quot;identity-obj-proxy&quot;
    },
    &quot;setupFiles&quot;: [
      &quot;./src/&quot;
    ],
    &quot;setupFilesAfterEnv&quot;: [
      &quot;./src/setUpTests.js&quot;
    ],
    &quot;testPathIgnorePatterns&quot;: [
      &quot;./node_modules/&quot;
    ]
  },
</code></pre>
<p>Please let me know what I am doing wrong here ? TIA</p>
",https://stackoverflow.com/questions/71519608/getting-syntaxerror-name-argument-is-not-a-valid-custom-element-name,"['reactjs', 'jestjs', 'syntax-error', 'enzyme', 'custom-element']",467,True,1,1
"Stubbing a module, its methods, and inner classes with RSpec","<p>I have a module like this that I'm trying to write unit tests for</p>
<pre class=""lang-rb prettyprint-override""><code>module MyThing
  module Helpers
    def self.generate_archive
      # ...
      ::Configuration.export(arg)
    rescue ::Configuration::Error =&gt; error
      raise error
    end
  end
end
</code></pre>
<p>The <code>::Configuration</code> module can't exist in my unit testing environment for reasons that are beyond my control, so I need to stub it out.  Here's what I've come up with so far.</p>
<pre class=""lang-rb prettyprint-override""><code>RSpec.describe 'MyThing' do
  it 'generates an archive' do
    configuration_stub = stub_const(&quot;::Configuration&quot;, Module.new)
    configuration_error_stub = stub_const(&quot;::Configuration::Error&quot;, Class.new)

    expect_any_instance_of(configuration_stub).to receive(:export).with(&quot;arg&quot;)
    MyThing::Helpers.generate_archive
  end
end
</code></pre>
<p>This gets me an error.</p>
<pre><code>NoMethodError:
  Undefined method `export' for Configuration:Module
</code></pre>
<p>If I put the <code>configuration_stub</code> definition inline with the <code>expect_any_instance_of</code> like this</p>
<pre class=""lang-rb prettyprint-override""><code>RSpec.describe 'MyThing' do
  it 'generates an archive' do
    configuration_error_stub = stub_const(&quot;::Configuration::Error&quot;, Class.new)

    expect_any_instance_of(stub_const(&quot;::Configuration&quot;, Module.new)).to receive(:export).with(&quot;arg&quot;)
    MyThing::Helpers.generate_archive
  end
end
</code></pre>
<p>I also get an error.</p>
<pre><code>NameError:
  Uninitialized constant Configuration::Error
...
# --- Caused by: ---
# NoMethodError:
#   Undefined method `export' for Configuration:Module
</code></pre>
",https://stackoverflow.com/questions/71055503/stubbing-a-module-its-methods-and-inner-classes-with-rspec,"['ruby', 'rspec', 'rspec-mocks']",628,True,0,1
"Accessing attributes of session throws NullPointerException error, when using WicketTester","<p>Accessing attributes of session throws NullPointerException error, when using WicketTester.</p>
<p>There was similar question asked earlier
<a href=""https://stackoverflow.com/questions/70258881/wicket-9-unit-testing-mockito-httpsession"">wicket 9: unit testing + mockito + httpSession</a></p>
<p>The discussion their suggested using</p>
<p>tester.getRequest().getSession().setAttribute(&quot;userName&quot;, &quot;Test user 1&quot;);</p>
<p>instead of</p>
<p>tester.getHttpSession().setAttribute(&quot;userName&quot;, &quot;Test user 1&quot;);</p>
<p>Making that change did not resolve the problem.
Complete project, created using 'wicket.apache.org/start/quickstart.html' can be found at github.com/rjngshn/WicketTesterSession</p>
<pre><code>    public class TestHomePage
{
    private WicketTester tester;

    @BeforeEach
    public void setUp()
    {
        tester = new WicketTester(new RTApplication());
    }
// https://stackoverflow.com/questions/70258881/wicket-9-unit-testing-mockito-httpsession
    @Test
    public void userPageRendersSuccessfully()
    {
        System.out.println(&quot;Testing userPageRendersSuccessfully &quot;);
        tester.getRequest().getSession().setAttribute(&quot;userName&quot;, &quot;Test user 1&quot;);
        System.out.println(&quot;Uesr name in session:&quot; + tester.getHttpSession().getAttribute(&quot;userName&quot;));
        //start and render the test page
        tester.startPage(UserPage.class);
        //assert rendered page class
        tester.assertRenderedPage(UserPage.class);
        tester.assertModelValue(&quot;txtUserName&quot;, &quot;Test user 1&quot;);
        System.out.println(&quot;Complete testing userPageRendersSuccessfully &quot;);
    }
}
</code></pre>
<p>The error is:</p>
<pre><code> [WARN] [stderr] java.lang.NullPointerException
 [WARN] [stderr]    at uk.ac.ox.ndph.ckb.UserPage.onInitialize(UserPage.java:19)
 [WARN] [stderr]    at org.apache.wicket.Component.fireInitialize(Component.java:883)
 [WARN] [stderr]    at org.apache.wicket.MarkupContainer.internalInitialize(MarkupContainer.java:1045)
</code></pre>
<p>...</p>
",https://stackoverflow.com/questions/71675884/accessing-attributes-of-session-throws-nullpointerexception-error-when-using-wi,"['java', 'wicket']",83,True,0,1
Proto.Actor - How do I unit test the following use case,"<p>I'm running the following <a href=""https://github.com/asynkron/protoactor-website/tree/master/hugo/content/docs/bootcamp/unit-9/lesson-2/dotnet/CalculatorExample"" rel=""nofollow noreferrer"">example</a> which uses Proto.Persistance for event sourcing and persists the history of the events in a sqlite event store.</p>
<p>How do I unit test it? Perhaps, I should switch to an in-memory event store? You can see what I did below. It would've been so much easier if there were examples with unit testing using Proto.Actor in the docs.</p>
<h1>Calculator.cs</h1>
<pre class=""lang-cs prettyprint-override""><code>public class Calculator : IActor
{
    private readonly Persistence _persistence;
    private double _result;

    public Calculator(IProvider provider)
    {
        _persistence = Persistence.WithEventSourcing(provider, &quot;demo-app-id&quot;, ApplyEvent);
    }

    public async Task ReceiveAsync(IContext context)
    {
        switch (context.Message)
        {
            case Started msg:
                Console.WriteLine(&quot;MyPersistenceActor - Started&quot;);
                await _persistence.RecoverStateAsync();
                break;

            case AddCommand msg:
                await _persistence.PersistEventAsync(new AddedEvent { Value = msg.Value });
                _result += msg.Value;

                break;

            case SubtractCommand msg:
                await _persistence.PersistEventAsync(new SubtractedEvent { Value = msg.Value });
                _result -= msg.Value;

                break;

            case DivideCommand msg:
                await _persistence.PersistEventAsync(new DividedEvent { Value = msg.Value });
                _result /= msg.Value;

                break;

            case MultiplyCommand msg:
                await _persistence.PersistEventAsync(new MultipliedEvent { Value = msg.Value });
                _result *= msg.Value;

                break;

            case ClearCommand msg:
                await _persistence.PersistEventAsync(new ResetEvent());
                _result = 0;

                break;

            case PrintResultCommand msg:
                Console.WriteLine(_result);
                break;
        }
    }

    private void ApplyEvent(Event @event)
    {
        switch (@event)
        {
            case RecoverEvent msg:
                switch (msg.Data)
                {
                    case AddedEvent addedEvent:
                        _result += addedEvent.Value;
                        break;
                    case SubtractedEvent subtractedEvent:
                        _result -= subtractedEvent.Value;
                        break;
                    case DividedEvent dividedEvent:
                        _result /= dividedEvent.Value;
                        break;
                    case MultipliedEvent multipliedEvent:
                        _result *= multipliedEvent.Value;
                        break;
                    case ResetEvent resetEvent:
                        _result = 0;
                        break;
                }

                break;
            case ReplayEvent msg:
                break;
            case PersistedEvent msg:
                break;
        }
    }
}
</code></pre>
<h1>CalculatorTests.cs</h1>
<pre class=""lang-cs prettyprint-override""><code>public class ManagementFixture : IAsyncDisposable
{
    public ManagementFixture()
    {
        System = new ActorSystem();
        var provider = new SqliteProvider(new SqliteConnectionStringBuilder { DataSource = &quot;states.db&quot; });

        var props = Props.FromProducer(() =&gt; new Calculator(provider));
        Pid = System.Root.Spawn(props);
    }

    public ActorSystem System { get; }
    public PID Pid { get; }

    public async ValueTask DisposeAsync()
    {
        await DisposeAsyncCore();
        GC.SuppressFinalize(this);
    }

    protected virtual async ValueTask DisposeAsyncCore()
    {
        await System.ShutdownAsync();
    }
}

public class CalculatorTests : IClassFixture&lt;ManagementFixture&gt;
{
    private readonly ManagementFixture _fixture;

    public CalculatorTests(ManagementFixture fixture)
    {
        _fixture = fixture;
    }

    [Fact]
    public void Test()
    {
        _fixture.System.Root.Send(_fixture.Pid, new ClearCommand());
        _fixture.System.Root.Send(_fixture.Pid, new AddCommand { Value = 100 });
        _fixture.System.Root.Send(_fixture.Pid, new SubtractCommand { Value = 50 });

        // TODO: How do I get the expected value?
        Assert.Equal(true, true);
    }
}
</code></pre>
",https://stackoverflow.com/questions/73271614/proto-actor-how-do-i-unit-test-the-following-use-case,"['c#', '.net', 'xunit', 'proto.actor']",150,False,0,0
Kotlin Exception when mocking suspend function java.io.EOFException: Premature end of stream: expected 1 bytes,"<p>I use <strong>KTor</strong> and <strong>Kotlin Serialization</strong> library in my android project, along with <strong>mockk</strong> and <strong>junit.jupiter</strong> for unit testing. I've encountered a problem when mocking ktor's <code>suspend</code> function <code>readText()</code>. The following unit test tests that <code>initErrorMessage()</code> function returns correct error message.</p>
<p>Test class:</p>
<pre><code>class ErrorTest {

    private val errorMessage = &quot;objectId must be provided.&quot;
    private val errorCode = 2689
    private val correctResponseJson = &quot;{\&quot;code\&quot;:$errorCode,\&quot;message\&quot;:\&quot;$errorMessage\&quot;}&quot;
    // ResponseException class is from ktor library
    private val exceptionMock: ResponseException = mockk(relaxed = true)

    @Test
    fun `initErrorMessage should return correct error message`() = runTest {
        coEvery { exceptionMock.response.readText() } returns correctResponseJson // &lt;-- here is the Error occurs

        val expectedError = errorMessage
        val actualError = initErrorMessage(exceptionMock)

        assertEquals(expectedError, actualError)
    }
}
</code></pre>
<p>Method to test:</p>
<pre><code>suspend fun initErrorMessage(cause: ResponseException): String {
    return try {
        val body = cause.response.readText()
        val jsonSerializer = JsonObject.serializer()
        val jsonObj = Json.decodeFromString(jsonSerializer, body)
        jsonObj[&quot;message&quot;].toString()
    } catch (e: Exception) {
        &quot;&quot;
    }
}
</code></pre>
<p>During execution of the first line in the test method I get an Error:</p>
<pre><code>Premature end of stream: expected 1 bytes
java.io.EOFException: Premature end of stream: expected 1 bytes
    at io.ktor.utils.io.core.StringsKt.prematureEndOfStream(Strings.kt:492)
    at io.ktor.utils.io.core.internal.UnsafeKt.prepareReadHeadFallback(Unsafe.kt:78)
    at io.ktor.utils.io.core.internal.UnsafeKt.prepareReadFirstHead(Unsafe.kt:61)
    at io.ktor.utils.io.charsets.CharsetJVMKt.decode(CharsetJVM.kt:556)
    at io.ktor.utils.io.charsets.EncodingKt.decode(Encoding.kt:103)
    at io.ktor.utils.io.charsets.EncodingKt.decode$default(Encoding.kt:101)
    at io.ktor.client.statement.HttpStatementKt.readText(HttpStatement.kt:173)
    at io.ktor.client.statement.HttpStatementKt.readText$default(HttpStatement.kt:168)
    at com.example.android.http.error.ErrorTest$initErrorMessage should return correct error message$1$1.invokeSuspend(ErrorTest.kt:37)
    at com.example.android.http.error.ErrorTest$initErrorMessage should return correct error message$1$1.invoke(ErrorTest.kt)
    at com.example.android.http.error.ErrorTest$initErrorMessage should return correct error message$1$1.invoke(ErrorTest.kt)
    at io.mockk.impl.eval.RecordedBlockEvaluator$record$block$2$1.invokeSuspend(RecordedBlockEvaluator.kt:28)
    at io.mockk.impl.eval.RecordedBlockEvaluator$record$block$2$1.invoke(RecordedBlockEvaluator.kt)
    at io.mockk.InternalPlatformDsl$runCoroutine$1.invokeSuspend(InternalPlatformDsl.kt:20)
</code></pre>
<p>How to mock this <code>suspend</code> method <code>readText()</code> without an Error?</p>
",https://stackoverflow.com/questions/70778215/kotlin-exception-when-mocking-suspend-function-java-io-eofexception-premature-e,"['android', 'unit-testing', 'kotlin', 'kotlin-coroutines', 'ktor']",5106,True,-1,2
How could i implement Spring JPA findAll(Specification&lt;T&gt; spec) method?,"<p>For unit testing purposes i want to create a fake JPA repository.</p>
<p>While methods like findAll(), findById(id) are easy to implement in java, methods like findAll(Specification spec) are more challenging.</p>
<pre><code>`
classe FakeJpaRepository implements JpaRepository&lt;Employee, Long&gt; {

private Map&lt;Long, Employee&gt; employees = new HashMap&lt;&gt;();

// other methods implementations omitted

public Optional&lt;Employee&gt; findById(Long id){
    return employees.stream()
    .filter(employee -&gt; employee.getId().equals(id))
    .findFirst();
}

public List&lt;Employee&gt; findAll(Specification&lt;Employee&gt; spec){
   // How could i implement this method ?
}
}
`
</code></pre>
<p>I tried to find a way to do that in vain, i expect some one to give me solution or example to follow or put me in the way to the solution.</p>
",https://stackoverflow.com/questions/74691903/how-could-i-implement-spring-jpa-findallspecificationt-spec-method,"['java', 'unit-testing', 'testing', 'spring-data-jpa', 'test-double']",91,False,0,0
Exclude (conditional) linked source files from code coverage,"<p>I'm using VS2022 Community Edition with <a href=""https://marketplace.visualstudio.com/items?itemName=FortuneNgwenya.FineCodeCoverage"" rel=""nofollow noreferrer"">Fine Code Coverage</a> and xUnit for unit testing. I would like the following linked source files in .csproj file to be excluded from testing code coverage:</p>
<pre><code>  &lt;ItemGroup&gt;
    &lt;Compile Include=&quot;..\..\ref\common\Argument.IReadOnlyLIst.VerifyNotEmpty.cs&quot; Link=&quot;ref\common\Argument.IReadOnlyLIst.VerifyNotEmpty.cs&quot; /&gt;
    &lt;Compile Include=&quot;..\..\ref\common\Argument.IReadOnlyList.VerifyNotNull.cs&quot; Link=&quot;ref\common\Argument.IReadOnlyList.VerifyNotNull.cs&quot; /&gt;
    &lt;Compile Include=&quot;..\..\ref\common\Argument.VerifyNotNull.cs&quot; Link=&quot;ref\common\Argument.VerifyNotNull.cs&quot; /&gt;
    &lt;Compile Include=&quot;..\..\ref\common\Object.GetObjectDisposedException.cs&quot; Link=&quot;ref\common\Object.GetObjectDisposedException.cs&quot; /&gt;
    &lt;Compile Include=&quot;..\..\ref\common\String.VerifyNotEmpty.cs&quot; Link=&quot;ref\common\String.VerifyNotEmpty.cs&quot; /&gt;
    &lt;Compile Include=&quot;..\..\ref\common\Type.GetStaticMethodInfo.cs&quot; Link=&quot;ref\common\Type.GetStaticMethodInfo.cs&quot; /&gt;
    &lt;Compile Include=&quot;..\..\ref\common\Type.ResolveStaticGetter.cs&quot; Link=&quot;ref\common\Type.ResolveStaticGetter.cs&quot; /&gt;
    &lt;Compile Include=&quot;..\..\ref\common\IReadOnlyList.IndexOf.cs&quot; Link=&quot;ref\common\IReadOnlyList.IndexOf.cs&quot; /&gt;
    &lt;Compile Include=&quot;..\..\ref\common\AppendOnlyList.cs&quot; Link=&quot;ref\common\AppendOnlyList.cs&quot; /&gt;
    &lt;Compile Include=&quot;..\..\ref\common\ListOfT.MoveRange.cs&quot; Link=&quot;ref\common\LIstOfT.MoveRange.cs&quot; /&gt;
  &lt;/ItemGroup&gt;

  &lt;ItemGroup Condition=&quot;('$(TargetFramework)' != 'netstandard2.0' and '$(TargetFramework)' != 'net461')&quot;&gt;
    &lt;Compile Include=&quot;..\..\ref\common\System.Text.ValueStringBuilder.cs&quot; Link=&quot;ref\common\System.Text.ValueStringBuilder.cs&quot; /&gt;
    &lt;Compile Include=&quot;..\..\ref\common\UInt32.AppendTo.cs&quot; Link=&quot;ref\common\UInt32.AppendTo.cs&quot; /&gt;
  &lt;/ItemGroup&gt;
</code></pre>
<p>These files are shared under <code>ref</code> folder and are tested separately.</p>
<p>The following is the dependent snippet of testing .csproj:</p>
<pre><code>  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;16.5.0&quot; /&gt;
    &lt;PackageReference Include=&quot;Moq&quot; Version=&quot;4.10.0&quot; /&gt;
    &lt;PackageReference Include=&quot;xunit&quot; Version=&quot;2.4.1&quot; /&gt;
    &lt;PackageReference Include=&quot;xunit.runner.visualstudio&quot; Version=&quot;2.4.3&quot; /&gt;
    &lt;PackageReference Include=&quot;coverlet.collector&quot; Version=&quot;3.0.3&quot; /&gt;
  &lt;/ItemGroup&gt;
</code></pre>
<p>Edit:
I tried adding a CodeCoverage.runsettings XML file to the solution:</p>
<pre><code>&lt;Sources&gt;
  &lt;Exclude&gt;
     &lt;Source&gt;.*\\ref\\common\\.*&lt;/Source&gt;
  &lt;/Exclude&gt;
&lt;/Sources&gt;
</code></pre>
<p>but with no luck:
<a href=""https://i.stack.imgur.com/zrfeQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/zrfeQ.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73862032/exclude-conditional-linked-source-files-from-code-coverage,"['c#', '.net', 'testing', 'code-coverage', 'xunit']",189,False,0,1
One method fails unit test only when all tests are run but passes when tested individually?,"<p>I am a first year at college studying application dev and our assignment is to make a simple registration and log in system.
The only problem right now is that the unit testing doesn't work when I run them all at once with the Run Tests feature on VSCode.
the error is this</p>
<pre><code>java.lang.AssertionError
 at st10035771.LoginTest.testIsValidPasswordF(LoginTest.java:35)
 at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
 at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
 at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
 at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
 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.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
 at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
 at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
 at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
</code></pre>
<p>Login.java:</p>
<pre><code>    package st10035771;


import java.util.Scanner;

public class Login {
    public final static int USERNAME_LIMIT = 5;
    public final static int PASSWORD_LENGTH = 8;
     

    public static boolean checkUserName(String username) {
        return username.length() &lt;= USERNAME_LIMIT &amp;&amp; username.contains(&quot;_&quot;);

    }
/*
 * code attribute
 * this code was adapted from DelftStack
 * https://www.delftstack.com/howto/java/password-checker-java/
 */
    public static boolean checkPasswordComplexity(String password) {
      boolean isValidPassword;
      final int minUppers = 1;
      final int minDigits = 1;
      final int minSpecials = 1;
      int uppers = 0;
      int digits = 0;
      int specials = 0;

        for (int i = 0; i &lt; password.length(); i++) {
            char ch = password.charAt(i);
            if (Character.isUpperCase(ch))
                uppers++;
            else if (Character.isDigit(ch))
                digits++;
            //if (ch &gt;= 33 &amp;&amp; ch &lt;= 47 || ch == 64) {
              if (!Character.isLetterOrDigit(ch)) {
                specials++;
            }

        }

        if (password.length() &gt;= PASSWORD_LENGTH &amp;&amp; uppers &gt;= minUppers &amp;&amp; digits &gt;= minDigits
                &amp;&amp; specials &gt;= minSpecials) {

            return isValidPassword = true;
        } else {
            return isValidPassword = false;
        }

    }
    public static void inputUser(){
        System.out.println(&quot;Please enter username:&quot;);
         Scanner un = new Scanner(System.in);
            String userName = un.next();

            if (checkUserName(userName)) {
                System.out.println(&quot;Username successfully captured&quot;);
            } else {
                System.out.println(
                        &quot;Username is not correctly formatted, please ensure that your username contains an underscore and is no more than 5 characters in length.&quot;);
            }
    }

    

    public static void inputPass(){
        System.out.println(&quot;Please enter password:&quot;);
         Scanner pa = new Scanner(System.in);
            String userPass = pa.next();

            if (checkPasswordComplexity(userPass)) {
                System.out.println(&quot;Password successfully captured&quot;);
            } else {
                System.out.println(
                        &quot;Password is not correctly formatted, please ensure that the password contains at least 8 characters, a capital letter, a number and a special character.&quot;);
            }
        
    }

    
}

</code></pre>
<p>LoginTest.java</p>
<pre><code>package st10035771;

import org.junit.Test;
import static org.junit.Assert.*;

public class LoginTest {

    public LoginTest() {
    }

    Login loginTest = new Login();

    @Test
    public void testSomeMethod() {

    }

    @Test
    public void testCheckUserName() {
        assertTrue(loginTest.checkUserName(&quot;kyl_1&quot;));
    }

    @Test
    public void testCheckUserNameF() {
        assertFalse(loginTest.checkUserName(&quot;kyle!!!!!!!&quot;));
    }

    @Test
    public void testIsValidPassword() {
        assertTrue(loginTest.checkPasswordComplexity(&quot;Ch&amp;&amp;sec@ke99!&quot;));
    }

    @Test
    public void testIsValidPasswordF() {
        assertFalse(loginTest.checkPasswordComplexity(&quot;password&quot;));
    }

}
</code></pre>
<p>The only one that fails when tested all at once is the <code>TestIsValidPasswordF</code></p>
",https://stackoverflow.com/questions/72202024/one-method-fails-unit-test-only-when-all-tests-are-run-but-passes-when-tested-in,"['java', 'unit-testing', 'validation', 'visual-studio-code', 'junit']",1075,False,0,1
Why does junit dependencies have not installed properly?,"<p>I am trying to run an unit testing and I have already installed the dependencies. Below is the pom.xml file.</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;org.example&lt;/groupId&gt;
    &lt;artifactId&gt;Lecture_1-2&lt;/artifactId&gt;
    &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt;

    &lt;properties&gt;
        &lt;maven.compiler.source&gt;17&lt;/maven.compiler.source&gt;
        &lt;maven.compiler.target&gt;17&lt;/maven.compiler.target&gt;
    &lt;/properties&gt;

    &lt;dependencies&gt;
        &lt;!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-api&lt;/artifactId&gt;
            &lt;version&gt;5.8.2&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;!-- https://mvnrepository.com/artifact/org.mockito/mockito-all --&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.mockito&lt;/groupId&gt;
            &lt;artifactId&gt;mockito-all&lt;/artifactId&gt;
            &lt;version&gt;1.10.19&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&lt;/artifactId&gt;
            &lt;version&gt;2.1&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;
    &lt;/dependencies&gt;

&lt;/project&gt;
</code></pre>
<p>But when I am running my test case, it still gives me the error,</p>
<pre><code>Cannot resolve symbol 'test'
</code></pre>
<p>I have tried reloading the maven project but it has not worked.</p>
<p>This is what I get when importing junit. Why is this?
<a href=""https://i.stack.imgur.com/3AMbu.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/3AMbu.png"" alt=""Cannot Resolve symbol junit?"" /></a></p>
<p>What is the reason for the issue?</p>
",https://stackoverflow.com/questions/71309320/why-does-junit-dependencies-have-not-installed-properly,"['java', 'maven', 'intellij-idea', 'junit']",82,False,0,0
Are assert and NDEBUG being used a lot these days?,"<p>I want to know whether the assert and NDEBUG parts are used in modern c++.</p>
<p>There are thread and memory checkers such as valgrind and sanitizer. And in unit testing, gtest is famous.
And even if I use those, I'm not sure why the debug part is taken out of the preprocessing separately. I think that the code that finds the bug always should be preserved.</p>
",https://stackoverflow.com/questions/74526387/are-assert-and-ndebug-being-used-a-lot-these-days,"['c++', 'debugging', 'c-preprocessor']",64,False,0,1
How to implement conditional requirements in a conanfile?,"<p>We have projects that require different Conan packages during unit tests (i.e. mocks) than during normal compilation.
Is there a best practice how to implement conditional requirements in a conanfile for such a use case?</p>
<p>We have tried using switches with environment variables like this:</p>
<pre><code>class project_a(ConanFile):
....
    def requirements()
        if os.getenv('UNIT_TESTING') == 'true':
            self.requires('mock_for_testing/1.0.0@someuser/somechannel
...
</code></pre>
<p>But then the requirements for project_a are always changed during unit testing.
So also when a project is tested, that consumes project_a.</p>
",https://stackoverflow.com/questions/70852585/how-to-implement-conditional-requirements-in-a-conanfile,"['jenkins', 'conan']",375,True,0,1
"When and where to use JUnit, Mockito and Integration testing in Spring Boot Application?","<p>I'm very novice to Unit Testing, I have created a Spring Boot Application and now I want to do some testing what's confusing me is where to use what e.g. I have classes and interfaces Controllers, Service, Repository I know each will have it's own Test class, so what will I be using let's say in Controllers, JUnit or Mockito ? similar question for Service and Repository.</p>
",https://stackoverflow.com/questions/74489307/when-and-where-to-use-junit-mockito-and-integration-testing-in-spring-boot-appl,"['java', 'spring-boot', 'mockito', 'junit5']",208,True,0,1
How do I initialize a function as every combination of a set of (Boolean) flags? (C++),"<p>Im doing unit testing and want to test my functions against each possible combinations of flags. Each flag can be either a 1 or a 0. the flags are global variables.</p>
<p>This is what I tried:</p>
<p>`</p>
<pre><code>for(flagA = 0; flagA &lt;= 1; ++flagA){
    for(flagB = 0; flagB &lt;= 1; ++flagB){
        for(flagC = 0; flabC &lt;= 1; ++flagC){
            for(flagD = 0; flagD &lt;= 1; ++flagD){
                myFunction();
            }
        }
    }
};
</code></pre>
<p>`</p>
<p>The issue I am having is myFunction() can change a flags value, causing the other calls of myFunction() to be called with unexpected flag values rather than testing every combination.</p>
",https://stackoverflow.com/questions/74243468/how-do-i-initialize-a-function-as-every-combination-of-a-set-of-boolean-flags,['c++'],73,False,-1,4
Python unittest when to test for value or object equality,"<p>I have the following code that I'm testing.</p>
<p><code>main.py</code></p>
<pre><code>import helpers

def do_something(some_arg):
    ...
    return helpers.help_do_something(some_arg)
</code></pre>
<p><code>test_main.py</code></p>
<pre><code>import unittest
from unittest import mock

class TestDoSomething(unittest.Testcase):
    @mock.patch('path.to.patch')
    def setUp(self, *_):
        import main
        self.main = main

    @mock.patch('main.helpers')
    def test_0_1(self, helpers_mock):
        ret = self.main.do_something('test_arg')
        self.assertIs(ret, helpers_mock.help_do_something.return_value)
</code></pre>
<p>When I'm testing the return value of <code>do_something</code> my instinct is telling me that the comparison should be asserting object equality, not value equality. Am I correct in thinking this? I'm having a difficult time articulating why this should be the case.</p>
<p>More generally, when should we be testing for object equality versus value equality in unit testing?</p>
",https://stackoverflow.com/questions/73476246/python-unittest-when-to-test-for-value-or-object-equality,"['python', 'unit-testing', 'mocking', 'python-unittest', 'object-equality']",115,False,0,1
Unit test of Spring MongoDB returns null,"<p>I'm trying to Unit test my MongoDB-based Spring Boot application, and I'm getting a <code>java.lang.NullPointerException: Cannot invoke &quot;blueprint.model.Garage.getCarModel()&quot; because &quot;savedGarage&quot; is null</code> error. The code is down below:</p>
<p>My Service:</p>
<pre><code> @Service
public class GarageService {

private final GarageRepository garageRepository;

@Autowired
public GarageService(GarageRepository garageRepository) {
    this.garageRepository = garageRepository;
}

public void addToGarage(Garage garage) {
    Optional&lt;Garage&gt; garageOptional = garageRepository.findByCarModel(garage.getCarModel());
    if(garageOptional.isPresent()) {
        throw new IllegalStateException(&quot;This Car model is already in our garage!&quot;);
    }
    garageRepository.save(garage);
}

public List&lt;Garage&gt; showOurGarage() {
    return garageRepository.findAll();
}

public void deleteFromGarage(String id) {
    boolean exists = garageRepository.existsById(id);
    if(!exists) {
        throw new IllegalStateException(&quot;A car with id &quot; + id + &quot; is not in our Garage.&quot;);
    }
    garageRepository.deleteById(id);
}

public void updateCar(String id, String carModel, Integer HP, Integer year, String designer) {
    Garage garage = garageRepository.findById(id)
            .orElseThrow(() -&gt; new IllegalStateException(
                    &quot;A car with the id &quot; + id + &quot; is not in our Garage.&quot;));
    if(carModel != null &amp;&amp; carModel.length() &gt; 0 &amp;&amp; !Objects.equals(garage.getCarModel(), carModel)) {
        garage.setCarModel(carModel);
    }
    if(HP != null &amp;&amp; !Objects.equals(garage.getHP(), HP)) {
        garage.setHP(HP);
    }
    if(year != null &amp;&amp; !Objects.equals(garage.getYear(), year)) {
        garage.setYear(year);
    }
    if(designer != null &amp;&amp; designer.length() &gt; 0 &amp;&amp; !Objects.equals(garage.getDesigner(), designer)) {
        garage.setDesigner(designer);
    }
    garageRepository.save(garage);
}
}
</code></pre>
<p>My Repository:</p>
<pre><code>@org.springframework.stereotype.Repository
public interface GarageRepository extends MongoRepository&lt;Garage, String&gt; {

Optional&lt;Garage&gt; findByCarModel(String carModel);
</code></pre>
<p>And here's a test:</p>
<pre><code>@DisplayName(&quot;Garage Service Test&quot;)
@DataMongoTest
class GarageServiceTest {

@Mock
private GarageRepository garageRepository;
private GarageService garageService;

@BeforeEach
void setUp() {
    MockitoAnnotations.openMocks(this);
    garageService = new GarageService(garageRepository);
}

@Test
@DisplayName(&quot;Add Car To Garage Test&quot;)
void testAddToGarage() {
    Garage testGarage = new Garage();
    testGarage.setId(&quot;630ca281f12905d5f5249f08&quot;);
    testGarage.setCarModel(&quot;Shelby Cobra&quot;);
    testGarage.setHP(485);
    testGarage.setYear(1965);
    testGarage.setDesigner(&quot;Carroll Shelby&quot;);

    Garage savedGarage = garageRepository.save(testGarage);

    String testedGarage = savedGarage.getCarModel();

    Optional&lt;Garage&gt; garages = garageRepository.findByCarModel(&quot;Shelby Cobra&quot;);
    assertEquals(testedGarage, garages.toString());
}
</code></pre>
<p>I'm pretty much green with Unit testing and MongoDB, so I'm not sure where and why this error happens. I've skipped adding the Controller because I think the rest of the code will be sufficient.</p>
",https://stackoverflow.com/questions/73743453/unit-test-of-spring-mongodb-returns-null,"['java', 'mongodb', 'junit5']",382,True,0,1
TypeError: Cannot read properties of undefined (reading &#39;html&#39;) - Jest,"<p>I have <code>React typescript</code> web app, and I would like to create some unit testing.
I am very new with tests and <code>Jest</code>, so I try to write a unit test for a basic component that displays 4 social links</p>
<p>My <code>SocialMediaArea.tsx</code> simply map a json to create 4 button with social medias links.</p>
<p>Here is my test component :</p>
<pre><code>import {render, screen} from &quot;@testing-library/react&quot;;
import SocialMediaArea from &quot;../components/Areas/SocialMediaArea&quot;;

describe(&quot;SocialMediaArea&quot;, () =&gt; {
    it(&quot;renders the correct social media links&quot;, () =&gt; {
        render(&lt;SocialMediaArea /&gt;);

        // Check that the correct number of social media links are rendered
        expect(screen.getAllByRole(&quot;link&quot;).length).toEqual(4);

        // Check that the Instagram link is correct
        expect(screen.getByRole(&quot;link&quot;, {name: /instagram/i})).toHaveAttribute(
            &quot;href&quot;,
            &quot;link&quot;
        );

        // Check that the Facebook link is correct
        expect(screen.getByRole(&quot;link&quot;, {name: /facebook/i})).toHaveAttribute(
            &quot;href&quot;,
            &quot;link&quot;
        );

        // Check that the Twitter link is correct
        expect(screen.getByRole(&quot;link&quot;, {name: /twitter/i})).toHaveAttribute(&quot;href&quot;, &quot;link&quot;);

        // Check that the YouTube link is correct
        expect(screen.getByRole(&quot;link&quot;, {name: /youtube/i})).toHaveAttribute(
            &quot;href&quot;,
            &quot;link&quot;
        );
    });
});
</code></pre>
<p>This test generate following error :</p>
<pre><code> TypeError: Cannot read properties of undefined (reading 'html')

      at new JSDOMEnvironment (node_modules/jest-environment-jsdom/build/index.js:72:44)
</code></pre>
<p><code>jest.config.js</code></p>
<pre><code>/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
    preset: &quot;ts-jest&quot;,
    testEnvironment: &quot;jsdom&quot;,
};
</code></pre>
<p>My <code>package.json</code></p>
<pre><code>&quot;devDependencies&quot;: {
        &quot;@testing-library/dom&quot;: &quot;^8.19.1&quot;,
        &quot;@testing-library/react&quot;: &quot;^13.4.0&quot;,
        &quot;@types/testing-library__react&quot;: &quot;^10.2.0&quot;,
        &quot;autoprefixer&quot;: &quot;^10.4.13&quot;,
        &quot;eslint&quot;: &quot;8.30.0&quot;,
        &quot;eslint-config-react-app&quot;: &quot;^7.0.1&quot;,
        &quot;jest&quot;: &quot;^29.3.1&quot;,
        &quot;postcss&quot;: &quot;^8.4.20&quot;,
        &quot;postcss-import&quot;: &quot;^15.1.0&quot;,
        &quot;prettier&quot;: &quot;^2.8.1&quot;,
        &quot;prettier-plugin-tailwindcss&quot;: &quot;^0.2.1&quot;,
        &quot;react-test-renderer&quot;: &quot;^18.2.0&quot;,
        &quot;tailwindcss&quot;: &quot;^3.2.4&quot;,
        &quot;ts-jest&quot;: &quot;^29.0.3&quot;
    }
</code></pre>
<p>Where is my mistake ?</p>
",https://stackoverflow.com/questions/74948978/typeerror-cannot-read-properties-of-undefined-reading-html-jest,"['reactjs', 'unit-testing', 'jestjs']",965,True,0,1
How to mock the environment variables to write unit tests for a grails application?,"<p>I have the following controller in which a method returns keywords based on the environment it is running on.</p>
<pre><code>import grails.util.Environment

class SearchController {

    static String currentEnvironment() {
        def curEnvironment
        if (Environment.current == Environment.PRODUCTION){
            curEnvironment = 'prod'
        }
        else {
            curEnvironment = 'alpha'
        }
        return curEnvironment
    }
}
</code></pre>
<p>How do I write a unit testing to mock the environment variables? Something like:</p>
<pre><code>void testEnvironment(){
    //mock(grails.util.Environment.current = &quot;PRODUCTION&quot;)
    assert controller.currentEnvironment == 'prod'
}
</code></pre>
<p>I tried running the test with <code>-Dgrails.env=prod</code> and it works, but this approach is not generic. So I was wondering if I could set the environment variables for the tests or better mock it.</p>
",https://stackoverflow.com/questions/73709188/how-to-mock-the-environment-variables-to-write-unit-tests-for-a-grails-applicati,"['grails', 'groovy', 'junit']",255,False,0,0
Is this correct that I would have to modify all the code that uses arrow functions in order to test them?,"<p>My background with unit testing is minimal.</p>
<p>From what I've found on Google it appears that I would have to change a lot of the code in our application in order to unit test arrow function code.</p>
<p>So, if code were as follow</p>
<pre><code> class MyComponent {
   fun: () =&gt; 'hello';
   constructor() {};
 }
</code></pre>
<p>Then I must change it to something like the following in order to unit test it.</p>
<p><strong>Create an interface</strong></p>
<pre><code>Interface MyService {
  fun: () =&gt; string;
}
</code></pre>
<p><strong>And change the code,</strong></p>
<pre><code>class Component {
   constructor() {
     this.mysService = () =&gt; {
       return {
         fun: () =&gt; 'hello'
       };
     };
   }
   myService: () =&gt; MyService;
 }
</code></pre>
",https://stackoverflow.com/questions/73991148/is-this-correct-that-i-would-have-to-modify-all-the-code-that-uses-arrow-functio,"['angular', 'unit-testing', 'jasmine', 'karma-jasmine', 'spectator']",23,False,0,1
How to Unit testing in CQRS Pattern C#,"<p>I need to know how to Unit testing in CQRS pattern. as a beginer i dont have much idea about that. I develope below Command and queries. I need to Test those</p>
<p>Here is my <strong>add student command</strong></p>
<pre><code> public record AddStudentCommand(Student student):IRequest&lt;Student&gt;;
</code></pre>
<p>Hear is my <strong>Add Studnet Hadler</strong></p>
<pre><code> public class AddStudentHandler : IRequestHandler&lt;AddStudentCommand, Student&gt;
{
    private readonly appDbContext _context;
    public AddStudentHandler(appDbContext context)
    {
        _context = context;
    }

    public async Task&lt;Student&gt; Handle(AddStudentCommand request, CancellationToken cancellationToken)
    {
        _context.students.Add(request.student);
        await _context.SaveChangesAsync();
        return request.student;
    }
}
</code></pre>
<p>This is <strong>Get All Student Query</strong></p>
<pre><code>public record GetAllStudentDataQuery : IRequest&lt;IEnumerable&lt;Student&gt;&gt;;
</code></pre>
<p>This is my <strong>Get All Student Handler</strong></p>
<pre><code>public class GetAllStudentHandler : IRequestHandler&lt;GetAllStudentDataQuery, IEnumerable&lt;Student&gt;&gt;
{
    private readonly appDbContext _context;
    public GetAllStudentHandler(appDbContext context)
    {
        _context = context;
    }

    public async Task&lt;IEnumerable&lt;Student&gt;&gt; Handle(GetAllStudentDataQuery request, CancellationToken cancellationToken)
    {
        return _context.students;
    }
}
</code></pre>
<p><strong>I need to Unit test these methods.</strong></p>
",https://stackoverflow.com/questions/74010676/how-to-unit-testing-in-cqrs-pattern-c,"['unit-testing', 'testing', 'asp.net-web-api', 'cqrs']",165,False,0,1
System.ArgumentException: A matching constructor for the given arguments was not found on the mocked type,"<p>I am Performing Unit Testing using Moq and I am facing this error :</p>
<blockquote>
<p>System.ArgumentException: A matching constructor for the given arguments was not found on the mocked type.
---&gt; System.MissingMethodException: Method not found: 'System.Reflection.Emit.AssemblyBuilder System.AppDomain.DefineDynamicAssembly(System.Reflection.AssemblyName, System.Reflection.Emit.AssemblyBuilderAccess)'.
at Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName)</p>
</blockquote>
<p>I'm new in this I don't understand what is the error. So, please can anyone please tell what I am doing wrong.</p>
<p>UniTest1.cs</p>
<pre><code>public class EventUnitTests
{
    private readonly EventAppService _sut;
    private readonly Mock&lt;IEventRepository&gt; _eventMock = new Mock&lt;IEventRepository&gt;();
    private readonly Mock&lt;IUserEventRepository&gt; _userEventMock = new Mock&lt;IUserEventRepository&gt;();
    private readonly Mock&lt;IUserRepository&gt; _userMock = new Mock&lt;IUserRepository&gt;();
    private readonly Mock&lt;ILogger&gt; _logger = new Mock&lt;ILogger&gt;();
    private readonly Mock&lt;IMapper&gt; _mapper = new Mock&lt;IMapper&gt;();
    private readonly Mock&lt;IEventUnitOfWork&gt; _eventUnitOfWork = new Mock&lt;IEventUnitOfWork&gt;();
    private readonly Mock&lt;IExceptionManager&gt; _exceptionManager = new Mock&lt;IExceptionManager&gt;();


    public EventUnitTests()
    {
        _sut = new EventAppService(_eventUnitOfWork.Object, _userEventMock.Object, _userMock.Object, _eventMock.Object, _mapper.Object, _exceptionManager.Object);
    }
    [Fact]
    public async void GetEventDetailById()
    {
        var events = new Event { Id = 1, Title = &quot;Three mistakes of my life&quot;, Date = DateTime.Now, Location = &quot;Plot 13&quot;, Duration = 3, StartTime = DateTime.Now, Description = &quot; A GOOD BOOK 1&quot;, OtherDetails = null, Type = EventType.PRIVATE, InviteByEmail = &quot;nitin6283saini@gmail.com&quot; };
        _eventMock.Setup(p =&gt; p.GetById(1)).Returns(events);

        _mapper.Setup(p =&gt; p.Map&lt;Event, EventDTO&gt;(events)).Returns(new EventDTO
        {
            Title = events.Title,
            Date = DateTime.Now,
            Location = events.Location,
            Duration = events.Duration,
            StartTime = events.StartTime,
            Description = events.Description,
            OtherDetails = events.OtherDetails,
            Type = events.Type,
            InviteByEmail = events.InviteByEmail
        });

        //EventAppService s = new EventAppService(_eventUnitOfWork.Object, _userEventMock.Object, _userMock.Object, _eventMock.Object, _mapper.Object, _exceptionManager.Object);
        OperationResult&lt;EventDTO&gt; result = _sut.GetEventById(1);
        Assert.Equal(result.Data.Id, events.Id);
        Assert.Equal(result.Data.Title, events.Title);
        Assert.Equal(result.Data.Location, events.Location);
    }

}
</code></pre>
<p>EventAppService.cs</p>
<pre><code>public EventAppService(IEventUnitOfWork unitOfWork, IUserEventRepository userEventRepository, IUserRepository userRepository ,IEventRepository eventRepository, IMapper mapper, IExceptionManager exceptionManager) : base(unitOfWork, exceptionManager)
{
    this._mapper = mapper;
    this._eventRepository = eventRepository;
    this._userRepository = userRepository;
    this._usereventRepository = userEventRepository;
}
</code></pre>
",https://stackoverflow.com/questions/71857784/system-argumentexception-a-matching-constructor-for-the-given-arguments-was-not,"['c#', 'unit-testing', 'asp.net-core', 'moq']",248,False,0,0
share db session across multiple lambda invocations using Mangum,"<p>So far, I've been declaring my db connection outside of my web server app creation:</p>
<pre class=""lang-py prettyprint-override""><code># src/main.py
db_session = ... # connection 
app = FastAPI()
handler = Mangum(app)

# other files would import db_session from src.main
# and query the db through it
</code></pre>
<p>For better unit testing, I decided to move the db declaration as part of the app state:</p>
<pre class=""lang-py prettyprint-override""><code>
def create_app(settings: Settings):
    app = FastApi()
    app.state.config = settings
    app.state.db_session = ... # here is the db declaration, using `settings` to get db credentials
    ...
    return app

app = create_app(settings)
handler = Mangum(app)
</code></pre>
<p>does anyone know if, by wrapping the app around <code>Mangum</code>, db session won't be shared anymore across multiple lambda invocations ? I don't know to which extent <code>app</code> here is within the handler real code.</p>
",https://stackoverflow.com/questions/71511475/share-db-session-across-multiple-lambda-invocations-using-mangum,"['amazon-web-services', 'aws-lambda', 'fastapi']",252,False,0,1
Adding 2FA to Rails Devise,"<p>I'm adding 2FA to an existing Rails app using Devise, using the active_model_otp gem to handle the authenticator code. Based on my unit testing, it seems to work. But given my limited knowledge about devise, I'd like to double check if there is any security issues with the implementation, and the sequencing of the calls.</p>
<p>For simplicity, I will only include the controller code for login:</p>
<pre><code># /app/controllers/users/sessions_controller.rb
class SessionsController &lt; Devise::SessionsController

  def create
    self.resource = resource_class.find_for_authentication(sign_in_params.except(:password, :otp_response_code, :remember_me))
    if resource

      if resource.active_for_authentication?
        if resource &amp;&amp; !resource.user_2fa_activation_date.present?
          super
        elsif resource &amp;&amp; resource.user_2fa_activation_date.present?
          if params[:user][:otp_response_code].present?
            if resource.authenticate_otp(params[:user][:otp_response_code])
              super
            else
              sign_out(resource)
              back_to_login_page(&quot;Invalid 2fa token value.&quot;)
            end
          else
            sign_out(resource)
            back_to_login_page(&quot;Your account requires 2-factor authentication.&quot;)
          end
        end
      else
        super
      end
    else
      # case when email is invalid.
      super
    end
  end

  def back_to_login_page(alert_message)
    redirect_to new_user_session_path, :alert =&gt; alert_message
    return false
  end
  
end
</code></pre>
",https://stackoverflow.com/questions/73282742/adding-2fa-to-rails-devise,"['ruby-on-rails', 'devise']",134,False,0,0
Testing Starknet Cairo contract function with address,"<p>I built a module with Cairo language and I would like to unit test it. The contract is pretty simple : it manages a list of authorized addresses and provide some &quot;modifier&quot; functions to help.</p>
<p>I have taken the sample unit testing code from the documentation but nothing is referring about sending an account address to a function with python.</p>
<p>How should I proceed ?</p>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/73034919/testing-starknet-cairo-contract-function-with-address,"['python', 'starknet', 'cairo-lang']",100,False,0,1
C# In-memory database. Nested entities,"<p>I'm using an in-memory database and Entity Framework for unit testing. In the test method, I added several entities (for example, two) to the main:</p>
<pre><code>var user = fixture.Build&lt;User&gt;().Create();
await context.Users.AddAsync(user);

foreach (var item in items)
{
    var game = fixture.Build&lt;Game&gt;().With(x =&gt; x.User, user)
        .With(x =&gt; x.Name, item.Name).With(x =&gt; x.Weight, item.Weight).Create();
    await context.Games.AddAsync(game);
}

await context.SaveChangesAsync();
</code></pre>
<p>In the business logic of the tested method I fetch only one game with the heaviest weight:</p>
<pre><code>var user = await context.Users
                        .Where(x =&gt; x.UserId == userId)
                        .Include(x =&gt; x.Games
                                       .OrderByDescending(y =&gt; y.Weight)
                                       .Take(1))
                        .FirstOrDefaultAsync();
</code></pre>
<p>But in the end, <code>user.Games</code> contain all entities (two). Because of this, the test falls.</p>
<p>Is there any way to avoid this without changing the business logic? Thank you</p>
",https://stackoverflow.com/questions/73271347/c-in-memory-database-nested-entities,"['c#', 'entity-framework', 'unit-testing']",51,False,1,0
TypeError when implement Unit Test with Jest on NextJS Commerce,"<p>I'm currently trying to implement Unit Testing on <a href=""https://github.com/vercel/commerce"" rel=""nofollow noreferrer"">NextJS Commerce</a> using Jest for vendure provider.</p>
<p>My component: \components\auth\LoginView.tsx</p>
<pre><code>  import useLogin from '@framework/auth/use-login'
  const login = useLogin()
  const handleLogin = async (values: any) =&gt; {
    try {
      setLoading(true)
      setMessage('')
      await login({
        ...values,
      })
      setLoading(false)
      closeModal()
    } catch ({ errors }) {
      // @ts-ignore
      setLoading(false)
    }
  }
</code></pre>
<p>And my test file:</p>
<pre><code>import { LoginView } from '@components/auth'
import { render, screen, waitFor } from '@testing-library/react'

describe('LoginView Component', () =&gt; {
  it('renders without error', () =&gt; {
    render(&lt;LoginView /&gt;)
  })
})
</code></pre>
<p>I only try to render the component but it keeps appearing the TypeError:</p>
<pre><code>TypeError: (0 , _useLogin.default) is not a function for the line: 
 
&gt; const login = useLogin()
</code></pre>
<p>And similar error for different authentication functions like Forgot Password, Reset Password,... I even try to render Index file and it just doesn't render without error.</p>
<p>Any help will be greatly appreciated.</p>
",https://stackoverflow.com/questions/70661442/typeerror-when-implement-unit-test-with-jest-on-nextjs-commerce,"['typescript', 'unit-testing', 'jestjs', 'next.js']",137,False,1,0
MissingStubError: &#39;get&#39; when using mockito 5.1.0 to test api using riverpod,"<p>I am trying to use mockito to return a fake response in the http.Client call and be able to test the service. I have followed the documentation. It tells me that I should use annotate to generate a fake class, but it seems that the null safe of flutter is causing problems. Does anyone know how? fix it thanks</p>
<p><strong>movies_provider_test.dart</strong></p>
<pre><code>import 'package:http/http.dart' as http;
import 'package:mockito/mockito.dart';
import 'package:mockito/annotations.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:watch_movie_app/src/data/data_source/remote/http_request.dart';
import 'package:watch_movie_app/src/data/models/models.dart';

import 'package:watch_movie_app/src/domain/services/movie_service.dart';
import 'package:watch_movie_app/src/environment_config.dart';

import 'mocks/popular_movies.dart';
import 'movies_provider_test.mocks.dart';

@GenerateMocks([http.Client])
void main() {
  test('returns an movies if the http call completes sucessfully', () async {
    final mockHttp = MockClient();
    final container = ProviderContainer(
      overrides: [
        httpClientProvider.overrideWithValue(HttpRequest(httpClient: mockHttp)),
      ],
    );
    addTearDown(container.dispose);

    final environmentConfig = container.read(environmentConfigProvider);
    final movieService = container.read(movieServiceProvider);

    String urlApi =
        &quot;${environmentConfig.domainApi}/${environmentConfig.apiVersion}/tv/popular?api_key=${environmentConfig.movieApiKey}&amp;language=en-US&amp;page=1&quot;;
    Uri url = Uri.parse(urlApi);
    when(mockHttp.get(url)).thenAnswer(
      (_) async =&gt; http.Response(fakeMovies, 200),
    );

    expectLater(await movieService.getMovies(), isInstanceOf&lt;List&lt;Movie&gt;&gt;());
  });
}
</code></pre>
<p><strong>movie_service.dart</strong></p>
<pre><code>import 'package:http/http.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:watch_movie_app/src/data/data_source/remote/http_request.dart';
import 'package:watch_movie_app/src/domain/enums/enums.dart';
import 'package:watch_movie_app/src/data/models/models.dart';
import 'package:watch_movie_app/src/environment_config.dart';
import 'package:watch_movie_app/src/helpers/movie_api_exception.dart';

final movieServiceProvider = Provider&lt;MovieService&gt;((ref) {
  final config = ref.read(environmentConfigProvider);
  final httpRequest = ref.read(httpClientProvider);
  return MovieService(config, httpRequest);
});

class MovieService {
  final EnvironmentConfig _environmentConfig;
  final HttpRequest _http;

  MovieService(this._environmentConfig, this._http);

  Future&lt;List&lt;Movie&gt;&gt; getMovies() async {
    try {
      String url =
          &quot;${_environmentConfig.domainApi}/${_environmentConfig.apiVersion}/tv/popular?api_key=${_environmentConfig.movieApiKey}&amp;language=en-US&amp;page=1&quot;;
      final response =
          await _http.request(typeHttp: EnumHttpType.get, urlApi: url);

      if (response.statusCode != 200) {
        throw const MovieApiException('Error al consulta las series populares');
      }

      List&lt;Movie&gt; movies = allMoviesFromJson(response.body);

      return movies;
    } on ClientException {
      throw const MovieApiException('Error al consultar la información');
    }
  }

  Future&lt;List&lt;Movie&gt;&gt; getMoviesRecommendations() async {
    try {
      String url =
          &quot;${_environmentConfig.domainApi}/${_environmentConfig.apiVersion}/tv/top_rated?api_key=${_environmentConfig.movieApiKey}&amp;language=en-US&amp;page=1&quot;;
      final response =
          await _http.request(typeHttp: EnumHttpType.get, urlApi: url);

      if (response.statusCode != 200) {
        throw const MovieApiException(
            'Error al consulta las series recomendadas');
      }

      List&lt;Movie&gt; movies = allMoviesFromJson(response.body);
      return movies;
    } on ClientException {
      throw const MovieApiException('Error al consultar los recomendados');
    }
  }

  Future&lt;MovieExtend&gt; getDetailMovie(int id) async {
    try {
      String url =
          &quot;${_environmentConfig.domainApi}/${_environmentConfig.apiVersion}/tv/$id?api_key=${_environmentConfig.movieApiKey}&amp;language=en-US&amp;page=1&quot;;

      final Response response =
          await _http.request(typeHttp: EnumHttpType.get, urlApi: url);

      if (response.statusCode != 200) {
        throw const MovieApiException(
            'Error al consulta el detalle de la serie');
      }

      MovieExtend movieExtend = movieExtendFromJson(response.body);
      return movieExtend;
    } on ClientException {
      throw const MovieApiException(
          'Error al consultar el detalle de la serie');
    }
  }

  Future&lt;List&lt;Movie&gt;&gt; getAirtodayMovies() async {
    try {
      String url =
          &quot;${_environmentConfig.domainApi}/${_environmentConfig.apiVersion}/tv/airing_today?api_key=${_environmentConfig.movieApiKey}&amp;language=en-US&amp;page=1&quot;;

      final Response response =
          await _http.request(typeHttp: EnumHttpType.get, urlApi: url);

      if (response.statusCode != 200) {
        throw const MovieApiException(
            'Error al consultar las series, intente nuevamente mas tarde');
      }
      List&lt;Movie&gt; movies = allMoviesFromJson(response.body);
      return movies;
    } on ClientException {
      throw const MovieApiException('Error al consultar las series de hoy');
    }
  }
}
</code></pre>
<p><strong>htt_request.dart</strong></p>
<pre><code>import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;

import 'package:watch_movie_app/src/domain/enums/enums.dart';

/// Clase que nos permite hacer peticiones Http
/// usando la libreria http.dar
class HttpRequest {
  final http.Client _httpClient;
  late String? token;

  HttpRequest({http.Client? httpClient})
      : _httpClient = httpClient ?? http.Client();

  Future&lt;http.Response&gt; request(
      {required EnumHttpType typeHttp, required String urlApi, data}) async {
    Map&lt;String, String&gt; headers = {'Content-Type': 'application/json'};
    Uri url = Uri.parse(urlApi);
    switch (typeHttp) {
      case EnumHttpType.post:
        return _httpClient.post(url, body: data, headers: headers);
      case EnumHttpType.get:
        return _httpClient.get(url, headers: headers);
      case EnumHttpType.patch:
        return _httpClient.patch(url, headers: headers);
      case EnumHttpType.put:
        return _httpClient.put(url, headers: headers);
      case EnumHttpType.delete:
        return _httpClient.delete(url, headers: headers);
      default:
        return _httpClient.get(url);
    }
  }
}

final httpClientProvider = Provider&lt;HttpRequest&gt;((ref) =&gt; HttpRequest());
</code></pre>
<p><strong>error detail</strong></p>
<pre><code>MissingStubError: 'get'

No stub was found which matches the arguments of this method call:

get(https://api.themoviedb.org/3/tv/popular?api_key=4dc138c853e44e4ea1d3dfd746fe451d&amp;language=en-US&amp;page=1, {headers: {Content-Type: application/json}}\)

Add a stub for this method using Mockito's 'when' API, or generate the MockClient mock with a MockSpec with 'returnNullOnMissingStub: true' (see https://pub.dev/documentation/mockito/latest/annotations/MockSpec-class.html\).

package:mockito/src/mock.dart 191:7                                          Mock._noSuchMethod

package:mockito/src/mock.dart 185:45                                         Mock.noSuchMethod

test\movies_provider_test.mocks.dart 45:14                                   MockClient.get

package:watch_movie_app/src/data/data_source/remote/http_request.dart 23:28  HttpRequest.request

package:watch_movie_app/src/domain/services/movie_service.dart 26:23         MovieService.getMovies

test\movies_provider_test.dart 36:36                                         main.&lt;fn&gt;

test\movies_provider_test.dart 17:68

   
</code></pre>
<p><strong>link doc:</strong>
<a href=""https://docs.flutter.dev/cookbook/testing/unit/mocking"" rel=""nofollow noreferrer"">mockito unit testing</a></p>
",https://stackoverflow.com/questions/71490908/missingstuberror-get-when-using-mockito-5-1-0-to-test-api-using-riverpod,"['flutter', 'unit-testing', 'mockito', 'riverpod', 'null-safety']",808,True,1,2
Why doesn&#39;t getByRole get an element with a name (but it does with aria-label)?,"<p>What I'm trying is to get a <code>&lt;button/&gt;</code> with <code>getByRole</code> for unit testing. Here's a simplified example:</p>
<pre><code>&lt;Button
  classes={myCustomClass}
  name={'day'}
&gt;
  &lt;ViewDayOutlinedIcon /&gt; {/** &lt;- This is a Material UI icon */}
&lt;/Button&gt;

// There are similar other buttons with different values in &quot;name&quot; attribute
</code></pre>
<p>The test case looks like...</p>
<pre><code>render(&lt;Component/&gt;);
const dayButton = screen.getByRole('button', { name: 'day' });

// fire events with dayButton and expect something
</code></pre>
<p>The console says <code>TestingLibraryElementError: Unable to find an accessible element with the role &quot;button&quot; and name &quot;day&quot;</code>, and shows the following</p>
<pre><code>Here are the accessible roles:

  button:

    Name &quot;&quot;:
    &lt;button
      class=&quot;MuiButtonBase-root makeStyles-iconButtonRoot-19 MuiIconButton-root MuiIconButton-sizeMedium css-78trlr-MuiButtonBase-root-MuiIconButton-root&quot;
      name=&quot;day&quot;
      tabindex=&quot;0&quot;
      type=&quot;button&quot;
    /&gt;
</code></pre>
<p>If I replace <code>name={'day'}</code> with <code>aria-label={'day'}</code> in the component, the button can be found by <code>screen.getByRole('button', { name: 'day' })</code>.</p>
<p>Why does it happen? <code>getByRole</code> is supposed to find an element by a name attribute and a wigdet role (<code>button</code>, <code>chekckbox</code>, <code>link</code>, etc), right? I can't find the answer from <a href=""https://testing-library.com/docs/queries/about/#priority"" rel=""nofollow noreferrer"">RTL's doc</a>.</p>
",https://stackoverflow.com/questions/73890955/why-doesnt-getbyrole-get-an-element-with-a-name-but-it-does-with-aria-label,"['reactjs', 'accessibility', 'react-testing-library']",859,True,1,1
Testing a Typescript React Component Giving Error on getByText,"<p>I'm trying to add unit testing to an application written with Typescript and React. I have a very basic component just for the sake of simplicity.</p>
<pre><code>import React from &quot;react&quot;;
import ReactDOM from &quot;react-dom&quot;;

type TypeProps = { }
type TypeState = { }

class App extends React.Component&lt;TypeProps, TypeState&gt; {
    constructor(props:TypeProps) {
        super(props);
        this.state = { };
    }
    render() {
        return(&lt;p&gt;Literally Nothing&lt;/p&gt;);
    }
}

function renderApp() {
    let AppElement = document.getElementById(&quot;app&quot;);
    if(AppElement) { ReactDOM.render(&lt;App /&gt;, AppElement); }
}

renderApp();
export { renderApp }
</code></pre>
<p>Then installed what I believed to be everything required for the tests</p>
<pre><code>npm install --save-dev jest ts-jest @types/jest
npm install --save-dev @testing-library/jest-dom @testing-library/react
</code></pre>
<p>With <code>jest.config.json</code> as</p>
<pre><code>module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'jsdom'
};
</code></pre>
<p>So this is all fine and I have a unit test of nothing</p>
<pre><code>import React from &quot;react&quot;;
import ReactDOM from &quot;react-dom&quot;;
import &quot;@testing-library/jest-dom&quot;;
import { render } from &quot;@testing-library/react&quot;;

import { renderApp } from &quot;./App&quot;;

test(&quot;Literally Nothing&quot;, function() {
    renderApp();
    expect(getByText(&quot;App&quot;)).toBeInTheDocument();
});
</code></pre>
<p>But it is throwing the following error on <code>build</code> and <code>npm run test</code></p>
<pre><code>TS2304: Cannot find name 'getByText'.
</code></pre>
<p>Am I missing an install or configuration step?</p>
",https://stackoverflow.com/questions/71362910/testing-a-typescript-react-component-giving-error-on-getbytext,"['reactjs', 'typescript', 'react-testing-library', 'ts-jest']",1033,True,1,1
Objectmapper.writeValueAsString returning null,"<p>I am doing unit testing with Junit and Mockito for a service class</p>
<p>I have mocked the ObjectMapper in Test Class as below</p>
<pre><code>@Mock
private ObjectMapper objectMapper;

@SuppressWarnings(&quot;deprecation&quot;)
@BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
}
</code></pre>
<p>then call to actual class method,
I am using fasterxml.jackson.databind.ObjectMapper.</p>
<p><strong>Actual code in service class</strong></p>
<pre><code>Map&lt;String, String&gt; ackMessage = new HashMap();
ackMessage.put(&quot;ID&quot;, &quot;123&quot;);
String **json** = objectMapper.writeValueAsString(ackMessage);
</code></pre>
<p>But this <strong>json</strong> string is getting null while debugging</p>
<p>I have autowired the Object mapper in my service class,</p>
<p>@Autowired
ObjectMapper objectMapper;</p>
<p>below code is how I get the ObjectMapper</p>
<pre><code>@Bean
public ObjectMapper getObjectMapper() {
return new ObjectMapper();
}
</code></pre>
",https://stackoverflow.com/questions/72634483/objectmapper-writevalueasstring-returning-null,"['unit-testing', 'junit', 'mockito', 'jackson-databind', 'objectmapper']",1673,False,1,0
AWS Amplify Cognito Angular Unit testing,"<p>I am new to unit testing and just decided to add test coverage for my existing app. I am struggling in writing the unit test cases for the given service .
I have created a AWS service file .</p>
<pre><code>import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { Router } from '@angular/router';
import { Auth } from 'aws-amplify';
import { IUser } from '../../models/userModel';
@Injectable({
  providedIn: 'root'
})
export class AwsAmplifyAuthService {
  private authenticationSubject: BehaviorSubject&lt;any&gt;;
  constructor(private router: Router) {
    this.authenticationSubject = new BehaviorSubject&lt;boolean&gt;(false);
  }

  // SignUp
  public signUp(user: IUser): Promise&lt;any&gt; {
    return Auth.signUp({
      username: user.name,
      password: user.password,
      attributes: {
        email: user.email,
        name:user.name
      }
    });
   }

  // Confirm Code
  public confirmSignUp(user: IUser): Promise&lt;any&gt; {
    return Auth.confirmSignUp(user.name, user.code);
  }

  // SignIn
  public signIn(user: IUser): Promise&lt;any&gt; {
    return Auth.signIn(user.name, user.password)
      .then((r) =&gt; {
        console.log('signIn response', r);
        this.authenticationSubject.next(true);
        if (user) {
          if (r.challengeName === 'NEW_PASSWORD_REQUIRED') {
            this.router.navigateByUrl('/forgotpass');
          } else {
            this.router.navigateByUrl('/home');
          }
        }
      });
  }
</code></pre>
<p>and created a interface model</p>
<pre><code>export interface IUser {
    email: string;
    password: string;
    code: string;
    name: string;
}
</code></pre>
<p>I have tired the mocking the service in the .spec.</p>
<pre><code>    beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      providers: [
        {
          provide: Auth,
          useValue: { currentUserInfo: () =&gt; Promise.resolve('hello') },
        },
      ]
    })
      .compileComponents();
    service = TestBed.inject(AwsAmplifyAuthService);
  });


  it('should be created', () =&gt; {
    expect(service).toBeTruthy();
  });
  it('#signIn should return expected data', async (done: any) =&gt; {
    await service.signIn(expectedData).then(data =&gt; {
      expect(data).toEqual(expectedData);
      done();
    });
  });
</code></pre>
<p>I am not able to pass the test case. Any guidance on the same would be appreciated.</p>
",https://stackoverflow.com/questions/72221295/aws-amplify-cognito-angular-unit-testing,"['angular', 'unit-testing']",336,False,1,2
"Python, Github: Get all branches","<p>I would like to get all the GitHub branches of a certain repository. Using the GitHub API as documented here, <a href=""https://developer.github.com/v3/repos/branches/#list-branches"" rel=""nofollow noreferrer"">https://developer.github.com/v3/repos/branches/#list-branches</a> I try to use the <code>GET</code> request documented.</p>
<p>However, when I try unit testing, the <code>response</code> always evaluates to <code>None</code> and I get error: <code>AttributeError: 'NoneType' object has no attribute 'json'</code>. I am unsure if my issue is with the API call, or I am testing the call. See code below:</p>
<pre><code> @staticmethod
    def get_branches(git_base, org, repo):

        github_repo_url = f&quot;https://{git_base}/api/v3/repos/{org}/{repo}&quot;
        collected_all_branches: bool = False
        page = 1
        github_branches = []
        # collect all branches in repo
        while not collected_all_branches:
            response = (requests.get(f&quot;{github_repo_url}/branches/?per_page=100&amp;page={page}&quot;,
                                     headers=HEADERS))
            if len(response.json()) == 0:
                collected_all_branches = True
            else:
                github_branches.extend([response[&quot;name&quot;] for response in response.json()])
            page = page + 1
        return github_branches

</code></pre>
<p>Unit Test:</p>
<pre><code>    @patch.object(requests, &quot;get&quot;, return_value=None)
    def test_get_branches(self, mock_get):

        r = GithubService.get_branches(&quot;test&quot;, &quot;test&quot;, &quot;test&quot;)
        mock_get.assert_called_with(&quot;test&quot;, &quot;test&quot;, &quot;test&quot;)

</code></pre>
",https://stackoverflow.com/questions/73250513/python-github-get-all-branches,"['python', 'python-3.x', 'python-unittest.mock']",149,False,0,1
How to pass 100% of coverage,"<pre><code>@Override
public int insertEvent(JobStatusDTO jobStatusDTO) throws AccountUpdateException {
        LOGGER.info(&quot;In insertAccountUpdateEvent- {}&quot;, jobStatusDTO);
        try {
            jdbcTemplate.execute(&quot;INSERT INTO EVENT_LOG (JOB_EXECUTION_ID, FILE_NAME, STATUS, TOTAL_EVENTS_RECD, TOTAL_EVENTS_PROCESSED, TOTAL_EVENTS_FAILED, FILE_PROCESS_START_TIME, FILE_PROCESS_END_TIME, PROCESS_MESSAGE_N) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)&quot;,new PreparedStatementCallback&lt;Boolean&gt;() {
   @Override
    public Boolean doInPreparedStatement(PreparedStatement ps)throws SQLException, DataAccessException {
                            ps.setLong(1, jobStatusDTO.getJobId());
                            ps.setString(2, jobStatusDTO.getFileName());
                            ps.setString(3, jobStatusDTO.getJobStatus());
                            ps.setLong(4, jobStatusDTO.getTotalEvents());
                            ps.setLong(5, jobStatusDTO.getTotalSuccessEvents());
                            ps.setLong(6, jobStatusDTO.getTotalFailedEvents());
                            ps.setTimestamp(7, new Timestamp(jobStatusDTO.getJobStartTime().getTime()));
                            ps.setTimestamp(8, new Timestamp(jobStatusDTO.getJobEndTime().getTime()));
                            ps.setString(9, processErrorMessage(jobStatusDTO));
                            return ps.execute();
                        }

                    });
        } catch (DataAccessException e) {
            throw new Exception(Error.ERR_080.getErrorMessage(), e.getMessage());
        } catch (Exception e) {
            throw new Exception(Error.ERR_081.getErrorMessage(), e.getMessage());
        }
        return 0;
    }
</code></pre>
<hr />
<p>I am using Spring framework for my project. When I Debug this it fails at doInpreparedStatement, as it is not getting inside of this method. I am not able to cover the PreparedStatementCallback, And due to this I am not able to achieve 100% coverage. I have written this test below, I am not sure if it is right or wrong as i am new to unit testing.</p>
<hr />
<p>class AccountUpdateAuditDAOImplTest {</p>
<pre><code>@InjectMocks
AccountUpdateAuditDAOImpl accountUpdateAuditDAOImpl;

@Mock
JdbcTemplate jdbcTemplate;

@Mock
ResultSet set;

@Mock
NamedParameterJdbcTemplate namedTemplate;

@SuppressWarnings(&quot;rawtypes&quot;)
@Captor
ArgumentCaptor argCaptor;

@BeforeEach
void setup() throws Exception {
    MockitoAnnotations.openMocks(this);
}

@SuppressWarnings(&quot;unchecked&quot;)
@Test
void testInsertAccountUpdateEvent() throws AccountUpdateException, Exception {
    when(jdbcTemplate.execute(Mockito.anyString(), Mockito.any(PreparedStatementCallback.class))).thenReturn(true);
    JobStatusDTO dTO = createMockDTO();
    PreparedStatement ps = mock(PreparedStatement.class);
    ps.setLong(1, dTO.getJobId());
    List&lt;JobStatusDTO&gt;   list = new ArrayList&lt;JobStatusDTO&gt;();
    dTO.setJobId(1);
    list.add(dTO);
    
    List&lt;Map&lt;String, Object&gt;&gt; value = new ArrayList&lt;Map&lt;String, Object&gt;&gt;();
    Map&lt;String, Object&gt; map =new HashMap&lt;String, Object&gt;();
    map.put(&quot;Job_Id&quot;, &quot;1&quot;);
    map.put(&quot;File_Name&quot;, &quot;RTAU_Btach&quot;);
    map.put(&quot;Job_Status&quot;, &quot;Completed&quot;);
    map.put(&quot;Total_Event&quot;, &quot;10&quot;);
    map.put(&quot;Success_Event&quot;, &quot;7&quot;);
    map.put(&quot;Failure_Event&quot;, &quot;3&quot;);
    value.add(map);
    
    Mockito.when(namedTemplate.queryForList(Mockito.anyString(), Mockito.anyMap())).thenReturn(value);
    assertDoesNotThrow(()-&gt;accountUpdateAuditDAOImpl.insertAccountUpdateEvent(dTO));
}


private JobStatusDTO createMockDTO() {
    JobStatusDTO jobStatusDTO = new JobStatusDTO();
    jobStatusDTO.setFileName(&quot;rtau_pulse_20220624104610853.txt&quot;);
    jobStatusDTO.setJobStatus(&quot;PARTIALLY COMPLETED&quot;);
    jobStatusDTO.setProcessMessage(&quot;Passed&quot;);
    jobStatusDTO.setTotalSuccessEvents(15l);
    return jobStatusDTO;
}
</code></pre>
<p>}</p>
",https://stackoverflow.com/questions/73786052/how-to-pass-100-of-coverage,"['java', 'junit', 'mockito', 'prepared-statement', 'dao']",87,False,0,0
"ng test error, No binary for Chrome browser on your platform. Please, set &quot;CHROME_BIN&quot; env variable","<p>I started the unit testing tutorial for angular, but upon doing the ng test, I am getting error saying</p>
<p>06 10 2022 22:02:54.887:ERROR [launcher]: No binary for Chrome browser on your platform.</p>
<p>Please, set &quot;CHROME_BIN&quot; env variable.</p>
<p>I search the few thing that does not seem to help. I am using the fedora 36 for development work.
can anyone assist me here ? thanks in advance</p>
",https://stackoverflow.com/questions/73977302/ng-test-error-no-binary-for-chrome-browser-on-your-platform-please-set-chrom,"['angular', 'unit-testing', 'jasmine', 'karma-runner']",281,False,0,1
EF Core define query using list instead of dbset in dbcontext,"<p>In EF Core using the <code>modelBuilder</code> a query can be defined for keyless entities like this:</p>
<pre><code>modelBuilder.Entity&lt;UrlResource&gt;()
    .ToInMemoryQuery(() =&gt; context.Blogs.Select(b =&gt; new UrlResource { Url = b.Url }));
</code></pre>
<p>For unit testing I would like to use a list for the query instead of a dbset, like this:</p>
<pre><code>var urlResources = new List&lt;UrlResource&gt;() { ... }.AsQueryable();

modelBuilder.Entity&lt;UrlResource&gt;()
    .ToInMemoryQuery(() =&gt; urlResources);
</code></pre>
<p>But in that case I get an exception with the <code>The LINQ expression could not be translated.</code> message.</p>
<p>Or for this ...</p>
<pre><code>var urlResources = new List&lt;UrlResource&gt;() { ... };

modelBuilder.Entity&lt;UrlResource&gt;()
    .ToInMemoryQuery(() =&gt; urlResources.AsQueryable());
</code></pre>
<p>... this exception:</p>
<p><code>System.ArgumentException : Expression of type 'System.Collections.Generic.List`1[UrlResource]' cannot be used for parameter of type 'System.Linq.IQueryable`1[UrlResource]' of method 'System.Linq.IQueryable`1[UrlResource] Where[UrlResource](System.Linq.IQueryable`1[UrlResource], System.Linq.Expressions.Expression`1[System.Func`2[UrlResource,System.Boolean]])' (Parameter 'arg0')</code></p>
<p>I tested several variations without success.</p>
<p>Does anybody know a way how to solve this problem?<br />
Any help is appreciated. Thanks in advance!</p>
",https://stackoverflow.com/questions/72641448/ef-core-define-query-using-list-instead-of-dbset-in-dbcontext,"['c#', 'entity-framework', 'linq', '.net-core', 'entity-framework-core']",267,False,3,0
Unit testing: can expected output be considered as part of test &quot;fixture&quot;?,"<p>Not sure if it's a common norm in unit testing nomenclature, but I've been writing some of my Jest unit tests like the following, and it just doesn't feel right to group the expected output with the given input(s) as <code>fixture</code>:</p>
<pre class=""lang-js prettyprint-override""><code>describe('24-25', () =&gt; {
  test('test 24', () =&gt; {
    // given
    const fixture = {
      givenInput: 24,
      expectedOutput: 50,
    };

    // when, then
    testDoubleInc(fixture);
  });

  test('test 25', () =&gt; {
    // given
    const fixture = {
      givenInput: 25,
      expectedOutput: 52,
    };

    // when, then
    testDoubleInc(fixture);
  });

  function testDoubleInc({ givenInput, expectedOutput }) {
    expect(doubleInc(givenInput)).toEqual(expectedOutput);
  }
});

// Unit Under Test
function doubleInc(x) {
  return (x + 1) * 2;
}
</code></pre>
<p>So the question is, have I been misusing the term &quot;fixture&quot; there? And if so, would it be more precise/correct in writing it this way instead?</p>
<pre class=""lang-js prettyprint-override""><code>// given
const fixture = {
  givenInput: 24,
};
const expectedOutput = 50;

// when, then
testDoubleInc({ givenInput: fixture.givenInput, expectedOutput });
</code></pre>
",https://stackoverflow.com/questions/73938632/unit-testing-can-expected-output-be-considered-as-part-of-test-fixture,"['unit-testing', 'testing', 'jestjs']",43,False,0,0
Javascript ReferenceError while using jest.mock method,"<p>I am trying to understand the jest unit testing framework in Javascript and specifically mocking modules part by following this article: <a href=""https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c"" rel=""nofollow noreferrer"">https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c</a> However, when I try to use <code>jest.mock()</code> to mock my module, I get this error: <code>ReferenceError: require is not defined</code></p>
<p>This is my math module that I am trying to mock:</p>
<pre><code>export function add(a, b) {
  return a + b;
}


export function subtract(a, b) {
  return a - b;
}
</code></pre>
<p>Here's my test file:</p>
<pre><code>import * as mathlib from '../mathlib';
import * as math from '../math';
import {jest, describe, test, expect} from '@jest/globals';

jest.mock('../math.js');

describe('math', () =&gt; {
  test('adds numbers', () =&gt; {
    mathlib.doAdd(1,2);
    expect(math.add).toHaveBeenCalledWith(1,2);
  })
})
</code></pre>
<p>Here's the package.json file:</p>
<pre><code>{
  &quot;name&quot;: &quot;sample&quot;,
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;description&quot;: &quot;sample package to learn jest&quot;,
  &quot;main&quot;: &quot;index.js&quot;,
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;node --experimental-vm-modules node_modules/jest/bin/jest.js&quot;
  },
  &quot;author&quot;: &quot;rakesh&quot;,
  &quot;license&quot;: &quot;ISC&quot;,
  &quot;devDependencies&quot;: {
    &quot;jest&quot;: &quot;^29.3.1&quot;
  },
  &quot;type&quot;: &quot;module&quot;
}
</code></pre>
<p>Can someone help me fix this issue?</p>
",https://stackoverflow.com/questions/74848265/javascript-referenceerror-while-using-jest-mock-method,"['javascript', 'unit-testing', 'jestjs']",48,False,0,0
Cannot access Salesforce api from Postman,"<p>I am trying to test an application (Azure function) that needs to send an http request to a Salesforce api. This works with unit testing in both Visual Studio and Azure DevOps pipeline. But when I try to test the Azure function using Postman, I get an error: <code>{&quot;error&quot;:&quot;invalid_grant&quot;,&quot;error_description&quot;:&quot;authentication failure&quot;}</code></p>
<p>I tried to set the connected app's &quot;IP Restrictions&quot; to &quot;Relax IP restrictions&quot;, but it did not help.</p>
<p>Here is my code:</p>
<pre><code>_httpClient = new HttpClient();

HttpContent content = new FormUrlEncodedContent(new Dictionary&lt;string, string&gt;
{
    {&quot;grant_type&quot;, &quot;password&quot;},
    {&quot;client_id&quot;, sfClientId},
    {&quot;client_secret&quot;, sfClientSecret},
    {&quot;username&quot;, sfUserName},
    {&quot;password&quot;, $&quot;{sfPassword}{sfToken}&quot;}
});

message = _httpClient.PostAsync(LoginEndpoint, content).Result;

response = message.Content.ReadAsStringAsync().Result;
</code></pre>
",https://stackoverflow.com/questions/71213304/cannot-access-salesforce-api-from-postman,"['azure-functions', 'postman', 'salesforce']",720,True,0,1
How to test a button its text changes depending on useState(),"<p>This is my jsx and when click the button the state changes and the button text changes too
`</p>
<pre><code>const [copied, setCopied] = useState(false);

&lt;button
          className={`btn ${copied ? 'copy copied' : 'copy'}`}
          onClick={() =&gt; {
            setCopied(true);
            navigator.clipboard.writeText(shortedLink);
          }}
        &gt;
          {copied ? 'copied!' : 'copy'}
        &lt;/button&gt;
</code></pre>
<p>`
How to test this conditional text with Jest &amp; RTL</p>
<p>I'm new to unit testing and, I've tried those two solutions but the two failed
-- the first said -- value must be an HTMLElement or an SVGElement. Received has value: null</p>
<p>-- the second said -- Cannot read properties of undefined (reading 'type')
`</p>
<pre><code>
</code></pre>
<pre><code>it('should change the text of the button when clicked', async () =&gt; {
    user.setup();
    render(&lt;ShortedLink /&gt;);
    const copyBtn = screen.getByRole('button', {
      name: 'copy'
    });
    const copiedBtn = screen.queryByRole('button', {
      name: 'copied!'
    });
    expect(copyBtn).toBeInTheDocument('copy');
    expect(copiedBtn).toBe(null);
    await user.click(copyBtn);
    expect(copiedBtn).toBeInTheDocument();
  });
</code></pre>
<pre><code>
</code></pre>
<p><code>and </code></p>
<pre><code>it('should change the text of the button when clicked', async () =&gt; {
    user.setup();
    render(&lt;ShortedLink /&gt;);
    const copyBtn = screen.getByRole('button', {
      name: 'copy'
    });
    expect(copyBtn).toHaveTextContent('copy');
    await user.click(copyBtn);
    expect(copyBtn).toHaveTextContent('copied!'
</code></pre>
",https://stackoverflow.com/questions/74399461/how-to-test-a-button-its-text-changes-depending-on-usestate,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library']",644,True,0,1
Should mocks created in beforeEach or reset in afterEach?,"<p>In order to reset the mocks, should we use beforeEach and create the mock again or define mock in one place and use afterEach to reset mocks? Does creating mocks in beforeEach have huge impact on the test performance? In general what would be the best practice in unit testing: reseting the mock or creating a new one?</p>
<p>Here is an example with beforeEach:</p>
<pre class=""lang-ts prettyprint-override""><code>interface X {
  getX(): string;
}

describe('withBeforeEach', () =&gt; {
  let mockX: X;
  beforeEach(() =&gt; {
    mockX = {
      getX: jest.fn()
    };
  });
});
</code></pre>
<p>Here is an example with afterEach:</p>
<pre class=""lang-ts prettyprint-override""><code>interface X {
  getX(): string;
}

describe('withAfterEach', () =&gt; {
  const mockX: X = {
    getX: jest.fn()
  };
  afterEach(() =&gt; {
    jest.resetAllMocks();
  });
});
</code></pre>
",https://stackoverflow.com/questions/73807456/should-mocks-created-in-beforeeach-or-reset-in-aftereach,"['unit-testing', 'jestjs']",41,False,0,0
Mock implementation of another module not working in jest,"<p>I am unit testing (using jest) a function named &quot;getTripDetails&quot; (inside file trip.js) that calls another file &quot;getTrace.js&quot; from different module (which exports a function as shown below).</p>
<p>I want to mock the call of function &quot;getTrace&quot; while testing &quot;getTripDetails&quot; function.</p>
<p>file: trips.js</p>
<pre><code>const gpsTrace = require(&quot;./gpsTrace&quot;);

getTripDetails = async(req, res)=&gt;{
    let gpsTraceRes = await gpsTrace(req.body, req.adToken)
    //more code...
    return {status:200};
}

</code></pre>
<p>file: getTrace.js</p>
<pre><code>module.exports = async(payload, token) =&gt;{
   try {
    //code
   } catch (e) {
     error(e)
     throw new Error(e)
   }
} 
</code></pre>
<p>This is what i tried after reading the docs.</p>
<p>file: test.js</p>
<pre><code>let ctrl = require(&quot;./trips&quot;);

describe(&quot;API -- testing&quot;, function () {

    it(&quot;Trip details&quot;, async function () {

        jest.mock('./gpsTrace');
        const gpsTrace = require('./gpsTrace');
        gpsTrace.mockImplementation(() =&gt; {});
        gpsTrace();
       
        await  ctrl.getTripDetails({},{});
        expect(response.status).to.eql(200);
    });
});

</code></pre>
<p>It did not get mocked, instead it was calling the original implementation.</p>
<p>Any suggesstions?</p>
",https://stackoverflow.com/questions/74290118/mock-implementation-of-another-module-not-working-in-jest,"['javascript', 'node.js', 'unit-testing', 'jestjs', 'mocking']",146,False,0,1
Jenkins dotnet test,"<p>If the unit testing fails, the pipeline ends.  I want to send the unit test results regardless of failure or success.  I am using an &quot;Execute Shell&quot; build trigger. (and want to)</p>
<pre class=""lang-sh prettyprint-override""><code>/dotnet/dotnet test --no-build --logger &quot;trx;LogFileName=UnitTests.xml&quot; /pathtotest

curl -X POST -H &quot;Content-Type:application/xml&quot; -d @/var/jenkins_home/workspace/MyJob/UnitTests.xml https://myendpoint.com
</code></pre>
<p>If the unit test fails, the curl command will not run because the pipeline ends with a failure.  If the unit test succeeds, the curl command WILL run.  It want it run regardless.</p>
<p>How do I do that?</p>
",https://stackoverflow.com/questions/72117203/jenkins-dotnet-test,"['.net', 'jenkins', 'curl']",347,False,0,1
disabling log4j not working after changing project to spring boot,"<p>We have always been able to disable logging from our Unit Test via this line</p>
<pre><code>Logger.getLogger(ServiceImpl.class).setLevel(Level.OFF);
</code></pre>
<p>However after changing the project to spring boot this no longer works.  Logs are written when unit test is ran.<br />
I have also tried adding a log4j2.xml in our test/resources and set the root level to off, but this had no effect either.
How can I disable console output when unit testing?</p>
",https://stackoverflow.com/questions/71208284/disabling-log4j-not-working-after-changing-project-to-spring-boot,"['java', 'log4j2']",256,False,0,1
dd-trace errors out with node.js jest test run,"<p>i have a node.js application and using jest for unit testing..  i use the following to use dd-trace lib..
<code>const tracer = require('dd-trace').init();</code></p>
<p>app works good, however when i try to run unit test via jest, just this init line alone cause the following error:</p>
<blockquote>
<p>jest --coverage --verbose</p>
</blockquote>
<p>FAIL  plugins/<strong>tests</strong>/Apputils.test.js
● Test suite failed to run</p>
<pre><code>TypeError: Cannot destructure property 'root' of 'path.parse(...)' as it is undefined.

  3 | const AWS = require(&quot;aws-sdk&quot;);
&gt; 4 | const tracer = require('dd-trace').init();
    |                ^
  5 | var StatsD = require('hot-shots');
  6 | var dogstatsd = new StatsD();

  at findUp (node_modules/dd-trace/packages/dd-trace/src/pkg.js:25:11)
  at findPkg (node_modules/dd-trace/packages/dd-trace/src/pkg.js:14:20)
  at Object.&lt;anonymous&gt; (node_modules/dd-trace/packages/dd-trace/src/pkg.js:37:18)
  at Object.&lt;anonymous&gt; (node_modules/dd-trace/packages/dd-trace/src/config.js:7:13)
  at Object.&lt;anonymous&gt; (node_modules/dd-trace/packages/dd-trace/src/proxy.js:6:16)
  at Object.&lt;anonymous&gt; (node_modules/dd-trace/packages/dd-trace/index.js:4:23)
  at Object.&lt;anonymous&gt; (node_modules/dd-trace/index.js:3:18)
</code></pre>
<p>Any idea to get this working?</p>
<p>if I remove this line, all works well..
<code>const tracer = require('dd-trace').init();</code></p>
",https://stackoverflow.com/questions/71086095/dd-trace-errors-out-with-node-js-jest-test-run,"['jestjs', 'trace', 'datadog']",1156,False,0,0
How to set a Camel exchangeProperty from a unit test,"<p>I have a bunch of unit tests that run camel routes with code like</p>
<pre><code>    // setup code here...
    String route = &quot;direct:someroute&quot;;
    try (CamelContext context = new DefaultCamelContext()) {
        Object response = runCamelRoute(context, route, ci);
        checkResponse(route, response);
    }
</code></pre>
<p>but this route expects an exchange property to be set before it gets here - how can I set it? CamelContext has a whole lot of methods but I can't seem to find something like:</p>
<pre><code>CamelRoute cr = context.getRoute(route);
cr.getExchange().setProperty(&quot;propertyName&quot;, &quot;propetyValue&quot;);
</code></pre>
<hr />
<p>Here is my camel run method for unit testing, with a bit of extra code for setting up an Oracle connection, etc.</p>
<pre><code>protected Object runCamelRoute(CamelContext context, String route, Object message) throws Exception {
    context.addRoutes(new MyRouteBuilder() {
    });

    setupRegistry(context);
    context.start();

    FluentProducerTemplate template = context.createFluentProducerTemplate();
    template.withBody(message)
            .withHeader(&quot;hello&quot;, &quot;goodbye&quot;) 
            .withProcessor(e -&gt; e.setProperty(&quot;propertyName&quot;, &quot;propertyValue&quot;)) // fail use header instead
            .to(route);

    try {
        Future&lt;Object&gt; future = template.asyncRequest();
        return future.get();
    } 
    catch(Exception ex) {
        System.out.println(route + &quot; &quot; + ex.getClass().getCanonicleName() + &quot; &quot; + ex.getMessage());
        throw ex;
    } 
    finally {
        template.stop();
        context.stop();
    }
}

private void setupRegistry(CamelContext context) {
    DataSource ds = DataSourceHelper.createConnectionPoolDev();
    context.getRegistry().bind(&quot;dataSource&quot;, ds);
    context.getRegistry().bind(&quot;Transformer&quot;, new Transformer());
}


public static OracleDataSource createConnectionPoolDev() {
    try {
        OracleDataSource ds = new OracleDataSource();
        ds.setConnectionCacheName(&quot;oraCache&quot;);
        ds.setURL(&quot;jdbc:oracle:thin:@//cluster:1521/server.domain.ca&quot;);
        ds.setUser(&quot;user&quot;);
        ds.setPassword(&quot;pass&quot;);
        return ds;
    } 
    catch (Exception ex) {
        logger.error(&quot;Failed to create connection to the database &quot; + ex.getMessage());
    }
    return null;
}
</code></pre>
",https://stackoverflow.com/questions/70582164/how-to-set-a-camel-exchangeproperty-from-a-unit-test,['apache-camel'],545,True,-1,1
ANGULAR NGRX Testing store,"<p>I'm meeting a problem to create a store's test.</p>
<p>My store content a array of post. Each post have a number &quot;loveit&quot;.
When we click on the loveit's button, this number increment and it 's saving in the store.</p>
<p>That's is ok!</p>
<p>Now I want to do a unit testing for check the increment of number in the store.</p>
<p><strong>liste-post.component.ts</strong></p>
<pre><code>import { Component, OnInit, Input } from '@angular/core';
import { Store } from '@ngrx/store';
import { first, Observable, of } from 'rxjs';
import { AppState } from 'src/app/_state';
import { deletePost, incrLovePost, LoadPosts } from 'src/app/_state/posts/posts.actions';
import { Ipost } from 'src/app/_models/post.model';
import { catsSelector } from '../../_state/index';
import { PostsService } from 'src/app/_services/posts.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-liste-posts',
  templateUrl: './liste-posts.component.html',
  styleUrls: ['./liste-posts.component.css']
})
export class ListePostsComponent implements OnInit {

  //Inhibition de la lecture depuis le store
  posts!: Observable&lt;Ipost[]&gt;;

  postsTab: any;

  constructor(
    private router: Router,
    private store: Store&lt;AppState&gt;, 
    private postsService: PostsService) { 
  }

  ngOnInit() {

    //Lecture des posts du store
        this.posts = this.store.select(catsSelector);
        //Permet d'ajouter les posts issu d'un fichier JSON.
        let isCharged = false;
        this.posts.subscribe(result =&gt; {
          isCharged = result.length&gt;0;
          //ajout des posts du fichier JSON dans le local storage
          localStorage.setItem('posts', JSON.stringify(result));
        });
        if (!isCharged) {
          this.store.dispatch(LoadPosts());
        }
        console.log(localStorage.getItem('posts'));
    /////////////////////

    //Lecture des posts depuis le local storage
    this.loadAllPosts();

  }

  likeit(incr: boolean, id: number){
    //console.log(id);
    
    console.log(id)
    this.store.dispatch(incrLovePost({incr: incr, index: id}));
    this.posts = this.store.select(catsSelector);
    this.reloadPosts(id);
  }

  deletePost(id: number){
    this.store.dispatch(deletePost({index: id}));
    this.postsService.delete(id).subscribe({
      next: (data) =&gt; {
        console.log(data);
        this.loadAllPosts();
        this.router.navigate(['/posts']);
      }});
    
  }

  savePosts = (posts:any) =&gt; {
    localStorage.setItem('posts', JSON.stringify(posts));
  }

  private loadAllPosts() {
    this.postsService.getAll()
        .pipe(first())
        .subscribe({
          next: posts =&gt; {
          this.postsTab = posts;
      }});
  }

  reloadPage(): void {
    window.location.reload();
  }

  reloadPosts(id:number) {
    let postUpdate ;
    //Récupération observable post
    this.posts.subscribe((result) =&gt; {
      postUpdate = result.find((x:any) =&gt; x.id === id);
    })
    console.log(&quot;lecture post: &quot;, postUpdate)
    this.postsService.updateLove(postUpdate, id).subscribe({
      next: (data) =&gt; {
        console.log(data);
        this.loadAllPosts();
      }});
  }
}
</code></pre>
<p><strong>liste-post.component.html</strong></p>
<pre><code>&lt;h1 style=&quot;text-align:center&quot;&gt;LISTE DES POSTES &lt;/h1&gt;

&lt;div class=&quot;posts-container&quot;&gt;
    &lt;div class=&quot;border mx-auto mb-2&quot;  *ngFor=&quot;let post of postsTab &quot; &gt;
        &lt;mat-card [ngStyle]=&quot;{'background-color':post.loveits &gt; 0 ? 'green' : 'red' }&quot; *ngIf=&quot;post&quot; class=&quot;card&quot;&gt;
            &lt;mat-card-title&gt;{{post.title}}&lt;/mat-card-title&gt;
            &lt;mat-card-content&gt;
                &lt;div [innerHTML]=&quot;post.content&quot;&gt;&lt;/div&gt;
            &lt;/mat-card-content&gt;
            &lt;mat-card-content&gt;
                &lt;div [innerHTML]=&quot;post.created_at&quot;&gt;&lt;/div&gt;
            &lt;/mat-card-content&gt;
            &lt;mat-card-content&gt;
                &lt;button (click)=&quot;likeit(true, post.id)&quot; id=&quot;loveit&quot; class=&quot;btn btn-primary me-2&quot;&gt;love it !&lt;/button&gt;
                &lt;button (click)=&quot;likeit(false, post.id)&quot; id=&quot;dontloveit&quot; class=&quot;btn btn-danger me-2&quot;&gt;don't love it !&lt;/button&gt;
                &lt;button (click)=&quot;deletePost(post.id)&quot; class=&quot;btn btn-danger me-2&quot;&gt;delete&lt;/button&gt;
            &lt;/mat-card-content&gt;
            &lt;mat-card-content&gt;
                &lt;div&gt;Appréciation de ce post : {{ post.loveits }}&lt;/div&gt;
            &lt;/mat-card-content&gt;
        &lt;/mat-card&gt;
    &lt;/div&gt;
&lt;/div&gt;
</code></pre>
<p><strong>liste-post.component.spec.ts</strong></p>
<pre><code>import { HttpClientModule } from '@angular/common/http';
import { async, ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';
import { BrowserModule, By } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { State, StoreModule, Store } from '@ngrx/store';
import { PostsService } from 'src/app/_services/posts.service';
import { provideMockStore, MockStore } from '@ngrx/store/testing';
import { ListePostsComponent } from './liste-posts.component';
import { postReducer, initialState } from '../../_state/posts/posts.reducer';
import { AppState, catsSelector, reducers } from 'src/app/_state';
import { Ipost } from 'src/app/_models/post.model';
import { Observable, of } from 'rxjs';
import { DebugElement } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatOptionModule, MatNativeDateModule } from '@angular/material/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { EffectsModule } from '@ngrx/effects';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { AppRoutingModule } from 'src/app/app-routing.module';
import { PostsEffects } from 'src/app/_state/posts/posts.effets';
import { environment } from 'src/environments/environment';
import { loveItState } from '../../_state/selected-posts/selected-posts.reducer';
import * as Actions from '../../_state/posts/posts.actions';


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

  let store: MockStore&lt;Ipost[]&gt;;

  const initState : any = {
    id : 1,
    title: 'Titre du post valide 1',
    content: 'Voici le contenu du post valide 2',
    loveits: 0,
    created_at: new Date(),
  };

  let postsList: any = [
    {
      id : 1,
      title: 'Titre du post valide 1',
      content: 'Voici le contenu du post valide 2',
      loveits: 0,
      created_at: new Date(),
    },
    {
      id : 2,
      title: 'Titre du post valide 2',
      content: 'Voici le contenu du post valide 2',
      loveits: 0,
      created_at: new Date(),
    }
  ];

  beforeEach(fakeAsync(() =&gt; {
    TestBed.configureTestingModule({
        imports: [ 
          BrowserModule,
          AppRoutingModule,
          HttpClientModule,
          FormsModule,
          MatCardModule,
          MatFormFieldModule,
          MatSelectModule,
          MatInputModule,
          MatButtonModule,
          MatIconModule,
          MatOptionModule,
          MatNativeDateModule,
          FormsModule,
          ReactiveFormsModule,
          BrowserAnimationsModule,
          MatDatepickerModule,
          StoreModule.forRoot(reducers),
          EffectsModule.forRoot([
            PostsEffects,
          ]),
          StoreDevtoolsModule.instrument({
            maxAge: 25, // Retains last 25 states
            logOnly: environment.production, // Restrict extension to log-only mode
          }),
            ],
        declarations: [ ListePostsComponent ],
        providers: [
            ListePostsComponent,
            Store,
            provideMockStore({ initialState }),
            {
                provide: PostsService,
            }
        ],
    })
    .compileComponents();
    store = TestBed.inject(MockStore);
    

    
  }));

  it('le composant est créé', async() =&gt; {
    fixture = TestBed.createComponent(ListePostsComponent);
    component = fixture.componentInstance;
    
    expect(component).toBeTruthy();
  });


  it('ajout d\'un love it d\'un appui sur love it', async() =&gt; {
    
    //Création du composant
    fixture = TestBed.createComponent(ListePostsComponent);
    fixture.detectChanges();
    const compiled = fixture.componentInstance;
    spyOn(compiled, 'likeit');
    
    //initialsiation des posts
    const postAdd: Ipost = {
        id : 1,
        title: 'Tit',
        content: 'Voici le contenu du post valide',
        loveits: 0,
        created_at: new Date(),
      };

    const addAction = Actions.addPost({post: postAdd});
    //const store = jasmine.createSpyObj&lt;Store&lt;AppState&gt;&gt;('store', ['dispatch']);

    store.setState(postsList);
    compiled.likeit(true, 1);
    fixture.detectChanges();    
    expect(compiled.posts).toBeTruthy();
    })
    
  });
});

</code></pre>
<p>Thanks for your help!!</p>
",https://stackoverflow.com/questions/73503052/angular-ngrx-testing-store,"['angular', 'unit-testing', 'ngrx-store']",162,False,0,0
Unit Testing Spring Issues,"<p>I'm trying to learn how to do unit testing / mockito testing in spring with java 8 and running into some problems. I'm trying to test my method findUserById but it keeps running false. Optional type issues were an issue but may have resolved those. However, it still runs false. My other tests work, so its just this one test that is being stubborn. I would appreciate your help.</p>
<pre><code>User Controller : 

 @GetMapping(&quot;/{id}&quot;)
    public ResponseEntity&lt;User&gt; findUserById(@PathVariable Integer id){
        return ResponseEntity.ok(userServiceImp.findUserById(id));
    }
</code></pre>
<pre><code>
UserApplictionTester : 


  @Autowired
    private Service service;

   @MockBean
    private Repository repo;

@Test
    public void exampleTest() {

        User expectedUser = new User(3, &quot;example@gmail.com&quot;, &quot;password1&quot;, &quot;exampleName&quot;, &quot;USER&quot;);
        User testUser = new User();
        testUser.setId(3);
        when(repo.findById(any())).thenReturn(Optional.of(testUser));
        assertEquals(expectedUser, service.findUserById(testUser.getId()));
    }

</code></pre>
",https://stackoverflow.com/questions/73585117/unit-testing-spring-issues,"['java', 'spring', 'testing', 'mockito']",23,False,0,1
Flask- Pytest mock file write for test file,"<p>New to unit testing in python. I am writing some Pytests for my file upload endpoint. While my test works, I do not want my test to write on my disk (which is what it does currently). What is the best way to mock the file save function and just check if it was called or not. Here is my code:</p>
<pre><code>from io import BytesIO


def test_upload_file_post_success(client):
    data = {
        'fields': 'somefield',
        'file': (BytesIO(b'FILE CONTENT'), 'test.csv')
    }
    response = client.post('/file-upload',
                           content_type='multipart/form-data',
                           data=data)
    assert response.status_code == 200
    
</code></pre>
<p>What I have tried so far:</p>
<pre><code>  
from werkzeug.datastructures import FileStorage
from unittest.mock import MagicMock

@patch('werkzeug.datastructures.FileStorage')
def test_upload_files_success(mocked_fs, client):
    mocked_fs.save.return_value = None
    file = FileStorage(
        stream=BytesIO(b'FILE CONTENT'),
        filename='test_page_one_input.csv',
        content_type='text/csv'
    )
    file.save = MagicMock(return_value=None)
    
    response = client.post(
        '/file-upload',
        content_type='multipart/form-data',
        data={&quot;file&quot;: file}
    )
    mocked_fs.save.assert_called_once()
</code></pre>
<p>Server code:</p>
<pre><code>
class UploadFiles(Resource):
    def post(self):
        # check if the post request has the file part
        if 'file' not in request.files:
            resp = jsonify({'message': 'No file in the request'})
            resp.status_code = 400
            return resp
        file = request.files['file']
        filename, extension = get_file_name_and_extension(file.filename)
        if file and extension in PARSERS.keys():
            filename = secure_filename(file.filename)
            # parse file and validate
            filepath = os.path.join('api/upload/datasets', filename)
            file.save(filepath)
            try:
                validate_file_content(filepath, PARSERS[extension])
                upload_to_storage(filename, file_version)
                resp = jsonify({'message': 'File successfully uploaded'})
                resp.status_code = 200
                return resp
            except (InvalidFileError, EmptyFileError, SaveFileError) as e:
                os.remove(filepath)
                resp = jsonify({'message': 'File validation Failed',
                                'details': str(e)})
                resp.status_code = 500
                return resp
        # check if valid file extension
        if extension not in PARSERS.keys():
            resp = jsonify(
                {'message': 'Invalid file format. Allowed file types are csv'})
            resp.status_code = 400
            return resp
        else:
            raise OSError(
                &quot;Error occured while uploading file. Please try again later&quot;)


</code></pre>
",https://stackoverflow.com/questions/73807004/flask-pytest-mock-file-write-for-test-file,"['python-3.x', 'flask', 'pytest', 'pytest-mock']",329,False,0,0
React Testing Library Sonar Cube conditions are not covered,"<p>I'm unit testing a react component using react testing library and analyzing the code coverage with sonarqube so I have a link and on click of that an API call is being made and based on some conditions it will log some text. When analyzed <strong>if</strong> condition is not totally covered and it says partial condition covered in sonar. Can someone help me with how to cover that condition?</p>
<pre><code>import &quot;./App.css&quot;;
import React, { useState, useEffect } from &quot;react&quot;;
import axios from &quot;axios&quot;;

function App() {
  const [data, setData] = useState([]);
  try {
    console.log(&quot;s&quot;);
    throw new Error(&quot;err&quot;);
  } catch (err) {
    console.log(err);
  }
  useEffect(() =&gt; {
    (async () =&gt; {
      const user = await axios.get(&quot;http://localhost:8080/api/getUser&quot;);
      setData(user.data);
    })();
  }, []);

  const handleClick = async () =&gt; {
    try {
      const result = await axios.get(
        &quot;https://jsonplaceholder.typicode.com/todos/1&quot;
      );
       // The below if-else condition is not  covered in code coverage[![enter image description here][1]][1]
      if (result?.data?.title) {
        console.log(&quot;here&quot;);
      } else {
        console.log(&quot;else&quot;);
      }
    } catch (err) {
      console.log(err);
    }
  };
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;table style={{ border: &quot;1px solid grey&quot; }}&gt;
        &lt;tbody&gt;
          &lt;tr&gt;
            &lt;th&gt;Website&lt;/th&gt;
            &lt;th&gt;URL&lt;/th&gt;
          &lt;/tr&gt;

          {data &amp;&amp;
            data.length &gt; 0 &amp;&amp;
            data.length &amp;&amp;
            data.map((dt, idx) =&gt; {
              return (
                &lt;tr key={idx}&gt;
                  &lt;td&gt;{dt.name}&lt;/td&gt;
                  &lt;td&gt;
                    {dt.url ? (
                      &lt;a href=&quot;#&quot; onClick={() =&gt; handleClick(dt.url)}&gt;
                        Link
                      &lt;/a&gt;
                    ) : (
                      &lt;a href=&quot;#&quot; onClick={() =&gt; handleClick()}&gt;
                        N/A
                      &lt;/a&gt;
                    )}
                  &lt;/td&gt;
                &lt;/tr&gt;
              );
            })}
        &lt;/tbody&gt;
      &lt;/table&gt;
    &lt;/div&gt;
  );
}

export default App;
</code></pre>
<p>Test file</p>
<pre><code>import { render, fireEvent, screen, waitFor } from &quot;@testing-library/react&quot;;
import App from &quot;../App&quot;;
import { rest } from &quot;msw&quot;;
import { setupServer } from &quot;msw/node&quot;;
const server = setupServer(
  rest.get(&quot;https://jsonplaceholder.typicode.com/todos/1&quot;, (req, res, ctx) =&gt; {
    return res(
      ctx.json({
        userId: 1,
        id: 1,
        title: &quot;delectus aut autem&quot;,
        completed: false,
      })
    );
  }),
  rest.get(&quot;http://localhost:8080/api/getUser&quot;, (req, res, ctx) =&gt; {
    return res(
      ctx.body([
        {
          url: &quot;https://www.google.com&quot;,
          name: &quot;Googles&quot;,
        },
        {
          name: &quot;Youtube&quot;,
        },
      ])
    );
  })
);
beforeAll(() =&gt; server.listen());
afterEach(() =&gt; server.resetHandlers());
afterAll(() =&gt; server.close());
window.open = jest.fn();

const asyncTests = () =&gt; {
  expect(screen.getByText(/googles/i)).toBeInTheDocument();
  expect(screen.getByText(/youtube/i)).toBeInTheDocument();
};
test(&quot;renders learn react link&quot;, async () =&gt; {
  render(&lt;App /&gt;);
  expect(screen.getByText(/website/i)).toBeInTheDocument();
  expect(screen.getByText(/url/i)).toBeInTheDocument();
  await waitFor(() =&gt; asyncTests());
  const redirectUrl = screen.getByRole(&quot;link&quot;, { name: &quot;Link&quot; });
  const ifNoUrl = screen.getByRole(&quot;link&quot;, { name: &quot;N/A&quot; });

  fireEvent.click(redirectUrl);
  expect(redirectUrl).toBeInTheDocument();
  expect(ifNoUrl).toBeInTheDocument();
  fireEvent.click(ifNoUrl);
});
</code></pre>
",https://stackoverflow.com/questions/73329115/react-testing-library-sonar-cube-conditions-are-not-covered,"['javascript', 'reactjs', 'sonarqube', 'react-testing-library', 'sonarqube-scan']",234,False,0,0
What unit tests would be better or redudant,"<p>I started to learn a new topic for me - unit testing. Ffter writing a few tests, I began to wonder what else can be written and whether it will not be redundant. If you write code examples it would be even better for me, thank you.</p>
<p>For example do i need to write same <code>Assert.ThrowsAsync&lt;NullReferenceException&gt;</code> test for method <code>ChooseFilmToWatchWithChilds</code> or it will be redundant</p>
<pre><code>/// &lt;summary&gt;
/// Check if database returns null
/// &lt;/summary&gt;
[Fact]
public void NoFilmsInDatabase_ExceptionReturns()
{
    Assert.ThrowsAsync&lt;NullReferenceException&gt;(
        async () =&gt; { await _homeFilmHandler.IndicateFavouritesOfOurFilms(); });
}
</code></pre>
<p>Like this</p>
<pre><code>/// &lt;summary&gt;
/// Check if database returns null
/// &lt;/summary&gt;
[Fact]
public void NoFilmsInDatabaseChooseFilmToWatchWithChilds_ExceptionReturns()
{ 
    Assert.ThrowsAsync&lt;NullReferenceException&gt;(
        async () =&gt; { await _homeFilmHandler.ChooseFilmToWatchWithChilds(); });
}
</code></pre>
<p><strong>Implementation class</strong></p>
<pre><code>using VideoArchive.Contracts.Abstractions.Data;
using VideoArchive.Contracts.Abstractions.FilmServices;
using VideoArchive.Contracts.Abstractions.Integrations;
using VideoArchive.Contracts.Models;
using VideoArchive.Contracts.Models.Home;

namespace VideoArchive.Implementations.FilmServices
{

    public class HomeFilmHandler : IHomeFilmHandler
    {
        #region Constructors and DI

        private readonly IFakeDatabaseService _fakeDatabaseService;
        private readonly IFakeInegrationService _fakeInegrationService;
        private readonly IMapper _mapper;

        public HomeFilmHandler(
            IFakeDatabaseService fakeDatabaseService,
            IFakeInegrationService fakeInegrationService,
            IMapper mapper)
        {
            _fakeDatabaseService = fakeDatabaseService;
            _fakeInegrationService = fakeInegrationService;
            _mapper = mapper;
        }

        #endregion

        public async Task&lt;HomeFilm&gt; ChooseFilmToWatchWithChilds()
        {
            var allFilms = await _fakeDatabaseService.GetAllFilms();

            var filmToWatch = allFilms
                .Where(film =&gt; film.IsFavorite)
                .OrderByDescending(film =&gt; film.TimesWatched);

            foreach (var film in filmToWatch)
            {
                if (_fakeInegrationService.GetAgeRestrictions(_mapper.Map&lt;Film&gt;(film)) &lt;= 6)
                {
                    return film;
                }
            }

            return await Task.FromResult&lt;HomeFilm&gt;(null);
        }


        public async Task IndicateFavouritesOfOurFilms()
        {
            var allFilms = await _fakeDatabaseService.GetAllFilms();

            if (!allFilms.Any() || allFilms == null)
            {
                throw new NullReferenceException();
            }

            IndicateFilms(allFilms);
        }

        private async void IndicateFilms(List&lt;HomeFilm&gt; films)
        {
            foreach (var film in films)
            {
                if (film.TimesWatched &gt;= 5)
                {
                    film.IsFavorite = true;
                    await _fakeDatabaseService.UpdateFilm(film, film.Id);
                }
            }
        }
    }
} 
</code></pre>
<p><strong>TestsClass</strong></p>
<pre><code>using AutoMapper;
using VideoArchive.Contracts.Abstractions.Data;
using VideoArchive.Contracts.Abstractions.Integrations;
using VideoArchive.Contracts.Models.Home;
using VideoArchive.Implementations.FilmServices;
using Moq;
using Xunit;

namespace VideoArchive.Tests
{
    public class HomeFilmHandlerTests
    {
        private readonly Fixture _fixture = new Fixture();
        private readonly Mock&lt;IFakeDatabaseService&gt; _fakeDatabaseService = new Mock&lt;IFakeDatabaseService&gt;();
        private readonly Mock&lt;IFakeInegrationService&gt; _fakeIntegrationService = new Mock&lt;IFakeInegrationService&gt;();
        private readonly Mock&lt;IMapper&gt; _mapper = new Mock&lt;IMapper&gt;();
        private readonly List&lt;HomeFilm&gt; _homeFilms;

        private readonly HomeFilmHandler _homeFilmHandler;

        public HomeFilmHandlerTests()
        {
            _homeFilms = _fixture.CreateMany&lt;HomeFilm&gt;().ToList();

            _fakeDatabaseService
                .Setup(service =&gt; service
                    .GetAllFilms())
                .ReturnsAsync(_homeFilms);
            _fakeDatabaseService
                .Setup(service =&gt; service
                    .UpdateFilm(It.IsAny&lt;HomeFilm&gt;(), It.IsAny&lt;int&gt;()));
            _fakeIntegrationService
                .Setup(service =&gt; service
                    .GetAgeRestrictions(It.IsAny&lt;HomeFilm&gt;()));

            _homeFilmHandler = new HomeFilmHandler(
                _fakeDatabaseService.Object,
                _fakeIntegrationService.Object,
                _mapper.Object);
        }

        [Fact]
        public void NoFilmsInDatabase_ExceptionReturns()
        {
            Assert.ThrowsAsync&lt;NullReferenceException&gt;(async () =&gt; { await _homeFilmHandler.IndicateFavouritesOfOurFilms(); });
        }

        [Fact]
        public async void FilmsAreIndicatedRightTimes_UpdateFilmCalled()
        {
            var filmCountThatNeededToIndicate =
                _homeFilms.Where(film =&gt; film.TimesWatched &gt;= 5).Count();

            await _homeFilmHandler.IndicateFavouritesOfOurFilms();

            _fakeDatabaseService.Verify(
                service =&gt; service.UpdateFilm(It.IsAny&lt;HomeFilm&gt;(), It.IsAny&lt;int&gt;()),
                Times.Exactly(filmCountThatNeededToIndicate));
        }

        [Fact]
        public void FilmWithChild()
        {
            //Write test here
        }
    }
} 
</code></pre>
<p><strong>FakeDatabaseService</strong></p>
<pre><code>using AutoFixture;
using VideoArchive.Contracts.Abstractions.Data;
using VideoArchive.Contracts.Models.Home;

namespace VideoArchive.Implementations.Data.Fake
{
    /// &lt;summary&gt;
    /// Fake service imitating databaseService
    /// &lt;/summary&gt;
    public class FakeDatabaseService : IFakeDatabaseService
    {
        private readonly Fixture Fixture = new Fixture();

        public async Task&lt;List&lt;HomeFilm&gt;&gt; GetAllFilms()
        {
            return Fixture.CreateMany&lt;HomeFilm&gt;().ToList();
        }

        public async Task&lt;HomeFilm&gt; GetFilmById(int id)
        {
            return Fixture.Build&lt;HomeFilm&gt;().With(film =&gt; film.Id, id).Create();
        }

        public async Task UpdateFilm(HomeFilm film, int id)
        {
            // Logic to updating film
        }
    }
}
</code></pre>
<p><strong>FakeInegrationService</strong></p>
<pre><code>namespace VideoArchive.Contracts.Abstractions.Integrations
{

    public interface IFakeIntegrationService
    {
        public int GetAgeRestrictions(IFilm film);
    }
}
</code></pre>
",https://stackoverflow.com/questions/71873815/what-unit-tests-would-be-better-or-redudant,"['c#', '.net', 'unit-testing', 'moq', 'xunit.net']",53,False,0,1
React Unit testing (useLocation() may be used only in the context of a &lt;Router&gt;),"<p>im getting this error
useLocation() may be used only in the context of a  component.
while unit testing but i have never used that hook
why ? btw the Navbar.tsx is under testing</p>
<p>index.tsx</p>
<pre><code>import React from &quot;react&quot;;
import ReactDOM from &quot;react-dom/client&quot;;
import App from &quot;./App&quot;;
import reportWebVitals from &quot;./reportWebVitals&quot;;
import { BrowserRouter as Router } from &quot;react-router-dom&quot;;
import { QueryClientProvider, QueryClient } from &quot;@tanstack/react-query&quot;;
import { createRoot } from &quot;react-dom/client&quot;;

const queryClient = new QueryClient();
const container = document.getElementById(&quot;root&quot;);
const root = createRoot(container!);
root.render(
  &lt;React.StrictMode&gt;
    &lt;QueryClientProvider client={queryClient}&gt;
      &lt;App /&gt;
    &lt;/QueryClientProvider&gt;
  &lt;/React.StrictMode&gt;
);

reportWebVitals();

</code></pre>
<p>app.tsx</p>
<pre><code>import Navbar from &quot;./components/Navbar/Navbar&quot;;
import &quot;./global.css&quot;;
import Layout from &quot;./Layout/Layout&quot;;
import { BrowserRouter as Router} from &quot;react-router-dom&quot;;

function App() {
  return (
    
      &lt;div id=&quot;root&quot;&gt;
        &lt;Layout /&gt;
      &lt;/div&gt;
    
  );
}

export default App;

</code></pre>
<p>NavBar.tsx</p>
<pre><code>import React from &quot;react&quot;;
import { NavLink, BrowserRouter as Router } from &quot;react-router-dom&quot;;

import {
  StyledNavbarDiv,
  StyledPostsIcon,
  StyledNavBarHolderNav,
  StyledContainerDiv,
  StyledNavLink,
} from &quot;./Navbar.style&quot;;

const Navbar: React.FC = () =&gt; {
  return (
    &lt;Router&gt;
      &lt;StyledContainerDiv&gt;
        &lt;StyledNavLink activeclassname=&quot;selected&quot; to={&quot;posts&quot;}&gt;
          &lt;StyledNavBarHolderNav&gt;
            &lt;StyledPostsIcon&gt;&lt;/StyledPostsIcon&gt;
            &lt;StyledNavbarDiv&gt;Posts&lt;/StyledNavbarDiv&gt;
          &lt;/StyledNavBarHolderNav&gt;
        &lt;/StyledNavLink&gt;
   
      &lt;/StyledContainerDiv&gt;
    &lt;/Router&gt;
  );
};

export default Navbar;

</code></pre>
<p>NavBar.test.tsx</p>
<pre><code>import * as ReactDOM from &quot;react-dom&quot;;
import Navbar from './../Navbar';

describe(&quot;navbar component test&quot;, () =&gt; {
  let container: HTMLDivElement;

  beforeEach(() =&gt; {
    container = document.createElement(&quot;div&quot;);
    document.body.appendChild(container);
    ReactDOM.render(&lt;Navbar /&gt;, container);
  });

  afterEach(() =&gt; {
    document.body.removeChild(container);
    container.remove();
  });

  it(&quot;correctly renders the initial component&quot;, () =&gt; {
    const divs = container.querySelectorAll(&quot;div&quot;);
    expect(divs).toHaveLength(1);
  });

});

</code></pre>
<p>i tried moving the navbar component and i tried wrapping app with router inside index.ts and app.ts but none worked
or i would get another error like you cant put routes in another routes</p>
",https://stackoverflow.com/questions/73463465/react-unit-testing-uselocation-may-be-used-only-in-the-context-of-a-router,"['reactjs', 'typescript', 'unit-testing']",27,False,0,0
Catch2 Framework Error: unknown type name &#39;DNA&#39;clang-tidy(clang-diagnostic-error),"<p>I'm using catch2 framework for unit testing. Below is the command I use for compiling the test file.</p>
<p><code>bin/tests: ./tests/tests.cc ./src/dna_strand.cc ./includes/dna_strand.hpp $(CXX) $(CXXFLAGS) ./tests/tests.cc ./src/dna_strand.cc -o $@</code></p>
<p>I'm trying to initialize constructor. I'm trying to use the class' method but it does not work. I'm guessing there is something wrong with my includes.
I also tried to initialize my DNAstrand class but it keeps throwing the same error.</p>
<p>Below is the code:</p>
<pre><code>#ifndef CATCH_CONFIG_MAIN
#  define CATCH_CONFIG_MAIN
#endif


#include &lt;catch/catch.hpp&gt;
#include &lt;iostream&gt;

#include &quot;dna_strand.hpp&quot;
#include &quot;node.hpp&quot;

DNAstrand sample();
sample.PushNode('h'); // &lt;- error

DNAstrand\* DNA = new DNAstrand();
DNA-&gt;SpliceIn('h'); // &lt;- error

TEST_CASE(&quot;Does nothing&quot;, &quot;\[does-nothing\]&quot;) { REQUIRE(true == true); 
</code></pre>
<p>Belows are the 4 errors I get</p>
<pre><code>unknown type name 'sample'
cannot use dot operator on a type
unknown type name 'DNA'
cannot use arrow operator on a type

</code></pre>
",https://stackoverflow.com/questions/71581272/catch2-framework-error-unknown-type-name-dnaclang-tidyclang-diagnostic-error,"['c++', 'constructor', 'catch2']",251,False,0,1
How do i do unit testing on a python class with a constructor?,"<p>I am new to Pytest and i wanted to do unit testing, but it fails saying the class has a constructor.
file app.py:</p>
<pre><code>class SQLService:
    def __init__(self):
        self.db_engine = create_engine(db_string, connect_args={'options': '-csearch_path={}'.format(&quot;schema_name&quot;)}, echo=False)
        base = declarative_base()
        session = sessionmaker(self.db_engine)
        self.session = session()
        base.metadata.create_all(self.db_engine)

    def insert_row(self, name, project_name):
        table = MyTable(
        Name=name, 
        Project=project_name, 
        )

        self.session.add(table)
        self.session.commit()
</code></pre>
<p>Same for this db_class.py:</p>
<pre><code>class MyTable(base):
    __tablename__ = &quot;table_name&quot;
    Name = Column(String)
    Project = Column(String)
</code></pre>
<p>Errors:</p>
<blockquote>
<p>PytestCollectionWarning: cannot collect test class 'SQLService'
because it has a __init_constructor (from app.py)</p>
<p>PytestCollectionWarning: cannot collect test class 'String' because it
has a __init__constructor ( from: db_class.py)</p>
</blockquote>
<p>Is there a way around this or a different tool that i can use?</p>
<p>Thank you</p>
",https://stackoverflow.com/questions/72373034/how-do-i-do-unit-testing-on-a-python-class-with-a-constructor,"['python', 'unit-testing', 'pytest']",53,False,0,0
Xcode 14 unit testing clone simulator,"<p>In Xcode 14, running unit testing seems to be creating simulator 'clones' (named 'Clone 1/2.. of iPhone').
On older machines, this can take a long time. This is happening every time when switching from running the App and running tests.
For example, running the App will launch the Simulator. Running tests will launch new one or more Simulators (Clone of ...), and running the App again will reload the original Simulator.<br />
Any way to control this? This makes running tests a real pain on older machines.</p>
",https://stackoverflow.com/questions/73746572/xcode-14-unit-testing-clone-simulator,['xcode14'],1776,True,11,1
how can i ise i18n in unit test from react testing library,"<p>I'm trying to get translations from i18n files in my unit testing, I've seen other answers but they work with just one i18n file, My problem is that, I have 2 files and the folder structure is like this,</p>
<ul>
<li>i18n/en/translation.json</li>
<li>i18n/es/translation.json</li>
</ul>
<p>and translation.json file is written like this
<code>{... &quot;info&quot;:&quot;information&quot;, &quot;name&quot;:&quot;Name&quot;, ...}</code>
doesn't have an export default.</p>
<p>and here is my test file,</p>
<pre><code>import React from 'react'
import '@testing-library/jest-dom'
import {render} from '@testing-library/react'
import AddUsers from '../../components/AddUsers'

test('Render OK',()=&gt;{
    
    const menuLinkUp =false

    const component =render(
            &lt;AddUsers/&gt;
        
    )
    component.getByText(&quot; how can i call my i18n?&quot;)
})
</code></pre>
<p>I'm using react testing library and jest for doing this.</p>
",https://stackoverflow.com/questions/73163774/how-can-i-ise-i18n-in-unit-test-from-react-testing-library,"['reactjs', 'jestjs', 'react-testing-library', 'react-i18next']",4201,True,1,1
CyPress unable to mock API call,"<ul>
<li>We are working on a react + typescript project &amp; trying to implement <strong>unit testing</strong> using cypress.</li>
<li>I have a component called <code>GettingStartedForm</code> where two APIs are called on <code>componentDidMount</code></li>
</ul>
<ol>
<li><code>Create API</code></li>
<li><code>Get API</code> - is called once the creation is successful.</li>
</ol>
<ul>
<li>We are trying to mock both API calls but the <code>Get API</code> call is not getting mocked.</li>
</ul>
<p>Here is the component,</p>
<pre><code>componentDidMount() {
    this.createMethod();
  }
  /* Create Method */
  createMethod() {
    const contentType = 'application/json';
    const pathAPICreate = '/v1/create/';

    postData(pathAPICreate, contentType, '')
        .then((response:any)=&gt; {
          this.getData();
        }).catch((error:any)=&gt;{
          ...
        });
  }
  /* Get step data */
  async getData() {
    const contentType = 'application/json';
    const pathData = '/v1/data/';
    try {
      const dataResponse = await getCreatedData(
          pathData,
          contentType,
      );
      ...
  }
</code></pre>
<p>Here is my test,</p>
<pre><code>import GettingStartedForm from '../GettingStartedForm';
import React from 'react';
import {mount} from '@cypress/react';
describe('Onboarding getting started form - step 1', () =&gt; {
  beforeEach(() =&gt; {
    cy.intercept('POST', '**/v1/create', {data: 'success'}).as('createConsultant');
    cy.intercept('GET', '**/v1/data/', {fixture: 'gettingStartedStepResponse.json'}).as('stepData');
  });
  it('Should render all elements', () =&gt; {
    mount(&lt;GettingStartedForm
      nextFormHandler={(e, formStatus) =&gt; false}
      previousFormHandler={(e, formStatus) =&gt; false}
    &gt;&lt;/GettingStartedForm&gt;);
    ...
  });
}); 
</code></pre>
<p>and console message here</p>
<p><a href=""https://i.stack.imgur.com/Tpu7m.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Tpu7m.png"" alt=""enter image description here"" /></a></p>
<p>Is there something we are missing here? Any help is highly appreciated.</p>
",https://stackoverflow.com/questions/71124293/cypress-unable-to-mock-api-call,"['reactjs', 'typescript', 'cypress', 'cypress-testing-library']",514,False,1,0
How to Test mapped Objects in golang,"<p>I try to implement some unit testing in my go code and find the topic of mocking method quite difficult.
I have the following example where I hope you can help me :)</p>
<p>On the first layer I have the following code:</p>
<pre><code>package api

import (
    &quot;fmt&quot;
    &quot;core&quot;
)

type createUserDTO struct {
    Id string
}

func ApiMethod() {
    fmt.Println(&quot;some incoming api call wit user&quot;)
    incomingUserData := &amp;createUserDTO{Id: &quot;testId&quot;}
    mapedUser := incomingUserData.mapUser()
    mapedUser.Create()
}

func (createUserDTO *createUserDTO) mapUser() core.User {
    return &amp;core.UserCore{Id: createUserDTO.Id}
}
</code></pre>
<p>The second layer has the following code:</p>
<pre><code>package core

import (
    &quot;fmt&quot;
)

type CoreUser struct{ Id string }

type User interface {
    Create()
}

func (user CoreUser) Create() {
    fmt.Println(&quot;Do Stuff&quot;)
}
</code></pre>
<p>My question now is, how do I test every public method in the api package without testing the core package. Especially the method Create().</p>
",https://stackoverflow.com/questions/74425152/how-to-test-mapped-objects-in-golang,"['go', 'testing', 'mocking']",181,True,1,1
How to mock Azure Storage Account in C# using Moq?,"<p>I have a service <code>IBlobService</code> :</p>
<pre><code>public interface IBlobService
{
    public Task&lt;BlobInfo&gt; GetBlobAsync(string name);
    public Task&lt;IEnumerable&lt;string&gt;&gt; ListBlobsAsync();
    public Task UploadFileBlobAsync(string filePath, string fileName);
    public Task UploadContentBlobAsync(string content, string fileName);
    public Task DeleteBlobAsync(string blobName);
}
</code></pre>
<p>Here is the implementation of the <code>GetBlobAsync</code> method within my <code>BlobService</code> class:</p>
<pre><code>public async Task&lt;BlobInfo&gt; GetBlobAsync(string name)
{
    var client = _blobContainerClient.GetBlobClient(name);
    var blobDownloadInfo = await client.DownloadContentAsync();
    return new BlobInfo(blobDownloadInfo.Value.Content, blobDownloadInfo.Value.Details.ContentType);
}
</code></pre>
<p>I am trying to figure out how I can use Moq to implement my test. I am relatively new to Moq. Any ideas or guidance?</p>
<p>I have tried to review this blog <a href=""https://devblogs.microsoft.com/azure-sdk/unit-testing-and-mocking/"" rel=""nofollow noreferrer"">https://devblogs.microsoft.com/azure-sdk/unit-testing-and-mocking/</a></p>
<p>but i'm still finding myself stuck.  I am trying to figure out the best way to implement my test.</p>
",https://stackoverflow.com/questions/74658579/how-to-mock-azure-storage-account-in-c-using-moq,"['c#', '.net', 'azure', 'rest']",233,True,1,1
unable to install newer opam package on travis ci image,"<p>I am using travis-ci to automate unit testing for my ocaml project. I am unable to complete my build so I am testing my build locally with the same docker travis-ci <a href=""https://hub.docker.com/r/travisci/ci-sardonyx/tags"" rel=""nofollow noreferrer"">image</a>. One of the opam packages <code>ounit2</code> is not in the <code>opam</code> installed in this image. But when I compile my test suit the error message is</p>
<pre><code>ocamlfind: Package `ounit2' not found
Command exited with code 2.
</code></pre>
<p>I am only able to install <code>ounit</code>, which is in opam, but not <code>ounit2</code>. What should I do?</p>
<pre><code>language: generic

os: linux
env:
  - OCAML_VERSION=4.07.0

addons:
  apt:
    packages:
      - opam


# Install the specified version of OCaml
before_install:
- opam init --auto-setup --comp=&quot;$OCAML_VERSION&quot;

# Install the required dependencies
install:
  - opam install --yes ocamlfind
  - opam install --yes ocamlbuild
  - opam install --yes oUnit
  - opam install --yes menhir

# Set the appropriate environment variables
before_script:
  - eval $(opam config env)

# Build and run the test suite
script:
  - make
  - make test
</code></pre>
",https://stackoverflow.com/questions/70628186/unable-to-install-newer-opam-package-on-travis-ci-image,"['ocaml', 'travis-ci', 'opam']",34,False,1,0
Why is Django&#39;s client.post nesting arg values in lists?,"<p>I'm unit testing my api with Django like this:</p>
<pre><code>result = self.client.post( reverse(path), { &quot;arg1&quot;:&quot;value&quot; })
</code></pre>
<p>Inside the view, I breakpoint.</p>
<pre><code>@api_view([&quot;POST&quot;])
def post_arg(request):
    breakpoint()
</code></pre>
<p>But when I print the POST data, the values have been added to lists.</p>
<pre><code>(Pdb) request.POST
{ 'arg1': ['value'] }
</code></pre>
<p>This example only has one arg, but if I add more they are each added to a list. I don't think this happens when my frontend posts data, so why does it here? And is there a way to not have the values added to a list?</p>
",https://stackoverflow.com/questions/74845285/why-is-djangos-client-post-nesting-arg-values-in-lists,"['python', 'django', 'testing']",27,True,1,1
How do I test an endpoint using Jasmine/Karma?,"<p>I have a method in one of my components that hits an endpoint like this...</p>
<pre><code>private async getRolesAsync(): Promise&lt;void&gt; {
    const roles = await this.http.get&lt;any&gt;('https://jsonplaceholder.typicode.com/todos/1').toPromise();
    this.data = roles;
  }
</code></pre>
<p>Notice I have a fake endpoint in there, but what I'd like to know is how do I test that in a unit test? I want a unit test that tests to see if the endpoint works, i.e, it returns a 200 success.</p>
<p>I'm using Angular 13 as my application framework and Jasmine/Karma as my unit testing framework.</p>
",https://stackoverflow.com/questions/71301074/how-do-i-test-an-endpoint-using-jasmine-karma,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",401,False,-1,1
Jasmine testing for a guess the number function,"<p>I'm new to StackOverflow and was hoping to clear a doubt I have with regards to Jasmine testing for the following:</p>
<p>I have a JavaScript function called guessTheNumber where the secretNumber is set to 4 (data type is number).</p>
<p>Would it be correct to input the number as a string and expect the result to be successful for my test to pass case? Is that the correct way to go about unit testing your function?</p>
",https://stackoverflow.com/questions/70960904/jasmine-testing-for-a-guess-the-number-function,"['javascript', 'unit-testing', 'jasmine']",118,False,0,0
Unit testing on imported package,"<p>I am currently creating unit testing for a project, i need to test a function that have dependency injection without interface from an entity. Here is the code</p>
<pre><code>func (u UserUsecase) CreateUser(ctx context.Context, p request.StoreUser) (entity.User, error) {
    user := &amp;entity.User{
        Username:  p.Username,
        Email:     p.Email,
        Phone:     p.Phone,
        Password:  p.Password,
        CompanyID: p.CompanyID,
    }

    err := user.Create(ctx, u.userRepo)
    if err != nil {
        return entity.User{}, err
    }

    return *user, nil
}
</code></pre>
<p>In the <code>user.Create(ctx, u.userRepo)</code> there is a function that call another function so when I create a test function I've been stuck and getting invalid memory address or null pointer. Here is the code in the <code>user.Create(ctx, u.userRepo)</code></p>
<pre><code>func (u *User) Create(ctx context.Context, ur UserStoreRepo) error {
    u.UUID = uuid.New()
    u.Status = constanta.ACTIVE
    pass, err := helpers.Bcrypting(u.Password)
    if err != nil {
        return err
    }
    u.Password = pass

    err = ur.Store(ctx, u)
    return err
}
</code></pre>
<p>What is the best method to override the <code>user.Create(ctx, u.userRepo)</code> so i can test the <code>CreateUser(ctx context.Context, p request.StoreUser)</code>.</p>
",https://stackoverflow.com/questions/72189953/unit-testing-on-imported-package,"['unit-testing', 'go', 'dependency-injection', 'mocking', 'stub']",140,True,-1,1
How does the unit testing works in Web API testing,"<p>I have a below code which is working fine. But I am not able to understand how <strong>act</strong> part works in below code. When I am debugging the code, it's not hitting to DB which is expected in unit testing as we do it using mock data instead of actual DB data. But then what is the use of below line and how does it make test successful while comparing the result with mock data.</p>
<pre><code>[Fact]
        public async Task GetEmployee_ShouldReturnOk()

        {

            //arrange
            var employees = fixure.Create&lt;List&lt;Employee&gt;&gt;();
            var empName = fixure.Create&lt;string&gt;();

            empService.Setup(x =&gt; x.GetEmployee(empName)).ReturnsAsync(employees);
            
            //act
            //this line is calling a controller method but not hitting to data access layer. So from where its getting data?
            var employeesResult = await EmpController.GetEmployee(empName);
            //assert
            employeesResult.Should().NotBeNull();
            employeesResult.Should().BeAssignableTo&lt;ActionResult&lt;IEnumerable&lt;Employee&gt;&gt;&gt;();
            employeesResult.Result.Should().BeAssignableTo&lt;OkObjectResult&gt;();
            empService.Verify(x=&gt;x.GetEmployee(empName), Times.Once());
        }
</code></pre>
",https://stackoverflow.com/questions/74191447/how-does-the-unit-testing-works-in-web-api-testing,"['.net', 'unit-testing', '.net-core', 'asp.net-web-api', 'xunit']",39,False,0,1
How to test ViewModel if flow from RemoteMediator (paging 3) library has been collected or implemented in this?,"<p>I am getting this exception while unit testing the viewModel.</p>
<pre><code>Exception in thread &quot;UI thread @coroutine#1&quot; java.lang.NullPointerException: Parameter specified as non-null is null: method androidx.paging.CachedPagingDataKt.cachedIn, parameter &lt;this&gt;
    at androidx.paging.CachedPagingDataKt.cachedIn(CachedPagingData.kt)
    at com.sarmad.newsprism.news.ui.NewsViewModel$getNewsStream$1.invokeSuspend(NewsViewModel.kt:46)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:304)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)
    Suppressed: kotlinx.coroutines.DiagnosticCoroutineContextException: [CoroutineId(1), &quot;coroutine#1&quot;:StandaloneCoroutine{Cancelling}@67526363, Dispatchers.Main]

expected:&lt;false&gt; but was:&lt;true&gt;
Expected :false
Actual   :true
</code></pre>
<p>I want to test if <code>newsViewModel.getNewsStream()</code> is called, it should start loading, stop loading and expose updated UiState to NewsFragment so fragment can call adapter.submitData(data). But, there is an exception indication an error (I am a beginner and I can't understand that even after research for a good amount of time) in <code>cachedIn(viewModelScope)</code> operator while I am collecting flow in viewModel.</p>
<p><strong>NewsViewModel</strong></p>
<pre><code>package com.sarmad.newsprism.news.ui

@HiltViewModel
class NewsViewModel @Inject constructor(
    private val newsRepository: NewsRepository,
    savedStateHandle: SavedStateHandle
) : ViewModel() {

    companion object {
        const val KEY_SUBREDDIT = &quot;us&quot;
        const val DEFAULT_SUBREDDIT = &quot;androiddev&quot;
    }

    init {
        if (!savedStateHandle.contains(KEY_SUBREDDIT)) {
            savedStateHandle[KEY_SUBREDDIT] = DEFAULT_SUBREDDIT
        }
    }

    @OptIn(ExperimentalCoroutinesApi::class)
    val articles = savedStateHandle.getLiveData&lt;String&gt;(KEY_SUBREDDIT)
        .asFlow()
        .flatMapLatest {
            newsRepository.getBreakingNewsStream(it)
        }.cachedIn(viewModelScope)

    private val _userMessage = MutableStateFlow&lt;String?&gt;(null)
    private val _isLoading = MutableStateFlow(false)
    private val _newsArticles = articles

    val uiState: StateFlow&lt;NewsItemListUiState&gt; = combine(
        _isLoading, _userMessage, _newsArticles
    ) { isLoading, userMessage, newsArticles -&gt;
        NewsItemListUiState(
            news = newsArticles,
            isLoading = isLoading,
            userMessage = userMessage
        )
    }.stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000L),
        initialValue = NewsItemListUiState(isLoading = true)
    )

    fun refresh() {
        _isLoading.value = true
        viewModelScope.launch {
            newsRepository.refreshTasks()
            _isLoading.value = false
        }
    }
}

</code></pre>
<p><strong>NewsRepository</strong></p>
<pre><code>package com.sarmad.newsprism.data.repository

import androidx.paging.PagingData
import com.sarmad.newsprism.data.entities.NewsResponse
import kotlinx.coroutines.flow.Flow
import com.sarmad.newsprism.data.Result
import com.sarmad.newsprism.data.entities.Article

interface NewsRepository {


    suspend fun getSearchedNewsStream(searchQuery: String, pageNumber: Int):
            Flow&lt;NewsResponse&gt;

    suspend fun getBreakingNewsStream(countryCode: String): Flow&lt;PagingData&lt;Article&gt;&gt;
}
</code></pre>
<p><strong>NewsRepositoryImpl</strong></p>
<pre><code>package com.sarmad.newsprism.data.repository

import android.util.Log
import androidx.paging.*
import com.sarmad.newsprism.data.Result
import com.sarmad.newsprism.data.entities.Article
import com.sarmad.newsprism.data.entities.NewsResponse
import com.sarmad.newsprism.data.localdatasource.ArticleDao
import com.sarmad.newsprism.data.localdatasource.ArticleDatabase
import com.sarmad.newsprism.data.localdatasource.RemoteKeysDao
import com.sarmad.newsprism.data.paging.mediaters.NewsRemoteMediator
import com.sarmad.newsprism.data.remotedatasource.api.NewsApi
import com.sarmad.newsprism.utils.Constants.Companion.PAGING_CONFIG_PAGE_SIZE
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.mapLatest
import javax.inject.Inject

private const val TAG = &quot;NewsRepositoryImpl&quot;

class NewsRepositoryImpl @Inject constructor(
    private val api: NewsApi,
    private val articleDao: ArticleDao,
    private val articleDatabase: ArticleDatabase,
    private val remoteKeysDao: RemoteKeysDao,
) : NewsRepository {

    override suspend fun getSearchedNewsStream(
        searchQuery: String,
        pageNumber: Int
    ): Flow&lt;NewsResponse&gt; = flow {
        val searchedNewsResponse = api.searchNews(searchQuery, pageNumber)

        if (searchedNewsResponse.isSuccessful) searchedNewsResponse.body()
            ?.let { newsList -&gt; emit(newsList) }
        else emptyFlow&lt;NewsResponse&gt;()
    }

    @OptIn(ExperimentalPagingApi::class)
    override suspend fun getBreakingNewsStream(
        countryCode: String
    ): Flow&lt;PagingData&lt;Article&gt;&gt; {

     return Pager(
            config = PagingConfig(
                pageSize = PAGING_CONFIG_PAGE_SIZE
            ),
            remoteMediator = NewsRemoteMediator(articleDatabase, articleDao, remoteKeysDao, api),
            pagingSourceFactory = { articleDao.getNewsStream() }
        ).flow
    }
}
</code></pre>
<p><strong>NewsRemoteMadiator</strong></p>
<pre><code>package com.sarmad.newsprism.data.paging.mediaters

import androidx.paging.ExperimentalPagingApi
import androidx.paging.LoadType
import androidx.paging.PagingState
import androidx.paging.RemoteMediator
import androidx.room.withTransaction
import com.sarmad.newsprism.data.remotedatasource.api.NewsApi
import com.sarmad.newsprism.data.entities.Article
import com.sarmad.newsprism.data.entities.ArticleRemoteKey
import com.sarmad.newsprism.data.localdatasource.ArticleDao
import com.sarmad.newsprism.data.localdatasource.ArticleDatabase
import com.sarmad.newsprism.data.localdatasource.RemoteKeysDao
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import kotlin.math.ceil

@OptIn(ExperimentalPagingApi::class)
class NewsRemoteMediator @Inject constructor(
    private val articleDatabase: ArticleDatabase,
    private val articleDao: ArticleDao,
    private val remoteKeysDao: RemoteKeysDao,
    private val api: NewsApi
) : RemoteMediator&lt;Int, Article&gt;() {

    override suspend fun initialize(): InitializeAction {
        val newsCacheTimeout = TimeUnit.MILLISECONDS.convert(1, TimeUnit.HOURS)
        val isSkipRefresh = remoteKeysDao.getLastUpdateTime()?.let {
            System.currentTimeMillis() - it &gt;= newsCacheTimeout
        }

        return if (isSkipRefresh == true) {
            InitializeAction.SKIP_INITIAL_REFRESH
        } else {
            InitializeAction.LAUNCH_INITIAL_REFRESH
        }
    }

    override suspend fun load(
        loadType: LoadType,
        state: PagingState&lt;Int, Article&gt;
    ): MediatorResult {
        return try {

            val currentPage = when (loadType) {
                LoadType.REFRESH -&gt; {
                    val remoteKey = getRemoteKeyClosestToCurrentPosition(state)
                    remoteKey?.nextPage?.minus(1) ?: 1
                }
                LoadType.PREPEND -&gt; {
                    val remoteKey = getRemoteKeyForFirstItem(state)
                    val prevPage = remoteKey?.prevPage ?: return MediatorResult.Success(
                        remoteKey != null
                    )
                    prevPage
                }
                LoadType.APPEND -&gt; {
                    val remoteKey = getRemoteKeyForLastItem(state)
                    val nextPage =
                        remoteKey?.nextPage
                            ?: return MediatorResult.Success(remoteKey != null)
                    nextPage
                }
            }

            val response = api.getBreakingNews(&quot;us&quot;, currentPage)

            val totalPages = response.body()?.totalResults?.toDouble()?.div(20)?.let { pages -&gt;
                ceil(pages)
            }?.toInt()

            val endOfPaginationReached = totalPages == currentPage

            val nextPage = if (endOfPaginationReached) null else currentPage.plus(1)
            val prevPage = if (currentPage == 1) null else currentPage.minus(1)

            articleDatabase.withTransaction {

                if (loadType == LoadType.REFRESH) {
                    articleDao.deleteAllArticles()
                    remoteKeysDao.deleteAllArticleRemoteKeys()
                }

                response.body()?.let { response -&gt;
                    val keys = articleDao.insertAll(response.articles)

                    val mappedKeysToArticles = keys.map { key -&gt;
                        ArticleRemoteKey(
                            id = key.toInt(),
                            nextPage = nextPage,
                            prevPage = prevPage,
                            modifiedAt = System.currentTimeMillis()
                        )
                    }
                    remoteKeysDao.insertArticleRemoteKeys(mappedKeysToArticles)
                }
            }
            MediatorResult.Success(endOfPaginationReached)
        } catch (ex: java.lang.Exception) {
            return MediatorResult.Error(ex)
        }
    }

    private suspend fun getRemoteKeyClosestToCurrentPosition(
        state: PagingState&lt;Int, Article&gt;
    ): ArticleRemoteKey? {
        return state.anchorPosition?.let { pos -&gt;
            state.closestItemToPosition(pos)?.id?.let { id -&gt;
                remoteKeysDao.getArticleRemoteKey(id)
            }
        }
    }

    private suspend fun getRemoteKeyForFirstItem(
        state: PagingState&lt;Int, Article&gt;
    ): ArticleRemoteKey? {

        return state.pages.firstOrNull {
            it.data.isNotEmpty()
        }?.data?.firstOrNull().let {
            it?.let { it1 -&gt; remoteKeysDao.getArticleRemoteKey(it1.id) }
        }
    }

    private suspend fun getRemoteKeyForLastItem(
        state: PagingState&lt;Int, Article&gt;
    ): ArticleRemoteKey? {

        return state.pages.lastOrNull {
            it.data.isNotEmpty()
        }?.data?.lastOrNull().let {
            it?.let { it1 -&gt; remoteKeysDao.getArticleRemoteKey(it1.id) }
        }
    }
}
</code></pre>
<p><strong>NewsViewModelTest</strong></p>
<pre><code>package com.sarmad.newsprism.news.ui

import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.sarmad.newsprism.data.remotedatasource.api.NewsApi
import com.sarmad.newsprism.data.repository.NewsRepository
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations

internal class NewsViewModelTest {

    @Mock
    lateinit var newsRepository: NewsRepository

    @Mock
    private lateinit var newsApi: NewsApi

    private lateinit var newsViewModel: NewsViewModel

    @OptIn(DelicateCoroutinesApi::class)
    private val mainThreadSurrogate = newSingleThreadContext(&quot;UI thread&quot;)

    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    @OptIn(ExperimentalCoroutinesApi::class)
    @Before
    fun setUp() {
        MockitoAnnotations.openMocks(this)
        Dispatchers.setMain(mainThreadSurrogate)
        newsViewModel = NewsViewModel(newsRepository)
    }

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

    @OptIn(ExperimentalCoroutinesApi::class)
    @Test
    fun test_getNewsFlow() = runTest {

        newsViewModel.getNewsStream(&quot;us&quot;)
        assertEquals(true, newsViewModel.newsFlow.value.isLoading)

        advanceUntilIdle()

        assertEquals(
            false,
            newsViewModel.newsFlow.value.isLoading
        )

        assertNotNull(
            newsViewModel.newsFlow.value.news
        )

    }
}
</code></pre>
",https://stackoverflow.com/questions/74584270/how-to-test-viewmodel-if-flow-from-remotemediator-paging-3-library-has-been-co,"['android', 'unit-testing', 'kotlin', 'testing', 'junit']",204,False,0,1
Table test not working on Golang with Receiver Function,"<p>I am trying to do some unit testing in Golang. I have this filter structure:</p>
<pre><code>tests/
|_ rcv-func.go
|_ rcv-func_test.go

</code></pre>
<p>My <code>rcv-func.go</code> looks like this:</p>
<pre><code>package main

import &quot;fmt&quot;


type Player struct {
    health, maxHealth int
    energy, maxEnergy int
    name              string
}

func (p *Player) modifyHealth(newHealth int) {
    p.health = newHealth
}

func (p *Player) modifyEnergy(newEnergy int) {
    p.energy = newEnergy
}

func main() {
    player := Player{
        health:    50,
        maxHealth: 300,
        energy:    20,
        maxEnergy: 100,
        name:      &quot;Jose&quot;,
    }
    fmt.Println(&quot;Before resting:&quot;, player)
    (&amp;player).modifyHealth(150)
    (&amp;player).modifyEnergy(100)
    fmt.Println(&quot;After resting:&quot;, player)
}
</code></pre>
<p>And my <code>rcv-func_test.go</code> like this:</p>
<pre><code>package main

import (
    &quot;fmt&quot;
    &quot;testing&quot;
)

var tests = []struct {
    health int
    energy int
    expect int
    name   string
    goal   bool
}{
    {200, 300, 50, &quot;test1&quot;, true},
    {100, 300, 0, &quot;test2&quot;, true},
}

func TestModifyEnergy(t *testing.T) {
    for _, tt := range tests {
        (&amp;tt).modifyEnergy(11)

    }
}
</code></pre>
<p>When I try to test the receiver function <code>.modifyEnergy()</code>, the line <code>(&amp;tt).modifyEnergy(11)</code> is giving me the following error:</p>
<pre><code>(&amp;tt).modifyEnergy undefined (type *struct{health int; energy int; expect int; name string; goal bool} has no field or method modifyEnergy) (exit status 2)
</code></pre>
<p>What would be the mistake here? It feels it is not defined but the method is clearly defined in the <code>rcv-func.go</code> file.</p>
<p>I tried making both receiver functions Public but to no avail.</p>
<p>Thank you in advance!</p>
",https://stackoverflow.com/questions/74911712/table-test-not-working-on-golang-with-receiver-function,"['unit-testing', 'go']",76,False,0,0
"xml.LoadData - Data at the root level is invalid. Line 1, position 1","<p>So basically I have an spreadsheetwriter class which has WriteToStream() method which takes an spreadsheet as input and convert that spreadsheet to stream.
Now what I am trying to do is to convert the stream into xml format so that at unit testing I am able to compare it.
But I have tried many thing but always it shows the following error.
System.Xml.XmlException: 'Data at the root level is invalid. Line 1, position 1.'</p>
<pre><code>Stream stream = SpreadsheetWriter.WriteToStream(sheet);
stream.Seek(0, SeekOrigin.Begin);
XmlDocument xmlDocument = new();
xmlDocument.Load(stream);
xmlDocument.Save(@&quot;..\Demo.xml&quot;);


  
</code></pre>
",https://stackoverflow.com/questions/71435967/xml-loaddata-data-at-the-root-level-is-invalid-line-1-position-1,"['c#', '.net', 'xml', 'visual-studio', 'openxml']",268,False,0,0
Undefined references for libusb library,"<p>I am trying to use GoogleTest to test a simple function, but as I run make in my build folder, the compiler throws Undefined Reference error messages at me for libusb library. I need to add libusb library in GTEST_SRCS_ part of the makefile but I get same error. I am new to unit testing so, I do not know what should I do? How to build gtest with libusb library?</p>
<p><strong>Makefile</strong></p>
<pre><code>GTEST_DIR= /home/sahin/googletest/googletest
LIBUSB_DIR= /usr/include/libusb-1.0

USER_DIR=.
LIBS += -L/usr/lib -lusb-1.0 -L/usr/lib/x86_64-linux-gnu/libusb-1.0.so -L./ 

CPPFLAGS += -I$(GTEST_DIR)/include -I$(LIBUSB_DIR)

CXXFLAGS += -g -Wall -Wextra -pthread

OBJECTS = main.o test.o
TESTS = test

GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \
                $(GTEST_DIR)/include/gtest/internal/*.h
LIBUSB_HEADERS = $(LIBUSB_DIR)/*.h

all : $(TESTS)

clean :
    rm -f $(TESTS) gtest.a gtest_main.a *.o

GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS)

gtest-all.o : $(GTEST_SRCS_)
    $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \
            $(GTEST_DIR)/src/gtest-all.cc

gtest_main.o : $(GTEST_SRCS_)
    $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \
            $(GTEST_DIR)/src/gtest_main.cc

gtest.a : gtest-all.o
    $(AR) $(ARFLAGS) $@ $^

gtest_main.a : gtest-all.o gtest_main.o
    $(AR) $(ARFLAGS) $@ $^

test.o : $(USER_DIR)/test.cpp $(GTEST_HEADERS)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/test.cpp

test : test.o gtest_main.a
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@
</code></pre>
",https://stackoverflow.com/questions/73303925/undefined-references-for-libusb-library,"['makefile', 'libusb', 'libusb-1.0']",179,False,0,0
Unit testing on imported package,"<p>I am currently creating unit testing for a project, i need to test a function that have dependency injection without interface from an entity. Here is the code</p>
<pre><code>func (u UserUsecase) CreateUser(ctx context.Context, p request.StoreUser) (entity.User, error) {
    user := &amp;entity.User{
        Username:  p.Username,
        Email:     p.Email,
        Phone:     p.Phone,
        Password:  p.Password,
        CompanyID: p.CompanyID,
    }

    err := user.Create(ctx, u.userRepo)
    if err != nil {
        return entity.User{}, err
    }

    return *user, nil
}
</code></pre>
<p>In the <code>user.Create(ctx, u.userRepo)</code> there is a function that call another function so when I create a test function I've been stuck and getting invalid memory address or null pointer. Here is the code in the <code>user.Create(ctx, u.userRepo)</code></p>
<pre><code>func (u *User) Create(ctx context.Context, ur UserStoreRepo) error {
    u.UUID = uuid.New()
    u.Status = constanta.ACTIVE
    pass, err := helpers.Bcrypting(u.Password)
    if err != nil {
        return err
    }
    u.Password = pass

    err = ur.Store(ctx, u)
    return err
}
</code></pre>
<p>What is the best method to override the <code>user.Create(ctx, u.userRepo)</code> so i can test the <code>CreateUser(ctx context.Context, p request.StoreUser)</code>.</p>
",https://stackoverflow.com/questions/72189953/unit-testing-on-imported-package,"['unit-testing', 'go', 'dependency-injection', 'mocking', 'stub']",140,True,-1,1
How to run a .dll test suite with CMake and Microsoft Unit Test Framework,"<p>In a CMake project, I generated a C++/CLI project and a testing SHARED library according to this post</p>
<p><a href=""https://stackoverflow.com/questions/53709197/cmake-for-integrated-microsoft-unit-testing-framework-vs2017"">CMake for integrated Microsoft Unit Testing Framework (VS2017)</a></p>
<p>I am trying to run the tests, but neither <code>Visual Studio</code> or <code>Visual Studio Code</code> are able to discover my tests.</p>
<p>The unique difference is that I am created a <code>test</code> subfolder as a CMake subproject, with it's respective CMakeLists.txt, but is exactly the same config.</p>
<p>What I am doing wrong?</p>
",https://stackoverflow.com/questions/70759660/how-to-run-a-dll-test-suite-with-cmake-and-microsoft-unit-test-framework,"['c++', 'unit-testing', 'cmake', 'clr', 'cil']",847,False,0,1
How to Spy on angular forkJoin for multiple response in unit test - Jasmine,"<p>I am working on the unit testing,i have one function which calls multiple API in one shot.I have written <strong>spyOn</strong> on the service function but  I am not able to return multiple response.Can any one please suggest where i am missing ?</p>
<p>component.ts</p>
<pre><code> loadMappedVendorDoc() {
    this.destroySearch$ = this.apiServ.cloneSubscribe();
    this.isDataLoading = true;
    const curdAPIsJoin = [
      this.apiServ.awsGet('api_path_one),
      this.authSer.awsGet('api_path_two')];

    forkJoin(curdAPIsJoin).pipe(takeUntil(this.destroySearch$)).subscribe(reps =&gt; {
      this.isDataLoading = false;
      if (reps[0].status_code === '200') {
        this.originalmappedDocTypeData = JSON.parse(JSON.stringify(reps[0].response));
        this.mappedDocTypeData = reps[0].response;
      } else {
        this.mappedDocTypeData = [];
      }
      if (reps[1].status_code === '200') {
        this.authSer.ihsDocType = reps[1].response;
      } else {
        this.authSer.ihsDocType = [];
      }
    });
  }
</code></pre>
<p>Note:  <strong>awsGet</strong> returns the observable</p>
<p>component.spec.ts</p>
<pre><code>  it('loadMappedVendorDoc shoud call', fakeAsync(() =&gt; {
        spyOn(apiService, 'awsGet').and.returnValue(of([{ status_code: '200', response: mappedStub }, { status_code: '200', response: mappedStub2 }]));
        component.originalmappedDocTypeData = mappedStub;
        component.mappedDocTypeData = mappedStub;
        component.loadMappedVendorDoc();
    
       fixture.detectChanges();
        tick(1000);
        expect(component.mappedDocTypeData.length).toBe(3);
        // flush();
    
      }));
</code></pre>
<p>Note: <strong>mappedStub</strong> is dummy response</p>
<p>Problem Statement:In code coverage if block is not executing because of that data is not displaying on the page.</p>
<p><a href=""https://i.stack.imgur.com/gXMNN.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/gXMNN.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73234332/how-to-spy-on-angular-forkjoin-for-multiple-response-in-unit-test-jasmine,"['angular', 'unit-testing', 'jasmine']",401,True,0,1
How to mock react hooks while writing Unit testing (jest )?,"<p>I am writing some unit test cases which will test some functionality . So, basically it is giving me some error, while executing, saying &quot;CANT ACCEPT NULL OR UNDEFINED IN USESTATE, USEEFFECT&quot;.
My question is, if i want to test just its functionality, and want to skip all the hooks, how can i do that? or any other suggetions , on how to deal with React hooks , with unit testing in jest will be helpful.</p>
",https://stackoverflow.com/questions/74860238/how-to-mock-react-hooks-while-writing-unit-testing-jest,"['reactjs', 'unit-testing', 'react-hooks', 'jestjs']",47,False,0,0
MERN unit test fails,"<p>I am trying to develop a MERN application. But MERN POST method unit testing fails with following error</p>
<p>ERROR:</p>
<p>1 failing</p>
<ol>
<li>POST /product/save/
OK, creating a new product works:
AssertionError: expected { error: { errors: { …(5) }, …(3) } } to have property '_id'
at Context. (test/api/product/post.js:33:29)
at processTicksAndRejections (node:internal/process/task_queues:96:5</li>
</ol>
<p>I have attached the code below.</p>
<p>MERNProject/products.js</p>
<pre><code>const mongoose = require(&quot;mongoose&quot;);

const postSchema = new mongoose.Schema({
  productName: {
    type: String,
    required: true,
  },
  description: {
    type: String,
    required: true,
  },
  price: {
    type: String,
    required: true,
  },
  productCategory: {
    type: String,
    required: true,
  },
  productUrl: {
    type: String,
    required: true,
  },
});

module.exports = mongoose.model(&quot;Products&quot;, postSchema);
</code></pre>
<p>MERNProject/routes/products.js</p>
<pre><code>    const express = require(&quot;express&quot;);
const Products = require(&quot;../models/products&quot;);

const router = express();

//save Products
router.post(&quot;/product/save&quot;, (req, res) =&gt; {
  let newProduct = new Products(req.body);

  newProduct.save((err) =&gt; {
    if (err) {
      return res.status(400).json({
        error: err,
      });
    }
    return res.status(200).json({
      success: &quot;Product saved successfuly&quot;,
    });
  });
});

module.exports = router;
</code></pre>
<p>MERNProject/test/api/post.js</p>
<pre><code>   const expect = require(&quot;chai&quot;).expect;
    const request = require(&quot;supertest&quot;);
    
    const app = require(&quot;../../../routes/products.js&quot;);
    const conn = require(&quot;../../../server.js&quot;);
    
    describe(&quot;POST /product/save/&quot;, () =&gt; {
      before((done) =&gt; {
        conn
          .connect()
          .then(() =&gt; done())
          .catch((err) =&gt; done(err));
      });
    
      after((done) =&gt; {
        conn
          .close()
          .then(() =&gt; done())
          .catch((err) =&gt; done(err));
      });
    
      it(&quot;OK, creating a new product works&quot;, async () =&gt; {
        const res = await request(app).post(&quot;/product/save/&quot;).send({
          productName: &quot;Mango&quot;,
          description: &quot;description Mango&quot;,
          price: &quot;rs 50&quot;,
          productCategory: &quot;fruits&quot;,
          productUrl:
            &quot;https://upload.wikimedia.org/wikipedia/commons/9/90/Hapus_Mango.jpg&quot;,
        });
    
        const body = res.body;
        expect(body).to.contain.property(&quot;_id&quot;);
        expect(body).to.contain.property(&quot;productName&quot;);
        expect(body).to.contain.property(&quot;description&quot;);
        expect(body).to.contain.property(&quot;price&quot;);
        expect(body).to.contain.property(&quot;productCategory&quot;);
        expect(body).to.contain.property(&quot;productUrl&quot;);
      });
    });
</code></pre>
<p>MERNProject/server.js</p>
<pre><code>const express = require(&quot;express&quot;);
const mongoose = require(&quot;mongoose&quot;);
const bodyParser = require(&quot;body-parser&quot;);
const cors = require(&quot;cors&quot;);

const app = express();

//import routes
const postRoutes = require(&quot;./routes/products&quot;);

//app middleware
app.use(bodyParser.json());
app.use(cors());

app.use(postRoutes);

const PORT = 8000;
const DB_URL =
  &quot;mongodb+srv://twg:twg123@cluster0.ong7q.mongodb.net/myFirstDatabase?retryWrites=true&amp;w=majority&quot;;

function connect() {
  return new Promise((resolve, reject) =&gt; {
    mongoose
      .connect(DB_URL)
      .then((res, err) =&gt; {
        if (err) return reject(err);
        //console.log(`DB connected`);
        resolve();
      })
      .catch((err) =&gt; console.log(`DB connection error`, err));
  });
}

function close() {
  return mongoose.disconnect();
}

connect();

app.listen(PORT, () =&gt; {
  console.log(`App is running on ${PORT}`);
});

module.exports = { connect, close };
</code></pre>
",https://stackoverflow.com/questions/71537503/mern-unit-test-fails,"['node.js', 'reactjs', 'express', 'unit-testing', 'mern']",118,True,0,1
AssertEquals failing . List size is returning more than actual size,"<p>everyone. I'm new to Spring and unit testing and I'm trying to test my repository layer. My test is failing when using assertEquals when asserting the size of my products list. In the first test, it says actual is 3 when clearly it should be 2.Same goes for the second test, it's returning 2 when it should be 1 after deletion of product1.I don't know what I'm doing wrong.</p>
<p>Thank you in advance.</p>
<pre><code>import com.eshop.shoppingcart.model.Product;
import org.junit.jupiter.api.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 java.util.List;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;

import static org.junit.jupiter.api.Assertions.*;


@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class ProductRepositoryTest {
    @Autowired
   ProductRepository productRepository;

    @Test
    void getAllProducts(){
        Product product1 = new Product();
        product1.setId(1L);
        product1.setName(&quot;The Stranger&quot;);
        product1.setPrice(124.5);
        product1.setPictureUrl(&quot;https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1590930002l/49552._SY475_.jpg&quot;);

        Product product2 = new Product();
        product2.setId(2L);
        product2.setName(&quot;Meditations&quot;);
        product2.setPrice(164.5);
        product2.setPictureUrl(&quot;https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1590930002l/49552._SY475_.jpg&quot;);

        productRepository.save(product1);
        productRepository.save(product2);

        List&lt;Product&gt; products = productRepository.findAll();

        assertNotNull(products);
        assertThat(products).isNotNull();
        assertThat(products.size()).isEqualTo(2);
        assertEquals(2, products.size());

    }

    @Test
    void deleteProduct(){
        Product product1 = new Product();
        product1.setId(1L);
        product1.setName(&quot;The Stranger&quot;);
        product1.setPrice(124.5);
        product1.setPictureUrl(&quot;https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1590930002l/49552._SY475_.jpg&quot;);
        productRepository.save(product1);
        Long id = product1.getId();

        Product product2 = new Product();
        product2.setId(2L);
        product2.setName(&quot;Meditations&quot;);
        product2.setPrice(164.5);
        product2.setPictureUrl(&quot;https://i.gr-assets.com/images/S/compressed.photo.goodreads.com/books/1590930002l/49552._SY475_.jpg&quot;);
        productRepository.save(product2);

        productRepository.delete(product1);
        List&lt;Product&gt; products = productRepository.findAll();
        Optional&lt;Product&gt; retrievedProduct =  productRepository.findById(id);

        assertThat(retrievedProduct.isEmpty());
        assertEquals(1, products.size());

    }
}
</code></pre>
",https://stackoverflow.com/questions/74119714/assertequals-failing-list-size-is-returning-more-than-actual-size,"['java', 'spring', 'unit-testing', 'junit', 'spring-data-jpa']",41,True,0,1
Is Mock Possible for a public method which does not have an interface,"<p>I have a C# class and it does not inherits any interface.
The method definition is :</p>
<pre><code>public HashSet&lt;string&gt; GetInfo (string file, HashSet&lt;string&gt; set)
{
..
}
</code></pre>
<p>Now, I do not want to test this method but do something like when this method is called, give me a static set with certain values. I am very new to unit testing. How is this possible or is it not possible ? I was thinking of having Moq, but I read it will only help if you have interface.</p>
",https://stackoverflow.com/questions/71342831/is-mock-possible-for-a-public-method-which-does-not-have-an-interface,"['c#', 'unit-testing']",347,False,0,1
ReferenceError: Vue is not defined while using shallowMount,"<p>I am working on vue project and while doing unit testing using jest, I am getting following error for shallowMount:</p>
<pre><code>ReferenceError: Vue is not defined

    &gt; 1 | import { shallowMount } from '@vue/test-utils';
        | ^
      2 | import About from '@/views/About.vue';
</code></pre>
<p>Following are my devDependencies from package.json:</p>
<pre><code>&quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;^7.18.5&quot;,
    &quot;@babel/eslint-parser&quot;: &quot;^7.12.16&quot;,
    &quot;@vue/cli-plugin-babel&quot;: &quot;~5.0.4&quot;,
    &quot;@vue/cli-plugin-e2e-cypress&quot;: &quot;~5.0.4&quot;,
    &quot;@vue/cli-plugin-eslint&quot;: &quot;~5.0.4&quot;,
    &quot;@vue/cli-plugin-pwa&quot;: &quot;~5.0.0&quot;,
    &quot;@vue/cli-plugin-router&quot;: &quot;~5.0.4&quot;,
    &quot;@vue/cli-plugin-unit-jest&quot;: &quot;^5.0.6&quot;,
    &quot;@vue/cli-plugin-vuex&quot;: &quot;~5.0.4&quot;,
    &quot;@vue/cli-service&quot;: &quot;^5.0.4&quot;,
    &quot;@vue/compiler-dom&quot;: &quot;^3.2.37&quot;,
    &quot;@vue/compiler-sfc&quot;: &quot;^3.0.0&quot;,
    &quot;@vue/eslint-config-airbnb&quot;: &quot;^6.0.0&quot;,
    &quot;@vue/test-utils&quot;: &quot;^2.0.0&quot;,
    &quot;@vue/vue3-jest&quot;: &quot;^28.0.0&quot;,
    &quot;babel-jest&quot;: &quot;^28.1.1&quot;,
    &quot;cypress&quot;: &quot;^8.3.0&quot;,
    &quot;eslint&quot;: &quot;^8.17.0&quot;,
    &quot;eslint-plugin-import&quot;: &quot;^2.25.3&quot;,
    &quot;eslint-plugin-vue&quot;: &quot;^9.1.0&quot;,
    &quot;eslint-plugin-vuejs-accessibility&quot;: &quot;^1.1.0&quot;,
    &quot;jest&quot;: &quot;^28.1.1&quot;,
    &quot;jest-environment-jsdom&quot;: &quot;^28.1.1&quot;,
    &quot;typescript&quot;: &quot;~3.9.3&quot;,
    &quot;vue-cli-plugin-i18n&quot;: &quot;~2.3.1&quot;,
    &quot;vue-cli-plugin-tailwind&quot;: &quot;~3.0.0&quot;,
    &quot;vue3-jest&quot;: &quot;^27.0.0-alpha.1&quot;,
    &quot;webpack&quot;: &quot;^5.73.0&quot;
  },
</code></pre>
<p>Following is my unit test code:</p>
<pre><code>import { shallowMount } from '@vue/test-utils';
import About from '@/views/About.vue';

describe('About.vue', () =&gt; {
  test('renders inner text', () =&gt; {
    // eslint-disable-next-line no-bitwise
    const wrapper = shallowMount(About);

    expect(wrapper.text()).toContain('about');
  });
});
</code></pre>
<p>Following is my Component code:</p>
<pre><code>&lt;template&gt;
  &lt;div class='about'&gt;
    &lt;h1&gt;This is an about page&lt;/h1&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
export default { name: 'about' };
&lt;/script&gt;
</code></pre>
<p>Just wonder if I am doing something wrong with unit test or the component code or does the jest and other supporting libraries require version upgrade/downgrade?</p>
<p>based on comment 1:
Following are the dependencies:</p>
<pre><code>&quot;dependencies&quot;: {
    &quot;@tailwindcss/postcss7-compat&quot;: &quot;^2.0.2&quot;,
    &quot;@vee-validate/rules&quot;: &quot;^4.1.17&quot;,
    &quot;autoprefixer&quot;: &quot;^9&quot;,
    &quot;core-js&quot;: &quot;^3.6.5&quot;,
    &quot;firebase&quot;: &quot;^8.2.7&quot;,
    &quot;howler&quot;: &quot;^2.2.1&quot;,
    &quot;lodash&quot;: &quot;^4.17.21&quot;,
    &quot;nprogress&quot;: &quot;^0.2.0&quot;,
    &quot;postcss&quot;: &quot;^7&quot;,
    &quot;register-service-worker&quot;: &quot;^1.7.1&quot;,
    &quot;tailwindcss&quot;: &quot;npm:@tailwindcss/postcss7-compat@^2.0.2&quot;,
    &quot;vee-validate&quot;: &quot;^4.1.18&quot;,
    &quot;vue&quot;: &quot;^3.0.0&quot;,
    &quot;vue-i18n&quot;: &quot;^9.0.0-rc.2&quot;,
    &quot;vue-router&quot;: &quot;^4.0.0-0&quot;,
    &quot;vuex&quot;: &quot;^4.0.0-0&quot;
  },
</code></pre>
",https://stackoverflow.com/questions/72673358/referenceerror-vue-is-not-defined-while-using-shallowmount,"['javascript', 'vue.js', 'unit-testing', 'jestjs', 'babel-jest']",350,False,0,0
Firebase React Unit Testing,"<p>I am trying to do unit testing on my React Web app which is using firebase auth, firestore and storage. I am pretty new to this and there aren't much resources I can find online.</p>
<p>I just tried to do a simple true test case but I keep getting a auth-api error. Anyone knows how to solve this? Are there any videos I could see to help me?</p>
<p>Code</p>
<pre><code>import * as firebase from &quot;@firebase/rules-unit-testing&quot;

describe(&quot;Login Component&quot;, () =&gt; {
    it(&quot;rendered input&quot; , () =&gt; {
        expect(true).toBeTruthy();
    })
});
</code></pre>
<p>Error</p>
<pre><code>Test suite failed to run

    FirebaseError: Firebase: Error (auth/invalid-api-key).

      26 | };
      27 | export const storage = app.storage(&quot;gs://sftc-development.appspot.com&quot;);
    &gt; 28 | export const auth = app.auth();
         |                         ^
      29 | export default app;

      at createErrorInternal (node_modules/@firebase/auth/src/core/util/assert.ts:128:44)
      at _assert (node_modules/@firebase/auth/src/core/util/assert.ts:153:30)
</code></pre>
<p>firebase.js</p>
<pre><code>import firebase from &quot;firebase/compat/app&quot;;
import &quot;firebase/compat/auth&quot;
import &quot;firebase/compat/firestore&quot;
import &quot;firebase/compat/storage&quot;

const app = firebase.initializeApp({
    apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
    authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
    databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
    projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
    storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.REACT_APP_FIREBASE_APP_ID
})

const firestore = app.firestore();
export const database = {
    usersRef: firestore.collection('user'),
    portfolioRef: firestore.collection('portfolio'),
    projectTitleRef: firestore.collection('projectTitle'),
    audioRef: firestore.collection('audio'),
    videoRef: firestore.collection('video'),
    imageRef: firestore.collection('image'),
    ascensionRef: firestore.collection('ascensionNumber'),
    regEmailRef: firestore.collection('regEmail')
};
export const storage = app.storage(&quot;gs://sftc-development.appspot.com&quot;);
export const auth = app.auth();
export default app;
</code></pre>
",https://stackoverflow.com/questions/73019848/firebase-react-unit-testing,"['reactjs', 'firebase', 'unit-testing']",84,False,0,0
Jasmine not works properly &quot;Incomplete: No specs found&quot; with Node.js and TypeScript Project,"<p>I'm trying to make unit testing by jasmine but jasmine can't find the spec as the following error
and I don't know why I get such an error even though I just try running a very simple suite which always returns true !!!!</p>
<p>any advice would be appreciated</p>
<pre><code>No specs found
Finished in 0.005 seconds
Incomplete: No specs found
npm ERR! code ELIFECYCLE
npm ERR! errno 2
npm ERR! img_process@1.0.0 jasmine: `jasmine`
npm ERR! Exit status 2
npm ERR!
npm ERR! Failed at the img_process@1.0.0 jasmine 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:my path
npm ERR! Test failed.  See above for more details.
</code></pre>
<p>this is jasmine.json file</p>
<pre><code>    {
  &quot;spec_dir&quot;: &quot;dist&quot;,
  &quot;spec_files&quot;: [
    &quot;**/*[sS]pec.?(m)js&quot;
  ],
  &quot;helpers&quot;: [
    &quot;helpers/**/*.?(m)js&quot;
  ],
  &quot;env&quot;: {
    &quot;stopSpecOnExpectationFailure&quot;: false,
    &quot;random&quot;: false
  }
}
</code></pre>
<p>note: the spec.js files located successfully in dist directory after ts build</p>
<p>this is my index.ts file</p>
<pre><code> import express, { Application, Request, Response } from 'express';
import dotenv from 'dotenv';



dotenv.config();

import routes from './routes/index';

const app: Application = express();


app.use(routes);

// app.use(supertest);
const port = process.env.PORT;

app.get('/', (req: Request, res: Response) =&gt; {
  res.json({
    message: 'Express + TypeScript Running '
  });
});

app.listen(port, () =&gt; {
  console.log(`⚡️[server]: Server is running at https://localhost:${port}`);
});

export default app;
</code></pre>
<p>this is the index.spec.ts file</p>
<pre><code> import supertest from 'supertest';
import app from '../index';

const request = supertest(app);
describe('Test endpoint responses', () =&gt; {
    it('gets the api endpoint', async (done) =&gt; {
        const response = await request.get('/');
        expect(response.status).toBe(200);
        done();
    }
)});


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

    it('will always pass', async () =&gt; {
        expect(true).toBe(true);
    });
});
</code></pre>
",https://stackoverflow.com/questions/73176387/jasmine-not-works-properly-incomplete-no-specs-found-with-node-js-and-typescr,"['node.js', 'typescript', 'jasmine', 'supertest']",271,False,0,0
React router v6 access route params and pass as props,"<p>In react router v6, how can I pass route params to a component without the need to use <code>useParams()</code> in the component?</p>
<p>This is what I want to do:</p>
<pre><code>&lt;Route
  path='/'
  element={ProfileComponent username={'thedefault'}
/&gt;
&lt;Route
  exact
  path='/u/:username/'
  render={(props) =&gt; 
    &lt;ProfileComponent username={props.match.params.username}/&gt;
  }
/&gt;
</code></pre>
<p>I don't want to put <code>useParams()</code> in the component because this tightly couples it to the URL. For example, what if I wanted to render another ProfileComponent elsewhere, with a different username to that in the URL. It seems to violate best practice for unit testing unless I can do it like my example.</p>
",https://stackoverflow.com/questions/70999713/react-router-v6-access-route-params-and-pass-as-props,"['javascript', 'reactjs', 'react-router', 'react-router-dom']",11192,True,5,2
What exactly is/means &quot;System.IO.Stream+NullStream&quot;?,"<p>I am currently experimenting to find the proper way of creating an HTTP context for unit testing purposes. While examining the stream types created, I was surprised that the following returns a type of <code>System.IO.Stream+NullStream</code>.</p>
<pre><code>var context = new DefaultHttpContext();

var requestBodyType = context.Request.Body.GetType().FullName; 
var responseBodyType = context.Response.Body.GetType().FullName; 
</code></pre>
<p>If the test case requires it, I'd simply replace the stream with a <code>MemoryStream</code> and then act upon it accordingly.</p>
<pre><code>var memoryStream = new MemoryStream();
var context = new DefaultHttpContext(); 
context.Response.Body = memoryStream;
</code></pre>
<p>So far so good. But what <em>exactly</em> is <code>System.IO.Stream+NullStream</code>? I would have expected to find a type of <code>NullStream</code> in the documentation, but couldn't find such a thing.</p>
",https://stackoverflow.com/questions/70834632/what-exactly-is-means-system-io-streamnullstream,"['c#', 'asp.net-core', 'httpcontext']",629,True,2,2
Extension entry point for both testing and deployment,"<p>I'm closing in on the development of a VS Code extension, so I started to experiment with packaging and publishing. With <em>webpack</em> set up, my <code>package.json</code> now points to</p>
<pre><code>&quot;main&quot;: &quot;./dist/extension&quot;,
</code></pre>
<p>as the packed-minified delopyment file is in the <code>dist</code> folder. Yet, to keep testing the extension, it should be</p>
<pre><code>&quot;main&quot;: &quot;./out/extension&quot;,
</code></pre>
<p>And I don't mean unit testing and similar, just running with debugging from VS Code. How can I reconcile the difference without manually changing back and forth every time?</p>
",https://stackoverflow.com/questions/74819189/extension-entry-point-for-both-testing-and-deployment,"['visual-studio-code', 'vscode-extensions']",48,False,2,0
Mock PeriodicTimer for UnitTests,"<p>My class is using <a href=""https://learn.microsoft.com/en-us/dotnet/api/system.threading.periodictimer?view=net-6.0"" rel=""nofollow noreferrer"">PeriodicTimer </a>. I want to mock its time in unit tests. Is it possible?
I can set up the class to have a shorter period but that's not the best practice for unit testing.</p>
<p>Nsubstitute example is preferable, but does not really matter.</p>
<p>Maybe it's possible to make a wrapper, however, <em>ValueTask</em> is a bit more tricky. Maybe I need to dig into <em>IValueTaskSource</em>. But maybe someone has a solution?</p>
<p>The code I want to test:</p>
<pre><code>public class Example : BackgroundService
     {
         private readonly PeriodicTimer _timer;
     
         public Example(IConfiguration configuration)
         {
             _timer = new PeriodicTimer(TimeSpan.Parse(configuration[&quot;Interval&quot;]));
         }
         
         protected override async Task ExecuteAsync(CancellationToken stoppingToken)
         {
             while (await _timer.WaitForNextTickAsync(stoppingToken)) // I want to simulate this without waiting for real time
             {
                 // Do something
             }
         }
}
</code></pre>
",https://stackoverflow.com/questions/74867695/mock-periodictimer-for-unittests,"['c#', '.net', 'unit-testing', 'async-await', '.net-6.0']",302,True,2,1
Setting up data for Mockito,"<p>I am unit testing my spring Rest API and I have had joy mocking my create and retrieve methods using the following structure.</p>
<pre><code>    @Test
    public void getAllUsersReturnsAListOfAllTheUsersInJSONFormat() throws Exception {
        List&lt;User&gt; users = new ArrayList&lt;&gt;();
        users.add(new User(&quot;DelBoy&quot;));
        users.add(new User(&quot;Rodney_Trotter&quot;));
        users.add(new User(&quot;Uncle.Albert&quot;));

        Mockito.when(service.getAllUsers()).thenReturn(users);

        mvc.perform(get(&quot;/api/users&quot;))
                .andExpect(status().isOk())
                .andExpect(jsonPath(&quot;$&quot;, Matchers.hasSize(3)))
                .andExpect(jsonPath(&quot;$[0].username&quot;, Matchers.equalTo(&quot;DelBoy&quot;)))
                .andExpect(jsonPath(&quot;$[1].username&quot;, Matchers.equalTo(&quot;Rodney_Trotter&quot;)))
                .andExpect(jsonPath(&quot;$[2].username&quot;, Matchers.equalTo(&quot;Uncle.Albert&quot;)));
    }
</code></pre>
<p>However, I am trying to create a test for my Update and Delete methods. When I mock the methods they never behave as expected because there is no data to update or delete. After extensive research online I cannot find any information pointing to resolving this issue. My current attempt is the following code.</p>
<pre><code>    @Test
    public void updateUserUpdatesAUserUponSuccess() throws Exception {

        User updatedUser = new User(UUID.fromString(&quot;da3f6cae-9126-407b-a1ea-093bdac72434&quot;), &quot;Trigger&quot;);

        Mockito.when(service.updateUser(updatedUser)).thenReturn(true);
        Mockito.when(validator.validateUsername(updatedUser.getUsername())).thenReturn(true);
        Mockito.when(validator.validateUUID(updatedUser.getUserId().toString())).thenReturn(true);

        String str = mvc.perform(put(&quot;/api/users/da3f6cae-9126-407b-a1ea-093bdac72434/TriggersBroom&quot;))
                .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

        System.out.println(str);
    }
</code></pre>
<p>I am not sure how to have user data mocked so that when I make a PUT request it can update the user at the hex Id specified to a different username (&quot;trigger&quot; being the username). How I would like this to work is to have a small set of user objects that I can update when I mock my <code>updateUser</code> function so I can test the update user route actually updates a record. Currently it returns false because nothing is being updated but it should return true as I have tested manually in my development environment outside of unit testing and it works.</p>
<p>Note:
The println was my was of checking what was actually returned and it was false.</p>
",https://stackoverflow.com/questions/71064682/setting-up-data-for-mockito,"['spring', 'spring-boot', 'spring-mvc', 'junit', 'mockito']",156,False,0,1
Unit Testing a method which contains a Using block,"<p>I have a already written (was written years ago) C# function, I have been asked to cover this method with Unit Tests.</p>
<pre><code>public string PlaceOrder(int requestId, string orderedby)
    {
        try
        {
            using (DatabaseContext dbContext = new DatabaseContext(&quot;myConnectionStringHere&quot;))
            {
                var req = dbContext.Orders.Where(row =&gt; row.id == requestId).FirstOrDefault();
                if (req == null)
                    return &quot;not found&quot;;
               
                req.status=&quot;A&quot;;
                dbContext.SaveChanges();
                return &quot;found&quot;;
            }
        }
        catch (Exception ex)
        {
            return &quot;error&quot;;
        }
    }
</code></pre>
<p>Now while Unit testing I need to make sure that it does not write anything to database, so I have to <code>MOQ</code> it.
How can I <code>MOQ</code>, it contains <code>Using</code> block.</p>
<p>I know architecture could have been better and design patterns should have been followed but I am not allowed to change the structure of the application as it is a legacy application.</p>
",https://stackoverflow.com/questions/71299193/unit-testing-a-method-which-contains-a-using-block,"['c#', 'unit-testing', 'nunit', 'moq']",480,True,4,2
Moq testing repositories,"<p>Trying to moq a repository call.</p>
<pre><code>public async Task&lt;T&gt; GetFirstOrDefault&lt;T&gt;(Expression&lt;Func&lt;T, bool&gt;&gt; predicate) where T : class
{
    return await WithQuery&lt;T, T&gt;(q =&gt; q.FirstOrDefaultAsync(predicate));
}
</code></pre>
<p>Then in my unit testing:</p>
<pre><code>var ruleList = new List&lt;Rule&gt;() (Imagine my list here)

_mockRepository.Setup(x =&gt; x.GetFirstOrDefault&lt;Rule&gt;(x =&gt; It.IsAny&lt;string&gt;() == It.IsAny&lt;string&gt;())).ReturnsAsync(ruleList);
</code></pre>
<p>This always returns null when it goes into my code.  I have a similar call not using a predicate that will return the value, it looks like this:</p>
<pre><code>public Task&lt;IEnumerable&lt;T&gt;&gt; ListAll&lt;T&gt;() where T : class
{
    return WithQuery&lt;T, IEnumerable&lt;T&gt;&gt;(async q =&gt; await q.ToListAsync());
}
</code></pre>
<p>and</p>
<pre><code>var ruleList = new List&lt;Rule&gt;() (Imagine my list here)

_mockRepository.Setup(x =&gt; x.ListAll&lt;Rule&gt;()).ReturnsAsync(ruleList);
</code></pre>
<p>This is not null. I'm probably missing something simple at this point but I have tried a few things without luck.</p>
<p><strong>Edit:</strong> thanks to Nkosi for the explanation and with a slight modification I was able to do:</p>
<pre><code>_mockRepository.Setup(x =&gt; x.GetFirstOrDefault&lt;Rule&gt;(It.IsAny&lt;Expression&lt;Func&lt;Rule, bool&gt;&gt;&gt;()))
    .Returns((Expression&lt;Func&lt;Rule, bool&gt;&gt; predicate) =&gt; {
        return Task.FromResult&lt;Rule&gt;(ruleList);
    });
</code></pre>
",https://stackoverflow.com/questions/72806620/moq-testing-repositories,"['c#', 'unit-testing', 'moq']",83,True,1,1
"Apache Camel test with mockEndpointsAndSkip() is not receiving messages, but weaveById().replace().to() is","<p>I tried unit testing Apache Camel and I started out with a real basic case where my route looks like that:</p>
<pre><code>public class TestRoute extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from(&quot;jpa:Data&quot;).to(&quot;jpa:Data&quot;).id(&quot;testId&quot;);
    }
}
</code></pre>
<p>Now the following approach didn't work. I tried mocking all endpoints, however I'm getting <code>mock://jpa:Data Received message count. Expected: &lt;1&gt; but was: &lt;0&gt;</code></p>
<pre><code>public class RouteTest extends CamelTestSupport {
    @Override
    @BeforeEach
    public void setUp() throws Exception {
        super.setUp();
    }

    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new TestRoute();
    }

    @Override
    public boolean isUseAdviceWith() {
        return true;
    }

    @Test
    void testRoute() throws Exception {
        AdviceWith.adviceWith(context, null, false, a -&gt; {
            a.replaceFromWith(&quot;direct:start&quot;);
            a.mockEndpointsAndSkip(&quot;*&quot;);
        });
        context.start();
        // The false here makes sure that I get an exception if I'm using a name 
        // of a nonexistent mocked endpoint, so that shouldn't be the problem here
        getMockEndpoint(&quot;mock:jpa:Data&quot;, false).expectedMessageCount(1);

        var data = getSomeTestData();
        template.sendBody(&quot;direct:start&quot;, data);
        assertMockEndpointsSatisfied();
    }
}
</code></pre>
<p>A workaround I found is replacing <code>a.mockEndpointsAndSkip(&quot;*&quot;);</code> with <code>a.weaveById(&quot;testId&quot;).replace().to(&quot;mock:jpa:Data&quot;);</code>. However I'm unsure what's the difference in this case, considering <code>mockEndpointsAndSkip</code> should also replace all endpoints with a mocked version. It would be a bit troublesome to replace ALL endpoints in a real scenario manually.</p>
",https://stackoverflow.com/questions/74094666/apache-camel-test-with-mockendpointsandskip-is-not-receiving-messages-but-wea,"['java', 'apache-camel']",180,True,1,1
Is it possible to Unit Test WinUI 3 code using NUnit?,"<p>I've got a WinUI-3 solution with three projects: class libary for the backend and ViewModels, Unit testing via NUnit and a WinUI-3 app.</p>
<p>Everything was working fine with all tests passing until I called Colors.Transparent in one of my ViewModel methods (called from the ViewModel constructor), now <em>all</em> the tests for that ViewModel fail with:</p>
<pre><code>        System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
  ----&gt; System.Runtime.InteropServices.COMException : Class not registered (0x80040154 (REGDB_E_CLASSNOTREG))

  Stack Trace: 
RuntimeType.CreateInstanceOfT()
Activator.CreateInstance[T]()
WeakLazy`1.get_Value()
_IColorsStatics.get_Instance()
Colors.get_Transparent()
MainViewModel.ctor(IServiceProvider provider) line 58
MainViewModelTests.Constructor_SetsCachedSortedColumn_ToLTV() line 64
--COMException
BaseActivationFactory.ctor(String typeNamespace, String typeFullName)
_IColorsStatics.ctor()
RuntimeType.CreateInstanceOfT()
</code></pre>
<p>It looks like a dependency injection issue, any ideas how to get around this or does NUnit just not support WinUI-3?</p>
",https://stackoverflow.com/questions/71533431/is-it-possible-to-unit-test-winui-3-code-using-nunit,"['nunit', 'winui-3']",313,False,1,1
Using unittest.mock to mock a DRF response,"<p>My example is pretty basic:</p>
<pre><code># urls.py
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from core import views

router = DefaultRouter()
router.register(r'core', views.CoreViewSet)

urlpatterns = [
    path('', include(router.urls)),
]
</code></pre>
<pre><code># views.py
from rest_framework import mixins, viewsets
from .models import Numbers
from .serializers import NumbersSerializer


class CoreViewSet(viewsets.GenericViewSet,
              mixins.ListModelMixin):
    queryset = Numbers.objects.all()
    serializer_class = NumbersSerializer
</code></pre>
<pre><code># serializers.py
from rest_framework import serializers
from .models import Numbers

class NumbersSerializer(serializers.ModelSerializer):
    class Meta:
        model = Numbers
        fields = '__all__'
</code></pre>
<pre><code># models.py
from django.db import models

# Create your models here.
class Numbers(models.Model):
    odd = models.IntegerField()
    even = models.IntegerField()

    class Meta:
        db_table = 'numbers'
</code></pre>
<p>What I'm trying to do is mock the request to the <code>/core/</code> URI so it returns a mocked response and not the response from the database. For example, considering unit testing in a CI pipeline when the database isn't available.</p>
<p>The below is what I have, but <code>print(response.data)</code> returns the actual response and not the mocked one:</p>
<pre><code>import unittest
from unittest.mock import patch
from rest_framework.test import APIClient

class CoreTestCase(unittest.TestCase):
    
    @patch('core.views')
    def test_response(self, mock_get):
        mock_get.return_value = [{'hello': 'world'}]
        client = APIClient()
        response = client.get('/core/')
        print(response.data)
</code></pre>
<p>Not finding the documentation very intuitive in figuring this out, so asking how I should be implementing this. Suggestions?</p>
",https://stackoverflow.com/questions/71476064/using-unittest-mock-to-mock-a-drf-response,"['python', 'django', 'django-rest-framework', 'python-unittest', 'python-unittest.mock']",721,True,1,1
How to mock react custom hook return value as a module with Jest,"<p>I need to mock my custom hook when unit testing React component. I've read some stackoverflow answers but haven't succeeded in implementing it correctly.</p>
<p>I can't use useAuth without mocking it as it depends on server request and I'm only writing unit tests at the moment.</p>
<pre><code>//useAuth.js - custom hook

const authContext = createContext();

function useProvideAuth() {
    const [accessToken, setAccessToken] = useState('');
    const [isAuthenticated, setAuthenticated] = useState(
        accessToken ? true : false
    );

    useEffect(() =&gt; {
        refreshToken();
    }, []);

    const login = async (loginCredentials) =&gt; {
        const accessToken = await sendLoginRequest(loginCredentials);
        if (accessToken) {
            setAccessToken(accessToken);
            setAuthenticated(true);
        }
    };

    const logout = async () =&gt; {
        setAccessToken(null);
        setAuthenticated(false);
        await sendLogoutRequest();
    };

    const refreshToken = async () =&gt; {
        const accessToken = await sendRefreshRequest();
        if (accessToken) {
            setAccessToken(accessToken);
            setAuthenticated(true);
        } else setAuthenticated(false);
        setTimeout(async () =&gt; {
            refreshToken();
        }, 15 * 60000 - 1000);
    };

    return {
        isAuthenticated,
        accessToken,
        login,
        logout
    };
}

export function AuthProvider({ children }) {
    const auth = useProvideAuth();

    return &lt;authContext.Provider value={auth}&gt;{children}&lt;/authContext.Provider&gt;;
}

AuthProvider.propTypes = {
    children: PropTypes.any
};

const useAuth = () =&gt; {
    return useContext(authContext);
};

export default useAuth;
</code></pre>
<p>The test I've written</p>
<pre><code>//mainPage.test.js

import React from 'react';
import { render, screen } from '@testing-library/react';
import Main from '../main/mainPage';

describe('Main when !isAuthenticated', () =&gt; {
    beforeEach(() =&gt; {
        jest.mock('../auth/useAuth', () =&gt; {
            const originalModule = jest.requireActual('../auth/useAuth');
            return {
                __esModule: true,
                ...originalModule,
                default: () =&gt; ({
                    isAuthenticated: false,
                    login: jest.fn,
                    logout: jest.fn
                })
            };
        });
    });

    afterEach(() =&gt; {
        jest.resetModules();
    });

    it('displays image and login form', () =&gt; {
        render(&lt;Main /&gt;);

        const image = screen.getByRole('img');
        const form = document.querySelector('[data-testid=loginForm]');
        expect(image).toBeInTheDocument();
        expect(form).toBeInTheDocument();
    });
});

</code></pre>
<p>However, I get this error.</p>
<pre><code> TypeError: Cannot read properties of undefined (reading 'isAuthenticated')

       7 |
       8 | function Main() {
    &gt;  9 |      const isAuthenticated = useAuth().isAuthenticated;
         |                              ^
      10 |      const location = useLocation();
      11 |
      12 |      if (isAuthenticated)

      at Main (src/main/mainPage.js:9:26)
      at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14985:18)...
</code></pre>
<p>I've been also trying to use spyOn but nothing helped. What exactly do I need to change to make the mock work?</p>
",https://stackoverflow.com/questions/71706495/how-to-mock-react-custom-hook-return-value-as-a-module-with-jest,"['javascript', 'reactjs', 'unit-testing', 'react-hooks']",6877,True,1,1
Unit testing a method that calls other methods Jest,"<p>I was thinkig a lot on WHAT to test in a method that works like an &quot;orchestrator&quot; and it's only job is to calls functions. So I have this BattleInteractor class</p>
<pre><code>class BattleInteractor {
    constructor(opts) {
        this.battleRepository = opts.battleRepository
        this.battleEntity = opts.battleEntity
        this.battleWinner = opts.battleWinner
        this.typeFactoryService = opts.typeFactory
    }
    
    async execute(pokemonOne, pokemonTwo) {

        const battleResult = this.battle(pokemonOne, pokemonTwo)
        return battleResult
    }

    battle(pokemonOne, pokemonTwo) {
        const strategy = this.typeFactoryService.getStrategy(pokemonOne, pokemonTwo)
        const pokemonsSetted = strategy.setStats(pokemonOne, pokemonTwo)
        const battleResult = this.battleEntity.battleLogic(pokemonsSetted)
        return this.battleWinner.battleWinner(battleResult)
    }

}

module.exports = BattleInteractor
</code></pre>
<p>And the test file with all methods mocked:</p>
<pre><code>const BattleInteractor = require('../../../../src/application/useCases/battle/battleInteractor')
describe('BattleInteractor test', () =&gt; {

    const pokemonOneMock = 'mock'
    const pokemonTwoMock = 'mock'
    const battleWinnerMock = 'mock'

    class TypeMock {
        setStats() {
            return 'mockStats'
        }
    }

    const battleInteractor = new BattleInteractor({
        battleRepository: {
            savedDatabase: () =&gt; true
        },
        typeFactory: {
            getStrategy: () =&gt; {
                return new TypeMock()
            },
        },
        battleEntity: {
            battleLogic: () =&gt; {
                return &quot;battleLogicMock&quot;
            }
        },
        battleWinner: {
            battleWinner: () =&gt; {
                return battleWinnerMock
            }
        },
    })


    test.only('Should return properties formatted', async () =&gt; {
        const res = await battleInteractor.execute(pokemonOneMock, pokemonTwoMock)
        expect(res.message).toBe(&quot;carnivine and naganadel have tied&quot;)
    })


})
</code></pre>
<p>All works fine, so I have some questions:
What should I test in a method like this?
Is this a unit testing or a integration testing?
How necessary is it to test a class/method like this?</p>
",https://stackoverflow.com/questions/72066525/unit-testing-a-method-that-calls-other-methods-jest,"['javascript', 'node.js', 'unit-testing', 'jestjs', 'integration-testing']",493,False,1,0
how to check 200 ok using Bunit in Blazor WebAssembly,"<p>I am new to Blazor WebAssembly  and unit testing.</p>
<p>I want to do a unit test</p>
<ol>
<li>Check whether a API returns with status code 200?</li>
<li>Check whether the API return correct output</li>
</ol>
<p>How can I do both?</p>
<p>I tried like this</p>
<pre><code>    public class CreateParticipantApiTest : TestContext
    {

        [Fact]
        public void ListAllAsyncShouldReturn200Status ()
        {
                var cut = RenderComponent&lt;ParticipantsGetAll&gt;(); // I face error at this line

//removed rest
        }

    }
</code></pre>
<pre><code>public class ParticipantsGetAll : IEndpoint&lt;IResult, GetAllParticipantsRequest&gt;
{
// removed
}
</code></pre>
<p>Error :
CS0311  The type 'ParticipantEndpoints.ParticipantsGetAll' cannot be used as type parameter 'TComponent' in the generic type or method 'TestContext.RenderComponent(params ComponentParameter[])'. There is no implicit reference conversion from 'ParticipantEndpoints.ParticipantsGetAll' to 'Microsoft.AspNetCore.Components.IComponent'.    test    Test\Participant\CreateParticipantApiTest.cs    27  Active</p>
",https://stackoverflow.com/questions/74823918/how-to-check-200-ok-using-bunit-in-blazor-webassembly,"['unit-testing', 'moq', 'xunit', 'blazor-webassembly', 'bunit']",68,False,1,1
Mock assigned to instance variable is null during Spock Groovy test,"<p>I am encountering a strange error with Spock when unit testing a Groovy class. In the test I am mocking a Jenkins CI class (not sure if relevant). During my test the <code>ctx</code> instance variable of <code>MyClass</code> is null so I get a <code>NullPointerException</code>, even though it is not null when created in the test (&quot;when&quot; feature).</p>
<p>Am I doing something wrong here? It appears that the mock object reference is cleared during the test. Below is a simplified example to illustrate:</p>
<pre><code>import org.jenkinsci.plugins.workflow.cps.CpsScript
import spock.lang.*

class MySpec extends Specification {

    def 'does something'() {
        given: 'valid input'
        def foo = 'foo'
       
        when: 'something happens'
        def context = createContext()
        assert context
        def obj = new MyClass(createContext())
        def success = obj.doSomething(foo)
        
        then: 'it is successful'
        assert success
    }

    private def createContext() {
        def ctx = Mock(CpsScript)
        ctx.sh(_) &gt;&gt; &quot;sh called&quot;
        return ctx
    }
}
</code></pre>
<pre><code>class MyClass {

    private final def ctx

    MyClass(ctx) {
        this.ctx = ctx
    }

    def doSomething(foo) {
        ctx.sh('// bash script that uses foo')
    }
}
</code></pre>
",https://stackoverflow.com/questions/73690817/mock-assigned-to-instance-variable-is-null-during-spock-groovy-test,"['jenkins', 'groovy', 'spock']",87,False,0,0
My tSQLt scripts gets overwritten when prod db refresh happens? How to persist the tsqlt script?,"<p>I have tsqlt installed on lower environments and I have created my tsqlt for the unit testing. But right now, we don't promote tSQLt to production since we are not allowed to install tSQLt in production db. But after every release, our dba team will refresh the lower environment with production data and hence our lower environment tSQLt script gets overwritten. How do I persist in my tsqlt in the lower environments? Any thoughts or solutions?</p>
",https://stackoverflow.com/questions/71408512/my-tsqlt-scripts-gets-overwritten-when-prod-db-refresh-happens-how-to-persist-t,"['unit-testing', 'sql-server-2012', 'tdd', 'clr', 'tsqlt']",68,False,0,0
How to have the console support input for System.in in Idea unit tests,"<p>When unit testing in IntelliJ IDEA Education Edition, the console does not support System.in input.</p>
<p>The code I wrote is as follows:</p>
<pre class=""lang-java prettyprint-override""><code>@Test
void main() {
    Scanner scanner = new Scanner(System.in);
    int judge = 1;
    while (judge == 1)
    {
        int n = scanner.nextInt();
        System.out.println(&quot;输入的数为：&quot; + n);
        if (n == 0)
            judge = 0;
    }
} 
</code></pre>
<p>When I run the test, I cannot enter it from the console and show that the test passed. I knew that unit tests didn't need input from the console to complete the test, but I happened to find out about the problem and wondered how to fix it. Just start learning unit tests, teach us a lot!</p>
",https://stackoverflow.com/questions/71797805/how-to-have-the-console-support-input-for-system-in-in-idea-unit-tests,"['java', 'unit-testing', 'intellij-idea']",115,False,0,1
How to get rid of Null Pointer Exception when I&#39;m trying to change value that I received after Mockito.doReturn?,"<p>I'm writing tests for my pet-project. Right now, I'm stuck with unit testing. I have a big method called &quot;check-ownership&quot;, that returns an enum value.</p>
<p>During a run, this method changes numerous amount of objects.</p>
<p>Part of my method:</p>
<pre><code>if(aruCalls.size() == 0) {
    aruCallDtoRequest.setDopFlag(0);
}
</code></pre>
<p>Take a look at aruCallDtoRequest.setDopFlag(0); line</p>
<p>Here is my test:</p>
<pre><code>@ExtendWith(MockitoExtension.class)
class ReRegistrationServiceImplTest {



    @InjectMocks
    private ReRegistrationServiceImpl reRegistrationServiceImpl;

    @Mock
    private IntegrationClient integrationClient;
    @Mock
    private AruCallsService aruCallsService;
    @Mock
    private AruRequestService aruRequestService;
    @Mock
    private DealerService dealerService;

    private Dealer dealer;
    private Location location;
    private LocalDateTime currentTime;
    private CheckRegistrationDtoRequest checkRegistrationDtoRequest;
    private AruCallDtoRequest aruCallDtoRequest;
    private AruRequest aruRequest;
    private AruRequestDtoRequest aruRequestDtoRequest;
    private ResponseEntity&lt;List&lt;UsageDetailDtoResponse&gt;&gt; outgoingCalls;

    @BeforeEach
    public void init() throws H1NotAllowed, H1NotFound {
        aruCallDtoRequest = AruCallDtoRequest.builder()
                .customerMsisdn(TEST_NUMBER)
                .aruRequestsId(null).build();
    }


    @Test
    @DisplayName(&quot;Test for checking of Aru Request Creating at the initialization of the checkOwnership method&quot;)
    public void test_aruCallsSizeIsEqualToZeroAndAruRequestHasBeenCreated() throws H1NotAllowed, H1NotFound {
        verify(dealerService).findMe();
        verify(integrationClient).getLocation(TEST_NUMBER);
        verify(aruCallsService).findAllByOnRegisteredBetween(currentTime.minusHours(24),TEST_NUMBER);
        verify(aruRequestService).create(new AruRequestDtoRequest());
        assertEquals(result,CheckOwnershipDtoResponse.MORE_NUMBERS_NEEDED);
    }
</code></pre>
<p>Every time I run it, I receive a NPE at the line with the &quot;aruCallDtoRequest.setDopFlag(0)&quot;. Any ideas how to get rid of this exception?</p>
",https://stackoverflow.com/questions/74740639/how-to-get-rid-of-null-pointer-exception-when-im-trying-to-change-value-that-i,"['java', 'testing', 'junit', 'mockito']",52,False,0,0
Mock function that is inherited while using pytest.mark.parametrize,"<p>I am new to unit testing. I created some classes to get from an API, deserialize it to JSON and input its values to a DB. All classes are working and I'm writing the unit tests right now. I have the following classes:</p>
<pre><code>import requests


class GetResponse():

    def getDeserialize(self, url: str):
        
        ApiResponse = requests.get(f'{url}')
        
        toJson = ApiResponse.json()
        
        return toJson


class MercadoBitcoin(GetResponse):

    def __init__(self) -&gt; None:
        #super().__init__()
        self.beginningOfUrl = 'https://www.mercadobitcoin.net/api'


    # This method is to get generally from the API
    def standardGet(self, coin: str, method: str):

        self.URL = f'{self.beginningOfUrl}/{coin}/{method}/'
        
        urlGet = super().getDeserialize(self.URL)

        return urlGet

    
    # This method is to get specifically from the API Day Summary
    def daySummary(self, year: int, month: int, day: int, coin: str):
        
        method = 'day-summary'

        self.URL = f'{self.beginningOfUrl}/{coin}/{method}/{year}/{month}/{day}'

        urlGet = super().getDeserialize(self.URL)

        return urlGet
</code></pre>
<p>I wrote this test:</p>
<pre><code>class TestMercadoBitcoin():
    
    
    @pytest.mark.parametrize(
        &quot;coin, method, expected&quot;,
        [
            (&quot;BTC&quot;, &quot;ticker&quot;, &quot;https://www.mercadobitcoin.net/api/BTC/ticker/&quot;),
            (&quot;ETH&quot;, &quot;ticker&quot;, &quot;https://www.mercadobitcoin.net/api/ETH/ticker/&quot;)
        ]
    )
    def test_standardGet(self, coin, method, expected):
        
        actual = MercadoBitcoin()
        actual.standardGet(coin=coin, method=method)
        assert actual.URL == expected
</code></pre>
<p><strong>I only want to test if the URL is the same as expected</strong>, not to run the request to the API. I tried these approaches for mockings and both didn't work:</p>
<pre><code>    @patch(requests.get)
    @pytest.mark.parametrize(
        &quot;coin, method, expected&quot;,
        [
            (&quot;BTC&quot;, &quot;ticker&quot;, &quot;https://www.mercadobitcoin.net/api/BTC/ticker/&quot;),
            (&quot;ETH&quot;, &quot;ticker&quot;, &quot;https://www.mercadobitcoin.net/api/ETH/ticker/&quot;)
        ]
    )
    def test_standardGet(self, coin, method, expected, mock_requests):
        
        actual = MercadoBitcoin()
        actual.standardGet(coin=coin, method=method)
        assert actual.URL == expected


    @patch(super.getDeserialize)
    @pytest.mark.parametrize(
        &quot;coin, method, expected&quot;,
        [
            (&quot;BTC&quot;, &quot;ticker&quot;, &quot;https://www.mercadobitcoin.net/api/BTC/ticker/&quot;),
            (&quot;ETH&quot;, &quot;ticker&quot;, &quot;https://www.mercadobitcoin.net/api/ETH/ticker/&quot;)
        ]
    )
    def test_standardGet(self, coin, method, expected, mock_requests):
        
        actual = MercadoBitcoin()
        actual.standardGet(coin=coin, method=method)
        assert actual.URL == expected
</code></pre>
",https://stackoverflow.com/questions/73041755/mock-function-that-is-inherited-while-using-pytest-mark-parametrize,"['python', 'oop', 'mocking', 'pytest', 'python-unittest']",184,False,0,0
How to test a method in a Stateful Widget?,"<p>I'm learning how to test a method in a Stateful Widget. Now I'm concerned with unit testing. This is my code (I cut the useless part):</p>
<pre><code>class Counter extends StatefulWidget {
  bool filter;
  Counter({Key? key, required this.filter}) : super(key: key);

  @override
  _CounterState createState() =&gt; _CounterState(filter);
}

class _CounterState extends State&lt;Counter&gt; {
  bool filter;
  int counter = 0;

  _CounterState(this.filter);

  void incrementCounter() {
    setState(() {
      if (counter &lt; 100) {
        counter++;
      }
    });
  }

  void decrementCounter() {
    setState(() {
      if (counter &gt; 0) {
        counter--;
      }
    });
  }

  void setCounter(double newValue) {
    setState(() {
      counter = newValue.toInt();
    });
  }

  @override...
</code></pre>
<p>And I want to test the methods incrementCounter() and decrementCounter() but the code can't find these two methods. This is an example:</p>
<pre><code>import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
//other imports...

void main() {
  group(&quot;Price should be incremented&quot;, () {
    PassMarker.useMobileLayout = true;
    test('value should start at 0', () {
      expect(Counter(filter: true), 0);
    });
  });
}
</code></pre>
<p>But when I call the two methods the code doesn't find them, I also try to substitue expect(Counter(filter:true),0); with expect(_CounterState(filter:true),0); but _CounterState isn't find</p>
",https://stackoverflow.com/questions/73386036/how-to-test-a-method-in-a-stateful-widget,"['flutter', 'unit-testing', 'testing', 'statefulwidget']",182,False,0,0
How to exclude certain logging level from [Test worker] logger,"<p>I use <code>WireMock</code> library for unit testing and every time I receive a lot of the DEBUG logs:</p>
<p><a href=""https://i.stack.imgur.com/fFMpL.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fFMpL.png"" alt=""enter image description here"" /></a></p>
<p>I try to exclude logs with `logbak-test.xml' file but it give an unexpectedly result: even I create an empty file - no one log outputted:</p>
<pre class=""lang-xml prettyprint-override""><code>&lt;configuration&gt;
&lt;/confuguration&gt;
</code></pre>
<p>But I need to receive ERROR and WARN logs, etc...</p>
<p>So, my WireMock configuration:</p>
<pre class=""lang-java prettyprint-override""><code>    @ConfigureWireMock
    protected Options options = wireMockConfig()
            .port(8088)
            .notifier(new Slf4jNotifier(true))
            .extensions(ResponseTemplateTransformer.builder()
                    .global(false)
                    .maxCacheEntries(10L)
                    .build());
</code></pre>
<p>logbak-test.xml:</p>
<pre class=""lang-xml prettyprint-override""><code>&lt;configuration debug=&quot;false&quot; scan=&quot;true&quot;&gt;
    &lt;!-- Turning down the wiremock logging --&gt;
    &lt;logger name=&quot;com.github.tomakehurst.wiremock&quot; level=&quot;WARN&quot;/&gt;
    &lt;logger name=&quot;wiremock.org&quot; level=&quot;ERROR&quot;/&gt;
    &lt;logger name=&quot;WireMock&quot; level=&quot;WARN&quot;/&gt;
    &lt;!-- wiremock has per endpoint servlet logging --&gt;
    &lt;logger name=&quot;/&quot; level=&quot;WARN&quot;/&gt;
&lt;/configuration&gt;
</code></pre>
<p>application.properties:</p>
<pre><code>com.github.tomakehurst.wiremock=TRACE
</code></pre>
<ul>
<li>How to receive exactly ERROR, INFO and WARN logs?</li>
</ul>
<p>There are the code where I need to get a log:</p>
<pre class=""lang-java prettyprint-override""><code>@Slf4j
public class TryCatchResponseUtil {
    public void logiingTest(){
        log.error(&quot;error&quot;);
    }
}
</code></pre>
",https://stackoverflow.com/questions/72433083/how-to-exclude-certain-logging-level-from-test-worker-logger,"['java', 'slf4j', 'wiremock']",389,False,0,1
First time use RSpec on Rails Engine,"<p>this is the first time i use RSpec for unit testing in Rails Engine, i want to ask something that i dont understand how its work</p>
<p>this is my routes:</p>
<pre><code>Community::Questions::Engine.routes.draw do
  resources :questions, path: '/', only: [:index, :show, :create, :destroy, :update] do
    resources :answers, path: '/answers', only: [:index, :show, :create, :destroy, :update]
    resources :search, path: '/all', only: [:index]
  end
end
</code></pre>
<p>this is my controller</p>
<pre><code>module Community::Questions
  class QuestionsController &lt; ApplicationController
    skip_before_action :verify_authenticity_token
    before_action :authenticate_user!, only: %i[create update destroy]

    def index
      questions = Community::Question.last(5)

      render_json(questions)
    end
  end
end
</code></pre>
<p>and this is my spec test files</p>
<pre><code>require &quot;rails_helper&quot;

RSpec.describe Community::Questions::QuestionsController, type: :controller do
  describe &quot;GET index&quot; do
    it &quot;returns a 200&quot; do
      get :index
      expect(response).to have_http_status(:ok)
    end
  end
end
</code></pre>
<p>but ive got an error that i really have no idea</p>
<pre><code>Failures:

  1) Community::Questions::QuestionsController GET index returns a 200
     Failure/Error: get :index
     
     ActionController::UrlGenerationError:
       No route matches {:action=&gt;&quot;index&quot;, :controller=&gt;&quot;community/questions/questions&quot;}
     # ./spec/community/questions_controller_spec.rb:6:in `block (3 levels) in &lt;top (required)&gt;'

Finished in 0.02578 seconds (files took 1.31 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/community/questions_controller_spec.rb:5 # Community::Questions::QuestionsController GET index returns a 200
</code></pre>
<p>does anyone here know where is my fault? and know how to fix my unit test please? an insight really helpful, thankyou so much :)</p>
",https://stackoverflow.com/questions/73405116/first-time-use-rspec-on-rails-engine,"['ruby-on-rails', 'ruby', 'rspec', 'rspec-rails']",64,False,0,0
Doxygen not collects files from INCLUDE_PATH,"<p>For Unit testing purposes I mocked some cpp files in a separate directory but still using the origin header files.</p>
<p>In my special case the cpp files (origin and mocked) are holding the member documentation.</p>
<p>Sadly the cpp mocks aren't documented. I've set INCLUDE_PATH to the origin of the h-files (where are the origin cpp files are located as well).</p>
<p>In the mocked cpp files I used @ingroup/@addtogroup to proper arrange them inside the modules section.</p>
",https://stackoverflow.com/questions/73566010/doxygen-not-collects-files-from-include-path,['doxygen'],94,False,0,0
How to mock a controller with action that retrieves and stores value using session storage and cookies?,"<p>I am currently unit testing a controller action method called ResourcesCustomReports by mocking it's controller.</p>
<p>The action method invokes a helper method called GetCurrentTenant which uses this.Request.Cookies[&quot;selectedtenant&quot;] to return a value.</p>
<p>In the action I also use session storage to store a key value pair. My question is how do I wire up/mock this action method? Atm I get this error:</p>
<p>System.NullReferenceException: 'Object reference not set to an instance of an object.'</p>
<p>Microsoft.AspNetCore.Mvc.ControllerBase.Request.get returned null.'</p>
<pre><code>    protected Guid GetCurrentTenant()
    {
        var currentTenant = this.Request.Cookies[&quot;selectedtenant&quot;] ?? 
        this.GetUserDefaultTenant().ToString();
        return Guid.Parse(currentTenant);
    }

    [TestMethod]
    public void GetCustomDateResourcesReturnsExcelWorkBook()
    {
        var mockPrismRepository = new Mock&lt;IPrismRepository&gt;();
        var mockIlogger = new Mock&lt;ILogger&lt;AzureReportsController&gt;&gt;();
        var mockReportsRepository = new Mock&lt;IReportsRepository&gt;();
        var context = new Mock&lt;ControllerContext&gt;();

        DateTime from = DateTime.Today;
        DateTime to = from.AddDays(30);

        var tenantId = Guid.Parse(&quot;3c6b60a7-8d30-4da3-bfdc-00691e899b5f&quot;);
        var excelWorkBook = new XLWorkbook();
        var mockReportRepository = new Mock&lt;IReportsRepository&gt;();

        mockReportRepository.Setup(r =&gt; r.GetCustomDateResources(tenantId,
        to, from)).Returns(excelWorkBook);
        var azureReportControllerUnderTest = new 
        AzureReportsController(mockIlogger.Object, 
        mockPrismRepository.Object, mockReportRepository.Object);

        azureReportControllerUnderTest.ControllerContext = new ControllerContext
        {
            HttpContext = new DefaultHttpContext(),
        };
        azureReportControllerUnderTest.ControllerContext = context.Object;

        var result = azureReportControllerUnderTest.ResourcesCustomReports(to, from);
        Assert.IsNotNull(result);

        excelWorkBook.Dispose();
        azureReportControllerUnderTest.Dispose();
    }

    protected Guid GetCurrentTenant()
    {
     var currentTenant = this.Request.Cookies[&quot;selectedtenant&quot;] ? 
     this.GetUserDefaultTenant().ToString();
     return Guid.Parse(currentTenant);
    }


   public IActionResult ResourcesCustomReports(DateTime? startingDate, 
   DateTime endingDate)
    {
        var selectedTenant = this.GetCurrentTenant();
        var fileName = $&quot;resources_report_tenant_id_{selectedTenant}.xlsx&quot;;
        var workbook = 
        this.reportsRepository.GetCustomDateResources(selectedTenant, startingDate, 
        endingDate);
        string handle = Guid.NewGuid().ToString();

        using (MemoryStream memoryStream = new MemoryStream())
        {
            workbook?.SaveAs(memoryStream);
            memoryStream.Position = 0;
            this.HttpContext.Session.Set(handle, memoryStream.ToArray());
        }

        return this.Json(new { FileGuid = handle, FileName = fileName });
    }
</code></pre>
",https://stackoverflow.com/questions/73857540/how-to-mock-a-controller-with-action-that-retrieves-and-stores-value-using-sessi,"['c#', 'unit-testing', 'asp.net-core', 'mocking']",115,False,0,0
Having issues referencing a class with NUnit testing,"<p>I have a directory labeled unit-testing-using-nunit as defined in the Microsoft documentation. My issue is being unable to reference the classes I want to test. I'm still relatively new to .NET so I'm having issues understanding how to properly implement these unit tests.</p>
<p><a href=""https://i.stack.imgur.com/rajPb.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/rajPb.png"" alt=""This is my directory tree"" /></a></p>
<p>After implementing Usings.cs
<a href=""https://i.stack.imgur.com/g33JD.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/g33JD.png"" alt=""Usings.cs"" /></a></p>
<p>I end up with this error:
<a href=""https://i.stack.imgur.com/I0A3J.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/I0A3J.png"" alt=""Error"" /></a></p>
<p>I feel like once I get a hint for how to reference /API/Entities/AppUser.cs I'll be able to take it from there.</p>
",https://stackoverflow.com/questions/74757825/having-issues-referencing-a-class-with-nunit-testing,"['c#', '.net', 'unit-testing', 'visual-studio-code', 'nunit']",30,True,0,1
Springboot 2.7 : Property &#39;sqlSessionFactory&#39; or &#39;sqlSessionTemplate&#39; are required in @WebMvcTest for spring boot with mybatis,"<p>Below is my PaymentController Unittest</p>
<pre><code>@WebMvcTest(PaymentController.class)
public class PaymentControllerTest {
    @MockBean
    PaymentService paymentService;

    @Autowired
    MockMvc mockMvc;

    @Test
    public void testFindAllPaymentDtoAndExpect200() throws Exception {
         mockMvc.perform(MockMvcRequestBuilders
                        .get(&quot;/payment/list&quot;))
                        .andExpect(status().isOk());
    }
    
</code></pre>
<p>I'm seeing the below stacktrace when I run the above unit test and am wondering why the @WebMvcTest trying to initialize the <code>sqlSessionFactory</code> for unit test? Can someone please help me fix this error?
I have refered the similar issue <a href=""https://github.com/mybatis/spring-boot-starter/issues/227"" rel=""nofollow noreferrer"">https://github.com/mybatis/spring-boot-starter/issues/227</a> but it was for integration testing in my case it is a unit testing.</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.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:110)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:94)
    at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:61)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:248)
    at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$8(ClassBasedTestDescriptor.java:363)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.executeAndMaskThrowable(ClassBasedTestDescriptor.java:368)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$9(ClassBasedTestDescriptor.java:363)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
    at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:179)
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
    at java.base/java.util.stream.StreamSpliterators$WrappingSpliterator.forEachRemaining(StreamSpliterators.java:310)
    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:762)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeTestInstancePostProcessors(ClassBasedTestDescriptor.java:362)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$instantiateAndPostProcessTestInstance$6(ClassBasedTestDescriptor.java:283)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.instantiateAndPostProcessTestInstance(ClassBasedTestDescriptor.java:282)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$4(ClassBasedTestDescriptor.java:272)
    at java.base/java.util.Optional.orElseGet(Optional.java:364)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$testInstancesProvider$5(ClassBasedTestDescriptor.java:271)
    at org.junit.jupiter.engine.execution.TestInstancesProvider.getTestInstances(TestInstancesProvider.java:31)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$prepare$0(TestMethodTestDescriptor.java:102)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:101)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.prepare(TestMethodTestDescriptor.java:66)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$prepare$2(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.prepare(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:90)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    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:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    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:77)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:568)
    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$3.run(TestWorker.java:193)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
    at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
    at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
    at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
    at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoApiController': Unsatisfied dependency expressed through field 'demoService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoServiceImpl' defined in file [C:\Dev\gitlab\billing-app\marketplace\build\classes\java\main\us\billing\service\impl\DemoServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoDataReadMapper' defined in file [C:\Dev\gitlab\billing-app\marketplace\build\classes\java\main\us\billing\mapper\DemoDataReadMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    at app//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659)
    at app//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639)
    at app//org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119)
    at app//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at app//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955)
    at app//org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
    at app//org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583)
    at app//org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734)
    at app//org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408)
    at app//org.springframework.boot.SpringApplication.run(SpringApplication.java:308)
    at app//org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:132)
    at app//org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:99)
    at app//org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    ... 88 more
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoServiceImpl' defined in file [C:\Dev\gitlab\billing-app\marketplace\build\classes\java\main\us\billing\service\impl\DemoServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoDataReadMapper' defined in file [C:\Dev\gitlab\billing-app\marketplace\build\classes\java\main\us\billing\mapper\DemoDataReadMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    at app//org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800)
    at app//org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:229)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at app//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at app//org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
    at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1391)
    at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311)
    at app//org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:656)
    ... 107 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoDataReadMapper' defined in file [C:\Dev\gitlab\billing-app\marketplace\build\classes\java\main\us\billing\mapper\DemoDataReadMapper.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1804)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:620)
    at app//org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335)
    at app//org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333)
    at app//org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208)
    at app//org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276)
    at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1391)
    at app//org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311)
    at app//org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:887)
    at app//org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:791)
    ... 120 more
Caused by: java.lang.IllegalArgumentException: Property 'sqlSessionFactory' or 'sqlSessionTemplate' are required
    at org.springframework.util.Assert.notNull(Assert.java:201)
    at org.mybatis.spring.support.SqlSessionDaoSupport.checkDaoConfig(SqlSessionDaoSupport.java:122)
    at org.mybatis.spring.mapper.MapperFactoryBean.checkDaoConfig(MapperFactoryBean.java:73)
    at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1863)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1800)
    ... 131 more
</code></pre>
<p>Below is <code>DemoApiController</code> code which is not linked with the <code>PaymentController</code> that am trying to unit test</p>
<pre><code>@RestController
public class DemoApiController implements DemoApi {
    @Autowired
    private DemoService demoService;

    @Override
    public String getDemoData(String id) {          
        return &quot;demo data size &quot; +demoService.demoFetchFromDatabase().size();
    }
}

public interface DemoService {
    List&lt;DemoData&gt; demoFetchFromDatabase();
}

@Service
@RequiredArgsConstructor
public class DemoServiceImpl implements DemoService {

    private final DemoDataReadMapper demoDataReadMapper;  

    @Override
    public List&lt;DemoData&gt; demoFetchFromDatabase() {
        return demoDataReadMapper.listDemoData(Arrays.asList(&quot;1&quot;, &quot;2&quot;));
    }
}

@Mapper
@Repository
@DBRouter(DatasourceType.Slave)
public interface DemoDataReadMapper {
    List&lt;DemoData&gt; listDemoData(@Param(&quot;items&quot;) Collection&lt;String&gt; idList);
}
</code></pre>
",https://stackoverflow.com/questions/74707199/springboot-2-7-property-sqlsessionfactory-or-sqlsessiontemplate-are-requir,"['java', 'spring', 'spring-boot', 'unit-testing', 'spring-mvc-test']",1155,False,3,1
Mocking a call to Cache::store -&gt;get() in unit tests in Laravel,"<p>I am unit testing a method that with the following call to the Cache facade. According to the laravel docs, this is the correct way to mock the call to the cache. I cannot find any docs on how to specify the store part of the call, which I am assuming is the cause of the error which is being thrown. My question is: <strong>how do I mock this Cache get call that is using the cache store?</strong></p>
<p>Service Method:</p>
<pre><code>    someMethod() 
{
         $option = Cache::store('ruleConditionsOptions')-&gt;get($condition-&gt;rule_conditions_option_id);
         return some stuff
}
</code></pre>
<p>Test:</p>
<pre><code>Cache::shouldReceive('get')
            -&gt;once()
            -&gt;with(4)
            -&gt;andReturn('Platform');

$result = someMethodCall
$this-&gt;assertSomething
</code></pre>
<p>Error:</p>
<pre><code>Received Mockery_0_Illuminate_Cache_CacheManager::store(), but no expectations were specified
</code></pre>
",https://stackoverflow.com/questions/72048843/mocking-a-call-to-cachestore-get-in-unit-tests-in-laravel,"['php', 'laravel', 'unit-testing', 'caching', 'mocking']",322,False,3,0
React JS Jest mock implementation of Class with static members,"<p>I am working on a project in which I am writing jest unit testing but I am stuck with below problem. I also search on google but not get any proper solution.</p>
<h2>ActivityDetailsModal.js</h2>
<pre><code>class ActivityDetailsModal {
    static Activity = {
        activityType : ‘PLOT’
    }
}
</code></pre>
<h2>Xyz.test.js</h2>
<pre><code>Import { ActivityDetailsModal, useCustomHook } from ‘@cc-module’;

// This mock being used in other test case
jest.mock(‘@cc-module’,() =&gt; ({
    useCustomHook : jest.fn();
}));

it('should fail test’, async () =&gt; {
    …..
    // Here I get the error : ActivityDetailsModal is undefined
    const activityType = ActivityDetailsModal.Activity.activityType;
    …..
});
</code></pre>
<p>So I think because of mock implementation of <code>@cc-module</code> I am unable to access <code>ActivityDetailsModal</code> here So how can I have mock implementation of this class or some how I can ignore mocking for one particular test. I don’t know how is this possible.</p>
",https://stackoverflow.com/questions/72024833/react-js-jest-mock-implementation-of-class-with-static-members,"['reactjs', 'unit-testing', 'class', 'static-methods']",70,True,0,1
How do I separate between integration testing and unit testing using Hapi in Node.js?,"<p>How do I separate between integration testing and unit testing using Hapi in Node.js?</p>
<p>I am trying to reduce the testing time in our automations for every time we update a unit within our API.</p>
<p>I was wondering can I just create two new folders test/unit and test/int to separate the scripts and what would the update to the package.json require?</p>
<p>I have the following in the package.json which runs the .labrc.js
package.json</p>
<pre><code>    &quot;test&quot;: &quot;npm run version-stamp &amp;&amp; lab --bail -t 80 -r html -o coverage.html -r console -o stdout -r junit -o TestResult.xml -r lcov -o coverage.dat&quot;,
    &quot;simple-test&quot;: &quot;npm run version-stamp &amp;&amp; lab&quot;,
    &quot;test-int&quot;: &quot;not sure what to put here&quot;,
</code></pre>
<p>labrc.js</p>
<pre><code>module.exports = {
    verbose: true,
    timeout: 7500,
    lint: true,
    paths: [
        &quot;test/init/aws&quot;,
        &quot;test/unit/plugins&quot;,
        &quot;test/unit/utils&quot;,
        &quot;test/unit/routes&quot;
    ],
</code></pre>
",https://stackoverflow.com/questions/74690668/how-do-i-separate-between-integration-testing-and-unit-testing-using-hapi-in-nod,"['node.js', 'unit-testing', 'jestjs', 'nunit', 'hapi.js']",52,False,0,1
IEnumerable swallows an exception and a unit test cannot catch it,"<p>I'm unit testing the following method and I expect <code>ArgumentOutOfRangeException</code> to be thrown. Instead <code>gridTrading.GridLevels().As&lt;double[]&gt;()</code> returns null for whatever reason. It basically swallows the exception. How do I fix it by keeping the return type as <code>IEnumerable&lt;double&gt;</code> and not converting it to <code>List&lt;double&gt;</code>? Btw, I added <code>.As&lt;double[]&gt;()</code> to prevent multiple enumeration.</p>
<p>Lastly, do you think I'm wrong by trying to keep it <code>IEnumerable&lt;double&gt;</code>?</p>
<pre class=""lang-cs prettyprint-override""><code>[Fact]
public void GridLevels_ShouldThrow_WhenGivenInvalidGridType()
{
    // Arrange
    const double lowerLimit = 2000;
    const double upperLimit = 10000;
    const int gridCount = 4;
    const int gridType = 4;

    var gridTrading = new GridTrading(lowerLimit, upperLimit, gridCount, (GridType)gridType);

    // Act
    var action = new Action(() =&gt; gridTrading.GridLevels().As&lt;double[]&gt;());

    // Assert
    action.Should().Throw&lt;ArgumentOutOfRangeException&gt;().WithMessage(&quot;Grid type must be valid&quot;);
}

// The method I test
public IEnumerable&lt;double&gt; GridLevels()
{
    switch (_gridType)
    {
        case GridType.Arithmetic:
            foreach (var level in CalculateArithmetic())
            {
                yield return level;
            }

            break;

        case GridType.Geometric:
            foreach (var level in CalculateGeometric())
            {
                yield return level;
            }

            break;

        default:
            throw new ArgumentOutOfRangeException(nameof(_gridType), &quot;Grid type must be valid&quot;);
    }

    IEnumerable&lt;double&gt; CalculateArithmetic()
    {
        var step = (_upperLimit - _lowerLimit) / _gridCount;

        for (var i = 0; i &lt;= _gridCount; i++)
        {
            var price = _lowerLimit + step * i;
            yield return price;
        }
    }

    IEnumerable&lt;double&gt; CalculateGeometric()
    {
        var step = Math.Pow(_upperLimit / _lowerLimit, 1.0 / _gridCount);

        for (var i = 0; i &lt;= _gridCount; i++)
        {
            var price = _lowerLimit * Math.Pow(step, i);
            yield return price;
        }
    }
}
</code></pre>
<p>I know I could make GridLevels a <code>List&lt;double&gt;</code> instead <code>IEnumerable&lt;double&gt;</code> which would make it throw for real but I don't wanna do that.</p>
<pre class=""lang-cs prettyprint-override""><code>public List&lt;double&gt; GridLevels()
{
    var list = new List&lt;double&gt;();

    switch (_gridType)
    {
        case GridType.Arithmetic:
            list.AddRange(CalculateArithmetic());
            break;

        case GridType.Geometric:
            list.AddRange(CalculateGeometric());
            break;

        default:
            throw new ArgumentOutOfRangeException(nameof(_gridType), &quot;Grid type must be valid&quot;);
    }

    return list;

    IEnumerable&lt;double&gt; CalculateArithmetic()
    {
        var step = (_upperLimit - _lowerLimit) / _gridCount;

        for (var i = 0; i &lt;= _gridCount; i++)
        {
            var price = _lowerLimit + step * i;
            yield return price;
        }
    }

    IEnumerable&lt;double&gt; CalculateGeometric()
    {
        var step = Math.Pow(_upperLimit / _lowerLimit, 1.0 / _gridCount);

        for (var i = 0; i &lt;= _gridCount; i++)
        {
            var price = _lowerLimit * Math.Pow(step, i);
            yield return price;
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/74203290/ienumerable-swallows-an-exception-and-a-unit-test-cannot-catch-it,"['c#', '.net', 'unit-testing', 'xunit', 'fluent-assertions']",158,True,0,1
Can&#39;t mock the navigator.language,"<p>I'm currently adding unit test for some of shard utils functions. I'm kinda new to unit testing. Currently having hard time to mock some global object. Is there any way to mock/update value of <code>navigator.language</code>? It is always returning <code>en-US</code>. I tried the Object.defineProperty and different jest mock objects. Didn't work.</p>
<p>The thing is, if I <code>console.log(navigator.language)</code> in the test, it will show me mocked value, but util function is not seeing that value.</p>
<p>Here is the code.</p>
<pre><code>//utils.js

export function getLang() {
  if (navigator.languages) return navigator.languages[0];
  return navigator.language;
}
</code></pre>
<pre><code>//utils.spec.ts

describe('Navigator', () =&gt; {
  afterEach(() =&gt; {
    jest.restoreAllMocks();
  });


  //Error - Failing
  it('should return exact response language if there is one', () =&gt; {
    jest.spyOn(navigator, 'language', 'get').mockImplementation(() =&gt; 'en-fr');
    expect(getLang()).toBe('en-fr');
  });



  // Successful - passing
  it('should return 1st language if there array of languages', () =&gt; {
    jest
      .spyOn(navigator, 'languages', 'get')
      .mockImplementation(() =&gt; ['en-fr', 'en-US', 'en']);
    expect(getLang()).toBe('en-fr');
  });
});
</code></pre>
<pre><code>    Expected: &quot;en-fr&quot;
    Received: &quot;en-US&quot;

      25 |     jest.spyOn(navigator, 'language', 'get').mockImplementation(() =&gt; 'en-fr');
      26 |     const lang = getLang();
    &gt; 27 |     expect(lang).toBe('en-fr');
         |                  ^
      28 |   });
</code></pre>
<pre><code>//package.json:

&quot;jest&quot;: &quot;^27.5.1&quot;,
</code></pre>
",https://stackoverflow.com/questions/72883375/cant-mock-the-navigator-language,"['javascript', 'typescript', 'unit-testing', 'jestjs', 'next.js']",179,True,0,1
How to determine that the webcam got turned on using C# Selenium,"<p>Basically the process is that the site uses the webcam to take a picture and verify it. Here in unit testing, at times the webcam takes little bit extra time to turn on and take photo. Before this happens the testing jumps this step and test fails. Below I have attached the code for your reference.</p>
<pre><code>driver.FindElement(By.LinkText(&quot;FACE RECOGNITION&quot;)).Click();
Thread.Sleep(5000);
            
driver.FindElement(By.XPath(&quot;//button[contains(text(),'CAPTURE')]&quot;)).Click();
Thread.Sleep(3000);

Assert.IsTrue(driver.FindElement(By.XPath(&quot;//*[@id='content']/div/div/div[2]/img&quot;)).Displayed);
Assert.IsFalse(driver.FindElement(By.XPath(&quot;//*[@id='content']//div[3]/span&quot;)).Displayed);

var confirmClockIn = driver.FindElement(By.XPath(&quot;//button[contains(text(),'CONFIRM')]&quot;));
var script = &quot;arguments[0].scrollIntoView(true);&quot;;
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript(script, confirmClockIn);
Thread.Sleep(3000);

confirmClockIn.Click();
</code></pre>
<p>How to overcome this problem?? Any idea?
Any improvement to the code? Or Any other way to handle this situation?</p>
",https://stackoverflow.com/questions/73117460/how-to-determine-that-the-webcam-got-turned-on-using-c-selenium,"['c#', 'selenium', 'selenium-webdriver']",112,True,0,1
How to write unittest for table row selection using Antd Library in React,"<p>I have a react application and I'm using <code>@testing-library/jest-dom</code> for unit testing and antd 3.x library for UI design. In one of my UI screen there is a table and a button where the button only enables when one of the row in table is checked. So I wanted to do a unittest for this. So below is my src code,</p>
<pre><code>import {Modal, Button, Form, Input, DatePicker, Table, Card, Tooltip} from 'antd';
...
...
return (
  &lt;&gt;
    &lt;Form&gt;
     ...
     &lt;Card&gt;
         &lt;Table
              data-testid={'lift-hold-grid'}
              className=&quot;holdListResultsTable&quot;
              rowSelection={rowSelection}
              columns={columns}
              dataSource={dataSourcee}
              components={{
                body: {
                  row: showRestorationTooltip
                }
              }}
            /&gt;
     &lt;/Card&gt;
     ...
     &lt;div style = {...}&gt;
       &lt;Button data-testid={'lift-hold-button'} disabled={...} onClick={...}&gt;
           Lift Hold
       &lt;/Button&gt;
     &lt;/div&gt;
    &lt;Form&gt;
  &lt;/&gt;
)
</code></pre>
<p>and below is the unittest</p>
<pre><code>import { render } from &quot;@testing-library/react&quot;;
import { Provider } from &quot;react-redux&quot;;
import thunk from &quot;redux-thunk&quot;;

function renderWithReduxAndThunk(ui, initialState) {
   const createdStore = createStore(rootReducer, initialState, applyMiddleware(thunk));
   return {
       ...render(&lt;Provider store={createdStore}&gt;{ui}&lt;/Provider&gt;),
       createdStore,
    }
}

const changedState = {
   ...
}
it('should enable the lift hold button after checkbox selection and note input', () =&gt; {
   const { container, getByTestId } = renderWithReduxAndThunk(&lt;LegalHoldLiftScreen /&gt;, changedState);
   const checkBox = container.querySelector('.ant-checkbox-input');
   fireEvent.click(checkBox);
   const downloadButton = getByTestId('lift-hold-button');
   expect(downloadButton).toBeTruthy();
   expect(downloadButton).not.toBeDisabled();
});
</code></pre>
<p>but this fails with below message</p>
<pre><code>● should enable the lift hold button after checkbox selection and note input
  Unable to fire a &quot;click&quot; event - please provide a DOM element.
</code></pre>
<p>what am I missing here??</p>
",https://stackoverflow.com/questions/73582321/how-to-write-unittest-for-table-row-selection-using-antd-library-in-react,"['antd', 'react-testing-library', 'redux-thunk']",124,False,0,0
Python unittest and argparse with required value not given,"<p>I am having trouble unit-testing a function I made using argparse library. I would like to test the case when no argument is given. This is the function I would like to test:</p>
<pre><code>def parse_arguments():
parser = argparse.ArgumentParser(description='Testing parsing')
parser.add_argument('--reqVal', required=True, help='Required value')
parser.add_argument('--notReq', required=False, help='Value not required')

return parser.parse_args()
</code></pre>
<p>Here are my tests:</p>
<pre><code>import argparse
from parse_gen import parse_arguments
from unittest.mock import patch


def test_parse_arguments_only_required_args(capsys):
    args_namespace = argparse.Namespace()
    args_namespace.reqVal = 'Required'
    args_namespace.notReq = None
    with patch('sys.argv', ['parse_arguments', '--reqVal', 'Required']):
        parsed_args = parse_arguments()
        assert parsed_args == args_namespace


def test_parse_arguments_no_args(capsys):
    with patch('sys.argv', ['parse_arguments']):
        parsed_args = parse_arguments()
        assert parsed_args == argparse.ArgumentTypeError()
</code></pre>
<p>First test case is working as expected. My problem is that when I want to test no_args case I get an error but it is very long and I do not understand how to fix it. Could you please help me?</p>
",https://stackoverflow.com/questions/72807587/python-unittest-and-argparse-with-required-value-not-given,"['python', 'parsing', 'argparse', 'python-unittest', 'python-unittest.mock']",56,False,0,0
The following constructor parameters did not have matching fixture data: IOptions,"<p>I have this service which I am creating the unit testing using XUnit.</p>
<pre><code>public class MyService : IMyService
{
    private readonly SqlOptions _sqlOptions;
    private readonly MyContext _myContext;
    private readonly IHttpClientFactory _httpClientFactory;

    public FulfillmentService(IOptions&lt;SqlOptions&gt; sqlOptions, 
        MyContext myContext, 
        IHttpClientFactory httpClientFactory)
    {
        _sqlOptions = sqlOptions.Value;
        _myContext = myContext;
        _httpClientFactory = httpClientFactory;
    }
}
</code></pre>
<p>Below is my code in Xunit</p>
<pre><code>public class MyServiceTest : IClassFixture&lt;IOptions&lt;SqlOptions&gt;&gt;, IClassFixture&lt;IHttpClientFactory&gt;
{

    private readonly IOptions&lt;SqlOptions&gt; _IsqlOptions;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly DbContextOptions&lt;MyContext&gt; _options;
    private IMyService? _myService = null;

    public FulFillmentServiceTest(IOptions&lt;SqlOptions&gt; sqlOptions, 
        IHttpClientFactory httpClientFactory)
    {
        _IsqlOptions = sqlOptions;
        _httpClientFactory = httpClientFactory;

        _options = new DbContextOptionsBuilder&lt;MyContext&gt;()
          .UseInMemoryDatabase(databaseName: &quot;myinmemorydb&quot;)
          .Options;
    }

    [Fact]
    public async Task WhenAValidMessagePosted_ThenShouldReturnStatus()
    {
        // code removed for brevity
    }
}
</code></pre>
<p>I put a breakpoint at <code>WhenAValidMessagePosted_ThenShouldReturnStatus</code>, but it could not reach the breakpoint.</p>
<p>These are some errors</p>
<blockquote>
<p>System.AggregateException : One or more errors occurred. (Class fixture type 'Microsoft.Extensions.Options.IOptions` ... may only define a single public constructor.) (The following constructor parameters did not have matching fixture data: IOptions IHttpClientFactory httpClientFactory)</p>
</blockquote>
<blockquote>
<p>---- The following constructor parameters did not have matching fixture data: IOptions ... IHttpClientFactory httpClientFactory</p>
</blockquote>
",https://stackoverflow.com/questions/73481083/the-following-constructor-parameters-did-not-have-matching-fixture-data-ioption,"['c#', 'xunit']",266,False,0,0
Mocking and unit testing Microsoft Graph API to get users list,"<p>I am using Microsoft Graph SDK in my project to call graph API which returns a list of users in</p>
<p>I am trying to mock a call to the microsoft graph api and return a list of users that I can use to assert. I am not really getting how to use the setup method to get an object to assert on. Currently getting an null references object error.</p>
<blockquote>
<p>Interface:</p>
</blockquote>
<pre><code>public Task&lt;IGraphServiceUsersCollectionPage&gt; GetUsersAsync();
</code></pre>
<blockquote>
<p>GetUsersAsync() method calling the API:</p>
</blockquote>
<pre><code>    public Task&lt;IGraphServiceUsersCollectionPage&gt; GetUsersAsync()
    {
        return this.appClient.Users
            .Request(this.queryOptions)
            .Select(@$&quot;
            Id,
            DisplayName,
            GivenName,
            Surname,
            Mail,
            OtherMails,
            CompanyName,
            .OrderBy(&quot;DisplayName&quot;)
            .GetAsync();
    }
</code></pre>
<blockquote>
<p>MS Test: Unit testing:</p>
</blockquote>
<pre><code>public Task&lt;IGraphServiceUsersCollectionPage&gt; GetUsersAsync()
    {
        return this.appClient.Users
            .Request(this.queryOptions)
            .Select(@$&quot;
            Id,
            DisplayName,
            GivenName,
            Surname,
            Mail,
            OtherMails,
            CompanyName,&quot;
            .OrderBy(&quot;DisplayName&quot;)
            .GetAsync();
    }

    
      [TestMethod]
    public void GetUsersAsyncSuccess()
    {
        var mockAuthProvider = new Mock&lt;IAuthenticationProvider&gt;();
        var mockHttpProvider = new Mock&lt;IHttpProvider&gt;();
        var mockGraphClient = new Mock&lt;GraphServiceClient&gt;(mockAuthProvider.Object, mockHttpProvider.Object);
        User users = new User() 
        { 
            Id = &quot;1&quot;, 
            DisplayName = &quot;test&quot;,
            GivenName = &quot;test2&quot;,
            Surname = &quot;test3&quot;
        };
        var emails = Enumerable.Empty&lt;string&gt;();

        // setup the call
        mockGraphClient
          .Setup(g =&gt; g.Users
              .Request()
              .GetAsync(CancellationToken.None))
              .ReturnsAsync(users)
              .Verifiable(); 

        // Act
        var graphClient = mockGraphClient.Object;
        var user = graphClient.Users
            .Request()
            .GetAsync();

        // Assert
        // Assert.AreEqual(users.Id, users.Id);
    }
</code></pre>
",https://stackoverflow.com/questions/74432270/mocking-and-unit-testing-microsoft-graph-api-to-get-users-list,"['c#', 'asp.net-mvc', 'microsoft-graph-api', 'azure-ad-graph-api']",593,False,0,0
"How to write Unit testing (RTL) for a custom onClick function, where this onClick funtion sending as a prop to React Component?","<pre><code>import React from &quot;react&quot;;
import &quot;./ToasterActionMessage.css&quot;;

const ToasterActionMessage = (props) =&gt; {

function retryFunction() {      
    if(props.onRetry) {
        const{onRetry} = props;
        onRetry();
    }    
}

if (props.action) {
    return (
      &lt;div className=&quot;ToasterActionMessage-Card&quot; style={{background: &quot;#A00E18&quot; }}&gt;
        &lt;div className=ToasterActionMessage-Side-body&quot;&gt;
          &lt;p className=&quot;ToasterActionMessage-Message&quot;&gt;
            {props.message}
          &lt;/p&gt;
          &lt;div className=&quot;ToasterActionMessage-btn-text&quot; onClick={retryFunction}&gt;Retry&lt;/div&gt;
        &lt;/div&gt;
      &lt;/div&gt;
    );
  }

  return null;
};

export default ToasterActionMessage;
</code></pre>
<hr />
<p>the above is component which has onClick funciton as a prop and that works as expected.</p>
<hr />
<p>while writing the unit testing, not able to <strong>click</strong> that Component?Somewhere i couldn't able to call that component. the below is the code</p>
<pre><code>import {render, screen} from &quot;@testing-library/react&quot;;
import userEvent from &quot;@testing-library/user-event&quot;
import React from &quot;react&quot;

test(&quot;renders Retry - Onclick function of ToasterActionMessage component&quot;, ()=&gt;{
    const mockOnclickFunction = jest.fn()
    render(&lt;ToasterActionMessage action=&quot;true&quot; onClick={mockOnclickFunction}/&gt;)
    userEvent.click(screen.getElementsByText(&quot;Retry&quot;))
    expect(mockOnclickFunction).toBeCalled();
})
</code></pre>
<p>Response :- <strong>No calls occured</strong></p>
<p>Hope the error is while screening the component, not able to call the component, tried in mulitple ways by usning, getElementsByText, getElementsByclassName, id etc.. somewhere its going wrong, please help to figure it out.</p>
",https://stackoverflow.com/questions/73703412/how-to-write-unit-testing-rtl-for-a-custom-onclick-function-where-this-onclic,"['javascript', 'reactjs', 'unit-testing', 'onclick', 'react-testing-library']",21,False,0,0
How to run Spark unit testing in parallel via pytest (and fixture)?,"<p>I am writing unit testing for a spark application. I am using pytest and I have created a fixture to load the spark session once.</p>
<p>When I run one test at a time, it is passing but when I run all the tests together I am getting unexpected behavior. Then, I realize, spark is not multi-threadable. Any way to fix this? Is running pytest in non-parallel mode is the only solution?</p>
<p>Sample code structure,</p>
<pre><code>@pytest.fixture(scope=&quot;session&quot;)
def spark() -&gt; SparkSession:
    builder = SparkSession.builder.appName(&quot;pandas-on-spark&quot;)
    builder = builder.config(&quot;spark.sql.execution.arrow.pyspark.enabled&quot;, &quot;true&quot;) 
    return builder.getOrCreate()
</code></pre>
<pre><code>def test1(spark):
   df = spark.createDataFrame(dummy_rows)
   # do some transformaton
   # assert
</code></pre>
<pre><code>def test2(spark):
   df = spark.createDataFrame(dummy_rows)
   # do some transformaton
   # assert
</code></pre>
<pre><code>def testN(spark):
   df = spark.createDataFrame(dummy_rows)
   # do some transformaton
   # assert
</code></pre>
<pre><code>pytest -s .
</code></pre>
",https://stackoverflow.com/questions/73754854/how-to-run-spark-unit-testing-in-parallel-via-pytest-and-fixture,"['python', 'apache-spark', 'pyspark', 'pytest']",336,False,0,1
How to test if function invoked inside Node.js API route has been called?,"<p>I'm using Node.js and Express to set up API route.<br />
A route calls a function on an HTTP request.<br />
I want to test if that function has been called.</p>
<p>When I'm making an HTTP request (using Axios, fetch, whatever) inside a test suite, I'm only able to test the HTTP response.</p>
<p>Any ideas on how to overcome this problem?</p>
<p><code>temp.js</code> module</p>
<pre><code>function testFn() {
  console.log(&quot;I just want to test if this fn has been called&quot;)
}

module.exports = {
  testFn,
}
</code></pre>
<p>Express app (that runs in the background)</p>
<pre><code>const { testFn } = require(&quot;./temp&quot;)

app.get('/test', (req, res) =&gt; {
  testFn()
  res.send('GET request')
})
</code></pre>
<p>My approach to testing which obviously doesn't work (it's not unit testing)</p>
<pre><code>const { default: axios } = require(&quot;axios&quot;)
const { testFn } = require(&quot;./temp&quot;)

jest.mock(&quot;./temp&quot;, () =&gt; ({
  testFn: jest.fn(),
}))

test(&quot;API test&quot;, async () =&gt; {
  await axios.get(`http://localhost:3000/test`)
  expect(testFn).toHaveBeenCalled()
})
</code></pre>
",https://stackoverflow.com/questions/72207093/how-to-test-if-function-invoked-inside-node-js-api-route-has-been-called,"['javascript', 'node.js', 'api', 'testing', 'jestjs']",280,False,0,0
Why it seems that jest does not detect scss?,"<p>I've been working for some days in a unit testing. It seems to work well but it shows some warnings about the scss that I don't know how to solve.
The component is this one:</p>
<pre><code>&lt;template&gt;
  &lt;div id=&quot;cb-nav-sidebar&quot;&gt;
    &lt;div class=&quot;project-name&quot;&gt;
      &lt;el-button
        :icon=&quot;'el-icon-s-' + (!isCollapsed ? 'fold' : 'unfold')&quot;
        type=&quot;text&quot;
        @click=&quot;toggle&quot;
      /&gt;
      &lt;h5 v-show=&quot;!isCollapsed&quot; class=&quot;bold&quot;&gt;{{ project.name }}&lt;/h5&gt;
    &lt;/div&gt;

    &lt;NavSidebarMenu
      position=&quot;top&quot;
      :items=&quot;menuTop&quot;
      :is-collapsed=&quot;isCollapsed&quot;
    &gt;&lt;/NavSidebarMenu&gt;
    &lt;NavSidebarMenu
      position=&quot;bottom&quot;
      :items=&quot;menuBottom&quot;
      :is-collapsed=&quot;isCollapsed&quot;
    &gt;&lt;/NavSidebarMenu&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script lang=&quot;ts&quot; setup&gt;
import { useI18n } from 'vue-i18n'
import { computed } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import NavSidebarMenu from '@/components/NavSidebarMenu.vue'
import { NavSidebarMenuItems } from '@/models/NavSidebarMenu'
import { PROCESS_ENV } from '@/utils/legacy/process-env'
import { getCurrentOrganization, Organizations } from '@/models/Organizations'

const { t } = useI18n({})
const MENU_ITEMS_TOP = [
  {
    label: 'analysis',
    icon: 'el-icon-s-data',
    path: '/analysis/',
    external: false,
  },
  {
    label: 'compare',
    icon: 'el-icon-copy-document',
    path: '/benchmark/',
    external: true,
  },
  {
    label: 'discovery',
    icon: 'el-icon-discover',
    path: '/discovery/',
    external: false,
  },
  {
    label: 'map',
    icon: 'el-icon-location-information',
    path: '/map/',
    external: true,
  },
]

const MENU_ITEMS_BOTTOM = [
  {
    label: 'categorize',
    icon: 'el-icon-s-operation',
    path: '/categorize/',
    external: true,
  },
  {
    label: 'settings',
    icon: 'el-icon-setting',
    path: '/project-settings/',
    external: true,
  },
  {
    label: 'export_data',
    icon: 'el-icon-download',
    path: '/export_data/export_data/export_csv',
    external: true,
  },
]
const store = useStore()
const route = useRoute()
let isCollapsed = false

// TODO: avoid duplicated code in TopNavBar.vue
const project = computed(() =&gt; {
  return store.getters['project/getCurrent']
})

const projectHasMap = computed(() =&gt; {
  const value = project.value
  return value.options['settings:has_map'] === '1'
})

const projectHasBenchmark = computed(() =&gt; {
  const value = project.value
  return value.datasets.length &gt; 4
})

const menuTop = computed(() =&gt; {
  return makeMenuItems(availableMenuItemsTop)
})

const menuBottom = computed(() =&gt; {
  return makeMenuItems(availableMenuItemsBottom)
})

const orgPath = computed(() =&gt; {
  const orgSlug = route.params.orgSlug
  const prjSlug = route.params.prjSlug
  return `/organization/${orgSlug}/project/${prjSlug}`
})

const externalOrgPath = computed(() =&gt; {
  const orgSlug = route.params.orgSlug
  const prjSlug = route.params.prjSlug
  return PROCESS_ENV.legacyUrl + `/organization/${orgSlug}/${prjSlug}`
})

function toggle() {
  // HACK: toggle disabled -&gt; todo layout width should change when menu is collapsed
  // this.isCollapsed = !this.isCollapsed
  isCollapsed = false
}

function makeMenuItems(items: NavSidebarMenuItems[]) {
  return items.map((item) =&gt; {
    const orgPathFinal = item.external ? externalOrgPath.value : orgPath.value

    return {
      ...item,
      label: t(`components.project_sidebar.menu.${item.label}`),
      section: item.path,
      path: `${orgPathFinal}${item.path}`,
    }
  })
}

function getAvailableMenuItemsTop() {
  const items: NavSidebarMenuItems[] = []
  MENU_ITEMS_TOP.forEach((item: any) =&gt; {
    if (item.label === 'map' &amp;&amp; !projectHasMap.value) {
      return
    }
    if (item.label === 'compare' &amp;&amp; !projectHasBenchmark.value) {
      return
    }

    items.push(item)
  })
  return items
}

function getAvailableMenuItemsBottom() {
  const items: NavSidebarMenuItems[] = []

  const organizations: Organizations = route?.meta
    ?.organizations as Organizations
  const organization = getCurrentOrganization(
    organizations,
    route.params.orgSlug as string
  )
  const userRole = organization.role

  MENU_ITEMS_BOTTOM.forEach((item: any) =&gt; {
    if (
      (item.label === 'categorize' || item.label === 'settings') &amp;&amp;
      userRole === 'viewer'
    ) {
      return
    }
    items.push(item)
  })
  return items
}

const availableMenuItemsTop = getAvailableMenuItemsTop()
const availableMenuItemsBottom = getAvailableMenuItemsBottom()
&lt;/script&gt;

&lt;style lang=&quot;scss&quot;&gt;
#cb-nav-sidebar {
  overflow: hidden;
  height: calc(100vh - 76px);
  display: flex;
  flex-direction: column;
  .project-name {
    padding: 1.3px 10px;
    display: flex;
    align-items: center;
    border-bottom: 1px solid var(--color-tertiary-400);

    h5 {
      font-size: var(--font-size--body);
      font-family: 'Roboto-Bold';
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    button {
      display: flex;
      margin-right: 8px;
      i {
        padding-left: 4px;
        font-size: var(--font-size--headline);
        color: var(--color-primary-800);
      }
    }
  }
}
&lt;/style&gt;
</code></pre>
<p>While the test is the following:</p>
<pre><code>import { render } from '@tests/app-test-utils'
import '@testing-library/jest-dom'

/* eslint @typescript-eslint/no-var-requires: &quot;off&quot; */
let mockStoreCommit: jest.Mock
const renderComponent = (getters: any) =&gt; {
  const ProjectNavSidebar = require('./ProjectNavSidebar.vue').default

  jest.mock('vuex', () =&gt; ({
    ...jest.requireActual('vuex'),
    useStore: () =&gt; ({
      getters: getters,
      commit: mockStoreCommit,
    }),
  }))

  jest.mock('vue-router', () =&gt; ({
    useRoute: () =&gt; ({
      params: {
        orgSlug: 'test',
      },
      meta: {
        organizations: [{ slug: 'test' }, { slug: 'test2' }],
      },
    }),
  }))

  render(
    ProjectNavSidebar,
    {},
    {
      props: {
        type: 'categories',
        menuType: 'checkbox',
        items: [
          {
            box_templates: '',
            id: '1',
            name: 'Culture',
          },
          {
            box_templates: '',
            id: '2',
            name: 'Economy',
          },
          {
            box_templates: '',
            id: '3',
            name: 'Education',
          },
        ],
      },
    }
  )
}

describe('NavSidebarMenu', () =&gt; {
  beforeEach(() =&gt; {
    jest.resetModules()
  })
  it('renders', () =&gt; {
    renderComponent({
      ['project/getCurrent']: {
        options: { 'setting:has_map': '1' },
        datasets: ['dataset_1', 'dataset_2', 'dataset_3'],
      },
    })
  })
})
</code></pre>
<p>The error that appears when testing:</p>
<pre><code>console.warn
    [Vue warn]: resolveComponent can only be used in render() or setup().

      185 |   overflow: hidden;
      186 |   height: calc(100vh - 76px);
    &gt; 187 |   display: flex;
          |                                     ^
      188 |   flex-direction: column;
      189 |   .project-name {
      190 |     padding: 1.3px 10px;

      at warn (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6799:17)
      at resolveAsset (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5515:9)
      at resolveComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5463:12)
      at Proxy.render (src/components/project/ProjectNavSidebar.vue:187:59)
      at renderComponentRoot (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:754:44)
      at ReactiveEffect.componentUpdateFn [as fn] (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4469:57)
      at ReactiveEffect.run (node_modules/@vue/reactivity/dist/reactivity.cjs.js:164:29)

  console.warn
    [Vue warn]: withDirectives can only be used inside render functions.

      193 |     border-bottom: 1px solid var(--color-tertiary-400);
      194 |
    &gt; 195 |     h5 {
          |         ^
      196 |       font-size: var(--font-size--body);
      197 |       font-family: 'Roboto-Bold';
      198 |       white-space: nowrap;

      at warn (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6799:17)
      at withDirectives (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:3291:9)
      at Proxy.render (src/components/project/ProjectNavSidebar.vue:195:38)
      at renderComponentRoot (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:754:44)
      at ReactiveEffect.componentUpdateFn [as fn] (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4469:57)
      at ReactiveEffect.run (node_modules/@vue/reactivity/dist/reactivity.cjs.js:164:29)
      at setupRenderEffect (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4595:9)

  console.warn
    [Vue warn]: resolveComponent can only be used in render() or setup().

      57 |   height: 100%;
      58 |   &amp;.el-menu {
    &gt; 59 |     .el-menu-item {
         |                                                  ^
      60 |       text-align: left;
      61 |     }
      62 |   }

      at warn (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6799:17)
      at resolveAsset (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5515:9)
      at resolveComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5463:12)
      at Proxy.render (src/components/NavSidebarMenu.vue:59:62)
      at renderComponentRoot (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:754:44)
      at ReactiveEffect.componentUpdateFn [as fn] (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4469:57)
      at ReactiveEffect.run (node_modules/@vue/reactivity/dist/reactivity.cjs.js:164:29)

  console.warn
    [Vue warn]: resolveComponent can only be used in render() or setup().

      58 |   &amp;.el-menu {
      59 |     .el-menu-item {
    &gt; 60 |       text-align: left;
         |                                                      ^
      61 |     }
      62 |   }
      63 |   &amp;.el-menu--collapse {

      at warn (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6799:17)
      at resolveAsset (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5515:9)
      at resolveComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5463:12)
      at Proxy.render (src/components/NavSidebarMenu.vue:60:57)
      at renderComponentRoot (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:754:44)
      at ReactiveEffect.componentUpdateFn [as fn] (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4469:57)
      at ReactiveEffect.run (node_modules/@vue/reactivity/dist/reactivity.cjs.js:164:29)

  console.warn
    [Vue warn]: Invalid VNode type: Symbol(Fragment) (symbol) 
      at &lt;Anonymous position=&quot;top&quot; items= [
      {
        label: 'components.project_sidebar.menu.analysis',
        icon: 'el-icon-s-data',
        path: '/organization/test/project/undefined/analysis/',
        external: false,
        section: '/analysis/'
      },
      {
        label: 'components.project_sidebar.menu.discovery',
        icon: 'el-icon-discover',
        path: '/organization/test/project/undefined/discovery/',
        external: false,
        section: '/discovery/'
      }
    ] is-collapsed=false &gt; 
      at &lt;Anonymous type=&quot;categories&quot; menuType=&quot;checkbox&quot; items= [
      { box_templates: '', id: '1', name: 'Culture' },
      { box_templates: '', id: '2', name: 'Economy' },
      { box_templates: '', id: '3', name: 'Education' }
    ]  ... &gt; 
      at &lt;VTUROOT&gt;

      at warn (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6799:17)
      at patch (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:3951:21)
      at mountChildren (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4127:13)
      at mountElement (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4037:17)
      at processElement (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4019:13)
      at patch (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:3939:21)
      at ReactiveEffect.componentUpdateFn [as fn] (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4476:21)

  console.warn
    [Vue warn]: resolveComponent can only be used in render() or setup().

      57 |   height: 100%;
      58 |   &amp;.el-menu {
    &gt; 59 |     .el-menu-item {
         |                                                  ^
      60 |       text-align: left;
      61 |     }
      62 |   }

      at warn (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6799:17)
      at resolveAsset (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5515:9)
      at resolveComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5463:12)
      at Proxy.render (src/components/NavSidebarMenu.vue:59:62)
      at renderComponentRoot (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:754:44)
      at ReactiveEffect.componentUpdateFn [as fn] (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4469:57)
      at ReactiveEffect.run (node_modules/@vue/reactivity/dist/reactivity.cjs.js:164:29)

  console.warn
    [Vue warn]: resolveComponent can only be used in render() or setup().

      58 |   &amp;.el-menu {
      59 |     .el-menu-item {
    &gt; 60 |       text-align: left;
         |                                                      ^
      61 |     }
      62 |   }
      63 |   &amp;.el-menu--collapse {

      at warn (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6799:17)
      at resolveAsset (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5515:9)
      at resolveComponent (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:5463:12)
      at Proxy.render (src/components/NavSidebarMenu.vue:60:57)
      at renderComponentRoot (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:754:44)
      at ReactiveEffect.componentUpdateFn [as fn] (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4469:57)
      at ReactiveEffect.run (node_modules/@vue/reactivity/dist/reactivity.cjs.js:164:29)

  console.warn
    [Vue warn]: Invalid VNode type: Symbol(Fragment) (symbol) 
      at &lt;Anonymous position=&quot;bottom&quot; items= [
      {
        label: 'components.project_sidebar.menu.categorize',
        icon: 'el-icon-s-operation',
        path: 'http://localhost:8000/organization/test/undefined/categorize/',
        external: true,
        section: '/categorize/'
      },
      {
        label: 'components.project_sidebar.menu.settings',
        icon: 'el-icon-setting',
        path: 'http://localhost:8000/organization/test/undefined/project-settings/',
        external: true,
        section: '/project-settings/'
      },
      {
        label: 'components.project_sidebar.menu.export_data',
        icon: 'el-icon-download',
        path: 'http://localhost:8000/organization/test/undefined/export_data/export_data/export_csv',
        external: true,
        section: '/export_data/export_data/export_csv'
      }
    ] is-collapsed=false &gt; 
      at &lt;Anonymous type=&quot;categories&quot; menuType=&quot;checkbox&quot; items= [
      { box_templates: '', id: '1', name: 'Culture' },
      { box_templates: '', id: '2', name: 'Economy' },
      { box_templates: '', id: '3', name: 'Education' }
    ]  ... &gt; 
      at &lt;VTUROOT&gt;

      at warn (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:6799:17)
      at patch (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:3951:21)
      at mountChildren (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4127:13)
      at mountElement (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4037:17)
      at processElement (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4019:13)
      at patch (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:3939:21)
      at ReactiveEffect.componentUpdateFn [as fn] (node_modules/@vue/runtime-core/dist/runtime-core.cjs.js:4476:21)
</code></pre>
<p>Taking into account the logs, it seems like jest does not detect very well the scss part. It is related to how jest is configurated?</p>
<p>Here the jest.config:</p>
<pre><code>module.exports = {
  transform: {
    '^.+\\.(ts)$': 'ts-jest',
    '^.+\\.vue$': 'vue3-jest',
    '\\.[jt]sx?$': 'babel-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|svg|ttf|woff|woff2|webp)$':
      'jest-transform-stub',
  },
  transformIgnorePatterns: ['/node_modules/(?!vue-awesome)'],
  moduleNameMapper: {
    '^@/(.*)$': '&lt;rootDir&gt;/src/$1',
    '^@tests/(.*)$': '&lt;rootDir&gt;/tests/$1',
  },
  moduleFileExtensions: ['js', 'ts', 'vue', 'json'],
  collectCoverage: true,
  collectCoverageFrom: [
    '&lt;rootDir&gt;/components/**/*.vue',
    '&lt;rootDir&gt;/pages/**/*.vue',
  ],
  testEnvironment: 'jsdom',
  setupFiles: ['&lt;rootDir&gt;/tests/setup.js'],
  testPathIgnorePatterns: ['tests'],
  globalSetup: '&lt;rootDir&gt;/tests/global-setup.js',
}
</code></pre>
<p>Thanks!</p>
",https://stackoverflow.com/questions/72619899/why-it-seems-that-jest-does-not-detect-scss,"['vue.js', 'unit-testing', 'jestjs', 'testing-library']",151,False,0,0
"How to unit test, nodes code in aws serverless with layers? jenkins and cicd issue","<p>I've tried code using local</p>
<p>Like</p>
<p>const data = require(&quot;../layers/utils/utils.js&quot;);</p>
<p>but when it's on the aws lambda
it should be like this
const data = require(&quot;/opt/util/util.js);</p>
<p>unit test on jenkins is failing, because he can't check the file location of /opt/
which is understandable,</p>
<p>is there some third party packages that has to simulate or stub the layers in order to replicated the layers on aws</p>
<p>as my sinon unit testing isn't working.</p>
",https://stackoverflow.com/questions/74156208/how-to-unit-test-nodes-code-in-aws-serverless-with-layers-jenkins-and-cicd-iss,"['node.js', 'jenkins', 'serverless', 'aws-lambda-layers', 'sinon-chai']",34,False,0,0
Configuration errors in Karma Jasmine when using with esnext,"<p>I am very new to unit testing and trying to configure Karma for testing a typescript project. In karma.config.ts when I try adding my <code>tsconfig</code> settings, I get following error:</p>
<blockquote>
<p>Object literal may only specify known properties, and 'karmaTypescriptConfig' does not exist in type 'ConfigOptions'.</p>
</blockquote>
<p>When I don't add this, the test runs but looks like by default karma expects <code>CommonJs</code> instead of <code>esnext</code> and shows so many compile time errors.</p>
<p>Here is my Karma.config.ts file:</p>
<pre><code>import * as karma from 'karma';

module.exports = function (config: karma.Config) {
 config.set({
  basePath: '',

  frameworks: ['jasmine', 'karma-typescript'],

  plugins: [
   require('karma-jasmine'),
   require('karma-chrome-launcher'),
   require('karma-jasmine-html-reporter'),
   require('karma-coverage'),
   require('karma-typescript'),
  ],

  files: [
  {
    pattern: 'util/**/*.ts',
    included: true,
    type: 'js',
  },
 ],

 // ERROR HERE
 karmaTypescriptConfig: {
  compilerOptions: {
      module: &quot;ESNext&quot;
  },
  tsconfig: &quot;./tsconfig.json&quot;,
 },

 // list of files / patterns to exclude
 exclude: [],

 preprocessors: {
  'util/**/*.ts': 'karma-typescript',
 },

 reporters: ['progress', 'karma-typescript'],
 port: 9876,
 colors: true,
 logLevel: config.LOG_INFO,
 autoWatch: true,
 browsers: ['ChromeHeadless'],
 singleRun: false,
 concurrency: Infinity,
});
};
</code></pre>
<p>Here is tsconfig.json:</p>
<pre><code> {
  &quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;esnext&quot;,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;lib&quot;: [
      &quot;esnext&quot;,
      &quot;esnext.asynciterable&quot;,
      &quot;dom&quot;
    ],
    ......
</code></pre>
",https://stackoverflow.com/questions/74595073/configuration-errors-in-karma-jasmine-when-using-with-esnext,"['typescript', 'unit-testing', 'karma-jasmine']",82,False,0,0
"Dependency injection in unit testing, xUnit","<p>This might be a stupid question, but I'm having one of those days.</p>
<p>I have a class called <code>JwtManager</code> and an interface called <code>IJwtManager</code>, I'm trying to inject the interface into a unit-testing class so I can test it but it doesn't work, the compiler gives me this message: <code>The following constructor parameters did not have matching fixture data: IJwtManager jwtManager</code>.</p>
<p>I think the problem is the compiler doesn't know what class should the interface be mapped to, but how can I write the equivalent of <code>services.AddScoped&lt;&gt;()</code> in a test class?</p>
<p>Code sample of test class:</p>
<pre><code>public class JwtManagerTests
{
    private readonly IJwtManager jwtManager;
    public JwtManagerTests(IJwtManager jwtManager)
    {
        this.jwtManager = jwtManager;
    }

    [Fact]
    public void Test_Something()
    {
        // Test here
    }
}
</code></pre>
",https://stackoverflow.com/questions/70884367/dependency-injection-in-unit-testing-xunit,"['c#', '.net', 'dependency-injection', 'xunit']",2419,True,2,1
How to run tests for a create-react-app written in Typescript?,"<p>I just started to write unit tests (jest) for my create-react-app project witten in Typescript and I'm having issues getting started.</p>
<p>I keep getting errors about: <code>SyntaxError: Cannot use import statement outside a module</code>.</p>
<p>Basically I ran <code>yarn jest --init</code> and did this configuration:</p>
<pre class=""lang-bash prettyprint-override""><code>√ Would you like to use Typescript for the configuration file? ... yes
√ Choose the test environment that will be used for testing » jsdom (browser-like)
√ Do you want Jest to add coverage reports? ... yes
√ Which provider should be used to instrument code for coverage? » babel
√ Automatically clear mock calls, instances and results before every test? ... yes
</code></pre>
<pre class=""lang-js prettyprint-override""><code>// jest.config.ts
export default {
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: &quot;coverage&quot;,
}
</code></pre>
<p>When I ran <code>yarn test</code> this is what I got:</p>
<pre class=""lang-bash prettyprint-override""><code>$ yarn test
yarn run v1.22.19
$ jest
 FAIL  tests/components/button.test.tsx
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default &quot;node_modules&quot; folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your &quot;node_modules&quot; files transformed, you can specify a custom &quot;transformIgnorePatterns&quot; in your config.
     • If you need a custom transformation specify a &quot;transform&quot; option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the &quot;moduleNameMapper&quot; config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    D:\my-project\tests\components\button.test.tsx:1
    ({&quot;Object.&lt;anonymous&gt;&quot;:function(module,exports,require,__dirname,__filename,jest){import { BUTTON_TYPE_CLASSES, getButton } from '../../src/components/button/button.component';
                                                                                      ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)

 PASS  tests/utils/delete.test.js
-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 | 
 delete.js |     100 |      100 |     100 |     100 | 
-----------|---------|----------|---------|---------|-------------------

Test Suites: 1 failed, 1 passed, 2 total
Tests:       3 passed, 3 total
Snapshots:   0 total
Time:        1.719 s, estimated 2 s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code></pre>
<p>The tests that pass all use Common JS syntax so there were no issues with them. But the tests I wrote for the button component is like this:</p>
<pre class=""lang-js prettyprint-override""><code>import { BUTTON_TYPE_CLASSES, getButton } from '../../src/components/button/button.component';
import { BaseButton, GoogleSignInButton, InvertedButton } from '../../src/components/button/button.styles';

describe('BUTTON COMPONENT', () =&gt; {
    it('returns base button', () =&gt; {
        expect(typeof getButton()).toEqual(typeof BaseButton);
    });
});
</code></pre>
<p>How do I start unit testing my React project written in Typescript?</p>
",https://stackoverflow.com/questions/74213298/how-to-run-tests-for-a-create-react-app-written-in-typescript,"['reactjs', 'typescript', 'unit-testing', 'jestjs']",1391,True,2,1
"Spring unit tests [webflux, cloud]","<p>I am new to the topic of unit testing and my question is whether I should perform the test as such of each line of code of a method or in what ways I can perform these tests to have a good coverage, if also, should exceptions be evaluated or not?</p>
<p>If for example I have this service method that also uses some helpers that communicate with other microservices, someone could give me examples of how to perform, thank you very much.</p>
<pre><code>public Mono&lt;BankAccountDto&gt; save(BankAccountDto bankAccount) {
  var count = findAccountsByCustomerId(bankAccount.getCustomerId()).count();

  var customerDto = webClientCustomer
        .findCustomerById(bankAccount.getCustomerId());
  var accountType = bankAccount.getAccountType();

  return customerDto
      .zipWith(count)
      .flatMap(tuple -&gt; {
        final CustomerDto custDto = tuple.getT1();
        final long sizeAccounts = tuple.getT2();
        final var customerType = custDto.getCustomerType();
        
        if (webClientCustomer.isCustomerAuthorized(customerType, accountType, sizeAccounts)) {
          return saveBankAccountAndRole(bankAccount);
        }
        return Mono.error(new Exception(&quot;.....&quot;));
      });

}
</code></pre>
<hr />
<h2>EDIT</h2>
<pre><code>public Mono&lt;BankAccountDto&gt; save(BankAccountDto bankAccount) {
    var count = findAccountsByCustomerId(bankAccount.getCustomerId()).count();

    var customerDto = webClientCustomer
            .findCustomerById(bankAccount.getCustomerId());

    return customerDto
            .zipWith(count)
            .flatMap(tuple -&gt; {
              final var customDto = tuple.getT1();
              final var sizeAccounts = tuple.getT2();
              final var accountType = bankAccount.getAccountType();

             // EDITED
              return webClientCustomer.isCustomerAuthorized(customDto, accountType, sizeAccounts)
                      .flatMap(isAuthorized -&gt; {
                        if (Boolean.TRUE.equals(isAuthorized)) {
                          return saveBankAccountAndRole(bankAccount);
                        }
                        return Mono.error(new Exception(&quot;No tiene permisos para registrar una cuenta bancaria&quot;));
                      });
            });

  }
</code></pre>
",https://stackoverflow.com/questions/70809602/spring-unit-tests-webflux-cloud,"['spring', 'mockito', 'spring-webflux', 'junit5']",67,True,2,1
Do I need Ubuntu to effectively develop Unittest Framework Tests for embedded C Projects?,"<p>I am trying to get started developing unittests for my embedded system, actually its a firmware that was already developed a while ago, now we want to add CI to it and start this by writing unittests.</p>
<p>I read blogs like
<a href=""https://dmitryfrank.com/articles/unit_testing_embedded_c_applications"" rel=""nofollow noreferrer"">https://dmitryfrank.com/articles/unit_testing_embedded_c_applications</a>
or <a href=""https://interrupt.memfault.com/blog/unit-testing-basics"" rel=""nofollow noreferrer"">https://interrupt.memfault.com/blog/unit-testing-basics</a> and they recommend to implement the unittests via a unittest framework as unity, cpputest and so on and so on. I tried to figure out how to make this run on my windows machine that I use at work but it seems tedious and prone to problems etc.
I also tried to start working with the microsoft vs unit testing framework but got discouraged after running into problems here, too. I think this can't be so hard, it shouldn't take so much effort to start writing the first littlest test...</p>
<p>Do you have experience with this and what would you recommend? Is it viable to do this on Windows? Should I push my boss to let me use a VM, WSL or a Machine that runs Ubuntu? In the end I would like to transfer the CI System to a lab pc (edit: this pc would then also be connected to the hardware, flash it, maybe run a debug build on it and compile some answers that it gets from the hardware... but now I want to talk about the unit test), so if I start developing on Ubuntu now, I will have to deal with this lateron, too...</p>
<p>Maybe a lot of thoughts but I feel a bit overwhelmed with the problem and don't know how to start.
Thanks for you replies, people!</p>
<p>Edit: The discussion I am looking for is not about whether unit testing for embedded systems is useful or the right approach (also interesting but I would like to seperate it) . It's about the question whether it can be fully developed under Windows or whether a Linux System is necessary to be efficient.</p>
",https://stackoverflow.com/questions/70681833/do-i-need-ubuntu-to-effectively-develop-unittest-framework-tests-for-embedded-c,"['c', 'linux', 'unit-testing']",83,False,1,0
Xunit.net: Validating model returned by an async ASP.NET method,"<p><a href=""https://i.stack.imgur.com/puhqw.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/puhqw.png"" alt=""enter image description here"" /></a>I have been writing unit testing for the API. I need to check whether values inside the model returned by the action method are expected or not.</p>
<pre class=""lang-cs prettyprint-override""><code>[Fact]
public async Task MerchantController_GetMGetProductByMerchantId_Merchant()
{
    //Arrange
    var merchantId = 1000;
    var merchant = new Merchant
    {
        MerchantId = merchantId,
        MerchantEmail = &quot;akhil@gmail.com&quot;,
        MerchantName=&quot;akhil&quot;,
        MerchantPassword=&quot;12345&quot;,
        ConfirmPassword=&quot;12345&quot;,
    };
    A.CallTo(() =&gt; _merchantRepository.GetMerchantByID(1000)).Returns(merchant);
    var MerchantController = new MerchantController(_merchantRepository);

    //Act
    var result = MerchantController.GetMerchant(merchantId);

    //Assert
    result.Should()
          .BeOfType&lt;Task&lt;ActionResult&lt;Merchant&gt;&gt;&gt;();
   
    Assert.True(merchant.Equals(result));
}
</code></pre>
<p>How can I check <code>result.MerchantEmail</code> and akhil@gmail.com are equal in the assert.</p>
<p>controller with the action method <code>GetMerchant</code></p>
<pre class=""lang-cs prettyprint-override""><code>[HttpGet(&quot;{id}&quot;)]
public async Task&lt;ActionResult&lt;Merchant&gt;&gt; GetMerchant(int id)
{
    try
    {
        return await _repository.GetMerchantByID(id);
    }
    catch
    {
        return NotFound();
    }
}
</code></pre>
<p>Repository for the 'GetMerchantByID'</p>
<pre class=""lang-cs prettyprint-override""><code>public async Task&lt;Merchant&gt; GetMerchantByID(int MerchantId)
{
    return await _context.Merchants.FindAsync(MerchantId);
}
</code></pre>
<p>I need to check the value contained in the merchant model and how I can do it.
Merchant model</p>
<pre class=""lang-cs prettyprint-override""><code>public class Merchant
{
    [Key]
    public int MerchantId { get; set; }

    [Required(ErrorMessage = &quot;Field can't be empty&quot;)]
    [DataType(DataType.EmailAddress, ErrorMessage = &quot;E-mail is not valid&quot;)]
    public string? MerchantEmail { get; set; }

    public string? MerchantName { get; set; }

    [DataType(DataType.PhoneNumber)]
    [Display(Name = &quot;Phone Number&quot;)]

    public string? MerchantPhoneNumber { get; set; }
    [Display(Name = &quot;Please enter password&quot;), MaxLength(20)]
    public string? MerchantPassword { get; set; }
    [NotMapped]

    [Display(Name = &quot;ConfirmPassword&quot;)]
    [Compare(&quot;MerchantPassword&quot;, ErrorMessage = &quot;Passwords don not match&quot;)]
    public string? ConfirmPassword { get; set; }
}
</code></pre>
<p>can someone help me to find a way if it is possible or suggest some resources</p>
",https://stackoverflow.com/questions/73726304/xunit-net-validating-model-returned-by-an-async-asp-net-method,"['asp.net-web-api', 'xunit.net', 'fluent-assertions', 'fakeiteasy']",65,True,1,2
Spring Boot + Flyway + Testcontainers(mariaDB): Table &quot;xxxx&quot; doesn&#39;t exist,"<p>I use Testcontainers with mariaDB database in a Spring Boot project for unit testing. I recently upgraded Spring Boot from 2.4.4 to 2.6.6 and found out that the unit test started to fail. The Testcontainers was created again (?) after the Flyway migration  happened (which created the database schema).</p>
<p>I am slightly confused and wonder whether there are specific configuration that needs to be set to make the unit test work again.</p>
<p>Dependencies are as below</p>
<pre><code>plugins {
    ...
    id 'org.springframework.boot' version '2.6.6'
    id &quot;org.flywaydb.flyway&quot; version &quot;8.4.2&quot;
    ...
}

dependencies {
    ...
    testCompileOnly 'junit:junit:4.13.2'
    testRuntimeOnly 'org.junit.vintage:junit-vintage-engine:5.8.2'
    implementation  &quot;org.flywaydb:flyway-core:8.1.0&quot;
    implementation 'org.mariadb.jdbc:mariadb-java-client:3.0.4'
    implementation &quot;org.jooq:jooq:3.16.5&quot;
    testImplementation &quot;org.testcontainers:mariadb:1.16.2&quot;
    ....
</code></pre>
<p>Configuration is as below</p>
<pre><code>spring.datasource.url=jdbc:tc:mariadb:10.5:///
spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver
spring.datasource.username=&quot;&quot;
spring.datasource.password=&quot;&quot;

spring.jooq.sql-dialect=MARIADB

spring.flyway.enabled=true
spring.flyway.locations=filesystem:./src/main/resources/db/migration
spring.flyway.url=jdbc:tc:mariadb:10.5:///
spring.flyway.baseline-on-migrate=true

# logging
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
</code></pre>
<p>Log message is as below</p>
<pre><code>INFO 49309 --- [    Test worker] c.a.a.m.r.MyUnitTest   : Starting MyUnitTest using Java 11.0.11 on xxxxxxx with PID 49309 (started by user.name in /Volumes/code/sample/sample)
INFO 49309 --- [    Test worker] c.a.a.m.r.MyUnitTest   : The following 1 profile is active: &quot;test&quot;
INFO 49309 --- [    Test worker] trationDelegate$BeanPostProcessorChecker : Bean 'io.opentracing.contrib.spring.cloud.async.DefaultAsyncAutoConfiguration' of type [io.opentracing.contrib.spring.cloud.async.DefaultAsyncAutoConfiguration$$EnhancerBySpringCGLIB$$3e8860ae] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
WARN 49309 --- [    Test worker] i.o.c.s.t.c.TracerAutoConfiguration      : Tracer bean is not configured! Switching to NoopTracer
INFO 49309 --- [    Test worker] o.c.s.w.s.ServerTracingAutoConfiguration : Creating WebMvcConfigurer bean with class io.opentracing.contrib.spring.web.interceptor.TracingHandlerInterceptor
INFO 49309 --- [    Test worker] o.t.utility.ImageNameSubstitutor         : Image name substitution will be performed by: DefaultImageNameSubstitutor (composite of 'ConfigurationFileImageNameSubstitutor' and 'PrefixingImageNameSubstitutor')
INFO 49309 --- [    Test worker] o.t.d.DockerClientProviderStrategy       : Loaded org.testcontainers.dockerclient.UnixSocketClientProviderStrategy from ~/.testcontainers.properties, will try it first
INFO 49309 --- [    Test worker] o.t.d.DockerClientProviderStrategy       : Found Docker environment with local Unix socket (unix:///var/run/docker.sock)
INFO 49309 --- [    Test worker] org.testcontainers.DockerClientFactory   : Docker host IP address is localhost
INFO 49309 --- [    Test worker] org.testcontainers.DockerClientFactory   : Connected to docker: 
  Server Version: 20.10.13
  API Version: 1.41
  Operating System: Docker Desktop
  Total Memory: 7859 MB
INFO 49309 --- [    Test worker] o.t.utility.RegistryAuthLocator          : Credential helper/store (docker-credential-desktop) does not have credentials for index.docker.io
2022-05-16 09:18:36.309  INFO 49309 --- [    Test worker] o.t.utility.RyukResourceReaper           : Ryuk started - will monitor and terminate Testcontainers containers on JVM exit
INFO 49309 --- [    Test worker] org.testcontainers.DockerClientFactory   : Checking the system...
INFO 49309 --- [    Test worker] org.testcontainers.DockerClientFactory   : ✔︎ Docker server version should be at least 1.6.0
INFO 49309 --- [    Test worker] org.testcontainers.DockerClientFactory   : ✔︎ Docker environment should have more than 2GB free disk space
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Creating container for image: mariadb:10.5
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Container mariadb:10.5 is starting: 57036754c74fbb2440acd1f1796bc5cc6b8e5ba3e303b73e53ed666ebee34b18
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Waiting for database connection to become available at jdbc:mariadb://localhost:51394/test using query 'SELECT 1'
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Container is started (JDBC URL: jdbc:mariadb://localhost:51394/test)
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Container mariadb:10.5 started in PT6.247538S
INFO 49309 --- [    Test worker] o.f.c.internal.license.VersionPrinter    : Flyway Community Edition 8.2.0 by Redgate
INFO 49309 --- [    Test worker] o.f.c.i.database.base.BaseDatabaseType   : Database: jdbc:mariadb://localhost:51394/test (MariaDB 10.5)
INFO 49309 --- [    Test worker] o.f.core.internal.command.DbClean        : Successfully dropped pre-schema database level objects (execution time 00:00.003s)
INFO 49309 --- [    Test worker] o.f.core.internal.command.DbClean        : Successfully cleaned schema `test` (execution time 00:00.013s)
INFO 49309 --- [    Test worker] o.f.core.internal.command.DbClean        : Successfully cleaned schema `test` (execution time 00:00.013s)
INFO 49309 --- [    Test worker] o.f.core.internal.command.DbClean        : Successfully dropped post-schema database level objects (execution time 00:00.002s)
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Creating container for image: mariadb:10.5
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Container mariadb:10.5 is starting: 1dfd0cd43d1d842ded36f12f7081fcaedc3768ff8dae2514a7ad8c3fba4a9bf6
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Waiting for database connection to become available at jdbc:mariadb://localhost:51457/test using query 'SELECT 1'
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Container is started (JDBC URL: jdbc:mariadb://localhost:51457/test)
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Container mariadb:10.5 started in PT6.413163S
INFO 49309 --- [    Test worker] o.f.c.internal.license.VersionPrinter    : Flyway Community Edition 8.2.0 by Redgate
INFO 49309 --- [    Test worker] o.f.core.internal.command.DbValidate     : Successfully validated 3 migrations (execution time 00:00.016s)
INFO 49309 --- [    Test worker] o.f.c.i.s.JdbcTableSchemaHistory         : Creating Schema History table `test`.`flyway_schema_history` ...
INFO 49309 --- [    Test worker] o.f.core.internal.command.DbMigrate      : Current version of schema `test`: &lt;&lt; Empty Schema &gt;&gt;
INFO 49309 --- [    Test worker] o.f.core.internal.command.DbMigrate      : Migrating schema `test` to version &quot;1.0 - create db schema&quot;
INFO 49309 --- [    Test worker] o.f.core.internal.command.DbMigrate      : Migrating schema `test` to version &quot;1.1 - remove bad entries&quot;
INFO 49309 --- [    Test worker] o.f.core.internal.command.DbMigrate      : Migrating schema `test` to version &quot;1.2 - remove old entries&quot;
INFO 49309 --- [    Test worker] o.f.core.internal.command.DbMigrate      : Successfully applied 3 migrations to schema `test`, now at version v1.2 (execution time 00:00.127s)
INFO 49309 --- [    Test worker] o.s.s.web.DefaultSecurityFilterChain     : Will not secure any request
INFO 49309 --- [    Test worker] org.eclipse.jetty.util.log               : Logging initialized @20593ms to org.eclipse.jetty.util.log.Slf4jLog
INFO 49309 --- [    Test worker] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Creating container for image: mariadb:10.5
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Container mariadb:10.5 is starting: 51aa6eb7e010bddd69d9e906cbc97cff242bd46a3d85a9d08dc1b85e6a35b70a
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Waiting for database connection to become available at jdbc:mariadb://localhost:51525/test using query 'SELECT 1'
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Container is started (JDBC URL: jdbc:mariadb://localhost:51525/test)
INFO 49309 --- [    Test worker] 🐳 [mariadb:10.5]                        : Container mariadb:10.5 started in PT6.344117S
INFO 49309 --- [    Test worker] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
INFO 49309 --- [    Test worker] o.s.b.a.h2.H2ConsoleAutoConfiguration    : H2 console available at '/h2'. Database available at 'jdbc:mariadb://localhost:51525/test?user=test&amp;password=***'
INFO 49309 --- [    Test worker] o.c.s.w.s.ServerTracingAutoConfiguration : Creating FilterRegistrationBean bean with TracingFilter mapped to [], skip pattern is &quot;/api-docs.*|/swagger.*|.*\.png|.*\.css|.*\.js|.*\.html|/favicon.ico|/hystrix.stream|/actuator/(health|health/.*)&quot;
INFO 49309 --- [    Test worker] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint(s) beneath base path '/actuator'
INFO 49309 --- [    Test worker] c.a.a.m.r.MyUnitTest   : Started MyUnitTest in 27.52 seconds (JVM running for 28.705)
INFO 49309 --- [    Test worker] o.s.t.c.transaction.TransactionContext   : Began transaction (1) for test context [DefaultTestContext@6b41f56a testClass = MyUnitTest, testInstance = com.demo.sample.process.repository.MyUnitTest@55c989d7, testMethod = testProcess@MyUnitTest, testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@6b04eb82 testClass = MyUnitTest, locations = '{}', classes = '{class com.demo.sample.sampleApplication, class com.demo.sample.process.config.TestAppConfig}', contextInitializerClasses = '[]', activeProfiles = '{test}', propertySourceLocations = '{classpath:application-integration.properties}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.autoconfigure.actuate.metrics.MetricsExportContextCustomizerFactory$DisableMetricExportContextCustomizer@775b1965, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@121f6d87, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@773ce2e2, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@4b69c0cb, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@411029bf, org.springframework.boot.test.context.SpringBootTestArgs@1, org.springframework.boot.test.context.SpringBootTestWebEnvironment@7aa81bef], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -&gt; true, 'org.springframework.test.context.web.ServletTestExecutionListener.populatedRequestContextHolder' -&gt; true, 'org.springframework.test.context.web.ServletTestExecutionListener.resetRequestContextHolder' -&gt; true, 'org.springframework.test.context.event.ApplicationEventsTestExecutionListener.recordApplicationEvents' -&gt; false]]; transaction manager [org.springframework.jdbc.support.JdbcTransactionManager@2da8b79d]; rollback [true]
INFO 49309 --- [    Test worker] org.jooq.Constants                       : 
                                      
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@  @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@        @@@@@@@@@@
@@@@@@@@@@@@@@@@  @@  @@    @@@@@@@@@@
@@@@@@@@@@  @@@@  @@  @@    @@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@    @@  @@  @@@@  @@@@@@@@@@
@@@@@@@@@@    @@  @@  @@@@  @@@@@@@@@@
@@@@@@@@@@        @@  @  @  @@@@@@@@@@
@@@@@@@@@@        @@        @@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@  @@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  Thank you for using jOOQ 3.15.1
                                      
INFO 49309 --- [    Test worker] org.jooq.Constants                       : 

jOOQ tip of the day: While you don't have to use jOOQ's code generator, there are *lots* of awesome features you're missing out on if you're not using it!

WARN 49309 --- [    Test worker] o.m.jdbc.message.server.ErrorPacket      : Error: 1146-42S02: Table 'test.my_db_table' doesn't exist
</code></pre>
",https://stackoverflow.com/questions/72260495/spring-boot-flyway-testcontainersmariadb-table-xxxx-doesnt-exist,"['spring-boot', 'mariadb', 'junit4', 'flyway', 'testcontainers']",2945,True,4,1
Unit testing angular async promise,"<p>I have some hard times trying to resolve some unit testing. I succeed in testing the function if params.callType === 'inbound' but don't know how to test if params.calltype === &quot;something else&quot;. Here is the code I have to test:</p>
<pre><code>searchObject(params: ISearchObjectParams): Promise&lt;IScreenPopSearchObjectResult&gt; {
return new Promise((resolve, reject) =&gt; {
  let searchParams;
  if (params.searchValuesString) {
    searchParams = params.searchValuesString;
  } else {
    const quotedSearchValues = params &amp;&amp; params.searchValues &amp;&amp; params.searchValues.map(x =&gt; '&quot;' + x + '&quot;');
    searchParams = quotedSearchValues &amp;&amp; quotedSearchValues.join(' OR ');
  }
  if (params.callType === 'inbound') {
    sforce.opencti.searchAndScreenPop({
      searchParams: searchParams,
      queryParams: params.queryParams,
      callType: params.callType,
      deferred: true,
      callback: response =&gt; {
        if (response.success) {
          resolve(this.createSearchObjectResult(response));
        } else {
          reject(this.parseLightningError(response, LocaleKeys.searchObject));
        }
      }
    });
  }
});
</code></pre>
<p>Here is the unit test I made that <strong>is working</strong> for the <strong>&quot;if (params.callType === 'inbound').</strong></p>
<pre><code>it('should resolve with parsed search result', async () =&gt; {
      service.createSearchObjectResult = jasmine.createSpy().and.returnValue({});
      sforce.opencti.searchAndScreenPop = jasmine.createSpy().and.callFake((params: {
        callback: (response: { returnValue: { runApex: string }, success: boolean }) =&gt; void
      }) =&gt; {
        params.callback({ success: true } as any);
      });
      await expectAsync(service.searchObject({ searchValues: ['value1', 'value2'], callType: 'inbound' } as any)).toBeResolvedTo({} as any);
      testUtils.expectSingleCall(service.createSearchObjectResult, { success: true });
    });
</code></pre>
<p>I'm trying to make it for <strong>the else,</strong> but I can't succeed. This is what I tried for <strong>params.callType === &quot;outbound&quot;(that should be the else condition):</strong></p>
<pre><code>  it('should not resolve if is not inbound', async () =&gt; {
      sforce.opencti.searchAndScreenPop = jasmine.createSpy().and.callFake((params: {
        callback: (response: { returnValue: { runApex: string }, success: boolean }) =&gt; void
      }) =&gt; {
        params.callback({ success: false } as any);
      });
      await expectAsync(service.searchObject({ searchValuesString: 'value1&amp;&amp;value2', callType: 'inbound' } as any)).toBeRejected({} as any);
      testUtils.expectNotCalled(sforce.opencti.searchAndScreenPop);
      expect(sforce.opencti.searchAndScreenPop).not.toHaveBeenCalled();
    });
</code></pre>
<p>Suggestions please?</p>
",https://stackoverflow.com/questions/72733610/unit-testing-angular-async-promise,"['angular', 'unit-testing', 'async-await', 'promise', 'jasmine']",47,False,1,1
DataAnnotations Validator Class Not Replicating Implicit Required Check for Non-Nullable String,"<p>When using <code>DataAnnotations</code> to validate models for incoming controller requests, <a href=""https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-7.0#non-nullable-reference-types-and-required-attribute"" rel=""nofollow noreferrer"">non-nullable reference types are implicitly treated as required unless you declare them as nullable</a> (i.e. <code>string?</code> instead of <code>string</code>).</p>
<pre><code>public class MyExampleModel
{
    // Cannot be null! Equivalent to having [Required(AllowEmptyStrings = true)] on it
    public string PropertyName { get; set; } 

    // Allowed to be null! No validation errors occur.
    public string? OtherProp { get; set; } 
}
</code></pre>
<p>This behavior results in an expected validation error of <code>The PropertyName field is required</code> when hitting the endpoint via Postman / etc.</p>
<p>However, when using the <code>Validator</code> class in a unit testing scenario, this implicit check is not correctly reported when passing <code>null</code> for the <code>string PropertyName</code> property.</p>
<pre><code>using System.ComponentModel.DataAnnotations;
using FluentAssertions;
using Xunit;

namespace MyNamespace.Tests;

public class TestingValidationOfMyExampleModel
{
    [Fact]
    public void ShouldHaveErrorWhenPropertyNameIsNull()
    {
        var model = new MyExampleModel(); // model.PropertyName is null.

        var validationResults = new List&lt;ValidationResult&gt;();
        var validationContext = new ValidationContext(model, null, null);

        // No errors returned! validationResults remains empty.
        Validator.TryValidateObject(model, validationContext, validationResults, true);

        validationResults.Should().HaveCount(1); // Fails!
    }
}
</code></pre>
<p>Is there some way to configure the static <code>System.ComponentModel.DataAnnotations.Validator</code> class so that it also makes this implicit check?</p>
",https://stackoverflow.com/questions/74703398/dataannotations-validator-class-not-replicating-implicit-required-check-for-non,"['c#', '.net-6.0', 'data-annotations', 'requiredfieldvalidator', 'nullable-reference-types']",115,True,1,1
How to tell whether a python unittest subTest has failed as it&#39;s running?,"<p>Python docs <a href=""https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests"" rel=""nofollow noreferrer"">say</a> give this example of using a subTest in unit testing:</p>
<pre><code>import unittest

class NumbersTest(unittest.TestCase):

    def test_even(self):
        &quot;&quot;&quot;
        Test that numbers between 0 and 5 are all even.
        &quot;&quot;&quot;
        for i in range(0, 6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)
</code></pre>
<p>This runs all 5 tests (i=0..5) before producing output for all 5 failures.</p>
<p>How can I print about the failures along the way (say in the for loop after the with block)?</p>
<p>I only need the answer for Python 3.</p>
<p>In my test, I have thousands of subtests and it can take many minutes to finish.  I want to know if it's already failed as I'm watching it.</p>
",https://stackoverflow.com/questions/74803953/how-to-tell-whether-a-python-unittest-subtest-has-failed-as-its-running,"['python', 'python-unittest']",97,False,1,1
How to mock the mongoDB client in golang?,"<p>We have written generic method to connect the MongoDB in golang. Now we want to write the unit testing to mock the DB call. So we need mock the mongo.client.
In Python, we have pymongo lib to mock db call. Similarly do we have any lib in golang?
Or
Do we have any other option to avoid the DB call for unit test implementation?</p>
<pre><code>func RunQuery(collec string, filter bson.M, client *mongo.Client) (result []bson.M, err error) {
    collection := client.Database(&quot;TESTDB&quot;).Collection(collec)
    cur, err := collection.Find(ctx, filter)
}
</code></pre>
<p>I want to write a unit test for the method &quot;getuserdetails&quot;.</p>
<pre><code>func Test_getUserdetails(t *testing.T) {
  mt := mtest.New(t, mtest.NewOptions().ClientType(mtest.Mock))
  defer mt.Close()
  mt.Run(&quot;success&quot;, func(mt *mtest.T) {
    usercollection := mt.Coll
    getuserdetails(usercollection.Database().Client())
  })
}
</code></pre>
<p>Error:</p>
<p>Message: &quot;no responses remaining&quot;
Labels : NetworkError</p>
",https://stackoverflow.com/questions/74361914/how-to-mock-the-mongodb-client-in-golang,"['unit-testing', 'go', 'mocking']",1492,False,1,0
React Unit testing onClick event,"<p>I have a Button wrapper component in which I am using mui button. I want to do the unit testing for this button wrapper component. I wrote some code but for onClick test it is falling.</p>
<p><strong>index.tsx (ButtonWrapper Component)</strong></p>
<pre><code>    import React from 'react';
    import { Button } from '@material-ui/core';
    import { ButtonProps } from '../../../model';
    
    type ConfigButtonProps ={
      // variant?: string,
      // color?: string,
      // fullWidth?: boolean,
      // type?: string
    }
    
    export const ButtonWrapper = (props: ButtonProps) =&gt; {
      const {children, onSubmit, disabled, type, onClick,  ...otherprops} = props
      console.log(&quot;button&quot;, otherprops, type);
    
      const configButton:ConfigButtonProps = {
        variant: 'contained',
        color: 'primary',
        fullWidth: true,
        type: type
      }
    
      return (
        &lt;Button disabled={disabled} onClick={onSubmit} {...configButton}&gt;
          {children}
        &lt;/Button&gt;
      );
    };
</code></pre>
<p><strong>index.test.tsx (Button Wrapper test)</strong></p>
<pre><code>import { ButtonWrapper } from &quot;./index&quot;
import { fireEvent, render, screen } from &quot;@testing-library/react&quot;;
import { ButtonProps } from &quot;../../../model&quot;;


const makeSut = (props: ButtonProps) =&gt; {
  return render(&lt;ButtonWrapper onClick={jest.fn()} {...props} /&gt;);
};

describe(&quot;&lt;ButtonWrapper /&gt;&quot;, () =&gt; {

  test(&quot;Button renders correctly&quot;,()=&gt;{
    render(&lt;ButtonWrapper /&gt;)

    const buttonElem = screen.getByRole('button')
    expect(buttonElem).toBeInTheDocument()
  })

  test(&quot;Should call onClick successfully&quot;, () =&gt; {
    const spy = jest.fn();

    const { getByRole } = makeSut({ onClick: spy });

    fireEvent.click(getByRole('button'));

   expect(spy).toHaveBeenCalled();
  });
});
</code></pre>
<p><strong>FormContainer.tsx (Parent Container)</strong></p>
<pre><code>return (&lt;form onSubmit={event=&gt;this.onSubmit(event)}&gt;
            {/* &lt;div&gt;FormContainer {JSON.stringify(this.props.states, null, 2)}&lt;/div&gt; */}
               {this.state.fields.map((field,index)=&gt;{
                   return &lt;FormControl 
                    key={field.id}
                    fieldConfig={field}
                    focused={(event:React.ChangeEvent&lt;HTMLInputElement&gt;)=&gt;this.fieldBlur(event,field,index)} 
                    changed={(event:React.ChangeEvent&lt;HTMLInputElement&gt;)=&gt;this.fieldChange(event,field,index)} /&gt;
               })}
               &lt;ButtonWrapper type='submit'&gt;Submit&lt;/ButtonWrapper&gt;
           &lt;/form&gt;)
</code></pre>
<p><strong>Error</strong>
<a href=""https://i.stack.imgur.com/L1lY5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/L1lY5.png"" alt=""enter image description here"" /></a></p>
<p>I also want to know in order to make 90% test coverage what else I need to test ?</p>
<p>[![enter image description here]]</p>
<p>I tried this below mentioned code also but the last line fails.</p>
<pre><code> test(&quot;Should call onClick successfully&quot;, () =&gt; {
    const onSubmitHandler = jest.fn();
    render(&lt;ButtonWrapper onClick={onSubmitHandler} /&gt;)
    
    const buttonElement = screen.getByRole('button');
    user.click(buttonElement)
    expect(onSubmitHandler).toHaveBeenCalledTimes(1) //This line fails

  });
</code></pre>
",https://stackoverflow.com/questions/73972388/react-unit-testing-onclick-event,"['javascript', 'reactjs', 'unit-testing', 'jestjs']",466,False,1,1
How to mock function without class in Kotlin?,"<pre><code>fun add() {
    return 4+1;
}


class Calculator {
    fun MathUtils() {
        // do something
        // calls add() function
        val x: Int = add()

        // return something
        return x + 22
    }
}


class CalculatorTest {
    var c = Calculator()
    
    @Test
    fun MathUtilsSuccess() {
    Assertions.assertThat(
            c.MathUtils()
        ).isEqualTo(24)
    }
}
</code></pre>
<p>I am new to unit Testing, I want to know is there any way I can call <code>MathUtils()</code> function (inside Calculator class)</p>
<p>in <code>MathUtilsSuccess()</code> (inside CalculatorTest class) and i have to mock <code>add()</code> function which is not inside any class such that <code>add()</code> always returns 2, so that in success scenario my Test pass.</p>
<p>All the classes are in separate file and fun add() is also in separate file.</p>
<p>P.S : I have broken down my doubt into this simple example, This is not the actual problem i am working on.</p>
",https://stackoverflow.com/questions/71283136/how-to-mock-function-without-class-in-kotlin,"['java', 'kotlin', 'mockito', 'junit5', 'mockk']",5327,True,3,1
Can we declare PonyORM models without using a database global variable?,"<p>Declaring classes that map the db in ponyORM inherits from <code>database</code> as a global variable.</p>
<pre><code>from pony.orm import *

db = Database()

class MyEntity(db.Entity):
    attr1 = Required(str)
</code></pre>
<p>Is there a way to declare Entities without relying on a global variable?</p>
<p>Maybe something in the line of</p>
<pre><code>class MyEntity(get_db().Entity):
</code></pre>
<p>but with control over when the classes are declared so that get_db() returns the appropriate db.</p>
<p>--</p>
<p>We have a few situations in which this would be desirable.</p>
<ol>
<li>Mixing databases</li>
</ol>
<p><a href=""https://stackoverflow.com/questions/45848795/using-multiple-databases-with-pony-orm"">Using multiple databases with Pony ORM</a></p>
<p>This is the solution we have currently running. But having inner Classes is ugly, specially because there are a lot of them.</p>
<p>Maybe we could make them go to the global space with global? or import the models within this inner function?</p>
<ol start=""2"">
<li>unit testing</li>
</ol>
<p>Having a global variable causes errors in unit testing or makes it overly complicated because each setUp must check if the database is already bound, and ensure it is the right database.</p>
<ol start=""3"">
<li>mapping views</li>
</ol>
<p>We would like to map views as pony classes. Declare some ORM classes, generate the tables, create the views, declare the ORM view classes.</p>
<p>--</p>
<p>We took a look to other projects that also rely on global objects like flask or celery but we didn't find a solution that would apply to ponyORM.</p>
<p>Maybe it's just not possible and the database object has to be defined and that's it.</p>
",https://stackoverflow.com/questions/72017421/can-we-declare-ponyorm-models-without-using-a-database-global-variable,"['python', 'ponyorm']",51,False,1,0
"Unit test, second function call in callback","<p>I`m learning unit testing and have some difficulties.
In one application a function looks like this:</p>
<pre><code>function f1()
{
  s7client.ReadArea(s7client.S7AreaMK, 0, 0, 1, s7client.S7WLByte, function (err, buf) {
       if (err) {...}
       processBuffer(buf);
       setTimeout(() =&gt; { f1(); }, 100);}
  });
}
</code></pre>
<p>I could make a test for the first function call of f1 but i have difficulties to test the second f1 call after the setTimout.
My test so far:</p>
<pre><code>test('callback unit test', function() {
      const s7client = require('s7client');
      let testCallback = sinon.stub(s7client, 'ReadArea');

      testCallback.onCall(0).callsFake(function (area, dbNumber, start, amount, wordLen, cb) 
      {
           cb(false, exampleValue1);
      }); 

      //code

      testCallback.onCall(1).callsFake(function (area, dbNumber, start, amount, wordLen, cb) 
      {
           cb(false, exampleValue2);
      });
      
      //code
} 
</code></pre>
<p>I tried to call the stubed function on a second call but the function is never called with the second callback exampleValue2.</p>
<p>Is there something I`m doing wrong or do I have to consider something else?</p>
",https://stackoverflow.com/questions/73968705/unit-test-second-function-call-in-callback,"['javascript', 'mocha.js']",48,False,0,0
How to properly test a method in a class that calls a method from the same class with Junit and Mockito,"<p>I am fairly new to Unit testing.</p>
<p>I have a class with a few methods, and in one of them we call the result from one of the other methods from the same class, should we mock, or we should only mock while using methods from collaborators like other classes?</p>
<p><em>Code:</em></p>
<pre class=""lang-java prettyprint-override""><code>class UserServiceImpl implements UserService {

  UserReader reader = new UserReader(&quot;/path&quot;);
  AccountChecker check;

  public boolean userExists(String userName) {
    List&lt;User&gt; users = mappedUsers();
    for (User u : users) {
      if (u.getName().equals(userName)) {
        return true;
      }
    }
    return false;
  }

  public List&lt;User&gt; mappedUsers() {
    List&lt;String&gt; userList = reader.readUsers();
    List&lt;User&gt; users = new ArrayList&lt;&gt;();
    for (String u : userList) {
      userList.add(new User(u));
    }
    return userList;
  }

}
</code></pre>
<p>So the question is if I want to test the method <code>userExists()</code>, should I simply test the method without any mocks or try to mock the <code>mappedUsers()</code> method while testing the <code>userExists()</code> method?</p>
",https://stackoverflow.com/questions/73099050/how-to-properly-test-a-method-in-a-class-that-calls-a-method-from-the-same-class,"['java', 'unit-testing', 'junit', 'mockito']",427,False,0,0
Taking full Input dataset when testing transformations in Palantir Foundry,"<p>In Palantir Foundry, I could see that we can write unit tests using Pytest or TransformRunner. My understanding is that, with Pytest we cannot pass an output of transform for unit testing and in TransformRunner we cannot use the dataset that we have to use originally. We need some test data. But I would like to use the whole input dataset on which my transform should run in production and do run tests on the output of it. How can I achieve that?</p>
",https://stackoverflow.com/questions/70570164/taking-full-input-dataset-when-testing-transformations-in-palantir-foundry,"['unit-testing', 'pyspark', 'palantir-foundry']",604,False,0,1
OpenAPI Generator vs. CDC Testing with Pact,"<p>We're overhauling our frontend and backend service contract reliability and are investigating two tools/techniques that seem to conflict. Consumer and provider code generation from an OpenAPI Spec (OAS) with a tool like <a href=""https://openapi-generator.tech/"" rel=""nofollow noreferrer"">openapi generator</a> vs. consumer driven contract (CDC) testing with a tool like <a href=""https://pact.io/"" rel=""nofollow noreferrer"">pact</a>.</p>
<p><em><strong>OAS Code Generation</strong></em></p>
<p>OAS works great for generating the consumer code, and we're working on integrating provider-side generation to complete the contract confidence on both sides. As long as contract alterations start w/ the OAS and providers and consumers generate their code, is this a suitable strategy?</p>
<p><em><strong>Pact Unit Testing</strong></em></p>
<p>Pact CDC testing doesn't seem to involve an OAS at all, but instead programmatically builds contracts between the consumer and provider via unit testing. When using a pact broker, the addition of the <a href=""https://docs.pact.io/pact_broker/can_i_deploy"" rel=""nofollow noreferrer"">can-i-deploy</a> tool seems like a nice addition to a ci/cd pipeline. One nice thing w/ pact is that it appears to support kafka event mocking, which would be something openapi-generator doesn't cover.</p>
<p>If every service, front and back, is using OAS code generation, is pact useful? I could see it's utility in an environment without codegen, but otherwise starts to feel redundant/conflicting.</p>
<p>Thanks for any insight or anecdotes you can provide!</p>
",https://stackoverflow.com/questions/71931295/openapi-generator-vs-cdc-testing-with-pact,"['testing', 'microservices', 'openapi-generator', 'pact', 'reliability']",491,True,1,1
Use PHP Spectator/Spectator inside BDD Behat feature class,"<p>I am new BDD and I am using <a href=""https://docs.behat.org/en/latest/"" rel=""nofollow noreferrer"">Behat</a> to write some BDD tests. I was wondering if I can able to integrate <a href=""https://github.com/hotmeteor/spectator"" rel=""nofollow noreferrer"">Spectator/Spectator</a> to do api testing while using Behat. Spectator will read my swagger.json and do validation during api testing inside feature context class.</p>
<p>It seems like Spectator/Spectator has been meant to use inside php unit testing and won't work with Behat.</p>
<p>Has anyone used Spectator/Spectator inside Behat feature class to test their rest api?</p>
",https://stackoverflow.com/questions/72616157/use-php-spectator-spectator-inside-bdd-behat-feature-class,"['php', 'unit-testing', 'bdd', 'behat', 'spectator']",17,False,0,0
Unit test Axios POST/PUT/DELETE with Jest on ReactJS/Typescript,"<p>I'm trying to add unit testing to my <strong>axios API calls</strong>
the <code>.get</code> call was easy to do... but when it comes to the <strong>POST/PUT/DELETE</strong> calls, I can't make it work.</p>
<p>here's what I tried (for POST)</p>
<p>my test:</p>
<pre><code>const mockedAxios = axios as jest.Mocked&lt;typeof axios&gt;
...    
test ('addGrocery()', async () =&gt; {
            const newGrocery: IGrocery = {
                _id: &quot;1&quot;,
                name: &quot;Banana&quot;,
                quantity: 2,
                status: false,
            }
            const data = {
                message: &quot;Grocery added&quot;,
                grocery: newGrocery,
                groceries: [
                    {
                        _id: &quot;1&quot;,
                        name: &quot;Banana&quot;,
                        quantity: 2,
                        status: false,
                    },
                    {
                        _id: &quot;2&quot;,
                        name: &quot;Strawberry&quot;,
                        quantity: 1,
                        status: true,
                    }
                ]
            }
    
            mockedAxios.post.mockImplementationOnce(() =&gt; Promise.resolve(data))
    
            await expect(addGrocery(newGrocery)).resolves.toEqual(data)
            expect(axios.post).toHaveBeenCalled()
        })
</code></pre>
<p>my API call:</p>
<pre><code>export const addGrocery = async (formData: IGrocery): Promise&lt;AxiosResponse&lt;ApiDataType&gt;&gt; =&gt; {
    try {
        const grocery: Omit&lt;IGrocery, &quot;_id&quot;&gt; = {
            name: formData.name,
            quantity: formData.quantity,
            status: false,
        }
        const apiUrl = baseUrl + '/add-grocery'
        const saveGrocery: AxiosResponse&lt;ApiDataType&gt; = await axios.request({
            method: 'POST',
            url: apiUrl,
            params: grocery
        })
        
        return saveGrocery
    } catch (error: any) {
        throw new Error(error)
    }
}
</code></pre>
<p>and the controller:</p>
<pre><code>const addGrocery = async (req: Request, res: Response): Promise&lt;void&gt; =&gt; {
    try {
        const query = req.query as unknown as Pick&lt;IGrocery, &quot;name&quot; | &quot;quantity&quot; | &quot;status&quot;&gt;
        
        const grocery: IGrocery = new Grocery({
            name: query.name,
            quantity: query.quantity,
            status: query.status,
        })

        const newGrocery: IGrocery = await grocery.save()
        const allGroceries: IGrocery[] = await Grocery.find()

        res.status(201).json({
            message: &quot;Grocery added&quot;,
            grocery: newGrocery,
            groceries: allGroceries
        })
    } catch (error) {
        throw error
    }
}
</code></pre>
<p>I did a lot of research, pretty much everything I could find was only for the <code>.get</code> call, sometimes something just saying &quot;change the <code>mockeAxios.get</code> to <code>mockedAxios.post</code>&quot; (which is what I tried), but didn't work.</p>
<p>Getting the following error:</p>
<pre><code> FAIL  src/__tests__/API.test.tsx (16.851 s)
  API tests
    √ getGroceries() (6 ms)
    × addGrocery() (5 ms)

  ● API tests › addGrocery()

    expect(received).resolves.toEqual(expected) // deep equality

    Expected: {&quot;groceries&quot;: [{&quot;_id&quot;: &quot;1&quot;, &quot;name&quot;: &quot;Banana&quot;, &quot;quantity&quot;: 2, &quot;status&quot;: false}, {&quot;_id&quot;: &quot;2&quot;, &quot;name&quot;: &quot;Strawberry&quot;, &quot;quantity&quot;: 1, &quot;status&quot;: true}], &quot;grocery&quot;: {&quot;_id&quot;: &quot;1&quot;, &quot;name&quot;: &quot;Banana&quot;, &quot;quantity&quot;: 2, &quot;status&quot;: false}, &quot;message&quot;: &quot;Grocery added&quot;}
    Received: undefined

      59 |         mockedAxios.post.mockImplementationOnce(() =&gt; Promise.resolve(data))
      60 |
    &gt; 61 |         await expect(addGrocery(newGrocery)).resolves.toEqual(data)
         |                                                       ^
      62 |         expect(axios.post).toHaveBeenCalled()
      63 |     })
      64 | })
</code></pre>
",https://stackoverflow.com/questions/71235719/unit-test-axios-post-put-delete-with-jest-on-reactjs-typescript,"['reactjs', 'typescript', 'unit-testing', 'axios', 'jestjs']",753,False,0,0
pytest-django django_db_server fixture not working,"<p>I would like to use a specialized test database for unit testing my Django app. I'm using <code>pytest</code> along with <code>pytest-django</code>. Per the <code>pytest-django</code> instructions, I provided my own custom <code>django_db_setup</code> fixture in a <code>conftest.py</code> file as follows:</p>
<pre><code>from pathlib import Path

import pytest
from django.conf import settings


@pytest.fixture(scope='session')
def django_db_setup():
    base_dir = Path(__file__).parent
    path = base_dir / 'test_db.sqlite3'
    assert path.exists()
    assert path.is_file()

    settings.DATABASES['default'] = {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': path
    }
</code></pre>
<p>I can confirm that this code is being executed when I run unit tests, and the <code>test_db.sqlite3</code> database is being found. However, the unit tests are still referring to my development database <strong>not</strong> my test database.</p>
<p>How do I get <code>pytest-django</code> to reference my test database instead of my development database?</p>
",https://stackoverflow.com/questions/72505289/pytest-django-django-db-server-fixture-not-working,"['python', 'django', 'pytest', 'pytest-django']",366,False,0,1
Moq Verify method not working with ToList,"<p>I am fairly new to unit testing in C# and learning to use Moq. Below is the example of my problem with Moq <code>Verify()</code> method.</p>
<pre><code>[Theory]
[AutoData]
public async Task WhenSomething_ThenSomething(IEnumerable&lt;string&gt; stringCollection)
{
        //Arange
        //Mock of the method used in Handle() that returns stringCollection.
        someMock.Setup(x =&gt; x.MethodReturningStringCollectionForHandler()).ReturnsAsync(stringCollection);
        var someList = stringCollection.ToList();

        //Act
        await handler.Handle(new SomeRequest(someId));

        //Assert
        //I want to verify if someMethod() inside handler was called once but with appropriate stringCollection
        problematicMock.Verify(x =&gt; x.someMethod(someList), Times.Once());
}
</code></pre>
<p>The above scenerio works, but when I remove <code>someList</code> variable and use <code>ToList()</code> directly in <code>Verify()</code>, like this:</p>
<pre><code>problematicMock.Verify(x =&gt; x.someMethod(stringCollection.ToList()), Times.Once());
</code></pre>
<p>then I get the following exception:</p>
<pre><code>Message: 
    Moq.MockException : 
    Expected invocation on the mock once, but was 0 times: x =&gt; x.someMethod([&quot;83436e1f-bd2f-44d3-9f8c-ba6afbf73e95&quot;, &quot;16593c11-0959-4ebe-aafd-d5fbe0cfbd17&quot;, &quot;633e6557-bed0-4ff0-b550-8790fab9e629&quot;])
</code></pre>
<p>As one could imagine, this is quite problematic, what if <code>someMethod()</code> would accept many collection-type parameters? For this particular example I would have to create many variables to pass to <code>Verify()</code> method. Why does it work this way?</p>
",https://stackoverflow.com/questions/71310365/moq-verify-method-not-working-with-tolist,"['c#', 'unit-testing', 'moq', 'xunit', 'autofixture']",460,True,-1,1
How to run unit testing for an Angular app on Gitlab CI?,"<p>I want to run unit testing on my Angular library using the Gitlab CI. The tests are working and succeeding on my local machine, but they don't see to be run at all on Gitlab. I have tried editing my test script to run the steps described <a href=""https://medium.com/@JohanPujol/test-unitaires-en-angular-avec-angular-cli-et-gitlab-ci-6c6124dfe7b9"" rel=""nofollow noreferrer"">here</a>, but to no avail. Here is the log of my test stage :</p>
<pre><code>Running with gitlab-runner 14.8.0~beta.44.g57df0d52 (57df0d52)
  on blue-4.shared.runners-manager.gitlab.com/default J2nyww-s
Preparing the &quot;docker+machine&quot; executor 00:33
Using Docker executor with image node:latest ...
Pulling docker image node:latest ...
Using docker image sha256:f8c8d04432c3686347434420abcc20646237c5685b4b11a7db63df7acb866cd6 for node:latest with digest node@sha256:a0590a265b222387d756ba357c4a9875778f1a7638ac011f3fb4942d3b7ae5c0 ...
Preparing environment 00:03
Running on runner-j2nyww-s-project-33286021-concurrent-0 via runner-j2nyww-s-shared-1644574459-102eb0f3...
Getting source from Git repository 00:03
$ eval &quot;$CI_PRE_CLONE_SCRIPT&quot;
Fetching changes with git depth set to 20...
Initialized empty Git repository in /builds/xxxxx/my-project/.git/
Created fresh repository.
Checking out 6c0fbcdf as main...
Skipping Git submodules setup
Restoring cache 00:15
Checking cache for 9e7cd7eec847386573b03db5adf9ef87d7c957c2...
Downloading cache.zip from https://storage.googleapis.com/gitlab-com-runners-cache/project/xxxx/cache
Successfully extracted cache
Checking cache for main...
Downloading cache.zip from https://storage.googleapis.com/gitlab-com-runners-cache/project/xxxx/main 
Successfully extracted cache
Executing &quot;step_script&quot; stage of the job script
Using docker image sha256:f8c8d04432c3686347434420abcc20646237c5685b4b11a7db63df7acb866cd6 for node:latest with digest node@sha256:a0590a265b222387d756ba357c4a9875778f1a7638ac011f3fb4942d3b7ae5c0 ...
$ npm ci --cache .npm --prefer-offline
npm WARN deprecated flatten@1.0.3: flatten is deprecated in favor of utility frameworks such as lodash.
npm WARN deprecated source-map-resolve@0.6.0: See https://github.com/lydell/source-map-resolve#deprecated
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
added 1308 packages, and audited 1524 packages in 32s
129 packages are looking for funding
  run `npm fund` for details
43 moderate severity vulnerabilities
To address issues that do not require attention, run:
  npm audit fix
To address all issues, run:
  npm audit fix --force
Run `npm audit` for details.
$ { # collapsed multi-line command
@my-group:registry=https://gitlab.com/api/v4/packages/npm/
//gitlab.com/api/v4/packages/npm/:_authToken=[MASKED]
//gitlab.com/api/v4/projects/xxxxx/packages/npm/:_authToken=[MASKED]
$ cd projects/my-lib
$ npm test
&gt; @my-group/my-lib@1.1.6 test
&gt; ng test
Node.js version v17.5.0 detected.
Odd numbered Node.js versions will not enter LTS status and should not be used for production. For more information, please see https://nodejs.org/en/about/releases/.
- Generating browser application bundles (phase: setup)...
11 02 2022 10:16:45.662:WARN [karma]: No captured browser, open http://localhost:9876/
11 02 2022 10:16:45.765:INFO [karma-server]: Karma v6.3.15 server started at http://localhost:9876/
11 02 2022 10:16:45.772:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
11 02 2022 10:16:45.784:INFO [launcher]: Starting browser Chrome
11 02 2022 10:16:45.785:ERROR [launcher]: No binary for Chrome browser on your platform.
  Please, set &quot;CHROME_BIN&quot; env variable.
✔ Browser application bundle generation complete.
11 02 2022 10:17:09.953:WARN [karma]: No captured browser, open http://localhost:9876/
✔ Browser application bundle generation complete.
</code></pre>
<p>It then remains stuck on that last instruction.
Here is my test stage :</p>
<pre><code>test:
  stage: test
  script:
    - cd projects/my-lib
    - npm test
</code></pre>
<p>The new test script I tried :</p>
<pre><code>&quot;test&quot;: &quot;./node_modules/.bin/karma start karma.conf.js&quot;
</code></pre>
<p>Thanks in advance</p>
",https://stackoverflow.com/questions/71078867/how-to-run-unit-testing-for-an-angular-app-on-gitlab-ci,"['angular', 'unit-testing', 'testing', 'gitlab', 'gitlab-ci']",1486,False,0,0
SyntaxError: Cannot use import statement outside a module Jest when node modules are ignored,"<p>Getting <code>SyntaxError: Cannot use import statement outside a module</code> while unit testing with Jest. The error is coming from the <code>node-fetch</code> package that is <a href=""https://github.com/developit/jsdom-worker/blob/master/package.json#:%7E:text=%22-,node%2Dfetch,-%22%3A%20%22%5E2.6.0%22"" rel=""nofollow noreferrer""><strong>required</strong></a> by the <a href=""https://github.com/developit/jsdom-worker"" rel=""nofollow noreferrer""><code>jsdom-worker</code></a> package. This could be an issue with the <code>node-fetch</code> package but not entirely sure.</p>
<p>I have node modules ignored in my <code>jest.config.js</code> so why is this an issue?</p>
<p><code>jest.config.js</code> file:</p>
<pre><code>const ignores = ['/node_modules/', '/__fixtures__/', '/fixtures/', '/__tests__/helpers/', '/__tests__/utils/', '__mocks__'];

module.exports = {
    preset: 'ts-jest',
    roots: ['&lt;rootDir&gt;'],
    modulePaths: [
        &quot;&lt;rootDir&gt;/src&quot;
    ],
    moduleDirectories: [
        &quot;node_modules&quot;
    ],
    transformIgnorePatterns: [...ignores],
    transform: {
        '^.+\\.(ts|tsx|js|jsx)?$': 'ts-jest',
        '^.+\\.(gif|svg|ico)$': '&lt;rootDir&gt;/svgTransform.js',
    },
    testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.js?$',
    moduleFileExtensions: ['tsx', 'js', 'json', 'node', 'ts'],
    moduleNameMapper: {
        &quot;\\.(css|less|scss|sass)$&quot;: &quot;identity-obj-proxy&quot;
      },
    clearMocks: true,
    // collectCoverage: true, // todo
    // coverageDirectory: &quot;coverage&quot;,  // todo
    testEnvironment: 'jsdom',
    setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect', 'jsdom-worker'],
}
// }
</code></pre>
<p><strong>UPDATE:</strong>
After downgrading <code>node-fetch</code> to version 2.4, <em>that</em> error went away, but now have the same Syntax issue with another package, why does this keep happening?</p>
<p><strong>Code Trace</strong>
<a href=""https://i.stack.imgur.com/eMWtv.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/eMWtv.png"" alt=""enter image description here"" /></a></p>
<p><code>babel.config.js</code></p>
<pre><code>// Need to convert modules to commonjs format so Jest can undertstand them.
const isTest = String(process.env.NODE_ENV) === 'test'
const isProd = String(process.env.NODE_ENV) === 'production'

module.exports = {
    // For transformation of TSX and other react related bable plugins
    presets: [
        // Allows smart transpilation according to target environments
        ['@babel/preset-env', { modules: isTest ? 'commonjs' : false }],
        // Enabling Babel to understand TypeScript
        '@babel/preset-typescript',
    ],
}
</code></pre>
<p>Also tried <em><strong><a href=""https://github.com/kentcdodds/kcd-scripts/blob/main/src/config/babelrc.js"" rel=""nofollow noreferrer"">this</a></strong></em> babel config from kcd-scripts:</p>
<pre><code>&quot;use strict&quot;;

const browserslist = require('browserslist');

const semver = require('semver');

const {
  ifDep,
  ifAnyDep,
  ifTypescript,
  parseEnv,
  appDirectory,
  pkg
} = require('../utils');

const {
  BABEL_ENV,
  NODE_ENV,
  BUILD_FORMAT
} = process.env;
const isTest = (BABEL_ENV || NODE_ENV) === 'test';
const isPreact = parseEnv('BUILD_PREACT', false);
const isRollup = parseEnv('BUILD_ROLLUP', false);
const isUMD = BUILD_FORMAT === 'umd';
const isCJS = BUILD_FORMAT === 'cjs';
const isWebpack = parseEnv('BUILD_WEBPACK', false);
const isMinify = parseEnv('BUILD_MINIFY', false);
const treeshake = parseEnv('BUILD_TREESHAKE', isRollup || isWebpack);
const alias = parseEnv('BUILD_ALIAS', isPreact ? {
  react: 'preact'
} : null);
const hasBabelRuntimeDep = Boolean(pkg.dependencies &amp;&amp; pkg.dependencies['@babel/runtime']);
const RUNTIME_HELPERS_WARN = 'You should add @babel/runtime as dependency to your package. It will allow reusing &quot;babel helpers&quot; from node_modules rather than bundling their copies into your files.';

if (!treeshake &amp;&amp; !hasBabelRuntimeDep &amp;&amp; !isTest) {
  throw new Error(RUNTIME_HELPERS_WARN);
} else if (treeshake &amp;&amp; !isUMD &amp;&amp; !hasBabelRuntimeDep) {
  console.warn(RUNTIME_HELPERS_WARN);
}
/**
 * use the strategy declared by browserslist to load browsers configuration.
 * fallback to the default if don't found custom configuration
 * @see https://github.com/browserslist/browserslist/blob/master/node.js#L139
 */


const browsersConfig = browserslist.loadConfig({
  path: appDirectory
}) || ['defaults'];
const envTargets = isTest ? {
  node: 'current'
} : isWebpack || isRollup ? {
  browsers: browsersConfig
} : {
  node: getNodeVersion(pkg)
};
const envOptions = {
  modules: false,
  loose: true,
  targets: envTargets
};

module.exports = () =&gt; ({
  presets: [[require.resolve('@babel/preset-env'), envOptions], ifAnyDep(['react', 'preact'], [require.resolve('@babel/preset-react'), {
    pragma: isPreact ? ifDep('react', 'React.h', 'h') : undefined
  }]), ifTypescript([require.resolve('@babel/preset-typescript')])].filter(Boolean),
  plugins: [[require.resolve('@babel/plugin-transform-runtime'), {
    useESModules: treeshake &amp;&amp; !isCJS
  }], require.resolve('babel-plugin-macros'), alias ? [require.resolve('babel-plugin-module-resolver'), {
    root: ['./src'],
    alias
  }] : null, ifAnyDep(['react', 'preact'], [require.resolve('babel-plugin-transform-react-remove-prop-types'), isPreact ? {
    removeImport: true
  } : {
    mode: 'unsafe-wrap'
  }]), isUMD ? require.resolve('babel-plugin-transform-inline-environment-variables') : null, [require.resolve('@babel/plugin-proposal-class-properties'), {
    loose: true
  }], isMinify ? require.resolve('babel-plugin-minify-dead-code-elimination') : null, treeshake ? null : require.resolve('@babel/plugin-transform-modules-commonjs')].filter(Boolean)
});

function getNodeVersion({
  engines: {
    node: nodeVersion = '10.13'
  } = {}
}) {
  const oldestVersion = semver.validRange(nodeVersion).replace(/[&gt;=&lt;|]/g, ' ').split(' ').filter(Boolean).sort(semver.compare)[0];

  if (!oldestVersion) {
    throw new Error(`Unable to determine the oldest version in the range in your package.json at engines.node: &quot;${nodeVersion}&quot;. Please attempt to make it less ambiguous.`);
  }

  return oldestVersion;
}
</code></pre>
",https://stackoverflow.com/questions/72918077/syntaxerror-cannot-use-import-statement-outside-a-module-jest-when-node-modules,"['reactjs', 'unit-testing', 'testing', 'jestjs', 'es6-modules']",4370,True,0,2
jest mocking toHaveReturnedWith undefined,"<p>I'm learning unit testing with jest and particularly mocking modules. I wrote some simple module in math.js file with some math methods:</p>
<pre><code>const add      = (a, b) =&gt; a + b;
const subtract = (a, b) =&gt; b - a;
const multiply = (a, b) =&gt; a * b;
const divide   = (a, b) =&gt; b / a;

module.exports = {
    add,
    subtract,
    multiply,
    divide
}
</code></pre>
<p>Then I include it in my main js and I do module mocking like this:</p>
<pre><code>jest.mock('./math.js');
const math = require('./math');

test(&quot;calls math.add&quot;, () =&gt; {
    math.add(1, 2);

    console.log(math.add.mock);

    expect(math.add).toHaveBeenCalled();
    expect(math.add).toHaveBeenCalledWith(1, 2);
    expect(math.add).toHaveReturned();
    expect(math.add).toHaveReturnedWith(3);
});
</code></pre>
<p>Now when I run my test all tests are passing besides the last one:</p>
<pre><code>expect(math.add).toHaveReturnedWith(3);
</code></pre>
<p>In console I see:</p>
<p>● calls math.add</p>
<pre><code>expect(jest.fn()).toHaveReturnedWith(expected)

Expected: 3
Received: undefined

Number of returns: 1

  10 |     expect(math.add).toHaveBeenCalledWith(1, 2);
  11 |     expect(math.add).toHaveReturned();
&gt; 12 |     expect(math.add).toHaveReturnedWith(3);
     |                      ^
  13 | });
</code></pre>
<p>and console.log(math.add.mock) gives me this:</p>
<pre><code> console.log
      {
        calls: [ [ 1, 2 ] ],
        instances: [
          {
            add: [Function],
            subtract: [Function],
            multiply: [Function],
            divide: [Function]
          }
        ],
        invocationCallOrder: [ 1 ],
        results: [ { type: 'return', value: undefined } ],
        lastCall: [ 1, 2 ]
      }
</code></pre>
<p>So it seems that math.add mocked function does not return any value. My question is why? What I do wrong?</p>
",https://stackoverflow.com/questions/71605818/jest-mocking-tohavereturnedwith-undefined,"['javascript', 'unit-testing', 'jestjs', 'mocking']",1338,True,0,1
How to do a simple angular Jasmine Unit testing when using RXJS reactive approach using a subject and a stream that calls a service,"<p>How can I do a simple angular Jasmine Unit testing when using RXJS reactive approach</p>
<p>Here is my simple implementation of the component. I have an items stream that gets some collection of items. Then I have a dropdown in HTML that calls the onSelectItem method which triggers the next() method of the selectedItemSubject. My goal is to test the $itemsWithSelected stream - to check if it returns the correct value - which is influenced by the selected Item and the items stream.</p>
<pre><code>  items$ = this.someService.getItems().pipe(
    map((items) =&gt; {
      return items;
    })
  );

  private selectedItemSubject$ = new Subject&lt;any&gt;();
  selectionItemAction$ = selectedItemSubject$.asObservable();

  $itemsWithSelected = combineLatest([this.selectionItemAction$, items$]).pipe(
    map(([selected, items]) =&gt; {
      var targetItem = items.find(x =&gt; x.id === selected);
    return someProcess(targetItem.someProperyOfThisItem);
    }));

  //some method that calls next of the subject
  onSelectItem($event){
    this.selectedItemSubject$.next($event.value);
  }
</code></pre>
",https://stackoverflow.com/questions/71462552/how-to-do-a-simple-angular-jasmine-unit-testing-when-using-rxjs-reactive-approac,"['angular', 'rxjs', 'reactive-programming', 'declarative-programming']",306,False,0,2
DUNITX call Setup with parameters,"<p>I guess the best practice in unit testing is writing code always called (like create object , do a primary init of these objects, .... )  for  a test  inside the setup procedure</p>
<pre><code>  [TestFixture]
  TMY_Testcases = class
  private

    FTestConfigParameter: TParameter;


  public

    [Setup]
    procedure Setup;
    [TearDown]
    procedure TearDown;

    [Test]
    [TestCase('CreateTrue', 'True')]
    [TestCase('CreateFalse', 'False')]
    procedure Test_DoMyTest (Createflag : Boolean);

  end; 
</code></pre>
<p>I have several sets of parameters for my objects I do the object.create in the setup procedure.
Is there any way to run the test cases with the setup procedure getting my parameter?
My ugl solution  goes like  this :</p>
<pre><code>    [Setup]
    procedure Setup;
    [TearDown]
    procedure TearDown;
    
    procedure MySetup(MyParameter : TParameter);

    [TestCase('CreateWithParameter', 'False,Parameter_AsString')]
     procedure Test_DoMyTest (Createflag : Boolean, Parameter : TParameter);
</code></pre>
<p>This approach makes setup and Teardown procedure obsolete, any better approach?</p>
",https://stackoverflow.com/questions/74252805/dunitx-call-setup-with-parameters,"['delphi', 'dunitx']",60,True,0,1
"Deploying Uniswap v2 / Sushiswap or similar in Brownie, Hardhat or Truffle test suite","<p>I am writing an automated test suite that needs to test functions against Uniswap v2 style automated market marker: do swaps and use different order routing. Thus, routers need to be deployed.</p>
<p>Are there any existing examples of how to deploy a testable Uniswap v2 style exchange in Brownie? Because Brownie is a minority of smart contract developers, are there any examples for Truffle or Hardhat?</p>
<p>I am also exploring the option of using a mainnet fork, but I am not sure if this operation is too expensive (slow) to be used in unit testing.</p>
",https://stackoverflow.com/questions/70846489/deploying-uniswap-v2-sushiswap-or-similar-in-brownie-hardhat-or-truffle-test,"['ethereum', 'ganache', 'hardhat', 'brownie', 'uniswap']",2186,True,5,3
What are the test description conventions in Flutter and Dart?,"<p>It seems to me that developers should have resources to some basic and general principles about how to write an appropriate description to a test. Should it be long? Short? Should it include numbers? Operations? And so on...</p>
<pre><code>void main() {
  //The first argument is the description I mean
  test('Counter value should be incremented', () {
    final counter = Counter();

    counter.increment();

    expect(counter.value, 1);
  });
}
</code></pre>
<p>I haven't found anything about it in the docs. For reference:</p>
<p><a href=""https://dart.dev/guides/language/effective-dart/design"" rel=""nofollow noreferrer"">Effective Dart: Style</a></p>
<p><a href=""https://dart.dev/guides/language/effective-dart/design"" rel=""nofollow noreferrer"">Effective Dart: Design</a></p>
<p><a href=""https://dart.dev/guides/testing"" rel=""nofollow noreferrer"">Dart testing</a></p>
<p><a href=""https://docs.flutter.dev/cookbook/testing/unit/introduction"" rel=""nofollow noreferrer"">An introduction to unit testing</a></p>
<p>Is this then completely open? If so, and answer confirming that this is the case would also be appreciated. Thank you in advance.</p>
",https://stackoverflow.com/questions/71163209/what-are-the-test-description-conventions-in-flutter-and-dart,"['flutter', 'dart', 'testing', 'automated-tests']",383,True,2,1
Exclude functions from Pester code coverage,"<p>The latest versions of Pester work with a PesterConfiguration object to set the configuration for the unit testing, as described <a href=""https://pester-docs.netlify.app/docs/commands/New-PesterConfiguration"" rel=""nofollow noreferrer"">here</a>.</p>
<p>In the 'old' command line settings of Invoke-Pester I could utilize a specific setting (Function) for <a href=""https://pester.dev/docs/usage/code-coverage"" rel=""nofollow noreferrer"">Code Coverage</a>, in which you can include/exclude functions in the to be tested file.</p>
<p>However, this option seems to be missing in the new PesterConfiguration object. I also cannot use both methods together unfortunately.</p>
<p>How can I still exclude functions for code coverage, while keeping the PesterConfiguration?</p>
",https://stackoverflow.com/questions/71334884/exclude-functions-from-pester-code-coverage,"['powershell', 'unit-testing', 'pester']",254,False,2,0
X unit test with fakeitesay faking async methods asp.net,"<p>The return type of result and expected are different unable to fake an async method
my code on x unit  testing</p>
<pre><code>using Amazon.Controllers;
using Amazon.Models;
using Amazon.Repository;
using FakeItEasy;
using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AmazonAPITest.Amazon_Controller_Merchant
{
    public  class Merchant_Controller_Test
    {
        private readonly IMerchantRepository _merchantRepository;

        public Merchant_Controller_Test()
        {
            _merchantRepository = A.Fake&lt;IMerchantRepository&gt;();
            
        }
        [Fact]
        public void MerchantController_GetMerchants_ListMerchantAsync()
        {
            //Arrange
            var MerchantList = A.Fake&lt;Task&lt;List&lt;Merchant&gt;&gt;&gt;();
            A.CallTo(() =&gt; _merchantRepository.GetMerchant()).Returns(MerchantList);
            var MerchantController = new MerchantController(_merchantRepository);
            var expected = A.Fake&lt;Task&lt;ActionResult&lt;List&lt;Merchant&gt;&gt;&gt;&gt;();

            //Act
            var result=  MerchantController.GetMerchants();
            
            //Assert
            result.Should().NotBeNull();
            result.Should().BeOfType&lt;Task&lt;ActionResult&lt;List&lt;Merchant&gt;&gt;&gt;&gt;();
           
            
        }
    }
}
</code></pre>
<p>controller action method code</p>
<pre><code>[HttpGet]
    public async Task&lt;ActionResult&lt;List&lt;Merchant&gt;&gt;&gt; GetMerchants()
    {
        return await _repository.GetMerchant();
    }
    
</code></pre>
<p>repository code</p>
<pre><code>  public async Task&lt;List&lt;Merchant&gt;&gt; GetMerchant()
    {
        try
        {
            return await _context.Merchants.ToListAsync();
        }
        catch
        {
            throw new NotImplementedException();

        }
    }
</code></pre>
<p>exception on debugging the test</p>
<p>Xunit.Sdk.XunitException: 'Expected type to be <strong>System.Threading.Tasks.Task<code>1[[Microsoft.AspNetCore.Mvc.ActionResult</code>1[[System.Collections.Generic.List<code>1[[Amazon.Models.Merchant, AmazonAPI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], Microsoft.AspNetCore.Mvc.Core, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]]**,  but found  **System.Runtime.CompilerServices.AsyncTaskMethodBuilder</code>1+AsyncStateMachineBox<code>1[[Microsoft.AspNetCore.Mvc.ActionResult</code>1[[System.Collections.Generic.List`1[[Amazon.Models.Merchant, AmazonAPI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], Microsoft.AspNetCore.Mvc.Core, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60],[System.Runtime.CompilerServices.IAsyncStateMachine, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]</strong>.</p>
<p>can someone figure any way to fake async method with fake it easy</p>
",https://stackoverflow.com/questions/73631155/x-unit-test-with-fakeitesay-faking-async-methods-asp-net,"['c#', 'async-await', 'xunit.net', 'fakeiteasy']",447,True,1,1
Mocking proto.Message in Go,"<p>I wrote a function that takes a list of <code>proto.Message</code> objects. Looking at the <a href=""https://pkg.go.dev/google.golang.org/protobuf@v1.28.0/proto#Message"" rel=""nofollow noreferrer"">documentation</a>, it seems like <code>proto.Message</code> wraps <code>protoreflect.ProtoMessage</code> which contains a single function, <code>ProtoReflect() Message</code>. Looking at the <a href=""https://pkg.go.dev/google.golang.org/protobuf@v1.28.0/reflect/protoreflect#Message"" rel=""nofollow noreferrer"">documentation</a> for <code>Message</code>, it implements a number of other functions that return types referenced by the <code>protoreflect</code> package.</p>
<p>It seems that attempting to create a mock <code>proto.Message</code> would be a lot more work that it's worth but I don't want to go through the whole process of creating a protobuf file, compiling it and referencing it just for unit testing.</p>
<p>Is there another way I can create a mock <code>proto.Message</code> object?</p>
",https://stackoverflow.com/questions/72299578/mocking-proto-message-in-go,"['unit-testing', 'go', 'proto']",771,True,4,1
Unit Testing by mocking S3 bucket,"<p>I am new to unit testing and I require to perform some simple unit tests for an object storage class.</p>
<p>I have a class named OSBucket as follows:</p>
<pre><code>def __initBucket(self):        
        
        ecs_session = boto3.Session(
        aws_access_key_id=&quot;OSKEY&quot;,
        aws_secret_access_key=&quot;SECRETKEY&quot;
        ) 

        OS_resource = ecs_session.resource('s3', verify=cert, endpoint_url=endpoint)
        self.mybucket = OS_resource.Bucket(OS_BUCKET)
                
        
def get_mybucket(self): 
        
   return self.mybucket


def download_file(self, fileName,filepath):
        
   self.mybucket.download_file(fileName, filepath)

def upload_file(self, filepath,dest_file_name):   
   self.mybucket.upload_file(filepath, '%s%s' % (&quot;/&quot;,dest_file_name))


</code></pre>
<p>The method __initBucket is called in the constructor of the class.</p>
<p>How could I start creating a unit test class to test, for example, the download_file method?</p>
<p><strong>UPDATE 1</strong></p>
<pre><code>        moto_fake.start()
        conn = boto3.resource('s3', aws_access_key_id=&quot;fake_id&quot;,
        aws_secret_access_key=&quot;fake_secret&quot;)
        conn.create_bucket(Bucket=&quot;OS_BUCKET&quot;)    

        os_bucket = OSBucket.OSBucket(thisRun)

        sourcefile = &quot;testingMoto.txt&quot;   
        filePath = os.path.join(&quot;/&quot;, sourcefile)   
        os_bucket.upload_file(filePath, sourcefile)  
</code></pre>
<p>which executes the <code>moto_fake.start()</code> before creating the <code>os_bucket</code> object does not work for me.</p>
<p><strong>UPDATE 2</strong></p>
<p>Using patch.object to change the endpoint variable to None, makes the test pass</p>
",https://stackoverflow.com/questions/71765091/unit-testing-by-mocking-s3-bucket,"['python', 'unit-testing', 'amazon-s3', 'mocking', 'bucket']",14697,True,1,1
Unittest has unrecognized arguments,"<p>I'm running unit tests for my program.py file.  I found an error: <code>python3 -m unittest: error: unrecognized arguments:</code>.</p>
<p>I believe the error comes from the <code>argparse</code> library I'm using where the target code is expecting some arguments.</p>
<p>Target file: program.py:</p>
<pre class=""lang-py prettyprint-override""><code>import argparse

parse = argparse.ArgumentParser(description=&quot;Command line program.&quot;)
parse.add_argument(&quot;--key&quot;, type=str,
                   help=&quot;Enter key&quot;)
parse.add_argument(&quot;--output&quot;, type=str,
                   help=&quot;Path to place results.&quot;)
args = parse.parse_args()


def program():
    # Use args here 

def writefile():
    # Uses args and write to file 

if __name__ == &quot;__main__&quot;:
    program()
</code></pre>
<p>Test file: program_test.py:</p>
<pre class=""lang-py prettyprint-override""><code>import unittest

import program

class TestProgram(unittest.TestCase):
    def setUp(self):
        self.argv_list = [&quot;--key&quot;, &quot;somefile.txt&quot;,
                          &quot;--output&quot;, &quot;myresultfile.txt&quot;]

    def test_program_stuff(self):
        # See &quot;Things I've tried&quot; 
        program.writefile(...)
</code></pre>
<p>Command:</p>
<pre class=""lang-bash prettyprint-override""><code>me@mylinux:myprogram$ env/bin/python3 -m unittest -v program_test.py 

usage: python3 -m unittest [-h] [--key KEY] [--output OUTPUT]
python3 -m unittest: error: unrecognized arguments: -v program_test.py
</code></pre>
<p><strong>Things I've tried:</strong></p>
<ul>
<li>Mock the <code>argparse.Namespace</code> with <code>argparse.Namespace(key=&quot;key.txt&quot;, output=&quot;result.txt&quot;)</code></li>
<li>Manipulate <code>sys.args</code> in test_program_stuff by <code>sys.args.append(self.argv_list)</code></li>
</ul>
<p>I've looked at solutions to unit testing argparse but none have helped so I'm thinking it may not be the same issue:</p>
<ul>
<li><a href=""https://stackoverflow.com/questions/39712987/python-argparse-unrecognized-arguments-error"">Python argparse &quot;unrecognized arguments&quot; error</a></li>
<li><a href=""https://stackoverflow.com/questions/18325211/argparse-fails-when-called-from-unittest-test"">argparse fails when called from unittest test</a></li>
<li><a href=""https://stackoverflow.com/questions/20265522/argparse-and-unittest-python"">argparse and unittest python</a></li>
</ul>
",https://stackoverflow.com/questions/73684932/unittest-has-unrecognized-arguments,"['python', 'argparse', 'python-unittest']",718,True,1,2
Junit testing spring boot,"<p>I want to start unit testing for my spring-boot application with Intelliji</p>
<p>code</p>
<pre><code>class BookingControllerTest {
    private MockMvc mvc;
    @Test
    void countBookings() throws Exception {
        RequestBuilder request = MockMvcRequestBuilders.get(&quot;/bookings/count&quot;);
        MvcResult result = mvc.perform(request).andReturn();
        assertEquals(3,3);

    }
}

</code></pre>
<p>whenever I start my test I got this error</p>
<pre><code>
WARNING: TestEngine with ID 'junit-vintage' failed to discover tests
org.junit.platform.commons.JUnitException: Failed to parse version of junit:junit: 4.13.2
    at org.junit.vintage.engine.JUnit4VersionCheck.parseVersion(JUnit4VersionCheck.java:54)
    at org.junit.vintage.engine.JUnit4VersionCheck.checkSupported(JUnit4VersionCheck.java:37)
    at org.junit.vintage.engine.JUnit4VersionCheck.checkSupported(JUnit4VersionCheck.java:32)
    at org.junit.vintage.engine.VintageTestEngine.discover(VintageTestEngine.java:61)
    at org.junit.platform.launcher.core.DefaultLauncher.discoverEngineRoot(DefaultLauncher.java:177)
    at org.junit.platform.launcher.core.DefaultLauncher.discoverRoot(DefaultLauncher.java:164)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)


java.lang.NullPointerException: Cannot invoke &quot;org.springframework.test.web.servlet.MockMvc.perform(org.springframework.test.web.servlet.RequestBuilder)&quot; because &quot;this.mvc&quot; is null

    at Booking.controllers.BookingControllerTest.countBookings(BookingControllerTest.java:26)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)
    at java.base/java.lang.reflect.Method.invoke(Method.java:577)
    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:628)
    at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:117)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:184)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:180)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:127)
    at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:68)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$5(NodeTestTask.java:135)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java: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:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at java.base/java.util.ArrayList.forEach(ArrayList.java: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:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$7(NodeTestTask.java:125)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:135)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:123)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:122)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:80)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:32)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:51)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:229)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$6(DefaultLauncher.java:197)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:191)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:128)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)


Process finished with exit code -1
</code></pre>
<p>you can find here my pom.xml file which contains all my dependencies in case there is something wrong or something I need to download / delete/add or change version!</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.7.3&lt;/version&gt;
        &lt;relativePath/&gt; &lt;!-- lookup parent from repository --&gt;
    &lt;/parent&gt;
    &lt;groupId&gt;Booking&lt;/groupId&gt;
    &lt;artifactId&gt;Booking&lt;/artifactId&gt;
    &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt;
    &lt;name&gt;Booking&lt;/name&gt;
    &lt;description&gt;BookingSystem&lt;/description&gt;
    &lt;properties&gt;
        &lt;java.version&gt;18&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&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework&lt;/groupId&gt;
            &lt;artifactId&gt;spring-web&lt;/artifactId&gt;
            &lt;version&gt;5.3.15&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-data-jpa&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;
            &lt;scope&gt;test&lt;/scope&gt;
            &lt;!--&lt;exclusions&gt;
                &lt;exclusion&gt;
                    &lt;groupId&gt;org.junit.vintage&lt;/groupId&gt;
                    &lt;artifactId&gt;junit-vintage-engine&lt;/artifactId&gt;

                &lt;/exclusion&gt;
            &lt;/exclusions&gt;--&gt;
        &lt;/dependency&gt;




        &lt;dependency&gt;
            &lt;groupId&gt;mysql&lt;/groupId&gt;
            &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
            &lt;scope&gt;runtime&lt;/scope&gt;
        &lt;/dependency&gt;

        &lt;dependency&gt;
            &lt;groupId&gt;javax.validation&lt;/groupId&gt;
            &lt;artifactId&gt;validation-api&lt;/artifactId&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;commons-io&lt;/groupId&gt;
            &lt;artifactId&gt;commons-io&lt;/artifactId&gt;
            &lt;version&gt;2.11.0&lt;/version&gt;
        &lt;/dependency&gt;
        &lt;dependency&gt;
            &lt;groupId&gt;org.junit.jupiter&lt;/groupId&gt;
            &lt;artifactId&gt;junit-jupiter-engine&lt;/artifactId&gt;
            &lt;version&gt;5.8.1&lt;/version&gt;
            &lt;scope&gt;test&lt;/scope&gt;
        &lt;/dependency&gt;

    &lt;/dependencies&gt;
    &lt;build&gt;
        &lt;plugins&gt;
            &lt;plugin&gt;
                &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
                &lt;artifactId&gt;spring-boot-maven-plugin&lt;/artifactId&gt;
                &lt;version&gt;${project.parent.version}&lt;/version&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;configuration&gt;
                    &lt;source&gt;17&lt;/source&gt;
                    &lt;target&gt;17&lt;/target&gt;
                &lt;/configuration&gt;
            &lt;/plugin&gt;
        &lt;/plugins&gt;
        &lt;finalName&gt;booking&lt;/finalName&gt;
    &lt;/build&gt;

&lt;/project&gt;

</code></pre>
<p>I tried to change the version of my Junit and restarted my Intellij( invalid chache) but nothing happend and the same error kept appearing
can anyone tell me what is the problem please ?</p>
",https://stackoverflow.com/questions/73438441/junit-testing-spring-boot,"['spring-boot', 'maven', 'testing', 'junit']",1234,False,1,2
How do I unit test my dependency injection in my Flask app?,"<p>I've been following those tutorials on (unit) testing for dependency injections and they're using pytest fixtures and I'm trying to replicate something similar in my Flask app. This is what my app looks like:</p>
<pre><code># all imports

class Container(containers.DeclarativeContainer):

    wiring_config = containers.WiringConfiguration(modules=[&quot;.routes&quot;, &quot;.scheduler&quot;])

    config = providers.Configuration(yaml_files=[&quot;src/conf/config.yaml&quot;])
    config.load(envs_required=True)
    s3_repository = providers.Resource(
        S3Repository, config.get(&quot;app.my_service.s3_bucket&quot;)
    )

    my_service = providers.Singleton(
        MyService, config, s3_repository
    )
</code></pre>
<p>My <code>app.py</code>:</p>
<pre><code>container = Container()
    container.init_resources()
    app = Flask(__name__)
    app.container = container
    
    # connect url rules and register error handlers
    routes.configure(app)

    # schedule and kickoff background jobs
    scheduler.schedule(app)

    # set flask configuration and logging
    app.config.from_mapping(app.container.config.get(&quot;app&quot;))
    setup_logging(app)

    return app
</code></pre>
<p><code>my_service.py</code></p>
<pre><code>class MyService:
    

    def __init__(self, config: dict, s3_repository: S3Repository) -&gt; None:
        self.s3 = s3_repository
        self.config = config
   
   # other logic/methods
</code></pre>
<p>My <code>S3Repository</code>:</p>
<pre><code>class S3Repository:
    def __init__(self, bucket):
        self.bucket = bucket
        

    def fetch(self, object_key, columns, filters):
    # code to fetch 

</code></pre>
<p>I'm trying to write my tests and working with <code>pytest</code> for the first time and this is what I have so far:</p>
<pre><code># TODO - re-write tests for since we're now using dependency injection
import unittest
from unittest.mock import Mock

import pytest as pytest

from src.repository.s3_repository import S3Repository
from src.service.HealthSignalService import HealthSignalService


class TestApp(unittest.TestCase):
    def something(self):
        pass


@pytest.fixture
def mock_config(mocker):
    return mocker.patch(&quot;providers.Configuration&quot;)


def test_app(mock_config):
    from src import create_app
    create_app()

</code></pre>
<p>When I run this I see:</p>
<pre><code>  @pytest.fixture
  def mock_config(mocker):
E       fixture 'mocker' not found
&gt;       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, mock_config, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
&gt;       use 'pytest --fixtures [testpath]' for help on them.

</code></pre>
<p>What am I doing wrong? What am I missing? Right now, I'm following this tutorial - <a href=""https://docs.pytest.org/en/7.1.x/explanation/fixtures.html"" rel=""nofollow noreferrer"">https://docs.pytest.org/en/7.1.x/explanation/fixtures.html</a></p>
",https://stackoverflow.com/questions/72004810/how-do-i-unit-test-my-dependency-injection-in-my-flask-app,"['python', 'flask', 'dependency-injection', 'pytest', 'python-unittest']",605,False,1,1
How to test a function that modifies the global scope?,"<p>I am earning unit testing. I know that best practice is that the functions should have local scope and they return something for example</p>
<pre><code>export function test(arr) {
    let arr2 = [];
    for(let i = 0;i &lt; arr.length;i++) {
        if(arr[i] % 2 === 0) {
            arr2.push(arr[i])
        }
    }
    return arr2;
}
</code></pre>
<p>i can write the test for this function very simple - where i will expect some result</p>
<pre><code>import { it, expect } from 'vitest';

it('should return even numbers', () =&gt; {
    let result = test([1,2,3,4]);
    expect(result).toEqual([2,4])
})
</code></pre>
<p>but I wonder, in functions where the global scope is modified from some function and the function is not returning anything for example</p>
<pre><code>let arr2 = [];
export function test(arr) {
    for(let i = 0;i &lt; arr.length;i++) {
        if(arr[i] % 2 === 0) {
            arr2.push(arr[i])
        }
    }
}
</code></pre>
<p>how can i write test for such a functions ? How can i assume that arr2 will containt [2,4] at the end ?</p>
",https://stackoverflow.com/questions/73204908/how-to-test-a-function-that-modifies-the-global-scope,"['unit-testing', 'jestjs', 'vitest']",53,False,0,0
How to unit test Kotlin coroutines with multiple async calls,"<p>I'm trying to write some unit tests for the following Kotlin code which uses async to create coroutines:</p>
<pre><code>class ClassToTest(val dependency1: Dependency1, val dependency2: Dependency2) {
fun funToTest(list: List&lt;X&gt;) {
    runBlocking {
        val deferreds: List&lt;Deferred&lt;Type&gt;&gt; = list.map { item -&gt;
            async(Dispatchers.Default) {
                val v1 = dependency1.func1(item)
                val v2 = dependency2.func2(v1)
                someFunc(v2)
            }
        }
        
        val results = deferreds.awaitAll()
    }
}
</code></pre>
<p>}</p>
<p>I mocked both dependency1 and dependency2 in the unit testing and provided a list of 2 items as input to the funToTest. I also mocked how the dependencies should return values based on different input, something like below</p>
<pre><code>val slot1 = slot&lt;&gt;()
every {dependency1.func1(capture(slot1))} answers {
    if (slot1.captured.field == xxx) {
        return1
    } else {
        return2
    }
}

//similar thing for dependency1

// invoke funToTest
</code></pre>
<p>However this doesn't seem like working as I'm getting unexpected results which indicated the mocked object didn't return results as desired between two coroutines.</p>
<p>Does anyone have any ideas what went wrong with these code?</p>
",https://stackoverflow.com/questions/72638262/how-to-unit-test-kotlin-coroutines-with-multiple-async-calls,"['unit-testing', 'kotlin', 'kotlin-coroutines']",371,False,3,0
Sending emails from Google Appengine fails because of missing api proxy,"<p>I am trying to send e-mails from a GAE application using this code:</p>
<pre><code>from google.appengine.api.mail import send_mail

send_mail(
    &quot;sender@nowhere.com&quot;,
    [&quot;user@example.com&quot;],
            &quot;Subject&quot;,
            &quot;Body&quot;,
)
</code></pre>
<p>I have configured usage of the apis in <code>app.yaml</code> with:</p>
<pre><code>app_engine_apis: true
</code></pre>
<p>And deploy to App Engine is done with <code>gcloud beta app deploy</code>.</p>
<p>However, I get this error:</p>
<pre><code>Traceback (most recent call last):   
File &quot;/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py&quot;, line 2073, in wsgi_app      response = self.full_dispatch_request()    
File &quot;/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py&quot;, line 1518, in full_dispatch_request      rv = self.handle_user_exception(e)    
File &quot;/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py&quot;, line 1516, in full_dispatch_request      rv = self.dispatch_request()    
File &quot;/layers/google.python.pip/pip/lib/python3.9/site-packages/flask/app.py&quot;, line 1502, in dispatch_request      return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)    
File &quot;/srv/infrastructure/view_modifiers.py&quot;, line 12, in view_method      response_val = f(*args, **kwargs)    
File &quot;/srv/views/orders.py&quot;, line 25, in create_order      vm.create_order()    
File &quot;/srv/viewmodels/orders/order_viewmodel.py&quot;, line 74, in create_order      self._send_order_email()    
File &quot;/srv/viewmodels/orders/order_viewmodel.py&quot;, line 54, in _send_order_email      send_mail(    
File &quot;/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/api/mail.py&quot;, line 401, in send_mail      message.send(make_sync_call=make_sync_call)    
File &quot;/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/api/mail.py&quot;, line 1209, in send      make_sync_call('mail', self._API_CALL, message, response)    
File &quot;/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/api/apiproxy_stub_map.py&quot;, line 96, in MakeSyncCall      return stubmap.MakeSyncCall(service, call, request, response)    
File &quot;/layers/google.python.pip/pip/lib/python3.9/site-packages/google/appengine/api/apiproxy_stub_map.py&quot;, line 348, in MakeSyncCall      assert stub, 'No api proxy found for service &quot;%s&quot;' % service  AssertionError: No api proxy found for service &quot;mail&quot;
</code></pre>
<p>This seems to suggest that even for the default behavior of the mail service, some kind of proxy needs to be configured. However, I cannot find any information about the setup of this proxy.
And, my initial understanding was that setting up a proxy is only needed for unit-testing or local development.</p>
",https://stackoverflow.com/questions/73357741/sending-emails-from-google-appengine-fails-because-of-missing-api-proxy,"['python', 'email', 'google-app-engine']",430,True,3,2
"How to write unit test for functions using azure storage file share, service bus?","<p>I have nestjs application, For unit testing, I need to test getting the files data from azure storage file share, for that I'm using @azure/storage-file-share. But I dont want access the actual storage account because, in our github pipeline runner it is not accessible. Is there a way to test storage file share on local/cicd pipeline without trying to access the actual service? P.S. I'm using jest to write unit tests.</p>
<p>I want to do the same thing with azure service bus.</p>
",https://stackoverflow.com/questions/72544833/how-to-write-unit-test-for-functions-using-azure-storage-file-share-service-bus,"['node.js', 'azure', 'jestjs', 'azureservicebus', 'azure-storage-files']",503,False,0,1
Unit testing for component with private @ViewChild child component?,"<p>How to write Unit testing for component with private @ViewChild child component?</p>
<p>Note: I can't change or update the main component codes just for writing test case.</p>
<p>Main component Code:</p>
<pre><code>import { Component, ViewChild } from '@angular/core';
import { ChildComponent } from './child/child.component';

@Component({
  selector: 'app-root',
  template: `
    &lt;button type=&quot;button&quot; (click)=&quot;update()&quot;&gt;Update&lt;/button&gt;
    &lt;br&gt;
    &lt;app-child&gt;&lt;/app-child&gt;`
})
export class AppComponent {
  @ViewChild(ChildComponent, { static: false })
  private childComponent!: ChildComponent;
    
  flag=false;
  update() {
        this.childComponent.updateTimeStamp();
        this.flag=true;
      }
}
</code></pre>
<p>Unit test code:
Issue is when I try to supply mock object for app.childComponent in below code. Though it works if I add // @ts-ignore but I don't think its correct. There must be a way to mock private ViewChild component.</p>
<pre><code>import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () =&gt; {
  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent
      ]
    }).compileComponents();
  });

  
  it('should call update', () =&gt; {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.componentInstance;
    expect(app.flag).toBe(false);
   **// app.update(); //fails**
  });
</code></pre>
<p>if it would have been non-private member, I could mock the child component like this.</p>
<pre><code>  it('should call update', () =&gt; {
     const fixture = TestBed.createComponent(AppComponent);
     const app = fixture.componentInstance;
     app.childComponent = &lt;ChildComponent&gt;{updateTimeStamp:()=&gt;{}}
     expect(app.flag).toBe(false);
     app.update(); 
     expect(app.flag).toBe(true);
   });


});
</code></pre>
",https://stackoverflow.com/questions/73985408/unit-testing-for-component-with-private-viewchild-child-component,"['angular', 'unit-testing', 'angular-test']",201,False,0,1
Airlfow API : testing tasks with parameters,"<p>I can't figure out how to use pytest to test a dag task waiting for xcom_arg.</p>
<p>I created the following DAG using the new airflow API syntax :</p>
<pre class=""lang-py prettyprint-override""><code> 
@dag(...)
def transfer_files():

  @task()
  def retrieve_existing_files():
    existing = []

    for elem in os.listdir(&quot;./backup&quot;):
      existing.append(elem)
    return existing

  @task()
  def get_new_file_to_sync(existing: list[str]):
    new_files = []

    for elem in os.listdir(&quot;./prod&quot;):
      if not elem in existing:
        new_files.append(elem)
    return new_files

  r = retrieve_existing_files()
  get_new_file_to_sync(r)

</code></pre>
<p>Now I want to perform unit testing on the <code>get_new_file_to_sync</code> task. I wrote the following test :</p>
<pre class=""lang-py prettyprint-override""><code>def test_get_new_elan_list():
    mocked_existing = [&quot;a.out&quot;, &quot;b.out&quot;]

    dag_bag = DagBag(include_examples=False)
    dag = dag_bag.get_dag(&quot;transfer_files&quot;)

    task = dag.get_task(&quot;get_new_file_to_sync&quot;)
    result = task.execute({}, mocked_existing)

    print(result)

</code></pre>
<p>The test fails because <code>task.execute</code> is waiting for 2 parameters but 3 were given.</p>
<p>My issue is that I don't have any clue of how to proceed in order to test my tasks waiting for arguments with a mocked custom argument.</p>
<p>Thanks for your insights</p>
",https://stackoverflow.com/questions/73278777/airlfow-api-testing-tasks-with-parameters,"['python', 'airflow', 'pytest', 'etl']",401,True,0,2
How to test methods imported from other components or JS file,"<p>I don´t have much experience with unit testing.
What is the proper way to test a method imported from a JS file or from another component?</p>
<p>This is a sample component I created a localSum just to use on the test.</p>
<pre class=""lang-js prettyprint-override""><code>&lt;template&gt;
    &lt;div class=&quot;fixed-center text-center text-h2&quot;&gt;
        &lt;p&gt;{{ getSum }}&lt;/p&gt;
    &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import { sum } from './testComponent.js';

export default {
    name: 'TestComponent',
    data() {
        return {
            a: 10,
            b: 20
        }
    },
    computed: {
        getSum() {
            return sum(this.a, this.b);
        }
    },
    methods: {
        localSum(a, b) {
            return a + b;
        }
    }
};
&lt;/script&gt;
</code></pre>
<p>The JS file:</p>
<pre class=""lang-js prettyprint-override""><code>export function sum(a, b) {
    return a + b;
}
</code></pre>
<p>This is the test, maybe I should not be using <code>wrapper.vm</code> to access the method?
One note: On the real component I don't want to test the method directly, which is why I did not import <code>sum</code> from the JS file.</p>
<pre class=""lang-js prettyprint-override""><code>import { mount } from '@vue/test-utils';
import TestComponent from '@components/TestComponent.vue';

describe('Testing component', () =&gt; { 
    test('Testing local method', () =&gt; { 
        const wrapper = mount(TestComponent);

        expect(wrapper.vm.localSum(10, 20)).toBe(30);
    });

    test('Testing method from js file', () =&gt; { 
        const wrapper = mount(TestComponent);

        expect(wrapper.vm.getSum(10, 20)).toBe(30);
    });
});
</code></pre>
<p>Test result:</p>
<pre><code>Testing component
    ✓ Testing local method (6 ms)
    ✕ Testing method from js file (2 ms)

  ● Testing component › Testing method from js file

    TypeError: wrapper.vm.getSum is not a function
</code></pre>
<p>Thanks!</p>
",https://stackoverflow.com/questions/74215500/how-to-test-methods-imported-from-other-components-or-js-file,"['vuejs2', 'jestjs', 'vue-test-utils']",93,True,0,1
Unit testing - casting an OkResult. What happens if the object cannot be cast to OkResult?,"<p>I've just started Unit Testing and I'm having some trouble understanding how should I write them.</p>
<p>I have this code</p>
<pre><code>[Theory]
        [InlineData(&quot;00000000-0000-0000-0000-000000000001&quot;)]
        [InlineData(&quot;00000000-0000-0000-0000-000000000002&quot;)]
        public void Delete_Intern(Guid id)
        {
            _internService.Setup(x =&gt; x.Delete(It.IsAny&lt;Guid&gt;())).Returns(true);

            var actual = (OkResult) _internsController.DeleteIntern(id);
            Assert.True(actual is OkResult);
        }

        [Theory]
        [InlineData(&quot;00000000-0000-0000-0000-000000000000&quot;)]
        [InlineData(&quot;00000000-0000-0000-0000-000000000005&quot;)]
        public void Delete_Intern_ShouldFail(Guid id)
        {
            _internService.Setup(x =&gt; x.Delete(It.IsAny&lt;Guid&gt;())).Returns(false);

            var actual = (OkResult)_internsController.DeleteIntern(id);
            Assert.False(actual is OkResult);
        }
</code></pre>
<p>which tests this method:</p>
<pre><code>[HttpDelete(&quot;{id}&quot;)]
        public IActionResult DeleteIntern(Guid id)
        {
            bool deleted = _internService.Delete(id);
            if (deleted == false)
            {
                return NotFound(&quot;Intern cannot be found&quot;);
            }
            return Ok();
        }
</code></pre>
<p>how should I write the ShouldFail method so it will be able to do that cast?</p>
<p>Right now, I'm getting an exception, saying that I cannot cast an object of type NotFoundResult to an OkResult.</p>
<p>I tried casting it to ObjectResult, then checking if it is an OkResult. But it doesn't work, because OkResult cannot be cast to ObjectResult.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/71829187/unit-testing-casting-an-okresult-what-happens-if-the-object-cannot-be-cast-to,"['c#', 'asp.net', '.net', 'unit-testing', 'asp.net-core']",217,True,0,2
How to test keydown keystrokes for a directive on a textbox?,"<p>I have a directive that I created that limits the input to be from 1 - 5 and limits the value to only have one decimal point. I am trying to unit test this, but I get a failed test when I try to inject a keydown event--Expected '' to be '1'. So it is as if there were no keys entered for the test. I feel like I am missing something simple. I am new to Angular and unit-testing.</p>
<p><strong>limited-value.directive.spec.ts</strong></p>
<pre><code>import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LimitedValueDirective } from './limited-value.directive';

@Component({
  selector: 'app-test-container',
  template: `
  &lt;div&gt;
    &lt;label for=&quot;limitedValue&quot;&gt;Limited Value&lt;/label&gt;
    &lt;input id=&quot;limitedValue&quot; type=&quot;text&quot; class=&quot;form-control&quot; formControlName=&quot;LimitedValue&quot; appLimitedValue&gt;
  &lt;/div&gt;
  `
})
class MyComponent { }
let fixture: ComponentFixture&lt;MyComponent&gt;;

beforeEach(async () =&gt; {

  await TestBed.configureTestingModule({
    declarations: [ MyComponent, LimitedValueDirective ],
  }).compileComponents();

  fixture = TestBed.createComponent(MyComponent);
  fixture.detectChanges();
 });

 describe('LimitedValueDirective', () =&gt; {
  it('should be empty', () =&gt; {
    let inputElement:HTMLInputElement = fixture.debugElement.nativeElement.querySelector('input[type=text]');
    expect(inputElement.value).toBe('');
  });

  it('should be one digit', async () =&gt; {
    fixture.detectChanges();
    fixture.whenStable().then(() =&gt; {
      let inputElement:HTMLInputElement = fixture.debugElement.nativeElement.querySelector('input[type=text]');

      const event = new KeyboardEvent(&quot;keydown&quot;, {
        &quot;key&quot;: &quot;1&quot;
      });
      inputElement.dispatchEvent(event);

      fixture.detectChanges();
      expect(inputElement.value).toBe('1');
    });
  });
});
</code></pre>
<p><strong>limited-value.directive.ts</strong></p>
<pre><code>import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
  selector: '[appLimitedValue]'
})
export class LimitedValueDirective {
  @Input() value: string;
  private regex: RegExp = new RegExp(/^[1-4](\.[0-9])?$|^[1-5]\.$|^5$|^5\.0$/g);
  private el: HTMLInputElement;
  private specialKeys: Array&lt;string&gt; = [
    'Backspace',
    'Tab',
    'End',
    'Home',
    'ArrowLeft',
    'ArrowRight',
    'Del',
    'Delete',
  ];

  constructor(private elementRef: ElementRef) {
    this.el = this.elementRef.nativeElement;
  }

  ngOnInit() {}

  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    if ((this.specialKeys.indexOf(event.key) !== -1) || (event.ctrlKey &amp;&amp; (event.key == 'v' || event.key == 'c'))) {
      return;
    }

    let current: string = this.elementRef.nativeElement.value;
    const position = this.elementRef.nativeElement.selectionStart;
    const next: string = [
      current.slice(0, position),
      event.key == 'Decimal' ? '.' : event.key,
      current.slice(position),
    ].join('');

    if (next &amp;&amp; !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}
</code></pre>
",https://stackoverflow.com/questions/72290165/how-to-test-keydown-keystrokes-for-a-directive-on-a-textbox,"['angular', 'unit-testing', 'input', 'jasmine', 'keydown']",76,False,0,1
Does stub make tests fragile?,"<p>suppose our SUT(Class A) has a dependency(IDependency) and we create stub with canned answer for some operations(Method A that return bool value).</p>
<p>in this manner we reveal some implementation details of SUT (SUT Using Method A) and if we want refactor the SUT without breaking the original behavior(instead of method A using method B that this method return bool value too).</p>
<p>according to Vladimir Khorikov  book (unit testing) our test does not has resistant to refactor.</p>
<p>question is :
does Stubs make tests fragile?</p>
",https://stackoverflow.com/questions/74164091/does-stub-make-tests-fragile,"['unit-testing', 'testing', 'automated-tests', 'stub', 'test-double']",65,False,0,1
How to write Jest unit testing for Socket in node js,"<p>I am trying to write the unit testing in JEST for the socket, test cases are passed but the code is not covered on codeCoverageReport I am not sure where I have gone wrong and jest is completely new as I am in a learning stage please help me.</p>
<p>This is node js simple code of socket</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 express = require(""express"");
const app = express();
items = [];

const server = app.listen(3000, () =&gt; {
  console.log(""This is listening to the port"");
});

//Web Sockets
const io = require(""socket.io"")(server, {
  cors: {
    origin: ""http://localhost:4200"",
    methods: [""GET"", ""POST""],
  },
});
io.on(""connection"", (socket) =&gt; {
  console.log(""a user connected"");

  socket.on(""message"", (message) =&gt; {
    console.log(message);
    io.emit(""message"", `${message}`);
  });

  socket.on(""disconnect"", () =&gt; {
    console.log(""a user disconnected!"");
  });
});
module.exports = io;</code></pre>
</div>
</div>
</p>
<p>This is the test file for the Socket</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 io = require('socket.io-client')
const io_server = require('../src/socket/index');

describe('basic socket.io example', () =&gt; {

  let socket;

  beforeEach(() =&gt; {
    // Setup
    socket = io.connect('http://localhost:3000');

    socket.on('connect', () =&gt; {
      console.log('connected')
    });

    socket.on('disconnect', () =&gt; {
      console.log('disconnected...');
    });
  });

  afterEach((done) =&gt; {
    // Cleanup
    if (socket.connected) {
      socket.disconnect();
    }
    socket.close();
    done();
  });

  it('should communicate', () =&gt; {
    // once connected, emit Hello World

    // console.log(socket)
    socket.emit('echo', 'Hello World');

    socket.once('echo', (message) =&gt; {
      // Check that the message matches
      expect(message).to.equal('Hello World');
    });

    socket.on('connection', (socket) =&gt; {
      expect(socket).to.not.be.null;
    });
  });

});</code></pre>
</div>
</div>
</p>
<p>Below is the screenshot of the code coverage</p>
<p><a href=""https://i.stack.imgur.com/0s5xW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0s5xW.png"" alt=""enter image description here"" /></a></p>
<p>When I run the test case it is showing it has passed</p>
<p><a href=""https://i.stack.imgur.com/jit7O.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/jit7O.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73795747/how-to-write-jest-unit-testing-for-socket-in-node-js,"['node.js', 'unit-testing', 'jestjs', 'socket.io', 'code-coverage']",62,False,0,1
How to reset global variable on custom hook,"<p>I need to reset global variable on custom hook when unit testing React component. I have read few tutorials and StackOverflow answers to this simple task, but without luck to implement it correctly.</p>
<p><strong>The problem</strong></p>
<p>userInfo is undefined in the first and second test but when runs the third test userInfo is defined then on useEffect doesn't change the value... So my question is how to reset userInfo for each test.</p>
<pre><code>jest.resetModules // doesn't work
jest.isolateModules // doesn't work
</code></pre>
<p>My simplest possible setup for single test is as following:</p>
<p><strong>My Environment</strong></p>
<pre><code>&quot;jest&quot;: &quot;^24.9.0&quot;,
</code></pre>
<p><strong>My Hook</strong></p>
<pre><code>import {useState, useEffect} from &quot;react&quot;;

// This variable is an object save user info
let userInfo = null;

export default (authService) =&gt; {
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() =&gt; {
    if (userInfo !== null || authService === null) {
      return;
    }

    setLoading(true);
    authService
      ?.getUser()
      .then((response) =&gt; {
        userInfo = {owners: [{...response, cost_center: response.costCenter || &quot;N/A&quot;}]};
      })
      .catch(() =&gt; {
        setError({
          title: &quot;authService Error&quot;,
          message: &quot;Error getting user&quot;,
          status: 500
        });
      })
      .finally(() =&gt; setLoading(false));
  }, [authService]);

  return [userInfo, error, loading];
};
</code></pre>
<p><strong>My Test</strong></p>
<pre><code>import {renderHook} from &quot;@testing-library/react-hooks&quot;;
import * as sinon from &quot;sinon&quot;;
import {getSpyOfUseOktaAuth} from &quot;../../../__tests__/&quot;;
import {Info, InfoFromRequest, InfoWithNoCostCenter} from &quot;../../../__tests__/&quot;;

describe(&quot;useGetUserInfo&quot;, () =&gt; {
  let clock;

  beforeEach(() =&gt; {
    clock = sinon.useFakeTimers();
    jest.useFakeTimers();
  });

  afterAll(() =&gt; {
    clock.restore();
  });

  it(&quot;should set the error value after the getUserInfo function throws an error&quot;, async () =&gt; {
    const useGetUserInfo = require(&quot;../index&quot;).default;

    const errorMessage = {
      title: &quot;authService Error&quot;,
      message: &quot;Error getting user from&quot;,
      status: 500
    };

    const getAuthMock = getSpyOfUseAuth({
      Auth: {
        signOut: jest.fn(),
        getUser: jest.fn(async () =&gt; {
          throw new Error(&quot;Auth Error&quot;);
        })
      },
      authState: {}
    });

    const {result, rerender, waitForNextUpdate} = renderHook(() =&gt;
      useGetUserInfo(getAuthMock.results.Auth)
    );

    rerender();

    await waitForNextUpdate();

    expect(result.current[1]).toEqual(errorMessage);
    getAuthMock.instance.mockRestore();
  });

  it(&quot;should return the user info from after run the getUserInfo function&quot;, async () =&gt; {
    const useGetUserInfo = require(&quot;../index&quot;).default;

    let authService = null;

    const {result, rerender, waitForNextUpdate} = renderHook(() =&gt; useGetOktaUserInfo(authService));

    const getAuthMock = getSpyOfUseAuth({
      Auth: {
        signOut: jest.fn(),
        getUser: jest.fn(async () =&gt; Info)
      },
      authState: {}
    });

    authService = getAuthMock.results.Auth;

    rerender();

    await waitForNextUpdate();

    expect(result.current[0]).toEqual(InfoFromRequest);
    getAuthMock.instance.mockRestore();
  });

  it(&quot;should set cost_center as in data as N/A if costCenter is not defined in user info &quot;, async () =&gt; {
    const useGetUserInfo = require(&quot;../index&quot;).default;

    const getAuthMock = getSpyOfUseAuth({
      Auth: {
        signOut: jest.fn(),
        getUser: jest.fn(async () =&gt; InfoWithNoCostCenter)
      },
      authState: {}
    });

    const {result, rerender} = renderHook(() =&gt; useGetUserInfo(getAuthMock.results.Auth));

    rerender();

    expect(result.current[0].owners[0].cost_center).toEqual(&quot;N/A&quot;);
    getAuthMock.instance.mockRestore();
  });
});
</code></pre>
",https://stackoverflow.com/questions/70624206/how-to-reset-global-variable-on-custom-hook,"['jestjs', 'rect']",754,True,0,2
Next JS Unit test page with multiple components inside using jest,"<p>I'm trying to do unit testing for the first time. I want to test my <code>index.tsx</code> page with multiple components inside. My <code>index.tsx</code> page structure is like this</p>
<p><strong>index.tsx</strong></p>
<pre><code>return (
  &lt;div&gt;
    &lt;DefaultLayout
      meta={
        &lt;Meta
          title=&quot;&quot;
          description=&quot;&quot;
          canonical=&quot;https://www.com&quot;
        /&gt;
      }
    &gt;
      {!props.acceptCookie &amp;&amp; &lt;CookieConsent /&gt;}
      &lt;Header promo={props.promo} /&gt;
      &lt;HomeBody
        totalPostsToday={props.totalPostsToday}
        promo={props.promo}
        postData={props}
        partners={props.partners}
      /&gt;
      &lt;Footer /&gt;
    &lt;/DefaultLayout&gt;
  &lt;/div&gt;
)
</code></pre>
<p>If I run my test code I got an error says</p>
<blockquote>
<p>Uncaught [Error: Objects are not valid as a React child (found: object with keys {store,
....
If you meant to render a collection of children, use an array instead.</p>
</blockquote>
<p><strong>index.spec.tsx</strong></p>
<pre><code>import { act, render } from '@testing-library/react'
import { RouterContext } from 'next/dist/shared/lib/router-context'

import Index from '@/pages'
import { createMockRouter } from '@/test-utils/createMockRouter'
import { renderWithProviders } from '@/test-utils/reduxMockProvider'

describe('Index page', () =&gt; {
  test('should proper render components', async () =&gt; {
    await act(() =&gt; {
      render(
        &lt;RouterContext.Provider value={createMockRouter({})}&gt;
          {renderWithProviders(&lt;Index /&gt;)}
        &lt;/RouterContext.Provider&gt;
      )
    })
  })
})
</code></pre>
<p>Aside of my error, does my approach fine or is it better if I do isolation test per components?</p>
",https://stackoverflow.com/questions/73054335/next-js-unit-test-page-with-multiple-components-inside-using-jest,"['javascript', 'typescript', 'unit-testing', 'next.js']",262,False,0,0
Airlfow API : testing tasks with parameters,"<p>I can't figure out how to use pytest to test a dag task waiting for xcom_arg.</p>
<p>I created the following DAG using the new airflow API syntax :</p>
<pre class=""lang-py prettyprint-override""><code> 
@dag(...)
def transfer_files():

  @task()
  def retrieve_existing_files():
    existing = []

    for elem in os.listdir(&quot;./backup&quot;):
      existing.append(elem)
    return existing

  @task()
  def get_new_file_to_sync(existing: list[str]):
    new_files = []

    for elem in os.listdir(&quot;./prod&quot;):
      if not elem in existing:
        new_files.append(elem)
    return new_files

  r = retrieve_existing_files()
  get_new_file_to_sync(r)

</code></pre>
<p>Now I want to perform unit testing on the <code>get_new_file_to_sync</code> task. I wrote the following test :</p>
<pre class=""lang-py prettyprint-override""><code>def test_get_new_elan_list():
    mocked_existing = [&quot;a.out&quot;, &quot;b.out&quot;]

    dag_bag = DagBag(include_examples=False)
    dag = dag_bag.get_dag(&quot;transfer_files&quot;)

    task = dag.get_task(&quot;get_new_file_to_sync&quot;)
    result = task.execute({}, mocked_existing)

    print(result)

</code></pre>
<p>The test fails because <code>task.execute</code> is waiting for 2 parameters but 3 were given.</p>
<p>My issue is that I don't have any clue of how to proceed in order to test my tasks waiting for arguments with a mocked custom argument.</p>
<p>Thanks for your insights</p>
",https://stackoverflow.com/questions/73278777/airlfow-api-testing-tasks-with-parameters,"['python', 'airflow', 'pytest', 'etl']",401,True,0,2
How to test methods imported from other components or JS file,"<p>I don´t have much experience with unit testing.
What is the proper way to test a method imported from a JS file or from another component?</p>
<p>This is a sample component I created a localSum just to use on the test.</p>
<pre class=""lang-js prettyprint-override""><code>&lt;template&gt;
    &lt;div class=&quot;fixed-center text-center text-h2&quot;&gt;
        &lt;p&gt;{{ getSum }}&lt;/p&gt;
    &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import { sum } from './testComponent.js';

export default {
    name: 'TestComponent',
    data() {
        return {
            a: 10,
            b: 20
        }
    },
    computed: {
        getSum() {
            return sum(this.a, this.b);
        }
    },
    methods: {
        localSum(a, b) {
            return a + b;
        }
    }
};
&lt;/script&gt;
</code></pre>
<p>The JS file:</p>
<pre class=""lang-js prettyprint-override""><code>export function sum(a, b) {
    return a + b;
}
</code></pre>
<p>This is the test, maybe I should not be using <code>wrapper.vm</code> to access the method?
One note: On the real component I don't want to test the method directly, which is why I did not import <code>sum</code> from the JS file.</p>
<pre class=""lang-js prettyprint-override""><code>import { mount } from '@vue/test-utils';
import TestComponent from '@components/TestComponent.vue';

describe('Testing component', () =&gt; { 
    test('Testing local method', () =&gt; { 
        const wrapper = mount(TestComponent);

        expect(wrapper.vm.localSum(10, 20)).toBe(30);
    });

    test('Testing method from js file', () =&gt; { 
        const wrapper = mount(TestComponent);

        expect(wrapper.vm.getSum(10, 20)).toBe(30);
    });
});
</code></pre>
<p>Test result:</p>
<pre><code>Testing component
    ✓ Testing local method (6 ms)
    ✕ Testing method from js file (2 ms)

  ● Testing component › Testing method from js file

    TypeError: wrapper.vm.getSum is not a function
</code></pre>
<p>Thanks!</p>
",https://stackoverflow.com/questions/74215500/how-to-test-methods-imported-from-other-components-or-js-file,"['vuejs2', 'jestjs', 'vue-test-utils']",93,True,0,1
How to import and use kafka connect datagen in spark application,"<p>We need to perform unit testing for our real time streaming application written in scala-spark.</p>
<p>One option is to use embedded-Kafka for kafka test case simulation.</p>
<p>The other option is to use kafka connect datagen - <a href=""https://github.com/confluentinc/kafka-connect-datagen"" rel=""nofollow noreferrer"">https://github.com/confluentinc/kafka-connect-datagen</a></p>
<p>The examples found on various blogs include CLI option.</p>
<p>What i'm looking for is an example to import kafka connect datagen within scala application.</p>
<p>Appreciate help on any good resource on kafka connect datagen OR simulating streaming application within scala application</p>
",https://stackoverflow.com/questions/71425859/how-to-import-and-use-kafka-connect-datagen-in-spark-application,"['scala', 'unit-testing', 'apache-kafka', 'apache-kafka-connect']",36,False,0,1
Run Python script unit testing - Selenium,"<p>I am a junior developer and totally new to Python and Selenium. I have to learn unit testing. They shared a small repository as an example. As required I installed Python and Selenium, but I don't know how to run. I have looked some tutorials, they just installed Python and Selenium, and added chromedriver, that's it. I have completed same steps, added PYTHONPATH and everything. But still getting errors.</p>
<p>My PYTHONPATH variable <code>C:\Users\yanke\altrium-systemtests\altsys</code></p>
<p><strong>Readme.md</strong></p>
<pre><code>System tests for Altrium frontend.

Install Python

export PYTHONPATH=&quot;.&quot;
python altsys/tests.py
</code></pre>
<p><strong>tests.py</strong></p>
<pre><code>&quot;&quot;Test altrium portal&quot;&quot;&quot;
import unittest
from selenium import webdriver

from altsys.selenium_helpers import sreenshot_on_fail

from altsys.page import AltriumPage


@sreenshot_on_fail()
class LoginTest(unittest.TestCase):
    &quot;&quot;&quot;Test altrium portal login

    Args:
        unittest ([type]): [description]
    &quot;&quot;&quot;
    def setUp(self) -&gt; None:
        self.driver = webdriver.Chrome()
        # self.driver = webdriver.Firefox()
        self.page = AltriumPage(self.driver, 'https://alpha.altrium.sg/login')

    def test_login(self):
        &quot;&quot;&quot;Test login
        &quot;&quot;&quot;
        self.page.login(
            'tdrobiszewski+st@gmail.com',
            'TestPassword123!'
            )

        # SLACK_TOKEN = 'xoxb-1178000328886-3062418273846-EIxTJ17QSbELkwB7WnbfHuFr'

if __name__ == '__main__':
    unittest.main()

</code></pre>
<p><em><strong>When I run I am getting these errors:</strong></em></p>
<pre><code>Error
Traceback (most recent call last):
  File &quot;C:\Program Files\Python310\lib\unittest\loader.py&quot;, line 34, in testFailure
    raise self._exception
ImportError: Failed to import test module: tests
Traceback (most recent call last):
  File &quot;C:\Program Files\Python310\lib\unittest\loader.py&quot;, line 154, in loadTestsFromName
    module = __import__(module_name)
  File &quot;C:\Users\yanke\altrium-systemtests\altsys\tests.py&quot;, line 5, in &lt;module&gt;
    from altsys.selenium_helpers import sreenshot_on_fail
  File &quot;C:\Users\yanke\altrium-systemtests\altsys\selenium_helpers.py&quot;, line 3, in &lt;module&gt;
    from slack_sdk import WebClient
ModuleNotFoundError: No module named 'slack_sdk'







Ran 1 test in 0.006s

FAILED (errors=1)

Process finished with exit code 1
</code></pre>
<p><em><strong>On Terminal</strong></em></p>
<pre><code>Traceback (most recent call last):
  File &quot;C:\Users\yanke\altrium-systemtests\altsys\tests.py&quot;, line 5, in &lt;module&gt;
    from altsys.selenium_helpers import sreenshot_on_fail
ModuleNotFoundError: No module named 'altsys'
</code></pre>
",https://stackoverflow.com/questions/73660710/run-python-script-unit-testing-selenium,"['python', 'selenium', 'unit-testing', 'testing', 'automated-tests']",45,False,0,0
Jasmine - how to test functions that should only be called once (executed via a closure variable),"<p>I'm using a closure to ensure that something is only called once:</p>
<pre><code>var pageDOM = (function() {
  var mounted = false

  return {
    initializePage: function() {
      if (mounted == false) {
        pageDOM.addBoxes();
        mount = true
      }
      pageDOM.otherInitProcedures();
    },
    otherFunction: function() {
    }
  }
})();
</code></pre>
<p>I'm not sure what's the right way of thinking about unit testing <code>pageDOM.initializePage</code>. Jasmine specs are run in random order, and I think it's important to keep this for testing integrity (i.e., I would NOT want to impose order). This is my spec code:</p>
<pre><code>describe(&quot;pageDOM&quot;, function() {
  describe(&quot;initializePage&quot;, function() {
    beforeEach(function() {
      spyOn(pageDOM, &quot;addBoxes&quot;)
      spyOn(pageDOM, &quot;otherInitProcedures&quot;)
    })
    describe(&quot;calling initializePage first time&quot;, function() {
      beforeEach(function() {
        pageDOM.initializePage();
      })
      it(&quot;should call both functions&quot;, function() {
        expect(pageDOM.otherInitProcedures).toHaveBeenCalled()
        expect(pageDOM.addBoxes).toHaveBeenCalled()
      })
      describe(&quot;calling initializePage again&quot;, function() {
        beforeEach(function() {
          pageDOM.initializePage();
        })
        it(&quot;should only call otherInitProcedures&quot;, function() {
          expect(pageDOM.otherInitProcedures).toHaveBeenCalled()
          expect(pageDOM.addBoxes).not.toHaveBeenCalled()
        })
      })
    })
  })
})
</code></pre>
<p>The problem is that if the specs don't run in order, then both will fail. What's a way to test this, or should I even try to test this?</p>
",https://stackoverflow.com/questions/71002371/jasmine-how-to-test-functions-that-should-only-be-called-once-executed-via-a,"['javascript', 'jasmine']",420,False,0,3
Node js stubbing issue,"<p>So, I am trying to write unit tests for a lambda handler. It is just a classic <code>exports.handler</code>
function expression.I require this using <code>const {handler}=require( &quot;.&quot;)</code>. Just after requiring it, there's a const which makes an api call to a third party service to obtain few details for further processing.</p>
<p>At my unit testing side, I am running into Assertion error of not passing the required key for that third party service.</p>
<pre><code>const analytics = new Analytics(process.env.yourWritekey, analyticsOptions);

exports.handler=async(event,context,callback)=&gt;{

  //this part is business logic
}
</code></pre>
<p>So my question is , how did I just test the handler by stubbing the third party api call?</p>
",https://stackoverflow.com/questions/73768824/node-js-stubbing-issue,"['node.js', 'unit-testing', 'mocking', 'stub']",16,False,0,0
Junit Test failing for Reactive Transaction with Spring-TransactionalOperator,"<p>I am using Spring reactive and want transactional behavior in saving data into two different tables. I have used .as(operator::transactional). I am facing issue while doing Unit Testing</p>
<h2>DAO Class Code with autowired Repositories &amp; TransactionalOperator:</h2>
<pre><code>var transactionDetails = getTransactionDetails(txnDetailsRequest, accountDetailsRequest, httpReqHeaders);
    var accountProcessingDetails = getAccountProcessingDetails(accountDetailsRequest);
    var response = transactionDetailsRepository.save(transactionDetails)
            .then(accountProcessingDetailsRepository.save(accountProcessingDetails))
            .onErrorMap(DataAccessException.class, handleDataAccessException)
            .onErrorMap(SocketTimeoutException.class, timeOutException)
            .as(operator::transactional)                
            .then(Mono.just(&quot;Insertion Successful&quot;));
</code></pre>
<hr />
<h2>Test case code:</h2>
<pre><code>@Test
public void test() {
    
    TransactionDetails transactionDetails =  TestHelper.createTransactionDetails();
    
    when(transactionDetailsRepository.save(any(TransactionDetails.class)))
    .thenReturn(Mono.just(transactionDetails));
    
    var accountProcessingDetails = TestHelper.createAccountProcessingDetails();
    
    when(accountProcessingDetailsRepository.save(any(AccountProcessingDetails.class)))
    .thenReturn(Mono.just(accountProcessingDetails));
    
    var txnEligibilityRequest = TestHelper.getTransactionsEligibilityRequest();
    Map&lt;String, String&gt; headerMap = TestHelper.getHeaderMap();
    
    var responseMono = transactionDetailsDAOImpl.saveTransactionDetails(txnEligibilityRequest.getDataRequest().getTxnDetailsRequestList().get(0),
            txnEligibilityRequest.getDataRequest().getAccountDetailsRequest(), headerMap);
    
    StepVerifier.create(responseMono).assertNext(response -&gt; {
        assertEquals(response, &quot;Insertion Successful&quot;);
    }).verifyComplete();
    
}
</code></pre>
<hr />
<p>While running the test case I'm getting the following error, on the line <code>.then(Mono.just(&quot;Insertion Successful&quot;));</code>:</p>
<p>java.lang.NullPointerException: Cannot invoke &quot;reactor.core.publisher.Mono.then(reactor.core.publisher.Mono)&quot; because the return value of &quot;reactor.core.publisher.Mono.as(java.util.function.Function)&quot; is null</p>
<hr />
<p>Can someone help in this issue:</p>
<ul>
<li>What's wrong in the current code?</li>
<li>How to mock the org.springframework.transaction.reactive.TransactionalOperator object?</li>
</ul>
",https://stackoverflow.com/questions/73500312/junit-test-failing-for-reactive-transaction-with-spring-transactionaloperator,"['spring-boot', 'junit', 'mockito', 'spring-webflux']",228,False,0,0
Is there a way in React to test whether or not a Functional Component calls a particular custom hook?,"<pre><code>describe(&quot;UI Logic&quot;, () =&gt; {
    it(&quot;Uses useEmailMultiSelectCustomHook&quot;, () =&gt; {
        const component = render(&lt;EmailMultiSelectCombobox/&gt;);
        const hook = jest.mock(&quot;./useEmailMultiSelectCombobox&quot;, () =&gt; ({
            useEmailMuliSelect: () =&gt; {
                return {
                    initialConditions: [&quot;test&quot;, &quot;test1&quot;, &quot;test2&quot;]
                }
            }
        }));
        
        const hookTest = renderHook(useEmailMultiSelectCombobox);
        expect(hookTest).toHaveBeenCalledTimes(1);
    });
})
</code></pre>
<pre><code>export const EmailMultiSelectCombobox = () =&gt; {
    const { initialConditions } = useEmailMultiSelectCombobox();
    
    
    return (
        &lt;&gt;
            {/*&lt;MultiSelectCombobox initialConditions={} handleSelectionChange={}/&gt;*/}
        &lt;/&gt;
    )
};
</code></pre>
<pre><code>export const useEmailMultiSelectCombobox = () =&gt; {
    const [initialConditions, setInitialConditions] = useState&lt;Array&lt;string&gt;&gt;([]);
    
    
    return { initialConditions };

}
</code></pre>
<p>So, I have a superrrr basic setup here. All I'm trying to do is test whether or not the hook was called/initialized from the component that I want to use the custom hook. The idea here is to be able to truly unit test a custom hook apart from unit testing a view. Most things I've seen really involve an integration test with a component view layer and a component logic layer being tested together, using the user-events library that comes with the testing library.</p>
",https://stackoverflow.com/questions/74746144/is-there-a-way-in-react-to-test-whether-or-not-a-functional-component-calls-a-pa,"['reactjs', 'unit-testing', 'tdd', 'react-functional-component', 'react-custom-hooks']",49,False,0,1
Is HTML covered in Angular default testing?,"<p>I have recently started working with Angular testing, I made a component using Material Angular auto Complete and I have conditional rendering inside it.</p>
<p>I am using Karma and Jasmine for unit testing.
This is the following output.</p>
<pre><code>Chrome Headless 103.0.5060.114 (Windows 10): Executed 5 of 5 SUCCESS (0.219 secs / 0.186 secs)
TOTAL: 5 SUCCESS

=============================== Coverage summary ===============================
Statements   : 100% ( 20/20 )
Branches     : 100% ( 1/1 )
Functions    : 100% ( 9/9 )
Lines        : 100% ( 19/19 )
================================================================================
</code></pre>
<p>When I did the testing, it says the testing is 100%, So one would only assume everything is tested.</p>
<p><strong>Html file</strong></p>
<pre><code>&lt;mat-form-field
  [ngStyle]=&quot;ngStyle&quot;
  appearance=&quot;outline&quot;
  class=&quot;primary-autoSelect&quot;
  floatLabel=&quot;always&quot;
&gt;
  &lt;mat-label&gt;{{ label }}&lt;/mat-label&gt;
  &lt;input
    type=&quot;text&quot;
    [placeholder]=&quot;placeholder&quot;
    matInput
    [formControl]=&quot;autoSelectFormControl&quot;
    [matAutocomplete]=&quot;auto&quot;
    (blur)=&quot;
      onBlur();
      blurExtension(
        autoSelectFormControl.value,
        autoSelectFormControl.valid &amp;&amp; autoSelectFormControl.touched
      )
    &quot;
  /&gt;
  &lt;mat-autocomplete #auto=&quot;matAutocomplete&quot;&gt;
    &lt;mat-option
      id=&quot;options&quot;
      *ngFor=&quot;let option of filteredOptions&quot;
      [value]=&quot;option.key&quot;
    &gt;
      {{ option.key }}
    &lt;/mat-option&gt;
  &lt;/mat-autocomplete&gt;
  &lt;mat-error *ngIf=&quot;autoSelectFormControl.hasError('required')&quot;&gt;
    {{ label }} is required
  &lt;/mat-error&gt;
  &lt;mat-error
    *ngIf=&quot;
      autoSelectFormControl.hasError('validAutoCompleteOption') &amp;&amp;
      !autoSelectFormControl.hasError('required')
    &quot;
  &gt;
    Please select a value from the list {{ label }}
  &lt;/mat-error&gt;
&lt;/mat-form-field&gt;
</code></pre>
<p><strong>TS file</strong></p>
<pre><code>interface Options {
  key: string;
  value: string;
}

@Component({
  selector: 'app-primary-auto-complete',
  templateUrl: './primary-auto-complete.component.html',
  styleUrls: ['./primary-auto-complete.component.css'],
})
export class PrimaryAutoCompleteComponent implements OnInit, OnChanges {
  @Input() label: string = '';
  @Input() placeholder: string = 'Start typing here';
  @Input() options: Options[] = [];
  @Input() ngStyle: { [Klass: string]: any } | null = null;
  @Input() blurExtension: (value: string, isValid: boolean) =&gt; void = () =&gt; {};

  @Input() autoSelectFormControl: FormControl = new FormControl('');

  filteredOptions: Options[] = [];

  // @ts-ignore
  @ViewChild('auto') autocomplete: MatAutocomplete;

  constructor() {}

  // When options are updated after the API call, triggers itself to update the filtered options
  ngOnChanges(changes: SimpleChanges): void {
    this.filteredOptions = this._filter(this.autoSelectFormControl.value);
  }

  ngOnInit() {
    this.autoSelectFormControl.valueChanges.subscribe((value) =&gt; {
      this.filteredOptions = this._filter(value);
    });
  }

  // Clears the option if it is a wrong one
  onBlur = (): void =&gt; {
    this.options.some((item) =&gt; {
      if (
        item.key.toLowerCase() ===
        this.autoSelectFormControl.value.toLowerCase()
      )
        this.autoSelectFormControl.setValue(item.key);
    });
  };

  private _filter(value: string): {
    key: string;
    value: string;
  }[] {
    const filterValue = value.toLowerCase();

    return this.options.filter((item) =&gt;
      item.key.toLowerCase().startsWith(filterValue)
    );
  }
}
</code></pre>
<p><strong>Test file</strong></p>
<pre><code>import { Component, SimpleChange, ViewChild } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule, ValidationErrors } from '@angular/forms';
import {
  MatAutocomplete,
  MatAutocompleteModule,
} from '@angular/material/autocomplete';
import { MatOption } from '@angular/material/core';
import { MatError, MatFormField, MatLabel } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { By } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { states } from 'src/app/constants/states';

import { PrimaryAutoCompleteComponent } from './primary-auto-complete.component';

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

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [
        PrimaryAutoCompleteComponent,
        MatAutocomplete,
        MatFormField,
        MatLabel,
        MatOption,
        MatError,
      ],
      imports: [
        ReactiveFormsModule,
        MatInputModule,
        BrowserAnimationsModule,
        MatAutocompleteModule,
      ],
    }).compileComponents();
  });

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

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

  describe(`When value 'Pu' is inserted into the input`, () =&gt; {
    it('should filter the options and remaining options should be 2', async () =&gt; {
      const stateList: {
        key: string;
        value: string;
      }[] = states.map((states) =&gt; {
        return {
          key: states.value,
          value: states.value,
        };
      });
      component.options = stateList;
      fixture.detectChanges();
      const inputElement = fixture.debugElement.query(By.css('input'));
      inputElement.nativeElement.dispatchEvent(new Event('focusin'));
      inputElement.nativeElement.value = 'pu';
      inputElement.nativeElement.dispatchEvent(new Event('input'));

      fixture.detectChanges();
      await fixture.whenStable();
      fixture.detectChanges();

      const matOptions = document.querySelectorAll('mat-option');
      expect(matOptions.length).toBe(
        2,
        'Expect to have less options after input text and filter'
      );
    });
  });

  describe(`When value 'Pu' is inserted into the input and Punjab is clicked`, () =&gt; {
    it('should filter the options and remaining options should be 2', async () =&gt; {
      const stateList: {
        key: string;
        value: string;
      }[] = states.map((states) =&gt; {
        return {
          key: states.value,
          value: states.value,
        };
      });
      component.options = stateList;
      fixture.detectChanges();
      const inputElement = fixture.debugElement.query(By.css('input'));
      inputElement.nativeElement.dispatchEvent(new Event('focusin'));
      inputElement.nativeElement.value = 'pu';
      inputElement.nativeElement.dispatchEvent(new Event('input'));

      fixture.detectChanges();
      await fixture.whenStable();
      fixture.detectChanges();

      const matOptions = document.querySelectorAll('mat-option');
      expect(matOptions.length).toBe(
        2,
        'Expect to have less options after input text and filter'
      );

      const optionToClick = matOptions[1] as HTMLElement;
      optionToClick.click();

      // Testing onChange call
      component.ngOnChanges({
        options: new SimpleChange(null, [], true),
      });

      fixture.detectChanges();
      await fixture.whenStable();
      fixture.detectChanges();
      // With this expect statement we verify both, proper type of event and value in it being emitted
      expect(inputElement.nativeElement.value).toBe('Punjab');
    });
  });

  describe(`When value 'punjab' is inserted into the input and on Blur is called`, () =&gt; {
    it(`should change the input value to 'Punjab'`, async () =&gt; {
      const stateList: {
        key: string;
        value: string;
      }[] = states.map((states) =&gt; {
        return {
          key: states.value,
          value: states.value,
        };
      });

      component.options = stateList;

      fixture.detectChanges();
      const inputElement = fixture.debugElement.query(By.css('input'));
      inputElement.nativeElement.dispatchEvent(new Event('focusin'));
      inputElement.nativeElement.value = 'punjab';
      inputElement.nativeElement.dispatchEvent(new Event('input'));

      fixture.detectChanges();
      await fixture.whenStable().then(() =&gt; {
        inputElement.nativeElement.dispatchEvent(new Event('blur'));
      });

      fixture.detectChanges();
      await fixture.whenStable();

      // With this expect statement we verify both, proper type of event and value in it being emitted
      expect(inputElement.nativeElement.value).toBe('Punjab');
    });
  });

  describe(`When notjing is inserted into the input and blur event is triggered`, () =&gt; {
    it('should have the required error inside the form control and render mat-error', async () =&gt; {
      const stateList: {
        key: string;
        value: string;
      }[] = states.map((states) =&gt; {
        return {
          key: states.value,
          value: states.value,
        };
      });
      component.options = stateList;
      fixture.detectChanges();
      const inputElement = fixture.debugElement.query(By.css('input'));
      inputElement.nativeElement.dispatchEvent(new Event('focusin'));
      // inputElement.nativeElement.value = 'pu';
      // inputElement.nativeElement.dispatchEvent(new Event('input'));

      // should not exist
      const errorElement = fixture.debugElement.query(By.css('mat-error'));
      expect(errorElement).toBeNull();

      component.autoSelectFormControl.setErrors({
        required: true,
      } as ValidationErrors);
      component.autoSelectFormControl.markAsTouched();
      component.autoSelectFormControl.markAsDirty();

      fixture.detectChanges();
      await fixture.whenStable().then(() =&gt; {
        inputElement.nativeElement.dispatchEvent(new Event('blur'));
      });

      fixture.detectChanges();
      await fixture.whenStable().then(() =&gt; {
        expect(errorElement).toBeNull();
      });
      fixture.detectChanges();

      expect(component.autoSelectFormControl.hasError('required')).toBe(true);
    });
  });
});
</code></pre>
<p>But is it really 100% tested? I have not tested the case where error comes and it renders mat-error. Any advice is appreciated.</p>
",https://stackoverflow.com/questions/72935810/is-html-covered-in-angular-default-testing,"['angular', 'testing', 'angular-unit-test']",40,False,0,0
react test-utils does not render any change after act,"<p>I'm trying to test a react component which contains a form and a button click which converts the form into edit mode.  My problem is that after the click the event seems to fire ok and the form changes to edit mode, but there is no change in the test ui when unit testing.  When I actually run the application through the browser the change happens.</p>
<p>This is what my unit test code looks like</p>
<pre><code>it.only('should display the edit page when the edit button is clicked', async () =&gt; {
    let r: any
    act(() =&gt; {
        r = render(
            &lt;MemoryRouter initialEntries={['/tickets/1']}&gt;
                &lt;Routes&gt;
                    &lt;Route path='tickets/:ticketId' element={&lt;TicketDetailPage /&gt;}&gt;&lt;/Route&gt;
                &lt;/Routes&gt;
            &lt;/MemoryRouter&gt;
        )
    })


    act(() =&gt; {
        const button = screen.getByTestId('editTicket')
        userEvent.click(button); // this is where I simulate the click, I also tried  button.dispatchEvent(new MouseEvent('click', {bubbles: true})); but with the same result.
    })

    console.log(r.baseElement.outerHTML)  // when I look at the html it has not been updated
    expect(r.baseElement.outerHTML).toMatchSnapshot()
})
</code></pre>
<p>This is the code that fires when the button is clicked</p>
<pre><code>const onSubmit: SubmitHandler&lt;Inputs&gt; = data =&gt; {
    if (!isEditMode) { // set the edit mode
        setEditMode(true)
    } else { // save the changes
        dispatch&lt;any&gt;(saveTicket({
            id: ticketId!,
            description: data.description,
            owner: data.owner,
            title: data.title
        }));
        setEditMode(false)
    }
}
</code></pre>
",https://stackoverflow.com/questions/73327785/react-test-utils-does-not-render-any-change-after-act,"['reactjs', 'react-testing-library']",221,False,0,0
"testcontainers-python hanging while showing &quot;waiting to be ready...&quot;, then fails","<p>I'm running my unit testing code for neo4j.
My environment:
Ubuntu 20.04LTS server
1Gb Memory
1CPU</p>
<p>Here is what is displayed in the console:</p>
<pre><code>====================================== test session starts ======================================
platform linux -- Python 3.8.10, pytest-7.1.2, pluggy-1.0.0
rootdir: ~/morsvq, configfile: pytest.ini
plugins: mock-3.8.2
collected 2 items

---------------------------------------- live log setup -----------------------------------------
INFO     testcontainers.core.container:container.py:52 Pulling image neo4j:latest
INFO     testcontainers.core.container:container.py:63 Container started: ad7963ed01
INFO     testcontainers.core.waiting_utils:waiting_utils.py:46 Waiting to be ready...
INFO     testcontainers.core.waiting_utils:waiting_utils.py:46 Waiting to be ready...
ERROR    neo4j:__init__.py:571 Failed to read from defunct connection IPv4Address(('localhost', 49153)) (IPv4Address(('127.0.0.1', 49153)))
</code></pre>
<p>The same code runs successfully on a faster virtual machine with 8Gb Memory. So the code itself shouldn't be faulty. My suspision is that there is something to do with my configuration, so that it now consumes to much memory?</p>
<p>I've checked the official websites' documentation, but it doesn't mention the memory problem. I wonder if someone has encountered similar problem? How to fix this?</p>
",https://stackoverflow.com/questions/73424146/testcontainers-python-hanging-while-showing-waiting-to-be-ready-then-fails,"['docker-container', 'testcontainers']",269,True,1,1
How to try doctesting in play.rust-lang.org? Rust Doctest example doesn&#39;t work,"<p>The doctest example off Rust-lang's rust-by-example page doesn't work, ironically hehe. How do I use doctesting? I successfully learned how to do unit testing in Rust, the chapter before doctesting.
<a href=""https://doc.rust-lang.org/rust-by-example/testing/doc_testing.html"" rel=""nofollow noreferrer"">https://doc.rust-lang.org/rust-by-example/testing/doc_testing.html</a></p>
<pre><code>fn main() {
    println!(&quot;Hello 3+2: {}&quot;, add(3,2));
}

/// First line is a short summary describing function.
///
/// The next lines present detailed documentation. Code blocks start with
/// triple backquotes and have implicit `fn main()` inside
/// and `extern crate &lt;cratename&gt;`. Assume we're testing `doccomments` crate:
///
/// ```
/// let result = doccomments::add(2, 3);
/// assert_eq!(result, 5);
/// ```
pub fn add(a: i32, b: i32) -&gt; i32 {
    a + b
}
</code></pre>
<p><a href=""https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=643def7ce943cca11820b379d671e21e"" rel=""nofollow noreferrer"">https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2021&amp;gist=643def7ce943cca11820b379d671e21e</a></p>
<h1>Expected Results</h1>
<p>Doctest to run (and pass or fail accordingly)</p>
<h1>Actual Results</h1>
<p>Doctest doesn't run. Not sure if it's possible to run a doctest in the rust playground due to this crate/module error.</p>
<h2>when ran (equivalent to <code>cargo run</code>)</h2>
<p>stdout:</p>
<pre><code>Hello 3+2: 5
</code></pre>
<p>stderr:</p>
<pre><code>Compiling playground v0.0.1 (/playground)
    Finished dev [unoptimized + debuginfo] target(s) in 0.70s
     Running `target/debug/playground`
</code></pre>
<h2>when tested (equivalent to <code>cargo test</code>)</h2>
<p>stdout:</p>
<pre><code>running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s


running 1 test
test src/lib.rs - add (line 11) ... FAILED

failures:

---- src/lib.rs - add (line 11) stdout ----
error[E0433]: failed to resolve: use of undeclared crate or module `doccomments`
 --&gt; src/lib.rs:12:14
  |
3 | let result = doccomments::add(2, 3);
  |              ^^^^^^^^^^^ use of undeclared crate or module `doccomments`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0433`.
Couldn't compile the test.

failures:
    src/lib.rs - add (line 11)

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.21s

</code></pre>
<p>stderr:</p>
<pre><code>   Compiling playground v0.0.1 (/playground)
warning: function `main` is never used
 --&gt; src/lib.rs:1:4
  |
1 | fn main() {
  |    ^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: `playground` (lib) generated 1 warning
    Finished test [unoptimized + debuginfo] target(s) in 0.66s
     Running unittests src/lib.rs (target/debug/deps/playground-a7fbc171eada2644)
   Doc-tests playground
error: doctest failed, to rerun pass `--doc`
</code></pre>
",https://stackoverflow.com/questions/74867819/how-to-try-doctesting-in-play-rust-lang-org-rust-doctest-example-doesnt-work,"['rust', 'rustdoc']",94,True,1,1
What and how to test an app using SQLAlchemy?,"<p>I am developing an app using SQLAlchemy and I have to unit test it. The answer probably exist on internet but after HOURS of research I cant find it. The only thing I find every time I search about unit testing SQLAlchemy is how to test the ORM.</p>
<p>Let's imagine I have this tables.py :</p>
<pre><code>Base = declarative_base()

class User(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key=True)
    name = Column(String(45), nullable=False, unique=True)
    group_id = Column(Integer, ForeignKey(&quot;group.id&quot;))


class Group(Base):
    __tablename__ = 'group'

    id = Column(Integer, primary_key=True)
    name = Column(String(45), nullable=False, unique=True)

</code></pre>
<p>And this is queries.py :</p>
<pre><code>def get_rows(table, options):

    get_object = session.query(table)

    if options.get(&quot;order&quot;):
        get_object = get_object.order_by(getattr(table, f'{options[&quot;order&quot;]}'))

    query = get_object

    try:
        return [row for row in query][0]
    except IndexError:
        return &quot;The objects are unknown.&quot;

</code></pre>
<p>Should I test the two tables ? If yes, if I have an application with 20 tables, should I test all those tables ? Should I test my queries.py ? If yes, how ?</p>
",https://stackoverflow.com/questions/71032070/what-and-how-to-test-an-app-using-sqlalchemy,"['python', 'unit-testing', 'sqlalchemy']",95,False,1,0
System.NullReferenceException when unit testing,"<p>I am new to unit testing,</p>
<p>I am working on a minimal API project. and I am testing an endpoint with xunit, moq</p>
<p>endpoint class - ParticipantsGetAll.cs</p>
<pre><code>public class ParticipantsGetAll : IEndpoint&lt;IResult, GetAllParticipantsRequest&gt;
{
    const string uri = &quot;api/participants-all&quot;;
    private ParticipantService? participantService;

    public void AddRoute(IEndpointRouteBuilder app)
    {
        app.MapPost(uri, async ( ParticipantService participantService, [FromBody] GetAllParticipantsRequest query) =&gt; 
        {
            this.participantService = participantService;
            return await HandleAsync(query);
        })
        .Produces&lt;List&lt;ParticipantSummaryModel&gt;&gt;()
        .WithTags(&quot;Participants&quot;)
        .WithName(&quot;GetAllParticipants&quot;);
    }

    public async Task&lt;IResult&gt; HandleAsync( GetAllParticipantsRequest query)
    {
        var participants = await participantService!.ListAllAsync(query);
        return Results.Ok(participants);
    }
</code></pre>
<p>I tried to write a unit test test above endpoint class.</p>
<p>CreateParticipantApiTest.cs</p>
<pre><code>    [Fact]
    public async void ListAllAsyncShouldReturn200Status()
    {
        var query = new GetAllParticipantsRequest()
        {
           Name= &quot;&quot;,
            KeyCordinator=&quot;&quot;,
            RelatedConnection=&quot;&quot;,
            Statuses = null

        };
        var participant = ParticipantMockData.NewParticipantModel(); // a static class

        var sut = new ParticipantsGetAll();
        var result = (OkObjectResult)await sut.HandleAsync(query);

        result.StatusCode.Should().Be(200);

    }
</code></pre>
<p>I got below error</p>
<blockquote>
<p>Message: 
System.NullReferenceException : Object reference not set to an instance of an object.<br />
Stack Trace: 
ParticipantsGetAll.HandleAsync(GetAllParticipantsRequest query) line 36
CreateParticipantApiTest.ListAllAsyncShouldReturn200Status() line 67</p>
</blockquote>
<p>I have no idea why the object tis null.</p>
<p>Please anyone help me to find the problem.
I am facing this issue for a long time</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/74866807/system-nullreferenceexception-when-unit-testing,"['c#', 'unit-testing', 'moq', '.net-6.0', 'minimal-apis']",228,True,1,1
ASP.NET MVC - IHtmlFormElement&#39;s GetSubmission returns null,"<p>I'm making a POST request through an MVC controller using ASP.NET MVC and while unit testing I'm getting 'Object reference not set to an instance of an Object' from an IHtmlFormElement's GetSubmission() method. The test finds the button and the button itself is not null, but when the test calls the GetSubmission() with the submit button as a parameter it returns null.</p>
<p>Everything works fine from browser.</p>
<p>This is my Add.cshtml file content:</p>
<pre><code>@model MVCPhones.Data.Phone

&lt;form method=&quot;post&quot; asp-action=&quot;Add&quot;&gt;

    &lt;div class=&quot;form-group&quot;&gt;
        &lt;label asp-for=&quot;Make&quot; class=&quot;control-label&quot;&gt;Make&lt;/label&gt;
        &lt;input asp-for=&quot;Make&quot; type=&quot;text&quot; class=&quot;form-control&quot; /&gt;
    &lt;/div&gt;
    &lt;div class=&quot;form-group&quot;&gt;
        &lt;label asp-for=&quot;Model&quot; class=&quot;control-label&quot;&gt;Model&lt;/label&gt;
        &lt;input asp-for=&quot;Model&quot; type=&quot;text&quot; class=&quot;form-control&quot; /&gt;
    &lt;/div&gt;
    &lt;div class=&quot;form-group&quot;&gt;
        &lt;label asp-for=&quot;RAM&quot; class=&quot;control-label&quot;&gt;RAM&lt;/label&gt;
        &lt;input asp-for=&quot;RAM&quot; type=&quot;number&quot; class=&quot;form-control&quot; /&gt;
    &lt;/div&gt;
    &lt;div class=&quot;form-group&quot;&gt;
        &lt;label asp-for=&quot;PublishDate&quot; class=&quot;control-label&quot;&gt;PublishDate&lt;/label&gt;
        &lt;input asp-for=&quot;PublishDate&quot; type=&quot;date&quot; class=&quot;form-control&quot; /&gt;
    &lt;/div&gt;
    &lt;button type=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;Submit&lt;/button&gt;
&lt;/form&gt;
</code></pre>
<p>Here is my PhonesController post method:</p>
<pre><code>        public async Task&lt;IActionResult&gt; Add(Phone phone)
        {
            try
            {
                phone.Created = DateTime.Now;
                phone.Modified = DateTime.Now;
                await _context.Phones.AddAsync(phone);
                await _context.SaveChangesAsync();

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }
</code></pre>
<p>Here is the section that gives the error:
<a href=""https://i.stack.imgur.com/ctSud.png"" rel=""nofollow noreferrer"">Error</a></p>
",https://stackoverflow.com/questions/73069937/asp-net-mvc-ihtmlformelements-getsubmission-returns-null,"['asp.net-mvc', 'forms', 'button', 'nullreferenceexception']",37,False,1,0
How to correctly send 403 error while testing file upload?,"<p>I'm using Nodejs Express Multer &amp; Mocha Chai for unit testing my API. I'm running into an issue :</p>
<p>I'm trying to test a route without the correct authorization. (I'm using express-jwt)</p>
<pre><code>    expressJwt({ secret: publicKey, algorithms:['RS256'] }),
    function(req, res, next) {
      if(PERMISSION_OK) {
        next();
      } else {
        return res.status(403).send({ errorMessage: &quot;Permission denied ! Clearance level not high enough !&quot; });
        // We're sending back the 403 error ! but Mocha &amp; chai gets ECONNRESET , Node &amp; Postman gets the error as expected
    }

</code></pre>
<p>This sample is simpler than the real one, but everything works fine in the authorization part.</p>
<p>So it seems that the .attach() in my tests is waiting the file to be treated, but it won't because we've already send back an Err:403. I'm stuck on this issue for several days now, any help would be nice !</p>
<p>Greetings</p>
<p>BDaniel</p>
",https://stackoverflow.com/questions/73402311/how-to-correctly-send-403-error-while-testing-file-upload,"['node.js', 'mocha.js', 'multer', 'chai']",203,False,1,0
How to start a gitlab pipeline job that fails when test coverage goes below a threshold,"<p>We have jest unit testing for our react app and need to set a threshold value of 80% test case coverage. I know that we can get the coverage report in <code>npm test -- --coverage --watchAll=false</code> but I am now tasked with failing the pipeline if the coverage goes below 80%.  I saw that there is a test pipeline stage which is commented right now.
I have the following script, I need to somehow get the coverage, and compare if it is 80 or more else fail the pipleline, what should I do</p>
<pre><code>test:
  stage: test
  image: node:16.13.1
  before_script:
    - npm i
    - npx node -v
    - npx npm -v
  script:
    - echo &quot;running test coverage&quot;
    - npm test -- --coverage --watchAll=false
  coverage: '/All files[^|]*\|[^|]*\s+([\d\.]+)/'
</code></pre>
",https://stackoverflow.com/questions/72666002/how-to-start-a-gitlab-pipeline-job-that-fails-when-test-coverage-goes-below-a-th,"['jestjs', 'gitlab', 'continuous-integration', 'gitlab-ci', 'continuous-deployment']",1285,True,1,1
How to separate development and production in python,"<p>I am developing a Python application to automate my tasks, I would like to have two separate environments, development and production, and in the future maybe a Web app environment or a CLI tool environment.</p>
<p>The development phase for example has modules for unit testing and API keys that I don't want to be shipped to production. Is it possible to have a <code>package.json</code> equivalent that can help me?</p>
<p>I also want to define the entry file that has to be executed first, which is <code>main.py</code> for my project, can this be achieved?</p>
",https://stackoverflow.com/questions/71275132/how-to-separate-development-and-production-in-python,"['python', 'unit-testing', 'devops', 'cicd']",876,True,1,1
xUnit fixtures classes for internal types,"<p>When unit testing classes with the <code>internal</code> access modifier, I can add the following to the <code>.csproj</code> file of the project under test:</p>
<pre><code>&lt;ItemGroup&gt;
  &lt;InternalsVisibleTo Include=&quot;[test_project_name]&quot;/&gt;
&lt;/ItemGroup&gt;
</code></pre>
<p>This works fine for any internal types in the original project, when they are being instantiated as private members of the test class, or as local variables in any of the test methods.</p>
<p>However, it can't work when trying to use them with fixtures, because these types need to be made public members of a public fixture class.</p>
<p>Is there a code pattern that allows me to declare my fixtures as internal?</p>
",https://stackoverflow.com/questions/74008985/xunit-fixtures-classes-for-internal-types,"['c#', 'xunit', 'fixtures']",327,False,1,0
Is there a way of unit testing what imports are used?,"<p>Is there a way of unit testing what modules are imported in a Python file (a bit like ArchUnit in Java)? The context is in implementing a hexagonal architecture and wanting to ensure that the domain model does not import any code that resides in an adapter. I'd like unit tests to fail if there are forbidden imports.</p>
<p>For example, I might like to test that no modules within <code>foo.bar.domain</code> import anything from <code>foo.bar.adapter</code>. Imports of <code>foo.bar.domain</code> should be allowed from within <code>foo.bar.adapter</code>.</p>
<p>Is this possible in Python and what's the best way of achieving this?</p>
",https://stackoverflow.com/questions/71369419/is-there-a-way-of-unit-testing-what-imports-are-used,"['python', 'unit-testing', 'hexagonal-architecture']",302,True,1,2
addItem unit test in php,"<p>I am trying to test if an item can be added to my shopping list. I am unsure of where I am going wrong and the error I am getting is:</p>
<pre><code>ArgumentCountError : Too few arguments to function Tests\Unit\Entities\ShoppingListTest::testAddItem(), 0 passed in
</code></pre>
<p>Which is confusing me because I have passed arguments where they are needed? I am new to unit testing and just need some guidance. I also realise that I may of picked the wrong assert to be called so any input on that would be helpful!
Here is my test:</p>
<pre><code> public function testAddItem(string $name): void
    {
        //Arrange: Given an item to add to the shopping list
        $items = [new ShoppingItem('lettuce')];
        $list = new ShoppingList('my-groceries', $items);

        //Act: Add the item to the list
         $list-&gt;addItem($name);

        //Assert: Check to see if the item was added to the list
        $this-&gt;assertContains($items, $list, 'Does not contain lettuce.');

    }
</code></pre>
<p>And here is my shopping list class that contains the function I am testing:</p>
<pre><code>class ShoppingList implements \iterable
{
    /**
     * @var string
     */
    private string $name;
    /**
     * @var ShoppingItem[]
     */
    private array $items;

    public function __construct(string $name, array $items)
    {
        $this-&gt;name = $name;
        foreach($items as $item) {
            if(!$item instanceof ShoppingItem) {
                throw new \InvalidArgumentException(&quot;Expecting only shopping items.&quot;);
            }
        }
        $this-&gt;items = $items;
    }

    public function getName(): string
    {
        return $this-&gt;name;
    }

    public function getItems(): array
    {
        return $this-&gt;items;
    }

    public function addItem(string $name): void
    {
        $item = new ShoppingItem($name);
        $this-&gt;items[] = $item;
    }

    public function checkOffItem(string $name): void
    {
        $item = $this-&gt;findItemByName($name);
        if($item) {
            $item-&gt;checkOffItem();
            return;
        }
        throw new \LogicException(&quot;There is no item on this list called $name.&quot;);
    }

    private function findItemByName(string $name): ?ShoppingItem
    {
        foreach($this-&gt;items as $item) {
            if($item-&gt;getName() === $name) {
                return $item;
            }
        }
        return null;
    }
</code></pre>
",https://stackoverflow.com/questions/71868585/additem-unit-test-in-php,"['php', 'unit-testing', 'oop']",43,True,1,1
Pass ref as context in react-testing-library with jest,"<p>I am trying my hand at unit testing and here is where I am stuck. The refs for inputs are saved in a global context and am trying to mock the context so I can test the components properly.</p>
<p>Issue is once of my components calls the <strong>focus()</strong> property from the ref and I am not sure how to mock the ref properly so even my test can use the <strong>focus()</strong> property.</p>
<p>This is my testing code:</p>
<pre><code>import { render as rtlRender, screen } from &quot;@testing-library/react&quot;;
import &quot;@testing-library/jest-dom&quot;;
import { Provider } from &quot;react-redux&quot;;
import store from &quot;../redux/store&quot;;
import { GlobalContextProvider } from &quot;../common/GlobalContext&quot;;
import { SalesContextProvider } from &quot;../Sales/SalesContext&quot;;

import PatientAutocomplete from &quot;../Sales/PatientAutocomplete&quot;;

const dummySalesContext = {
  patientRef: null,
};


const dummyGlobalContext = {
  currentComponent: &quot;demo&quot;,
  setEnableGlobalNavigation: jest.fn(),
};

const render = (component) =&gt;
  rtlRender(&lt;Provider store={store()}&gt;{component}&lt;/Provider&gt;);

test(&quot;renders learn react link&quot;, () =&gt; {
  render(
    &lt;GlobalContextProvider value={dummyGlobalContext}&gt;
      &lt;SalesContextProvider value={dummySalesContext}&gt;
        &lt;PatientAutocomplete
          searchTerm=&quot;Demo&quot;
          patientSelected={null}
          close={null}
        /&gt;
      &lt;/SalesContextProvider&gt;
    &lt;/GlobalContextProvider&gt;
  );
  const linkElement = screen.getByText(/Add patient/i);
  expect(linkElement).toBeInTheDocument();
});
</code></pre>
<p>This is the error that is thrown:
TypeError: Cannot read property 'focus' of undefined</p>
<pre><code> }, [searchTerm, debounceFetchPatients]);
        useEffect(() =&gt; {
           if (!showEditPatient) patientRef.current.focus({ preventScroll: true });
                                                     ^
        }, [showEditPatient]);
</code></pre>
",https://stackoverflow.com/questions/71408450/pass-ref-as-context-in-react-testing-library-with-jest,"['javascript', 'reactjs', 'jestjs', 'react-testing-library', 'react-context']",283,False,1,0
How to get the same dict from a Pandas.DataFrame.to_dict when it has `nan`?,"<p>I have a Pandas DataFrame constructed from a dict with a nan (e.g.: <code>float(&quot;nan&quot;)</code>). When I use <code>.to_dict</code> on it, I get a different dict - the nan values is something &quot;else&quot;.</p>
<p>Is it possible to know what this new nan value is?</p>
<p>Here is a toy example I created, and a bunch of checks I did:</p>
<pre><code>import numpy as np
import pandas as pd

a_dict = {
            &quot;a&quot;: (1, 2),
            &quot;b&quot;: (3, float(&quot;nan&quot;)),
        }
df = pd.DataFrame(a_dict)

print(df.to_dict())
# {'a': {0: 1, 1: 2}, 'b': {0: 3.0, 1: nan}}

# to_dict() gives a different dict:
print(a_dict == a_dict) # True
print(df.to_dict == a_dict)  # False

print(df.to_dict()[&quot;b&quot;][1]) # nan
print(type(df.to_dict()[&quot;b&quot;][1])) # &lt;class 'float'&gt;


print(df.to_dict()[&quot;b&quot;][1] == float(&quot;nan&quot;))  # False
print(df.to_dict()[&quot;b&quot;][1] == np.nan)  # False
print(df.to_dict()[&quot;b&quot;][1] == pd.NA)  # False
print(df.to_dict()[&quot;b&quot;][1] is None)  # False
print(np.isnan(df.to_dict()[&quot;b&quot;][1]))  # True
print(pd.isna(df.to_dict()[&quot;b&quot;][1]))  # True
</code></pre>
<p>In terms of motivation, this is biting me when I try to create tests using <code>unittest.TestCase.assertEqual</code></p>
<p>Thanks upfront.</p>
<p>Related but didn't help:</p>
<ul>
<li><a href=""https://stackoverflow.com/questions/944700/how-can-i-check-for-nan-values"">How can I check for NaN values?</a></li>
<li><a href=""https://stackoverflow.com/questions/32524084/pandas-unit-testing-how-to-assert-equality-of-nat-and-nan-values"">Pandas unit testing: How to assert equality of NaT and NaN values?</a></li>
</ul>
",https://stackoverflow.com/questions/74037085/how-to-get-the-same-dict-from-a-pandas-dataframe-to-dict-when-it-has-nan,"['python', 'pandas', 'nan']",165,True,0,2
Python: Process inside decorator,"<p>Could somebody tell me why on Earth we can't still not use local function with the <code>multiprocessing.Process</code> standard libraries ?<br />
We are in 2022 and this problem required copy-pasting code to solve it...</p>
<pre class=""lang-python prettyprint-override""><code>def run_ping_outside():
    ping_on_port('google.com', 1234, timeout=5)


class PingHelperUnitTest(unittest.TestCase):

    def test_ping_on_port_timeout(self):
        def run_ping_inside():
            self.assertTrue(ping_on_port('google.com', 1234, timeout=5))

        # Don't work
        # process = Process(target=run_ping_inside)
        process = Process(target=run_ping_outside)
        process.start()
</code></pre>
<p>That is a simple example but the real benefit would be to create a <code>@timeout</code> decorator for unit testing<br />
And be able to test the speed of some part of our applications.</p>
<pre class=""lang-python prettyprint-override""><code>def timeout(max_timeout_allowed):
    def _timeout(decorated_function):
        def timeout_wrapper(self=None):
            def timeout_inner(*args, **kwargs):
                arguments = (args, kwargs) if self is None else (self, args, kwargs)
                process = Process(target=decorated_function, args=arguments)
                process.start()
                sleep(max_timeout_allowed)
                done_in_time = not process.is_alive()
                if not done_in_time:
                    process.terminate()
                if self is not None:
                    self.assertTrue(done_in_time, f&quot;Function ran out out time: {max_timeout_allowed} second(s)&quot;)

            return timeout_inner()
        return timeout_wrapper
    return _timeout
</code></pre>
<p>Here a <strong>non working</strong> example of this decorator because we can't pickle a decorated function...</p>
<p>PS: No I can't use <code>Thread</code> as we are not able to terminate them...</p>
",https://stackoverflow.com/questions/73146709/python-process-inside-decorator,"['python', 'multiprocessing']",89,True,0,1
how to configure a service for unit testing in angular,"<p>One of the service(ProductService) is dependent on the LoggerService, want to perform the unit testing ofProductService.
Spyobj Loggerservice is registered in the provider of the testbed and in the testcase will get the ProductService using TestBed.Inject(ProductService).</p>
<p>Compared testcase with the one of the example available in the angular.io -&gt; <a href=""https://angular.io/guide/testing-services"" rel=""nofollow noreferrer"">https://angular.io/guide/testing-services</a>
In the example both Service and dependent service are registered in the provider of the testbed.</p>
<p>Do we need to register in the provider array of the test bed before getting the ProductService using TestBed.Inject?</p>
<pre><code>            let masterService: MasterService;
            let valueServiceSpy: jasmine.SpyObj&lt;ValueService&gt;;

            beforeEach(() =&gt; {
              const spy = jasmine.createSpyObj('ValueService', ['getValue']);

              TestBed.configureTestingModule({
                // Provide both the service-to-test and its (spy) dependency
                providers: [
                  MasterService,
                  { provide: ValueService, useValue: spy }
                ]
              });
              // Inject both the service-to-test and its (spy) dependency
              masterService = TestBed.inject(MasterService);
              valueServiceSpy = TestBed.inject(ValueService) as jasmine.SpyObj&lt;ValueService&gt;;
            });


            export class LogserviceService {

              constructor() { }

              public logMessage(value:string)
              {
                console.log(value);
              }
            }

            export class ProductService {

               products:IProduct[]=[];

              constructor(private logservice:LogserviceService) {
                console.log('getting the service created');
                console.log(logservice);
                console.log(logservice instanceof (LogserviceService));
               }
              getProducts(): IProduct[] {

                this.products =
                [
                  {name:&quot;TV&quot;,cost:100,model:&quot;123434&quot;,category:&quot;Electronics&quot;},
                 
                ];

                this.logservice.logMessage(&quot;I am in the product service&quot;);

                return this.products;
              }

              getProduct(category:string):IProduct[]
              {
                this.logservice.logMessage(&quot;callling getProduct&quot;);

                let products = this.getProducts();
                let prodct= products.filter(x=&gt;x.category ===category);
                return prodct;
              }

            }

            describe('ProductService', () =&gt; {
              let service: ProductService;
              let logService: LogserviceService;

              logService = jasmine.createSpyObj(['logMessage']);
              beforeEach(() =&gt; {
                TestBed.configureTestingModule({
                  providers: [{ provide: LogserviceService, useValue: logService },
                    
                  ],
                });
              });

             
              it('should get the product list, if valid caterogy is sent', () =&gt; {
               
                let service = TestBed.inject(ProductService);  //product service not registered in the providers
                let products = service.getProduct('Electronics');

                expect(products.length).toBeGreaterThan(0);
                expect(logService.logMessage).toHaveBeenCalledWith('callling getProduct');
                expect(products[0].category).toEqual('Electronics');

              });
            });
</code></pre>
",https://stackoverflow.com/questions/71527479/how-to-configure-a-service-for-unit-testing-in-angular,"['angular', 'jasmine']",393,False,0,0
Mocking Auth Token function in Pester,"<p>I have written a PowerShell function that generates an auth token in azure using REST API call. I am using the tenant id, Service principal client id and client secret as input param to generate this token. The SP client id and client secret are being read from the azure keyvault.</p>
<p>I wish to write a unit test to:</p>
<ol>
<li>Read secret from keyvault</li>
<li>Mock the REST API call to generate dummy auth token</li>
</ol>
<p>I am planning to use PESTER for unit testing and need some assistance here.</p>
<p>Here is my function:</p>
<pre><code>function string GetAuthToken() {       
        $AuthTokenUri = &quot;https://login.microsoftonline.com/$TenantId/oauth2/token&quot;
        $Body = @{
            'resource'      = $resourcename
            'client_id'     = $ID
            'grant_type'    = 'client_credentials'
            'client_secret' = $Secret
        }
       $Token = Invoke-RestMethod -Method Post -Uri $AuthTokenUri -Body $Body -ContentType application/x-www-form-urlencoded'
       $AuthToken = ($Token.access_token).ToString()
       return $AuthToken
}
</code></pre>
",https://stackoverflow.com/questions/71220770/mocking-auth-token-function-in-pester,"['powershell', 'unit-testing', 'pester', 'pester-5']",175,False,0,0
Jest ---outputFile removes CLI coverage output,"<p>We use jest for unit testing in our repo, and include config for code coverage:</p>
<pre><code>collectCoverage: true,
collectCoverageFrom: ['src/**/*.ts', 'infrastructure/**/*.ts'],
</code></pre>
<p>Normally this results in CLI output for coverage when running the tests. Recently however we've added Danger JS integration on our PR build, and the plugin we're using to report on Jest tests relies on the <code>--outputFile</code> switch for the jest command i.e. <code>jest --outputFile test-results.json --json</code>.</p>
<p>With <code>--outputFile</code> specified code coverage is still run and results are put in the <code>coverage</code> directory, but the CLI output doesn't include coverage, only pass / fail information. Is it possible to have both the outputFile and coverage to stdout?</p>
",https://stackoverflow.com/questions/71127598/jest-outputfile-removes-cli-coverage-output,"['javascript', 'unit-testing', 'jestjs', 'code-coverage']",797,False,0,0
Axon Framework: Aggregate Autowired Bean throws NullPointerException in Test,"<p>Springboot and Axon: Basically I am unit testing an aggregate that uses three different ObjectMapper instances, each with a different configuration. These are defined in config class :</p>
<pre><code>    @Configuration
    public class JacksonConfiguration {

    @Bean(name=&quot;flatMapper&quot;)
    @Primary
    public ObjectMapper flatMapper(){
        return new ObjectMapper();
    }

    @Bean(name=&quot;unknownPropertiesMapper&quot;)
    public ObjectMapper unknownPropertiesMapper(){
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }

    @Bean(name=&quot;nullPropertiesMapper&quot;)
    public ObjectMapper nullPropertiesMapper(){
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper;
    }

}
</code></pre>
<p>They are injected and used in my aggregate as follow:</p>
<pre><code>@Aggregate
@Data
@Component
public class MyAggregate {

    @Autowired
    @Qualifier(&quot;flatMapper&quot;)
    private ObjectMapper flatMapper;

    @Autowired
    @Qualifier(&quot;unknownPropertiesMapper&quot;)
    private ObjectMapper unknownPropertiesMapper;

    @Autowired
    @Qualifier(&quot;nullPropertiesMapper&quot;)
    private ObjectMapper nullPropertiesMapper;


    @AggregateIdentifier
    private String id;

  //Methods and Handlers: a method is using &quot;unknownPropertiesMapper&quot; is &quot;changedKeySet&quot; 
</code></pre>
<p>when I run SpringBootApplication everything is properly instanciated and working as expected, but when testing I get NullPointerException over thier instances:</p>
<pre><code>@ContextConfiguration(classes = JacksonConfiguration.class)
@SpringBootTest(classes = OccurrenceAggregate.class)
@ComponentScan(basePackageClasses = MyAggregate.class)
public class AggregateTest {
    
    private FixtureConfiguration&lt;MyAggregate&gt; fixture;

    @BeforeEach
    public void setUp() {
        fixture = new AggregateTestFixture&lt;&gt;(MyAggregate.class);
    }

    @Test
    public void myTest() {

       fixture.givenNoPriorActivity().... 

    }
</code></pre>
<p>test console:</p>
<pre><code>org.axonframework.test.AxonAssertionError: The command handler threw an unexpected exception

Expected &lt;ANYTHING&gt; but got &lt;exception of type [NullPointerException]&gt;. Stack trace follows:
java.lang.NullPointerException
    at com.example.business.aggregates.MyAggregate.changedKeySet(MyAggregate.java:185)
</code></pre>
<p><code>changedKeySet()</code> is throwing NPE because its using <code>unknownPropertiesMapper</code> and it is value is null.
as I mentionned it works fine when I run the Main class but not in tests (Junit5).</p>
",https://stackoverflow.com/questions/71264657/axon-framework-aggregate-autowired-bean-throws-nullpointerexception-in-test,"['java', 'spring-boot', 'junit5', 'axon', 'axon-framework']",483,True,0,1
How to write a unit test using Pytest for the main function in Python,"<p>I am new with unit testing and am confused about a lot of things. In the project I have been inherited, there is a <code>__main__.py</code> file, in which there is only one function:</p>
<pre><code>import some_class

def func1 (some_instance) -&gt; bool:
    #some code
    #returns true or False



some_instance = some_class()
func1 (some_instance)
</code></pre>
<p>Now, in another file (<code>tests.py</code>), which is in the same folder as <code>__main__.py</code>, I want to write a unit test to test the <code>func1</code> function. I don't know how I can do that. This is all I got:</p>
<pre><code>import some_class
from __main__ import func1

def test_func1():
    test_instance = some_class()
    assert func1(test_instance) is True
</code></pre>
<p>It doesn't work and I think the <code>test_func1()</code> cannot even access <code>func1</code>. How can import <code>func1</code>? How can I test it? The (<code>from __main__ import func1</code>) part looks strange.</p>
",https://stackoverflow.com/questions/73264261/how-to-write-a-unit-test-using-pytest-for-the-main-function-in-python,"['python', 'unit-testing', 'pytest', 'program-entry-point']",1781,False,0,1
"Get sibling component in Vue test utils (Vue 3, Composition API)","<p>I'm currently exploring unit testing and Vue test utils particularly. I have an external library (<code>vue-toastification</code>) that shows a toast message when something occurs. I'd like to test that this toast has been shown, if an Error was thrown. But the problem is that the toast is rendered outside component's scope (in App.vue, as far as I can see), meanwhile with <code>.get</code> method we can only retrieve child components of a wrapper. So, how can I access this toast component without mounting the whole application? Maybe I should somehow use <code>&lt;teleport&gt;</code>?</p>
",https://stackoverflow.com/questions/71406359/get-sibling-component-in-vue-test-utils-vue-3-composition-api,"['vue.js', 'vuejs3', 'vue-test-utils']",175,False,0,0
Docker SDK - Can&#39;t connect to DB from HOST,"<p>I want to create a temporary <code>MySQL</code> database for unit testing in Python. I decided to go with <code>docker</code> as the tests will be run on different machines.</p>
<p>As a first thing I run the container:</p>
<pre><code>client = docker.from_env()
container = client.containers.run(&quot;ubuntu/mysql&quot;, detach=True, ports={3306:3307},environment={
    'MYSQL_USER':'mysqluser',
    'MYSQL_PASSWORD':'password',
    'MYSQL_DATABASE':'mydb',
                                                                                              })

print('Container Started : {}'.format(container.status))
</code></pre>
<p>And then I try to connect using SQLAlchemy:</p>
<pre><code>engine = sa.create_engine(f'mysql+pymysql://mysqluser:password@localhost:3307/mydb')
engine.connect()
</code></pre>
<p>which returns:</p>
<pre><code>sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
</code></pre>
<p><strong>EDIT</strong></p>
<p>After putting <code>sleep(10)</code> after <code>container.run</code>, the response is different:</p>
<pre><code>sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, &quot;Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)&quot;)
</code></pre>
<p>Do you know what I'm doing wrong?</p>
<p>What I want to do is to connect to <code>MySQL</code> database on port <code>3307</code> (as one server already runs on the host). Then I want to create and populate a table.</p>
<p><strong>EDIT2</strong></p>
<p>Switching ports to <code>{3307:3306}</code> returns error:</p>
<pre><code>docker.errors.APIError: 500 Server Error for http+docker://localhost/v1.41/containers/67a04b384bf3d39407881d4dfc73961932a3ce72fe8dc82c3cd6aedd57da2821/start: Internal Server Error (&quot;driver failed programming external connectivity on endpoint hopeful_leakey (97840eb42d2c09b5e9754b634481d8e048c57ba2de8ffc10b34261de2f76600b): Error starting userland proxy: listen tcp4 0.0.0.0:3306: bind: address already in use&quot;)
</code></pre>
",https://stackoverflow.com/questions/70671819/docker-sdk-cant-connect-to-db-from-host,"['python', 'mysql', 'linux', 'docker', 'dockerpy']",246,False,0,0
Using H2 for unit test and postgres for prod with Spring Data JDBC,"<p>With Spring Data JPA, I could use H2 for unit tests and postgres(or any other relational DB) for prod. Here, I need not worry about compatibility issues with queries as its abstracted by JPA.</p>
<p>Can I use the same combination of DBs with Spring Data JDBC without much worry about compatibility issues?
If no, what is the recommended approach for unit testing?</p>
<p>Please note, I have explored the option of Testcontainers. It seems to be complex and time-consuming option, especially on MS Windows based dev environments.</p>
",https://stackoverflow.com/questions/74485593/using-h2-for-unit-test-and-postgres-for-prod-with-spring-data-jdbc,['spring-data-jdbc'],74,True,0,1
"Skip a parameter in MockK unit test, Kotlin","<p>I use <a href=""https://mockk.io/"" rel=""nofollow noreferrer"">MockK</a> library for unit testing.</p>
<p>Tested method contains strings that don't have meaning for a result. I want to check other variables, but have to define a behaviour of strings because they are used in tested methods.</p>
<p>For <a href=""https://stackoverflow.com/a/71675182/2914140"">instance</a>,</p>
<pre><code>every {
    resources.getQuantityString(R.plurals.age, 10, 10)
} returns &quot;10 years&quot;
every {
    resources.getString(
        R.string.surname,
        &quot;surname&quot;
    )
} returns &quot;surname&quot;
</code></pre>
<p>How can I omit parameters in these methods? So that I could pass any integer instead of 10, any string instead of &quot;surname&quot;? In this case a result of <code>resources.getString</code> won't have matter. I don't want to calculate a value of each parameter for a test. Just mock a behaviour.</p>
",https://stackoverflow.com/questions/71676134/skip-a-parameter-in-mockk-unit-test-kotlin,"['kotlin', 'android-resources', 'mockk']",1694,True,0,1
Alternative to Enzyme for unit testing in React,"<p>Since Enzyme is dead for React 18 and everyone seems to be talking about React Testing Library, for a more integration-testing approach. However, in my case I need more of a unit-testing solution to test functions within my React component:</p>
<pre><code>export default function Chat({ userName, roomName }: ChatProps) {
    const [userInput, setUserInput] = useState(&quot;&quot;);
    const [messageList, setMessageList] = useState&lt;SocketMessageNS.NewMessageIn[]&gt;([]);

    const [sendSocketMessage, isConnected] = useSocketIo(userName, roomName, handleOnNewMessage);

    function handleOnNewMessage(msg: SocketMessageNS.NewMessageIn) {
        // ...
    }

    function handleOnSendMessage() {
        // ...
    }

    return (
        &lt;div className=&quot;Chat&quot;&gt;
            &lt;ChatHeader isConnected={isConnected} roomName={roomName} /&gt;
            &lt;ChatConversation data={messageList} userName={userName} /&gt;
            &lt;ChatInput value={userInput} onChange={setUserInput} onSubmit={handleOnSendMessage} /&gt;
        &lt;/div&gt;
    );
}
</code></pre>
<p>I want to be able to test my functions on their own, simply by calling them like you would do with Enzyme:       <code>wrapper.instance().handleOnSendMessage();</code></p>
<p>It doesn't seem to be possible with React Testing Library.
What do you do when you need to test your functions with React components with spies and such?</p>
",https://stackoverflow.com/questions/74281739/alternative-to-enzyme-for-unit-testing-in-react,"['reactjs', 'jestjs', 'react-testing-library']",49,False,-1,1
How to match number pattern in python&#39;s responses library,"<p>I am unit testing in Python (pytest, responses library - It's for an API project...). I am creating fake responses which have to match a request string. The only difference in those responses is the number in the middle of the string:</p>
<pre><code>    responses.add(
        GET, 
        'http://app/projects/1200979733003518/tasks?opt_pretty=false', 
        status=200,
        body=json.dumps(res_t)
    )
    responses.add(
        GET, 
        'http://app/projects/1200979733003526/tasks?opt_pretty=false', 
        status=200,
        body=json.dumps(res_t)
    )
    responses.add(
        GET, 
        'http://app/projects/1201345940827570/tasks?opt_pretty=false', 
        status=200,
        body=json.dumps(res_t)
    )
</code></pre>
<p>I want to get rid of the repetition. I tried using python's re.compile, my idea was to do something like this:</p>
<pre><code>    responses.add(
    GET, 
    re.compile('http://app/projects/\\[0-9]+/tasks?opt_pretty=false'), 
    status=200,
    body=json.dumps(res_t)
)
</code></pre>
<p>It doesn't work. Read the manual for re, but can't come up with a working solution. How can i achieve that the response matches any number in my strings at this position?</p>
",https://stackoverflow.com/questions/70691867/how-to-match-number-pattern-in-pythons-responses-library,"['python', 'python-3.x', 'regex']",229,True,0,1
jest Could not locate module error in React typescript,"<p>I'm trying to learning unit testing in react applications. My app created with webpack instead of create-react-app. I looked at the topics with similar errors, then I applied the config file as follows. The problem is I'm using alias in tsconfig and  also edited <code>moduleNameMapper</code> accordingly in jest.config file. But in console this error appears.</p>
<p>Configuration error:</p>
<pre><code>Could not locate module @layouts/main mapped as:
views/commons/layouts/$1.

Please check your configuration for these entries:
{
  &quot;moduleNameMapper&quot;: {
    &quot;/^@layouts\/(.*)$/&quot;: &quot;views/commons/layouts/$1&quot;
  },
  &quot;resolver&quot;: undefined
}

&gt; 1 | import MainLayout from '@layouts/main'
    | ^
  2 |
  3 | const NotFoundPage = () =&gt; (
  4 |   &lt;MainLayout&gt;
</code></pre>
<p>I created a config file as below.
// jest.config.js</p>
<pre><code>const { pathsToModuleNameMapper } = require('ts-jest')
const { compilerOptions } = require('./tsconfig')

/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
  preset: 'ts-jest',
  roots: ['&lt;rootDir&gt;/src'],
  moduleDirectories: ['node_modules', __dirname],
  setupFilesAfterEnv: ['&lt;rootDir&gt;/setupTests.js'],
  moduleNameMapper: {
    ...pathsToModuleNameMapper(compilerOptions.paths),
    '^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub'
  },
  transform: {
    '^.+\\.ts?$': 'ts-jest',
    '^.+\\.js?$': 'babel-jest',
    '.+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$':
      'jest-transform-stub'
  },
  moduleFileExtensions: ['js', 'ts', 'd.ts', 'jsx', 'tsx', 'json']
}
</code></pre>
<p>// setupTests.js</p>
<pre><code>import '@testing-library/jest-dom'
</code></pre>
<p>// tsconfig.js</p>
<pre><code>{
  &quot;compilerOptions&quot;: {
    &quot;baseUrl&quot;: &quot;./src/&quot;,
    &quot;target&quot;: &quot;es5&quot;,
    &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;],
    &quot;allowJs&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;strict&quot;: true,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;noEmit&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;resolveJsonModule&quot;: true,
    &quot;isolatedModules&quot;: true,
    &quot;jsx&quot;: &quot;react-jsx&quot;,
    &quot;allowSyntheticDefaultImports&quot;: true,
    &quot;noFallthroughCasesInSwitch&quot;: true,
    &quot;paths&quot;: {
      &quot;@api/*&quot;: [&quot;api/*&quot;],
      &quot;@assets/*&quot;: [&quot;assets/*&quot;],
      &quot;@icons/*&quot;: [&quot;assets/icons/*&quot;],
      &quot;@images/*&quot;: [&quot;assets/images/*&quot;],
      &quot;@styles/*&quot;: [&quot;assets/styles/*&quot;],
      &quot;@hooks/*&quot;: [&quot;hooks/*&quot;],
      &quot;@i18n&quot;: [&quot;i18n/index&quot;],
      &quot;@i18n/*&quot;: [&quot;i18n/*&quot;],
      &quot;@store&quot;: [&quot;store/index&quot;],
      &quot;@store/*&quot;: [&quot;store/*&quot;],
      &quot;@reducers/*&quot;: [&quot;store/reducers/*&quot;],
      &quot;@storage&quot;: [&quot;store/storage/index&quot;],
      &quot;@storage/*&quot;: [&quot;store/storage/*&quot;],
      &quot;@storeUtils/*&quot;: [&quot;store/utils/*&quot;],
      &quot;@staticStore/*&quot;: [&quot;store/static/*&quot;],
      &quot;@types&quot;: [&quot;types/index&quot;],
      &quot;@types/*&quot;: [&quot;types/*&quot;],
      &quot;@views/*&quot;: [&quot;views/*&quot;],
      &quot;@commonViews/*&quot;: [&quot;views/commons/*&quot;],
      &quot;@footers/*&quot;: [&quot;views/commons/footers/*&quot;],
      &quot;@headers/*&quot;: [&quot;views/commons/headers/*&quot;],
      &quot;@layouts/*&quot;: [&quot;views/commons/layouts/*&quot;],
      &quot;@providers/*&quot;: [&quot;views/commons/providers/*&quot;],
      &quot;@seo/*&quot;: [&quot;views/commons/seo/*&quot;],
      &quot;@components/*&quot;: [&quot;views/components/*&quot;],
      &quot;@viewsConfigs/*&quot;: [&quot;views/configs/*&quot;],
      &quot;@pages/*&quot;: [&quot;views/pages/*&quot;]
    }
  },
  &quot;include&quot;: [&quot;src/**/*&quot;, &quot;**/*.ts&quot;, &quot;**/*.tsx&quot;],
  &quot;exclude&quot;: [&quot;node_modules&quot;]
}
</code></pre>
<p>//babelrc</p>
<pre><code>{
  &quot;presets&quot;: [
    &quot;@babel/preset-env&quot;,
    &quot;@babel/preset-react&quot;,
    &quot;@babel/preset-typescript&quot;
  ],
  &quot;plugins&quot;: []
}
</code></pre>
<hr />
<p>By the way, if I changes <code>moduleDirectories: ['node_modules', __dirname]</code>, like <code>moduleDirectories: ['node_modules', &quot;.&quot;]</code>, error does not appears anymore. But I'm getting new error like that:</p>
<pre><code>Test suite failed to run

TypeError: Cannot read properties of undefined (reading 'extend')

  at createJestExpect (node_modules/@jest/expect/build/index.js:29:19)
  at Object.&lt;anonymous&gt; (node_modules/@jest/expect/build/index.js:39:20)
</code></pre>
",https://stackoverflow.com/questions/74931506/jest-could-not-locate-module-error-in-react-typescript,"['reactjs', 'typescript', 'jestjs', 'react-testing-library', 'ts-jest']",384,False,0,0
Struggling to Unit Test Service method for Searching/Filtering data using a Page,"<p>i'm new to Unit Testing but have a problem I'm struggling to understand.
I have a Service method to searching/filtering an entity which returns a Page, I am trying to add a Test for this method so that when I search for a certain query I only get those entities that much it (Since there's no db to pull the data from I'm unsure how to mock this correctly so that I can actually ensure the unit works correctly, meaning the search functionality)</p>
<p><strong>Repository</strong></p>
<pre class=""lang-java prettyprint-override""><code>@Repository
public interface PostRepository extends PagingAndSortingRepository&lt;Post, Long&gt;, JpaSpecificationExecutor&lt;Post&gt; {
    // Return values that match the brand,model etc of the Post/Advertisement entity
    @Query(value = &quot;SELECT * FROM post p WHERE (p.brand LIKE :query OR p.model like :query OR p.description LIKE :query OR p.title LIKE :query) AND p.active=true&quot;, nativeQuery = true)
    Page&lt;Post&gt; searchAllActivePosts(@Param(&quot;query&quot;)String query,Pageable pageable);
}
</code></pre>
<p><strong>Service</strong></p>
<pre class=""lang-java prettyprint-override""><code>
@Service
public class PostServiceImpl implements PostService {

    private final PostRepository postRepository;
    private final UserRepository userRepository;
    private final FileUploadService fileUploadService;

    public PostServiceImpl(PostRepository postRepository, UserRepository userRepository, FileUploadService fileUploadService) {
        this.postRepository = postRepository;
        this.userRepository = userRepository;
        this.fileUploadService = fileUploadService;
    }
   @Override
    public Page&lt;Post&gt; findAllActivePosts(String query, Pageable pageable) {
        Page&lt;Post&gt; page = postRepository.searchAllActivePosts(query, pageable);

        // Loop through each post and see if it is expired(14 days after creation) then setActive to False
        page.stream().forEach(post -&gt; {
            if (post.isPostExpired()) post.setActive(false);
            postRepository.save(post);
        });

        if (page.isEmpty()) throw new PostNotFoundException(&quot;There are no matching records..&quot;);
        return page;
    }
}


</code></pre>
<p><strong>Controller Endpoint</strong></p>
<pre class=""lang-java prettyprint-override""><code>    @GetMapping(&quot;/posts/search&quot;)
    public ResponseEntity&lt;?&gt; getAllActivePosts(
        @RequestParam(required=false) String query,
        @RequestParam(required = false) List&lt;String&gt; brand,
        @RequestParam(required=false) String province,
        @RequestParam(required=false) List&lt;String&gt; city,
        @RequestParam(defaultValue = &quot;0&quot;, required = false) int pageNo,
        @RequestParam(defaultValue = &quot;5&quot;, required = false) int pageSize,
        @RequestParam(defaultValue = &quot;id&quot;, required = false) String sortBy,
        @RequestParam(defaultValue = &quot;desc&quot;, required = false) String sortDir,
        @RequestParam(defaultValue = &quot;0&quot;, required = false) int minValue,
        @RequestParam(defaultValue = &quot;5000000&quot;, required = false) int maxValue) {

        Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortBy).ascending() : Sort.by(sortBy).descending();

        Pageable pagingSort = PageRequest.of(pageNo, pageSize, sort);

        Page&lt;Post&gt; pageTuts;
        if(query != null) {
            pageTuts = postService.findAllActivePosts(query, pagingSort);
        }

        return new ResponseEntity&lt;&gt;(createMapForPageContents(pageTuts), HttpStatus.OK);
    }
</code></pre>
<p><strong>Attempt to Test the method</strong></p>
<pre class=""lang-java prettyprint-override""><code>@ExtendWith(MockitoExtension.class)
class PostServiceImplTest {

    @InjectMocks
    private PostServiceImpl postService;

    @Mock
    private PostRepository postRepository;

    @Mock
    private UserRepository userRepository;

    private Post postOne, postTwo, postThree;

    @BeforeEach
    void setUp() {
        postOne = new Post(1L,
                &quot;This is my first post on the website&quot;,
                &quot;Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaqueoluptas sit aspernatur aut odit aut fugit&quot;,
                &quot;Toyota&quot;, &quot;Supra&quot;, 120000D, &quot;Red&quot;, 92000D, &quot;Sedan&quot;, &quot;Petrol&quot;, &quot;Automatic&quot;,
                2019, &quot;Province 1&quot;, &quot;city 1&quot;);

        postTwo = new Post(2L,
                &quot;This is my second post on the website&quot;,
                &quot;Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaqueoluptas sit aspernatur aut odit aut fugit&quot;,
                &quot;BMW&quot;, &quot;i35&quot;, 120000D, &quot;Red&quot;, 92000D, &quot;Sedan&quot;, &quot;Petrol&quot;, &quot;Automatic&quot;,
                2019, &quot;Province 2&quot;, &quot;city 2&quot;);

        postThree = new Post(3L,
                &quot;This is my third post on the website&quot;,
                &quot;Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaqueoluptas sit aspernatur aut odit aut fugit&quot;,
                &quot;Audi&quot;, &quot;A3&quot;, 120000D, &quot;Red&quot;, 92000D, &quot;Sedan&quot;, &quot;Petrol&quot;, &quot;Automatic&quot;,
                2019, &quot;Province 3&quot;, &quot;city 3&quot;);

        postOne.setExpiredAt(postOne.getCreatedAt().plusDays(14));
        postTwo.setExpiredAt(postTwo.getCreatedAt().plusDays(14));
        postThree.setExpiredAt(postThree.getCreatedAt().plusDays(14));

        postService = new PostServiceImpl(postRepository, userRepository, null);
    }

    @AfterEach
    void tearDown() {
        postRepository.deleteAll();
    }


    @Test
    public void canGetAllPostsThatAreActive() {

        // Here I want to search from the 3 posts in the setUp() method for a value that matches &quot;Audi&quot;, in this case there is 1/3 posts that match this, but I'm unsure how to get it working properly
        when(postRepository.searchAllActivePosts(&quot;Audi&quot;, PageRequest.ofSize(10)))
                .thenReturn(new PageImpl&lt;&gt;(List.of(postThree)));

        Page&lt;Post&gt; posts = postService.findAllActivePosts(&quot;Audi&quot;,  PageRequest.ofSize(10));

        // Here there should be 1 element in the page (The one with the value &quot;Audi&quot;, so i was hoping to use this to assert that the test is working correctly)
        assertThat(posts.getTotalElements()).isEqualTo(1);


    }

}
</code></pre>
",https://stackoverflow.com/questions/74450228/struggling-to-unit-test-service-method-for-searching-filtering-data-using-a-page,"['java', 'spring-boot', 'unit-testing', 'junit', 'mockito']",47,False,0,0
NullPointer exception on calling @Postconstruct method in AEM Model,"<p>I am trying to use AemContext to adapt the JSON resource file with Model. I used @Postconstruct annotation for initializing the model function. But every time I run the project, I get a null pointer exception on invocking getList() function in the test class. I am trying to get a grasp of unit testing this model which runs through @Postconstruct injection. It will be really helpful if I get to know the reason of getting null pointer exception.</p>
<p>Model Interface</p>
<pre><code>package com.xyz.core.models;

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

public interface TableModel {

    /**
     * Function to be implemented to fetch
     * list of table items from JCR
     * 
     * @return list of items
     */
    public List&lt;Map&lt;String, String&gt;&gt; getList();
}
</code></pre>
<p>Model Class</p>
<pre><code>package com.xyz.core.models.impl;

import com.xyz.core.models.TableModel;

import javax.annotation.PostConstruct;
import javax.inject.Inject;

import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.Optional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Model(adaptables = Resource.class, adapters = TableModel.class)
public class TableModelImpl implements TableModel{

    @Inject
    @Optional
    private Resource items;

    private List&lt;Map&lt;String, String&gt;&gt; itemsChildren = new ArrayList&lt;Map&lt;String, String&gt;&gt;();

    @PostConstruct
    public void init(){
        if (items != null) {
            for (Resource resource: items.getChildren()) {
                ValueMap properties = resource.adaptTo(ValueMap.class);
                String title = properties.get(&quot;title&quot;, String.class);
                String content = properties.get(&quot;content&quot;, String.class);
                Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
                map.put(&quot;title&quot;, title);
                map.put(&quot;content&quot;, content);
                itemsChildren.add(map);
            }
        }
    }

    public List&lt;Map&lt;String, String&gt;&gt; getList() {
        return Collections.unmodifiableList(itemsChildren);
    }
}

</code></pre>
<p>Test Class of Model Class</p>
<pre><code>package com.xyz.core.models;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Map;

import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;

import org.junit.jupiter.api.BeforeEach;

import com.xyz.core.models.impl.TableModelImpl;

import io.wcm.testing.mock.aem.junit5.AemContext;
import io.wcm.testing.mock.aem.junit5.AemContextExtension;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.mockito.junit.jupiter.MockitoExtension;

@ExtendWith({AemContextExtension.class, MockitoExtension.class})
public class TableModelImplTest {
    private final AemContext aemContext = new AemContext();
    TableModelImpl tableModelImpl;
    private List&lt;Map&lt;String, String&gt;&gt; expectedItemsChildren = new ArrayList&lt;Map&lt;String, String&gt;&gt;();
    private final Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();

    @BeforeEach
    void setUp() {
        aemContext.addModelsForClasses(TableModelImpl.class);
        aemContext.load().json(&quot;/com/xyz/core/models/impl/Table.json&quot;, &quot;/component&quot;);
    }

    @Test 
    void getList() {
        aemContext.currentResource(&quot;/component/table&quot;);
        tableModelImpl = aemContext.request().adaptTo(TableModelImpl.class)
        map.put(&quot;title&quot;, &quot;TItle&quot;);
        map.put(&quot;content&quot;,&quot;content&quot;);
        this.expectedItemsChildren.add(map);
        map.put(&quot;title&quot;, &quot;Many&quot;);
        map.put(&quot;content&quot;,&quot;More&quot;);
        List&lt;Map&lt;String, String&gt;&gt; actualItemsChildren = tableModelImpl.getList();
        assertEquals(expectedItemsChildren, actualItemsChildren);
    }
}
</code></pre>
<p>JSON file from resource</p>
<pre><code>{
    &quot;table&quot;:{
        &quot;jcr:primaryType&quot;:&quot;nt:unstructured&quot;,
        &quot;jcr:createdBy&quot;:&quot;admin&quot;,
        &quot;jcr:lastModifiedBy&quot;:&quot;admin&quot;,
        &quot;jcr:created&quot;:&quot;Wed Aug 24 2022 10:38:41 GMT+0900&quot;,
        &quot;jcr:lastModified&quot;:&quot;Wed Aug 24 2022 10:39:03 GMT+0900&quot;,
        &quot;sling:resourceType&quot;:&quot;xyz/components/table&quot;,
        &quot;items&quot;:{
        &quot;jcr:primaryType&quot;:&quot;nt:unstructured&quot;,
        &quot;item0&quot;:{
            &quot;jcr:primaryType&quot;:&quot;nt:unstructured&quot;,
            &quot;title&quot;:&quot;TItle&quot;,
            &quot;content&quot;:&quot;Content&quot;
        },
        &quot;item1&quot;:{
            &quot;jcr:primaryType&quot;:&quot;nt:unstructured&quot;,
            &quot;title&quot;:&quot;Many&quot;,
            &quot;content&quot;:&quot;More&quot;
        }
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/73471888/nullpointer-exception-on-calling-postconstruct-method-in-aem-model,"['java', 'junit', 'aem', 'sling', 'jcr']",458,True,-2,1
Git push but with following conditions,"<p>I have the following requirement.</p>
<p>Git repo A (on BitBucket): all development is committed multiple times a day
Git repo B (on AWS CodeCommit): only specific commits from Repo A should go into it...</p>
<p>Example: I work on a block of code (have multiple commits into Repo A) and then when I'm happy with the progress and unit testing..etc.. I want to push all the changes into Repo B as a single commit (similar to a merge)</p>
<p>This is to keep the commit history of Repo B clean</p>
",https://stackoverflow.com/questions/73767023/git-push-but-with-following-conditions,"['git', 'bitbucket', 'aws-codecommit']",31,False,0,1
N-Tier Architecture WebApi: NUnit - No suitable constructor was found,"<p>I'm extremely new in this unit testing and NUnit testing.
When I'm trying to run below code... I'm getting the following error</p>
<pre><code>namespace NC_BLUnitTests
{
[TestFixture]
public class ProductBLTests
{
    private IBLProductsRepo blRepo;

    public ProductBLTests(IBLProductsRepo _blRepo)
    {
        blRepo = _blRepo;
    }

    [Test]
    public void AddProduct_Test()
    {
        //Arrange 
        var expectedResult = new ProductVM()
        {
            Name = &quot;prod 4&quot;,
            CreatedDateTime = DateTime.Now,
            Price = 65.89m,
            Status = (int)StatusEnm.Active
        };

        // Act
        int resId = blRepo.AddProduct(expectedResult).Result.Data;
        var res = blRepo.GetProduct(resId);

        // Assert
        Assert.Equals(expectedResult, res);
    }
}}
</code></pre>
<blockquote>
<p>No suitable constructor was found</p>
</blockquote>
<p>Now, I searched many articles here but I don't understand anything at all.</p>
<p>Here is my business layer code that I'm trying to test</p>
<pre><code>namespace NC_BLRepositories {
public class BLProductsRepo : IBLProductsRepo
{
    private IDLProductsRepo dlProductsRepo;

    public BLProductsRepo(IDLProductsRepo dlRepo)
    {
        dlProductsRepo = dlRepo;
    }

    public Task&lt;Response&lt;int&gt;&gt; AddProduct(ProductVM product)
    {
        Response&lt;int&gt; res = new Response&lt;int&gt;();
        try
        {
            res.Data = dlProductsRepo.AddProduct(product).Result;
            res.IsSuccess = true;
            res.Message = &quot;Product Added Successfully&quot;;
        }
        catch (Exception ex)
        {
            res.IsSuccess = false;
            res.Message = &quot;Some Error While Adding Product: &quot; + ex.Message;
        }
        return Task.FromResult(res);
    }

    public Task&lt;Response&lt;ProductVM&gt;&gt; GetProduct(int productId)
    {
        Response&lt;ProductVM&gt; res = new Response&lt;ProductVM&gt;();
        try
        {
            res.IsSuccess = true;
            res.Message = &quot;Product fetched successfully&quot;;
            res.Data = new ProductVM(dlProductsRepo.GetProduct(productId).Result);
            if (res.Data?.Id == 0)
                res.Message = &quot;Invalid Product&quot;;

        }
        catch (Exception ex)
        {
            res.IsSuccess = false;
            res.Message = &quot;Some Error While Fetching Single Product: &quot; + ex.Message;
        }
        return Task.FromResult(res);
    }
}}
</code></pre>
<p>and this is the Data Layer that is injected here and will go for testing in future.</p>
<pre><code>namespace NC_DLRepositories {
public class DLProductsRepo : IDLProductsRepo
{
    private MyShopContext dbCtx;

    public DLProductsRepo(MyShopContext ctx)
    {
        dbCtx = ctx;
    }

    public async Task&lt;int&gt; AddProduct(Product product)
    {
        Product newProduct = product;
        dbCtx.Products.Add(newProduct);
        await dbCtx.SaveChangesAsync();
        return newProduct.Id;
    }

    public async Task&lt;Product&gt; GetProduct(int productId)
    {
        return await dbCtx.Products.Where(e =&gt; e.Id == productId).SingleOrDefaultAsync();
    }
}}
</code></pre>
<p>Please guide me, I have 0 knowledge of all these things and the internet is giving me all the basic articles only.</p>
",https://stackoverflow.com/questions/72955359/n-tier-architecture-webapi-nunit-no-suitable-constructor-was-found,"['c#', '.net', 'unit-testing', 'asp.net-core', 'nunit']",33,False,0,1
How to extract &quot;Image&quot; type from SQL Server Northwind database with JDBC,"<p>I'm unit testing binary data in a sample database and I want to read the image column from the Categories table from northwind sample db and save it to a file.</p>
<p><a href=""https://github.com/microsoft/sql-server-samples"" rel=""nofollow noreferrer"">https://github.com/microsoft/sql-server-samples</a></p>
<p>I get the byte array fine but if I write it the image file is invalid.  I've read that the format contains an OLE header 78 bytes to remove. I tried that but still the image is not viewable when I save it to a file.  I tried saving as JBP and BMP. Neither worked.</p>
<p>Any ideas?</p>
",https://stackoverflow.com/questions/71486809/how-to-extract-image-type-from-sql-server-northwind-database-with-jdbc,"['java', 'sql-server', 'jdbc', 'northwind']",170,False,0,0
Jest React Native FlatList onViewableItemsChanged on executing inside functions while testing using Jest,"<p>I am using the onViewableItemsChanged prop from Flatlist. The functionality is working as expected, but when I perform unit test on the same I can see that the function is being called but the statements inside the function are not being executed when performing unit testing.</p>
<p><strong>app.js</strong></p>
<pre><code>  const onViewableItemsChanged = React.useCallback(
    ({ viewableItems, changed, viewabilityConfig }) =&gt; {
      setActiveIndex(viewableItems);
    },
    [],
  );

  const setActiveIndex = (activeViews) =&gt; {
    if (activeViews?.length !== 0) {
      let index = activeViews[0]?.index;
      setActiveViewIndex(index);
    }
  };

  return(
    &lt;View&gt;
      &lt;View&gt;
        &lt;FlatList
          data={checkedInPersonsList}
          horizontal
          showsHorizontalScrollIndicator={false}
          style={{ flexGrow: 0 }}
          contentContainerStyle={{
            paddingHorizontal: containerHorizontalPadding,
          }}
          renderItem={({ item, index }) =&gt;
            renderFlatList(item, index, checkedInPersonsList)
          }
          //   onScroll={onScroll}
          onViewableItemsChanged={onViewableItemsChanged}
          viewabilityConfig={{
            itemVisiblePercentThreshold: 92,
          }}
          ItemSeparatorComponent={() =&gt; (
            &lt;View style={{ paddingHorizontal: 10 }} /&gt;
          )}
          testID={'PaxScrollerFlatList.test'}
        /&gt;
      &lt;/View&gt;
    &lt;/View&gt;
  )

</code></pre>
<p><strong>app.test.js</strong></p>
<pre><code>import React from 'react';
import { render, fireEvent } from '@testing-library/react-native';
import PaxScroller from './index';

describe('Pax Scroller', () =&gt; {
  test('Scroll Flatlist Horizontal', () =&gt; {
    const { getAllByTestId, getByTestId } = render(
      &lt;PaxScroller checkedInPersonsList={list} /&gt;,
    );
    
    let fList = getByTestId('PaxScrollerFlatList.test');
    fireEvent.scroll(fList, {
      nativeEvent: {
        contentSize: { height: 600, width: 600 },
        contentOffset: { y: 0, x: 0 },
        layoutMeasurement: { height: 100, width: 400 },
      },
    });
  });
}

</code></pre>
<p>After Executing the test case, I can see in the test coverage that onViewableItemsChanged is being called but the inside statements are not getting executed. Is there a way where this statements highlighted in red can be executed?</p>
<p><a href=""https://i.stack.imgur.com/ZaaAR.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZaaAR.png"" alt=""enter image description here"" /></a></p>
<p>Please help me execute the inside statements.</p>
",https://stackoverflow.com/questions/74604212/jest-react-native-flatlist-onviewableitemschanged-on-executing-inside-functions,"['react-native', 'unit-testing', 'jestjs', 'react-native-flatlist', 'flatlist']",359,False,0,0
Modify redis configs using python client,"<p>We are using redis python client to start a local redis server for unit testing. Sample code here:</p>
<pre><code>r = StrictRedis(host=&quot;localhost&quot;, port=6379)
try:
    r.ping()
except ConnectionError:
    subprocess.Popen(&quot;./redis-server&quot;)
</code></pre>
<p>We want to change <a href=""https://stackoverflow.com/a/21484282/3921053"">a redis config</a> to allow us to run unit tests correctly. Since these unit tests run on AWS Lambda, we don't have direct access to the redis-cli to make any permanent config change.</p>
<p>Is there any way to change redis configuration in the python code?</p>
<p>Note: We are not using any redis.conf for unit test. But if there is a solution using that, we can try that too.</p>
",https://stackoverflow.com/questions/71330026/modify-redis-configs-using-python-client,"['python', 'aws-lambda', 'redis']",341,True,0,1
Mock object cannot be cast to Entity object using ModelMapper in unit test,"<p>I am unit testing a service method <code>create product</code>. This method takes in a Dto object and then transfers the Dto object to a <code>ProductEntity</code> object using <code>ModelMapper</code>. This method works fine but when I unit test it, I mock the <code>modelMapper</code> and stub it like this <code>when(modelMapper.map(createProductRequestDto, ProductEntity.class)).thenReturn(expectedProduct)</code> with <code>expectedProduct</code> is a <code>ProductEntity</code> instance, it throws <code>java.lang.ClassCastException</code></p>
<p>StackTrace:</p>
<pre><code>java.lang.ClassCastException: class com.example.demo.dto.responses.product.ProductResponseDto$MockitoMock$737533970 cannot be cast to class com.example.demo.entities.ProductEntity (com.example.demo.dto.responses.product.ProductResponseDto$MockitoMock$737533970 and com.example.demo.entities.ProductEntity are in unnamed module of loader 'app')

    at com.example.demo.services.implementations.product.ProductCrudServiceImpl.createProduct(ProductCrudServiceImpl.java:78)
    at com.example.demo.services.product.ProductCrudServiceImplTest.createProduct_ShouldReturnProductResponseDto(ProductCrudServiceImplTest.java:136)
    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$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
</code></pre>
<p>createProduct service method:</p>
<pre><code>@Override
    public ProductResponseDto createProduct(CreateProductRequestDto createProductRequestDTO) {
        Long genderId = createProductRequestDTO.getGenderId();
        Long sportId = createProductRequestDTO.getSportId();
        List&lt;Long&gt; categoryIds = createProductRequestDTO.getCategoryIds();
        List&lt;Long&gt; technologyIds = createProductRequestDTO.getTechnologyIds();

        GenderEntity genderEntity = genderCrudService.findById(genderId);
        SportEntity sportEntity = sportCrudService.findById(sportId);
        List&lt;CategoryEntity&gt; categoryEntities = categoryCrudService.findByIds(categoryIds);
        List&lt;TechnologyEntity&gt; technologyEntities = technologyService.findByIds(technologyIds);
        Set&lt;TechnologyEntity&gt; technologyEntitySet = technologyEntities.stream().collect(Collectors.toSet());
        Set&lt;CategoryEntity&gt; categoryEntitySet = categoryEntities.stream().collect(Collectors.toSet());

        ProductEntity productEntity = modelMapper.map(createProductRequestDTO, ProductEntity.class);
        productEntity.setTechnologies(technologyEntitySet);
        productEntity.setCategories(categoryEntitySet);
        productEntity.setGender(genderEntity);
        productEntity.setSport(sportEntity);

        productEntity = productRepository.save(productEntity);

        AddSizeToProductRequestDto requestDto = addSizeToProductRequestDtoFactory.createAddSizeToRequestDto(productEntity.getId(), createProductRequestDTO.getProductSizeDtoList());
        productEntity = productSizeService.addSizeToProduct(requestDto);

        return modelMapper.map(productEntity, ProductResponseDto.class);
    }
</code></pre>
<p>Unit test class:</p>
<pre><code>public class ProductCrudServiceImplTest {
    ModelMapper modelMapper;
    ProductCrudServiceImpl productCrudServiceImpl;
    GenderCrudService genderCrudService;
    SportCrudService sportCrudService;
    CategoryCrudService categoryCrudService;
    ProductRepository productRepository;
    TechnologyService technologyService;
    ProductSizeService productSizeService;
    CreateProductRequestDto createProductRequestDTO;
    List&lt;Long&gt; categoryIds;
    List&lt;Long&gt; technologyIds;
    GenderEntity genderEntity;
    SportEntity sportEntity;
    List&lt;CategoryEntity&gt; categoryEntities;
    List&lt;TechnologyEntity&gt; technologyEntities;
    Set&lt;TechnologyEntity&gt; technologyEntitiesSet;
    Set&lt;CategoryEntity&gt; categoryEntitiesSet;
    List&lt;ProductSizeDto&gt; productSizeDtoList;
    ProductEntity initProduct;
    ProductEntity expectedProduct;
    AddSizeToProductRequestDto addSizeToProductRequestDto;
    AddSizeToProductRequestDtoFactory addSizeToProductRequestDtoFactory;
    ProductResponseDto resultProductDto;

    @BeforeEach
    public void beforeEach() {
        modelMapper = mock(ModelMapper.class);
        genderCrudService = mock(GenderCrudService.class);
        sportCrudService = mock(SportCrudService.class);
        categoryCrudService = mock(CategoryCrudService.class);
        productRepository = mock(ProductRepository.class);
        technologyService = mock(TechnologyService.class);
        productSizeService = mock(ProductSizeService.class);
        addSizeToProductRequestDto = mock(AddSizeToProductRequestDto.class);
        addSizeToProductRequestDtoFactory = mock(AddSizeToProductRequestDtoFactory.class);
        productCrudServiceImpl = new ProductCrudServiceImpl(
                modelMapper,
                genderCrudService,
                sportCrudService,
                categoryCrudService,
                productRepository,
                technologyService,
                productSizeService,
                addSizeToProductRequestDtoFactory
        );

        createProductRequestDTO = mock(CreateProductRequestDto.class);
        genderEntity = mock(GenderEntity.class);
        sportEntity = mock(SportEntity.class);
        categoryIds = mock(List.class);
        technologyIds = mock(List.class);
        categoryEntities = Arrays.asList(CategoryEntity.builder().id(1L).name(&quot;category&quot;).description(&quot;description&quot;).build());
        categoryEntitiesSet = categoryEntities.stream().collect(Collectors.toSet());
        technologyEntities = Arrays.asList(TechnologyEntity.builder().id(1L).name(&quot;technology&quot;).description(&quot;description&quot;).build());
        technologyEntitiesSet = technologyEntities.stream().collect(Collectors.toSet());
        expectedProduct = ProductEntity.builder()
                .id(1L)
                .name(&quot;product&quot;)
                .price(1)
                .year(2022)
                .thumbnail(&quot;thumbnail&quot;)
                .sport(sportEntity)
                .gender(genderEntity)
                .technologies(technologyEntitiesSet)
                .categories(categoryEntitiesSet)
                .description(&quot;description&quot;)
                .build();
        productSizeDtoList = mock(List.class);
        addSizeToProductRequestDto = mock(AddSizeToProductRequestDto.class);
        addSizeToProductRequestDtoFactory = mock(AddSizeToProductRequestDtoFactory.class);
        resultProductDto = mock(ProductResponseDto.class);

        when(createProductRequestDTO.getGenderId()).thenReturn(1L);
        when(createProductRequestDTO.getSportId()).thenReturn(2L);
        when(createProductRequestDTO.getCategoryIds()).thenReturn(categoryIds);
        when(createProductRequestDTO.getTechnologyIds()).thenReturn(technologyIds);

        when(genderCrudService.findById(1L)).thenReturn(genderEntity);
        when(sportCrudService.findById(1L)).thenReturn(sportEntity);
        when(categoryCrudService.findByIds(categoryIds)).thenReturn(categoryEntities);
        when(technologyService.findByIds(technologyIds)).thenReturn(technologyEntities);

        when(modelMapper.map(createProductRequestDTO, ProductEntity.class)).thenReturn(expectedProduct);
        when(productRepository.save(any())).thenReturn(expectedProduct);

        when(createProductRequestDTO.getProductSizeDtoList()).thenReturn(productSizeDtoList);
        when(addSizeToProductRequestDtoFactory.createAddSizeToRequestDto(1L, productSizeDtoList)).thenReturn(addSizeToProductRequestDto);
        when(productSizeService.addSizeToProduct(addSizeToProductRequestDto)).thenReturn(expectedProduct);
        when(modelMapper.map(any(), ArgumentMatchers.&lt;Class&lt;ProductResponseDto&gt;&gt;any())).thenReturn(resultProductDto);
    }

    @Test
    public void createProduct_ShouldReturnProductResponseDto() {
        ProductResponseDto result = productCrudServiceImpl.createProduct(createProductRequestDTO);

        ArgumentCaptor&lt;ProductEntity&gt; productCaptor = ArgumentCaptor.forClass(ProductEntity.class);
        verify(productRepository).save(productCaptor.capture());
        ProductEntity savedProduct = productCaptor.getValue();
        verify(modelMapper).map(productCaptor.capture(), ProductEntity.class);
        ProductEntity mappedProduct = productCaptor.getValue();
//
        assertEquals(savedProduct, expectedProduct);
        assertEquals(mappedProduct, expectedProduct);
        assertThat(result, is(resultProductDto));
    }
</code></pre>
<p>I did some research on this but I can't identify the root cause and I have no idea how this could happen. Could you please help me with this?</p>
<p>Thank you very much for your precious time.</p>
",https://stackoverflow.com/questions/72246830/mock-object-cannot-be-cast-to-entity-object-using-modelmapper-in-unit-test,"['java', 'casting', 'junit4', 'modelmapper']",593,True,0,1
How to mock NGXS Select with ng-mock Angular,"<p>Im using <strong>NGXS</strong> store for my Angular project and <strong>ng-mock</strong> for unit testing.</p>
<p>I'm wondering how to deal with NGXS <strong>'@Select'</strong> when testing?</p>
<p>My Component TS</p>
<pre><code>import { Component } from '@angular/core';
import { Select } from '@ngxs/store';
import { Observable } from 'rxjs';
import { Account } from '../../models/account';
import { AccountState } from '../../state/account.state';

@Component({
  templateUrl: './account-management.component.html',
  styleUrls: ['./account-management.component.scss'],
})
export class AccountManagementComponent {
  @Select(AccountState.getAccount) account$!: Observable&lt;Account | null&gt;;
}
</code></pre>
<p>And the template</p>
<pre><code>&lt;app-account-status *ngIf=&quot;(account$ | async) as account&quot; [account]=&quot;account&quot;&gt;
&lt;/app-account-status&gt;
&lt;app-edit-account-form&gt;&lt;/app-edit-account-form&gt;
</code></pre>
<p>What is the proper way to Mock <strong>account$</strong> Observable and test that <strong>app-account-status</strong> get proper data in its input?</p>
<p>In my Test File I Have this</p>
<pre><code>    beforeEach(() =&gt; {
      return MockBuilder(AccountManagementComponent)
      .keep(NgxsModule.forRoot())
    });

    it('Test child component input', fakeAsync(() =&gt; {
        account = getCleanMock(UserAccountMock);
        fixture = MockRender(AccountManagementComponent);
        let component = fixture.componentInstance;
        component['account$']= of(account);

        tick();
        fixture.detectChanges();

        const mockComponent =
        ngMocks.find&lt;AccountStatusComponent&gt;(
          'app-account-status',
        ).componentInstance;

        expect(mockComponent.account).toEqual(account);
    }))
</code></pre>
<p>And I get this error</p>
<p><strong>Cannot set property account$ of [object Object] which has only a getter</strong></p>
<p>My question is how to deal with that and what is the proper way to mock and test?</p>
",https://stackoverflow.com/questions/74430438/how-to-mock-ngxs-select-with-ng-mock-angular,"['angular', 'unit-testing', 'ngxs']",98,False,0,0
Writing Unit Test cases for Web Api in .Net,"<p>I wanted to write unit test cases for my .Net project . This is How my Controller looks like</p>
<pre><code>using backend.Models;
using backend.services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace backend.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    [ApiController]
    public class GuestTypeController : ControllerBase
    {
        private readonly GuestTypeService _guestType;
        public GuestTypeController(GuestTypeService _guestType)
        {
            this._guestType = _guestType;

        }
        [HttpGet(&quot;GuestType&quot;)]

        
         public List&lt;GuestType&gt; guestType()
        {

            return _guestType.getGuestType();
        }
    }
}


</code></pre>
<p>This is how Service class looks like</p>
<pre><code>
namespace backend.services
{
    public class GuestTypeService
    {
        private readonly bookingengineContext dbContext;
        public GuestTypeService(bookingengineContext dbContext)
        {
            this.dbContext = dbContext;
        }

        public List&lt;GuestType&gt; getGuestType()
        {
              
            return dbContext.GuestTypes.ToList();
        }
    }
}
</code></pre>
<p>I have object of service in my constructor of controller . While writing test cases I am calling my controller and mocking my db context and services class. But since my controller contains service class object in contstructor i am not able to test it . What is the way to test my controlller.  This is my first time writing unit testing . So I am struggling.</p>
",https://stackoverflow.com/questions/73540601/writing-unit-test-cases-for-web-api-in-net,"['c#', 'asp.net', '.net', 'entity-framework']",637,True,0,1
Fix OWLOntologyStorageException,"<p>I'm developing a Java application using owl-api. For testing I want to use a TestDataProvider to provide test data for unit-testing.</p>
<p>I'm using version 5.0.0 because the tutorial I read is using this version too. I plan to update later.</p>
<pre><code>&lt;dependency&gt;
            &lt;groupId&gt;net.sourceforge.owlapi&lt;/groupId&gt;
            &lt;artifactId&gt;owlapi-distribution&lt;/artifactId&gt;
            &lt;version&gt;5.0.0&lt;/version&gt;
&lt;/dependency&gt;
</code></pre>
<p>But I run in following exception</p>
<pre><code>org.semanticweb.owlapi.model.OWLOntologyStorageException: java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
    at org.semanticweb.owlapi.util.AbstractOWLStorer.storeOntology(AbstractOWLStorer.java:49)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.saveOntology(OWLOntologyManagerImpl.java:1160)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.saveOntology(OWLOntologyManagerImpl.java:1134)
    at uk.ac.manchester.cs.owl.owlapi.OWLOntologyManagerImpl.saveOntology(OWLOntologyManagerImpl.java:1122)
    at de.abk.wiwiservice.OntologyTestDataProvider.addOWLIndividualToOWLOntology(OntologyTestDataProvider.java:58)
    at de.abk.wiwiservice.OntologyTestDataProvider.&lt;init&gt;(OntologyTestDataProvider.java:32)
    at de.abk.wiwiservice.owlindividual.OWLIndividualRepositoryImplTest.setup(OWLIndividualRepositoryImplTest.java:40)
    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:725)
    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.interceptLifecycleMethod(TimeoutExtension.java:126)
    at org.junit.jupiter.engine.extension.TimeoutExtension.interceptBeforeAllMethod(TimeoutExtension.java:68)
    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.ClassBasedTestDescriptor.lambda$invokeBeforeAllMethods$11(ClassBasedTestDescriptor.java:397)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.invokeBeforeAllMethods(ClassBasedTestDescriptor.java:395)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:209)
    at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.before(ClassBasedTestDescriptor.java:80)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:148)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at java.base/java.util.ArrayList.forEach(ArrayList.java:1541)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
    at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
    at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
    at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
    at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
    at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
    at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
    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:114)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
    at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
    at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
    at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
    at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
    at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
    at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
    at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
Caused by: java.net.ProtocolException: cannot write to a URLConnection if doOutput=false - call setDoOutput(true)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1349)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1342)
    at org.semanticweb.owlapi.util.AbstractOWLStorer.prepareActualOutput(AbstractOWLStorer.java:64)
    at org.semanticweb.owlapi.util.AbstractOWLStorer.storeOntology(AbstractOWLStorer.java:46)
    ... 65 more
</code></pre>
<p>at the last line of <strong>addOWLIndividualToOWLOntology()</strong></p>
<pre><code>public class OntologyTestDataProvider {

    private OWLOntology owlOntology;

    private IRI baseIRI;

    private List&lt;OWLClass&gt; owlClasses;

    private List&lt;OWLIndividual&gt; owlIndividuals;

    private List&lt;OWLDeclarationAxiom&gt; owlDeclarationAxioms;

    public OntologyTestDataProvider() throws OWLOntologyCreationException, OWLOntologyStorageException {
        owlClasses = new ArrayList&lt;&gt;();
        owlDeclarationAxioms = new ArrayList&lt;&gt;();
        owlIndividuals = new ArrayList&lt;&gt;();
        baseIRI = IRI.create(&quot;http://www.semanticweb.org/andreas.b/ontologies/2022/1/test-ontology&quot;);
        OWLOntologyManager owlOntologyManager = OWLManager.createOWLOntologyManager();
        owlOntology = owlOntologyManager.createOntology(baseIRI);
        addOWLClassesToOWLOntology();
        addOWLIndividualToOWLOntology();
    }

    private void addOWLClassesToOWLOntology() {
        final OWLClass person = owlOntology.getOWLOntologyManager().getOWLDataFactory().getOWLClass(baseIRI + &quot;#Person&quot;);
        final OWLClass role = owlOntology.getOWLOntologyManager().getOWLDataFactory().getOWLClass(baseIRI + &quot;#Role&quot;);

        owlClasses.add(person);
        owlClasses.add(role);

        OWLDeclarationAxiom owlDeclarationAxiomPerson = owlOntology.getOWLOntologyManager().getOWLDataFactory().getOWLDeclarationAxiom(person);
        OWLDeclarationAxiom owlDeclarationAxiomRolle = owlOntology.getOWLOntologyManager().getOWLDataFactory().getOWLDeclarationAxiom(role);

        owlDeclarationAxioms.add(owlDeclarationAxiomPerson);
        owlDeclarationAxioms.add(owlDeclarationAxiomRolle);

        owlOntology.add(owlDeclarationAxiomPerson);
        owlOntology.add(owlDeclarationAxiomRolle);
    }

    private void addOWLIndividualToOWLOntology() throws OWLOntologyStorageException {
        final OWLIndividual andy = owlOntology.getOWLOntologyManager().getOWLDataFactory().getOWLNamedIndividual( baseIRI + &quot;#Andy&quot;);
        owlIndividuals.add(andy);
        OWLClassAssertionAxiom andyClassAssertion = owlOntology.getOWLOntologyManager().getOWLDataFactory().getOWLClassAssertionAxiom(owlClasses.get(0), andy);
        owlOntology.getOWLOntologyManager().addAxiom(owlOntology, andyClassAssertion);
        owlOntology.add(andyClassAssertion);
        owlOntology.getOWLOntologyManager().saveOntology(owlOntology);
    }

}
</code></pre>
<p>I already read that I have to retrieve an new OWLOntologyManager from the ontology everytime and changed my code accordingly but that didn't do the trick. I hope you can give me a hint.</p>
",https://stackoverflow.com/questions/71183961/fix-owlontologystorageexception,"['java', 'owl-api']",47,True,0,1
mockStatic of Mockito vs mockStatic of PowerMock,"<p>In order to mock static methods for unit testing in Java we can either use PowerMock or we Can use mockStatic of Mockito. I already know that need to mock static method means code smell and I should refactor the original code but that is not possible as of now.</p>
<p>Sample Class to be Tested</p>
<pre><code>public class classToBeTested{

//Some Code

public static String methodToBeTested() {
// Some Code
}

}
</code></pre>
<p>Testing Using Mockito-Inline (Mockito MockStatic)</p>
<pre><code>public class TestClassToBeTested{
private MockedStatic&lt;classToBeTested&gt; mockedClassToBeTested;

@Test
public void testmethodToBeTested() {

mockedClassToBeTested =
Mockito.mockStatic(classToBeTested.class);
mockedClassToBeTested.when(classToBeTested::methodToBeTested)
.thenReturn(&quot;Some Value&quot;);

// extra code for testing
}
}
</code></pre>
<p>Testing Using PowerMock</p>
<pre><code>public class TestClassToBeTested{

@Test
public void testmethodToBeTested() {

PowerMockito.mockStatic(classToBeTested.class);
when(classToBeTested.methodToBeTested())
.thenReturn(&quot;Some Value&quot;);

// extra code for testing
}
}
</code></pre>
<p>So which mocking technique is better mockito-inline one or power mockito. what is the difference between them? what do they do behind the scene to achieve this?</p>
",https://stackoverflow.com/questions/74741676/mockstatic-of-mockito-vs-mockstatic-of-powermock,"['java', 'unit-testing', 'mockito', 'powermockito', 'mockstatic']",135,False,0,0
Not able to add reference to my project in the test project in visual studio,"<p>I'm writing my first C# program in Visual Studio for mac, and now I want to do unit testing for the code.</p>
<p>I can't add a reference to my original project. When I open the references dialog box it's empty and I'm not able to browse. The test file is in it's own project, therefore not the same namespace.</p>
<p>I followed these steps: <a href=""https://learn.microsoft.com/en-us/visualstudio/test/walkthrough-creating-and-running-unit-tests-for-managed-code?view=vs-2022"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/visualstudio/test/walkthrough-creating-and-running-unit-tests-for-managed-code?view=vs-2022</a></p>
<p>The guide is not for mac but seems to work similar.</p>
",https://stackoverflow.com/questions/73619979/not-able-to-add-reference-to-my-project-in-the-test-project-in-visual-studio,"['c#', 'visual-studio', 'unit-testing']",209,False,0,0
android: Bitmap decodeFile returns NullPointerException,"<p>I am unit testing some images from a resources folder. I am mocking the BitmapFactory method with <a href=""https://github.com/powermock/powermock"" rel=""nofollow noreferrer"">Power Mock</a></p>
<pre><code>   PowerMockito.mockStatic(BitmapFactory::class.java)

      val bitmap: Bitmap =  BitmapFactory.decodeFile(imagePath);
</code></pre>
<p>Everything works fine just that I get an error trying to decode the image path. I am very certain that the path string is not null. The image path is something like this:</p>
<pre><code>/$project location/android/app/build/intermediates/java_res/devDebugUnitTest/out/images/image.jpg
</code></pre>
<p>What could be the reason for this error:</p>
<pre><code>decodeFile(images[0].fullPath) must not be null

java.lang.NullPointerException: decodeFile(imagePath) must not be null
    at biometrics.utils.BiometricFunctionsHelper$Companion.processImages(BiometricFunctionsHelper.kt:71)
    at BiometricsTests.before(BiometricsTests.kt:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:133)
    at org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:96)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:310)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:131)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.access$100(PowerMockJUnit47RunnerDelegateImpl.java:59)
    at org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner$TestExecutorStatement.evaluate(PowerMockJUnit47RunnerDelegateImpl.java:147)
</code></pre>
<p>There is no much details about this error which makes it hard to fix. I tried reducing the size of the image but still didnt work. Please help</p>
",https://stackoverflow.com/questions/74080057/android-bitmap-decodefile-returns-nullpointerexception,"['android', 'unit-testing', 'kotlin']",109,False,0,0
Mocking data and Calling action from container,"<p>I'm having issues making a Unit Testing because I have this code <code>helperController</code> Controller:</p>
<pre><code>public static function applyDiscount(array $params, MoneyParser $moneyParser): Money
{
    $discount = Money::BRL(0);
    switch ($params['typeOf']) {
        case 'above_value':
            $amount = $params['value']-&gt;subtract($params['value']-&gt;multiply(0.85));
            $discount = $discount-&gt;add($amount);
            break;
        case 'above_quantity':
            $subtractedQuantity = intval(round($params['quantity'] / 3));
            $value = $params['value']-&gt;multiply($subtractedQuantity);
            $discount = $discount-&gt;add($value);
            break;
        case 'same_category':
            $lowestVal = 0;
            foreach ($params['cart'] as $item) {
                if (empty($lowestVal)) {
                    $lowestVal = $item['unitPrice'];
                } elseif ($item['unitPrice'] &lt; $lowestVal) {
                    $lowestVal = $item['unitPrice'];
                }
            }
            $valueOf = floatval($lowestVal) * 0.40;
            $rounded = floor($valueOf * 100) / 100;
            $unitPrice = $moneyParser-&gt;parse(strval($rounded), 'BRL');
            $discount = $discount-&gt;add($unitPrice);
            break;
        case 'for_employees':
            $amount = $params['value']-&gt;subtract($params['value']-&gt;multiply(0.80));
            $discount = $discount-&gt;add($amount);
            break;
        case 'for_newones':
            $amount = $moneyParser-&gt;parse('25', 'BRL');
            $discount = $discount-&gt;add($amount);
            break;
    }

    return $discount;
}
</code></pre>
<p>And I'm trying to mock the data to test it, for example, in the first case I'm trying to do this:</p>
<pre><code>public function testApplyDiscountAboveValue(): void
{
    $params = [
        'typeOf' =&gt; 'above_value',
        'value' =&gt; Money::BRL('3001'),
    ];

    $money = app(MoneyParser::class);

    $currency = app(Currency::class, ['code' =&gt; 'BRL']);

    $moneyValue = app(Money::class, [ 
        'amount' =&gt; 3001,
        'currency' =&gt; $currency
    ]);

    $discount = app(Money::class, [
        'amount' =&gt; 450,
        'currency' =&gt; $currency
    ]);

    $mock = Mockery::mock($moneyValue);

    $mock-&gt;shouldReceive('multiply')
        -&gt;with(0.85)
        -&gt;once()
        -&gt;andReturn(Money::BRL('2550'));

    $mock-&gt;shouldReceive('subtract')
        -&gt;with(Money::BRL('2550'))
        -&gt;once()
        -&gt;andReturn(Money::BRL('450'));

    $mock-&gt;shouldReceive('add')
        -&gt;with(Money::BRL('450'))
        -&gt;once()
        -&gt;andReturn(Money::BRL('450'));

    $response = app(HelperDiscountController::class)-&gt;applyDiscount($params, $money);
    $this-&gt;assertEquals($discount, $response);
}
</code></pre>
<p>When I execute the phpunit my result is this:</p>
<blockquote>
<ol>
<li>App\Http\Controllers\HelperDiscountControllerTest::testApplyDiscountAboveValue
Mockery\Exception\InvalidCountException: Method multiply(0.85) from Mockery_0_Money_Money_Money_Money should be called
exactly 1 times but called 0 times.</li>
</ol>
</blockquote>
<p>I'm trying to understand what I am doing wrong. Did I have all the necessary adaptations to test my code at least for the first case?</p>
",https://stackoverflow.com/questions/74140083/mocking-data-and-calling-action-from-container,"['php', 'laravel', 'phpunit', 'laravel-8']",32,True,0,1
unit dep stubs test issue in react native,"<p>Hello i have a an issue with my test.
I have many services and their stubs files that I want to use in unit testing.
the issue is when I run tests I see that my Dependecies test file uses the real services not the fake ones.
example:
les suppose we have this service</p>
<pre><code>export interface TestService { testMethod: () =&gt; string }
</code></pre>
<pre><code>export class TestServiceImpl implements TestService { testMethod (): string { return 'something' } }
</code></pre>
<pre><code>export class TestServiceStub implements TestService { testMethod (): string { return 'fake return' } }
</code></pre>
<p>all services inside a dependencies implementation</p>
<pre><code>// DepenedenciesImpl.ts file

const testservice = new TestServiceImpl();
export const dependencies: Depenedencies = {
  service: testservice;
}
</code></pre>
<p>then I have an assembly</p>
<pre><code>// TestAssembly.ts. - using fake impl

export class TestAssembly implements Depenedencies {
 service: TestServiceStub;

constructor () {
this.service = new TestServiceStub();
}

jest.resetAllMocks();
}
</code></pre>
<p>in configuration the <code>setup-test-env.js</code>
has this line</p>
<pre><code>jest.mock('routetodep/DependenciesImpl', () =&gt; ({
  dependencies: {
    remoteLogger: {
      send: jest.fn(),
    },
  },
}));
</code></pre>
<p>app works correctly but in unit test instead of using fake files it's using the real ones.</p>
<p>what could be the issue?
thanks.</p>
",https://stackoverflow.com/questions/74179779/unit-dep-stubs-test-issue-in-react-native,"['reactjs', 'unit-testing', 'testing', 'jestjs']",11,False,0,0
Testing in JEST React. Invalid hook call,"<p>Learning JEST and unit testing in Javascript, but have errors when testing. There's an error</p>
<blockquote>
<p>Invalid hook call. Hooks can only be called inside of the body of a
function component</p>
<ol>
<li>You might have mismatching versions of React and the renderer (such as React DOM)</li>
<li>You might be breaking the Rules of Hooks</li>
<li>You might have more than one copy of React in the same app
See <a href=""https://reactjs.org/link/invalid-hook-call"" rel=""nofollow noreferrer"">https://reactjs.org/link/invalid-hook-call</a> for tips about how to debug and fix this problem.</li>
</ol>
</blockquote>
<p>I believe that the error comes when the use of renderInTestApp.</p>
<pre><code>import * as React from 'react';
import { render, RenderResult, screen } from '@testing-library/react';
import ReactDom from 'react-dom'
import { EntityJiraOverviewCard, isJiraAvailable } from '@roadiehq/backstage-plugin-jira';
import { permissionApiRef } from '@backstage/plugin-permission-react';
import { overviewContent } from './EntityPage';
import { renderWithEffects } from '@backstage/test-utils';
import {
  MockPermissionApi,
  renderInTestApp,
  TestApiProvider,
} from '@backstage/test-utils';
import {
  EntityProvider,
  starredEntitiesApiRef,
  MockStarredEntitiesApi,
} from '@backstage/plugin-catalog-react';
import { EntityLayout } from '@backstage/plugin-catalog';



describe('Developer Portal Plugin', () =&gt; {
  const jira = {
    apiVersion: 'vi',
    kind: 'Component',
    metadata: {
      name: 'TestPlugin',
      annotations: {
        'jira/project-key': 'DET',
      },
    },
    spec:{
      'type': 'service',
      'lifecycle' : 'production',
      'owner' : 'test',
    },
  };

  const mockedApi = {
   listWorkflowRuns: jest.fn().mockResolvedValue([]),
  };

  const mockPermissionApi = new MockPermissionApi();

  describe('jiraContent', () =&gt; {
     it('Should render Jira View', async () =&gt; {
       const rendered = await renderInTestApp(
         &lt;TestApiProvider
           apis={[
             [isJiraAvailable, mockedApi],
             [starredEntitiesApiRef, new MockStarredEntitiesApi()],
             [permissionApiRef, mockPermissionApi],
           ]}
         &gt;
           &lt;EntityProvider entity={jira}&gt;
             &lt;EntityLayout&gt;
               &lt;EntityLayout.Route path=&quot;/&quot; title=&quot;Overview&quot;&gt;
                 {overviewContent}
               &lt;/EntityLayout.Route&gt;
             &lt;/EntityLayout&gt;
           &lt;/EntityProvider&gt;
         &lt;/TestApiProvider&gt;,
       );

       expect(rendered.getByText('TestPlugin')).toBeInTheDocument();

       await expect(
         rendered.findByText('Devops Engineering Team | software'),
       ).resolves.toBeInTheDocument();
       expect(rendered.getByText('Activity stream')).toBeInTheDocument();
     });
   });
 })
</code></pre>
",https://stackoverflow.com/questions/73197342/testing-in-jest-react-invalid-hook-call,"['javascript', 'jestjs', 'render', 'backstage']",290,False,0,0
"&lt;HttpResponseNotFound status_code=404, &quot;text/html&quot;&gt; in django-test","<p>I'm new to unit testing and I've been trying to test a GET method of the card game that I've built.</p>
<p>My TestCase is the following:</p>
<pre><code>def test_rooms(self):
    c = APIClient()
    room_id = PokerRoom.objects.get(name='planning').id
    request = c.get('http://127.0.0.1:8000/room/{}'.format(room_id))
    print(request)
</code></pre>
<p>The id is a UUID that's why I'm using the room_id method.</p>
<p>My url:</p>
<pre><code>    path('room/&lt;int:pk&gt;', room),
</code></pre>
<p>where room is a @api_view(['GET']) method and pk is the id of the room. But when I try to test it, an error occurs:</p>
<pre><code>&lt;HttpResponseNotFound status_code=404, &quot;text/html&quot;&gt;
</code></pre>
<p>Checked if the room exists in the test database and it exists, now I don't know what is happening. Can someone help me?</p>
",https://stackoverflow.com/questions/70986505/httpresponsenotfound-status-code-404-text-html-in-django-test,"['django', 'python-unittest', 'django-testing']",516,True,0,1
Unit Test For the Controller class,"<p>Hi I am trying to write a simple unit test for a function.</p>
<p>That function is to get something from the Controller class and get a specific item from it.</p>
<p>This is the code that I wanted to do unit test from (In Helper class):</p>
<pre><code>public static string GetMemberCode(Controller controller)
{
    var claim = controller.User.Claims.FirstOrDefault(c =&gt; c.Type == &quot;membercode&quot;);
    return (claim != null) ? claim.Value : string.Empty;
}
</code></pre>
<p>The way this function is called is by using (More than 1 Controller class will be calling this)</p>
<pre><code>string membercode = Helper.GetMemberCode(this)
</code></pre>
<p>This is what I have in my unit testing for now</p>
<pre><code>[Theory]
[InlineData(&quot;asdfqwer&quot;)]
public void GetMemberCode_IfControllerIsValid(string membercode)
{
    //Arrange
    var controller = new Controller(); //ERROR:CS0144 Cannot create an instance of the abstract type or interface 'Controller'
    //TODO: How to assign value inside?
    //Act
    var result = Helper.GetMemberCode(controller);
    //Assert
    result.Should().Be(membercode);
}
</code></pre>
<p>So my question is How to assign value inside the Controller class?</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/71491262/unit-test-for-the-controller-class,"['c#', 'asp.net', 'unit-testing', 'xunit']",243,False,0,0
Indexing a custom Stack Class,"<p>I am currently doing some C# Unit-Testing using an Udemy Course. In this course, the current Stack class is implemented:</p>
<pre><code>namespace Testing
{
    public class Stack&lt;T&gt;
    {
        public readonly List&lt;T&gt; _list = new List&lt;T&gt;();
        
        public int Count =&gt; _list.Count;

        public void Push(T obj)
        {
            if (obj == null)
                throw new ArgumentNullException();
            
            _list.Add(obj);
        }

        public T Pop()
        {
            if (_list.Count == 0)
                throw new InvalidOperationException();

            var result = _list[_list.Count - 1];
            _list.RemoveAt(_list.Count - 1);

            return result; 
        }


        public T Peek()
        {
            if (_list.Count == 0)
                throw new InvalidOperationException();

            return _list[_list.Count - 1];
        }
    }
}
</code></pre>
<p>Now, I do not understand why the <code>Peek</code> function can use:</p>
<pre><code>return _list[_list.Count - 1];
</code></pre>
<p>As far as I know, a list object cannot be indexed, if such functionality is not explicitly implemented (which does not seem to be the case here). Furthermore, if I create an instance of that object:</p>
<pre><code>Stack&lt;int&gt; newStack = new Stack&lt;int&gt;();
newStack.Push(5);
var lastElement = newStack[0];
</code></pre>
<p>I get a squiggly error message:</p>
<pre><code>cannot apply indexing with to an expression of 'Testing.Stack&lt;int&gt;'
</code></pre>
<p>...which supports my assumption that this instance cannot be indexed. Can someone please explain me this behavior?</p>
",https://stackoverflow.com/questions/71578753/indexing-a-custom-stack-class,"['c#', 'list', 'stack']",47,True,-1,1
OutsideClickHandler not firing in React Testing Library,"<p>I'm not able to get trigger the outside click handler from my component inside a React Testing Library test. Runs fine on the client, so just a testing issue.</p>
<pre class=""lang-js prettyprint-override""><code>const Modal = ({ children, onClose }) =&gt; (
  &lt;div role=&quot;presentation&quot;&gt;
    &lt;OutsideClickHandler onOutsideClick={onClose}&gt;
      &lt;div&gt; modal stuff... &lt;/div&gt;
    &lt;/OutsideClickHandler&gt;
  &lt;/div&gt;
)
</code></pre>
<pre class=""lang-js prettyprint-override""><code>it('should close modal when clicked outside', () =&gt; {
  const mockHandleClose = jest.fn()
  render(&lt;Modal {...props} onClose={mockHandleClose} /&gt;)
  fireEvent.click(document)
  // userEvent.click(document.body)  -- Tried this as well with no luck
  expect(mockHandleClose).toBeCalled()
})

// Test output:
//    expect(jest.fn()).toBeCalled()
//    Expected number of calls: &gt;= 1
//    Received number of calls:    0
</code></pre>
<p>I also tried targeting the &quot;presentation&quot; role div with no luck.</p>
<p>RTL Docs for testing a Modal (not OCH, but based off of their own pattern):
<a href=""https://testing-library.com/docs/example-react-modal"" rel=""nofollow noreferrer"">https://testing-library.com/docs/example-react-modal</a></p>
<p>Code Sandbox:
<a href=""https://codesandbox.io/s/react-testing-library-demo-forked-g7su2i?file=/src/__tests__/hello.js"" rel=""nofollow noreferrer"">https://codesandbox.io/s/react-testing-library-demo-forked-g7su2i?file=/src/__tests__/hello.js</a></p>
<p>Referenced this SO post: <a href=""https://stackoverflow.com/questions/56978283/unit-testing-react-click-outside-component-using-jest-and-react-testing-library"">Unit testing React click outside component using Jest and react testing library</a></p>
",https://stackoverflow.com/questions/74212868/outsideclickhandler-not-firing-in-react-testing-library,"['reactjs', 'jestjs', 'react-testing-library', 'react-outside-click-handler']",238,False,0,0
Python unit test gives AttributeError: &#39;TestCalculator&#39; object has no attribute &#39;calculator&#39;,"<p>I am attempting some unit testing in python for the first time for a simple calculator. I have the calculator file as <code>Calculator_steps.py</code></p>
<pre><code>class Calculator:

def addNumbers(self, numberlist):
    total = 0
    if numberlist == &quot;&quot;:
        numberlist = &quot;0&quot;
        numbers = numberlist.split(&quot;,&quot;)
    if len(numbers) &gt; 3:
        raise TypeError(&quot;Only three variables are accepted&quot;)
    for i in range(len(numbers)):
        if int(numbers[i]) &gt; 100:
            raise TypeError(&quot;Only values less than 100 is accepted&quot;)
        try:
            total = total+int(numbers[i])
        except ValueError:
            raise TypeError(&quot;Only integers values are allowed&quot;)
    return total
</code></pre>
<p>I have written a test file as <code>test_calculator.py</code>
There i have 4 test functions to test addition with one integer, two integers, three integers and one to check for only whole numbers</p>
<pre><code>import unittest

import Calculator_steps as CalculatorClass

class TestCalculator(unittest.TestCase):

    def _init_(self):
        self.calculator = CalculatorClass.Calculator()  

    def test_oneIntegers(self):
        self.assertEqual(self.calculator.addNumbers('6'),6)

    def test_twoIntegers(self):
        self.assertEqual(self.calculator.addNumbers('5,6'),11)

    def test_threeIntegers(self):
    self.assertEqual(self.calculator.addNumbers('100,6,7'),113)

    def test_DecimalValues(self):
        with self.assertRaises(Exception):
            self.calculator.addNumbers('5.66,3.44')
</code></pre>
<p>When i try to run this i get <code>AttributeError: 'TestCalculator' object has no attribute 'calculator'</code> for the first three functions. I'm confused as to what the issue is. Can some one explain to me why it is giving this error to the first three and not the fourth.</p>
",https://stackoverflow.com/questions/73918622/python-unit-test-gives-attributeerror-testcalculator-object-has-no-attribute,"['python-3.x', 'unit-testing', 'python-unittest']",339,False,0,1
Configuration error: Could not locate module when running unit test with vue-test-utils and jes,"<p>Been struggling with this configuration error when unit testing with jest and vue-test-util. In detail, I'm testing total of 4 Vue components. The other 3 would pass just fine, but when running test for the fourth one, I ran into configuration issue for a file that is not used by the testing Vue Component:</p>
<p>Terminal Error:</p>
<pre><code> FAIL  tests/unit/panels/EditorContextPanel.spec.ts
  ● Test suite failed to run

    Configuration error:

    Could not locate module @/lib-components/assets/svg/Icons mapped as:
    C:\Users\nnguyen\Documents\NPM.AdvancedEditor.Components\src\$1.

    Please check your configuration for these entries:
    {
      &quot;moduleNameMapper&quot;: {
        &quot;/^@\/(.*)$/&quot;: &quot;C:\Users\nnguyen\Documents\NPM.AdvancedEditor.Components\src\$1&quot;
      },
      &quot;resolver&quot;: undefined
    }

      1 | import { API, BlockAPI, BlockTool, BlockToolData } from '@ado/editorjs'
    &gt; 2 | import Icons from '@/lib-components/assets/svg/Icons'
        | ^
      3 | import './styles/TableBlock.css'
      4 | import { defaultSanitizerConfig } from './configs/sanitizerConfig'
      5 |

      at createNoMappedModuleFoundError (node_modules/jest-resolve/build/resolver.js:579:17)
      at Object.&lt;anonymous&gt; (src/lib-components/editor/BlockTools/TableBlock.ts:2:1)

Test Suites: 1 failed, 4 passed, 5 total
Tests:       10 passed, 10 total
Snapshots:   0 total
Time:        11.308 s
Ran all test suites.
</code></pre>
<p>The testing file that ran into this issue:</p>
<pre><code>import { shallowMount } from '@vue/test-utils'
import EditorContextPanel from '@/lib-components/panels/EditorContextPanel.vue'
import { createTestingPinia } from '@pinia/testing'
import { useApplicationStateStore } from '@/lib-components/stores/applicationStateStore'

describe('ContentToolsPanel', () =&gt; {
  it('panel visible when set', () =&gt; {
    const wrapper = shallowMount(EditorContextPanel, {
      global: {
        plugins: [createTestingPinia()],
      },
    })
    const store = useApplicationStateStore()
    store.showEditorContextButtons = false
    expect(wrapper.find('[data-testid=editor-context-button]').isVisible).toBe(false)
    store.showEditorContextButtons = true
    expect(wrapper.find('[data-testid=editor-context-button]').isVisible).toBe(true)
  })
})
</code></pre>
<p>The Icon file that shows in the Terminal Error:</p>
<pre><code>const Icons = {
  toolbarIcons: {
    bold: '&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot; viewBox=&quot;0 0 20 20&quot;&gt;&lt;path class=&quot;b&quot; d=&quot;M13.6854,9.76a4.1607,4.1607,0,0,0,1.886-3.189A4.506,4.506,0,0,0,11.1314,2q-.066-.0009-.132,0H3.8564V18h8.046a4.334,4.334,0,0,0,1.783-8.24Zm-6.4-4.9h3.429a1.7145,1.7145,0,1,1,0,3.429H7.2854Zm4,10.286h-4v-3.432h4a1.7145,1.7145,0,1,1,0,3.429Z&quot;/&gt;&lt;/svg&gt;',
  }
};

export default Icons;

</code></pre>
<p>my jest config in package.json:</p>
<pre><code>  &quot;jest&quot;: {
    &quot;verbose&quot;: true,
    &quot;cache&quot;: false,
    &quot;moduleFileExtensions&quot;: [
      &quot;js&quot;,
      &quot;json&quot;,
      &quot;ts&quot;,
      &quot;vue&quot;
    ],
    &quot;transform&quot;: {
      &quot;^.+\\.vue$&quot;: &quot;vue3-jest&quot;,
      &quot;^.+\\.(ts|tsx)$&quot;: &quot;ts-jest&quot;,
      &quot;^.+\\.(js|jsx)?$&quot;: &quot;babel-jest&quot;
    },
    &quot;transformIgnorePatterns&quot;: [
      &quot;/node_modules/&quot;
    ],
    &quot;collectCoverage&quot;: false,
    &quot;moduleNameMapper&quot;: {
      &quot;\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$&quot;: &quot;&lt;rootDir&gt;/tests/mocks/fileMock.js&quot;,
      &quot;\\.(css|less)$&quot;: &quot;&lt;rootDir&gt;/tests/mocks/styleMock.js&quot;,
      &quot;^@/(.*)$&quot;: &quot;&lt;rootDir&gt;/src/$1&quot;
    },
    &quot;collectCoverageFrom&quot;: [
      &quot;src/lib-components/**/*.{vue,ts}&quot;,
      &quot;!src/entry.esm.ts&quot;,
      &quot;!src/entry.ts&quot;,
      &quot;!**/main.ts&quot;,
      &quot;!**/index.ts&quot;,
      &quot;!**/styles/**&quot;,
      &quot;!**/stubs/**&quot;,
      &quot;!**/assets/**&quot;
    ],
    &quot;snapshotSerializers&quot;: [
      &quot;jest-serializer-vue&quot;
    ],
    &quot;preset&quot;: &quot;@vue/cli-plugin-unit-jest/presets/typescript-and-babel&quot;,
    &quot;moduleDirectories&quot;: [
      &quot;node_modules&quot;
    ]
  }
</code></pre>
<p>I ran tests with <code>vue-cli-service test:unit --no-cache</code>. Any tips or insight would be greatly appreciated!</p>
",https://stackoverflow.com/questions/72902159/configuration-error-could-not-locate-module-when-running-unit-test-with-vue-tes,"['jestjs', 'vuejs3', 'ts-jest', 'vue-test-utils', 'babel-jest']",627,False,0,1
Feedback on testing approach of MobX store in React,"<p>I am new to testing MobX stores in React with Jest. I have read <a href=""https://stackoverflow.com/questions/61693917/testing-mobx-react-observer-with-react-usecontext-react-mobx"">this</a> and <a href=""https://stackoverflow.com/questions/63907798/mobx-react-test-component"">this</a>, but these posts are focused on testing components with the stores and not the stores <em>themselves</em>.</p>
<p>What would be the best approach for unit testing the stores in isolation with Jest?</p>
<p>My initial thought was instantiating the class (new EpochManager) and then calling the methods to change the state of the store, but a TypeError is thrown <code>TypeError: _EpochManager.default is not a constructor</code>. This probably shows my naivety with MobX.</p>
<p>For example, here is a store that I wish to unit test:</p>
<pre><code>import { createContext } from 'react'
import UnirepContext from './Unirep'
import UserContext from './User'
import { makeAutoObservable } from 'mobx'

const unirepConfig = (UnirepContext as any)._currentValue
const userContext = (UserContext as any)._currentValue

class EpochManager {
    private timer: NodeJS.Timeout | null = null
    private currentEpoch = 0
    readonly nextTransition = 0
    readyToTransition = false

    constructor() {
        makeAutoObservable(this)
        if (typeof window !== 'undefined') {
            this.updateWatch()
        }
    }

    async updateWatch() {
        await unirepConfig.loadingPromise
        if (this.timer) {
            clearTimeout(this.timer)
            this.timer = null
        }
        this.readyToTransition = false
        this.currentEpoch = await unirepConfig.currentEpoch()
        // load the last transition time
        ;(this as any).nextTransition = await this._nextTransition()
        const waitTime = Math.max(this.nextTransition - +new Date(), 0)
        console.log(
            `Next epoch transition in ${waitTime / (60 * 60 * 1000)} hours`
        )
        this.timer = setTimeout(() =&gt; {
            this.timer = null
            this.tryTransition()
        }, waitTime) // if it's in the past make wait time 0
        return waitTime
    }

    private async _nextTransition() {
        await unirepConfig.loadingPromise
        const [lastTransition, epochLength] = await Promise.all([
            unirepConfig.unirep.latestEpochTransitionTime(),
            unirepConfig.epochLength,
        ])
        return (lastTransition.toNumber() + epochLength) * 1000
    }

    private async tryTransition() {
        // wait for someone to actually execute the epoch transition
        for (;;) {
            // wait for the epoch change to happen
            const newEpoch = await userContext.loadCurrentEpoch()
            if (newEpoch &gt; this.currentEpoch) {
                // we're ready to transition,
                this.currentEpoch = newEpoch
                this.readyToTransition = true
                return
            }
            await new Promise((r) =&gt; setTimeout(r, 10000))
        }
    }
}

export default createContext(new EpochManager())
</code></pre>
",https://stackoverflow.com/questions/74223373/feedback-on-testing-approach-of-mobx-store-in-react,"['reactjs', 'testing', 'jestjs', 'mobx', 'mobx-react-lite']",99,False,0,1
Testing a module importing non-existing modules with pytest,"<p>I am testing my code with <a href=""https://docs.pytest.org/en/7.2.x/"" rel=""nofollow noreferrer"">pytest</a>, and locally I have all submodules in the project I am testing checked out. All tests run as they should.</p>
<p>But on our test server, I don't want to check out all submodules to do the unit testing so I of course get <code>ImportError</code> for module imports from these submodules. Locally I just mock them, but when they don't exist I cannot get that far.</p>
<p>What pytest functionality can I use to mock these imports? Or am I thinking of this the wrong way? Thank you.</p>
",https://stackoverflow.com/questions/74207314/testing-a-module-importing-non-existing-modules-with-pytest,"['python', 'pytest']",24,False,0,0
Unit testing retry in Spring Webflux with mocked response,"<p>During unit testing retry the response of the mock seems cached, or most probably I am doing something wrong.</p>
<p>I am trying to request something, if error happened then retry twice with delay of 1 second.</p>
<pre><code>  public Mono&lt;Object&gt; someMethod(String someParam) {
    return someInjectedService.doSomething(someParam)
        .doOnError(ex -&gt; System.out.println(ex + &quot;: &quot; + System.currentTimeMillis()))
        .retryWhen(Retry.fixedDelay(2, Duration.ofSeconds(1)).filter(ex -&gt; ex instanceof SomeCustomException))
        .doOnSuccess(result -&gt; doSomethingOnSuccess(result));
  }
</code></pre>
<p>My test:</p>
<pre><code>  @Test
  void testshouldRequestThrice_whenErrorOccurs() {
    // Given
    String someParam = &quot;testParam&quot;;
    when(someInjectedService.doSomething(someParam))
        .thenReturn(Mono.error(new SomeCustomException(&quot;SomeCustomException&quot;))) // 1st response
        .thenReturn(Mono.error(new SomeCustomException(&quot;SomeCustomException&quot;))) // 2nd response
        .thenReturn(Mono.just(&quot;SomeValidResponse&quot;)); // 3rd valid response

    // When
    var result = testService.someMethod(someParam).block();

    // Then
    // Initial request, followed by two retries
    verify(someInjectedService, times(3)).doSomething(someParam);
  }
</code></pre>
<p>here <code>someInjectedService</code> is a mock.
My plan was to return an exception twice, and on third request return valid response. But what I get is:</p>
<blockquote>
<p>org.mockito.exceptions.verification.TooFewActualInvocations:
someInjectedService.doSomething(&quot;testParam&quot;);</p>
</blockquote>
<blockquote>
<p>Wanted 3 times:
-&gt; at shouldRequestThrice_whenErrorOccurs(test.java:138)</p>
</blockquote>
<blockquote>
<p>But was 1 time:</p>
</blockquote>
<p>While I do see 3 prints from <code>.doOnError(ex -&gt; System.out.println(ex + &quot;: &quot; + System.currentTimeMillis()))</code> block, I feel like the actual request is sent only once.</p>
<p>Thank you in advance,</p>
",https://stackoverflow.com/questions/70770215/unit-testing-retry-in-spring-webflux-with-mocked-response,"['java', 'project-reactor', 'webflux', 'retrywhen']",2367,True,5,1
Error Could not find a part of the path when build the testing .net core application,"<p>I have a testing (unit testing and integration testing) app in .net core 5,,
Another explanation that I can say is that in my solution I have 3 Project , 1 for App and 2 other for testing
when I build my project I get this error</p>
<p>when I build my project I get this error</p>
<blockquote>
<p>Error     Could not find a part of the path 'C:\testProject\obj\Debug\net6.0\testProject.GeneratedMSBuildEditorConfig.editorconfig'.  testProject C:\Program Files\Microsoft Visual Studio\2022\Enterprise\MSBuild\Current\Bin\Roslyn\Microsoft.Managed.Core.targets  190</p>
</blockquote>
<p>Why I get this error?
How can I solve this error?
Thank a bunch</p>
",https://stackoverflow.com/questions/74666115/error-could-not-find-a-part-of-the-path-when-build-the-testing-net-core-applica,"['c#', 'build']",2910,True,5,1
How to verify a method inside a method is called in mockito,"<p>I was doing some unit testing in flutter with mockito, and I feels unable to verify a method is called within another method. The code I've written so far as follows,</p>
<p>The class I want to test</p>
<pre><code>class A {
  void doSomething() {
    callMe();
  }

  void callMe() {}
}
</code></pre>
<p>Mocked class</p>
<pre><code>class MockA extends Mock implements A {}
</code></pre>
<p>The test I wrote,</p>
<pre><code>test(&quot;Test method is called&quot;, () {
    A a = new MockA();
    a.doSomething();
    verify(a.callMe()).called(1);
  });
</code></pre>
<p>When I run the above test I am getting an error</p>
<pre><code>No matching calls. All calls: MockA.doSomething()
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
</code></pre>
<p>If i verify doSomething is called it works, but for a call on callMe within doSomething doesn't work. Is this the default behavior or am I doing something wrong? Please note I need to verify the callMe() method is called when doSomething() is called.</p>
",https://stackoverflow.com/questions/73240744/how-to-verify-a-method-inside-a-method-is-called-in-mockito,"['flutter', 'dart', 'mockito']",1262,True,3,1
How to test update methods?,"<p>I am new in unit testing and use JUnit in my Java (Spring Boot) app. I sometimes need to test update methods, but when I search on the web, there is not a proper example or suggestion. So, could you please clarify me how to test the following update method? I think this may require a different approach than testing void. I also thought that while testing first mocking the record and then update its field and then update. Finally retrieve the record again and compare the updated properties. But I think there may be more proper approach than this inexperienced one.</p>
<pre><code>public PriceDTO update(UUID priceUuid, PriceRequest request) {
    Price price = priceRepository
                    .findByUuid(priceUuid)
                    .orElseThrow(() -&gt; new EntityNotFoundException(PRICE));

    mapRequestToEntity(request, price);
    Price updated = priceRepository.saveAndFlush(price);
    
    return new PriceDTO(updated);
}

private void mapRequestToEntity(PriceRequest request, Price entity) {
    entity.setPriceAmount(request.getPriceAmount());
    // set other props
}
</code></pre>
",https://stackoverflow.com/questions/70606351/how-to-test-update-methods,"['java', 'spring-boot', 'unit-testing', 'junit', 'mockito']",3076,True,3,3
Runtime error when checking colorScheme environment variable in unit tests?,"<p>After updating to Xcode 14.1, when unit testing the following code:</p>
<pre><code>struct MyView&lt;T: ItemProtocol&gt;: View
{
    @Environment(\.colorScheme) var colorScheme
    
    var result: T
    
    var body: some View
    {
        
        VStack(alignment: .leading, spacing: 15) {
            Text(result.displayName)
                .font(.inter(size: 16, weight: .regular, italic: false))
                .foregroundColor(colorScheme == .dark ? .navigationBarTint : .darkBlue)
                .multilineTextAlignment(.leading)
        }
    }
}
</code></pre>
<p><code>.foregroundColor(colorScheme == .dark ? .navigationBarTint : .darkBlue)</code> gives me the following runtime error:</p>
<p><code>Accessing Environment&lt;ColorScheme&gt;'s value outside of being installed on a View. This will always read the default value and will not update.</code></p>
<ol>
<li>This was not an issue before the update</li>
<li>When running the app normally and testing the code between dark/light mode, there are no runtime errors and it works correctly</li>
<li>If I change this code to appease the compiler to not show the error, the runtime error just pops up somewhere else in the code with the same colorScheme check</li>
</ol>
<p>Am I doing something wrong in my code, unit tests setup or is this a bug with Xcode 14.1?</p>
",https://stackoverflow.com/questions/74479108/runtime-error-when-checking-colorscheme-environment-variable-in-unit-tests,"['swift', 'xcode', 'swiftui']",129,False,2,0
Mock class in Python with decorator patch,"<p>I would like to patch a class in Python in unit testing. The main code is this (<code>mymath.py</code>):</p>
<pre><code>class MyMath:
    def my_add(self, a, b):
        return a + b

def add_three_and_two():
    my_math = MyMath()
    return my_math.my_add(3, 2)

</code></pre>
<p>The test class is this:</p>
<pre><code>import unittest
from unittest.mock import patch
import mymath

class TestMyMath(unittest.TestCase):
    @patch('mymath.MyMath')
    def test_add_three_and_two(self, mymath_mock):
        mymath_mock.my_add.return_value = 5

        result = mymath.add_three_and_two()

        mymath_mock.my_add.assert_called_once_with(3, 2)
        self.assertEqual(5, result)

unittest.main()

</code></pre>
<p>I am getting the following error:</p>
<pre><code>AssertionError: Expected 'my_add' to be called once. Called 0 times.
</code></pre>
<p>The last assert would also fail:</p>
<pre><code>AssertionError: 5 != &lt;MagicMock name='MyMath().my_add()' id='3006283127328'&gt;
</code></pre>
<p>I would expect that the above test passes. What I did wrong?</p>
<p>UPDATE:
Restrictions:</p>
<ul>
<li>I would not change the tested part if possible. (I am curious if it is even possible, and this is the point of the question.)</li>
<li>If not possible, then I want the least amount of change in the to be tested part. Especially I want to keep the <code>my_add()</code> function non-static.</li>
</ul>
",https://stackoverflow.com/questions/74525368/mock-class-in-python-with-decorator-patch,"['python', 'python-unittest', 'python-unittest.mock']",49,True,2,2
"Unit Test with Express, TypeScript, Prisma and Jest","<p>I'm trying to unit test with Prisma and Jest following this link <a href=""https://www.prisma.io/docs/guides/testing/unit-testing"" rel=""nofollow noreferrer"">https://www.prisma.io/docs/guides/testing/unit-testing</a>.
Here is my test code:</p>
<pre><code>test(&quot;should create a user &quot;, async () =&gt; {   
    var user: any = {
    store_id: &quot;601d6dea-9b89-4c0d-adfc-6ed52424a2a0&quot;,
    password: '1234',
    user_name: &quot;username&quot;,
    first_name: &quot;Rich&quot;,
    last_name: &quot;hello@prisma.io&quot;,
    phone: &quot;12345&quot;,
    is_phone_verified: true,
    is_email_verified: true,   };

  prismaMock.sec_user_fs.create.mockImplementation(user)

  await expect(createUser(user)).resolves.toEqual({
    store_id: &quot;601d6dea-9b89-4c0d-adfc-6ed52424a2a0&quot;   }); });
</code></pre>
<p>createUser method is save data to database. Here is code:</p>
<pre><code>export async function createUser(user: CreateUser) {
  
    user = await prisma.sec_user_fs.create({
      data: user,
    })

    return {&quot;store_id&quot;: user.store_id} }
</code></pre>
<p>So my questions are:</p>
<ol>
<li><p>prismaMock.sec_user_fs.create.mockImplementation(user) - In my understanding this line mocked database table, it prevent not insert data to table while testing. But, it does. How can mock without inserting, updating,deleting to table?</p>
</li>
<li><p>createUser method return json object. But if i test my api end point /code is below/ how expect result? Because it does return res.status(200) etc.?</p>
</li>
</ol>
<pre><code>export default asyncHandler(async (req: CustomRequest, res: Response)=&gt; {

  const body = {
    user_name: req.body.user_name,
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    phone: req.body.phone,
    phone_country_code: req.body.phone_country_code   }

  const user_id = req.params.id

  const user = await prisma.sec_user_fs.updateMany({
    where: {
      user_id,
      status: 'A'
    },
    data: body   });

  res.status(200).send({
    status: 'Success',
    message: req.t('success'),
    errors: [],
    data: user,   }); });
</code></pre>
<p>Thanks in advance :)</p>
",https://stackoverflow.com/questions/72500670/unit-test-with-express-typescript-prisma-and-jest,"['express', 'unit-testing', 'jestjs', 'prisma']",777,False,2,0
"When testing, code that causes React state updates should be wrapped into act(...) - with simple react-native nested screen/components with jest axios","<p>I am new to unit testing/jest, but I know some about react native.
I want to write a test for my HomeScreen, which contains a component that makes a simple request. The code runs without any issue but fails when I run it with Jest.</p>
<p><strong>HomeScreen.js</strong></p>
<pre><code>import { View } from 'react-native'
import APIExample from '@components/Examples/APIExample'
const HomeScreen = () =&gt; {
    return (&lt;View&gt; &lt;APIExample /&gt; &lt;/View&gt;)
}
export default HomeScreen
</code></pre>
<p><strong>HomeScreen.test.js</strong></p>
<pre><code>import { render } from '@testing-library/react-native'
import HomeScreen from '@screens/HomeScreen'

it('should run', async () =&gt; {
    const { getByText } = await render(&lt;HomeScreen /&gt;)
})
</code></pre>
<p><strong>APIExample.js</strong></p>
<pre><code>import { useState, useEffect } from 'react'
import { Text, View } from 'react-native'
import API from '../../API'

const APIExample = () =&gt; {
    const [apiResponse, setApiResponse] = useState(null)

    const Submit = async () =&gt; {
        const response = await API.Test()
        setApiResponse(response)
    }
    useEffect(() =&gt; {
        Submit()
    }, [])
    return (
        &lt;View&gt;
            &lt;Text&gt;
                {JSON.stringify(apiResponse)}
            &lt;/Text&gt;
        &lt;/View&gt;
    )
}
export default APIExample
</code></pre>
<p>I try to figure out why does it keep saying that I should wrap it in act and what exactly do I need to wrap?
I already tried to wrap the render whole line but had no success.</p>
<p>The API.Test is a simple axios.get</p>
<p>The error I've kept getting is:</p>
<pre><code>Warning: An update to APIExample inside a test was not wrapped in act(...).

When testing, code that causes React state updates should be wrapped into act(...):

act(() =&gt; {
  /* fire events that update state */
});
/* assert on the output */

This ensures that you're testing the behavior the user would see in the browser. Learn more at https://reactjs.org/link/wrap-tests-with-act
</code></pre>
",https://stackoverflow.com/questions/70684277/when-testing-code-that-causes-react-state-updates-should-be-wrapped-into-act,"['reactjs', 'react-native', 'jestjs', 'testing-libraryreact-native']",1705,True,2,3
How to trigger place_changed event in Jest,"<p>I am learning how to use the Google Maps API with my React app.</p>
<p>However, I am facing issues with unit testing the google api.</p>
<p>However, there is an issue with global.google.maps.event (it is apparently undefined). I had to mock window.google for the Autocomplete object. So I need to use the 'real' trigger method on the event obj, but mock the autocomplete.</p>
<p>My test for initialisation passes, but not for the 2nd one on triggering the event. I am trying to trigger a place_changed event manually and to check that the place changed handler is called.</p>
<p>Code is as below:</p>
<p>initAutocomplete.ts</p>
<pre><code>import { handlePlaceChange } from &quot;../handlePlaceChange/handlePlaceChange&quot;;

export const initAutocomplete = () =&gt; {
    let autoComplete: google.maps.places.Autocomplete;
    autoComplete = new window.google.maps.places.Autocomplete(
        document.getElementById('autocomplete') as HTMLInputElement,
        {
        types: ['establishment'],
        componentRestrictions: { 'country': ['SG']},
        fields: ['place_id', 'name', 'geometry']
        }
    )
    autoComplete.addListener(&quot;place_changed&quot;, () =&gt; handlePlaceChange(autoComplete))
}
</code></pre>
<p>initAutocomplete.test.ts</p>
<pre><code>
import { handlePlaceChange } from &quot;../handlePlaceChange/handlePlaceChange&quot;;
import { initAutocomplete } from &quot;./initAutocomplete&quot;;

jest.mock(&quot;../handlePlaceChange/handlePlaceChange&quot;);
document.getElementById = jest.fn();
const mockAddListener = jest.fn();
const mockAutoComplete = jest.fn();

window['google'] = {
    maps: {
        places: {
            Autocomplete: mockAutoComplete
        } as unknown as google.maps.places.Autocomplete
    } as unknown as google.maps.Place
} as any


describe('initAutocomplete', () =&gt; {
    const mockInputElement : HTMLInputElement = document.createElement('input');
    beforeEach(() =&gt; { 
        (document.getElementById as jest.Mock).mockReturnValue(mockInputElement);
        (mockAutoComplete as jest.Mock).mockReturnValue({ addListener: mockAddListener });
    });
    
    // this test passes
    it('initialises google map Autocomplete object', () =&gt; {
        initAutocomplete();
        expect(mockAutoComplete).toHaveBeenCalledWith(
            mockInputElement,
            {
                types: ['establishment'],
                componentRestrictions: { 'country': ['SG']},
                fields: ['place_id', 'name', 'geometry']
            }
        );
    });
    
    it('calls handlePlaceChange handler when place_changed event is triggered', () =&gt; {
        initAutocomplete();
    
        // Cannot read properties of undefined (reading 'trigger') 
        global.google.maps.event.trigger(mockAutoComplete, 'place_changed'); // fails at this line
        expect(handlePlaceChange).toHaveBeenCalledWith(mockAutoComplete);
    });
})
</code></pre>
",https://stackoverflow.com/questions/71722761/how-to-trigger-place-changed-event-in-jest,"['javascript', 'unit-testing', 'google-maps', 'google-maps-api-3', 'jestjs']",587,False,2,0
Gradient of Image in PyTorch - for Gradient Penalty calculation in WGAN,"<p>I am following this <a href=""https://github.com/amanchadha/coursera-gan-specialization/blob/main/C1%20-%20Build%20Basic%20Generative%20Adversarial%20Networks/Week%203/C1W3_WGAN_GP.ipynb"" rel=""nofollow noreferrer"">Github Repo</a> for the WGAN implementation with Gradient Penalty.</p>
<p>And I am trying to understand the following method, which does the job of unit-testing the gradient-penalty calulations.</p>
<pre class=""lang-py prettyprint-override""><code>def test_gradient_penalty(image_shape):
    bad_gradient = torch.zeros(*image_shape)
    bad_gradient_penalty = gradient_penalty(bad_gradient)
    assert torch.isclose(bad_gradient_penalty, torch.tensor(1.))

    image_size = torch.prod(torch.Tensor(image_shape[1:]))
    good_gradient = torch.ones(*image_shape) / torch.sqrt(image_size)
    good_gradient_penalty = gradient_penalty(good_gradient)
    assert torch.isclose(good_gradient_penalty, torch.tensor(0.))

    random_gradient = test_get_gradient(image_shape)
    random_gradient_penalty = gradient_penalty(random_gradient)
    assert torch.abs(random_gradient_penalty - 1) &lt; 0.1

# Now pass tuple argument for image dimenstion of 
# (batch_size, channel, height, width)
test_gradient_penalty((256, 1, 28, 28))
</code></pre>
<h3>I don't understand the below line</h3>
<p><code>good_gradient = torch.ones(*image_shape) / torch.sqrt(image_size)</code></p>
<p>In above the <code>torch.ones(*image_shape)</code> is just filling a 4-D Tensor filled up with 1 and then
<code>torch.sqrt(image_size)</code> is just representing the value of <code>tensor(28.)</code></p>
<h3>So, what I am trying to understand why I need to divide the 4-D Tensor by <code>tensor(28.)</code> to get the <code>good_gradient</code></h3>
<p>If I print bad_gradient, it will be a 4-D Tensor as below</p>
<pre><code>tensor([[[[0., 0., 0.,  ..., 0., 0., 0.],
          [0., 0., 0.,  ..., 0., 0., 0.],
          [0., 0., 0.,  ..., 0., 0., 0.],
          ...,
          [0., 0., 0.,  ..., 0., 0., 0.],
          [0., 0., 0.,  ..., 0., 0., 0.],
          [0., 0., 0.,  ..., 0., 0., 0.]]],

          ---
          ---
</code></pre>
<p>If I print <code>good_gradient</code>, the output will be</p>
<pre><code>tensor([[[[0.0357, 0.0357, 0.0357,  ..., 0.0357, 0.0357, 0.0357],
          [0.0357, 0.0357, 0.0357,  ..., 0.0357, 0.0357, 0.0357],
          [0.0357, 0.0357, 0.0357,  ..., 0.0357, 0.0357, 0.0357],
          ...,
          [0.0357, 0.0357, 0.0357,  ..., 0.0357, 0.0357, 0.0357],
          [0.0357, 0.0357, 0.0357,  ..., 0.0357, 0.0357, 0.0357],
          [0.0357, 0.0357, 0.0357,  ..., 0.0357, 0.0357, 0.0357]]],

          ---
          ---
</code></pre>
",https://stackoverflow.com/questions/71685494/gradient-of-image-in-pytorch-for-gradient-penalty-calculation-in-wgan,"['python', 'deep-learning', 'pytorch', 'computer-vision', 'generative-adversarial-network']",469,True,2,1
how to convert this format csv file to a json file?,"<p>The CSV file looks like this way, I have the id and tags. But some tag may have multiple value, each value take one column, so some tag may have multiple columns.</p>
<pre><code>id,tags
403744,[&quot;&quot;]
403745,[&quot;phsecurity&quot;]
403750,[&quot;unit-testing&quot;,&quot;testing&quot;,&quot;boolean&quot;]
403757,[&quot;&quot;]
403759,[&quot;object-oriented&quot;,&quot;architectural-patterns&quot;]
</code></pre>
<p>I try to use this python code to convert:</p>
<pre><code>import csv
import json


# Function to convert a CSV to JSON
# Takes the file paths as arguments
def make_json(csvFilePath, jsonFilePath):

    # create a dictionary
    data = {}

    # Open a csv reader called DictReader
    with open(csvFilePath, encoding='utf-8') as csvf:
        csvReader = csv.DictReader(csvf)

        # Convert each row into a dictionary
        # and add it to data
        for rows in csvReader:

            # Assuming a column named 'No' to
            # be the primary key
            key = rows['id']
            data[key] = rows

    # Open a json writer, and use the json.dumps()
    # function to dump data
    with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
        jsonf.write(json.dumps(data, indent=4))

# Driver Code


# Decide the two file paths according to your
# computer system
csvFilePath = r'aaa.CSV'
jsonFilePath = r'bbb.json'

# Call the make_json function
make_json(csvFilePath, jsonFilePath)
</code></pre>
<p>However it give the format like this:
{
&quot;403744&quot;: {
&quot;id&quot;: &quot;403744&quot;,
&quot;tags&quot;: &quot;[&quot;&quot;]&quot;
},
&quot;403745&quot;: {
&quot;id&quot;: &quot;403745&quot;,
&quot;tags&quot;: &quot;[&quot;phsecurity&quot;]&quot;
},
&quot;403750&quot;: {
&quot;id&quot;: &quot;403750&quot;,
&quot;tags&quot;: &quot;[&quot;unit-testing&quot;&quot;,
&quot;null&quot;: [
&quot;testing&quot;,
&quot;boolean]&quot;
]
}</p>
<p>This is not the correct json format.Like I want to add &quot;testing&quot; and &quot;boolean&quot;  also in the tags. Also you can see, it put &quot;[&quot;or &quot;]&quot; into the value too.Anyone know how to fix it ?Thanks</p>
",https://stackoverflow.com/questions/72778207/how-to-convert-this-format-csv-file-to-a-json-file,"['json', 'csv']",66,True,1,1
Reactor TestPublisher not working with non-completing flux,"<p>I think this is a very basic question about unit testing with project reactor (java), but I've been looking at the docs and can't figure out what my misunderstanding is. I've been trying to use TestPublisher and StepVerifier to test a flux that is supposed to be never-ending, so my scenario doesn't include a terminal signal.</p>
<p>Whereas using a regular sink created with Sinks.many().unicast() works as I expect, using TestPublisher doesn't:</p>
<pre><code>import org.junit.jupiter.api.Test;
import reactor.core.publisher.Sinks;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;

import java.time.Duration;

public class ExploreStepVerifier {

    // this test fails: Did not observe any item or terminal signal within 1000ms in 'source(FluxSource)'
    @Test
    void test_with_test_publisher() {
        TestPublisher&lt;String&gt; publisher = TestPublisher.create();
        publisher.next(&quot;hello&quot;);
        var result = publisher.flux();
        StepVerifier.create(result)
            .expectNext(&quot;hello&quot;).as(&quot;initial message received&quot;)
            .verifyTimeout(Duration.ofSeconds(1));
    }

    // this test succeeds
    @Test
    void test_with_sink() {
        Sinks.Many&lt;String&gt; sink = Sinks.many().unicast().onBackpressureBuffer();
        sink.tryEmitNext(&quot;hello&quot;);
        var result = sink.asFlux();
        StepVerifier.create(result)
            .expectNext(&quot;hello&quot;).as(&quot;initial message received&quot;)
            .verifyTimeout(Duration.ofSeconds(1));
    }
}
</code></pre>
<p>I expected that I'd be able to  substitute  TestPublisher for sink as shown in test_with_test_publisher, but it doens't work.  Can anyone explain?
Thanks--</p>
",https://stackoverflow.com/questions/71050759/reactor-testpublisher-not-working-with-non-completing-flux,"['unit-testing', 'project-reactor']",425,True,1,1
Why are my testing-library queries not working?,"<p>I am using Jest/React Testing Library(RTL) to to unit testing for the UI.</p>
<p>None of my RTL queries work.</p>
<p>It keeps telling me errors like</p>
<pre><code>TestingLibraryElementError: Unable to find an element by: [data-testid=&quot;analysis-categories-header&quot;]
</code></pre>
<p>no matter how I query it.</p>
<p>I have tried <code>getBy*, findBy*(yes, with async...await), getByTestId</code> and everything.</p>
<p>The only difference is that when I use <code>findBy*</code> I get an extra error that says</p>
<pre><code>Error: Error: connect ECONNREFUSED 127.0.0.1:80
</code></pre>
<p>even <code>screen.debug()</code> is ignored and not working.</p>
<p>Out of the 13 tests I have, only one test work surprisingly. The queries go through.
test:</p>
<pre><code>import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import { HelmetProvider } from 'react-helmet-async';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
import Login from '../src/pages/login';

test('renders logo and login box with &quot;LOG IN&quot; text and two buttons', () =&gt; {
  const initState = {};
  const mockStore = configureStore();

  render(
    &lt;HelmetProvider&gt;
      &lt;Provider store={mockStore(initState)}&gt;
        &lt;Login /&gt;
      &lt;/Provider&gt;
    &lt;/HelmetProvider&gt;,
  );

  expect(screen.getByTestId('login-logo')).toBeVisible();
  expect(screen.getByTestId('login-title')).toBeVisible();
  expect(screen.getByRole('button', { name: 'Sign In' })).toBeVisible();
  expect(
    screen.getByRole('button', { name: 'Sign In With Intuit' }),
  ).toBeVisible();
});
</code></pre>
<p>component:</p>
<pre><code>import { useAuth0 } from '@auth0/auth0-react';
import {
  Box,
  Button,
  Card,
  CardContent,
  Container,
  Typography,
} from '@material-ui/core';
import Link from 'next/link';
import { useRouter } from 'next/router';
import type { FC } from 'react';
import React, { useEffect } from 'react';
import { Helmet } from 'react-helmet-async';
import Logo from 'src/components/Logo';
import axios from 'src/lib/axios';
import gtm from 'src/lib/gtm';

const Login: FC = () =&gt; {
  const router = useRouter();
  const { isLoading, isAuthenticated, loginWithRedirect } = useAuth0();

  useEffect(() =&gt; {
    gtm.push({ event: 'page_view' });
  }, []);

  useEffect(() =&gt; {
    if (!isLoading &amp;&amp; isAuthenticated) {
      router.push('/recommendations');
    }
  }, [isLoading, isAuthenticated]);

  const handleIntuitLogin = async () =&gt; {
    try {
      const response = await axios.get('/auth/sign-in-with-intuit');
      window.location = response.data;
    } catch (e) {
      throw new Error(e);
    }
  };

  const handleAuth0Login = async () =&gt; {
    try {
      const response = await axios.get('/auth/sign-in-with-auth0');
      window.location = response.data;
    } catch (e) {
      throw new Error(e);
    }
  };
  return (
    &lt;&gt;
      &lt;Helmet&gt;
        &lt;title&gt;Login&lt;/title&gt;
      &lt;/Helmet&gt;
      &lt;Box
        sx={{
          backgroundColor: 'background.default',
          display: 'flex',
          flexDirection: 'column',
          minHeight: '100vh',
        }}
      &gt;
        &lt;Container maxWidth=&quot;sm&quot; sx={{ py: '80px' }}&gt;
          &lt;Box
            sx={{
              display: 'flex',
              justifyContent: 'center',
              mb: 8,
            }}
          &gt;
            &lt;Link href=&quot;/login&quot;&gt;
              &lt;Box&gt;
                &lt;Logo height={100} width={300} /&gt;
              &lt;/Box&gt;
            &lt;/Link&gt;
          &lt;/Box&gt;
          &lt;Card&gt;
            &lt;CardContent
              sx={{
                display: 'flex',
                flexDirection: 'column',
                p: 4,
              }}
            &gt;
              &lt;Box
                sx={{
                  alignItems: 'center',
                  display: 'flex',
                  justifyContent: 'space-between',
                  mb: 3,
                }}
              &gt;
                &lt;div&gt;
                  &lt;Typography
                    color=&quot;textPrimary&quot;
                    gutterBottom
                    variant=&quot;h4&quot;
                    data-testid=&quot;login-title&quot;
                  &gt;
                    Log in
                  &lt;/Typography&gt;
                &lt;/div&gt;
              &lt;/Box&gt;
              &lt;Box
                sx={{
                  flexGrow: 1,
                  mt: 3,
                }}
              &gt;
                &lt;Button
                  color=&quot;primary&quot;
                  onClick={handleAuth0Login}
                  fullWidth
                  size=&quot;large&quot;
                  type=&quot;button&quot;
                  variant=&quot;contained&quot;
                &gt;
                  Sign In
                &lt;/Button&gt;
              &lt;/Box&gt;

              &lt;Box sx={{ mt: 2 }}&gt;
                &lt;Button
                  color=&quot;primary&quot;
                  onClick={handleIntuitLogin}
                  fullWidth
                  size=&quot;large&quot;
                  type=&quot;button&quot;
                  variant=&quot;contained&quot;
                &gt;
                  Sign In With Intuit
                &lt;/Button&gt;
              &lt;/Box&gt;
            &lt;/CardContent&gt;
          &lt;/Card&gt;
        &lt;/Container&gt;
      &lt;/Box&gt;
    &lt;/&gt;
  );
};

export default Login;
</code></pre>
<p>The only difference is that this component (nextjs page) does not use redux thunk. This is how far I got to find the cause.</p>
",https://stackoverflow.com/questions/71710756/why-are-my-testing-library-queries-not-working,"['javascript', 'reactjs', 'unit-testing', 'testing', 'jestjs']",656,False,1,0
vue 2 jest coverage is incorrect,"<p>I have setup unit testing using installation instructions from <a href=""https://v1.test-utils.vuejs.org/"" rel=""nofollow noreferrer"">https://v1.test-utils.vuejs.org/</a></p>
<p>Tests are running properly. But the coverage is coming incorrectly.</p>
<p>In the report it is showing it has only 1 statement, 1 function, 2 branches for some reason.</p>
<p>It's not showing coverage for all the lines. It shows coverage in the first line and doesn't show coverage anywhere else. Don't know what's the issue is here.</p>
<p>I'm using Bootstrap-vue to render components. Can this create an issue with coverage? I'm asking this because the example.spec.js that came for the helloworld component is showing coverage correctly.</p>
<p><a href=""https://i.stack.imgur.com/wnyXJ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/wnyXJ.png"" alt=""enter image description here"" /></a></p>
<p>my dev dependencies</p>
<pre><code>&quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;^7.12.16&quot;,
    &quot;@babel/eslint-parser&quot;: &quot;^7.12.16&quot;,
    &quot;@vue/cli-plugin-babel&quot;: &quot;~5.0.0&quot;,
    &quot;@vue/cli-plugin-eslint&quot;: &quot;~5.0.0&quot;,
    &quot;@vue/cli-plugin-unit-jest&quot;: &quot;^5.0.4&quot;,
    &quot;@vue/cli-service&quot;: &quot;~5.0.0&quot;,
    &quot;@vue/test-utils&quot;: &quot;^1.3.0&quot;,
    &quot;@vue/vue2-jest&quot;: &quot;^27.0.0-alpha.2&quot;,
    &quot;babel-jest&quot;: &quot;^27.0.6&quot;,
    &quot;eslint&quot;: &quot;^7.32.0&quot;,
    &quot;eslint-plugin-vue&quot;: &quot;^8.0.3&quot;,
    &quot;flush-promises&quot;: &quot;^1.0.2&quot;,
    &quot;jest&quot;: &quot;^27.0.5&quot;,
    &quot;node-sass&quot;: &quot;^7.0.1&quot;,
    &quot;sass-loader&quot;: &quot;^12.6.0&quot;,
    &quot;vue-template-compiler&quot;: &quot;^2.6.14&quot;
  },
</code></pre>
",https://stackoverflow.com/questions/71837311/vue-2-jest-coverage-is-incorrect,"['vue.js', 'code-coverage', 'vue-test-utils', 'vue-testing-library']",1066,False,1,0
Unit testing of Angular app in Azure DevOps pipeline timing out,"<p>I'm trying to set up testing of our Angular app in an Azure DevOps pipeline, but am running into trouble with unit testing timing out.  This is in a Linux virtual machine, with the chromedriver npm package installed (<code>npm install chromedriver --chromedriver-force-download --include_chromium</code>).  Below is the error I am seeing (I tried increasing the timeout period, but it still times out):</p>
<pre><code>INFO [karma-server]: Karma v6.3.17 server started at http://localhost:9876/
INFO [launcher]: Launching browsers ChromeHeadless with concurrency unlimited
INFO [launcher]: Starting browser ChromeHeadless
WARN [launcher]: ChromeHeadless has not captured in 180000 ms, killing.
INFO [launcher]: Trying to start ChromeHeadless again (1/2).
WARN [launcher]: ChromeHeadless has not captured in 180000 ms, killing.
INFO [launcher]: Trying to start ChromeHeadless again (2/2).
WARN [launcher]: ChromeHeadless has not captured in 180000 ms, killing.
ERROR [launcher]: ChromeHeadless failed 2 times (timeout). Giving up.
</code></pre>
<p>The <code>CHROME_BIN</code> environment variable is set correctly via:</p>
<pre><code>export CHROME_BIN=&lt;project-path&gt;/node_modules/chromedriver/lib/chromedriver/chromedriver
</code></pre>
<p>Testing then then started with:</p>
<pre><code>ng test --watch=false --browsers=ChromeHeadless --reporters=junit --code-coverage
</code></pre>
<p>Is the chromedriver sufficient to run unit tests on an Angular app?  Do I need to install something else?  Is there any way to tell if testing is even happening?</p>
",https://stackoverflow.com/questions/72875291/unit-testing-of-angular-app-in-azure-devops-pipeline-timing-out,"['angular', 'unit-testing', 'azure-pipelines']",590,False,1,0
Mapbox Unit Testing - Failed to initialize WebGL,"<p>I'm currently using Mapbox for a React application and I'm trying to perform unit testing but it doesn't seem to work. I've set the Mapbox testMode to true and it still gives me an error saying:</p>
<pre><code>Error: Failed to initialize WebGL.
at new Map (C:\Users\...\node_modules\mapbox-gl\dist\mapbox-gl.js:35:427889)
</code></pre>
<p>The following snippet is how we generate the mapbox component which also receives a test variable to set the testMode.</p>
<pre><code>const MapBox = (props: MapBoxProps) =&gt; {
  const { floorPlan, isTest } = props;
  const { width } = useWindowDimensions();
  const mapContainer = useRef(null);
  const map = useRef(null);
  const [lng, setLng] = useState(48);
  const [lat, setLat] = useState(25);
  const [zoom, setZoom] = useState(1.8);

  const createMapbox = () =&gt; {
    if (!isTest) {
      mapboxgl.accessToken = appConfig.MAPBOX_TOKEN;
    }
    const mb = new mapboxgl.Map({
      attributionControl: false,
      container: mapContainer.current,
      testMode: isTest,
      style: {
        version: 8,
        sources: {},
        layers: [
          {
            id: &quot;background&quot;,
            type: &quot;background&quot;,
            paint: {
              &quot;background-color&quot;: &quot;white&quot;,
            },
          },
        ],
      },
      center: [lng, lat],
      zoom: zoom,
      maxZoom: 6,
      dragRotate: false,
    });
    mb.addControl(new mapboxgl.NavigationControl({ showCompass: false }));
    return mb;
  };
  return &lt;div
        data-cr=&quot;mapbox-container&quot;
        ref={mapContainer}
      /&gt;;
}
</code></pre>
<p>And the code for testing our <strong>CustomMapBox</strong> component is as follows:</p>
<pre><code>const renderMapBox = () =&gt; {
  return render(&lt;CustomMapBox floorPlan={mockedFloorPlan} isTest={true} /&gt;);
};

describe(&quot;MapBox&quot;, () =&gt; {
  it(&quot;renders without error and two floors&quot;, () =&gt; {
    renderMapBox();
  });
}
</code></pre>
<p>I've tried to:</p>
<ul>
<li>Change versions</li>
<li>Change jest configurations</li>
<li>Set mapbox testMode to true</li>
</ul>
<p>And nothing seems to work.</p>
<p>Versions:</p>
<pre><code>&quot;mapbox-gl&quot;: &quot;^2.8.2&quot;,
&quot;react&quot;: &quot;^17.0.2&quot;,
&quot;react-dom&quot;: &quot;^17.0.2&quot;,
&quot;ts-jest&quot;: &quot;^27.0.7&quot;,
&quot;jest&quot;: &quot;^27.3.1&quot;,
</code></pre>
<p>I'd really appreciate if someone could help me.
Best regards,
Daniel</p>
",https://stackoverflow.com/questions/72628355/mapbox-unit-testing-failed-to-initialize-webgl,"['javascript', 'reactjs', 'typescript', 'unit-testing', 'mapbox']",859,False,1,1
"Test register user method with user lookup, encode and websocket","<p>I'm testing my application using jest for unit testing in my service. I'm having trouble understanding how I would test a method of creating a new user, methods within it have others that validate if this user already exists (find : username), I get the password and use a hash to encrypt, in addition to using websocket for the created to identify a new user and reflect to all logged in users that a new user was. However, I'm getting an error in my test unit in my new user method.</p>
<p>My service:</p>
<pre><code> async registerUser(user: createUser): Promise&lt;createUser&gt; {
    
    const userFound = await this.userModel.findOne({ username: user.username });
    if (userFound) {
      throw new BadRequestException('Usuario ja existe.');
    }

    user.password = await Criptography.encodePwd(user.password);

    const userCreate = await this.userModel.create(user);

    this.socketGateway.emitnewUser(userCreate);

    return  userCreate;
  }  
</code></pre>
<p>My test using jest:</p>
<pre><code>const userModelTest: User[] = [

  new User({ _id: '89d58w5',username: 'testUser50',password: '123456',name: 'teste1',role: 'operador', WebSocket: 'mywebsocket1',
  }),
];


describe('userservice', () =&gt; {
  let userService: Userservice;
  let userRepository: Model&lt;User&gt;;

  beforeEach(async () =&gt; {
    const userMockRepository = {
      find: jest.fn().mockResolvedValue(userModelTest),
      findAll: jest.fn().mockResolvedValue(userModelTest),
      findById: jest.fn(),
      findOne: jest.fn().mockResolvedValue(userModelTest[0]),
      registerUser: jest.fn().mockReturnValue(userModelTest[0]),
      exec: jest.fn().mockImplementation(),
      findByIdAndUpdat: jest.fn(),
      findOneAndDelete: jest.fn(),
      listUsers: jest.fn().mockImplementation(),
      create: jest.fn().mockResolvedValue( {
        username: 'testUser1',
        password: '123456',
        name: 'teste1',
        role: 'operador',
      })
    };
   
 const module: TestingModule = await Test.createTestingModule({

      providers: [
        Userservice,
        AppGateway,
        {
          provide: getModelToken('User'),
          useValue: userMockRepository,
        },
      ],
    }).compile();

    userService = module.get&lt;Userservice&gt;(Userservice);
    userRepository = module.get&lt;Model&lt;User&gt;&gt;(getModelToken('User'));
  });
</code></pre>
<p>DESCRIBE TEST:</p>
<pre><code>describe('Create', ()=&gt;{
    it('Create New User', async ()=&gt;{
      const data : createUser = {
        username: 'testUser1',
        password: '123456',
        name: 'teste1',
        role: 'operar',
      }
      const userAlreadyExists = await userService.findOne(data.username)
      expect(userAlreadyExists).toBe(true)
      const result = await userService.registerUser(data)
      expect(result).toEqual( data)
      const encode = await userService
      console.log(result)
      
    })
  });
</code></pre>
<p>ERROR:</p>
<p>BadRequestException: User already exist.</p>
<pre><code>  46 |     const userFound = await this.userModel.findOne({ username: user.username });
  47 |     if (userFound) {
&gt; 48 |       throw new BadRequestException('Usuario ja existe.');
     |             ^
  49 |     }
  50 |
  51 |     user.password = await Criptography.encodePwd(user.password);

  at Userservice.registerUser (users/shared/user.service.ts:48:13)
  at Object.&lt;anonymous&gt; (users/shared/user.service.spec.ts:120:22)
</code></pre>
",https://stackoverflow.com/questions/72985095/test-register-user-method-with-user-lookup-encode-and-websocket,"['unit-testing', 'websocket', 'hash', 'jestjs', 'nest']",35,False,1,0
GitLab CI failing due to &quot;jobs config should contain at least one visible job&quot;,"<p>I am attempting to setup a pipeline for a .NET 6 project to just run some unit tests. I have a separate project in the same repository (also .NET 6) using xUnit for a unit testing framework. It seems that no matter what I try to change in my <em>.gitlab-ci.yml</em> file, I get the same error from the pipeline job. The error I'm seeing is this: <a href=""https://i.stack.imgur.com/Lv9M7.png"" rel=""nofollow noreferrer"">GitLab pipeline error</a></p>
<p>When putting my configuration into GitLab's CI Lint tool, it tells me the yml is valid.</p>
<p>Here is my configuration:</p>
<pre><code>image: mcr.microsoft.com/dotnet/sdk:6.0

stages:
  - build
  - test

job_compile:
  stage: build
  before_script:
    - &quot;dotnet restore&quot;
  script:
    - &quot;dotnet build --no-restore&quot;

job_run_tests:
  stage: test
  script:
    - &quot;dotnet test --no-restore&quot;
</code></pre>
<p>I am having trouble finding the issue here. Any help would be appreciated!</p>
",https://stackoverflow.com/questions/72321380/gitlab-ci-failing-due-to-jobs-config-should-contain-at-least-one-visible-job,"['gitlab', 'continuous-integration', 'gitlab-ci', 'pipeline', '.net-6.0']",921,True,1,1
Mocking react custom hook return value as a module with Jest returns wrong value,"<p>I need to mock my custom hook when unit testing React component. I've read some stackoverflow answers but haven't succeeded in implementing it correctly.</p>
<p>I can't use useAuth without mocking it as it depends on server request and I'm only writing unit tests at the moment.</p>
<pre><code>//useAuth.js - custom hook

import React, { createContext, useContext, useEffect, useState } from 'react';
import PropTypes from 'prop-types';

const authContext = createContext();

function useProvideAuth() {
    const [accessToken, setAccessToken] = useState('');
    const [isAuthenticated, setAuthenticated] = useState(
        accessToken ? true : false
    );

    useEffect(() =&gt; {
        refreshToken();
    }, []);

    const login = async (loginCredentials) =&gt; {
        const accessToken = await sendLoginRequest(loginCredentials);
        if (accessToken) {
            setAccessToken(accessToken);
            setAuthenticated(true);
        }
    };

    const logout = async () =&gt; {
        setAccessToken(null);
        setAuthenticated(false);
        await sendLogoutRequest();
    };

    const refreshToken = async () =&gt; {
        const accessToken = await sendRefreshRequest();
        if (accessToken) {
            setAccessToken(accessToken);
            setAuthenticated(true);
        } else setAuthenticated(false);
        setTimeout(async () =&gt; {
            refreshToken();
        }, 15 * 60000 - 1000);
    };

    return {
        isAuthenticated,
        accessToken,
        login,
        logout
    };
}

export function AuthProvider({ children }) {
    const auth = useProvideAuth();

    return &lt;authContext.Provider value={auth}&gt;{children}&lt;/authContext.Provider&gt;;
}

AuthProvider.propTypes = {
    children: PropTypes.any
};

const useAuth = () =&gt; {
    return useContext(authContext);
};

export default useAuth;
</code></pre>
<p>The test I've written</p>
<pre><code>import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import { NavBar } from '../App';

jest.resetAllMocks();
jest.mock('../auth/useAuth', () =&gt; {
    const originalModule = jest.requireActual('../auth/useAuth');
    return {
        __esModule: true,
        ...originalModule,
        default: () =&gt; ({
            accessToken: 'token',
            isAuthenticated: true,
            login: jest.fn,
            logout: jest.fn
        })
    };
});

describe('NavBar when isAuthenticated', () =&gt; {
    it('LogOut button is visible when isAuthenticated', () =&gt; {
        render(&lt;NavBar /&gt;);
        expect(screen.getByText(/log out/i)).toBeVisible();
    });
});
</code></pre>
<p>The function I'm writing tests on:</p>
<pre><code>//App.js
import React from 'react';
import cn from 'classnames';
import useAuth, { AuthProvider } from './auth/useAuth';
import './App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.css';

function App() {
    return (
        &lt;AuthProvider&gt;
            &lt;Router&gt;
                    &lt;NavBar /&gt;
            &lt;/Router&gt;
        &lt;/AuthProvider&gt;
    );
}

const NavBarSignUpButton = () =&gt; (
    &lt;button className='button info'&gt;
        Sign up
    &lt;/button&gt;
);

const NavBarLogoutButton = () =&gt; {
    const auth = useAuth();
    const handleLogOut = () =&gt; {
        auth.logout();
    };

    return (
        &lt;button className='button info' onClick={handleLogOut}&gt;
            Log out
        &lt;/button&gt;
    );
};

export const NavBar = () =&gt; {
    const isAuthenticated = useAuth().isAuthenticated;
    const loginButtonClassName = cn({
        btn: true,
        invisible: isAuthenticated
    });

    return (
        &lt;nav className='navbar navbar-expand-lg navbar-light'&gt;
            &lt;div className='container'&gt;
                &lt;div className='d-flex justify-content-end'&gt;
                    &lt;div className='navbar-nav'&gt;
                        &lt;button className={loginButtonClassName}&gt;
                            Log In
                        &lt;/button&gt;
                        {isAuthenticated ? &lt;NavBarLogoutButton /&gt; : &lt;NavBarSignUpButton /&gt;}
                    &lt;/div&gt;
                &lt;/div&gt;
            &lt;/div&gt;
        &lt;/nav&gt;
    );
};
</code></pre>
<p>The test code above doesn't throw any errors. However, the test fails as useAuth().isAuthenticated is always false (but I'm mocking it to return true). It doesn't change whether I test App or only NavBar</p>
<p>What am I doing wrong?</p>
",https://stackoverflow.com/questions/71778604/mocking-react-custom-hook-return-value-as-a-module-with-jest-returns-wrong-value,"['reactjs', 'unit-testing', 'jestjs']",3586,True,1,1
Test suite failed to run createRoot(...): Target container is not a DOM element,"<pre><code>**FAIL  src/containers/pages/signIn/SignIn.test.js**
  ● Test suite failed to run

    createRoot(...): Target container is not a DOM element.

       5 | import { ConfigProvider } from &quot;antd&quot;;
       6 |
    &gt;  7 | const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));
         |                       ^
       8 | root.render(
       9 |   &lt;React.StrictMode&gt;
      10 |     &lt;ConfigProvider theme={{ hashed: false }}&gt;

      at createRoot (node_modules/react-dom/cjs/react-dom.development.js:29345:11)
      at Object.createRoot$1 [as createRoot] (node_modules/react-dom/cjs/react-dom.development.js:29800:10)
      at Object.createRoot (node_modules/react-dom/client.js:12:16)
      at Object.&lt;anonymous&gt; (src/index.js:7:23)
      at Object.&lt;anonymous&gt; (src/containers/pages/signIn/SignIn.js:3:1)
      at Object.&lt;anonymous&gt; (src/containers/pages/signIn/SignIn.test.js:3:1)
      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:       0 total
Snapshots:   0 total
Time:        0.995 s
Ran all test suites.

Watch Usage: Press w to show more.
</code></pre>
<p>I am importing SignIn component in the below code. But the error is in index.js file. I don't have idea that whether it will automatically call index.js for all tests.</p>
<p>SignIn.test.js</p>
<pre><code>import React from 'react';
import { shallow } from 'enzyme';
import SignIn from './SignIn';

describe('SignIn', () =&gt; {
  it('renders without crashing', () =&gt; {
    const { getByText } = shallow(&lt;SignIn /&gt;);
    expect(getByText('Welcome to the App!')).toBeInTheDocument();
  });
});

</code></pre>
<p>**
The import statement itself is the cause of this error. I don't know whether I am missing anything here.**</p>
<p>index.js</p>
<pre><code>import React from &quot;react&quot;;
import ReactDOM from &quot;react-dom/client&quot;;
import App from &quot;./App&quot;;
import * as serviceWorker from &quot;./serviceWorker&quot;;
import { ConfigProvider } from &quot;antd&quot;;

const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));
root.render(
  &lt;React.StrictMode&gt;
    &lt;ConfigProvider theme={{ hashed: false }}&gt;
      &lt;App /&gt;
    &lt;/ConfigProvider&gt;
  &lt;/React.StrictMode&gt;
);
serviceWorker.unregister();

</code></pre>
<p>SignIn.js Imports</p>
<pre><code>import React from &quot;react&quot;;
import { useNavigate } from &quot;react-router-dom&quot;;
import { Form, Modal } from &quot;antd&quot;;
import SignInStyleWrapper from &quot;./SignIn.styles&quot;;
import applogo from &quot;../../../image/applogo.png&quot;;
import { loginUser } from &quot;../../../redux_Rtk/UserLogin/loginService&quot;;
import { useDispatch} from &quot;react-redux&quot;;

</code></pre>
<p>Dependencies installed</p>
<pre><code>&quot;react&quot;: &quot;^18.2.0&quot;,
&quot;react-custom-scrollbars&quot;: &quot;^4.2.1&quot;,
&quot;react-dom&quot;: &quot;^18.2.0&quot;,
&quot;react-redux&quot;: &quot;^8.0.5&quot;,
&quot;react-router&quot;: &quot;^6.4.3&quot;,
&quot;react-router-dom&quot;: &quot;^6.4.3&quot;,
&quot;react-saga&quot;: &quot;^0.3.1&quot;,
&quot;react-scripts&quot;: &quot;5.0.1&quot;,
&quot;@testing-library/jest-dom&quot;: &quot;^5.16.5&quot;,
&quot;@testing-library/react&quot;: &quot;^13.4.0&quot;,
&quot;@testing-library/user-event&quot;: &quot;^14.4.3&quot;,
&quot;enzyme&quot;: &quot;^3.11.0&quot;,
&quot;jest&quot;: &quot;24.9.0&quot;,
&quot;jest-html-reporters&quot;: &quot;^3.0.11&quot;,
&quot;enzyme-to-json&quot;: &quot;^3.6.2&quot;,
</code></pre>
<p>I tried &quot;@testing-library/react&quot; instead of enzyme. Its the same result. I could see the The import statement itself is the cause of this error.</p>
<p>I am writing unit testing for the first time. So don't know really what I am missing here.</p>
",https://stackoverflow.com/questions/74832767/test-suite-failed-to-run-createroot-target-container-is-not-a-dom-element,"['unit-testing', 'jestjs', 'enzyme', 'react-testing-library']",134,False,0,0
How to perform Unit Testing for hibernate transactional query statements?,"<p>Need some advice on how to do Unit testing for DAO class. My application uses DAO class to interact with my database directly and it is heavily used. I would like to construct unit tests for those DAO class functions. What would be a good way to do it?</p>
<p>Below are some of the methods in a sample DAO class:</p>
<pre><code>
@Repository
public class PortfolioDaoImpl implements PortfolioDao {
    
private static final Logger log = LoggerFactory.getLogger(PortfolioDaoImpl.class);
    
    public List&lt;Portfolio&gt; findAll(Pageable pageable){
        log.info(&quot;findAll in DaoImpl..&quot;);
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            
            String sql = &quot;SELECT * FROM PMS_PORT order by ID desc &quot;;                
                    
            NativeQuery sqlQuery = session.createSQLQuery(sql);
    
            sqlQuery.addEntity(Portfolio.class);
            sqlQuery.setFirstResult(pageable.getPageNumber() * pageable.getPageSize());
            sqlQuery.setMaxResults(pageable.getPageSize());
    
            List&lt;Portfolio&gt; portfolio = sqlQuery.list();
            
            return portfolio;
        } catch (Exception e) {
            // convert to HibernateException then to DataAccessException
            throw SessionFactoryUtils.convertHibernateAccessException(new HibernateException(e.getMessage()));
        }
    }
    
    public void addPortfolio(Portfolio portfolioForm) {
        log.info(&quot;adding portfolio in DaoImpl..&quot;);
        
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            Transaction transaction = session.beginTransaction();
            
            String sql = &quot;insert into PMS_PORT (ID,PORT_NAME,CREATED_BY,CREATED_DT,LAST_MDFY_BY,LAST_MDFY_DT,REMARKS) values &quot;
                    + &quot;(SQ_PMS_PORT.nextval, :portfolioName, :createdBy, sysdate , :lastMdfyBy, sysdate, :remarks)&quot; ; 
            
            NativeQuery query = session.createSQLQuery(sql);
            query.setParameter(&quot;portfolioName&quot;, portfolioForm.getPortfolioName());
            query.setParameter(&quot;createdBy&quot;, portfolioForm.getCreatedBy());
            query.setParameter(&quot;lastMdfyBy&quot;, portfolioForm.getLastMdfyBy());
            query.setParameter(&quot;remarks&quot;, portfolioForm.getRemarks());
            query.executeUpdate();
            
            transaction.commit();
            session.close();
            
        } catch (Exception e) {
            // convert to HibernateException then to DataAccessException
            throw SessionFactoryUtils.convertHibernateAccessException(new HibernateException(e.getMessage()));
        }
    }
    
    public Portfolio updatePortfolio(Portfolio portfolioForm){
        log.info(&quot;updating portfolio in DaoImpl..&quot;);
        
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            Transaction transaction = session.beginTransaction();
            
            String sql = &quot;update PMS_PORT set port_name =:portfolioName, remarks = :remarks, &quot;
                    + &quot;last_mdfy_by = :lastMdfyBy, last_mdfy_dt = sysdate where id = :id&quot;;
            
            log.info(&quot;id: &quot; + portfolioForm.getId().toString());
            
            NativeQuery query = session.createSQLQuery(sql);
            query.setParameter(&quot;id&quot;,portfolioForm.getId());
            query.setParameter(&quot;portfolioName&quot;,portfolioForm.getPortfolioName());
            query.setParameter(&quot;remarks&quot;, portfolioForm.getRemarks());
            query.setParameter(&quot;lastMdfyBy&quot;, portfolioForm.getLastMdfyBy());        
            query.executeUpdate();
            
            transaction.commit();
            session.close();
        
            return portfolioForm;
        
        } catch (Exception e) {
            // convert to HibernateException then to DataAccessException
            throw SessionFactoryUtils.convertHibernateAccessException(new HibernateException(e.getMessage()));
        }
    }
    
    public void deletePortfolio(long id) {
        log.info(&quot;deleting portfolio in DaoImpl..&quot;);
        try {
            Session session = HibernateUtil.getSessionFactory().openSession();
            Transaction transaction = session.beginTransaction();
            
            String sql1 = &quot;delete from PMS_PORT where id = :id&quot;; 
            String sql2 = &quot;delete from PMS_PORT_TRANS where port_id = :id&quot;;
            String sql3 = &quot;delete from PMS_PORT_HOLD where port_id = :id&quot;;
            String sql4 = &quot;delete from PMS_UNREAL_PL where port_id = :id&quot;;
            String sql5 = &quot;delete from PMS_REAL_PL where port_id = :id&quot;;
            
            NativeQuery query = session.createSQLQuery(sql1);
            query.setParameter(&quot;id&quot;,id);
            query.executeUpdate();
            
            NativeQuery query2 = session.createSQLQuery(sql2);
            query2.setParameter(&quot;id&quot;,id);
            query2.executeUpdate();
            
            NativeQuery query3 = session.createSQLQuery(sql3);
            query3.setParameter(&quot;id&quot;,id);
            query3.executeUpdate();
            
            NativeQuery query4 = session.createSQLQuery(sql4);
            query4.setParameter(&quot;id&quot;,id);
            query4.executeUpdate();
            
            NativeQuery query5 = session.createSQLQuery(sql5);
            query5.setParameter(&quot;id&quot;,id);
            query5.executeUpdate();
            
            transaction.commit();
            session.close();
        
        } catch (Exception e) {
            // convert to HibernateException then to DataAccessException
            throw SessionFactoryUtils.convertHibernateAccessException(new HibernateException(e.getMessage()));
        }
    }
</code></pre>
<p>My idea is to do something like below. But I think modifying data on the actual tables are not a good way to do testing. Will using dummy table be feasible? How can i do so?</p>
<pre><code>
@Test
public void TestAddPortfolio(){
  
//Make sure that table PMS_PORT has 0 record

  //create new object -&gt;     Portfolio portfolio = new Portfolio();

  //execute addPortfolio(Portfolio portfolio)

  //assert that PMS_PORT has 1 record
}
</code></pre>
",https://stackoverflow.com/questions/72715859/how-to-perform-unit-testing-for-hibernate-transactional-query-statements,"['hibernate', 'unit-testing', 'testing', 'transactions']",83,False,0,0
Why isn&#39;t my environment variable being cleared in FastApi test?,"<p>I'm relatively new to FastApi and unit testing in Python.</p>
<p>I am testing an api that has a conditional check on whether an environment variable <code>FOO</code> is present.</p>
<p>I am trying to clear that environment variable so that when the api gets invoked by the test <strong>the environment variable is not found</strong>:</p>
<pre><code>  def test_invoice(self, requests_mock):
     with mock.patch.dict(os.environ, {}, clear=True):          
        
        url = &quot;/api/invoices/check&quot;

        requests_mock.post(url, real_http=True)

        response = self.test_client.post(url, json.dumps([invoice_id]))

  @router.post(&quot;/api/invoices/check&quot;)
  def invoices_api():
    if os.environ.get(&quot;FOO&quot;):
</code></pre>
<p>When the test client gets invoked and the env var is checked <strong>the env variable is not <code>None</code></strong>?</p>
<p>How I can make the code I am trying to test use the mocked os environment?</p>
<p><strong>Note:</strong> I've also tried clearing the env variable with the following syntax:</p>
<pre><code>  @mock.patch.dict(os.environ, {}, clear=True)
  def test_invoice(self, requests_mock):
</code></pre>
",https://stackoverflow.com/questions/74330851/why-isnt-my-environment-variable-being-cleared-in-fastapi-test,"['python', 'fastapi', 'requests-mock']",268,False,0,1
jest - react - mocked geolocation inside useEffect in hook,"<p>how would you test a hook that is using  <code>navigator.geolocation.getCurrentPosition()</code> method (mocked it already based on this: <a href=""https://newdevzone.com/posts/how-to-mock-navigatorgeolocation-in-a-react-jest-test"" rel=""nofollow noreferrer"">https://newdevzone.com/posts/how-to-mock-navigatorgeolocation-in-a-react-jest-test</a>) in <code>useEffect</code>?
I can't see the way how to wait for result as upon calling the function it does not return anything and returned data are processed in passed callback. found some hackish solution that works when run debug using jest runner vsc extension, but does not for regular test run.</p>
<p>the hook:</p>
<pre><code>const useGeolocation = () =&gt; {
  const [coords, setCoords] = useState&lt;GeolocationCoordinates&gt;();

  useEffect(() =&gt; {
    navigator.geolocation.getCurrentPosition((position) =&gt; {
      setCoords(position.coords);
    });
  }, []);

  return coords;
};
</code></pre>
<p>test:</p>
<pre><code>import { renderHook } from '@testing-library/react';

it('should return non-empty coords', async () =&gt; {
    const { result } = renderHook(() =&gt; useGeolocation());

    // MISSING CODE

    expect(result.current).not.toBe(undefined);
});
</code></pre>
<p>I'll be happy for any idea leading to solution so I don't need to give up on unit testing once again :slight_smile:</p>
",https://stackoverflow.com/questions/74334651/jest-react-mocked-geolocation-inside-useeffect-in-hook,"['reactjs', 'jestjs']",17,False,0,0
"issue with Jest unit test case ,in scenario of mockrejectedvalue","<p>I'm trying to write the unit test case using jest for the following function</p>
<pre><code> public async getArtifacts(): Promise&lt;any&gt; {
        let artifacts: Artifact[] = [];
        return new Promise(async(resolve,reject) =&gt; {
            try{            
                let files = await fspromise.readdir(`${envConfig.artifacts_path}`); 
                for(const filename of files){
                    if(path.extname(filename).toLowerCase() == '.zip'){
                        let file_path = path.join(`${envConfig.artifacts_container_path}`,filename);
                        let artifact = new Artifact(filename,file_path);   
                        artifact =  await this.processArtifact(artifact);                
                        artifacts.push(artifact);                    
                    }
                };
                
                resolve(artifacts);         
            }
            catch(error){
                LoggerWrapper.error(`Error while accessing ZIP artifacts from the source path`, error);
                throw error;
            }
        });
    }    
</code></pre>
<p>I was trying to write a test case in which the processArtifact would be failing  and throw and error and the same would be handled by catch block of getArtifacts,the unit test that i wrote is as follows</p>
<pre><code>test('test get artifacts with exception', async () =&gt; {
    const mockGetRestClient = jest.fn();
    artifactService.processArtifact = mockGetRestClient;
     mockGetRestClient.mockRejectedValue(new InternalServerException());
    try {
      const response = await artifactService.getArtifacts();
      expect(artifactService.processArtifact).toHaveBeenCalled();
     // expect(response).toEqual(new InternalServerException);
      expect(artifactService.getArtifacts).toThrow('Error while accessing ZIP artifacts from the source path');
    }
    catch (e: any) {
        console.log(e)
     }
  }); 
</code></pre>
<p>but the unit test case fails ,the error that i get is</p>
<pre><code> Console

    console.log
      2022-09-16T06:29:02.154Z [error] : &quot;Error while accessing ZIP artifacts from the source path&quot;

      at Console.log (node_modules/winston/lib/winston/transports/console.js:79:23)

  ● test artifact service › test get artifacts with exception



      232 |     const mockGetRestClient = jest.fn();
      233 |     artifactService.processArtifact = mockGetRestClient;
    &gt; 234 |      mockGetRestClient.mockRejectedValue(new InternalServerException());
          |                                          ^
      235 |     try {
      236 |       const response = await artifactService.getArtifacts();
      237 |       expect(artifactService.processArtifact).toHaveBeenCalled();

      at Object.&lt;anonymous&gt; (test/services/artifact-service.spec.ts:234:42)

  ● test artifact service › test get artifacts with exception

    thrown: &quot;Exceeded timeout of 5000 ms for a test.
    Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test.&quot;

      229 |   })
      230 |
    &gt; 231 |   test('test get artifacts with exception', async () =&gt; {
          |   ^
      232 |     const mockGetRestClient = jest.fn();
      233 |     artifactService.processArtifact = mockGetRestClient;
      234 |      mockGetRestClient.mockRejectedValue(new InternalServerException());

      at test/services/artifact-service.spec.ts:231:3
      at Object.&lt;anonymous&gt; (test/services/artifact-service.spec.ts:20:10)
</code></pre>
<p>what is that i'm doing wrong i'm new to this jest unit testing ,not able to find exactly why its failing</p>
<p>PS - have tried adding the settimeout but still same issue.</p>
",https://stackoverflow.com/questions/73740810/issue-with-jest-unit-test-case-in-scenario-of-mockrejectedvalue,"['javascript', 'node.js', 'jestjs']",103,False,0,0
JEST compatibility for Angular-4,"<p>I am working on angular project with version-4 &amp; as per the requirement need to implement JEST framework for Unit testing, I have tried with latest version of JEST:29.3.1 but getting below error:</p>
<blockquote>
<p>ERROR : while running : ng run test</p>
<p>TypeError: Cannot read property 'split' of undefined at isAfterVersion
\node_modules\jest-preset-angular\build\ngtsc\ts compatibility\src\ts_cross_version_utils.js:87:67) at Object.
\node_modules\jest-preset-angular\build\ngtsc\ts_compatibility\src\ts_cross_version_utils.js:13:24)
at Module. compile (internal/modules/cjs/loader.js:1085:14)</p>
</blockquote>
<p>Tried with lower version of JEST as well but getting same error.</p>
<p>package.json</p>
<pre><code>dependencies&quot;: {
    &quot;@angular/aninations&quot;: &quot;^4.4.6&quot;,
    &quot;@angular/cdk&quot;: &quot;^2.0.0-beta.12&quot;,
    &quot;@angular/cli&quot;: &quot;1.0.0&quot;
    &quot;@angular/common&quot;: &quot;^4.0.0&quot;,
    &quot;@angular/compile&quot;: &quot;^4.0.0&quot;,
    &quot;@angular/core&quot;: &quot;^4.0.0&quot;,
    &quot;@angular/forms&quot;: &quot;^4.0.0&quot;,
    &quot;@angular/http&quot;: &quot;^4.0.8&quot;,
    &quot;@angular/material&quot;: &quot;^2.0.0-beta.12&quot;,
    &quot;@angular/platform-browser&quot;: &quot;^4.0.0&quot;,
    &quot;@angular/platform-browser-dynamic&quot;:&quot;4.8.8&quot;,
    &quot;@angular/router&quot;: &quot;^4.0.8&quot;,
    &quot;bootstrap&quot;: &quot;3.5.7&quot;,
    &quot;core-js&quot;: &quot;2.4.1&quot;,
    &quot;enhanced-resolve&quot;: &quot;^3.3.0&quot;,
    &quot;Jest&quot;: &quot;29.3.1&quot;,
    &quot;jest-preset-anguler: 12.2.3&quot;
}
</code></pre>
",https://stackoverflow.com/questions/74700370/jest-compatibility-for-angular-4,"['angular', 'jestjs']",65,False,0,0
"Wanna unit-test a function, but constructor gives error","<p>I am trying to unit test a function which is in an entity class, and it is stored in my DB by the use of a constructor. Each time I am trying to test this function it is giving me that error</p>
<blockquote>
<p>ArgumentCountError: Too few arguments to function App\Entity\Deal::__construct(), 0 passed in /var/www/html/casus/tests/dealsEntityFunctionsTest.php on line 10 and exactly 1 expected</p>
</blockquote>
<p>It is obvious I think, but I am really new with unit testing and that stuff so I couldn't find the answer. Could you please help me?</p>
<p>My code is</p>
<pre><code>class Deal
{
    private bool $isNewToday

    public function __construct($deal)
    {
        $this-&gt;isNewToday = $deal['is_new_today'];
    }

    public function getIsNewToday(): ?bool
    {
        return $this-&gt;isNewToday;
    }

    public function setIsNewToday(bool $isNewToday): self
    {
        $this-&gt;isNewToday = $isNewToday;

        return $this;
    }
}
</code></pre>
<p>And my unit test is</p>
<pre><code>class test extends TestCase
{
    public function testIsNewTodayIsTrue()
    {
        $deal = new Deal();
        $deal-&gt;setIsForSale(true);
        $this-&gt;assertTrue($deal-&gt;getIsForSale(), true);
    }
}
</code></pre>
",https://stackoverflow.com/questions/70696349/wanna-unit-test-a-function-but-constructor-gives-error,['php'],141,True,0,2
Using BCryptPasswordEncoder in Unit Test returns a null value,"<p>I'm learning Unit Testing with JUnit and Mockito on a Spring boot application, I have a registration method I want to test, in my test method I create a User but I see that the value of the password is always null when using .encode(mypassword), resulting in an Assertion Error.</p>
<hr />
<p><strong>UserServiceImpl.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }


    @Override
    public User register(User user) {


         Role role = roleService.findByName(ERole.ROLE_USER);

         Set&lt;Role&gt; roleSet = new HashSet&lt;&gt;();
         user.setFullName(user.getFullName());
         user.setEmailAddress(user.getEmailAddress());
         user.setPassword(passwordEncoder.encode(user.getPassword()));
         user.setConfirmPassword(&quot;&quot;);
         user.setEmailVerified(true);
         roleSet.add(role);
         user.setRoles(roleSet);

         if(userRepository.existsByEmailAddress(user.getEmailAddress())) {
             throw new EmailAlreadyExistsException(&quot;Account already exists with this email&quot;);
         }
        return userRepository.save(user);
    }



}

</code></pre>
<hr />
<p><strong>UserServiceImplTest.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>@ExtendWith(MockitoExtension.class)
class UserServiceImplTest {

    @InjectMocks
    private UserServiceImpl userService;

    @Mock
    private UserRepository userRepository;

    @Mock
    public PasswordEncoder passwordEncoder;

  

   @BeforeEach
    void setUp() {
        userService = new UserServiceImpl(userRepository, passwordEncoder);
    }

  @Test
    void testIfUserCanRegisterSuccessfully() {

        User user = new User(1, &quot;admin&quot;, &quot;admin@gmail.com&quot;, passwordEncoder.encode(&quot;password&quot;));

        when(userRepository.save(any())).thenReturn(user);
        User theUser = userService.register(user);


        System.out.println(&quot;theUser: &quot; + theUser);

        assertNotNull(theUser);
        assertEquals(1, theUser.getId());
        assertEquals(&quot;admin@gmail.com&quot;, theUser.getEmailAddress());
        assertTrue(passwordEncoder.matches(&quot;password&quot;, theUser.getPassword()));
    }

}

</code></pre>
<hr />
<p><strong>SecurityConfig.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Value(&quot;${spring.security.ant.matchers}&quot;)
    private String[] securityAntMatchers;
    

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint authenticationEntryPoint;

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable().formLogin().disable().httpBasic().disable();

        http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
            .and()
            .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        http
            .authorizeRequests()
            .antMatchers(securityAntMatchers)
            .permitAll()
            .anyRequest()
            .authenticated();
    }

}

</code></pre>
<hr />
<p>The output of theUser is this, I'm not sure how to handle the password encryption when testing the method.</p>
<p>theUser: User{id=1, fullName='admin', emailAddress='admin@gmail.com', dateJoined=Tue Nov 15 00:06:01 CAT 2022, emailVerified=true, password='null'}</p>
<hr />
<p><strong>EDITED</strong></p>
<pre class=""lang-java prettyprint-override""><code>

    @BeforeEach
    void setUp() {
        // Instantiating password encoder before every test, now I get the output
        this.passwordEncoder = new BCryptPasswordEncoder();
        userService = new UserServiceImpl(userRepository, passwordEncoder);


    }

  @Test
    void testIfUserCanRegisterSuccessfully() {
        User user = new User(1, &quot;admin&quot;, &quot;admin@gmail.com&quot;,&quot;password&quot;);

        when(userRepository.save(any())).thenReturn(user);
        User created = userService.register(user);

        assertEquals(created.getPassword(), user.getPassword());
        assertEquals(created.getEmailAddress(), user.getEmailAddress());
        verify(userRepository).save(any());
    }

</code></pre>
",https://stackoverflow.com/questions/74438448/using-bcryptpasswordencoder-in-unit-test-returns-a-null-value,"['java', 'testing', 'junit', 'mockito']",274,True,0,1
Jasmine - Test and API call with HttpClientTestingModuel,"<p>I'm trying to start working with Unit Testing in my Ionic application, with Angular 6, Jasmine and Karma.</p>
<p>I have a loginPage, this calls an AuthService which in turn calls an HttpService, below I show you the code.</p>
<p>The problem I'm having is that if I call the doLogin function (in the loginPage) or if I call the login function (in the authService) I can never get the response. I tried using a subscribe and executing toPromise() to convert the Observable into a Promise, but I didn't succeed either.</p>
<p>Can you help me?
Thanks a lot.</p>
<p>LOGINPAGE.TS</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Credentials } from '../models/credentials';
import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.page.html',
  styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {

  ionicForm: FormGroup;
  isSubmitted: boolean = false;
  credential: Credentials;
  constructor(public formBuilder: FormBuilder, private _authService: AuthService) { }

  ngOnInit() {
    this.ionicForm = this.formBuilder.group({
      email: ['eve.holt@reqres.in', [Validators.required, Validators.minLength(8)]],
      password: ['cityslicka', [Validators.required, Validators.minLength(8)]],
    });
  }
  
  doLogin1() {
    this.isSubmitted = true;
    if (!this.ionicForm.valid) {
      return false;
    } else {
      return true    
    }
  }

  async doLogin():  Promise&lt;Credentials | false&gt;  {
    this.isSubmitted = true;
    if (!this.ionicForm.valid) {
      return false;
    } else {
      this.credential = await this._authService.login(this.ionicForm.value);   
      return this.credential;
    }
  }

  get errorControl() {
    return this.ionicForm.controls;
  }

}
</code></pre>
<p>AUTHSERVICE.TS</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpService } from './http.service';

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

  constructor(private _httpService: HttpService) { }


  async login(body){
    return await this._httpService.post('https://reqres.in/api/login',body).toPromise();
  }


}
</code></pre>
<p>HTTPSERVICE.TS</p>
<pre><code>import { Injectable } from '@angular/core';
import { Observable, Subject, throwError } from 'rxjs';
import { HttpClient, HttpErrorResponse, HttpHeaders} from '@angular/common/http';
import { catchError } from 'rxjs/operators';

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

  errorLogin = new Subject&lt;boolean&gt;();
  constructor(private httpClient: HttpClient) {
  }

  public get(path: string, options?: any): Observable&lt;any&gt; {
    return this.httpClient.get(path,options).pipe(catchError(this.formatErrors));
  }

  public put(path: string, body: object = {},headers?:any): Observable&lt;any&gt; {
    let options = {
      headers: headers
    }
    return this.httpClient.put(path, JSON.stringify(body),options).pipe(catchError(this.formatErrors));
  }

  public post(path: string, body: object = {},options?: any): Observable&lt;any&gt; {
    return this.httpClient.post(path,body,options).pipe(catchError(this.formatErrors));
  }

  public delete(path: string, headers?:any): Observable&lt;any&gt; {
    return this.httpClient.delete(path, {headers,responseType: 'text' }).pipe(catchError(this.formatErrors));
  }

  public appendHeaders(header:HttpHeaders){
    if (header != undefined){
       return header.set('Content-Type','application/json');
    }
    return new HttpHeaders().set('Content-Type','application/json');
  }
  
  public formatErrors(error: HttpErrorResponse): Observable&lt;any&gt; {
    if (error.status === 401 &amp;&amp; error.error.message == 'Authentication failed'){
      try {
        this.errorLogin.next(true);
      } catch(error){
      }
    }
    return throwError(error);
  }

  showCredError(){
    this.errorLogin.next(true);
  }
  hideCredError(){
    this.errorLogin.next(false);
  }
  /*
    Metodo de prueba, eliminar al pasar a producción
  */
  public testRest(){
    return this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1');
  }
}


</code></pre>
<p>LOGINPAGE.SPEC.TS</p>
<pre><code>import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { IonicModule } from '@ionic/angular';
import { HttpClientTestingModule,  } from '@angular/common/http/testing';
import { LoginPage } from './login.page';
import { AuthService } from '../services/auth.service';
import { HttpService } from '../services/http.service';
import { of } from 'rxjs';
import { Credentials } from '../models/credentials';

describe('LoginPage', () =&gt; {
  let component: LoginPage;
  let fixture: ComponentFixture&lt;LoginPage&gt;;
  let authService: AuthService;
  beforeEach(waitForAsync(() =&gt; {
    TestBed.configureTestingModule({
      declarations: [ LoginPage ],
      imports: [IonicModule.forRoot(),
        FormsModule,
        ReactiveFormsModule,
        HttpClientTestingModule],
      providers: [AuthService, HttpService]
    }).compileComponents();

    fixture = TestBed.createComponent(LoginPage);
    component = fixture.componentInstance;
    fixture.detectChanges();
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000;
  }));

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

  it('B) send form without data', () =&gt;{
    component.ionicForm = component.formBuilder.group({
      email: ['', [Validators.required, Validators.minLength(8)]],
      password: ['', [Validators.required, Validators.minLength(8)]],
    });
    component.doLogin().then((data)=&gt;{
      expect(data).toBeFalse();
    });
    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('.errorUsernameRequired'))).not.toBeNull();
    expect(fixture.debugElement.query(By.css('.errorPasswordRequired'))).not.toBeNull();
  });

  it('C) send form without password', () =&gt;{
    component.ionicForm = component.formBuilder.group({
      email: ['UsuarioPrueba', [Validators.required, Validators.minLength(8)]],
      password: ['', [Validators.required, Validators.minLength(8)]],
    });
    component.doLogin().then((data)=&gt;{
      expect(data).toBeFalse();
    });
    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('.errorUsernameRequired'))).toBeNull();
    expect(fixture.debugElement.query(By.css('.errorPasswordRequired'))).not.toBeNull();
  });

  it('D) send form without username', () =&gt;{
    component.ionicForm = component.formBuilder.group({
      email: ['', [Validators.required, Validators.minLength(8)]],
      password: ['ContraseñaPrueba', [Validators.required, Validators.minLength(8)]],
    });
    component.doLogin().then((data)=&gt;{
      expect(data).toBeFalse();
    });
    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('.errorUsernameRequired'))).not.toBeNull();
    expect(fixture.debugElement.query(By.css('.errorPasswordRequired'))).toBeNull();
  });

  it('E) send form with minor lenght in both inputs', () =&gt;{
    component.ionicForm = component.formBuilder.group({
      email: ['ABCDEF', [Validators.required, Validators.minLength(8)]],
      password: ['ABCDEF', [Validators.required, Validators.minLength(8)]],
    });
    
    component.doLogin().then((data)=&gt;{
      expect(data).toBeFalse();
    });
    fixture.detectChanges();
    expect(fixture.debugElement.query(By.css('.errorPasswordMinLength'))).not.toBeNull();
    expect(fixture.debugElement.query(By.css('.errorUsernameMinLength'))).not.toBeNull();
  });

  it('F) send form successfully', (()=&gt;{
    component.ionicForm = component.formBuilder.group({
      email: ['eve.holt@reqres.in', [Validators.required, Validators.minLength(8)]],
      password: ['cityslicka', [Validators.required, Validators.minLength(8)]],
    });
    
    component.doLogin().then((data)=&gt;{
      console.log(data);
      // THIS CONSOLE LOG NOT APPEAR IN THE CHROME CONSOLE
    })
  }));


});

</code></pre>
",https://stackoverflow.com/questions/71679465/jasmine-test-and-api-call-with-httpclienttestingmoduel,"['angular', 'typescript', 'ionic-framework', 'jasmine', 'karma-jasmine']",1820,True,0,1
How to do Testing in Angular 14 - catchError operator &#39;rxjs&#39;,"<p>can you please help me to test the code. I have not been able to test the catch Error operator that is inside the pipe...</p>
<p>I am currently testing in angular 14 for observables. I am making a API call from service and using pipe operator to catch the error.</p>
<p>Here is my component code:</p>
<pre><code>    

    getallSectionsData() {
        this.projService
          .getAllSections()
          .pipe(
            catchError((err) =&gt; {
              this.errorObject = err.message;
              this.alertMessage = [
                { status: 'critical', message: this.errorObject },
              ];
              this.changeDetectorRef.detectChanges();
              return throwError(() =&gt; {
                return this.errorObject;
              });
            })
          )
          .subscribe((res) =&gt; {
            this.projectData = JSON.parse(res.body).data;
            this.changeDetectorRef.detectChanges();
          });
    
      } 


</code></pre>
<p>My unit testing code in spec file :</p>
<pre><code>    
    it('should display the error template in case of error', fakeAsync(() =&gt; {
        service.getAllSections = jasmine
          .createSpy()
          .and.returnValue(throwError(() =&gt; errorMessage));
    
        component.getallSectionsData();
        tick();
        expect(component.errorObject).toBeDefined();
      }));
</code></pre>
<p>Above code is covering the code for coverage but test has been failing as below :</p>
<pre><code>Chrome 107.0.0.0 (Windows 10)it should display the error template in case of error FAILED       
   Http failure response for https://soteria-dev.np-0000136.npause1.bakerhughes.com/api/sections: 0 Unknown    Error thrown
</code></pre>
<p><a href=""https://i.stack.imgur.com/mX5Zx.png"" rel=""nofollow noreferrer"">enter image description here</a></p>
<p>I followed and searched everything I can but not able to solve the issue, any help is highly appreciated.</p>
<p>Thanks in advance!</p>
",https://stackoverflow.com/questions/74582629/how-to-do-testing-in-angular-14-catcherror-operator-rxjs,"['unit-testing', 'rxjs', 'karma-jasmine', 'angular14']",28,False,0,0
fastapi&#39;s class as dependency override in unit testing,"<p>Using the parameter supplied in the request body, I wanted to instantiate an object. For instance, if the request body contains <code>type=push</code> I desired to instantiate in this manner.</p>
<pre><code>    if channel_type.upper() == &quot;PUSH&quot;:
       return NotificationService(Push())
</code></pre>
<p>I am able to achieve this through classes as dependency of fastapi as following:</p>
<pre><code>def factory(channel_type):
    if channel_type.upper() == &quot;PUSH&quot;:
        return NotificationService(Push())
    elif channel_type.upper() == &quot;EMAIL&quot;:
        return NotificationService(Email())
    else:
        return NotificationService(Sms())


class NotificationRequest:
    def __init__(self, type: str = Body(&quot;push&quot;)):
        self.service = factory(type)


class MessageRequest(BaseModel):
    title: str
    message: str
    payload: Dict = {}


@router.post(&quot;/&quot;, response_model=dict)
def notify(message: MessageRequest, request: NotificationRequest = Depends()) -&gt; Any:
    request.service.send(users=get_users(), message=Message(
        title=message.title, message=message.message, payload=message.payload
    ))
    return {&quot;success&quot;: True}

 
</code></pre>
<p>However, I wanted to override the NotificationRequest dependency in the unit test so that I could provide fake instances of real classes:</p>
<pre><code>def get_factory(channel_type):
    if channel_type.upper() == &quot;PUSH&quot;:
        return NotificationService(FakePush())
    elif channel_type.upper() == &quot;EMAIL&quot;:
        return NotificationService(FakeEmail())
    else:
        return NotificationService(FakeSms()) 
</code></pre>
<p>I have tried following:</p>
<pre><code>app.dependency_overrides[factory] = lambda: get_factory
</code></pre>
<p>which fails because the factory is not injected through the dependency.</p>
<p>How can we give a parameter to the body and inject a dependency into the function to produce a fake instance for unit testing?</p>
",https://stackoverflow.com/questions/74813396/fastapis-class-as-dependency-override-in-unit-testing,['fastapi'],36,False,0,0
Use multiple return values in Substitute from &#39;@fluffy-spoon/substitute&#39;,"<p>I am using jest for unit testing of my nestJs service , for mocking a service from B to a service in A , i use Substitue module, but once a value (firstContractDocument) is set in return of mocked function of B , the same value is appearing in all 'it' tests.
I tried of using arguments instead of 'Arg.any()' , nut it returns 'Proxy 'SubstituteJS'} jest'.
Can anyone help me to return new value (secondContractDocument) in next 'it' instead of reappearing of previous value.</p>
<pre><code>import Substitute, { Arg } from '@fluffy-spoon/substitute';
....
describe('Test CollaboratorService', () =&gt; {
const contractDocumentService = Substitute.for&lt;ContractDocumentService&gt;();
....
 beforeEach(async () =&gt; {
    const moduleRef = await Test.createTestingModule({
      imports: [],
      controllers: [],
      providers: [
        ....
        {
          provide: 'ContractDocumentService',
          useValue: contractDocumentService,
        },

      ],
     }).compile();
   ....
    });

it('should return collaborators with the given contractDocumentId', async () =&gt; {
      contractDocumentService
         .findOneOrFail(Arg.any())
        .returns(Promise.resolve(firstContractDocument));
});
it('should return collaborators with the given contractDocumentId', async () =&gt; {
      contractDocumentService
         .findOneOrFail(Arg.any())
        .returns(Promise.resolve(secondContractDocument));
});
....
</code></pre>
<p>return value is always 'firstContractDocument'</p>
<p>Need to change value on next 'it' test case to secondContractDocument</p>
",https://stackoverflow.com/questions/74231553/use-multiple-return-values-in-substitute-from-fluffy-spoon-substitute,"['unit-testing', 'jestjs', 'nestjs', 'nsubstitute']",112,True,0,1
Cannot import hamcrest matchers for some reason,"<p>I am super new to unit testing and java in general, so my apologies for the basic question. However, when I try to import import static org.hamcrest.Matchers.hasEntry; I get a message saying &quot;cannot resolve symbol 'Matchers'. I'm trying to use hasEntry to unit test a method that returns a map.</p>
<p>Here are the imports I have</p>
<pre><code>    import static org.hamcrest.CoreMatchers.equalTo;
    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.Matchers.hasEntry;
</code></pre>
<p>the top two are working fine, but I can't get the last one to work. If anyone has any suggestions as to how to fix the problem, or if there is another way I can import hasEntry, please let me know! Thank you</p>
",https://stackoverflow.com/questions/72932129/cannot-import-hamcrest-matchers-for-some-reason,['hamcrest'],322,False,0,2
Mulitple errors when using Power Mock,"<p>I am working on unit testing for images stored in a resources folder. I am trying to test this images to get its metadata. I am currently stuck trying to get <code>Bitmap</code> of the image from the path.</p>
<p>As far as I know <code>BitmapFactory</code> don't work for Android Unit Tests. So I tried mocking the method with <a href=""https://github.com/powermock/powermock"" rel=""nofollow noreferrer"">Power Mock</a> library. But I keep getting loads of exceptions. Has anyone used this library before to mock BitmapFactory? Or is there a better way I can achieve what I want? I can use <code>Instrumentation Tests</code> because I need to test for classes and methods not Activities.</p>
<pre><code>    **These are my dependencies**
  //power mock to mock static methods
    testImplementation 'org.powermock:powermock-api-mockito:1.7.0'
    testImplementation 'org.powermock:powermock-module-junit4-rule-agent:1.7.0'
    testImplementation 'org.powermock:powermock-module-junit4-rule:1.7.0'
    testImplementation 'org.powermock:powermock-module-junit4:1.7.0'
</code></pre>
<p><strong>Errors</strong></p>
<pre><code>    java.lang.RuntimeException: Internal error: Failed to find the &quot;modifiers&quot; field in method setInternalState.
    
        at org.powermock.reflect.internal.WhiteboxImpl.sedModifiersToField(WhiteboxImpl.java:2348)
        at 

org.objenesis.ObjenesisException: java.lang.reflect.InvocationTargetException

    at org.objenesis.instantiator.sun.SunReflectionFactoryHelper.newConstructorForSerialization(SunReflectionFactoryHelper.java:54)
    at org.objenesis.instantiator.sun.SunReflectionFactoryInstantiator.&lt;init&gt;(SunReflectionFactoryInstantiator.java:41)
    at org.objenesis.strategy.StdInstantiatorStrategy.newInstantiatorOf(StdInstantiatorStrategy.java:67)
    at org.objenesis.ObjenesisBase.getInstantiatorOf(ObjenesisBase.java:94)
    at org.powermock.reflect.internal.WhiteboxImpl.newInstance(WhiteboxImpl.java:259)
    at org.powermock.reflect.Whitebox.newInstance(Whitebox.java:139)
</code></pre>
",https://stackoverflow.com/questions/74065496/mulitple-errors-when-using-power-mock,"['android', 'kotlin', 'android-bitmap']",43,False,0,0
Django Unit Testing - How to test all instances in a model?,"<p>I want to test all instances in a DB using Django.</p>
<p>I have a python script that populates the DB and I want to test every single instance if it pass the test.</p>
<p>I provide here a dummy <em>tests.py</em>:</p>
<pre><code>from django.test import TestCase
from app_core.models import Item
# Item model fields are: pk, first, second

class PairTestCase(TestCase):
    def setUp(self):
        # This script populates the DB creating several Item instances
        from app_core.init import init_items

    def test_pair_elems_different(self):
        &quot;&quot;&quot;First and second fields MUST be different inside the instance&quot;&quot;&quot;
        item = Item.objects.get(pk=1)
        self.assertNotEqual(item.first, item.second)
</code></pre>
<p>As you can see, I just tested a <em>single</em> instance.
Let's suppose the DB contains 1000 Item instances, what is the best way to test them all?</p>
<p>The only solution that pops up in my mind is using a simple FOR loop inside <em>test_pair_elems_different</em>, iterating all object and comparing each instance.</p>
<p>Is this approach correct in the context of unit testing best practices/principles?</p>
",https://stackoverflow.com/questions/74099916/django-unit-testing-how-to-test-all-instances-in-a-model,"['python', 'django', 'unit-testing']",118,False,0,2
@Value in springboot is giving null in Service layer when running only a unit test,"<p>I'm writing a dummy code to simulate my problem::
when I run the spring boot application I can get the value from @Value and all is good
But when I'm running a unit test for that service when I debug it gets null from @Value in the service layer</p>
<p>and when I run unitTest Alone and debug to get the value from @Value in Test Class I get the value and all is good.</p>
<p>So my unit testing is failing due to it can't get the dummyMboxName from the properties file in the running time of the testService
CODE::</p>
<pre><code>#Simulation of the Application
@PropertySource(value = {&quot;classpath:application-dummy.properties&quot;})

public class Application implements WebMvcConfigurer {
            SpringApplication.run(Application.class, args);

}

simulation of the service file :: 
@Service
public class DummyService {
    @Value(&quot;${mvax.dummy.mbox.name}&quot;)
     String dummyMboxName;


void print(){        System.out.println(dummyMboxName);
}
}
simulation of the serviceTest file :: 



@ExtendWith(SpringExtension.class)
@TestPropertySource(locations = &quot;classpath:application-dummy.properties&quot;)
@Log4j2
public class dummyServiceTest extends WiremockJunitTest {

    @InjectMocks
    DummyService dummyService ;

    @Value(&quot;${mvax.dummy.mbox.name}&quot;)
    private String dummyMboxName;
    @Test
    void testCallingdummyContent() {
dummyService.print();
}
}

  
</code></pre>
",https://stackoverflow.com/questions/74086720/value-in-springboot-is-giving-null-in-service-layer-when-running-only-a-unit-te,"['java', 'spring', 'spring-boot', 'properties-file']",80,False,0,0
Unit Test for different conditions in the same method?,"<p>I am wondering if I should test the same parts of a method when there are multiple conditions in this method in Unit Testing. I mean that, for example, in the following method there are 2 conditions (the code is simplified and unnecessary parts are omitted):</p>
<pre><code>private Boolean demo() {
    
        Boolean result = null;
        List&lt;Employee&gt; employees = employeeRepository.findAll();
        
        if (/* condition 1 */) {            
                result = true;
        } else { /* condition 2 */                       
                result = false;
        }
        
        employeeRepository.saveSalary(BigDecimal salary);
        employeeRepository.saveEmployee(Employee employee);
        
        return result;
}
</code></pre>
<p>When I test condition 1, I also test the parts in the <code>saveSalary()</code> and <code>saveEmployee()</code> methods.</p>
<p>In this scene, when I test condition 2 using another test method in the same Unit Test class, should I also test <code>saveSalary()</code> and <code>saveEmployee()</code> methods again? Or just verifying them as <code>verify(employeeRepository, times(1)).saveSalary(any());</code> and <code>verify(employeeRepository, times(1)).saveEmployee(any());</code> enough? What is the correct approach for this kind of situation?</p>
",https://stackoverflow.com/questions/71078892/unit-test-for-different-conditions-in-the-same-method,"['java', 'unit-testing', 'testing', 'junit', 'mockito']",909,False,0,1
Jest test mocks for Excel calculate method,"<p>I am new in creating Jest test scenarios. I was trying to create a mock data and test coverage for a Excel calculate method ( context.application.calculate(Excel.CalculationType.full) ) and I struggle to figure out how to create a mocks for it and what the test function should receive and what to expect when whole workbook is being recalculated.</p>
<p>I've been looking on how to do it on : <a href=""https://learn.microsoft.com/en-us/office/dev/add-ins/testing/unit-testing#install-the-tool"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/office/dev/add-ins/testing/unit-testing#install-the-tool</a> but my function is different than any shown here.</p>
<p>The function that needs to be tested is this:</p>
<pre><code>const recalculateWorkbook = async () =&gt; {
   await Excel.run(async (context) =&gt; {
     context.application.calculate(Excel.CalculationType.full);
     await context.sync();
   }).catch(function (error) {
     console.log(error);
   });
 };
</code></pre>
",https://stackoverflow.com/questions/72969394/jest-test-mocks-for-excel-calculate-method,"['excel', 'unit-testing', 'jestjs', 'office-js', 'office-addins']",75,False,0,0
How to write test cases in Jest for login page,"<p>The following code is what I have written in order for the Admin to log in to the system. I am now trying to carry out unit testing and have to test the ValidateLogin for admin in particular. I have chosen jest to do that.</p>
<p>I created a test file:</p>
<pre><code>const LoginController = reqire('./LoginController')
test('login to the system', () =&gt; {
    expect(true).toBe(true);
})

</code></pre>
<p>Instead of checking for true to be true. I want to check for the username and password to be true. Please explain how should I do it.</p>
<p>Following is the code for login:</p>
<pre><code>class User {
    username;
    password;
    email;
    firstName;
    lastName;
    roleName;

    constructor(username,password,email,firstName, lastName, roleName){
        this.username = username;
        this.password = password;
        this.email = email;
        this.firstName = firstName;
        this.lastName = lastName;
        this.roleName = roleName;
    }

    getlogininfo(username, password, callback) {       
        var sql = &quot;SELECT * FROM User Where username = '&quot; + username + 
            &quot;' AND password = '&quot; + password + &quot;'&quot;;
        var Username;
        var dataRes;

        con.query(sql, function(err, results){
            if (err){ 
                throw err;
            }

            if(results.length&gt;0) { //result is not empty
                Username = results[0].username;  // Scope is larger than function
                dataRes = {
                    username: results[0].username,
                    firstName: results[0].firstName,
                    lastName: results[0].lastName,
                    roleName: results[0].roleName
                }
                return callback(dataRes);
            } else {
                return callback(false);
            }
        })
    }
}

exports.User = User
</code></pre>
<pre><code>class LoginController {
 
    ValidateLogin(req, res) {   
        let user = new User(); 

        var dataRes;
        var username = req.body.username
        var password = req.body.password

        console.log(username + &quot;kekw&quot; + password); 
        
        user.getlogininfo(username, password, function(result){
            if(result) { 
                dataRes = result;
                var session;

                // Login endpoint               
                if(dataRes.roleName == &quot;useradmin&quot;) {
                    console.log(&quot;Call User Admin Dashboard&quot;);
                    res.redirect(&quot;/UserAdmin&quot;);
                }
                else if(dataRes.roleName == &quot;manager&quot;) {
                    console.log(&quot;Call Manager Dashboard&quot;);
                    res.redirect(&quot;/Manager&quot;);
                }
                else if(dataRes.roleName == &quot;staff&quot;) {
                    console.log(&quot;Called Staff Dashboard&quot;);
                    res.redirect('/Staff');
                }
                else if(dataRes.roleName == &quot;customer&quot;) {
                    console.log(&quot;Called Customer Dashboard&quot;);
                    res.redirect('/Customer');
                }
                /*
                else if(dataRes.role == &quot;Pharmacist&quot;) {
                    console.log(&quot;Called Pharmacist home&quot;);
                    res.redirect('/PharmacistHome');
                }
                else if(dataRes.role == &quot;Patient&quot;) {
                    console.log(&quot;Called Patient home&quot;);
                    res.redirect('/PatientHome');
                }*/                
            }
            else {
                req.flash('message', 'Wrong Username or Password!')
                res.redirect(&quot;/?error=true&quot;);
                return false;
            }
        });        
    }    
}

//module.exports = LoginController;
exports.LoginController = LoginController;
</code></pre>
<p>I want to write test cases for username and password for the useradmin login. How do I do so? Thanks.</p>
",https://stackoverflow.com/questions/72367651/how-to-write-test-cases-in-jest-for-login-page,"['javascript', 'node.js', 'unit-testing', 'testing', 'jestjs']",933,False,0,1
Invalid Record User Must exist - Rspec,"<p>I'm making some unit testing with rspec to <code>Active Campaign</code> and on the response I encounter this error:</p>
<pre><code>Failures:

  1) Create Token for Active Campaign updates a contact
     Failure/Error: expect(response_body).to eq(200)
     
       expected: 200
            got: &quot;\&quot;{\\\&quot;error\\\&quot;:{\\\&quot;reason\\\&quot;:\\\&quot;Invalid Record\\\&quot;,\\\&quot;message\\\&quot;:{\\\&quot;user\\\&quot;:[\\\&quot;must exist\\\&quot;]}},\\\&quot;meta\\\&quot;:{\\\&quot;message\\\&quot;:\\\&quot;Invalid Record\\\&quot;,\\\&quot;type\\\&quot;:\\\&quot;error\\\&quot;,\\\&quot;code\\\&quot;:422,\\\
     
       (compared using ==)
</code></pre>
<p>This is my spec:</p>
<pre><code>require 'rails_helper'

RSpec.describe 'Create Token for Active Campaign', type: :request do
  let(:user) { create(:user) }
  let(:create_active_params) do
    {
      contact: {
        id: '100',
        email: 'john@sample.com',
        app_user_id: 12,
        first_name: 'john',
        last_name: 'Doe',
        tags: 'form-step-1'
      }
    }
  end

  it 'updates a contact' do
    VCR.use_cassette('update_contact') do
      post '/api/v1/active_campaign_contacts', params: create_active_params.to_json, headers: { 'Content-Type' =&gt; 'application/json' }
      response_body = JSON.dump(response.body)
      expect(response_body).to eq(200)
    end
  end
end
</code></pre>
<p>This is my controller I am testing: (which works perfectly fine without rspec)</p>
<pre><code>class API::V1::ActiveCampaignContactsController &lt; API::V1::ApiController
  BASE_URL = Rails.application.credentials.dig(:active_campaign, :url)
  private_constant :BASE_URL
  API_KEY = Rails.application.credentials.dig(:active_campaign, :key)
  private_constant :API_KEY

  def create
    update_contact
  end

  def update_contact
    contact = create_token
    url = URI(&quot;#{BASE_URL}/api/3/contacts/#{contact.active_campaign_id}&quot;)
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true

    request = Net::HTTP::Put.new(url)
    request['Accept'] = 'application/json'
    request['Content-Type'] = 'application/json'
    request['api-token'] = API_KEY
    data = { contact: { fieldValues: [{ field: '1', value: token.email_token }] } }
    request.body = JSON.dump(data)
    response = http.request(request)
    response.code == '200' ? render(json: { success: true }) : render(json: { success: false })
  end

  def create_token
    Token.create_with(
      email_token: SecureRandom.urlsafe_base64(12),
      active_campaign_id: params.dig(:contact, :id)&amp;.to_i
    ).find_or_create_by!(
      user_id: params.dig(:contact, :app_user_id)&amp;.to_i
    )
  end
end
</code></pre>
<p>The controller above works perfectly fine without running the specs. So I'm really not sure what could be failing.</p>
<p>In details, my model <code>Tokens</code> has a <code>t.references :user</code> so whenever I save a <code>Token</code>it looks for a <code>user_id</code></p>
<p>My <code>Tokens</code>model:</p>
<pre><code>class Token &lt; ApplicationRecord
  belongs_to :user
end
</code></pre>
<p>And this is what is being saved or the actual columns when a <code>token is saved</code>:</p>
<pre><code>[#&lt;Token:0x00007f9cdce64080
  id: 16,
  email_token: &quot;K287IeBkuA9fdjAr&quot;,
  active_campaign_id: 100,
  user_id: 12,
  created_at: Thu, 23 Jun 2022 19:12:28.119304000 UTC +00:00,
  updated_at: Thu, 23 Jun 2022 19:12:28.119304000 UTC +00:00&gt;]
</code></pre>
<p>So, it does not nag for a user, but somehow my spec does.</p>
<p>What could I be missing here?</p>
",https://stackoverflow.com/questions/72737764/invalid-record-user-must-exist-rspec,"['ruby-on-rails', 'rspec', 'rspec-rails', 'vcr']",233,False,0,0
React-leaflet unit testing with react-testing-library,"<p>I am having some issues in unit testing my Map component created using React-Leaflet.</p>
<p>Here is my code:</p>
<pre><code>test('Map renders', () =&gt; {
  const {container} = render(
   &lt;Map data={mapData} /&gt;
  );
});
</code></pre>
<p>I am getting this error:
<strong>TypeError: Cannot use 'in' operator to search for '_leaflet_id' in null</strong></p>
<p>If I remove the data it works fine, which is required to render the Map.
I tried using <code>&lt;Map data={JSON.parse(mapData)} /&gt;</code> which gives invalid character error.</p>
<p><strong>EDIT:</strong></p>
<p>I finally figured out the problem, but not the solution. The issue is in rendering the Polygon in the Map component. If I comment it out everything(Marker, EditControl, Popup, Tooltip) works like a charm.
Is thetre any alternative way to fix it?</p>
",https://stackoverflow.com/questions/72858361/react-leaflet-unit-testing-with-react-testing-library,"['reactjs', 'unit-testing', 'react-leaflet']",277,False,0,0
How to do azure function (typescript) unit testing,"<p>I'm pretty new to typescripts and jest.  I have an azure function which works with the traffic manager, and I want to do some unit testing, basically updating endpoints.  One thing I want to test is, my code throws exception if the traffic manager does not have exact 2 endpoints.</p>
<p>Azure has a class <code>TrafficManagerManagementClient</code>, this is its definition</p>
<pre class=""lang-js prettyprint-override""><code>export declare class TrafficManagerManagementClient extends coreClient.ServiceClient {
    $host: string;
    apiVersion: string;
    subscriptionId: string;
    /**
     * Initializes a new instance of the TrafficManagerManagementClient class.
     * @param credentials Subscription credentials which uniquely identify client subscription.
     * @param subscriptionId Gets subscription credentials which uniquely identify Microsoft Azure
     *                       subscription. The subscription ID forms part of the URI for every service call.
     * @param options The parameter options
     */
    constructor(credentials: coreAuth.TokenCredential, subscriptionId: string, options?: TrafficManagerManagementClientOptionalParams);
    endpoints: Endpoints;
    profiles: Profiles;
    geographicHierarchies: GeographicHierarchies;
    heatMap: HeatMap;
    trafficManagerUserMetricsKeys: TrafficManagerUserMetricsKeys;
}
</code></pre>
<p>I need to get the endpoints this way</p>
<pre class=""lang-js prettyprint-override""><code>TrafficManagerManagementClient client = new TrafficManagerManagementClient(...);
let profile = client.profiles.get(...);
let endpoints = profile.endpoints;
</code></pre>
<p>So, I'm trying to mock <code>TrafficManagerManagementClient</code> this way</p>
<pre class=""lang-js prettyprint-override""><code>import {TrafficManager} from &quot;../services/trafficemanager&quot;;

jest.mock(&quot;@azure/arm-trafficmanager&quot;, () =&gt; {
    const original = jest.requireActual(&quot;@azure/arm-trafficmanager&quot;);
    return {
        __esModule: true,
        ...original,
        TrafficManagerManagementClient: class {
            constructor() {
            }
        },
    }
});
</code></pre>
<p>Then I got stuck here.  The mocked <code>TrafficManagerManagementClient</code> does not need any parameters for its constructor, but the compiler gives error here.</p>
<p>Am I mocking it correctly?</p>
",https://stackoverflow.com/questions/74291681/how-to-do-azure-function-typescript-unit-testing,"['typescript', 'unit-testing', 'jestjs', 'ts-jest']",119,False,0,0
"Wanna unit-test a function, but constructor gives error","<p>I am trying to unit test a function which is in an entity class, and it is stored in my DB by the use of a constructor. Each time I am trying to test this function it is giving me that error</p>
<blockquote>
<p>ArgumentCountError: Too few arguments to function App\Entity\Deal::__construct(), 0 passed in /var/www/html/casus/tests/dealsEntityFunctionsTest.php on line 10 and exactly 1 expected</p>
</blockquote>
<p>It is obvious I think, but I am really new with unit testing and that stuff so I couldn't find the answer. Could you please help me?</p>
<p>My code is</p>
<pre><code>class Deal
{
    private bool $isNewToday

    public function __construct($deal)
    {
        $this-&gt;isNewToday = $deal['is_new_today'];
    }

    public function getIsNewToday(): ?bool
    {
        return $this-&gt;isNewToday;
    }

    public function setIsNewToday(bool $isNewToday): self
    {
        $this-&gt;isNewToday = $isNewToday;

        return $this;
    }
}
</code></pre>
<p>And my unit test is</p>
<pre><code>class test extends TestCase
{
    public function testIsNewTodayIsTrue()
    {
        $deal = new Deal();
        $deal-&gt;setIsForSale(true);
        $this-&gt;assertTrue($deal-&gt;getIsForSale(), true);
    }
}
</code></pre>
",https://stackoverflow.com/questions/70696349/wanna-unit-test-a-function-but-constructor-gives-error,['php'],141,True,0,2
Using BCryptPasswordEncoder in Unit Test returns a null value,"<p>I'm learning Unit Testing with JUnit and Mockito on a Spring boot application, I have a registration method I want to test, in my test method I create a User but I see that the value of the password is always null when using .encode(mypassword), resulting in an Assertion Error.</p>
<hr />
<p><strong>UserServiceImpl.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>@Service
public class UserServiceImpl implements UserService {
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
    }


    @Override
    public User register(User user) {


         Role role = roleService.findByName(ERole.ROLE_USER);

         Set&lt;Role&gt; roleSet = new HashSet&lt;&gt;();
         user.setFullName(user.getFullName());
         user.setEmailAddress(user.getEmailAddress());
         user.setPassword(passwordEncoder.encode(user.getPassword()));
         user.setConfirmPassword(&quot;&quot;);
         user.setEmailVerified(true);
         roleSet.add(role);
         user.setRoles(roleSet);

         if(userRepository.existsByEmailAddress(user.getEmailAddress())) {
             throw new EmailAlreadyExistsException(&quot;Account already exists with this email&quot;);
         }
        return userRepository.save(user);
    }



}

</code></pre>
<hr />
<p><strong>UserServiceImplTest.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>@ExtendWith(MockitoExtension.class)
class UserServiceImplTest {

    @InjectMocks
    private UserServiceImpl userService;

    @Mock
    private UserRepository userRepository;

    @Mock
    public PasswordEncoder passwordEncoder;

  

   @BeforeEach
    void setUp() {
        userService = new UserServiceImpl(userRepository, passwordEncoder);
    }

  @Test
    void testIfUserCanRegisterSuccessfully() {

        User user = new User(1, &quot;admin&quot;, &quot;admin@gmail.com&quot;, passwordEncoder.encode(&quot;password&quot;));

        when(userRepository.save(any())).thenReturn(user);
        User theUser = userService.register(user);


        System.out.println(&quot;theUser: &quot; + theUser);

        assertNotNull(theUser);
        assertEquals(1, theUser.getId());
        assertEquals(&quot;admin@gmail.com&quot;, theUser.getEmailAddress());
        assertTrue(passwordEncoder.matches(&quot;password&quot;, theUser.getPassword()));
    }

}

</code></pre>
<hr />
<p><strong>SecurityConfig.java</strong></p>
<pre class=""lang-java prettyprint-override""><code>@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Value(&quot;${spring.security.ant.matchers}&quot;)
    private String[] securityAntMatchers;
    

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint authenticationEntryPoint;

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }



    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable().formLogin().disable().httpBasic().disable();

        http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .exceptionHandling().authenticationEntryPoint(authenticationEntryPoint)
            .and()
            .addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        http
            .authorizeRequests()
            .antMatchers(securityAntMatchers)
            .permitAll()
            .anyRequest()
            .authenticated();
    }

}

</code></pre>
<hr />
<p>The output of theUser is this, I'm not sure how to handle the password encryption when testing the method.</p>
<p>theUser: User{id=1, fullName='admin', emailAddress='admin@gmail.com', dateJoined=Tue Nov 15 00:06:01 CAT 2022, emailVerified=true, password='null'}</p>
<hr />
<p><strong>EDITED</strong></p>
<pre class=""lang-java prettyprint-override""><code>

    @BeforeEach
    void setUp() {
        // Instantiating password encoder before every test, now I get the output
        this.passwordEncoder = new BCryptPasswordEncoder();
        userService = new UserServiceImpl(userRepository, passwordEncoder);


    }

  @Test
    void testIfUserCanRegisterSuccessfully() {
        User user = new User(1, &quot;admin&quot;, &quot;admin@gmail.com&quot;,&quot;password&quot;);

        when(userRepository.save(any())).thenReturn(user);
        User created = userService.register(user);

        assertEquals(created.getPassword(), user.getPassword());
        assertEquals(created.getEmailAddress(), user.getEmailAddress());
        verify(userRepository).save(any());
    }

</code></pre>
",https://stackoverflow.com/questions/74438448/using-bcryptpasswordencoder-in-unit-test-returns-a-null-value,"['java', 'testing', 'junit', 'mockito']",274,True,0,1
Writing a code without using any python libraries or built in python functions and using an unit test,"<p>Hello I am struggling in my AI class right now we are working on this homework pertaining to python and unit testing. Here is the homework question:</p>
<p>Without using any python libraries or built in python functions:</p>
<ul>
<li>Show you can do the necessary research to lookup the formula for mode
and standard deviation</li>
<li>Write a function that returns the &quot;mode&quot; from a list</li>
<li>Write a function that returns the standard deviation of the list</li>
<li>Write unit tests for both functions that cover all use cases</li>
</ul>
<p>Here is what I have so far, just don't know if it's done correctly.</p>
<pre><code>def mode(num):
    count = dict()
    mode = False
    mode_int = 0
    result = 0
    for x in num:
        if not count.get(x):
            count[x] = 1
        else:
            count[x] += 1
            mode = True
            if count[x] &gt; mode_int:
                mode_int = count[x]
                result = x
    if mode:
        return result
    else:
        return &quot;There was no mode&quot;

</code></pre>
<pre><code>def standard_deviation(num):
    total = 0
    for x in num:
        total += x
    m = total/len(num)
    size = len(num)
    i = 0
    sum = 0
    while i &lt; size:
        sum += (num[i] - m) * (num[i] - m)
        i += 1
    sum = sum / (size - 1)
    return sum**0.5

</code></pre>
",https://stackoverflow.com/questions/71303074/writing-a-code-without-using-any-python-libraries-or-built-in-python-functions-a,"['python', 'unit-testing']",383,False,0,0
What is NoOpMediator in Clean Architecture,"<p>I am playing around with the <a href=""https://ardalis.com/clean-architecture-asp-net-core/"" rel=""nofollow noreferrer"">Clean Architecture by Ardalis</a>.</p>
<p>Can someone please explain what this <a href=""https://github.com/ardalis/CleanArchitecture/blob/main/tests/Clean.Architecture.UnitTests/NoOpMediator.cs"" rel=""nofollow noreferrer"">NoOpMediator</a> role in Unit testing?</p>
<pre class=""lang-cs prettyprint-override""><code>using System.Runtime.CompilerServices;
using MediatR;

namespace Clean.Architecture.UnitTests;

public class NoOpMediator : IMediator
{
  public Task Publish(object notification, CancellationToken cancellationToken = default)
  {
    return Task.CompletedTask;
  }

  ...
  ...
}
</code></pre>
<p>It does not seem to do anything. For <a href=""https://github.com/ardalis/CleanArchitecture/blob/af7379fedcef0176f3f1dfc0dc41bf047c3843db/tests/Clean.Architecture.UnitTests/NoOpMediator.cs#L10"" rel=""nofollow noreferrer"">four of its methods it returns Task.CompletedTask</a>. And for the <a href=""https://github.com/ardalis/CleanArchitecture/blob/af7379fedcef0176f3f1dfc0dc41bf047c3843db/tests/Clean.Architecture.UnitTests/NoOpMediator.cs#L20"" rel=""nofollow noreferrer"">rest of the two it returns Task.FromResult&lt;object?&gt;(default)</a></p>
<p>Further more in the <a href=""https://github.com/ardalis/CleanArchitecture/blob/af7379fedcef0176f3f1dfc0dc41bf047c3843db/tests/Clean.Architecture.IntegrationTests/Data/BaseEfRepoTestFixture.cs#L17"" rel=""nofollow noreferrer"">BaseEfRepoTestFixture class here</a>, there is no configuration of Mock object. Bit misty.</p>
<p>Also noted that this is configured in <a href=""https://github.com/ardalis/CleanArchitecture/blob/main/tests/Clean.Architecture.FunctionalTests/CustomWebApplicationFactory.cs"" rel=""nofollow noreferrer"">CustomWebApplicationFactory</a> way <a href=""https://github.com/ardalis/CleanArchitecture/blob/af7379fedcef0176f3f1dfc0dc41bf047c3843db/tests/Clean.Architecture.FunctionalTests/CustomWebApplicationFactory.cs#L87"" rel=""nofollow noreferrer"">down here</a>.</p>
<pre><code>services.AddScoped&lt;IMediator, NoOpMediator&gt;();
</code></pre>
<p>Even if I comment out that line, the tests still pass.</p>
<p><a href=""https://i.stack.imgur.com/IpWok.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/IpWok.png"" alt=""Units tests sill passing even after NoOpMediator Configuration is removed"" /></a></p>
<p>There should be an example test to show how this works.</p>
",https://stackoverflow.com/questions/71008347/what-is-noopmediator-in-clean-architecture,"['clean-architecture', 'mediatr', 'ardalis-cleanarchitecture']",144,False,0,0
Why does Python unit test on SQLite Database fail when I have all the parameters?,"<p>I'm new to python and I'm trying unit testing. Right now I'm trying to test insertions into my SQLite database but it keeps saying I'm missing the required parameters 'author', 'maincharacter', 'place', 'year' when I've entered it in my insertion statement. I'm obviously missing something but I just can't see it.</p>
<p>Here's the unit test case:</p>
<pre><code>import unittest

import backend


class MyTestCase(unittest.TestCase):
   def test_db_write(self):
    self.assertEqual(backend.insert(&quot;&quot;&quot;INSERT INTO `book`&quot;, (title, author, year, maincharacter, place) 
                           ('5', 'Harry Potter', 'JK Rowling', '2000','Harry','Closet' )&quot;&quot;&quot;), True)
    self.assertEqual(backend.insert(&quot;&quot;&quot;INSERT INTO `book`&quot;, (title, author, year, maincharacter, place)
                                       ('6', 'Harry Potter', 'JK Rowling', '2000','Harry','Closet')&quot;&quot;&quot;), True)
    self.assertEqual(backend.delete(&quot;&quot;&quot;DELETE FROM `book` WHERE id='5' &quot;&quot;&quot;), True)
    self.assertEqual(backend.delete(&quot;&quot;&quot;DELETE FROM `book` WHERE id='6' &quot;&quot;&quot;), True)


if __name__ == '__main__':
    unittest.main()
</code></pre>
<p>This is the error message:</p>
<p>Error
Traceback (most recent call last):
File &quot;C:\Users\google\PycharmProjects\BookManagementSystem\BookManagerTest.py&quot;, line 8, in test_db_write
self.assertEqual(backend.insert(&quot;&quot;&quot;INSERT INTO book VALUES(NULL, ?,?,?,?,?)&quot;, (title, author, year, maincharacter, place)
TypeError: insert() missing 4 required positional arguments: 'author', 'year', 'maincharacter', and 'place'</p>
",https://stackoverflow.com/questions/73170545/why-does-python-unit-test-on-sqlite-database-fail-when-i-have-all-the-parameters,"['python', 'unit-testing', 'pytest', 'python-unittest']",177,True,0,1
JEST - detected 1 open handle - AWS SDK SSM,"<p>When implementing unit testing with the help of the JEST framework, I have problems with the AWS SDK.</p>
<p>Attached is the <code>api.test.js</code> which calls the handler function of the <code>api.js</code> which makes an AWS SDK call to SSM to get the credentials to a DB connect in the <code>config.js</code>.</p>
<p>The unit test runs fine and pass, but the test cannot be finished with the message &quot;<strong>Jest has detected the following 1 open handle potentially keeping Jest from exiting: --&gt; TLSWRAP</strong>&quot;, which causes by the call to the SSM API.</p>
<p>Is there a possible solution to close this open connection?</p>
<p><strong>api.test.js</strong></p>
<pre><code>test('API GET/{ID}', async () =&gt; {
    const event = {httpMethod: &quot;GET&quot;, pathParameters: {id: 1234}};
    const getResult = await api.handler(event);
    expect(getResult).toBeDefined(); 
    expect(typeof getResult).toBe('object');
});
</code></pre>
<p><strong>api.js</strong></p>
<pre><code>module.exports.handler = async event =&gt; {
    if (typeof connection === undefined) {
      let config = await getDBConfigFromSSM();
      /* CREATE DB CONNECTION */
    }
    /* MAKE DB CALL */
};
</code></pre>
<p><strong>config.js</strong></p>
<pre><code>const AWS = require('aws-sdk');
const ssm = new AWS.SSM();

module.exports.getDBConfigFromSSM = async () =&gt; {
  const params = {
    Name: `PATH/TO/db-config`,
    WithDecryption: true,
  };

  try {
    return await ssm.getParameter(params).promise();
  } catch (ex) {
    console.error(ex);
    console.log('ERROR', ex);
    return false;
  }
};
</code></pre>
",https://stackoverflow.com/questions/73682466/jest-detected-1-open-handle-aws-sdk-ssm,"['amazon-web-services', 'jestjs']",93,False,0,0
How to test a controller that uses IMemoryCache?,"<p>I have a controller with the definition:</p>
<pre><code>public async Task&lt;ResponseDto&gt; MethodNameController(List&lt;string&gt; identifiers)
{
    if(!_cache.TryGetValue(key, out IDictonary&lt;string, string&gt; result))
    {
        result = await service.GetMethodService(activityContextObject, identifiers)
        var cacheEntryOptions = new MemoryCacheEntryOptions()
        .SetSlidingExpiration(TimeSpan.FromSeconds(80))
        .SetAbsoluteExpiration(TimeSpan.FromSeconds(120))
        .SetSize(1024);
        _cache.Set(key, result, cacheEntryOptions);
    }

    return new ResponseDto{ //ResponseDto Object split into many fields};
}
</code></pre>
<p>The constructor is as below</p>
<pre><code>public Controller(serviceName, httpContextAccessor, IOptionsSnapshot_config, IMemoryCache)
{
    _serviceName = serviceName,
    _httpContextAccessor = httpContextAccessor,
    _config = IOptionsSnapshot_config
    _cache = IMemoryCache
}
</code></pre>
<p>I'm facing difficulty in unit testing this method. I followed <a href=""https://stackoverflow.com"">this blog</a>, <a href=""https://stackoverflow.com/questions/38318247/mock-imemorycache-in-unit-test"">this SO answer</a> and many more trynig to replicate them in my scenario and failed. I tried passing regular memory cache object(because I'm unable to mock it) but invoking controller returns error <code>slidingExpirationTime should be positive, current time set is 00:00:00</code> I'm unable to set the sliding expiration in test classes.
Can anyone guide me to correct resources or tell me how I can test this method. I'm new to writing xUnit tests, so any help will be great(For learning moq etc).</p>
",https://stackoverflow.com/questions/73791847/how-to-test-a-controller-that-uses-imemorycache,"['c#', '.net', 'asp.net-core', 'asp.net-web-api', 'xunit.net']",143,True,0,1
Mockito - Mock a service method call in a different class,"<p>Consider I have two classes [classA and classB]. I am unit testing methodA1() of classA which makes call to another methodB1 present in classB. Again in classB a different serviceB1 calls a method methodB2.</p>
<p>I want to mock the output of serviceB1.methodB2();</p>
<pre><code>@Service
classA {
  @Autowired
  private ServiceA1 serviceA1;

  public XYZ methodA1(String str) {
    return serviceA1.methodB1(str);
  }
}
</code></pre>
<hr />
<pre><code>@Service
classB {
  @Autowired
  private ServiceB1 serviceB1;

  public XYZ methodB1(String str) {
    return serviceB1.methodB2(str);  // I want to mock the output of this call from methodA1() in classA
  }
}
</code></pre>
<p>What i did?</p>
<p>I tried to Mock the serviceB1 and mocked the return value methodB2, but it was constantly returning 'null' value.</p>
<p>Also, for now I don't want to mock the return value of serviceA1.methodB1(str);</p>
<p>Please suggest me if I'm doing too much of should I directly mock serviceA1.methodB1(str);</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/74267998/mockito-mock-a-service-method-call-in-a-different-class,"['java', 'mockito', 'junit5']",31,False,0,0
Upload an Excel File using Flask test client without mocking,"<p>View for my API:</p>
<pre><code>@api.resource('/project/&lt;string:val&gt;/upload')
class UploadView(Resource):
    @classmethod
    @jwt_required
    def post(self, val):
        uploaded_file = request.files['file']
        file_name = secure_filename(uploaded_file.filename)
        file_path = os.path.join('data','files',filename)
        try:
            uploaded_file.save(file_path)
            status_code = 200
            response[&quot;result&quot;] = &quot;done&quot;
        except Exception as e:
            print(e)
        return Response(response, status_code)
</code></pre>
<p>PyTest function having client, headers passed in as fixtures in functional scope used in the test class:</p>
<pre><code>def test_upload_view(self, client, headers):
    file_path = rootdir + 'file.xlsx'
    file = FileStorage(
            stream=io.BytesIO(open(file_path, &quot;rb&quot;).read()),
            filename=&quot;uploadedFile.xlsx&quot;,
            content_type=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&quot;,
       )
    url = &quot;/v1/project/K6400/upload&quot;
    response = client.post(
                url,
                headers=headers,
                data=dict(file=file),
                follow_redirects=True,
                content_type=&quot;application/vnd.openxmlformats-officedocument.spreadsheetml.sheet&quot;
               )
    assert response.status_code == 200
</code></pre>
<p>I have set up and teardown methods implemented properly which also closes the opened file to avoid errors. I am still getting a 400 error on the POST method. My API works properly on the UI and downloads the file, but on unit testing, it is failing. I understand request.files['file'] is a FileStorage object so I have tried to covert into BytesIO in the stream argument. Not sure what, I am doing wrong. Help would be really appreciated.</p>
",https://stackoverflow.com/questions/73127059/upload-an-excel-file-using-flask-test-client-without-mocking,"['python', 'flask', 'pytest', 'werkzeug']",243,True,0,2
Set State of Functional Component While Unit Testing in Jasmine,"<p>My Component:</p>
<pre class=""lang-js prettyprint-override""><code>import React from 'react';

export const Bar() {
 const [myState, setMyState] = React.useState([]);

 const disableSubmit = React.useMemo(() =&gt; {
  return myState.length === 0
 }, [myState]);

 // logic to get myState data by making API call
 setMyState(getMyStateData());

 const onSubmit = () =&gt; {
  // do some validation and make API call
 };
 
 return (
  &lt;form
   className=&quot;form-wrapper&quot;      
   onSubmit={event =&gt; props.onSubmit(event)}
  &gt;
   // logic to display myState data
   &lt;button className=&quot;btn custom-btn&quot; type=&quot;submit&quot; value=&quot;Submit&quot; disabled={disableSubmit}&gt;
     Submit
   &lt;/button&gt;
  &lt;/form&gt;
 );
}
</code></pre>
<p>I am using Jasmine to do unit testing on my components.</p>
<p>I want to write a unit test to simulate the click event on submit button but I can't do this until the value of <code>myState</code> is not set to some array with <code>length&gt;0</code>.</p>
<p>How can I set the value of <code>myState</code> in my unit test?</p>
<p>I have already tried using <code>instance</code> and then setting the value of <code>myState</code> but it throws an error that <code>component.instance()</code> is <code>undefined</code>.</p>
<p>I also came across <code>setState</code> but I found out that it only works for class components.</p>
<p>So, how can I set the value of <code>myState</code> in my unit test?</p>
",https://stackoverflow.com/questions/74199923/set-state-of-functional-component-while-unit-testing-in-jasmine,"['reactjs', 'unit-testing', 'jasmine', 'karma-jasmine']",102,False,0,0
Is there an example of PyFlink SQL unit testing in a self-contained repo?,"<p>Is there an example of a self-contained repository showing how to perform SQL unit testing of PyFlink (specifically 1.13.x if possible)?</p>
<p>There is a related SO question <a href=""https://stackoverflow.com/questions/69937520/pyflink-sql-local-test"">here</a>, where it is suggested to use some of the tests from PyFlink itself.  The issue I'm running into is that the PyFlink repo assumes that a bunch of things are on the Java classpath and that some Python utility classes are available (they're not distributed via PyPi apache-flink).</p>
<p>I have done the following:</p>
<ol>
<li>Copied <code>test_case_utils.py</code> and <code>source_sink_utils.py</code> from <a href=""https://github.com/apache/flink/tree/f8172cdbbc27344896d961be4b0b9cdbf000b5cd/flink-python/pyflink/testing"" rel=""nofollow noreferrer"">PyFlink</a> into my project.</li>
<li>Copy an example unit test (<a href=""https://github.com/apache/flink/blob/f8172cdbbc27344896d961be4b0b9cdbf000b5cd/flink-python/pyflink/table/tests/test_sql.py#L39"" rel=""nofollow noreferrer"">this one</a> as suggested by the related SO question.</li>
</ol>
<p>When I try to run the test, I get an error because the test case cannot determine what version of Avro jars to download (<code>download_apache_avro()</code> fails, because <a href=""https://github.com/apache/flink/blob/34e6895af8587b62a692f76591882f9a061fdb34/flink-python/pyflink/pyflink_gateway_server.py#L230-L232"" rel=""nofollow noreferrer"">this code</a> tries to evaluate the value of <code>avro.version</code> by running <code>mvn help:evaluate -Dexpression=avro.version</code>)</p>
<p>I then added a dummy <code>pom.xml</code> defining a Maven property of <code>avro.version</code> (with a value of <code>1.10.0</code>) and my unit test case is loaded.</p>
<p>I now get a new error and my test is skipped:</p>
<pre><code>'flink-table-planner*-tests.jar' is not available. Will skip the related tests.
</code></pre>
<p>I don't know how to fix this. I've tried adding <code>flink-table-planner</code> and <code>flink-table-planner-blink</code> dependencies with <code>&lt;type&gt;test-jar&lt;/type&gt;</code> to my dummy pom.xml, but it still fails.</p>
<p>This is starting to feel like a real pain to do something that should be trivial: basic TDD of a PyFlink project.  Is there a real-world example of a Python project that shows how to set up a testing environment for unit testing SQL with PyFlink?</p>
",https://stackoverflow.com/questions/71983434/is-there-an-example-of-pyflink-sql-unit-testing-in-a-self-contained-repo,"['python', 'apache-flink', 'flink-sql', 'pyflink']",238,False,0,1
What are the benefits of Reactive Form over Template-Driven Form?,"<p>Answers to other similar questions are talking about form scalability and unit testing.</p>
<p>Could you please give some examples of large scaled form that cannot be made by <code>[(ngModel)]</code> with <code>*ngIf</code> and <code>*ngFor</code>?</p>
<p>About the unit testing, Angular official documentation gives samples of view-to-model and model-to-view testing cases. There ARE differences between two approaches.</p>
<p>But aren't those tests responsibility of <code>@angular/forms</code>? Why should we do such tests in our own component? Shouldn't we trust Angular while using its official mature stable modules?</p>
<p>So please give evidences that Reactive Forms are really better than Template-Driven Forms, not just saying so.</p>
<p>Can you please state a case where reactive cover a scenario that can't be accomplished with template driven forms?</p>
<p>Can you please give a unit test example that is not the case and responsibility of Value Accessor?</p>
<p>Angular as an MVVM FE framework, you have a View(HTML template), you have a Model(JavaScript object represents the form), and you have a View-Model(two-way binding of [(ngModel)] and other directives beneath). Then there're the FormGroups, FormControls and FormArrays that managed to fulfill the same scalability as of JavaScript object?</p>
<p>TypeScript is already typed, now the typed forms?</p>
<pre class=""lang-html prettyprint-override""><code>&lt;input [(ngModel)]=&quot;loginForm.email&quot;&gt;
&lt;input [(ngModel)]=&quot;loginForm.password&quot;&gt;
</code></pre>
<pre><code>export interface LoginForm {
  email: string;
  password: string;
}

export class MyComponent {

  loginForm: LoginForm = {
    email: '',
    password: '',
  }

  // ...
}
</code></pre>
<p>Or double the complexity by a nullable
<code>const email = new FormControl&lt;string|null&gt;('angularrox@gmail.com');</code> because its value will be null when you call reset <code>email.reset()</code>.</p>
<blockquote>
<p>... option affects the runtime behavior of your form when .reset() is called, and should be flipped with care ...</p>
</blockquote>
<p><a href=""https://angular.io/guide/typed-forms#nullability"" rel=""nofollow noreferrer"">https://angular.io/guide/typed-forms#nullability</a></p>
<p>That'll just add burden to the developers.</p>
",https://stackoverflow.com/questions/73501914/what-are-the-benefits-of-reactive-form-over-template-driven-form,"['angular', 'angular-reactive-forms']",145,True,-1,1
Can&#39;t Mock _db.Users for XUnit Testing in C# MVC App,"<p>I have an MVC app and I'm trying to do Unit Testing and injecting all of the relevant code into the Testing app. This is the part of my actual app (called amaranth) that I'm currently testing for the <code>Index()</code> function (which returns a View) in a Controller called <code>amaranth/Controllers/AdminController.cs</code>:</p>
<pre><code>using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using amaranth.Data;
using amaranth.Models.ViewModels;
using amaranth.Helpers;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using amaranth.Models;
using NBitcoin;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace amaranth.Controllers
{
    [Authorize(Roles = &quot;Admin&quot;)]
    public class AdminController : Controller
    {
        private ApplicationDbContext _db;
        private UserManager&lt;IdentityUser&gt; _manager;
        private BitcoinHelper _btcHelper;

        public AdminController(ApplicationDbContext ctx, UserManager&lt;IdentityUser&gt; manager, BitcoinHelper bitcoinHelper) : base()
        {
            _db = ctx;
            _manager = manager;
            _btcHelper = bitcoinHelper;
        }

        public IActionResult Index()
        {
            var users = _db.Users
                .OrderBy(p =&gt; p.Id)
                .ToList();

            return View(users);
        }
</code></pre>
<p>I want to test <code>Index()</code>. So I have a parallel project <code>amaranth.Tests</code> in the same directory as <code>amaranth</code>. I constructed the following test in <code>amaranth.Tests/Controllers/AdminControllerTest.cs</code>:</p>
<pre><code>using Moq;
using amaranth.Data;
using Microsoft.AspNetCore.Identity;
using Xunit;
using Microsoft.EntityFrameworkCore;

namespace amaranth.Tests.Controllers
{
    public class AdminControllerTest
    {
        private Mock&lt;ApplicationDbContext&gt; _db = new Mock&lt;ApplicationDbContext&gt;();
        private Mock&lt;UserManager&lt;IdentityUser&gt;&gt; _manager = new Mock&lt;UserManager&lt;IdentityUser&gt;&gt;();

        [Fact]
        public void Test1()
        {
            var options = new DbContextOptionsBuilder&lt;Users&gt;()
                .UseInMemoryDatabase(databaseName: &quot;amaranth_test_dbone&quot;)
                .Options;

            using (var context = new UserContext(options))
            {
                context.Users.Add(new User { UserName = &quot;example@gmail.com&quot;, NormalizedUserName = &quot;EXAMPLE@GMAIL.COM&quot;, Email = &quot;EXAMPLE@GMAIL.COM&quot; });
                context.SaveChanges();
            }

            using (var context = new UserContext(options))
            {
                var users = _db.Users
                    .OrderBy(p =&gt; p.Id)
                    .ToList();
                Assert.NotEmpty(users);
            }
        }
    }
}
</code></pre>
<p>This test is just supposed to see if the <code>users</code> entry contains any actual entries which it should because I &quot;Mocked&quot; one called &quot;example@gmail.com.&quot; The compiler throws the error <code>'DbContextOptionsBuilder&lt;Users&gt;' does not contain a definition for 'UseInMemoryDatabase' and no accessible extension method 'UseInMemoryDatabase' accepting a first argument of type 'DbContextOptionsBuilder&lt;Users&gt;', could be found (are you missing a using directive or an assembly reference?)</code> on <code>UseInMemoryDatabase</code> and can't find <code>Users</code> or <code>UserContext</code>. So what am I doing wrong?</p>
",https://stackoverflow.com/questions/72419687/cant-mock-db-users-for-xunit-testing-in-c-mvc-app,"['c#', 'asp.net-mvc', 'unit-testing', 'moq']",152,False,3,1
Mocking Bigquery for integration test,"<p>I'm using <a href=""https://github.com/googleapis/google-cloud-go"" rel=""nofollow noreferrer"">https://github.com/googleapis/google-cloud-go</a> to interact with GCP Bigquery to fetch some data.</p>
<p>I want to write some tests for my code. for the unit testing, it's easy because I can mock my repository ( data layer) and return what I expected for.</p>
<p>I'm looking for writing an integration test,  if it was just basic HTTP I could write a httptest server and return some dummy ( fake) data. but this library is using gRPC to communicate with GCP Bigquery.</p>
<p>I'm wondering how I can write an integration test for GCP Bigquery in Golang.</p>
<p>let's keep it in the simplest way and just provide the integration part for <code>Query a table in a dataset and read data</code>.</p>
",https://stackoverflow.com/questions/74878734/mocking-bigquery-for-integration-test,"['go', 'testing', 'integration-testing']",1166,True,3,1
Make mocha test fail in try / catch,"<p>I have the following function to validate a JSON file:</p>
<pre><code>export const validateJSON = (sourceDir, fileName) =&gt; {
  return new Promise((resolve, reject) =&gt; {
    try {
        pricingService.processJSON(params, data)
          .then(data =&gt; {
            config.accounts.currencies.forEach(function (currency) {
              if (data[currency] === '' || data[currency] === undefined) {
                reject({err: 'Missing required values'});
              }
            });
            resolve('JSON Validation Success');
          })
          .catch(error =&gt; {
            logger.error({
              message: `Error while processing JSON, request Failed with Error: ${error}`,
            });
            reject({err: error});
          });
      }
    } catch (error) {
      logger.error({
        message: `Error while validating JSON file, request Failed with Error: ${error}`,
      });
      return reject({err: {status: 422, message: 'Error while validating JSON - Unprocessable Entity'}});
    }
  });
};
</code></pre>
<p>Now, I have a test in Mocha</p>
<pre><code>it.only('Validate Pricing JSON file', function () {
        s3Service.validateJSON('',filename,Date.now()).then(data =&gt;{
            setTimeout(() =&gt;{
                assert.equal(data, 'JSON Validation Success')
                done()
            }, 1000)
        }).catch(function (error) {
            console.error(&quot;JSON validation failed &quot;+JSON.stringify(error))
            throw error
        })
    });
</code></pre>
<p>What I am trying to do is to validate the JSON file in the test and if there is some fields are missing in the file, the test should fail. Now when I execute the test with a file with missing entries, I am getting the following error printed to console.</p>
<p><code>JSON validation failed {&quot;err&quot;:{&quot;status&quot;:422,&quot;message&quot;:&quot;Error while validating JSON - Unprocessable Entity&quot;}}</code></p>
<pre><code>(node:26091) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): #&lt;Object&gt;
(node:26091) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
</code></pre>
<p>But the test is shown as passed. How can I make it fail if there is an error ? Also how to get rid of the <code>UnhandledPromiseRejectionWarning</code> ? I am very new to Unit Testing and so any help will be appreciated.</p>
",https://stackoverflow.com/questions/74472789/make-mocha-test-fail-in-try-catch,"['node.js', 'mocha.js']",28,False,2,1
Cannot connect to SQL database using Blazor and Entity Framework,"<p>I'm trying to setup a simple Blazor website that connects to a SQL Server database and I can't seem to get it to work, I get an error:</p>
<blockquote>
<p>System.PlatformNotSupportedException: Strings.PlatformNotSupported_DataSqlClient</p>
</blockquote>
<p>when trying to query any of the database entities. Connecting to the same database and using the same <code>DBContext</code> works fine from a unit testing projects, I just can't make it work using Blazor.</p>
<p>In my program.cs I have:</p>
<pre><code>builder.Services.AddDbContext&lt;IntegrationDBContext&gt;(options =&gt; options.UseSqlServer(@&quot;MyConnString&quot;));
</code></pre>
<p>I even tried using an in-memory provider, which worked fine. I'm using .NET 6 and connecting to an Azure based SQL (although I did try connecting to a LocalDB instance, with the same results).</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/70835347/cannot-connect-to-sql-database-using-blazor-and-entity-framework,"['c#', '.net', 'entity-framework', 'blazor', 'blazor-webassembly']",1231,True,2,1
Using Xunit in .Net core web API - How to test/ pass 500 status code,"<p>We are trying the Test Driven Development for our .Net core 3.1 Web API and using XUnit for the same.</p>
<p>In my controller, I have test cases or [Fact] written for the status codes 200,404 and other scenarios.</p>
<p>When it comes to unit testing 500 internal server error - <strong>I am not sure how to pass the code</strong>, or how to assert it.</p>
<p>It always fails for me by using the below code.</p>
<p>How to <strong>successfully test the 500 - Internal server error in my unit test</strong>?</p>
<p>I am very new to TDD any comment is helpful, below is the code :</p>
<pre><code>[Fact] // 404 Sample unit test method
public async Task Get_OnNotFound_Returns404()
{
    // Arrange
    var mockService = new Mock&lt;IService&gt;();

    mockService.Setup(service =&gt; service.GetTypes(It.IsAny&lt;string&gt;(), 
        It.IsAny&lt;CancellationToken&gt;())).ReturnsAsync(new List&lt;TypeResponse&gt;());

    var sut = new HomeController(mockService.Object);

    //Act
    var result = await sut.GetSampleMethod(&quot;foo&quot;) as ObjectResult;

    //Assert

    Assert.Equal(StatusCodes.Status404NotFound, result.StatusCode);
}


// Below is my always failing 500 code unit test

[Fact]
public async Task Returns_500_When_Returns_Error()
{
    // Arrange
    var mockService = new Mock&lt;IService&gt;();

    mockService.Setup(service =&gt; service.GetTypes(It.IsAny&lt;string&gt;(),
        It.IsAny&lt;CancellationToken&gt;())).ReturnsAsync(new List&lt;TypeResponse&gt;());

    var sut = new HomeController(mockService.Object);

    //Act
    var result = await GetSampleMethod(&quot;foo&quot;) as ObjectResult;

    //Assert
    Assert.Equal(StatusCodes.Status500InternalServerError, result.StatusCode);
}
</code></pre>
<p>Below is my controller method :</p>
<pre><code>[HttpGet]
public async Task&lt;IActionResult&gt; GetSampleMethod(string id, 
    CancellationToken cancellationToken)
{
    try
    {
        var result = await _service.GetSampleMethod(id, cancellationToken);
        if (result.Any())
        {
            return Ok(result);
        }

        return StatusCode(StatusCodes.Status404NotFound,
            new Error { Message = &quot;No Records .&quot; });
    }
    catch (Exception ex)
    {
        return StatusCode(StatusCodes.Status500InternalServerError,
            new Error
            {
                Message = !string.IsNullOrWhiteSpace(ex.Message)
                    ? ex.Message : &quot;An unhandled error occurred.&quot;
            });
    }
}
</code></pre>
",https://stackoverflow.com/questions/72168889/using-xunit-in-net-core-web-api-how-to-test-pass-500-status-code,"['c#', 'asp.net-core', 'tdd', 'xunit', 'http-status-code-500']",2122,True,2,1
Mocha not recognizing path definitions defined in tsconfig in Vue project,"<p>I'm unit testing my pinia stores in a vue project. I use the &quot;@&quot; src reference throughout my project, e.g. &quot;@models&quot; should map to &quot;src/models&quot; as defined in tsconfig compiler options:</p>
<pre><code>&quot;paths&quot;: {
      &quot;@/*&quot;: [
        &quot;src/*&quot;,
      ]
    },
</code></pre>
<p>This works fine when running the code, but breaks with Mocha tests:</p>
<pre><code>Error: Cannot find module '@/models'
</code></pre>
<p>coming from this line:</p>
<pre><code>import { Recipe } from &quot;@/models&quot;;
</code></pre>
<p>My relevant directory structure:</p>
<pre><code>-project root
/public
/src
   /models
/tests
tsconfig.json
</code></pre>
<p>My mocha script:</p>
<pre><code>&quot;test&quot;: &quot;env TS_NODE_COMPILER_OPTIONS='{\&quot;module\&quot;: \&quot;commonjs\&quot;}' mocha --exit -r ts-node/register 'tests/**/*.ts'&quot;
</code></pre>
<p>I've tried adding a &quot;path&quot; item to the script TS_NODE_COMPILER_OPTIONS and tried all manner of relative paths, but still get the same error.  It's not a huge deal as the tests will run if I don't use the &quot;@&quot; notion for paths, but would like to understand why it doesn't work.</p>
",https://stackoverflow.com/questions/71174503/mocha-not-recognizing-path-definitions-defined-in-tsconfig-in-vue-project,"['typescript', 'vue.js', 'mocha.js']",282,False,2,0
Koin singleton injection vs Kotlin object,"<p>I'm a bit confused should I use Koin or any other dependency Injection for providing repositories to ViewModel or Should I use Kotlin object class for repositories so that we don't need to pass any dependency to ViewModel.
Also for unit testing, we can mock kotlin object using mockk so no problem in mocking.</p>
<p>In my opinion, the first approach is very easy to create a Kotlin object but there may be a reason to use Koin or any other in this situation that I'm not aware of.</p>
<pre><code>object SomeRepository{

    fun someFunction() {
        ApiHelper.getData()
    }
}

class SomeViewModel {

    fun someFunction(number: Long) {
       SomeRepository.someFunction() 
    }
}

OR

class SomeRepository(api:ApiHelper){

    fun someFunction() {
        api.getData()
    }
}

class SomeViewModel(repo: SomeRepository) {

    fun someFunction(number: Long) {
       repo.someFunction() 
    }
}
</code></pre>
<p>Using koin we can inject repository and API helper</p>
<p>Please help me to clarify which approach is best and why.</p>
",https://stackoverflow.com/questions/71672872/koin-singleton-injection-vs-kotlin-object,"['android', 'unit-testing', 'kotlin', 'dependency-injection', 'koin']",1719,False,2,0
Angular unit tesing HTTP interceptor that appends XCSRF token in header,"<p>I am unit testing global HTTP interceptor that gets the XSCRF token from a service call  <strong>getReponse()</strong> and appends it to the header only in POSTS request <strong>postResponse()</strong> call ( service call mentioned below )</p>
<p>So far I tried testing it but i am not able to pass the test case. Any help would be much appreciated.</p>
<p>This is the <strong>optout.service.ts</strong> file which contains two methods</p>
<blockquote>
<p>getResponse() method uses mergeMap to chain two calls, first service call is to get the token for XCSRF and the second to get the form response</p>
</blockquote>
<pre><code> getReponse():Observable&lt;optout&gt;{
    return this.httpClient.get&lt;any&gt;(`https://thisIsGetTokenApi.com`).pipe(
     mergeMap(token=&gt;this.httpClient.get&lt;optout&gt;(`https://someurlenpoint2.com`))
  )

  postResponse(data:optout):Observable&lt;optout&gt;{
    return this.httpClient.post&lt;optout&gt;('https://api-endpoint',data)
    }
</code></pre>
<p>Here is <em><strong>global-http-interceptor.ts</strong></em> file</p>
<pre><code>import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpErrorResponse, HttpResponse } from '@angular/common/http';
import { Observable } from &quot;rxjs&quot;;
import { tap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { environment } from 'src/environments/environment';

@Injectable({
  providedIn: 'root'
})

export class GlobalHttpInterceptorService implements HttpInterceptor {
  public hostURL=environment.hostURL;
  public apiURL=environment.apiURL;

  constructor(public router: Router) { }

  token:string='';
  intercept(req: HttpRequest&lt;any&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;any&gt;&gt; {
    if(this.token &amp;&amp; req.method== &quot;POST&quot;){
      req=req.clone({headers:req.headers.append('X-CSRF-TOKEN',this.token)});
    }
    return next.handle(req)
    .pipe(
        tap(event =&gt; {
          if (event instanceof HttpResponse) {
            if(req.url.includes('/getToken')){
            this.token=event.body.XCSRFTOKEN;
          }
        }
      }, (error:any) =&gt; {
          if(error instanceof HttpErrorResponse){
            if(error.status === 400 || error.status === 401 || error.status === 402){
            window.location.href=`https://some-direct-url.com`;
            }
          }
        })
      )
    }
  }
</code></pre>
<p><strong>This is test spec file global-http-interceptor.spec.ts that i tried</strong></p>
<pre><code>import { fakeAsync, TestBed, tick } from '@angular/core/testing';
import { GlobalHttpInterceptorService } from './global-http-interceptor.service';
import { RouterTestingModule } from '@angular/router/testing';
import { OptoutService } from './optout.service';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { API_CONFIG_TOKEN } from '../token';
import { GlobalConstants } from '../global-constants';
import { environment } from 'src/environments/environment';
import { optout } from '../model/optoutModel';

describe('GlobalHttpInterceptorService', () =&gt; {
  let apiURL=environment.apiURL;
  let httpController: HttpTestingController;
  let getPreferenceApi='http://somegetrequestapi/v1/get';
  let updatePreferenceApi='http://getpostrequest/v1/post';

  let service: GlobalHttpInterceptorService;
  let optoutService: OptoutService;
  let httpMock: HttpTestingController;

  beforeEach(() =&gt; {
    TestBed.configureTestingModule({
      imports:[RouterTestingModule, HttpClientTestingModule ],
      providers:[
        OptoutService,
        {provide:HTTP_INTERCEPTORS,useClass:GlobalHttpInterceptorService,multi:true},
        {provide:API_CONFIG_TOKEN,useValue:{useFcvApi:false}},
      ]
    });
    service = TestBed.inject(GlobalHttpInterceptorService);
    optoutService =TestBed.inject(OptoutService);
    httpMock=TestBed.get(HttpTestingController);
  });

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

  it('should add an XCSRF header',() =&gt; {
    const optoutMock:optout={
      &quot;output&quot;: {
            &quot;somevar1&quot;: &quot;somvalue&quot;,
            &quot;somevar2&quot;: false
          },{
            &quot;somevar1&quot;: &quot;somvalue2&quot;,
            &quot;somevar2&quot;: false
          }
    }

    optoutService.getResponse().subscribe(res=&gt;{
      expect(res).toBeTruthy();
    })

    optoutService.postResponse(optoutMock).subscribe(res=&gt;{
      expect(res).toBeTruthy();
    })

    const httpRequest=httpMock.expectOne(getTokenApi);
    expect(httpRequest.request.headers.has('X-CSRF-TOKEN')).toEqual(true);

  });
});
</code></pre>
",https://stackoverflow.com/questions/71925698/angular-unit-tesing-http-interceptor-that-appends-xcsrf-token-in-header,"['angular', 'jasmine', 'karma-jasmine', 'angular-http-interceptors', 'angular-unit-test']",336,False,1,1
Swift Code Coverage without SwiftUI View Code,"<p>We are dividing our code into feature frameworks which contain the SwiftUI code as well as the view models. We are unit testing all of the view models and want to generate an accurate code coverage metric yet the number is low due to all the existing SwiftUI code in the framework. Is there a way to exclude UI code from being counted towards the code coverage metric? We do not want to introduce any additional third party frameworks to accomplish this. Do I need to create a separate target that only contains the view models then run the tests there and get the code coverage?</p>
",https://stackoverflow.com/questions/71002009/swift-code-coverage-without-swiftui-view-code,"['swift', 'unit-testing', 'swiftui', 'code-coverage']",581,False,1,0
Sqlite with EFCore version 7.0.0 does not load database for in-memory connections. Fails with &#39;SQLite Error 1: &#39;&#39;.&#39; at EnsureDeleted(),"<p>For Unit Testing, I am using EFCore SQLite in-memory db and creating schema as per the MS docs, but when the code attempts to execute EnsureDeleted(). It fails at with exception 'SQLite Error 1: ''.'</p>
<p>Not much details are provided in the exception and it fails provided below stacktrace.</p>
<p>First part of stacktrace:
<a href=""https://i.stack.imgur.com/oosh6.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/oosh6.png"" alt=""enter image description here"" /></a></p>
<p>second part of stacktrace:
<a href=""https://i.stack.imgur.com/WdMxQ.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/WdMxQ.png"" alt=""enter image description here"" /></a></p>
<p>The code uses Dotnet with version .net6.0 and for EFcore and Sqlite below are the packages with versions</p>
<p><code>&lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.InMemory&quot; Version=&quot;7.0.0&quot; /&gt; &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.Sqlite&quot; Version=&quot;7.0.0&quot; /&gt; &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.Sqlite.Core&quot; Version=&quot;7.0.0&quot; /&gt; &lt;PackageReference Include=&quot;Microsoft.Extensions.DependencyInjection&quot; Version=&quot;7.0.0&quot; /&gt; &lt;PackageReference Include=&quot;Microsoft.EntityFrameworkCore.Sqlite.NetTopologySuite&quot; Version=&quot;7.0.0&quot; /&gt; </code></p>
<p>The code I use to make the connection is as below</p>
<pre><code>var dbConnection = new SqliteConnection(&quot;Filename=:memory:&quot;);
dbConnection.Open();
var dbOptions = new DbContextOptionsBuilder&lt;TestDBContext&gt;()
    .UseSqlite(dbConnection, opt =&gt; opt.UseNetTopologySuite())
    .Options;

TestDBContext db = new TestDBContext(dbOptions);
db.Database.EnsureDeleted(); // This is where it fails.
db.Database.EnsureCreated();

</code></pre>
<ol>
<li>I have tried changing the connection string from &quot;Filename=:memory:&quot; to different variations.</li>
<li>Tried adding or removing different packages.</li>
</ol>
<p>Nothing has helped so far.</p>
",https://stackoverflow.com/questions/74700903/sqlite-with-efcore-version-7-0-0-does-not-load-database-for-in-memory-connection,"['.net', 'sqlite', '.net-6.0', 'ef-core-7.0']",112,False,1,1
Why is the direction in port mappings from the design to the test-bench and not vice versa?,"<p>When testing with a testbench in VHDL we map the I/O from the design we are testing to the I/O of the test bench.</p>
<p>For me, it would make sense to give the input of our design some generated values from the testbench and then observe the output from the design and check if it matches what we expect. (Like in unit testing e.g.)</p>
<p>But when defining the architecture of the testbench:</p>
<pre><code>architecture behavior of tb is 
  
  signal tb_input : std_logic := '0'; 
  signal tb_output: std_logic := '0';

  -- Component decl. for the Unit under Test (UUT)
  component design_to_test is 
   port (
      input : in std_logic; 
      output: out std_logic);
  end component design_to_test; 

begin 
   -- Here we initiate the UUT
   UUT : design_to_test
      port map ( 
        input =&gt; tb_input
        -- this is what I don't understand. Why are we 
           giving the input of our design to the testbench? 
        output =&gt; tb_output
        -- this makes sense to me as we have to observe the 
           the output of our design. 
       ); 
       -- main testing 
end behavior; 
</code></pre>
<hr />
<p>So essentially the part I don't understand is how we use the input of the testbench. Why aren't we defining some input and then giving it to the design to evaluate?</p>
",https://stackoverflow.com/questions/71605599/why-is-the-direction-in-port-mappings-from-the-design-to-the-test-bench-and-not,"['testing', 'vhdl', 'test-bench']",100,True,1,1
Is declaring a friend which is forward-declared in an unnamed namespace an ODR-violation?,"<p>I've been using a dirty trick where I use unnamed namespaces to specify different behavior for each file (it is for unit-testing). It feels like it shouldn't be well-defined, but it works on every major compiler released in the past six years.</p>
<p>I first forward-declare a bunch of classes in an anonymouse namespace:</p>
<pre class=""lang-cpp prettyprint-override""><code>namespace {
class context_check;
class context_block;
class register_test;
} // namespace
</code></pre>
<p>Then I declare a class and make these classes <code>friend</code>s:</p>
<pre class=""lang-cpp prettyprint-override""><code>struct test_case
{
    // ...
};

class context {
// ...
private:
    // TODO: this feels like ODR-violation...
    friend class context_check;
    friend class context_block;
    friend class register_test;

private:
    void add_test(test_case&amp;&amp; test)
    {
        // ...
    }

    // ...
};
</code></pre>
<p>And in each cpp file I have following declarations (for tha sake of simplicity I copy and pasted them here, but in reality I declare the content of unnamed namespace in a header):</p>
<pre class=""lang-cpp prettyprint-override""><code>// A.cpp

namespace {
extern context file_context;

class register_test {
public:
    register_test(const char* test_name, test_case&amp;&amp; test)
    {
        file_context.add_test(std::move(test));
    }
};

} // namespace

register_test register_test_1( test_case{&quot;test1&quot;} );
</code></pre>
<pre class=""lang-cpp prettyprint-override""><code>// B.cpp

namespace {
extern context file_context;

class register_test {
public:
    register_test(const char* test_name, test_case&amp;&amp; test)
    {
        file_context.add_test(std::move(test));
    }
};

} // namespace

register_test register_test_2( test_case{&quot;test2&quot;} );
</code></pre>
<p>So each TU has its own definitions of <code>register_test</code>, <code>context_check</code> etc.
Is this well-defined? Feels like it should be an UB...</p>
",https://stackoverflow.com/questions/72718417/is-declaring-a-friend-which-is-forward-declared-in-an-unnamed-namespace-an-odr-v,"['c++', 'language-lawyer', 'undefined-behavior', 'unnamed-namespace']",132,True,6,1
Unit Test Mock Database Returning Null,"<p>I'm new to unit testing and mocking databases. One of my tests SHOULD work, but when the module I'm testing accesses the InMemoryDatabase it returns null instead of the user object.</p>
<p>I'm using Moq and xUnit.</p>
<p>My Test Setup:</p>
<pre><code>// Mock List of Db users
private List&lt;User&gt; GetFakeUsers()
{
    List&lt;User&gt; output = new List&lt;User&gt; {
        new User { Id = 1, Email = &quot;admin_test@mysite.com&quot;, Username = &quot;admin_test&quot;, PasswordHash = System.Text.Encoding.UTF8.GetBytes(&quot;fgftfhstafgsrstf54&quot;), Role = &quot;admin&quot; },
        new User { Id = 2, Email = &quot;user2@mysite.com&quot;, Username = &quot;user2&quot;, PasswordHash = System.Text.Encoding.UTF8.GetBytes(&quot;fgftfhstafgsrstf54&quot;), Role = &quot;premium&quot; },
        new User { Id = 3, Email = &quot;user3@mysite.com&quot;, Username = &quot;user3&quot;, PasswordHash = System.Text.Encoding.UTF8.GetBytes(&quot;fgftfhstafgsrstf54&quot;), Role = &quot;basic&quot; },
    };

    return output;
}


// Set up the InMemory Mock Database
private DataContext GetInMemoryMockDB()
{
    // Set Up Entity InMemory Database
    // I'm using the same DataContext as in the main program.
    var options = new DbContextOptionsBuilder&lt;DataContext&gt;()
        .UseInMemoryDatabase(databaseName: &quot;UserServiceMockDb&quot;)
        .Options;

    // Set Up Mock AppSettings.json file
    // Our DataContext.cs has two parameters in its constructor a dbContext and an IConfiguration it uses to read the appsettings.json file.
    var config = new ConfigurationBuilder()
        .SetBasePath(@&quot;...blahblahblah...&quot;)
        .AddJsonFile(&quot;mockAppSettings.json&quot;, optional: false, reloadOnChange: true)
        .AddEnvironmentVariables();

    _configuration = config.Build();

    var dbContext = new DataContext(options, _configuration);
    dbContext.Database.EnsureCreated();
    dbContext.Users.AddRange(GetFakeUsers());                        // Add our test users to the database

    return dbContext;
}
</code></pre>
<p>My Unit Test:</p>
<pre><code>
// Test - Check normal successful input. Get user3.
[Fact]
public async void GetUserByUsername_Works()
{
    using (var mock = AutoMock.GetLoose())
    {
        // Arrange
        // The module needs a few dependencies injected into its constructor...
        var mapperCfg = new MapperConfiguration(m =&gt; { m.AddProfile&lt;API_Project.AutoMapperProfile&gt;(); });
        IMapper mapper = mapperCfg.CreateMapper();
        var databaseContext = GetInMemoryMockDB();
        var loggerMock = new Mock&lt;ILogger&lt;UserService&gt;&gt;();
        var mockHttpContextAccessor = new Mock&lt;IHttpContextAccessor&gt;();
        
        // We have to supply an &quot;admin&quot; role claim
        mockHttpContextAccessor.Setup(x =&gt; x.HttpContext.User.FindFirst(It.IsAny&lt;string&gt;())).Returns(new Claim(&quot;role&quot;, &quot;admin&quot;));
        
        var suppliedUserList = GetFakeUsers();


        // Act
        var userService = new UserService(mapper, databaseContext, loggerMock.Object, mockHttpContextAccessor.Object);
        ServiceResponse&lt;GetUserDto&gt; returnedUser = await userService.GetUserByUsername(&quot;user3&quot;);                        // Lookup username &quot;user3&quot;        



        //Assert
        // Compare supplied user3 to the returned user.
        Assert.Equal(suppliedUserList[2].Email, returnedUser.Data.Email);
        Assert.Equal(suppliedUserList[2].Username, returnedUser.Data.Username);
        Assert.Equal(suppliedUserList[2].Role, returnedUser.Data.Role);

    }
}
</code></pre>
<p>And Finally, the unit I'm trying to test:</p>
<pre><code>public async Task&lt;ServiceResponse&lt;GetUserDto&gt;&gt; GetUserByUsername(string username)
{
    var serviceResponse = new ServiceResponse&lt;GetUserDto&gt;();

    // Get user by USERNAME from the database
    // Check if the user role is &quot;admin&quot; ? [true] Lookup the specified user Id : [false] return only their user info
    // This is returning NULL for the username search?
    var dbUser =
        GetUserRole().Equals(&quot;admin&quot;) ?
        await _context.Users.FirstOrDefaultAsync(c =&gt; c.Username.Contains(username)) :
        await _context.Users.Where(u =&gt; u.Id == GetUserId()).FirstOrDefaultAsync();

    // FirstOrDefault() returns null if nothing is found.
    if (dbUser != null)
    {
        serviceResponse.Data = _mapper.Map&lt;GetUserDto&gt;(dbUser);
    }
    else
    {
        // Send a message to tell user of the error
        serviceResponse.Success = false;
        serviceResponse.Message = &quot;Sorry, we couldn't find that user.&quot;;
        _logger.LogInformation(&quot;Error - Search for an unknown user. UserService.GetUserByUsername - USERNAME: {1}&quot;, username);
    }

    return serviceResponse;
}
</code></pre>
<p>The issue is &quot;var dbUser&quot; in the above module I'm testing is returning null. It works in my production database but not with the InMemoryDatabase. I'm guessing it can't handle the linq query or something?</p>
<p>This is my first time using InMemoryDatabases, so I don't really know their limits.
I hope it's not due to a spelling mistake or something...</p>
",https://stackoverflow.com/questions/72666203/unit-test-mock-database-returning-null,"['c#', 'unit-testing', 'moq', 'xunit', 'c#-5.0']",916,True,1,1
Error: Failed to parse source for import analysis because the content contains invalid JS syntax,"<p>When I using vite + vue to do the unit testing for web components, I met this error:</p>
<blockquote>
<p>Error: Failed to parse source for import analysis because the content contains invalid JS syntax. You may need to install appropriate plugins to handle the .html file format.
❯ formatError node_modules/vite/dist/node/chunks/dep-59dc6e00.js:38663:46
❯ TransformContext.error node_modules/vite/dist/node/chunks/dep-59dc6e00.js:38659:19
❯ TransformContext.transform node_modules/vite/dist/node/chunks/dep-59dc6e00.js:56777:22
❯ async Object.transform node_modules/vite/dist/node/chunks/dep-59dc6e00.js:38900:30
❯ async doTransform node_modules/vite/dist/node/chunks/dep-59dc6e00.js:55857:29</p>
</blockquote>
<p>How can I solve this problem?</p>
",https://stackoverflow.com/questions/72474681/error-failed-to-parse-source-for-import-analysis-because-the-content-contains-i,"['javascript', 'vue.js', 'unit-testing', 'vite']",3870,True,1,1
Using Specflow without the unit testing frameworks,"<p>So for my current project I need to perform several tests on a (physical) system.
Within my company we have this testing framework, which provides several features out of the box, such as writing my results to a database and such.</p>
<p>Now I've heard about BDD and I found that a gherkin way of writing these tests would be really nice and clean.
So I started looking into Specflow, which looks really good.
Only problem with Specflow is that you are required to use a Unit Testing framework. This is not at all what I want, since my own framework already provides all this stuff. Starting a test for example needs to be done by an operator from a GUI. So the unit testing framework is not needed at all.</p>
<p>Now my question is whether I can use Specflow simply to generate these tests (within their own test class or something) and keep using my own framework.</p>
<p>So as an example, what I'm looking for is something along these lines:</p>
<pre><code>Given that the machine is in base state
When we open the valve
Then the valve sensor should have value higher than 450
</code></pre>
<p>Then have a StepDefinition file, which will contain the actual machine interface (sample code ofc)</p>
<pre><code>public void MachineInBaseState()
{
    machine.GoToBaseState();
}
public void ValvePosition(bool open)
{
    machine.SetValve(open);
}
public void CheckValveSensorPosition(int valueToCheckAgainst)
{
    testResults.Add(new ValueResult(value:machine.GetSensorValue(),min:valueToCheckAgainst,max:double.NaN));
}
</code></pre>
<p>Then during build of the project, to have the gherkin file be generated in such a way that my own testing framework can pick up the generated testresults.</p>
<p>I know that this may not be something that a lot of people do, but maybe someone has seen something like it before.</p>
<p>Another way of course is to write a source generator, but that will take a lot more time.</p>
",https://stackoverflow.com/questions/73165522/using-specflow-without-the-unit-testing-frameworks,"['c#', '.net-6.0', 'specflow', 'gherkin']",126,True,2,2
Unit testing DynamoDB SDK in Go?,"<p>I'm using the AWS SDK in Go, but I'm having trouble unit testing my DynamoDB updates. Basically, I'm using <code>gomock</code> to set the expected <code>UpdateItemInput</code> like so:</p>
<pre><code>return m.EXPECT().UpdateItemWithContext(
            gomock.Any(),
            &amp;dynamodb.UpdateItemInput {
                ConditionExpression: aws.String(&quot;(#0 = :0) AND (#1 = :1)&quot;),
                ExpressionAttributeNames: map[string]*string{
                    &quot;#0&quot;: aws.String(&quot;PK&quot;),
                    &quot;#1&quot;: aws.String(&quot;SK&quot;),
                    &quot;#2&quot;: aws.String(&quot;SomeAttrName&quot;),
                },
                ExpressionAttributeValues: map[string]*dynamodb.AttributeValue {
                    &quot;:0&quot;: {S: aws.String(primaryKey)},
                    &quot;:1&quot;: {S: aws.String(secondaryKey)},
                    &quot;:2&quot;: {S: aws.String(ValueToUpdate)},
                },
                Key: map[string]*dynamodb.AttributeValue{
                    &quot;PK&quot;: {S: aws.String(primaryKey)},
                    &quot;SK&quot;: {S: aws.String(secondaryKey)},
                },
                ReturnValues:     aws.String(dynamodb.ReturnValueAllNew),
                TableName:        aws.String(dynamo.TableName),
                UpdateExpression: aws.String(&quot;SET #2 = :2\n&quot;),
            }

</code></pre>
<p>However, when I run the test, it fails because it seems there is a mismatch between what gomock expected and what it got. The positions of the values in the <code>UpdateItemInput</code> from the business logic are different every time I run the test, which I think is what's messing this up.</p>
<p>Is there a better way to test things like this in Go? Or if not, is there a way to enforce the same order every time, or ignore the order?</p>
",https://stackoverflow.com/questions/71384143/unit-testing-dynamodb-sdk-in-go,"['amazon-web-services', 'go', 'testing']",700,False,1,1
nalgebra type annotations for converting Matrix to DMatrix,"<p>I'm trying to convert a static matrix into a dynamic matrix using a function. Reason being is that I'm comparing two matrices for unit-testing. Thus the <code>test_value</code> from the test, and the <code>benchmark</code> matrices have to be the same element wise. They will only compare though if they're the same type and sometimes the <code>test_value</code> is a static matrix. I'd like a function that takes in a static matrix type and converts it into a dynamic matrix. So far using the vscode refactor tool I've managed this:</p>
<pre><code>    fn matrix_to_dynamic_matrix(matrix: Matrix&lt;f64, Const, Const, ArrayStorage&lt;f64&gt;&gt;) -&gt; Matrix&lt;f64, Dynamic, Dynamic, VecStorage&lt;f64, Dynamic, Dynamic&gt;&gt; {
        let matrix_vector:Vec&lt;f64&gt; = matrix.iter().map(|x| x.to_owned()).collect();
        let (rows, columns) = matrix.shape();
        let matrix_dynamic:DMatrix&lt;f64&gt; = DMatrix::from_vec(rows, columns, matrix_vector);
        matrix_dynamic
    }
</code></pre>
<p>The compiler won't get past the <code>Matrix&lt;f64, Const, Const, ArrayStorage&lt;f64&gt;&gt;</code>. What the right way to take in the statically sized matrix into the function?</p>
",https://stackoverflow.com/questions/74311320/nalgebra-type-annotations-for-converting-matrix-to-dmatrix,"['rust', 'nalgebra']",178,True,1,1
Issue with setting up jest mock,"<p>I have the following function that is used within cypress tests for which I want to do unit testing (filterTests.js):</p>
<pre><code>const filterTests = (definedTags, runTest) =&gt; {
  console.log(`Cypress tags: ${definedTags}`);
  let isFound = true;
  
  const includeTag = Cypress.env('INCLUDETAG');
  const excludeTag = Cypress.env('EXCLUDETAG');
  
  if (includeTag) {
    isFound = definedTags.includes(includeTag);
  }

  if (excludeTag) {
    isFound = ! definedTags.includes(excludeTag);
  }

  if (isFound) {
    runTest();
  }
};

export default filterTests;
</code></pre>
<p>A test double for Cypress.env needs to be created. I'm not sure if this would technically be considered a stub, mock, fake, dummy, etc..., but the philosophical discussion isn't the focus right now. It looks like in the Cypress world, everything is lumped together under 'mock'.</p>
<p>I started down the path of something like this in the Jest test file:</p>
<pre><code>import filterTests from '../../cypress/support/filterTests';

describe('Something', () =&gt; {
  jest.mock('Cypress', () =&gt; ({
      env: {
        INCLUDETAG: 'jenkins1'
      }
  }));


  it('Something else ', (done) =&gt; {
    const tempFunc = () =&gt; {
      console.log('here a');
      done();
    };

    filterTests(tag, tempFunc);
  });
});
</code></pre>
<p>But for that I get the error message:</p>
<pre><code>    Cannot find module 'Cypress' from 'spec/cypress/filterTestsSO2.test.js'

      2 |
      3 | describe('Something', () =&gt; {
    &gt; 4 |   jest.mock('Cypress', () =&gt; ({
        |        ^
      5 |       env: {
      6 |         INCLUDETAG: 'jenkins1'
      7 |       }
</code></pre>
<p>I believe what is complicating this situation is that Cypress is not explicitly imported in filterTests.js</p>
",https://stackoverflow.com/questions/71309496/issue-with-setting-up-jest-mock,"['javascript', 'unit-testing', 'testing', 'jestjs', 'cypress']",86,True,1,1
Python Unit testing script that calls some functions,"<p>I ended up with testing an &quot;automation&quot; script in python, basically just a script calling bunch of functions.</p>
<p>I have 3 classes: class_A, class_B, class_C, with each class having a &quot;run&quot; function</p>
<p>Script.py is calling class_A.run(), class_B.run, class_C.run()</p>
<p>My question would be if is there is a way of unit testing Script.py to just assert if the 3 run functions we're called, without actually running (going trough their code) them.</p>
<p>I tried patching the class and i can get the correct assert, but the run functions are still &quot;running&quot; their code.</p>
<p>Is it possible to somehow Mock the class_A.run() and assert if was called?</p>
",https://stackoverflow.com/questions/70609954/python-unit-testing-script-that-calls-some-functions,"['python', 'unit-testing', 'mocking']",51,True,1,1
Github actions ./gradlew test can&#39;t find directory to run unit test,"<p>I set up a simple CI work in Github Action for my Android project (Kotlin) that would init unit testing before merging with the master (main) branch</p>
<pre><code>on: 
  push: 
    branches: [ master ] 
  pull_request: 
    branches: [ master ]

jobs: 
  # This workflow contains a single job called &quot;build&quot; 
  build: 
    # The type of runner that the job will run on 
    runs-on: ubuntu-latest

    # Steps represent a sequence of tasks that will be executed as part of the job 
    steps:
      - uses: actions/checkout@v3
      # Setup JAVA
      - name: set up JDK 1.8
        uses: actions/setup-java@v1
        with:
          java-version: 1.8

      # Execute unit tests
      - name: Unit Test
        run: chmod +x ./gradlew  test
</code></pre>
<p>But whenever i push any commit into directory, i receive next error which fails Unit tests and block merging:</p>
<pre><code>Run chmod +x ./gradlew  test
  chmod +x ./gradlew  test
  shell: /usr/bin/bash -e {0}
  env:
    JAVA_HOME_8.0.342_x64: /opt/hostedtoolcache/jdk/8.0.342/x64
    JAVA_HOME: /opt/hostedtoolcache/jdk/8.0.342/x64
    JAVA_HOME_8_0_342_X64: /opt/hostedtoolcache/jdk/8.0.342/x64
chmod: cannot access 'test': No such file or directory
Error: Process completed with exit code 1.
</code></pre>
<p>I tried to manually set up a directory with tests using <code>working-directory: app/src/</code> but it throws the same type of error.
What I am doing wrong?</p>
<p>Will provide more info on request. Thanks in advance.</p>
<p>ANSWER: To run unit test in pre-merge, you need to set the correct directory, with the   <code>working-directory:</code>, In my case it's :</p>
<blockquote>
<p>./app/src/</p>
</blockquote>
<p>Changes in workflow .yaml</p>
<pre><code># List all files (Optional)
  - name: ls
    run: ls -alrth
  - name: add permisiion to gradlew
    run: chmod +x ./gradlew 
    # Execute unit tests
  - name: run unit tests
    working-directory: ./app/src/
    run: chmod +x ./test
</code></pre>
",https://stackoverflow.com/questions/73184176/github-actions-gradlew-test-cant-find-directory-to-run-unit-test,"['android', 'github-actions', 'workflow']",136,True,1,1
Getting error on await act() JEST. Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.Timeout,"<p>I am new to unit testing and jest, and was stuck at a scenario where the react's state are being set asynchronously after API call is resolved or rejected. I found some answers in which they've mentioned to use <code>waitFor</code> or <code>await act(async()=&gt;{})</code>. Whenever I'm trying to await with act or even async act, I'm getting this error and the tests are failing. I've tried to replicate a similar scenario below.
If these ways of handling async updates to component are not correct, then what could be the other solutions. I'm using react hooks to set the state after api resolves or rejects.</p>
<p><strong>React and react-dom version : 16.8</strong></p>
<pre><code>test('new ', async () =&gt; {
  await act(() =&gt; {
    console.log('test');
  });
  expect('temp').toBe('temp');
});
</code></pre>
",https://stackoverflow.com/questions/71284012/getting-error-on-await-act-jest-async-callback-was-not-invoked-within-the-500,"['javascript', 'reactjs', 'jestjs', 'enzyme', 'react-testing-library']",654,False,0,0
How to initialize WidgetInfo for unit testing in Xcode?,"<p>I am trying to initialize the <code>WidgetKit</code> struct <code>WidgetInfo</code> for unit testing a function that takes <code>WidgetInfo</code> as an argument:</p>
<pre><code>let widgetInfo = WidgetInfo()
</code></pre>
<p>This gives me the error:
<em>'WidgetInfo' cannot be constructed because it has no accessible initializers</em></p>
<p>I tried adding:</p>
<pre><code>extension WidgetInfo {
    public init() {}
}
</code></pre>
<p>and I can initialize - yay! But then I try to set one of its properties</p>
<pre><code>widgetInfo.family = .systemSmall
</code></pre>
<p>and get the error: <em>Cannot assign to property: 'family' is a 'let' constant</em></p>
<p>I tried another initializer with arguments:</p>
<pre><code>extension WidgetInfo {
    public init(family: WidgetFamily, kind: String) {
        self.family = family
        self.kind = kind
    }
}
</code></pre>
<p>and I get the error: <em>'let' property 'family' may not be initialized directly; use &quot;self.init(...)&quot; or &quot;self = ...&quot; instead</em></p>
<p>I'm stuck - is there a way for me to initialize <code>WidgetInfo</code>? Or another way to test a function that takes <code>WidgetInfo</code> as an argument?</p>
",https://stackoverflow.com/questions/72481788/how-to-initialize-widgetinfo-for-unit-testing-in-xcode,"['ios', 'swift', 'xcode', 'xctest', 'widgetkit']",90,True,0,1
How to force a return value from a mocked non-exported function using sinon or proxyquire or rewire?,"<p>I am just getting started unit testing nodejs. I have been using mocha, chai and sinon.</p>
<p>I hit a snag when I wanted to test a function which is not exported. <a href=""https://www.npmjs.com/package/proxyquire"" rel=""nofollow noreferrer"">proxyquire</a> looks good, as does <a href=""https://www.npmjs.com/package/rewire"" rel=""nofollow noreferrer"">rewire</a>.</p>
<p>There are lots of tutorials, but they tend to be simplistic. E.g</p>
<pre><code>// Software under test
function saySecret() {      // this function is *not* exported
  return '🤫';
}

// Unit test file
import utilsRewire from './utils.js';

describe('saySecret', () =&gt; {
  it('returns shh emoji', () =&gt; {
    const saySecret = utilsRewire.__get__('saySecret'); // 👈 the secret sauce

    expect(saySecret()).toBe('🤫');
  });
});
</code></pre>
<p>While that is nice, I want to be able to force the function <code>saySecret</code> to return a specific value. The reason being that the function is called by a function which <em><strong>is</strong></em> exported, and I want to unit test the outer function, forcing it down failure paths.</p>
<p>How can I do that with sinon/proxyquire/rewire?</p>
",https://stackoverflow.com/questions/71285081/how-to-force-a-return-value-from-a-mocked-non-exported-function-using-sinon-or-p,"['node.js', 'unit-testing', 'sinon', 'proxyquire', 'rewire']",709,True,0,1
Angular Excluding external javascript library from unit testing,"<p>I am unit testing my component which uses a external javascript library, I am importing and initializing the libary in my component.ts All my test cases work fine if I comment the line <strong>aksService = aksServiceFactory(); (code below)</strong> but it gives a error <strong>TypeError: Cannot read properties of undefined (reading 'AKS')</strong> if i uncomment it. I tried importing the library in spec.ts file also but it gives same error.</p>
<p>I want to include this library in my component.spec.ts file so it doesnt give me this error or if there is a way can we exclude this file from unit test so it doesnt give this error.</p>
<p>component.ts file</p>
<pre><code>import { aksServiceFactory } from '../../services/gdl.service';
import { GlobalConstants } from '../../global-constants';


@Component({
  selector: 'app-page',
  templateUrl: './opt-page.component.html',
  styleUrls: ['./opt-page.component.scss']

})

export class OptPageComponent implements OnInit {

  //initialize aks Service

  aksService = aksServiceFactory();
</code></pre>
<p>aks.service.ts</p>
<pre><code>// aks.service.js

export const aksServiceFactory = () =&gt; {
    const aksQueue = window.cms.aks;
    const sendPageview = (pageId) =&gt; {
      aksQueue.push(['event:publish', ['page', 'pageinfo']]);
    };

    const sendEvent = (category, name, payload) =&gt; {
      aksQueue.push(['event:publish', [category, name, payload]]);
    };

    const enableDebugMode=()=&gt;{
      aksQueue.debug.enable();
    }

    return {
      enableDebugMode,
      sendPageview,
      sendEvent,
    };
  };
</code></pre>
",https://stackoverflow.com/questions/71985987/angular-excluding-external-javascript-library-from-unit-testing,"['angular', 'jasmine', 'karma-jasmine', 'karma-runner', 'angular-unit-test']",301,False,0,1
Mocking EF in Xunit,"<p>I am new to unit testing and mocking but I am trying to add tests for existing CRUD functions. I know that I need to use MOQ library but I am not sure if I can do it with the function below. All CRUD functions have <code>using</code> statement inside them.</p>
<p>I am using .NET 5.0 and EF6</p>
<p>Example of the existing function:</p>
<pre><code>public static async Task CreateRoleAsync(string roleName)
        {
            using(DbEntities db = new DbEntities())
            {
                Log newLog = CreateLog();
                Role newRole = new Role()
                {
                    Name = roleName,
                    Log = newLog
                };

                db.Roles.Add(newRole);
                await db.SaveChangesAsync();
            }
        }
</code></pre>
<p>Is it possible to maintain current structure of functions and implement mocking? Or should these functions be refactored to use dependency injections?</p>
<p>I would appreciate if you could point me in the right direction. Let me know if additional information is needed.</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/71758519/mocking-ef-in-xunit,"['c#', 'unit-testing', 'mocking', 'entity-framework-6', 'xunit']",943,True,0,3
Testing array length with Mockito,"<p>I'm trying to implement unit test for a Spring boot project.</p>
<p>I'm new with unit testing in Java and I learned that I can test my project in the service layer. So I have this:</p>
<pre><code>    @Mock
    private ICampusRepository campusRepository;

    @InjectMocks
    private CampusServiceImplementation campusService;

    private List&lt;Campus&gt; campusList = new ArrayList&lt;&gt;();

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);
        campusList.add(new Campus(1, &quot;Campus Name 1&quot;, &quot;ACTIVE&quot;));
        campusList.add(new Campus(2, &quot;Campus Name 2&quot;, &quot;ACTIVE&quot;));
        campusList.add(new Campus(3, &quot;Campus Name 3&quot;, &quot;INACTIVE&quot;));
    }
</code></pre>
<p>Then, for testing I have some very basic test:</p>
<pre><code>    @Test
    void getAllCampus() {
        when(campusRepository.findAll()).thenReturn(campusList);
        assertNotNull(campusService.getAllCampus());
    }
</code></pre>
<p>I want to make a test to verify if certain method returns a list of campus with &quot;ACTIVE&quot; attribute only, I'm trying to do this:</p>
<pre><code>    @Test
    void listAllActiveCampus() {
        when(campusRepository.findAllActiveCampus()).thenReturn(campusList);
        assertEquals(2, campusService.listAllActiveCampus().size());
    }
</code></pre>
<p>But the test result is:</p>
<pre><code>org.opentest4j.AssertionFailedError: 
Expected :2
Actual   :0
</code></pre>
<p>The question is: Should I create a new array with 2 values only? Is there a better way to create better conclusive test?</p>
<p><strong>EDIT</strong></p>
<p>campusService code:</p>
<pre><code>    @Override
    public List&lt;Campus&gt; getAllCampus() {
        return campusRepository.findAll();
    }

...

    @Override
    public List&lt;Campus&gt; listAllActiveCampus() {
        return campusRepository.findAllActiveCampus();
    }
</code></pre>
<p>The repository:</p>
<pre><code>public interface ICampusRepository extends JpaRepository&lt;Campus, Integer&gt; {

    @Query(value = &quot;SELECT * FROM catSede WHERE sedeEstatusId = 3&quot;, nativeQuery = true)
    List&lt;Campus&gt; findAllActiveCampus();
}
</code></pre>
<p><strong>EDIT 2</strong></p>
<p>Full test Class:</p>
<pre><code>@SpringBootTest
class CampusServiceImplementationTest {

    @Mock
    private ICampusRepository campusRepository;

    @InjectMocks
    private CampusServiceImplementation campusService;

    @BeforeEach
    void setUp() {
        MockitoAnnotations.openMocks(this);

    }

    @Test
    void getAllCampus() {
        List&lt;Campus&gt; campusList = new ArrayList&lt;&gt;();
        campusList.add(new Campus(1, &quot;Campus Name 1&quot;, &quot;ACTIVE&quot;));
        campusList.add(new Campus(2, &quot;Campus Name 2&quot;, &quot;ACTIVE&quot;));
        campusList.add(new Campus(3, &quot;Campus Name 3&quot;, &quot;INACTIVE&quot;));
        when(campusRepository.findAll()).thenReturn(campusList);

        List&lt;Campus&gt; result = campusRepository.findAll();
        assertNotNull(result);
        assertEquals(3, result.size());
        verify(campusRepository, times(1)).findAll();
    }

    @Test
    void listAllActiveCampus() {
        List&lt;Campus&gt; campusList = new ArrayList&lt;&gt;();
        campusList.add(new Campus(1, &quot;Campus Name 1&quot;, &quot;ACTIVE&quot;));
        campusList.add(new Campus(2, &quot;Campus Name 2&quot;, &quot;ACTIVE&quot;));
        campusList.add(new Campus(3, &quot;Campus Name 3&quot;, &quot;INACTIVE&quot;));

        when(campusRepository.findAllActiveCampus()).thenReturn(campusList);

        List&lt;Campus&gt; result = campusRepository.findAllActiveCampus();
        assertNotNull(result);
        assertEquals(2, result.size());
        verify(campusRepository, times(1)).findAllActiveCampus();
    }
}
</code></pre>
<p>Service class:</p>
<pre><code>@Service
@RequiredArgsConstructor
public class CampusServiceImplementation implements ICampusService {

    private final ICampusRepository campusRepository;

    @Override
    public List&lt;Campus&gt; getAllCampus() {
        return campusRepository.findAll();
    }


    @Override
    public List&lt;Campus&gt; listAllActiveCampus() {
        return campusRepository.findAllActiveCampus();
    }
}
</code></pre>
<p>Repository:</p>
<pre><code>public interface ICampusRepository extends JpaRepository&lt;Campus, Integer&gt; {
    @Query(value = &quot;SELECT * FROM catSede WHERE sedeEstatusId = 3&quot;, nativeQuery = true)
    List&lt;Campus&gt; findAllActiveCampus();
}
</code></pre>
",https://stackoverflow.com/questions/72859337/testing-array-length-with-mockito,"['java', 'spring-boot', 'unit-testing', 'junit', 'mockito']",675,False,0,1
"Flutter, test failing when running together but passing when running indivudally","<p>I've been working on flutter unit testing on my API but I encountered a problem.</p>
<p>I've mocked an HTTP client to test all the POST, GET, DELETE, and PATCH requests. The problem is that when I run all my tests <strong>together</strong>, some tests on POST and PATCH requests fail (often after a test on a POST or PATCH request that passes) but when I run them <strong>individually</strong>, they pass.</p>
<p>The error I face is: <code>Bad state: Cannot call when within a stub response</code></p>
<p>If anyone has encountered a similar problem and found a solution I would gladly take it :)</p>
<p>Thanks in advance for your time on my problem, I wish you all a good day!</p>
",https://stackoverflow.com/questions/72317242/flutter-test-failing-when-running-together-but-passing-when-running-indivudally,"['flutter', 'unit-testing', 'dart', 'dart-null-safety']",221,False,0,0
How to Unit Test SwiftUI Views without ViewInspector?,"<p>How do we test SwiftUI views?  Can we test them in Unit testing?</p>
<p>If so we don't have proper apis to get the view hierarchy or the required set of objects for testing. We have to rely on using identifier for every object and extract the view with the id?
I have seen many using ViewInspector which extracts the view hierarchy and has apis to test the array of views matching a text etc. But is it using a right approach for extracting views will it have issues when ever the Xcode or Os is upgraded?</p>
<p>Is snapshot testing right approach for swiftUI views?****</p>
",https://stackoverflow.com/questions/73694372/how-to-unit-test-swiftui-views-without-viewinspector,"['ios', 'unit-testing', 'swiftui', 'xctest']",321,False,0,1
How do I unmock jquery globally in Jest after automocking?,"<p>I've used jest automock as I'm facing nested namespace issues for my unit testing of a jQuery application.</p>
<pre><code>module.exports = {
                automock: true;
                 }
</code></pre>
<p>I'm mostly there, used code from Jon G</p>
<pre><code>
const jQ = jest.requireActual(&quot;jquery&quot;);

const get = jest.fn((path) =&gt; {
    return Promise.resolve(path);
});

const when = jest.fn((prom1, prom2, prom3, prom4) =&gt; {
    return Promise.resolve();
});

const jQuery = jQ;
jQuery.get = get;
jQuery.when = when;
exports.jQuery = jQuery;
</code></pre>
<p>I need the .find functionality unmocked</p>
<p>Ideally i want to use the jest.spyOn() feature to mock internal anonymous function calls which otherwise return as undefined, so I've ended up using babel-plugin-rewire to allow me to import the functions unaccessible to spyOn()</p>
<p>The function looks like</p>
<pre><code>var XYZ = XYZ || {};
XYZ.Utils = (function () {
var functionName = function (blahblahblah) {
var x = XYZ.OtherNameSpace.usefulFunction(blahblahblah)
return x
}
</code></pre>
<p>And is called by</p>
<pre><code>XYZ.Utils.functionName(blahblahblah)
</code></pre>
<p>I want to mock var x = XYZ.OtherNameSpace.usefulFunction(blahblahblah)
because jest can't see it and returns undefined.
Thus automocking, please help, I didn't write it this poorly coupled.</p>
",https://stackoverflow.com/questions/74866720/how-do-i-unmock-jquery-globally-in-jest-after-automocking,"['jquery', 'web', 'jestjs', 'mocking', 'automocking']",43,False,0,0
Mocha executes irrelevant file before test file,"<p>In my express app, I'm trying unit testing using Mocha for an independent util class. When kicking off the mocha tests, something strange happened.</p>
<p>Mocha somehow launches the express app before tests.</p>
<p>Since the file that initiates the app is not referenced from any test suite, I think it's weird that Mocha reaches out to it.</p>
<p>Here's my folder structure:</p>
<pre><code>/dist
/index.ts &lt;-- server launching script
/util
  / util.ts &lt;-- independent util class
  / util.test.ts &lt;-- tests for util.ts
/package.json
</code></pre>
<p>In package.json I define something like:</p>
<pre><code>&quot;test:unit&quot;: &quot;mocha --require source-map-support/register 'dist/**/*.test.js'&quot;
</code></pre>
<p>And when I run it, the log output is something like:</p>
<pre><code>&gt; my-project@1.0.0 test:unit
&gt; mocha --require source-map-support/register 'dist/**/*.test.js'

info: server started

  Util class
    ✔ Test case 1 (64ms)
    ✔ Test case 2 (62ms)
    ✔ Test case 3 (122ms)

  3 passing (258ms)

info: server listening on port 3333

(And Mocha never exits!!!!)
</code></pre>
<p>Currently, the <code>--exit</code> flag makes it possible to forcefully quit the tests after finishing. But it's still a mystery why Mocha behaves like this. Does anyone know the reason? Any answers would be appreciated.</p>
",https://stackoverflow.com/questions/73604685/mocha-executes-irrelevant-file-before-test-file,"['node.js', 'unit-testing', 'mocha.js']",11,False,0,0
Bypassing Qt signaling to avoid class-to-class signaling,"<p>I'm trying to figure out how I could work with Qt signals in a little bit different way.
I have a working example of such:</p>
<pre><code>Game::Game(QObject *parent)
    : QObject{parent}
    , m_timer{nullptr}
{
  m_timer = new QTimer(this);
  connect(m_timer, &amp;QTimer::timeout, this, &amp;Game::run);
  m_timer-&gt;setinterval(300);
  m_timer-&gt;start();
}
</code></pre>
<p>Above signaling works fine and calls the Game::run regularly as desired. Now I am trying to replicate this with this bypass (for the sake of learning and it could be useful for more complicated moments especially in unit testing)</p>
<p>Abstract class:</p>
<pre><code>class ISignalHandler
{
public:
    virtual void onTimeout() = 0;
protected:
    virtual ~ISignalHandler() = default;
};
</code></pre>
<p>and another class MyTimer.cpp:</p>
<pre><code>MyTimer::MyTimer(QTimer *parent)
    : QTimer{parent}
{
    m_timer = new QTimer(this);
    connect(m_timer, &amp;QTimer::timeout, this, &amp;MyTimer::onTimeout);
}

MyTimer::~MyTimer()
{
    delete m_timer;
    m_timer = nullptr;
}

void MyTimer::registerTimerSignal(ISignalHandler* callback)
{
    m_callback = callback;
}

void MyTimer::onTimeout()
{
    if (m_callback != nullptr)
    {
        m_callback-&gt;onTimeout();
    }
}
</code></pre>
<p>and finally Game class:</p>
<pre><code>//header:
class Game : public QObject, public ISignalHandler
{
    Q_OBJECT
public:
    explicit Game(QObject *parent = nullptr);
    ~Game();
//cpp:
        Game::Game(QObject *parent)
            : QObject{parent}
            , m_timer{nullptr}
        {
          m_timer = new MyTimer();
          m_timer-&gt;registerTimerSignal(this);
          m_timer-&gt;setinterval(300);
          m_timer-&gt;start();
        }

    void Game::onTimeout()
    {
        run();
    }
</code></pre>
<p>I expected that the MyTimer class will repeat within itself, and the signal will be handled to Game class so ::run will be continuously called. Where is a mistake here?</p>
",https://stackoverflow.com/questions/72482143/bypassing-qt-signaling-to-avoid-class-to-class-signaling,"['c++', 'qt', 'signals']",49,False,0,0
"mounted method giving error message - Nuxt.js, Jest","<p>I am new to unit testing and have a question about the mounted method inside the component.</p>
<p>I am testing if the button text is correctly displaying depends on one of the data values, and it passes. However, I have one method in mounted() inside the component and requests API call which is called from nuxt context.</p>
<p>The method is failing and consoling err message from try and catch because looks like it can not find nuxt context inside the test. This is not affecting my test but I wonder if it is fine, or do I need to fix something.</p>
<p>This is my component.</p>
<pre class=""lang-html prettyprint-override""><code>    &lt;template&gt;
        &lt;button&gt;
            {{variations.length &gt; 0 ? 'Select options' : 'add to cart'}}
        &lt;/button&gt;
    &lt;/template&gt;

    &lt;script&gt;
        data() {
            return {
                variations: [],
            }
        },
        mounted() {
            this.getVaridations()
        },
        methods: {
            async getVaridations() {         
                try {
                    const variations = await this.$getVatiation.get() // this part is failing and consoling err message from catch
                    this.variations = variations
                } catch (err) {
                    console.log(err) // consoling as TypeError: Cannot read properties of undefined (reading 'get')
                }        
            },
        },
    &lt;/script&gt;
</code></pre>
<p>This is testing</p>
<pre class=""lang-js prettyprint-override""><code>    describe('Product.vue', () =&gt; {
        it('btn display as &quot;Select options&quot; when there is validation', () =&gt; {
            const wrapper = mount(Product, {})
            expect(wrapper.find('.product-btn').text()).toBe('Select options') // This passes
        })
    })

</code></pre>
",https://stackoverflow.com/questions/70671701/mounted-method-giving-error-message-nuxt-js-jest,"['jestjs', 'nuxt.js']",287,True,0,1
Need help transforming GraphQL results,"<p>A returned data object looks like the following:</p>
<pre><code>{
  data: {
    posts: {
      edges: [
        {
          post: {
            id: &quot;1&quot;,
            title: &quot;Foo&quot;
          }
        },
        {
          post: {
            id: &quot;2&quot;,
            title: &quot;Bar&quot;
          }
        }
      ]
    }
  }
}
</code></pre>
<p>This is based on the following query:</p>
<pre><code>    query MyQuery {
      posts {
        edges {
          post: node {
            id
            title
          }
        }
      }
    }
</code></pre>
<p>This works and I can use it, but I’m having to create nested interfaces, unfortunately.</p>
<p>Question: <strong>Can I either simplify the returned results OR transform them with JavaScript <code>map()</code>?</strong></p>
<p>Ideally, I’d like for the GQL response (or resulting object) to be like:</p>
<pre><code>{
  data: {
    posts: [
      {
        id: &quot;1&quot;,
        title: &quot;Foo&quot;
      },
      {
        id: &quot;2&quot;,
        title: &quot;Bar&quot;
      }
    ]
  }
}
</code></pre>
<p><strong>Note:</strong> I do not have the ability to update the server-side GraphQL schema. The solution must be client/consumer side.</p>
<p>Thanks!</p>
<h2>EDIT</h2>
<p>Adding my Angular/TS code that calls and processes the GraphQL...</p>
<h3>post.service.ts</h3>
<pre class=""lang-js prettyprint-override""><code>import { Injectable } from '@angular/core';
import { Apollo, gql } from 'apollo-angular';
import { map, Observable } from 'rxjs';
import { GraphQLResponse } from 'src/app/core/types/graphQLResponse';
import { Post } from '../models/post';

export interface PostResponse {
  edges: Post[]
  pageInfo: {
    startCursor: string
    hasPreviousPage: boolean
    hasNextPage: boolean
    endCursor: string
  }
}

export const getPostsQuery = gql`
  query getPostsQuery {
    posts {
      edges {
        post: node {
          id
          title
          date
          uri
          categories {
            edges {
              category: node {
                id
                name
                uri
              }
            }
          }
        }
        cursor
      }
      pageInfo {
        startCursor
        hasPreviousPage
        hasNextPage
        endCursor
      }
    }
  }
`;

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

  constructor(private apollo: Apollo) { }

  public getPosts(): Observable&lt;PostResponse&gt; {
   
    return this.apollo.query&lt;GraphQLResponse&lt;'posts', PostResponse&gt;&gt;({
      query: getPostsQuery
    }).pipe(map(resp =&gt; resp.data.posts));
  }
}
</code></pre>
<h3>model/post.ts</h3>
<pre class=""lang-js prettyprint-override""><code>interface CategoryNode {
    id: string;
    name: string;
    uri: string;
}

interface Category {
    category: CategoryNode;
}

interface CategoryEdges{
    edges: Category[];
}

interface PostNode {
    id: string;
    title: string;
    date: string;
    uri: string;
    categories: CategoryEdges;
}

export interface Post {
    article: PostNode;
    cursor: string;
}
</code></pre>
<p>As you can see, way too many nested interfaces.</p>
<h3>Actual sample response (used for unit testing)</h3>
<pre class=""lang-js prettyprint-override""><code>      {
        data: {
          posts: {
            edges : [
              {
                post: {
                  id: &quot;cG9zdDoxMjc=&quot;,
                  title: &quot;Lorem Ipsum&quot;,
                  date: &quot;2022-01-06T22:00:53&quot;,
                  uri: &quot;\/2022\/01\/06\/lorem-ipsum\/&quot;,
                  categories: {
                    edges: [
                      {
                        category: {
                          id: &quot;dGVybToy&quot;,
                          name: &quot;General&quot;,
                          uri: &quot;\/category\/general\/&quot;
                        }
                      }
                    ]
                  }
                },
                cursor: &quot;YXJyYXljb25uZWN0aW9uOjEyNw==&quot;
              },
              {
                post: {
                  id: &quot;cG9zdDoxMjc=&quot;,
                  title: &quot;Lorem Ipsum&quot;,
                  date: &quot;2022-01-06T22:00:53&quot;,
                  uri: &quot;\/2022\/01\/06\/lorem-ipsum\/&quot;,
                  categories: {
                    edges: [
                      {
                        category: {
                          id: &quot;dGVybToy&quot;,
                          name: &quot;General&quot;,
                          uri: &quot;\/category\/general\/&quot;
                        }
                      },
                      {
                        category: {
                          id: &quot;dGVybToy&quot;,
                          name: &quot;General&quot;,
                          uri: &quot;\/category\/general\/&quot;
                        }
                      }
                    ]
                  }
                },
                cursor: &quot;YXJyYXljb25uZWN0aW9uOjEyNw==&quot;
              },
            ],
            pageInfo: {
              startCursor: &quot;YXJyYXljb25uZWN0aW9uOjEyNw==&quot;,
              hasPreviousPage: false,
              hasNextPage: false,
              endCursor: &quot;YXJyYXljb25uZWN0aW9uOjEyNw==&quot;
            }       
          }
        }
      }; 
</code></pre>
<pre><code></code></pre>
",https://stackoverflow.com/questions/70628426/need-help-transforming-graphql-results,"['javascript', 'angular', 'typescript', 'graphql', 'apollo']",729,False,0,2
"C# Console App and Test Frameworks don&#39;t match, how to fix","<p>I wrote code in C# Console application using .NET 6.0.In order to see whether my methods are working or not I wrote a Test program. You can see the properties of my console application below.</p>
<p><a href=""https://i.stack.imgur.com/YtuJe.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/YtuJe.png"" alt=""C#ConsoleAppPropertiesFramework"" /></a></p>
<p>So, I wrote a test program and test method. However, I can not run the test because, I cannot use the same framework with console app program. I can choose these frameworks for test program:</p>
<p><a href=""https://i.stack.imgur.com/yCViy.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/yCViy.png"" alt=""enter image description here"" /></a></p>
<p>In my case, the test program uses .NET Framework 4.8 and the console application uses .NET 6.0
I'm trying to do unit testing. How can I fix this situation? Any help?
I'm using Visual Studio 2022.</p>
",https://stackoverflow.com/questions/74468777/c-console-app-and-test-frameworks-dont-match-how-to-fix,"['c#', '.net', 'visual-studio', 'frameworks']",98,True,0,1
Mocking KafkaConsumer with pytest,"<p>Recently I've been trying to learn unit testing and now I'm on the concept mocking. I'm writing my code with python and using pytest library to test my code. I've a simple factory class has only one function that creates a KafkaConsumer, and I want to test that function. This is the factory class:</p>
<pre><code>from kafka import KafkaConsumer
import json

class KafkaFactory:
    
    @staticmethod
    def consumer(topic, group_id, server):
        return KafkaConsumer(
            topic,
            group_id=group_id,
            bootstrap_servers=server,
            auto_offset_reset='earliest',
            enable_auto_commit=False,
            value_deserializer=lambda v: json.loads(v.decode('utf-8'))
        )
</code></pre>
<p>This is my unit test:</p>
<pre><code>from src.factories.kafka import KafkaFactory

class TestKafkaFactory:
    
    def test_consumer(self, mocker):
        mocker.patch('kafka.KafkaConsumer').return_value = 'consumer'
        spy_factory = mocker.spy(KafkaFactory, 'consumer')
        KafkaFactory.consumer('fake-topic', 'fake-group-id', 'fake-server')
        
        assert spy_factory.spy_return == 'consumer'
</code></pre>
<p>But when I run that test, I see that KafkaConsumer tries to connect a kafka client and I get NoBrokerAvailable expection. I've assumed that when I use mocker.patch method, it does not try to find a client and gives me a mock object. What am I missing? Thank you.</p>
",https://stackoverflow.com/questions/71194969/mocking-kafkaconsumer-with-pytest,"['unit-testing', 'pytest', 'kafka-python']",923,False,0,0
XUnit MethodName_Condition_Behaviour refactoring protection,"<p>In Unit Testing is common to use the convention:</p>
<pre><code>MethodName_Condition_Behaviour()
</code></pre>
<p>Now, If for any reason I try to refactor the method &quot;MethodName&quot;, I obtain inconsistent tests name for that method.</p>
<p>For handling this problem I thought this approach:</p>
<p><strong>Step 1</strong></p>
<p>Extend the XUnit Fact attribute and use a constructor that takes in input also the method to test name</p>
<pre><code>public class FactForAttribute : FactAttribute
{
   public FactForAttribute(string methodName = &quot;Constructor&quot;, [CallerMemberName] string testMethodName = &quot;&quot;)
        =&gt; DisplayName = $&quot;{methodName}_{testMethodName}&quot;;
}
</code></pre>
<p><strong>Step2</strong></p>
<p>Use the nameof operator to make refactoring possible:</p>
<pre><code>public class A
{
    public int Just2() =&gt; 2;
}

public class ATests
{
    [FactFor(nameof(A.Just2))]
    public void Should_Return2()
    {
        var a = new A();
        a.Just2().Should().Be(2);
    }
}
</code></pre>
<p>Now the question. I never found this approach anywhere, so I doubt this is the best way to go.</p>
<p>There is any particular reason that make this approach not advisable?
There is any best practice to protect against refactoring using this convention?</p>
",https://stackoverflow.com/questions/70647414/xunit-methodname-condition-behaviour-refactoring-protection,"['c#', 'refactoring', 'xunit']",59,True,0,1
"Using pytest and SonarQube, How can I cover code in an if statement that circumstantially can&#39;t be reached?","<p>An illustrative simplified example of the problem</p>
<pre><code>import datetime

def func(value):
    now = datetime.datetime.now()
    if now.month &lt; 7:
        out = value
    else:
        out = value + 1
    return out

# fails half the year
def test_func():
    a=func(4)
    assert a==4

# works but only covers one half of the branch based on month.
def test_func2():
    a=func(4)
    now = datetime.datetime.now()
    if now.month &lt; 7:
        assert a==4
    else:
        assert a==5
</code></pre>
<p>How do I create a current-date agnostic single test that covers both branches of the if?
I've tried various experiments with the mock library, and patching, with limited success, and even where apparently successful, the code coverage still wasn't complete, presumably because the test was being conducted on a mocked object.</p>
<p>I'm very new to unit testing and pytest in particular, I think the question I'm asking is, is there a way to somehow &quot;override&quot; a value in a function (in this case, &quot;now&quot;) where it can't be influenced by function parameters, and also obtain code coverage?</p>
",https://stackoverflow.com/questions/72464627/using-pytest-and-sonarqube-how-can-i-cover-code-in-an-if-statement-that-circums,"['python', 'python-3.x', 'unit-testing', 'pytest', 'code-coverage']",176,False,0,1
Jest NodeJS - Any way to put mocks in test directory?,"<p>I have an application that I am testing with Jest.  Of course, for unit testing, it is useful to create mocks for dependencies.  However, as components of my application are interdependent (e.g. a service that requires a DAO), I need to mock them.  Currently, as documented in the Jest docs, I have a <strong>mocks</strong> directory in my source tree to hold the mock code.  However, I would like my test code to be separate from my source code.  Is there any way to configure Jest which will allow me to have my test code together and my source code together?  For example:</p>
<p>What I have:</p>
<pre><code>- src
-- service
--- service.js
-- db
--- dao.js
--- __mocks__
---- dao.js
- test
-- service
--- service.test.js
</code></pre>
<p>What I want:</p>
<pre><code>- src
-- service
--- service.js
-- dao
--- dao.js
- test
-- __mocks__
--- dao.js
-- service
--- service.test.js
</code></pre>
",https://stackoverflow.com/questions/70670875/jest-nodejs-any-way-to-put-mocks-in-test-directory,"['node.js', 'unit-testing', 'jestjs', 'mocking']",147,False,0,0
How to unit test nested for loop function in Python,"<p>I'm trying to unit test a function with nested for loop using the Mock module in Python:</p>
<p>main.py:</p>
<pre><code>@dataclass
Helper_class():
  Attr1: Set[some_object]
  Attr2: Set[str]

def fetch_rule_for(api, id):
    return some rule_objects based on id

def my_func(list_ids):
    api = create some api connection
    result_dict = dict()
    for id in list_ids:
      Attr1_set = set()
      Attr2_set = set()
      for rule in fetch_rule_for(api, id):
        if any(a.name == 'some_action_name' for a in rule.actions):
          Attr2_set.add(rule.attr1)
          Attr1_set.add(rule)
      result_dict[id] = Helper_class(Attr1_set, Attr2_set)

    return result_dict
      
</code></pre>
<p>Rule is a class object with method actions, action is another class object with attribute name.</p>
<p>Two questions I'm struggling with:</p>
<p>(1) How do I pacth the return value of function fetch_rule_for(api, id) where the return is a complicated class object?</p>
<p>(2) How do I deal with the for loops in Python using unit test? I have seen mock.call_count mentioned but can someone please get into more details or point me to relevant resources?</p>
<p>I'm new to unit testing in Python so any help is much appreicated!</p>
",https://stackoverflow.com/questions/73281233/how-to-unit-test-nested-for-loop-function-in-python,"['python', 'unit-testing', 'mocking']",143,False,0,1
Unit test for spark read/write function to azure data lake mount path,"<p>I am very new to unit testing and I need to write a unit test for spark read/write function.</p>
<p>I have a function as below for example:</p>
<pre><code>def read_file(path, format, logger):
   df = spark.read.load(path, format = format)
   etc.....
   return df
</code></pre>
<p><em>note : the path is mounted.</em></p>
<p>now I need to write unit test for this function / <strong>mock adls location</strong>.</p>
<p>I have checked below link which is using patch to mock blobServiceClient but I am not sure whether this is useful to me as it is using open function of python.</p>
<p><a href=""https://stackoverflow.com/questions/62622820/trying-to-use-patch-to-mock-blobserviceclient-but-the-real-class-is-called-inste"">Trying to use patch to mock BlobServiceClient but the real class is called instead</a></p>
<p>Is it even possible to mock adls and if so how?</p>
<p>Can anyone please help me in this.
Any help would be appreciated.</p>
",https://stackoverflow.com/questions/73621715/unit-test-for-spark-read-write-function-to-azure-data-lake-mount-path,"['python', 'apache-spark', 'pyspark', 'pytest', 'azure-storage-account']",307,False,3,1
How to unit test a transaction-wrapped function in Prisma?,"<p>I'm very new to Prisma and NestJS. I have the following transaction-wrapped function that I want to unit test by mocking the internal function <code>reserveSingleBook</code>.</p>
<p>This is my code (it does a few actions in a for loop and I want all those actions to be successful before committing the transaction).</p>
<pre><code>  async reserveBooks(reserveBooksDto: ReserveBoksDto): Promise&lt;SuccessfulReservationResponse&gt; {
    return await this.prisma.$transaction(async (prisma) =&gt; {

      const reservedBooksResponse = new SuccessfulReservationResponse();

      for (const reservation of reserveBooksDto.reservations){

        const bookBucket = await this.reserveSingleBook(
          prisma,
          reserveBooksDto.libraryId,
          reservation,
        );

        const successfulReservation = new SuccessfulReservation();
        successfulReservation.book_bucket_id = bookBucket.id;
        successfulReservation.units_reserved = reservation.units;

        reservedBookssResponse.successful_reservations.push(successfulReservation);    
      }

      return reservedBooksResponse
    })
  }
</code></pre>
<p>This is how I'm currently unit testing it:</p>
<pre><code>    it('should throw an exception when at least a parent book does not exist', async () =&gt; {
  // Arrange
  const nonExistingParentBookId = 'non-existing-parentbook-id';
  const existingParentBookId = 'existing-parent-book-id'; 
  const mock = jest.spyOn(service, 'reserveSingleBook');
  mock
  .mockResolvedValueOnce(
    {
      parentBookId: existingParentBookId,
      reserved: 10,
      used: 0,
    } as BookBucket
  )
  .mockRejectedValueOnce(new NotFoundException())
  const reserveBooksDto = new ReserveBooksDto();
  reserveBooksDto.library_id= 'abcde';
  const firstReservation = new Reservation();
  firstReservation.book_id= nonExistingParentBookId;
  firstReservation.units = 10;
  const secondReservation = new Reservation();
  secondReservation.book_id= existingParentBookId;
  secondReservation.units = 10;
  reserveBooksDto.reservations = [firstReservation, secondReservation];

  // Act / Assert
  await expect(service.reserveBooks(
    reserveBooksDto
  )).rejects.toThrowError(NotFoundException);
  expect(mock).toBeCalledTimes(2);

  mock.mockRestore();
});
</code></pre>
<p><strong>The unit test works PERFECTLY if I remove the transaction</strong>, since my second mock call returns the NotFoundException, which is then passed on to ReserveBooks.</p>
<p>However, when I have the transaction in place (don't want anything commited if anything fails), I get an 'undefined' resolved in my function call, instead of the exception thrown.</p>
<p>Does anybody know what I might be doing wrong?</p>
<p>Thanks in advance!!</p>
",https://stackoverflow.com/questions/73007221/how-to-unit-test-a-transaction-wrapped-function-in-prisma,"['unit-testing', 'jestjs', 'transactions', 'nestjs', 'prisma']",1017,False,7,1
How should a pure function read a config file or open a database?,"<p>Often I have functions that need data from either a config file or a database. I would prefer pure functions at much as possible and something that can be unit tested.</p>
<p>I have no idea how to do this correctly, as I don't have a CS degree. The options I can see are:</p>
<p><strong>Example 1:</strong></p>
<pre><code>function myFunc(p1, p2, db, configFile) { ... }
</code></pre>
<p>but that means all other functions that calls <code>myFunc()</code> also needs to have <code>db, configFile</code> as arguments.</p>
<p><strong>Example 2:</strong></p>
<pre><code>function myFunc(p1, p2) { 
  const config = readConfig();
  dbConn = openDb();    
  ...
}
</code></pre>
<p>I suppose this make unit testing impossible?</p>
<p><strong>Example 3:</strong></p>
<pre><code>const struct = {
  config: readConfig(),
  dbConn: openDb(),
  ...
};

function myFunc(p1, p2, struct) { ... }
</code></pre>
<p>This have the down side, that when other functions data also gets stored in this global <code>struct</code> then each function have access to more than what they need.</p>
<p><strong>Question</strong></p>
<p>Are there other possibilities? What is the recommended approach?</p>
",https://stackoverflow.com/questions/73387544/how-should-a-pure-function-read-a-config-file-or-open-a-database,"['javascript', 'typescript', 'computer-science']",195,False,2,2
Triggering Events in ag grid for unit test,"<p>i wanted to trigger ag grid events manually but don't know how</p>
<p>So I have a event tied to a column which is type of cell clicked event, and when you click on it, it opens a mat dialog.
So the question is how can you trigger that event for unit testing? I tried to get that cell with Dom and click on it, and also use the grid API but it doesn't work.</p>
<pre><code>it('checking mat dialog option', async ()=&gt;{
jest.spyOn(matDialog,'open');

//using grid api which doesn't work
// component.gridOptions.api.dispatchEvent(cellClikcedEvent);

// using dom
const select= fixture.nativeElement.querySelectorAll('.ag-cell');
select[3].dispatchEvent(new Event('click));
// or  select[3].click();

expect(matDialog.open).toBeCalled();
)
</code></pre>
<p>there are typos, i'm writing this question at home and don't have my code , but the logic is some thing like above. there is a really bad documentation about it too. like you don't know how you can use it</p>
",https://stackoverflow.com/questions/71694209/triggering-events-in-ag-grid-for-unit-test,"['angular', 'unit-testing', 'jestjs', 'ag-grid']",2015,True,2,1
Hypothesis library: strategy for the complement of some other strategy,"<p>I'm using the <a href=""https://hypothesis.readthedocs.io/en/latest/index.html"" rel=""nofollow noreferrer"">Hypothesis</a> library for unit testing. With this library you don't hand-pick inputs, but you define the complete set of inputs for which you want to test. Hypothesis will then sample from this set to look for inputs that break the function. This is also known as property-based testing. In Hypothesis, these sets are called strategies.</p>
<p>Now I would like to unit test a function that validates some input:</p>
<pre><code>GRIDSIZE_FORMAT = &quot;^[0-9]+x[0-9]+$&quot;
CELL_FORMAT = &quot;^[A-Z]+[0-9]+$&quot;

def _validate(gridsize, walls, entrance):
    if not re.match(GRIDSIZE_FORMAT, gridsize):
        raise ValueError(f&quot;grid size '{gridsize}' does not match format '{GRIDSIZE_FORMAT}'&quot;)
    for wall in walls:
        if not re.match(CELL_FORMAT, walls):
            raise ValueError(f&quot;wall '{wall}' does not match format '{CELL_FORMAT}'&quot;)
    if not re.match(CELL_FORMAT, entrance):
        raise ValueError(f&quot;entrance '{entrance}' does not match format '{CELL_FORMAT}'&quot;)
</code></pre>
<p>To properly test this function I want to generate examples of the form &quot;anything but X&quot;, X being the proper input format for this function.</p>
<p>Is there a strategy in the Hypothesis library that can generate inputs like this?</p>
",https://stackoverflow.com/questions/71869905/hypothesis-library-strategy-for-the-complement-of-some-other-strategy,"['python', 'unit-testing', 'python-hypothesis']",155,True,2,2
Failing to get dependency during SonarScan action,"<p>In our Java SpringBoot project we are using GitHub actions to run SonarScan. It was working like a charm until I've added first custom library to the project. That library is in Nexus repo and accessible only via VPN.</p>
<p>Locally project is built without any issues and works fine. Unit-testing and dev deployment GH actions run successfully. But SonarScan action is failing on :compileJava because of the missing resource (log below).</p>
<p>Looks like it tries to get it from the Apache Maven although it is in the Nexus. Here is the relevant part of the log:</p>
<pre><code>&gt; Task :compileJava
Watching 37 directories to track changes
Resolving global dependency management for project 'project_name'
Resource missing. [HTTP GET: https://repo.maven.apache.org/maven2/com/company_name/lib_name/1.0.7-SNAPSHOT/maven-metadata.xml]
Resource missing. [HTTP GET: https://repo.maven.apache.org/maven2/com/company_name/lib_name/1.0.7-SNAPSHOT/lib_name-1.0.7-SNAPSHOT.pom]
Excluding []


FAILURE: Build failed with an exception.
&gt; Task :compileJava FAILED
* What went wrong:
:compileJava (Thread[included builds,5,main]) completed. Took 4 mins 35.418 secs.
1 actionable task: 1 executed
Execution failed for task ':compileJava'.
&gt; Could not resolve all files for configuration ':compileClasspath'.
   &gt; Could not resolve com.company_name:lib_name:1.0.7-SNAPSHOT.

     Required by:
         project :
      &gt; Skipped due to earlier error
</code></pre>
<p>Here is our build.gradle file (shortened):</p>
<pre><code>plugins {
    id 'org.springframework.boot' version '2.6.4'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id 'java-library'
    id &quot;org.sonarqube&quot; version &quot;3.3&quot;
}


//Sets Java Version
java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(17))
    }
}

ext {
    set('mongoVersion', '4.4.1')
    set('mavenUsername', &quot;maven.user&quot;)
    set('mavenPassword', &quot;password&quot;)
    set('mavenUrl', &quot;https://nexus-repo-url/repository/repo-name&quot;)
}

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
    maven {
        credentials {
            username &quot;${mavenUsername}&quot;
            password &quot;${mavenPassword}&quot;
        }
        url &quot;${mavenUrl}&quot;
        authentication {
            basic(BasicAuthentication)
        }
    }
}

dependencies {
    ...
    implementation &quot;com.company_name:lib_name:1.0.7-SNAPSHOT&quot;
}


sonarqube {
    properties {
        property &quot;sonar.projectKey&quot;, &quot;prject_key&quot;
        property &quot;sonar.java.binaries&quot;, &quot;build/classes&quot;
    }
}

</code></pre>
<p>I am obviously missing some path somewhere, but failing to find where actually.</p>
",https://stackoverflow.com/questions/73402479/failing-to-get-dependency-during-sonarscan-action,"['java', 'spring', 'maven', 'gradle', 'sonarqube']",249,True,2,2
fulfillRandomWords callback is not getting executed after calling fulfillRandomWords on the VRF v2 contract,"<p>I am following <a href=""https://www.youtube.com/watch?v=gyMwXuJrbJQ"" rel=""nofollow noreferrer"">this tutorial</a> and I am doing the exact same in terms of deployment, subscription funding, and unit testing.</p>
<p>But the problem is in the last unit test, when I call <code>fulfillRandomWords</code> on the <code>vrfCoordinatorV2Mock</code> contract, I expect it to call the <code>fulfillRandomWords</code> callback function on my contract. For some reason it does not and the unit test times out.</p>
<p>Here is my smart contract:</p>
<pre><code>// SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;

import &quot;@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol&quot;;
import &quot;@chainlink/contracts/src/v0.8/VRFConsumerBaseV2.sol&quot;;

import &quot;@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol&quot;;

error RandomApeYachtClub__NotOwner();
error RandomApeYachtClub__BreedNotFound();
error RandomApeYachtClub__NotEnoughFeeToMint();
error RandomApeYachtClub__NotAbleToWithdraw();

contract RandomApeYachtClub is ERC721URIStorage, VRFConsumerBaseV2 {
  enum ApeBreed {
    CHIMP,
    GORILLA,
    BABOON,
    BLACK_HOWLER
  }

  // VRF helpers
  VRFCoordinatorV2Interface immutable private COORDINATOR;
  address immutable private i_vrfCoordinator;
  bytes32 immutable private i_keyHash;
  uint32 immutable private i_callbackGasLimit;
  uint64 immutable private i_subscriptionId;
  mapping (uint256 =&gt; address) s_requestIdToMinter;

  // NFT helper
  uint256 constant private MAX_RARITY = 500;
  uint256 private s_tokenId;
  string[4] private s_tokenURIs;
  mapping (uint256 =&gt; string) tokenIdToTokenURI;

  uint256 private i_mintFee;
  address immutable private i_owner;

  // Events
  event NFTRequested(uint256 requestId, address sender);
  event NFTMinted(uint256 requestId, uint256 tokenId, ApeBreed breed, address minter);

  constructor (
    address vrfCoordinator,
    bytes32 keyHash,
    uint32 callbackGasLimit,
    uint64 subscriptionId,
    string[4] memory tokenURIs,
    uint256 mintFee
  )
  ERC721(&quot;RandomApeYachtClub&quot;, &quot;RAYC&quot;)
  VRFConsumerBaseV2(vrfCoordinator)
  {
    i_owner = msg.sender;
    COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
    i_vrfCoordinator = vrfCoordinator;
    i_keyHash = keyHash;
    i_callbackGasLimit = callbackGasLimit;
    i_subscriptionId = subscriptionId;
    s_tokenURIs = tokenURIs;
    i_mintFee = mintFee;
  }
  
  // ETH fee to mint, random nft minted
  function mintNft() payable external returns (uint256 requestId) {
    if(msg.value &lt; i_mintFee)
      revert RandomApeYachtClub__NotEnoughFeeToMint();

    requestId = COORDINATOR.requestRandomWords(
      i_keyHash,
      i_subscriptionId,
      3,
      i_callbackGasLimit,
      1
    );

    s_requestIdToMinter[requestId] = msg.sender;
    emit NFTRequested(requestId, msg.sender);
  }

  // randomness
  function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal override {
    address minter = s_requestIdToMinter[requestId];
    uint256 tokenId = s_tokenId;

    uint256 randomNumber = randomWords[0] % MAX_RARITY;
    ApeBreed apeBreed = getApeFromNumber(randomNumber);
    string memory _tokenURI = s_tokenURIs[uint256(apeBreed)];
    _safeMint(minter, tokenId);
    _setTokenURI(tokenId, _tokenURI);
    tokenIdToTokenURI[tokenId] = _tokenURI;
    s_tokenId++;
    emit NFTMinted(requestId, tokenId, apeBreed, minter);
  }

  function getApeFromNumber(uint256 randomNumber) public pure returns (ApeBreed) {
    uint256[4] memory rarityChance = getRarityChance();
    uint256 accu = 0;
    for (uint i = 0; i &lt; rarityChance.length; i++) {
      if((randomNumber &gt;= rarityChance[i]) &amp;&amp; (randomNumber &lt; (rarityChance[i] + accu))) {
        return ApeBreed(i);
      }
      accu += rarityChance[i];
    }
    revert RandomApeYachtClub__BreedNotFound();
  }

  function getRarityChance() internal pure returns (uint256[4] memory) {
    return [10, 30, 120, MAX_RARITY];
  }

  // owner of the contract can withdraw
  function withdraw () external ownerOnly {
    uint256 balance = address(this).balance;

    (bool success, ) = i_owner.call{value: balance}(&quot;&quot;);
    if(!success)
      revert RandomApeYachtClub__NotAbleToWithdraw();
  }

  // tokenURI to return the NFT's uri
  function tokenURI(uint256 tokenId) public view override returns (string memory) {
    return tokenIdToTokenURI[tokenId];
  }

  modifier ownerOnly () {
    if(i_owner != msg.sender) {
        revert RandomApeYachtClub__NotOwner();
    }
    _;
  }

  function getMaxRarity() public pure returns (uint256) {
    return MAX_RARITY;
  }

  function getTokenURIs() public view returns (string[4] memory) {
    return s_tokenURIs;
  }

  function getMintFee() public view returns (uint256) {
    return i_mintFee;
  }
}

</code></pre>
<p>this is the VRF v2 mock:</p>
<pre><code>// SPDX-License-Identidier: MIT
pragma solidity ^0.8.0;

import &quot;@chainlink/contracts/src/v0.8/mocks/VRFCoordinatorV2Mock.sol&quot;;
</code></pre>
<p>this is the deploy script for the mock:</p>
<pre><code>const { network, ethers } = require('hardhat');
const { networkConfig, devChains } = require('../network.config');

const BASE_FEE = ethers.utils.parseEther(&quot;0.25&quot;);

module.exports = async ({ getNamedAccounts, deployments }) =&gt; {
  const currentNetworkConfig = networkConfig[network.config.chainId];
  const isLocal = devChains.includes(currentNetworkConfig.name);
  if(isLocal) {
    const { deploy, log } = deployments;
    const { deployer } = await getNamedAccounts();
    
    await deploy('VRFCoordinatorV2Mock', {
      from: deployer,
      contract: 'VRFCoordinatorV2Mock',
      args: [BASE_FEE, 10000000000000],
      log: true,
    });
    log('Mocks deployed')
    log('-------------------------------------------------');
  }
}

module.exports.tags = ['all', 'mocks'];
</code></pre>
<p>this is the deploy script for the randomApeYachtClub contract:</p>
<pre><code>const { network, ethers } = require('hardhat');
const { networkConfig, devChains } = require('../network.config');
const { handleUploadToPinia } = require('../utils/handleUploadToPinata');
const { verify } = require('../utils/verify');

let tokenURIs = [
  'ipfs://QmR27pW2CVvZ8DRqC35vcvLjnfxZpesGJwyFW8ihyR2HQb',
  'ipfs://QmaqQxmqdodEeFigZ89TcNkT3hzsqqDcNaU9w14bNb4c4T',
  'ipfs://QmcEtwoygjJWkFapRLorJX6TJwZbXMLWtDSyFvBF2gzf1Q',
  'ipfs://QmWj9RjQhuSei9XVoMW1EGy9ueZAMD8wbCtWpsqjj5VM9d'
];

const FUND_AMOUNT = ethers.utils.parseEther('10');

module.exports = async ({ getNamedAccounts, deployments }) =&gt; {
  const { deploy, log } = deployments;
  const { deployer } = await getNamedAccounts();
  
  const currentNetwork = networkConfig[network.config.chainId];
  const isLocal = devChains.includes(currentNetwork.name);

  let vrfCoordinator = '';
  let subscriptionId = 0;

  if(process.env.UPLOAD_TO_PINATA === 'true') {
    tokenURIs = await handleUploadToPinia();
  }

  console.log(isLocal);
  if(isLocal) {
    const VRFCoordinatorV2Mock = await ethers.getContract('VRFCoordinatorV2Mock');
    vrfCoordinator = VRFCoordinatorV2Mock.address;
    const tx = await VRFCoordinatorV2Mock.createSubscription();
    const receipt = await tx.wait(1);
    subscriptionId = receipt.events[0].args.subId;
    await VRFCoordinatorV2Mock.fundSubscription(subscriptionId, FUND_AMOUNT);
  } else {
    vrfCoordinator = currentNetwork.vrfCoordinator;
    subscriptionId = currentNetwork.subscriptionId;
  }

  const keyHash = currentNetwork.keyHash;
  const callbackGasLimit = currentNetwork.callbackGasLimit;
  const mintFee = currentNetwork.mintFee;

  const args = [
    vrfCoordinator,
    keyHash,
    callbackGasLimit,
    subscriptionId,
    tokenURIs,
    mintFee,
  ]

  const RandomApeYachtClub = await deploy('RandomApeYachtClub', {
    from: deployer,
    args,
    log: true,
    waitConfirmations: network.config.blockConfirmations || 1,
  });

  if(!isLocal) {
    await verify(RandomApeYachtClub.address, args);
  }
}

module.exports.tags = ['all', 'RAYC'];
</code></pre>
<p>this is the unit tests file (the last test is the only one that's not working):</p>
<pre><code>const { expect, assert } = require('chai');
const { ethers, deployments, network, getNamedAccounts } = require('hardhat');
const { devChains, networkConfig } = require('../../network.config');

!devChains.includes(network.name) ?
describe.skip : 
describe('RAYC', function () {
  let randomApeYachtClub, vrfCoordinatorV2Mock, deployer;
  const mintFee = networkConfig[network.config.chainId].mintFee;

  beforeEach(async function() {
    accounts = await ethers.getSigners();
    deployer = accounts[0];
    await deployments.fixture(['mocks', 'RAYC']);

    vrfCoordinatorV2Mock = await ethers.getContract(&quot;VRFCoordinatorV2Mock&quot;);
    randomApeYachtClub = await ethers.getContract(&quot;RandomApeYachtClub&quot;);
  });

  describe('constructor', function () {
    it('tokenURIs is assigned', async function() {
      const tokenURIs = await randomApeYachtClub.getTokenURIs();
      expect(tokenURIs).to.have.lengthOf(4);
    });

    it('mint fee is assigned', async function() {
      const contractMintFee = await randomApeYachtClub.getMintFee();
      assert.equal(ethers.utils.formatEther(contractMintFee), ethers.utils.formatEther(mintFee));
    })
  });

  describe('minNft', function() {
    it('if paid less than mint fee, an error is thrown', async function() {
      const smallFee = ethers.utils.parseEther('0.09');
      await expect(randomApeYachtClub.mintNft({ value: smallFee })).to.be.revertedWith('RandomApeYachtClub__NotEnoughFeeToMint');
    });

    it('NFTRequested event is fired', async function () {
      await expect(randomApeYachtClub.mintNft({ value: mintFee })).to.emit(randomApeYachtClub, 'NFTRequested');
    });
  });

  describe('withdraw', function() {
    it('the amount of the contract is 0 after withdrawing', async function() {
      await randomApeYachtClub.withdraw();
      const provider = ethers.provider;
      const balance = await provider.getBalance(randomApeYachtClub.address);
      expect(balance).to.equal(0);
    });
  });

  describe('fulfillRandomWords', function() {
    it('reverts if no valid requestId is provided', async function () {
      await expect(vrfCoordinatorV2Mock.fulfillRandomWords(0, randomApeYachtClub.address)).to.be.revertedWith('nonexistent request');
    });

    it('emits RandomWordsFulfilled', async function () {
      // mint NFT
      const tx = await randomApeYachtClub.mintNft({ value: mintFee });
      const receipt = await tx.wait(1);
      const requestId = receipt.events.find(e =&gt; e.event === 'NFTRequested').args['requestId'];
      // call fulfillRandomWords
      // and watch for the event
      await expect(vrfCoordinatorV2Mock.fulfillRandomWords(requestId, randomApeYachtClub.address))
      .to.emit(vrfCoordinatorV2Mock, 'RandomWordsFulfilled');
    });

    it('the vrf fulfillRandomWords sends the randomWords and emits NFTMinted', async function () {
      await new Promise(async (resolve, reject) =&gt; {
        randomApeYachtClub.on('NFTMinted', () =&gt; {
          try {
            // This right here is never executed
            console.log('NFTMinted is emitted!');
          } catch (error) {
            console.log(erro);
          }
        });
        try {
          // mint NFT
          const tx = await randomApeYachtClub.mintNft({ value: mintFee });
          const receipt = await tx.wait(1);
          const requestId = receipt.events.find(e =&gt; e.event === 'NFTRequested').args['requestId'];
          // call fulfillRandomWords
          // and watch for the event
          await vrfCoordinatorV2Mock.fulfillRandomWords(requestId, randomApeYachtClub.address);
        } catch (error) {
          console.log(error);
        }
      })
    });
  });
});
</code></pre>
<p>I am not sure what I'm doing wrong. Please help!</p>
",https://stackoverflow.com/questions/73658174/fulfillrandomwords-callback-is-not-getting-executed-after-calling-fulfillrandomw,"['unit-testing', 'ethereum', 'solidity', 'ethers.js', 'hardhat']",222,False,1,0
How does nyc istanbul pass instrumented code to test runners?,"<p>I've been trying to generate code coverage for a vanilla Typescript (no react or any web frameworks) project on Webpack 5 using Cypress for unit testing. I'm not able to generate code coverage for it as if I'm failing to tell Cypress that it needs to use the source instrumented by nyc.</p>
<p>In order to come up with ideas on solving this, I need to know: how exactly nyc passes the instrumented source to test runners?</p>
<p>In this <a href=""https://docs.cypress.io/guides/tooling/code-coverage#Instrumenting-code"" rel=""nofollow noreferrer"">documentation</a>, it mentioned using <code>nyc</code> to instrument the code but it doesn't really show how the instrumented code is going to be picked up by Cypress. Following the provided command line does not allow your cypress test to generate code.</p>
",https://stackoverflow.com/questions/71234883/how-does-nyc-istanbul-pass-instrumented-code-to-test-runners,"['cypress', 'code-coverage', 'webpack-5', 'nyc']",373,False,1,1
Mocking GetStorage for testing in flutter,"<p>I am unit testing and widget testing my code. I have tried <code>mokito</code> and <code>moktail</code> to mock the Get storage but get this error:</p>
<pre><code>package:get_storage/src/storage_impl.dart 47:7  GetStorage._init
===== asynchronous gap ===========================
package:get_storage/src/storage_impl.dart 28:7  new GetStorage._internal.&lt;fn&gt;
</code></pre>
<p>the class that I am testing:</p>
<pre><code>class ShowCaseController extends GetxController {

   final box = GetStorage();
   displayAnySC(String playKey, String replayKey, GetStorage box) async {

    bool? showcasePlayStatus = box.read(playKey);
    if (showcasePlayStatus == null) {
      box.write(playKey, false);
      // box.remove(replayKey);
      box.write(replayKey, false);
      return true;
    }

    bool? showcaseReplayStatus = box.read(replayKey);
    if (showcaseReplayStatus == null) {
      box.write(replayKey, false);
      return true;
    }

    return false;
  }
}
</code></pre>
<p>here is one empty simple test using mock that gives error:</p>
<pre><code>class MockStorage extends Mock implements GetStorage {}

void main() {
  group('Show case controller', () {
    final showCaseCnt = ShowCaseController();

    late bool _data;
    late MockStorage _mockStorage;
    setUp(() {
      _mockStorage = MockStorage();
      _data = showCaseCnt.displayAnySC('playKey', 'replayKey', _mockStorage);
    });

      test(
          'displayAnySC should return false when the play and replay are not null',
          () {
      
      });
  });
}
</code></pre>
<p>I have tried <code>@GenerateMocks([ShowCaseController])</code> and also added <code>GetStorage.init()</code> inside the <code>main</code> function of the test but got the same error.</p>
<p>P.S. I haven't seen any article or question related to mocking the GetStorage for test in Flutter. Appreciate any explanation or link that helps in this regard.</p>
<p>I am using the GetX package for dependency injection and state management. And using the GetStorage package for keeping the theme persistent and storing keys for notifying the app to play or replay ShowCaseView.</p>
",https://stackoverflow.com/questions/71066904/mocking-getstorage-for-testing-in-flutter,"['flutter', 'unit-testing', 'dart', 'mocking', 'mockito']",785,False,1,0
Infinite Recursion with Spies in Angular Unit Testing,"<p>New to unit testing here.</p>
<p>I have a situation where the function I am testing <code>getFolderTree$()</code> recursively calls another function <code>getFolderChildren$()</code>. I tried setting up a spy for <code>getFolderChildren$()</code> as seen in the below attempt at a unit test. However, this results in <code>getFolderTree$()</code> never getting the chance to hit the base case because it keeps getting more and more children and a maximum call stack size exceeded error.</p>
<p>When I set the <code>getFolderChildren$()</code> spyOn to return an empty array, I solve the recursion issue but I can't cover the lines that deal with children.</p>
<p>Does anyone know how I can solve this issue and still get full coverage of the original function? Any help appreciated!</p>
<p><strong>Original Function</strong></p>
<pre><code>getFolderTree$(tenantId: number, folderId: number): Observable&lt;FolderTree&gt; {
  return combineLatest([
    this.getFolder$(tenantId, folderId),
    this.getFolderChildren$(tenantId, folderId)]).pipe(
      map(([folder, subFolders]) =&gt; ({
        parent: { name: folder.folderName, id: folder.id, description: folder.description, children: [] } as FolderTree,
        childFolders: subFolders
      })),
      mergeMap(data =&gt; forkJoin([
        of(data.parent),
        ...data.childFolders.map(child =&gt; this.getFolderTree$(child.tenantId, child.id))
      ])),
      map(([parent, ...children]) =&gt; { parent.children = children.sort(this.sortByFolderName); return parent; })
    );
}
</code></pre>
<p><strong>Unit Test</strong></p>
<pre><code>it('should get folder tree', () =&gt; {
        let folder = {id: 1, tenantId: tenantID, folderName: 'some folder'} as IFolder;
        let subFolders = [{id: 2, tenantId: tenantID, folderName: 'some child folder'} as IFolder];

        spyOn(folderService, 'getFolder$').and.returnValue(of(folder));
        spyOn(folderService, 'getFolderChildren$').and.returnValue(of(subFolders));

        let result = folderService.getFolderTree$(tenantID, folderID);
        result.subscribe(value =&gt; {
            //expectation here
        });
    });
</code></pre>
",https://stackoverflow.com/questions/70560028/infinite-recursion-with-spies-in-angular-unit-testing,"['angular', 'typescript', 'unit-testing', 'recursion', 'karma-jasmine']",139,False,1,0
React testing Library | .toHaveAttribute(),"<p>I'm trying to test a component but having issue with unit testing.</p>
<p>The component have tabs provided via props. It's an array of object.
When the component first render, the first tab is supposed to be selected :</p>
<ul>
<li>aria-selected set to true</li>
<li>inline style setting a different background color property.</li>
<li>The selected tab has a state of isActive = true</li>
</ul>
<p>When another tab then the selected one is clicked, all the property listed above is supposed to be apply to the clicked tab.</p>
<p>When I test manually, everything is working fine. But, when I make a unit test for testing this behavior, it's not working at all.</p>
<p>Here's the code :</p>
<pre><code>import React, { useState } from &quot;react&quot;;
import { Box, Typography, Button } from &quot;@mui/material&quot;;
import style from &quot;./header.module.scss&quot;;

interface IProps {
  tabs: Array&lt;{ src: string; name: string }&gt;;
}

const Header = ({ tabs }: IProps) =&gt; {
  const [activeTab, setActiveTab] = useState&lt;string&gt;(
    tabs[0].name.toUpperCase(),
  );

  const handleClick = (event: React.MouseEvent&lt;HTMLButtonElement&gt;): void =&gt; {
    const tabName: string = event.currentTarget.innerText;
    setActiveTab(tabName);
  };

  const buttonBackgroundColor = (
    buttonName: string,
    activeTabName: string,
  ): string =&gt; {
    let className: string;
    if (
      buttonName &amp;&amp;
      activeTabName &amp;&amp;
      buttonName.toUpperCase() === activeTabName.toUpperCase()
    ) {
      className = &quot;rgb(94, 70, 136)&quot;;
    } else {
      className = &quot;inherit&quot;;
    }

    return className;
  };

  const setAriaSelected = (currentTab: string): boolean =&gt; {
    return (
      currentTab.localeCompare(activeTab, undefined, {
        sensitivity: &quot;accent&quot;,
      }) === 0
    );
  };

  return (
    &lt;Box component=&quot;header&quot; className={style.header}&gt;
      {tabs.map((tab) =&gt; (
        &lt;Button
          key={tab.name}
          className={style.button}
          onClick={handleClick}
          role=&quot;tab&quot;
          aria-selected={setAriaSelected(tab.name)}
          style={{
            backgroundColor: buttonBackgroundColor(tab.name, activeTab),
          }}
        &gt;
          &lt;div className={style.imgWrapper}&gt;
            &lt;img src={tab.src} alt={tab.name} /&gt;
          &lt;/div&gt;
          &lt;Typography fontWeight={300} letterSpacing=&quot;0.1rem&quot; fontSize=&quot;0.9rem&quot;&gt;
            {tab.name}
          &lt;/Typography&gt;
        &lt;/Button&gt;
      ))}
    &lt;/Box&gt;
  );
};

export default Header;
</code></pre>
<p>Testing file:</p>
<pre><code> it(&quot;makes the second tab to have aria-selected attribute to true when it's clicked&quot;, async () =&gt; {
    render(
      &lt;MemoryRouter&gt;
        &lt;Header tabs={tabs} /&gt;
      &lt;/MemoryRouter&gt;,
    );
    const user = userEvent.setup();
    const secondTab = screen.getByRole(&quot;tab&quot;, { name: /tab2/i });
    await user.click(secondTab);

    expect(secondTab).toHaveAttribute(&quot;aria-selected&quot;, &quot;true&quot;);
  });
</code></pre>
<p>Console message:</p>
<pre><code>● Header component › makes the second tab to have aria-selected attribute to true when it's clicked

expect(element).toHaveAttribute(&quot;aria-selected&quot;, &quot;true&quot;) // element.getAttribute(&quot;aria-selected&quot;) === &quot;true&quot;

Expected the element to have attribute:
  aria-selected=&quot;true&quot;
Received:
  aria-selected=&quot;false&quot;

  57 |     await user.click(secondTab);
  58 |
&gt; 59 |     expect(secondTab).toHaveAttribute(&quot;aria-selected&quot;, &quot;true&quot;);
     |                       ^
  60 |   });
  61 | });
  62 |

  at Object.&lt;anonymous&gt; (src/shared/header/__tests__/Header.tsx:59:23)
</code></pre>
",https://stackoverflow.com/questions/74071002/react-testing-library-tohaveattribute,"['reactjs', 'testing', 'react-testing-library', 'user-event']",2876,True,1,1
Unexpected execution order in Pytest,"<p>I'm using <code>pytest</code> to do unit testing. I have the logging code on the top of the <code>calc_test.py</code> source code:</p>
<pre><code>module_logger = logging.getLogger(__name__)
module_logger.warning(f&quot;Start module:{__name__}, the source file: {__file__}&quot;)
</code></pre>
<p>I expect that every time I run <code>pytest -vv -s calc_test.py</code>, the above logging info would show near <strong>the very beginning</strong> of the logs.</p>
<p>To my surprise, this logging never shows up. Even the loggings in <code>conftest.py</code> were successfully shown.
I dug into the official documentation, to find any explantion of the execution order for each test file. However there is no mentioning of the loggings at the beginning of each file. My guess is that pytest will put on hold each testing files and first run all the stuff in <code>conftest.py</code>. But this isn't confirmed by the documentation.
Very weird, could you explain this behavior?</p>
",https://stackoverflow.com/questions/72493983/unexpected-execution-order-in-pytest,['pytest'],32,False,1,0
How would I go about writing tests for Sharepoint Webparts?,"<p>How would I go about Unit Testing CRUD methods in a Sharepoint webpart? I've tried following the Jest documentation in regards to creating Mock of classes / specific methods, but I don't think its possible given that the service class that I'm supposed to be testing, requires a specific Context for the constructor.</p>
<pre><code>export default class PnpServices implements IPnpServices {
private _sp;
constructor(context: WebPartContext) {
    this._sp = getSP(context);
}

public async sp_createItem(listName: string, itemObject: any): Promise&lt;any&gt; {
    try {
        const iar: IItemAddResult = await this
        ._sp.web.lists.getByTitle(listName).items.add(itemObject)
        return iar.data.Id;
    } catch (e) {
        throw new Error(&quot;error&quot;)
    }
}
</code></pre>
<p>I tried setting up a simple test to check if the Constructor could even be called when parsing &quot;null&quot; as an argument instead of a context</p>
<pre><code>    jest.mock('./pnpservices')
it('should pass', () =&gt; {
    const mockedClassInstance = new PnpServices(null);
    expect(PnpServices).toBeCalledTimes(1);
})
</code></pre>
<p>Most examples I can find dont create actual genuinely useful tests or even have business-oriented methods such as CRUD, theyre mostly just simple &quot;addition&quot; methods or their only functionality is returning a console.log.</p>
<p>Any help?</p>
",https://stackoverflow.com/questions/74232695/how-would-i-go-about-writing-tests-for-sharepoint-webparts,"['node.js', 'typescript', 'sharepoint', 'web-parts', 'ts-jest']",94,False,0,1
Cannot find module &#39;#node-web-compat&#39; from aws-jwt-verify library in Next.js tests,"<p><b>Issue description</b></p>
<p>I'm going to test the service in api used in Next.js app and using babel jest for that specific tests file. The problem that I struggle is issue regarding finding a module and the error that appears in terminal is as in the listing below.</p>
<pre class=""lang-bash prettyprint-override""><code>    Cannot find module '#node-web-compat' from 'node_modules/aws-jwt-verify/dist/cjs/https.js'

    Require stack:
      node_modules/aws-jwt-verify/dist/cjs/https.js
      node_modules/aws-jwt-verify/dist/cjs/jwk.js
      node_modules/aws-jwt-verify/dist/cjs/jwt-rsa.js
      node_modules/aws-jwt-verify/dist/cjs/index.js
      pages/api/auth/auth.service.ts
      __tests__/sign-up/api/auth/auth-service.test.ts

      at Resolver._throwModNotFoundError (node_modules/jest-resolve/build/resolver.js:491:11)
      at Object.&lt;anonymous&gt; (node_modules/aws-jwt-verify/dist/cjs/https.js:9:28)
</code></pre>
<p>The tested service is used by TypeScript decorator in middleware. It works as expected when I'm testing it manually but the issue appears only while running tests.</p>
<p><b>Goal</b></p>
<p>My goal is unit testing service that uses library <code>aws-jwt-verify</code> to verify JWT accessToken. I would like to mock it and use in my <code>jest</code> unit tests.</p>
<p><b>tried methods</b></p>
<p>I've tried to copy dependency to <code>devDependencies</code> and reinstall packages but it didn't help</p>
<p><b>dependencies in package.json</b></p>
<pre class=""lang-json prettyprint-override""><code>{
...
  &quot;dependencies&quot;: {
    &quot;@aws-sdk/client-cognito-identity-provider&quot;: &quot;^3.137.0&quot;,
    &quot;@chakra-ui/react&quot;: &quot;^2.2.3&quot;,
    &quot;@emotion/react&quot;: &quot;^11&quot;,
    &quot;@emotion/styled&quot;: &quot;^11&quot;,
    &quot;@hookform/resolvers&quot;: &quot;^2.9.7&quot;,
    &quot;@storyofams/next-api-decorators&quot;: &quot;^1.8.2&quot;,
    &quot;@tanstack/react-query&quot;: &quot;^4.0.10&quot;,
    &quot;@tanstack/react-query-devtools&quot;: &quot;^4.0.10&quot;,
    &quot;aws-jwt-verify&quot;: &quot;^3.1.0&quot;,
    &quot;axios&quot;: &quot;^0.27.2&quot;,
    &quot;class-transformer&quot;: &quot;^0.5.1&quot;,
    &quot;class-validator&quot;: &quot;^0.13.2&quot;,
    &quot;cookie&quot;: &quot;^0.5.0&quot;,
    &quot;framer-motion&quot;: &quot;^6&quot;,
    &quot;next&quot;: &quot;latest&quot;,
    &quot;react&quot;: &quot;^18.2.0&quot;,
    &quot;react-cookie&quot;: &quot;^4.1.1&quot;,
    &quot;react-dom&quot;: &quot;^18.2.0&quot;,
    &quot;react-hook-form&quot;: &quot;^7.34.0&quot;,
    &quot;react-icons&quot;: &quot;^4.4.0&quot;,
    &quot;storybook-addon-next-router&quot;: &quot;^4.0.0&quot;,
    &quot;zod&quot;: &quot;^3.17.10&quot;
  },
...
}
</code></pre>
<p><b>tsconfig.json</b></p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;compilerOptions&quot;: {
    &quot;target&quot;: &quot;es5&quot;,
    &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;],
    &quot;allowJs&quot;: true,
    &quot;skipLibCheck&quot;: true,
    &quot;strict&quot;: false,
    &quot;forceConsistentCasingInFileNames&quot;: true,
    &quot;noEmit&quot;: true,
    &quot;esModuleInterop&quot;: true,
    &quot;module&quot;: &quot;esnext&quot;,
    &quot;moduleResolution&quot;: &quot;node&quot;,
    &quot;resolveJsonModule&quot;: true,
    &quot;isolatedModules&quot;: true,
    &quot;jsx&quot;: &quot;preserve&quot;,
    &quot;incremental&quot;: true,
    &quot;experimentalDecorators&quot;: true,
    &quot;emitDecoratorMetadata&quot;: true
  },
  &quot;include&quot;: [&quot;next-env.d.ts&quot;, &quot;**/*.ts&quot;, &quot;**/*.tsx&quot;],
  &quot;exclude&quot;: [&quot;node_modules&quot;]
}

</code></pre>
<p><b> jest.config.js </b></p>
<pre class=""lang-js prettyprint-override""><code>const nextJest = require('next/jest');

const createJestConfig = nextJest({
 test environment
  dir: './'
});

const customJestConfig = {for alias' to work
  moduleDirectories: ['node_modules', '&lt;rootDir&gt;/']
};

module.exports = createJestConfig(customJestConfig);
</code></pre>
<p><b>auth.service.ts</b></p>
<pre class=""lang-js prettyprint-override""><code>// auth.service.ts
import { CognitoJwtVerifier } from 'aws-jwt-verify';
import { BadRequestException } from '@storyofams/next-api-decorators';
import { CognitoAccessTokenPayload } from 'aws-jwt-verify/jwt-model';

export class AuthService {
  async verifyToken(token: string): Promise&lt;boolean&gt; {
    const verifier = CognitoJwtVerifier.create({
      userPoolId: process.env.COGNITO_USER_POOL_ID,
      tokenUse: 'access',
      clientId: process.env.COGNITO_WEB_CLIENT_ID
    });

    try {
      const verifyResult: CognitoAccessTokenPayload = await verifier.verify(token);

      const isNotExpired = verifyResult.exp &gt; Math.floor(Date.now() / 1000);
      const isCorrectClient = verifyResult.client_id === process.env.COGNITO_WEB_CLIENT_ID;
      const isCorrectUserPool =
        verifyResult.iss ===
        `https://cognito-idp.${process.env.AWS_REGION}.amazonaws.com/${process.env.COGNITO_USER_POOL_ID}`;
      const isTokenUseValid = verifyResult.token_use === 'access';

      return isNotExpired &amp;&amp; isCorrectClient &amp;&amp; isCorrectUserPool &amp;&amp; isTokenUseValid;
    } catch (e) {
      throw new BadRequestException(e.message);
    }
  }
}
</code></pre>
<p><b>auth-service.test.ts</b></p>
<pre class=""lang-js prettyprint-override""><code>// auth-service.test.ts
describe('Auth Service', () =&gt; {
  describe('verifyToken', () =&gt; {
    beforeEach(() =&gt; {
      jest.clearAllMocks();
    });

    it('should verify token successfully', async () =&gt; {
      jest.mock('aws-jwt-verify', () =&gt; {
        return {
          CognitoJwtVerifier: jest.fn().mockImplementation(() =&gt; {
            return {
              verify: jest.fn().mockResolvedValue({
                exp: Math.floor(Date.now() / 1000) + 3600,
                client_id: process.env.COGNITO_WEB_CLIENT_ID,
                iss: `https://cognito-idp.${process.env.AWS_REGION}.amazonaws.com/${process.env.COGNITO_USER_POOL_ID}`,
                token_use: 'access'
              })
            };
          })
        };
      });
      const authService = new AuthService();
      const result = await authService.verifyToken('token');
      expect(result).toBeTruthy();
    });
  });
});
</code></pre>
",https://stackoverflow.com/questions/73331259/cannot-find-module-node-web-compat-from-aws-jwt-verify-library-in-next-js-tes,"['typescript', 'unit-testing', 'next.js', 'jestjs', 'jwt']",1220,True,5,2
Cannot override final class FormErrorHandler with JWT Serializer,"<p>Good morning all , I did a complete migration of my symfony 2.8 application to version 5.4. I am now at the unit testing stage.</p>
<p>but I have a little problem with one in running my tests. On the old version of my project, I was using the FormErrorHandler class from the JWT serializer bundle that I was overloaded. However, on the new version of the bundle compatible with version 5.4 of Symfony, the class has been passed to final and I can no longer override. Is there a simple way to circumvent this? Thanks in advance.</p>
<p>My old class :</p>
<pre><code>use JMS\Serializer\Context;
use JMS\Serializer\Handler\FormErrorHandler as JMSFormErrorHandler;
use JMS\Serializer\JsonSerializationVisitor;
use JMS\Serializer\VisitorInterface;
use JMS\Serializer\XmlSerializationVisitor;
use Symfony\Component\Form\Form;
use JMS\Serializer\YamlSerializationVisitor;
use Symfony\Component\Form\FormError;
use Symfony\Component\Translation\TranslatorInterface;
use JMS\Serializer\GraphNavigator;

/**
 * Extend the JMS FormErrorHandler to include more informations when using the ViewHandler.
 */
class FormErrorHandler extends JMSFormErrorHandler
{
    /** @var TranslatorInterface */
    private $translator;
    /** @var string */
    private $translationDomain;

    public static function getSubscribingMethods()
    {
        $methods = array();
        foreach (array('xml', 'json', 'yml') as $format) {
            $methods[] = array(
                'direction' =&gt; GraphNavigator::DIRECTION_SERIALIZATION,
                'type' =&gt; 'Symfony\Component\Form\Form',
                'format' =&gt; $format,
            );
            $methods[] = array(
                'direction' =&gt; GraphNavigator::DIRECTION_SERIALIZATION,
                'type' =&gt; 'Symfony\Component\Form\FormError',
                'format' =&gt; $format,
            );
        }

        return $methods;
    }

    public function __construct(TranslatorInterface $translator = null, $translationDomain = 'validators')
    {
        parent::__construct($translator, $translationDomain);
    }

    public function serializeFormToXml(XmlSerializationVisitor $visitor, Form $form, array $type)
    {
        if (null === $visitor-&gt;document) {
            $visitor-&gt;document = $visitor-&gt;createDocument(null, null, false);
            $visitor-&gt;document-&gt;appendChild($formNode = $visitor-&gt;document-&gt;createElement('form'));
            $visitor-&gt;setCurrentNode($formNode);
        } else {
            $visitor-&gt;getCurrentNode()-&gt;appendChild(
                $formNode = $visitor-&gt;document-&gt;createElement('form')
            );
        }

        $formNode-&gt;setAttribute('name', $form-&gt;getName());

        $formNode-&gt;appendChild($errorsNode = $visitor-&gt;document-&gt;createElement('errors'));
        foreach ($form-&gt;getErrors() as $error) {
            $errorNode = $visitor-&gt;document-&gt;createElement('entry');
            $errorNode-&gt;appendChild($this-&gt;serializeFormErrorToXml($visitor, $error, array()));
            $errorsNode-&gt;appendChild($errorNode);
        }

        foreach ($form-&gt;all() as $child) {
            if ($child instanceof Form) {
                if (null !== $node = $this-&gt;serializeFormToXml($visitor, $child, array())) {
                    $formNode-&gt;appendChild($node);
                }
            }
        }

        return $formNode;
    }

    public function serializeFormToJson(JsonSerializationVisitor $visitor, Form $form, array $type)
    {
        return new \ArrayObject($this-&gt;clearEmptyValues($this-&gt;convertFormToArray($visitor, $form)));
    }

    public function serializeFormToYml(YamlSerializationVisitor $visitor, Form $form, array $type)
    {
        return new \ArrayObject($this-&gt;clearEmptyValues($this-&gt;convertFormToArray($visitor, $form)));
    }

    public function serializeFormErrorToXml(XmlSerializationVisitor $visitor, FormError $formError, array $type)
    {
        if (null === $visitor-&gt;document) {
            $visitor-&gt;document = $visitor-&gt;createDocument(null, null, true);
        }

        return $visitor-&gt;document-&gt;createCDATASection($this-&gt;getErrorMessage($formError));
    }

    public function serializeFormErrorToJson(JsonSerializationVisitor $visitor, FormError $formError, array $type)
    {
        return $this-&gt;getErrorMessage($formError);
    }

    public function serializeFormErrorToYml(YamlSerializationVisitor $visitor, FormError $formError, array $type)
    {
        return $this-&gt;getErrorMessage($formError);
    }

    private function getErrorMessage(FormError $error)
    {

        if ($this-&gt;translator === null){
            return $error-&gt;getMessage();
        }

        if (null !== $error-&gt;getMessagePluralization()) {
            return $this-&gt;translator-&gt;transChoice($error-&gt;getMessageTemplate(), $error-&gt;getMessagePluralization(), $error-&gt;getMessageParameters(), $this-&gt;translationDomain);
        }

        return $this-&gt;translator-&gt;trans($error-&gt;getMessageTemplate(), $error-&gt;getMessageParameters(), $this-&gt;translationDomain);
    }

    /**
     * @param VisitorInterface $visitor
     * @param Form $data
     * @return array
     */
    private function convertFormToArray(VisitorInterface $visitor, Form $data)
    {
        $isRoot = null === $visitor-&gt;getRoot();

        $form = [];
        $errors = array();
        foreach ($data-&gt;getErrors() as $error) {
            $errors = $this-&gt;getErrorMessage($error);
        }

        if ($errors) {
            $form = $errors;
        }

        $children = array();
        foreach ($data-&gt;all() as $child) {
            if ($child instanceof Form &amp;&amp; empty($errors)) {
                $children[$child-&gt;getName()] = $this-&gt;convertFormToArray($visitor, $child);
            } else if (!empty($errors)) {
                $children[$child-&gt;getName()] = $errors;
            }
        }

        if ($children) {
            $form = $children;
        }

        if ($isRoot) {
            $visitor-&gt;setRoot($form);
        }

        return count($form) &gt; 0 ? $form : null;
    }

    /**
     * Remove fields without errors
     * @param $array
     * @return array
     */
    private function clearEmptyValues($array)
    {
        foreach ($array as $key =&gt; &amp;$value) {
            if (is_array($value)) {
                $value = $this-&gt;clearEmptyValues($value);
            }
            if (empty($value)) {
                unset($array[$key]);
            }
        }
        return $array;
    }
}
</code></pre>
<p>My old config :</p>
<pre><code># API Form error handler
 jms_serializer.form_error_handler:
    class: WORD\CoreBundle\Serializer\Handler\FormErrorHandler
    arguments:
        - '@translator'
    tags:
        - { name: jms_serializer.subscribing_handler }
</code></pre>
<p>The new FormErrorHandler marked as final :</p>
<pre><code>&lt;?php

declare(strict_types=1);

namespace JMS\Serializer\Handler;

use JMS\Serializer\GraphNavigatorInterface;
use JMS\Serializer\Visitor\SerializationVisitorInterface;
use JMS\Serializer\XmlSerializationVisitor;
use Symfony\Component\Form\Form;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface as TranslatorContract;

use function get_class;

final class FormErrorHandler implements SubscribingHandlerInterface
{
    /**
     * @var TranslatorInterface|null
     */
    private $translator;

    /**
     * @var string
     */
    private $translationDomain;

    /**
     * {@inheritdoc}
     */
    public static function getSubscribingMethods()
    {
        $methods = [];
        foreach (['xml', 'json'] as $format) {
            $methods[] = [
                'direction' =&gt; GraphNavigatorInterface::DIRECTION_SERIALIZATION,
                'type' =&gt; Form::class,
                'format' =&gt; $format,
            ];
            $methods[] = [
                'direction' =&gt; GraphNavigatorInterface::DIRECTION_SERIALIZATION,
                'type' =&gt; FormInterface::class,
                'format' =&gt; $format,
                'method' =&gt; 'serializeFormTo' . ucfirst($format),
            ];
            $methods[] = [
                'direction' =&gt; GraphNavigatorInterface::DIRECTION_SERIALIZATION,
                'type' =&gt; FormError::class,
                'format' =&gt; $format,
            ];
        }

        return $methods;
    }

    public function __construct(?object $translator = null, string $translationDomain = 'validators')
    {
        if (null !== $translator &amp;&amp; (!$translator instanceof TranslatorInterface &amp;&amp; !$translator instanceof TranslatorContract)) {
            throw new \InvalidArgumentException(sprintf(
                'The first argument passed to %s must be instance of %s or %s, %s given',
                self::class,
                TranslatorInterface::class,
                TranslatorContract::class,
                get_class($translator)
            ));
        }

        $this-&gt;translator = $translator;
        $this-&gt;translationDomain = $translationDomain;
    }

    /**
     * @param array $type
     */
    public function serializeFormToXml(XmlSerializationVisitor $visitor, FormInterface $form, array $type): \DOMElement
    {
        $formNode = $visitor-&gt;getDocument()-&gt;createElement('form');

        $formNode-&gt;setAttribute('name', $form-&gt;getName());

        $formNode-&gt;appendChild($errorsNode = $visitor-&gt;getDocument()-&gt;createElement('errors'));
        foreach ($form-&gt;getErrors() as $error) {
            $errorNode = $visitor-&gt;getDocument()-&gt;createElement('entry');
            $errorNode-&gt;appendChild($this-&gt;serializeFormErrorToXml($visitor, $error, []));
            $errorsNode-&gt;appendChild($errorNode);
        }

        foreach ($form-&gt;all() as $child) {
            if ($child instanceof Form) {
                if (null !== $node = $this-&gt;serializeFormToXml($visitor, $child, [])) {
                    $formNode-&gt;appendChild($node);
                }
            }
        }

        return $formNode;
    }

    /**
     * @param array $type
     */
    public function serializeFormToJson(SerializationVisitorInterface $visitor, FormInterface $form, array $type): \ArrayObject
    {
        return $this-&gt;convertFormToArray($visitor, $form);
    }

    /**
     * @param array $type
     */
    public function serializeFormErrorToXml(XmlSerializationVisitor $visitor, FormError $formError, array $type): \DOMCdataSection
    {
        return $visitor-&gt;getDocument()-&gt;createCDATASection($this-&gt;getErrorMessage($formError));
    }

    /**
     * @param array $type
     */
    public function serializeFormErrorToJson(SerializationVisitorInterface $visitor, FormError $formError, array $type): string
    {
        return $this-&gt;getErrorMessage($formError);
    }

    private function getErrorMessage(FormError $error): ?string
    {
        if (null === $this-&gt;translator) {
            return $error-&gt;getMessage();
        }

        if (null !== $error-&gt;getMessagePluralization()) {
            if ($this-&gt;translator instanceof TranslatorContract) {
                return $this-&gt;translator-&gt;trans($error-&gt;getMessageTemplate(), ['%count%' =&gt; $error-&gt;getMessagePluralization()] + $error-&gt;getMessageParameters(), $this-&gt;translationDomain);
            } else {
                return $this-&gt;translator-&gt;transChoice($error-&gt;getMessageTemplate(), $error-&gt;getMessagePluralization(), $error-&gt;getMessageParameters(), $this-&gt;translationDomain);
            }
        }

        return $this-&gt;translator-&gt;trans($error-&gt;getMessageTemplate(), $error-&gt;getMessageParameters(), $this-&gt;translationDomain);
    }

    private function convertFormToArray(SerializationVisitorInterface $visitor, FormInterface $data): \ArrayObject
    {
        $form = new \ArrayObject();
        $errors = [];
        foreach ($data-&gt;getErrors() as $error) {
            $errors[] = $this-&gt;getErrorMessage($error);
        }

        if ($errors) {
            $form['errors'] = $errors;
        }

        $children = [];
        foreach ($data-&gt;all() as $child) {
            if ($child instanceof FormInterface) {
                $children[$child-&gt;getName()] = $this-&gt;convertFormToArray($visitor, $child);
            }
        }

        if ($children) {
            $form['children'] = $children;
        }

        return $form;
    }
}
</code></pre>
<p>Has anyone encountered this problem before?</p>
",https://stackoverflow.com/questions/74292178/cannot-override-final-class-formerrorhandler-with-jwt-serializer,"['php', 'symfony', 'jmsserializerbundle', 'jms-serializer']",75,False,0,0
Approaches for unit testing DB components,"<p>I have a component that provides a CRUD interface to store and manage data internally in a database. For unit testing this component, I have several options:</p>
<ol>
<li>Test each method individually using a mock DB client and check whether the correct methods were called with the correct arguments,</li>
<li>Test each method individually using a functional DB client and check whether the internal state of the DB is as expected,</li>
<li>Test methods together, e.g.,
<pre><code>put(&quot;a&quot;, &quot;1&quot;);
result = get(&quot;a&quot;);
assert_equals(&quot;1&quot;, result);
</code></pre>
</li>
</ol>
<p>I personally tend to use method 3 because 1 and 2 are very fragile towards changes to the underlying data management. But what are the pros and cons of each method? Which method is usually used for such code?</p>
",https://stackoverflow.com/questions/71641581/approaches-for-unit-testing-db-components,['unit-testing'],20,True,-1,1
Unit testing a state machine with all possible transitions?,"<p>I have a state machine implemented as this data structure under the hood:</p>
<pre><code>Map&lt;State, Map&lt;State, boolean&gt;&gt;
</code></pre>
<p>The idea being you use the original state as the input to lookup the list of possible target states. Then you lookup the target state in that embedded map, and if it's there, a possible transition exists.</p>
<p>My problem is unit testing all possible transitions, such that if you give the test some input that will throw an error (an invalid state transition), then the test should fail if you have not included <em>all</em> of the states.</p>
<p>My test looks something like this:</p>
<pre><code>public void invalid_state_transition() {
    State originalState = State0;
    List&lt;State&gt; targetStates = List.of(
        State1, 
        State2, 
        ...
    )

    for (targetState : targetStates) {
        TransitionToTargetState(originalState, targetState)
    }
}
</code></pre>
<p>How would I go about doing this? Or am I thinking about the problem in the wrong way?</p>
",https://stackoverflow.com/questions/71970545/unit-testing-a-state-machine-with-all-possible-transitions,"['java', 'state-machine']",200,False,0,0
Truffle not calling the function in past time,"<p>I was writing writing some unit testing code for my vesting smart contract in truffle, when I encountered a problem, I had a function which was getting time as one of its parameters so instead of providing it with a manual time I was calculating the time in real time and passing it as a parameter, then I was using a timeout function to delay the time for a while so when I call the function of smart contract the block.timestamp would have been greater then the time passed previously but that was not the case, instead after debugging I found out that the block.timestamp was stuck when the contract was basically deployed.</p>
",https://stackoverflow.com/questions/72879732/truffle-not-calling-the-function-in-past-time,"['mocha.js', 'blockchain', 'solidity', 'chai', 'truffle']",43,False,-1,1
How can i test a void function in python using pytest?,"<p>I just started unit testing in python using pytest. Well, when I have a function with a return value, with the &quot;assert&quot; I can compare a certain value with the value that the function return.
But if I had a void function that returns nothing and does a print at the end, for example:</p>
<pre><code>def function() -&gt; None:
    number = randint(0, 4)

    if (number == 0):
       print(&quot;Number 0&quot;)

    elif (number == 1):
       print(&quot;Number 1&quot;)

    elif (number == 2):
       print(&quot;Number 2&quot;)

    elif (number == 3):
       print(&quot;Number 3&quot;)

    elif (number == 4):
       print(&quot;Number 4&quot;)
</code></pre>
<p>How can i test this simple function to get 100% code coverage?</p>
<p>One method I've found to test this function is to do a return of the value (instead of print) and print it later, and then use the assert. But I wanted to know if it was possible to avoid this and do a test directly on the print statemant.</p>
",https://stackoverflow.com/questions/74578124/how-can-i-test-a-void-function-in-python-using-pytest,"['python', 'unit-testing', 'pytest']",320,True,0,2
Cannot mock adding to entity with EF Mock (Collection was modified; enumeration operation may not execute.),"<p>I'm trying to build my first unit test using EF and Moq. I am able to create a mock of the data and query it just fine. Now I want to unit test adding to the entity and observe behavior. (Eventually would like to incorporate AddRange() but can't even get add() working). The section I will be unit testing does everything with Async().</p>
<p>I keep getting this error</p>
<pre><code>System.InvalidOperationException : Collection was modified; enumeration operation may not execute.
</code></pre>
<p>I'm passing in a list mockOrganizationTasks to this method to mock the entities</p>
<pre class=""lang-cs prettyprint-override""><code>var mockOrganizationTasksList = new List&lt;OrganizationTask&gt; { new OrganizationTask { OrganizationTaskKey = 1} }
var mockOrganizationTasksData = mockOrganizationTasks.AsQueryable();
var mockOrganizationTasksSet = new Mock&lt;DbSet&lt;OrganizationTask&gt;&gt;();
mockOrganizationTasksSet.As&lt;IDbAsyncEnumerable&lt;OrganizationTask&gt;&gt;()
    .Setup(m =&gt; m.GetAsyncEnumerator())
    .Returns(new TestDbAsyncEnumerator&lt;OrganizationTask&gt;(mockOrganizationTasksData.GetEnumerator()));
        mockOrganizationTasksSet.As&lt;IQueryable&lt;OrganizationTask&gt;&gt;()
            .Setup(m =&gt; m.Provider)
            .Returns(new TestDbAsyncQueryProvider&lt;OrganizationTask&gt;(mockOrganizationTasksData.Provider));
mockOrganizationTasksSet.As&lt;IQueryable&lt;OrganizationTask&gt;&gt;().Setup(m =&gt; m.Expression).Returns(mockOrganizationTasksData.Expression);
mockOrganizationTasksSet.As&lt;IQueryable&lt;OrganizationTask&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(mockOrganizationTasksData.ElementType);
mockOrganizationTasksSet.As&lt;IQueryable&lt;OrganizationTask&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(() =&gt; mockOrganizationTasksData.GetEnumerator());
        
mockOrganizationTasksSet.Setup(x =&gt; x.Add(It.IsAny&lt;OrganizationTask&gt;())).Callback&lt;OrganizationTask&gt;(x =&gt; {
            mockOrganizationTasksList.Add(x);
            mockOrganizationTasksSet.As&lt;IQueryable&lt;OrganizationTask&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(() =&gt; mockOrganizationTasksList.GetEnumerator());
        }).Returns&lt;OrganizationTask&gt;(x =&gt; x);

var mockContext = new Mock&lt;CustomDBContext&gt;(typeof(CustomDBContext).Name);
mockContext.Setup(c =&gt; c.Set&lt;OrganizationTask&gt;()).Returns(mockOrganizationTasksSet.Object);
</code></pre>
<p>Later on, I try to add OrganizationTask but get an error when I try to query the collection after adding.</p>
<pre><code>var allOrganizationTasks1 = await _dbContext.OrganizationTasks
            .ToListAsync();
_dbContext.OrganizationTasks.Add(_mockOrganizationTask1);

var allOrganizationTasks2 = await _dbContext.OrganizationTasks
            .ToListAsync();
</code></pre>
<p>I've tried various different add() methods but haven't had any luck</p>
",https://stackoverflow.com/questions/73145396/cannot-mock-adding-to-entity-with-ef-mock-collection-was-modified-enumeration,"['c#', 'entity-framework', 'unit-testing', 'moq']",59,False,0,0
"How to test setFieldValue from Formik, in a react-slider component","<p>maybe it is a weird question, but I am new to unit testing, and can't wrap my head around this one.</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 { Field, FieldInputProps, FieldMetaProps, FormikHelpers, FormikValues } from 'formik';
import Slider from 'components/elements/slider';
import FormError from 'components/elements/formerror';
import { useEffect, useState } from 'react';

interface IScheduleSlider {
  min?: number;
  max?: number;
  title: string;
  name: string;
  unitLabel: string;
  conversions: {
    first: {
      //eslint-disable-next-line
      convertFct: (x: number) =&gt; number;
      label: string;
    };
    second: {
      //eslint-disable-next-line
      convertFct: (x: number) =&gt; number;
      label: string;
    };
  };
  showError?: boolean;
}

const ScheduleSlider = ({ min = 0, max = 100, title, name, unitLabel, conversions, showError = false }: IScheduleSlider) =&gt; {
  const [error, setError] = useState(false);
  console.log(conversions);
  useEffect(() =&gt; {
    if (showError) {
      setError(true);
    }
  }, [showError]);

  const getRealValue = (val: number) =&gt; (val &gt; max ? max : val);

  return (
    &lt;Field name={name}&gt;
      {({
        field,
        form: { setFieldValue, setFieldTouched },
        meta,
      }: {
        field: FieldInputProps&lt;never&gt;;
        form: FormikHelpers&lt;FormikValues&gt;;
        meta: FieldMetaProps&lt;never&gt;;
      }) =&gt; (
        &lt;div className={`schedule-slider ${error ? 'error' : ''}`} data-testid=""schedule-slider-test""&gt;
          &lt;div className=""schedule-slider__top""&gt;
            &lt;h4&gt;{title}&lt;/h4&gt;
            {typeof conversions?.first?.convertFct === 'function' &amp;&amp; typeof conversions?.second?.convertFct === 'function' &amp;&amp; (
              &lt;div&gt;
                &lt;div className=""schedule-slider__top--conversion""&gt;
                  &lt;h5&gt;{conversions?.first?.convertFct(field.value)}&lt;/h5&gt;
                  &lt;span&gt;{conversions?.first?.label}&lt;/span&gt;
                &lt;/div&gt;
                &lt;div className=""schedule-slider__top--conversion""&gt;
                  &lt;h5&gt;{conversions?.second?.convertFct(field.value)}&lt;/h5&gt;
                  &lt;span&gt;{conversions?.second?.label}&lt;/span&gt;
                &lt;/div&gt;
              &lt;/div&gt;
            )}
          &lt;/div&gt;
          &lt;div className=""schedule-slider__bottom""&gt;
            &lt;Slider
              max={Math.ceil(max)}
              min={min}
              value={Math.ceil(field.value)}
              onChange={(val: number) =&gt; {
                setFieldValue(field?.name, getRealValue(val));
                setFieldTouched(field?.name, true);
                setError(false);
              }}
              labels={{ left: `${min} ${unitLabel}`, right: `${max} ${unitLabel}` }}
            /&gt;
            &lt;div className=""schedule-slider__value""&gt;
              &lt;div&gt;
                &lt;h3 data-testid=""field-test-value""&gt;{field.value}&lt;/h3&gt;
                &lt;span&gt;{unitLabel}&lt;/span&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt;
          {error &amp;&amp; &lt;FormError meta={meta} /&gt;}
        &lt;/div&gt;
      )}
    &lt;/Field&gt;
  );
};

export default ScheduleSlider;</code></pre>
</div>
</div>
</p>
<p>This is my tsx file with the component, I have a ScheduleSlider component which in itself contains a formik component, and a react-slider, which has  the onChange prop where setFieldValue and setFieldTouched is.</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>/* eslint-disable testing-library/no-container */
/* eslint-disable testing-library/no-node-access */
import ScheduleSlider from './scheduleslider';
import * as Formik from 'formik';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import userEvent from '@testing-library/user-event';
import { renderWithRedux } from 'test-utils';
describe('render ScheduleSlider', () =&gt; {
  const mockFn = jest.fn();

  const useFormikContextMock = jest.spyOn(Formik, 'useFormikContext');

  beforeEach(() =&gt; {
    useFormikContextMock.mockReturnValue({
      setFieldValue: jest.fn(),
      setFieldTouched: jest.fn(),
    } as unknown as never);
  });

  afterEach(() =&gt; {
    jest.clearAllMocks();
    cleanup();
  });

  const defaultId = 'schedule-slider-test';
  const sliderId = 'slider-test';
  const fieldId = 'field-test-value';

  it('render component with props', async () =&gt; {
    const props = {
      min: 0,
      max: 100,
      title: 'Test title',
      name: 'POWER',
      unitLabel: 'kWh',
      conversions: {
        first: {
          convertFct: jest.fn().mockImplementation((x) =&gt; x),
          label: '%',
        },
        second: {
          convertFct: jest.fn().mockImplementation((x) =&gt; x),
          label: 'km',
        },
      },
      showError: false,
    };
    const { container } = renderWithRedux(
      &lt;Formik.Formik initialValues={{}} enableReinitialize onSubmit={mockFn}&gt;
        &lt;ScheduleSlider {...props} /&gt;
      &lt;/Formik.Formik&gt;
    );
    // const slider = screen.queryByRole('slider');
    const slider = screen.getByTestId(sliderId);

    expect(container).toBeVisible();
    props.conversions.first.convertFct.mockReturnValue('10');
    props.conversions.second.convertFct.mockReturnValue('30');
    // expect(slider).toBeVisible();
    // expect(slider).toHaveClass('slider__thumb slider__thumb-0');
    if (slider) {
      slider.ariaValueMin = '1';
      slider.ariaValueMax = '100';
      // screen.getByTestId(fieldId).textContent = '80';

      fireEvent.keyDown(slider, { key: 'ArrowLeft', code: 'ArrowLeft', charCode: 37 });
    }
    // expect(useFormikContextMock).toBeCalled();
    // console.log(slider?.ariaValueMin);
    // console.log(screen.getByTestId(fieldId).textContent);
    console.log(props.conversions.second.convertFct.mock.results);
    console.log(container.textContent);
  });

  it('render with default min, max, showError value', () =&gt; {
    const props = {
      min: undefined,
      max: undefined,
      title: 'test title',
      name: 'schedule',
      unitLabel: 'test unit',
      conversions: {
        first: {
          convertFct: jest.fn(),
          label: '%',
        },
        second: {
          convertFct: jest.fn(),
          label: 'km',
        },
      },
      showError: true,
    };

    render(
      &lt;Formik.Formik initialValues={{}} enableReinitialize onSubmit={mockFn}&gt;
        &lt;ScheduleSlider {...props} /&gt;
      &lt;/Formik.Formik&gt;
    );
    expect(screen.getByTestId(defaultId)).toBeVisible();
  });

  it('checks for onChange values', () =&gt; {
    const props = {
      min: 0,
      max: 100,
      title: 'test title',
      name: 'schedule',
      unitLabel: 'test unit',
      conversions: {
        first: {
          convertFct: jest.fn(),
          label: '%',
        },
        second: {
          convertFct: jest.fn(),
          label: 'km',
        },
      },
      showError: undefined,
    };

    render(
      &lt;Formik.Formik initialValues={{}} enableReinitialize onSubmit={mockFn}&gt;
        &lt;ScheduleSlider {...props} /&gt;
      &lt;/Formik.Formik&gt;
    );
    expect(screen.getByTestId(defaultId)).toBeVisible();
  });
});</code></pre>
</div>
</div>
</p>
<p>And this is my test file, I could render the component, and some of the branches, functions, statemnts are covered, but don't know how to test setFieldValue. Tried to fire events, but I am making some errors and can't see where. Anybody has any idea how to start with this. Sorry for the comments, console.log-s but I was tryng all kinds of solutions</p>
",https://stackoverflow.com/questions/73957358/how-to-test-setfieldvalue-from-formik-in-a-react-slider-component,"['reactjs', 'typescript', 'jestjs', 'react-testing-library', 'formik']",56,False,0,0
Problems with Unit Testing in C++ (Visual studio 2022),"<p>Issues with unit testing</p>
<p>I cant really see what is going wrong with that code, but something doesn't include right
relevant files:</p>
<h4>MetaData.h</h4>
<pre><code>#pragma once
#include &lt;string&gt;
enum ChessColor
{
    White,
    Black
};
enum PieceType
{
   King,
   Queen,
   Rook,
   Bishop,
   Knight,
   Pawn,
   None
};
const int BOARD_SIZE = 8;

std::string getLongNameOfChessType(PieceType* type);
std::string getShortNameOfChessType(PieceType* type);

std::string getLongNameOfChessColor(ChessColor* color);
std::string getShortNameOfChessColor(ChessColor* color);
</code></pre>
<h4>MetaData.cpp</h4>
<pre><code>#include &quot;MetaData.h&quot;

std::string getLongNameOfChessType(PieceType* type)
{
    switch (*type)
    {
    case PieceType::King:
        return &quot;King&quot;;
    case PieceType::Queen:
        return &quot;Queen&quot;;
    case PieceType::Rook:
        return &quot;Rook&quot;;
    case PieceType::Bishop:
        return &quot;Bishop&quot;;
    case PieceType::Knight:
        return &quot;Knight&quot;;
    case PieceType::Pawn:
        return &quot;Pawn&quot;;
    default:
        return &quot;NoType&quot;;
    }
}

std::string getShortNameOfChessType(PieceType* type)
{
    switch (*type)
    {
    case PieceType::King:
        return &quot;K&quot;;
    case PieceType::Queen:
        return &quot;Q&quot;;
    case PieceType::Rook:
        return &quot;R&quot;;
    case PieceType::Bishop:
        return &quot;B&quot;;
    case PieceType::Knight:
        return &quot;N&quot;;
    case PieceType::Pawn:
        return &quot;P&quot;;
    default:
        return &quot;NoType&quot;;
    }
}
std::string getLongNameOfChessColor(ChessColor* color)
{
    switch (*color)
    {
    case ChessColor::White:
        return &quot;White&quot;;
    case ChessColor::Black:
        return &quot;Black&quot;;
    default:
        return &quot;NoColor&quot;;
    }
}
std::string getShortNameOfChessColor(ChessColor* color)
{
    switch (*color)
    {
    case ChessColor::White:
        return &quot;W&quot;;
    case ChessColor::Black:
        return &quot;B&quot;;
    default:
        return &quot;NoColor&quot;;
    }
}
</code></pre>
<h4>ChessTest.cpp</h4>
<p>The test file.</p>
<pre><code>#include &quot;pch.h&quot;
#include &quot;CppUnitTest.h&quot;
#include &lt;MetaData.h&gt;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace ChessTest
{
    TEST_CLASS(ChessTest)
    {
    public:
        
        TEST_METHOD(TestMethod1)
        {
            ChessColor c = ChessColor::Black;
            std::string actual = &quot;B&quot;;
            std::string trying = getShortNameOfChessColor(&amp;c);
            Assert::AreEqual(actual,trying);
        }
    };
}
</code></pre>
<p>So the errors i get are these</p>
<pre><code>Error   LNK2019 unresolved external symbol &quot;class std::basic_string&lt;char,struct std::char_traits&lt;char&gt;,class std::allocator&lt;char&gt; &gt; __cdecl getShortNameOfChessColor(enum ChessColor *)&quot; (?getShortNameOfChessColor@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PEAW4ChessColor@@@Z) referenced in function &quot;public: void __cdecl ChessTest::ChessTest::TestMethod1(void)&quot; (?TestMethod1@ChessTest@1@QEAAXXZ)    ChessTest   C:\Users\censoredUsername\Desktop\prog\Chess\ChessProject\ChessTesting\ChessTest\ChessTest.obj  1
</code></pre>
<p>A few warnings</p>
<pre><code>Warning C26812  The enum type 'PieceType' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).    ChessProject    C:\Users\censoredUsername\Desktop\prog\Chess\ChessProject\ChessProject\MetaData.cpp 3
Warning C26812  The enum type 'ChessColor' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).   ChessProject    C:\Users\censoredUsername\Desktop\prog\Chess\ChessProject\ChessProject\MetaData.cpp 44  
Warning C26812  The enum type 'ChessColor' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).   ChessTest   C:\Users\censoredUsername\Desktop\prog\Chess\ChessProject\ChessTesting\ChessTest\ChessTest.cpp  14  
</code></pre>
<p>Error 2</p>
<pre><code>Error   LNK1120 1 unresolved externals  ChessTest   C:\Users\censoredUsername\Desktop\prog\Chess\ChessProject\x64\Debug\ChessTest.dll   1   
</code></pre>
<p>Some Extra info</p>
<p>I made a project, added some basic files and wanted to do a test driven development.<br />
Thus i added a Native Unit Test Project to my current Project.
Described here: <a href=""https://learn.microsoft.com/en-us/visualstudio/test/writing-unit-tests-for-c-cpp?view=vs-2022"" rel=""nofollow noreferrer"">MS Description to add unit tests</a></p>
<p>I coded in a lot of languages before, but have the most experience with java/c# (and as you know, these are very different to cpp)</p>
<p>I appreciate every comment/input for that matter.</p>
",https://stackoverflow.com/questions/72707644/problems-with-unit-testing-in-c-visual-studio-2022,"['c++', 'visual-studio', 'unit-testing', 'enums', 'include']",150,True,0,1
Not able set mock data for ShimSqlDataReader for integer and string field,"<p>I am using ShimSQLconnection to cover unit testing reading data form SQLDataReader with SQLConnection, here I am not able to set the mock data for ShimSqlDataReader for integer and string field.
I tried mock for each column index wise with ShimSqlDataReader.AllInstances.ItemGetInt32... but this code not mocking it, but same mock code when use reader[0] in actual code then the mocked data is coming, We don't know why mock data is not coming when we use reader.GetInt32(0) and reader.GetString(1)</p>
<p>Note: we can not change actual code, need to write unit test for actual code.
could you please check below code and help on this</p>
<p>C# code :</p>
<pre><code>public Customer GetArchivedCustomer(int customerId)
    {
        using (var sqlConnection = new SqlConnection(connectionString))
        {
            sqlConnection.Open();

            var command = new SqlCommand(&quot;SELECT Id, Name FROM Customer WHERE CustomerId = @customerId&quot;, sqlConnection) { CommandType = CommandType.Text };
            command.Parameters.AddWithValue(&quot;@customerId&quot;, customerId);

            using (var reader = command.ExecuteReader())
            {
                if (reader.Read())
                {
                    return new Customer { Id = reader.GetInt32(0), Name = reader.GetString(1) };
                }
            }
        }

        return null;
    }
</code></pre>
<p>Unit test code :</p>
<pre><code>using (ShimsContext.Create())
        {

            ShimSqlConnection.AllInstances.Open = connection =&gt; { };

            string commandText;
            ShimSqlCommand.AllInstances.ExecuteReader = command =&gt;
            {
                commandText = command.CommandText;
                return new ShimSqlDataReader();
            };

            int readCount = 0;

            ShimSqlDataReader.AllInstances.Read = (sender) =&gt;
            {
                readCount++;
                return readCount &lt;= 1;
            };
            
            ShimSqlDataReader.AllInstances.ItemGetInt32 = (reader, i) =&gt;
            {
                switch (i)
                {
                    case 0:
                        return 1;
                    case 1:
                        return &quot;cool customer&quot;;
                    default:
                        return DateTime.Now;
                }

            };

            IArchivedDataService archivedDataService = new ArchivedDataService();
            var result = archivedDataService.GetArchivedCustomer(1);
            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(Customer));
        }
</code></pre>
<p>Appreciate all your help</p>
",https://stackoverflow.com/questions/73274408/not-able-set-mock-data-for-shimsqldatareader-for-integer-and-string-field,"['c#', 'unit-testing', 'mstest', 'shim']",63,False,0,0
Jest/ExpressJS - TypeError: Cannot read properties of undefined - Inner https.request call set to const var - var.on after https call can&#39;t be read,"<p>Can't get the last four lines in the helpers.js below to run for the test. The webpage works great, but I can't get the tests to pass/the mocks correct. This is my first time using Jest and unit testing in general, so there may be a fundamental understanding issue as well.</p>
<p>Function in helpers.js</p>
<pre><code>exports.get_logout = (req, resp) =&gt; {
  // sent to backend
  const options = {
    hostname: backend_hostname,
    port: backend_port,
    method: 'POST',
    path: '/api/logout',
    ca: ca,
    headers: {
      'Content-Type': 'application/json',
    }
  };
  // set cookie
  options.headers.Cookie = `ws_sid=${req.cookies.ws_sid}`

  // send to backend to end session
  const https_req = https.request(options, (response) =&gt; {
    const response_status = response.statusCode;
    const response_headers = response.headers;

    response.on('data', (d) =&gt; {
      process.stdout.write(d);
    });

    response.on('end', () =&gt;{
      switch (response_status) {
        case 200:
          console.log('Successfully logged out')
          resp.clearCookie('ws_sid', {path: '/'})
          resp.redirect('/')
          break;
        case 400:
          console.log('Error on logout!')
          resp.redirect('/');
          break;
        case 403:
          console.log('User not logged in!')
          resp.redirect('/');
          break;
      }
    })
  });

  https_req.on('error', (e) =&gt; {
    console.error(e);
  });
  
  https_req.write(JSON.stringify({}))
  https_req.end();
}
</code></pre>
<p>the issue in website.test.js, is that the https_req.on is giving a TypeError:Cannot read properties of undefined (reading 'on')</p>
<p>Test here:</p>
<pre><code>const helpers = require('./helpers');
const https = require('node:https'); 

// Mock for express request parameter 
let mockRequest = (sessionData, method, body) =&gt; {
  return {
    session: { data: sessionData, cookie: {_expires: 'test_expire'}},
    method: method,
    body: {username:&quot;&quot;, password:&quot;&quot;},
    cookies: {ws_sid:&quot;&quot;},
  };
};

// Mock for express response parameter
let mockResponse = () =&gt; {
  const res = {};
  res.status = jest.fn().mockReturnValue(res);
  res.json = jest.fn().mockReturnValue(res);
  res.send = jest.fn().mockReturnValue(res);
  res.sendStatus = jest.fn().mockReturnValue(res)
  res.render = jest.fn().mockReturnValue(res)
  res.redirect = jest.fn().mockReturnValue(res)
  return res;
};


jest.mock('https');
https.request = jest.fn();
https.on = jest.fn();
https.end = jest.fn();


test('should redirect to / if user successfully logged out', async () =&gt; {
  const req = mockRequest({ 'username': 'all' });
  const resp = mockResponse();
  helpers.get_logout(req, resp);
  expect(resp.redirect).toHaveBeenCalledWith('/');
});
</code></pre>
<p>Any help greatly appreciated.</p>
<p>I have tried mocking the https_req object - but kept getting errors with the implementation (not a function, can't access before initialization). I tried adding the https_req object to the mockRequest with (on, end) but got the same TypeError</p>
",https://stackoverflow.com/questions/74417462/jest-expressjs-typeerror-cannot-read-properties-of-undefined-inner-https-re,"['express', 'jestjs']",52,False,0,0
Testing a serviceworker using Workbox,"<p>I have made an implementation of a service working using Google's Workbox library and I want to test my custom route handlers and logic, but I am really unsure how I can best test this. The tests should be performed in the browser because I will need to verify if the cache or my database has been modified. I also load in my custom route and handlers via a config file, so I need to make sure the correct routes are registered.</p>
<p>Can somebody help me point in the right direction? I have tried unit testing with Jest, but I could make the functions work which use parts of the Workbox library.</p>
",https://stackoverflow.com/questions/71938891/testing-a-serviceworker-using-workbox,"['service-worker', 'workbox']",251,True,0,1
xUnit with SQLite in memory test,"<p>I want to use SQLite for unit testing and I have noticed that it load the real database data.
The whole databse (fortunatelly it is not so big) is in the context before seeding it.
First I did not understand why it throws a <strong>SQLite Error 19: 'UNIQUE constraint failed</strong> error at seeding but than I noticed this wierd thing.</p>
<p>Am I wrong or it is right?</p>
<p><strong>Update</strong></p>
<p>It seems to me that SQLite preserves data after debug process is finished.
How can I ensure that SQLite is deleted after each debugging process, please?</p>
<p><strong>Update</strong>
Oh, the seed method of real db context load data into SQLite in memory database at each time when I run test.</p>
",https://stackoverflow.com/questions/70679721/xunit-with-sqlite-in-memory-test,"['sqlite', 'xunit']",217,False,0,1
Moq mocking EF DbContext,"<p>I have a Repository pattern that interacts with Entity Framework.
I'd like to run some unit tests on the repository, and for this reason, I would like to mock DbContext.</p>
<p>So I've created a unit test project (.Net Core 3.1), using Moq as package for unit testing, everything seems to be ok, but when I perform a .ToListAsync() on my repository it throws the following exception:</p>
<blockquote>
<p>System.NotImplementedException : The method or operation is not
implemented.   Stack Trace: 
IAsyncEnumerable.GetAsyncEnumerator(CancellationToken cancellationToken)
ConfiguredCancelableAsyncEnumerable<code>1.GetAsyncEnumerator() EntityFrameworkQueryableExtensions.ToListAsync[TSource](IQueryable</code>1
source, CancellationToken cancellationToken)</p>
</blockquote>
<p>The source code:</p>
<pre><code>public class Customer
{
    public Guid Id { get; set; }

    public string Name { get; set; }
}

public class CustomersDbContext : DbContext
{
    public virtual DbSet&lt;Customer&gt; Customers { get; set; }

    public CustomersDbContext(DbContextOptions&lt;Customer&gt; options) : base(options) { }
}

public interface ICustomerRepository
{
    Task&lt;IEnumerable&lt;Customer&gt;&gt; GetCustomersAsync(Guid? customerId);
}
public class CustomerRepository : ICustomerRepository
{

    private readonly CustomersDbContext _dbContext;

    public CustomerRepository(CustomersDbContext dbContext)
    {
        _dbContext = dbContext;

        _dbContext.Database.EnsureCreated();
    }

    public async Task&lt;IEnumerable&lt;Customer&gt;&gt; GetCustomersAsync(Guid? customerId)
    {
        IEnumerable&lt;Customer&gt; customers = null;

        if (customerId.HasValue)
        {
            var customer = await _dbContext.Customers.FindAsync(new object[] { customerId.Value }, CancellationToken.None);

            if (customer != null)
                customers = new List&lt;Customer&gt;() { customer };
        }
        else
        {
            customers = await _dbContext.Customers.ToListAsync(CancellationToken.None);
        }

        return customers;
    }
}


public class CustomerServiceUnitTests
{
    private Mock&lt;CustomersDbContext&gt; GetCustomerDbContextMock()
    {
        var data = new List&lt;Customer&gt;()
        {
            new Customer()
            {
                Id = Guid.NewGuid(),
                Name = &quot;Name 1&quot;
            },
            new Customer()
            {
                Id = Guid.NewGuid(),
                Name = &quot;Name 2&quot;
            }
        }.AsQueryable();

        var mockSet = new Mock&lt;DbSet&lt;Customer&gt;&gt;();
        mockSet.As&lt;IQueryable&lt;Customer&gt;&gt;().Setup(m =&gt; m.Provider).Returns(data.Provider);
        mockSet.As&lt;IQueryable&lt;Customer&gt;&gt;().Setup(m =&gt; m.Expression).Returns(data.Expression);
        mockSet.As&lt;IQueryable&lt;Customer&gt;&gt;().Setup(m =&gt; m.ElementType).Returns(data.ElementType);
        mockSet.As&lt;IQueryable&lt;Customer&gt;&gt;().Setup(m =&gt; m.GetEnumerator()).Returns(data.GetEnumerator());

        var optionsBuilder = new DbContextOptions&lt;CustomersDbContext&gt;();

        var mockContext = new Mock&lt;CustomersDbContext&gt;(optionsBuilder);

        Mock&lt;DatabaseFacade&gt; databaseFacade = new Mock&lt;DatabaseFacade&gt;(mockContext.Object);
        databaseFacade.Setup(d =&gt; d.EnsureCreatedAsync(CancellationToken.None)).Returns(Task.FromResult(true));

        mockContext.Setup(c =&gt; c.Database).Returns(databaseFacade.Object);
        mockContext.Setup(c =&gt; c.Customers).Returns(mockSet.Object);

        return mockContext;
    }

    [Fact]
    public async Task Infrastructure_CustomerRepository_GetAll()
    {

        var mockContext = this.GetCustomerDbContextMock();

        ICustomerRepository customerRepository = new CustomerRepository(mockContext.Object);

        var customers = await customerRepository.GetCustomersAsync(null);

        Assert.NotNull(customers);
        Assert.Equal(2, customers.Count());
    }
}
</code></pre>
<p>If I send an ID filled to the repository it works fine, so this seems to be not ok only for .ToListAsync().</p>
<p>I'm kinda stuck here, what can I do to overcome this?</p>
",https://stackoverflow.com/questions/71228582/moq-mocking-ef-dbcontext,"['c#', 'unit-testing', 'moq']",3588,True,0,2
Unit testing component text -- philosophy,"<p>I'm a bit new to unit testing, and I've really only tested methods and things. I'm curious about components like <code>&lt;h1&gt;text&lt;/h1&gt;</code> Is it common to unit test the value inside h1? I understand that it would be useful to see in the tests that it has changed, and that the test knows, similar to knowing if any other method or item has changed. But it seems like a lot of work to unit test every line of text in a project. Thoughts? Is it common to unit test text? I understand how framework pieces like Vuetify or React-bootstrap it would be vital to making sure it is rendered in the correct spots, but is it useful in standard projects</p>
",https://stackoverflow.com/questions/71773164/unit-testing-component-text-philosophy,['unit-testing'],39,True,-1,1
How to test NotFound in WebAPI using xUNit,"<p>I am having a Web API method which is taking two inputs as <code>string</code> and returning output. I have performed below steps to to a unit testing using xUnit.</p>
<ol>
<li>Created xUnit project and added one method to it.</li>
<li>Creating a mock data using <code>AutoFixure</code>.</li>
<li>Added test code and running the test <strong>without running</strong> <strong>API project</strong>. Am I doing this right here? Do I need to run API project as well?</li>
<li>My test is giving me result instead of NoDataFound. When I am running a test case from Postman, I am getting expected <code>404 error</code> but in xUnit, getting object with count 3.</li>
</ol>
<p>I am not sure where and what I am missing. Any help please. TIA.
Below is my code.</p>
<pre><code>public class ControllerTest
{
    private readonly IFixture fixure;
    private readonly Mock&lt;ICustomerService&gt; service;;
    private readonly CustController  controller;

    public CustControllerTest()
    {
        service = new Mock&lt;ICustomerService&gt;();
        controller = new CustController(service.Object);
        fixure = new Fixture();
    }

    [Fact]
    public async Task GetMember_WithZeroAsInput_ShouldReturnNotFound()

    {

        //arrange
            var member = fixure.Create&lt;List&lt;Member&gt;&gt;();//creating a mock for Member object
            var Id = Convert.ToString(0); //0 as input
            var name = Convert.ToString(0);//0 as input

            service.Setup(x =&gt; x.GetMember(Id, name)).ReturnsAsync(member);//here I am getting 3 record count even my both inputs are 0

            //act
            var result = await CustController.GetMember(Id, name);//here also I am getting 3 record count even my both inputs are 0.
                //when I am calling GetMember from Postman with 0 as inputs I am getting NotFound result. 

            //assert
            result.Should().NotBeNull();
            result.Result.Should().BeAssignableTo&lt;NotFoundObjectResult&gt;();//getting error here as - Expected memberFlagResult.Result to be assignable to Microsoft.AspNetCore.Mvc.NotFoundObjectResult, but Microsoft.AspNetCore.Mvc.OkObjectResult is not.
            result.Verify(x =&gt; x.GetMember(memberId, flagName), Times.Once());
        
    }
}```
</code></pre>
",https://stackoverflow.com/questions/74152856/how-to-test-notfound-in-webapi-using-xunit,"['.net', 'unit-testing', 'asp.net-web-api', 'xunit', 'autofixture']",30,False,0,1
How to mock a function of a class in an imported module but outside the scope of a function?,"<p>I am trying to figure out how to use the <code>@patch.object</code> to mock a <code>__init__</code> and, <code>log.write()</code> for the <code>Logger</code> class, which is imported but isn't used inside the function of a module. The tuorial such as this, <a href=""https://www.pythontutorial.net/python-unit-testing/python-patch/"" rel=""nofollow noreferrer"">https://www.pythontutorial.net/python-unit-testing/python-patch/</a>
, points to the patching needs to be at the target where it is used, not where it comes from. However, every example used shows the target to be mocked inside another function.</p>
<p>In the use case mentioned below, the logger is imported and used to write the log outside the scope of a function. Is there a way to mock the behavior both in <code>main.py</code> and <code>routers.py</code>?</p>
<p><strong>src/apis/main.py</strong></p>
<pre><code>from utils.log import Logger
from routes import route

log = Logger(name=&quot;logger-1&quot;)
log.write(&quot;logger started&quot;)

def main():
    log = Logger(name=&quot;logger-1&quot;)
    log.write(&quot;inside main&quot;)
    route()

if __name__ == &quot;__main__&quot;:
    import logging
    logging.basicConfig(level=logging.INFO)  # for demo
    main()
</code></pre>
<p><strong>In src/apis/routers/routes.py</strong></p>
<pre><code>from utils.log import Logger
log = Logger(name=&quot;logger-1&quot;)
log.write, message=f&quot;Inside route&quot;)
def route():
    log.write, message=f&quot;Logging done.&quot;)
</code></pre>
<p><strong>In utils/log/logging.py</strong></p>
<pre><code>import logging
Class Logger:
     def __init__(self, name):
          # needs to be mocked

     def write(self, message):
          # needs to be mocked to return None
</code></pre>
",https://stackoverflow.com/questions/74695297/how-to-mock-a-function-of-a-class-in-an-imported-module-but-outside-the-scope-of,"['python', 'unit-testing', 'python-unittest', 'python-mock', 'python-unittest.mock']",326,True,0,1
Rails 7.0.4 API App with Devise throwing DisabledSessionError,"<p>I am developing a Rails 7.0.4 API only application where I am using Devise to log in a Cinema owner to update and edit cinema's billboard.</p>
<p>I am facing an error when simple testing with MiniTest:</p>
<pre class=""lang-rb prettyprint-override""><code>test &quot;should get index&quot; do
  sign_in users(:one)
  get movies_url, as: :json
  assert_response :success
end
</code></pre>
<pre><code>Minitest::UnexpectedError: ActionDispatch::Request::Session::DisabledSessionError: Your application has sessions disabled. To write to the session you must first configure a session store
    test/controllers/movies_controller_test.rb:11:in `block in &lt;class:MoviesControllerTest&gt;'
test/controllers/movies_controller_test.rb:11:in `block in &lt;class:MoviesControllerTest&gt;'
</code></pre>
<p>I have already searched for this issue on Github on this link (<a href=""https://github.com/heartcombo/devise/issues/5443"" rel=""nofollow noreferrer"">https://github.com/heartcombo/devise/issues/5443</a>) and I have already tried to have in application.rb the following:</p>
<pre class=""lang-rb prettyprint-override""><code>config.session_store :cookie_store, key: '_interslice_session'
config.middleware.use ActionDispatch::Cookies
config.middleware.use config.session_store, config.session_options
</code></pre>
<p>and also I have tried to have this fix</p>
<pre class=""lang-rb prettyprint-override""><code>module RackSessionFixController
  extend ActiveSupport::Concern

  class FakeRackSession &lt; Hash
    def enabled?
      false
    end
  end

  included do
    before_action :set_fake_rack_session_for_devise
    
    private

    def set_fake_rack_session_for_devise
      request.env['rack.session'] ||= FakeRackSession.new
    end
  end
end
</code></pre>
<p>but it does not work either. Note this happens only when unit testing with MiniTest. I am testing a controller (Movies) in which is required to be logged in to make any operations (such as create, update and delete).</p>
",https://stackoverflow.com/questions/74687302/rails-7-0-4-api-app-with-devise-throwing-disabledsessionerror,"['ruby-on-rails', 'ruby', 'api', 'devise', 'minitest']",69,False,0,0
How to create application scope for nunit for ASP.NET Core 3.1 project,"<p>I'm new to unit testing and I think I need to get the application scope of my ASP.NET Core 3.1 web so that I can get some scoped services to use in testing.</p>
<p>Question: how do I get the app object so that I can get the scope?</p>
<p>The error I'm seeing is</p>
<blockquote>
<p>Cannot resolve scoped service 'className' from root provider.</p>
</blockquote>
<p>From the Google searches, I think I see that the problem is that <code>className</code> is created in the application's <code>ConfigureServices</code> method in <code>Startup.cs</code> with <code>services.AddScoped&lt;className&gt;()</code>.</p>
<p>I believe the problem is that Nunit doesn't run in the same scope(?) as the application being tested (not sure).</p>
<p>At any rate, how do I get the app in the nunit test framework?</p>
<p>TIA,</p>
<p>Owen</p>
",https://stackoverflow.com/questions/74237713/how-to-create-application-scope-for-nunit-for-asp-net-core-3-1-project,"['nunit', 'asp.net-core-3.1']",63,False,0,1
Unit Testing Vue with Jest and Vue Test Utils,"<p>I'm brand new at Unit Testing with vue.
I'm trying to unit test a navigation vue component. I started out easy, I just wanted to test a method that just makes a boolean false(triggered by an on click). I am also using vuetify. I somewhat managed to mimic a button and then my hope is that the variable I'm passing (showLoginDrawer) returns false in my unit test. My error is TypeError: _vm.is.has is not a function which relates to a different part of my code, I think I'm missing something but I couldn't find anything online about it.</p>
<p>Below I've included the component and my testing file.</p>
<pre><code>//Nav.vue
&lt;template&gt;
  &lt;v-btn
        :to=&quot;{ name: 'home' }&quot;
        aria-label=&quot;Home button&quot;
        @click=&quot;hideDiv()&quot;
   &gt;
   &lt;/v-btn&gt;

      &lt;div&gt;
        &lt;transition name=&quot;nav-fade&quot;&gt;
          &lt;component v-bind:is=&quot;drawerSection&quot;&gt;&lt;/component&gt;
        &lt;/transition&gt;
      &lt;/div&gt;

&lt;/template&gt;
&lt;script&gt;
     data() {
      return {
        drawerSection: function () {
          if (this.is.has('learning')) {
            return 'nav-learning'
          } else {
            return 'nav-explore'
          }
        },
      }
    },
    methods: {
      hideDiv() {
        if (!this.appState.restrictedAccessAlert)
          this.appState.showLoginDrawer = false
      }
}
&lt;/script&gt;
&lt;style&gt;//disregard&lt;/style&gt;

</code></pre>
<pre><code>//Nav.spec.js
import Vue from 'vue'
import Vuex from 'vuex'
import Vuetify from 'vuetify'
import { shallowMount, mount } from '@vue/test-utils'
import Nav from '@/components/Nav'


const localVue = createLocalVue()
localVue.use(Vuetify)
localVue.use(Vuex)

describe('Testing Nav component', () =&gt; {
    let vuetify
    beforeEach(() =&gt; {
      vuetify = new Vuetify()
    })
    test('Test Button click when logged out', () =&gt; {
    const wrapper = mount(Navigation, {
      data() {
        return {
          appState: {
            showLoginDrawer: true,
            lastCapabilityPath: '',
            restrictedAccessAlert: false,
          },
          is: 'learning',
          localVue,
          vuetify,
        }
      },
    })

    const event = jest.fn()
    const button = wrapper.findAll('.v-btn').at(0)
    expect(button.text()).toContain('My Profile')

    button.vm.$on('click', event)
    expect(event).toHaveBeenCalledTimes(0)
    expect(wrapper.vm.showLoginDrawer).toBeTruthy()
    button.trigger('click')
    expect(event).toHaveBeenCalledTimes(1)
    expect(wrapper.vm.showLoginDrawer).toBeFalsy()
  })
})
</code></pre>
<p>I get the error:</p>
<p><code>TypeError: _vm.is.has is not a function</code></p>
<p>Thank you for any help!</p>
",https://stackoverflow.com/questions/71712969/unit-testing-vue-with-jest-and-vue-test-utils,"['javascript', 'vue.js', 'unit-testing', 'jestjs', 'vue-test-utils']",846,True,0,2
Nestjs - Unit testing for a controller that is inherited from CrudController,"<p>I am doing a unit testing script for a controller file for an API called promotions.controller.ts. However, I am not sure why my controller file is not instantiating the service file that I mock using jest in its constructor and throwing the error of:</p>
<p><strong>TypeError: Cannot read property 'findOne' of undefined.</strong></p>
<p>findOne is one of the function that exist in my promotions.service.ts and it is also extended from a CrudService which is a parent class of this service.</p>
<p>I have already tried to mock a class and spyOn to mock the PromotionService but it is still not working.</p>
<p>This is the code for <strong>promotions.controller.spec.ts</strong>:</p>
<pre><code>import { PromotionsService } from &quot;../promotions.service&quot;;
import {PromotionsController} from &quot;../promotions.controller&quot;
import { Test, TestingModule } from &quot;@nestjs/testing&quot;
import {OrganizationsService} from &quot;../../organizations/organizations.service&quot;

describe('PromotionsController', () =&gt; {
    let promotionsController: PromotionsController;
    let promotionsService: PromotionsService;

    jest.mock(&quot;../promotions.service&quot;);

    const mockOrganizationsService = {
    }

    const mockPromotionsService = {
        
    };
    

    beforeEach(async () =&gt; {
      const moduleRef = await Test.createTestingModule({
          controllers: [PromotionsController],
          providers:[PromotionsService,OrganizationsService]
        }).overrideProvider(PromotionsService).useValue(mockPromotionsService)
          .overrideProvider(OrganizationsService).useValue(mockOrganizationsService)
          .compile();
  
      promotionsService = moduleRef.get&lt;PromotionsService&gt;(PromotionsService);
      promotionsController = moduleRef.get&lt;PromotionsController&gt;(PromotionsController);

      const promotions = await promotionsController.performDelete({id:'1234'});
    });
  
    describe('promotionsController', () =&gt; {

      it('controller should be defined', async () =&gt; {
        expect(promotionsController).toBeDefined();
      });

      it('service should be defined', async () =&gt; {
        expect(promotionsService).toBeDefined();
      });

      it('promotionsController should be calling performDelete', async () =&gt; {
        expect(promotionsController.performDelete({id:'1234'})).not.toEqual(null);
        expect(promotionsService.find).toHaveBeenCalled();
      })

    });
  });

</code></pre>
<p>This is the code at my <strong>promotions.controller.ts</strong>:</p>
<pre><code>import { Controller } from '@nestjs/common';
import {ApiBearerAuth} from &quot;@nestjs/swagger&quot;;
import {Crud} from &quot;../ms-common/utils/crud/crud.decorator&quot;;
import {Promotion} from &quot;./promotions.model&quot;;
import {PromotionsDto} from &quot;./dto/promotions.dto&quot;;
import {CrudController} from &quot;../ms-common/utils/crud/crud.controller&quot;;
import {PromotionsService} from &quot;./promotions.service&quot;;
import {OrganizationsService} from &quot;../organizations/organizations.service&quot;;

@ApiBearerAuth()
@Crud({
  model: Promotion,
  routes: {
    create: {dto: PromotionsDto},
    update: {dto: PromotionsDto},
  },
})

@Controller('promotions')
export class PromotionsController extends CrudController {
  constructor(public model: PromotionsService, private organization: OrganizationsService) {
    super(model);
  }

  async performDelete(id) {
    const instance = await this.model.findOne({id});
    await this.organization.sbQueue({
      type: &quot;promotion&quot;,
      ids: [id],
      delete: true,
      organization: instance.organization,
    });
    return super.performDelete(id);
  }
}

</code></pre>
<p>Anyone knows how should I resolve this issue?</p>
",https://stackoverflow.com/questions/73122762/nestjs-unit-testing-for-a-controller-that-is-inherited-from-crudcontroller,"['typescript', 'unit-testing', 'nestjs']",198,True,0,1
Best approach for testing a http post service within a void method?,"<p>I am pretty new into unit testing and I am struggling to know how to test a void method in service that contains an http post. I am not looking for code solution on spec.ts, just any clue or idea to get the best approach for this. What I have read on internet it was not very useful at the moment for me. Thank you very much in advance, you guys are an awesome community!</p>
<p>So this is my member-add.service.ts:</p>
<pre><code>import { Injectable } from &quot;@angular/core&quot;;
import {
  HttpClient,
  HttpHeaders,
  HttpErrorResponse,
} from &quot;@angular/common/http&quot;;
import { MemberContact } from &quot;src/app/models/member-contact/member-contact.interface&quot;;
import { throwError, catchError } from &quot;rxjs&quot;;
import { Router } from &quot;@angular/router&quot;;

@Injectable({
  providedIn: &quot;root&quot;,
})
export class MemberAddService {
  private _membersUrl: string = &quot;http://localhost:8080/api/members&quot;;
  private _http: HttpClient;
  private _newMember: MemberContact;

  constructor(http: HttpClient, private router: Router) {
    this._http = http;
  }

  postMemberContactInfo(
    memberContactInfo: MemberContact,
    callback: Function,
    errorCallback: Function
  ) {
    this._http
      .post&lt;MemberContact&gt;(this._membersUrl, memberContactInfo, {
        headers: new HttpHeaders({ &quot;Content-Type&quot;: &quot;application/json&quot; }),
        responseType: &quot;json&quot;,
        observe: &quot;body&quot;,
      })
      .subscribe({
        next: (value) =&gt; {
          this._newMember = value;
        },
        complete: () =&gt; {
          this.router.navigate([`/members/${this._newMember.id}`], {
            state: this._newMember,
          });
          callback(this._newMember);
          console.log(this._newMember);
        },

        error: (error) =&gt; {
          catchError(this.handleError);
          errorCallback(error);
          console.log(this._newMember);
        },
      });
  }

  private handleError(error: HttpErrorResponse) {
    if (error.status == 0) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error(&quot;An error occurred:&quot;, error.error);
    } else {
      // The backend returned an unsuccessful response code.
      // The response body may contain clues as to what went wrong.
      console.error(
        `Backend returned code ${error.status}, body was: `,
        error.error
      );
    }
    // Return an observable with a user-facing error message.
    return throwError(
      () =&gt; new Error(&quot;Something bad happened; please try again later.&quot;)
    );
  }
}
</code></pre>
<p>As you can see, there is an only method which sets a callback to the component if the new member insertion is succesful or not. How I can test this if nothing is returned?</p>
",https://stackoverflow.com/questions/71169659/best-approach-for-testing-a-http-post-service-within-a-void-method,"['angular', 'unit-testing', 'karma-jasmine', 'typescript2.0']",652,False,0,1
JUnit Testing: Declaring String input as input parameter with .csv file using @CsvFileSource,"<p>I'm trying to write some JUnit test with @CsvFileSource to mimic the unit testing input procedure of Codility/Leetcode, where the test case inputs for String datas are written as [1,2,...]. However, I am not sure how to represent this in JUnit itself.</p>
<p>This is my sample testcase.csv file which contains the set of input parameters:</p>
<pre><code>input_array, expected_answer
[1,2,3,5,6], 2
</code></pre>
<p>and this my sample unit test method:</p>
<pre><code>  @ParameterizedTest
  @CsvFileSource(resources = &quot;/testcase.csv&quot;)
    void CodilityDemoTest_Attempt2(@ ConvertWith( ??? ) int[] input, int expected) {
    assertEquals(expected, Attempt2.solution(input));
    }
</code></pre>
<p>I've explored @ArgumentsConverter and @ConverterWith annotations and I guess I should use them to &quot;format&quot; the inputs from the .csv file when I pass the parameters into the test method, but I am not sure how to do so exactly. Any tips on how to pass the argument from the unit test properly with @CsvFileSource?</p>
",https://stackoverflow.com/questions/74315964/junit-testing-declaring-string-input-as-input-parameter-with-csv-file-using-c,"['java', 'unit-testing', 'testing', 'junit', 'junit5']",113,False,0,0
Verify method of Mockito library not working as expected when counting number of invocations of method,"<p>I created a springboot application that has this test method in which I check if deleting a city record through a service to which I applied @InjectMocks annotation and a repository I mocks works properly.</p>
<pre><code>@Test
public void test_deleteCity()
{
    String cityName=&quot;New York&quot;;
    City city=new City(cityName);
    
    
    cityService.deleteCity(cityName);
    verify(cityRepository,times(1)).delete(city);
    
}
</code></pre>
<p>This is the the deleteCity method within the service:</p>
<pre><code>public boolean deleteCity(String cityName) {
    
    if(cityRepository==null &amp;&amp; !cityRepository.existsByCityName(cityName))
        return false;
    cityRepository.delete(new City(cityName));
    return true;
}
</code></pre>
<p>Now, for some reason according to the verify method in the test, the delete method of the repository was not called at all because the unit testing ended with 1 failure, even though it was called ( I know so because I printed something after the line it was called, like this:</p>
<pre><code>    @Override
public boolean deleteCity(String cityName) {
    
    if(cityRepository==null &amp;&amp; !cityRepository.existsByCityName(cityName))
        return false;
    cityRepository.delete(new City(cityName));
    System.out.println(&quot;This is a check message&quot;);
    return true;
}
</code></pre>
<p>and this was actually printed )</p>
<p>Can anyone tell me why the verify method doesn't work as expected?</p>
",https://stackoverflow.com/questions/72629312/verify-method-of-mockito-library-not-working-as-expected-when-counting-number-of,"['spring-boot', 'unit-testing', 'mockito']",123,False,0,0
Cannot load image in Google Test,"<p>I'm trying to do unit testing with Google Test for a university project, and I created a test with a tile (I'm making a platform game with a tileMap) and a player to check if the player collides with it. The test passed, but the texture of the tile was not loaded (&quot;Failed to load &quot;../images/wall.png&quot;. Reason: unable to open file). I also tried to set the directory of my project as the working directory in Google Test, but nothing changed. It works only if the image is loaded directly in the constructor of the test. How could I fix this? Here is the method I use to load the texture:</p>
<pre><code>bool LevelTile::setupSprite(char tile) {

    std::string textureName;

    switch(tile){

        case '2':
            textureName = &quot;../images/door.png&quot;;
            exit = true;
            tileType = DOOR;
            break;
        case '0':
            textureName = &quot;../images/Ground.jpg&quot;;
            tileType = GROUND;
            break;
        case '1':
            textureName = &quot;../images/wall.png&quot;;
            tileType = WALL;
            break;
        default:
            textureName = &quot;&quot;;

    }

    if(!texture.loadFromFile(textureName))
        return false;

    texture.setSmooth(true);
    body.setFillColor(sf:: Color::White);
    body.setTexture(&amp;texture);
    //temporary texture cut for testing
    body.setTextureRect(sf::IntRect(0,0,50,50));
    return true;

</code></pre>
",https://stackoverflow.com/questions/73728153/cannot-load-image-in-google-test,"['c++', 'c++14', 'sfml']",60,False,0,0
GCOV - include header files in code coverage report,"<p>I am quite new to Ceedling and unit testing, so bear with me for a moment ...</p>
<p>The code that I am testing contains macros in a header file in the form:</p>
<pre><code>#define DO_Something_with_a_MCU_Registers() \
        (&lt;does_something_on_a_MCU_register&gt;)
</code></pre>
<p>The written unit tests are currently working. However I would like to have a coverage report with GCOV for this particular header file. At the moment the GCOV report is empty.
What I would like to see/prove is that my tests are executing the macros. I do understand this poses a challenge, as the macros are included in the unit test as part of the pre-processor. But I would like to hear if there are other options or ideas?</p>
",https://stackoverflow.com/questions/73727370/gcov-include-header-files-in-code-coverage-report,"['embedded', 'microcontroller', 'gcov', 'ceedling']",94,False,0,0
"can we mock private , static method in java 11 without powermock since powermock not support java 11","<p>I have legacy code and i am using power mock for mocking the private and static method but power mock does not support java 11. I want to use some other tools or any workaround to mock the private and static method in my project. i am aware that testing of the private method is bad Unit testing.
I have tried the reflection way of writing the Unit test case in place of powermock but I did not have much success on that.I heard of JMockito as the other option but due to some issue, we can not go for JMockito.
Please suggest if any other feasible solution I can use to mock this ?</p>
",https://stackoverflow.com/questions/71380077/can-we-mock-private-static-method-in-java-11-without-powermock-since-powermock,"['java', 'powermock']",584,False,0,0
How to simulate user intercation in Django?,"<p>I have a Django project representing an abstract retail store. Let's say it's deployed on a server and is available in the local network. I want to write another program (or extend this one?) to generate a bunch of Users, automate the process of signing up and logging in and automate their interaction with the system: make them interact with the system to order goods. So it's not just unit testing of my system but rather demonstration of how it works in real life. And I want to spawn many users to see how my system can handle many requests at once.
Is there some kind of framework for that? How would you implement this? Thanks.</p>
",https://stackoverflow.com/questions/72431493/how-to-simulate-user-intercation-in-django,"['django', 'automation', 'simulation']",37,True,0,1
Preventing use of global variables in Flask Blueprints to improve unit tests,"<h2>Problem</h2>
<p>I'm seeing examples that use global variables in Blueprints to store objects used by the Blueprint. However, this causes problems in unit-testing in case multiple instances of an application are created.</p>
<p>To illustrate, below is an example where parsed files are cached, based on a setting during blueprint initialization (Note: I know there are many issues with the below code, it's just an example):</p>
<pre class=""lang-py prettyprint-override""><code>
from pathlib import Path
import json
from flask import Blueprint, jsonify
from whatevermodule import JSONFileCache

bp = Blueprint('cached_file_loader', __name__, url_prefix='/files')

json_cache = JSONFileCache()

@bp.record
def init(setup_state):
    if not setup_state.options['use_caching']:
        json_cache.disable()

@bp.route('/&lt;path:path&gt;')
def view_json(path):
    localpath = Path('/tmp', path.lstrip('/'))
    data = json_cache.get(localpath)
    if data is None:
        with open(localpath, 'r') as jsonfile:
            data = json.load(jsonfile)
            json_cache.set(localpath, data)
    return jsonify(data)
</code></pre>
<p>The problem is, in this example a global variable 'json_cache' is used. This means if I create multiple instances of an app with this blueprint, using different caching settings, these will interfere, causing tests to fail.</p>
<h2>What I've tried/considered</h2>
<ol>
<li>Keep using global variables, and just use one application per test file. This actually what I'm using currently. However,
since pytest collects all tests in one process, I have to do <code>find ./tests -iname &quot;test_*.py&quot; -print0 | xargs -0 -n1 pytest</code>
to make sure everything runs .</li>
<li>Storing the objects (in this case the json_cache) on the Blueprint instance. This is however not   possible, since the 'bp' variable is also a global variable, that will be reused...</li>
<li>Inside the 'init' function, storing the objects inside <code>setup_state.app.config</code>. This should
work, since this variable is initialized per application. The
<a href=""https://flask.palletsprojects.com/en/1.1.x/config/"" rel=""nofollow noreferrer"">docs</a> for configuration handling actually
say:</li>
</ol>
<blockquote>
<p>That way you can create multiple instances of your application with different configurations
attached which makes unit testing a lot easier.</p>
</blockquote>
<p>Although option (3) should work, it looks very 'hacky' to me to store functional objects inside a dictionary marked as 'config', where I would only expect configuration variables.</p>
<h2>Question</h2>
<p>Is there a better way, that looks less 'hacky' that option (3), to store objects used inside blueprints, at the app level during intialization?</p>
",https://stackoverflow.com/questions/74491903/preventing-use-of-global-variables-in-flask-blueprints-to-improve-unit-tests,"['python', 'flask']",25,False,0,0
"Jest, ES6 modules &quot;does not provide export named&quot;","<p>I have an express app with a CRUD API (with sequelize) and I want to test it with Jest. I'm pretty new in unit-testing so I follow this <a href=""https://www.albertgao.xyz/2017/05/24/how-to-test-expressjs-with-jest-and-supertest/"" rel=""nofollow noreferrer"">guide</a>, recommended by <a href=""https://jestjs.io/docs/testing-frameworks#expressjs"" rel=""nofollow noreferrer"">Jest's website</a>.</p>
<p>The problem I have is that my app is built with ES6 modules and Jest ES6 modules is experimental and it seems that it doesn't &quot;import&quot; packages.</p>
<p>I have this test <em>(took from the guide)</em></p>
<pre class=""lang-js prettyprint-override""><code>import request from 'supertest';
import app from '../app';

describe('Test the root path', () =&gt; {
    test('It should response the GET method', done =&gt; {
        request(app)
            .get('/')
            .then(response =&gt; {
                expect(response.statusCode).toBe(404);
                done();
            });
    });
});
</code></pre>
<p>And when I launched it (with <code>NODE_OPTIONS=--experimental-vm-modules npx jest</code> I had to follow this <a href=""https://jestjs.io/docs/ecmascript-modules"" rel=""nofollow noreferrer"">jest wiki page</a>), It says that</p>
<p><code>'sequelize' does not provide an export named 'DataTypes'</code> and when I launch my app normally (like with <code>npm start</code>) it works fine, without any problems.</p>
<p><em>(the complete error log):</em></p>
<pre><code>(node:49576) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  __tests__/app_test.js
  ● Test suite failed to run

    SyntaxError: The requested module 'sequelize' does not provide an export named 'DataTypes'

      at Runtime.linkAndEvaluateModule (node_modules/jest-runtime/build/index.js:779:5)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)
</code></pre>
<p><em>(and my Jest config)</em></p>
<pre><code>// Sync object
/** @type {import('@jest/types').Config.InitialOptions} */

export default async () =&gt; {
    return {
        verbose: true,
        transform: {},
    };
};
</code></pre>
<p>Am I doing something wrong ? Should I change to commonJS instead of ES6</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/70985255/jest-es6-modules-does-not-provide-export-named,"['node.js', 'express', 'unit-testing', 'jestjs']",3268,True,3,1
"Jest, ES6 modules &quot;does not provide export named&quot;","<p>I have an express app with a CRUD API (with sequelize) and I want to test it with Jest. I'm pretty new in unit-testing so I follow this <a href=""https://www.albertgao.xyz/2017/05/24/how-to-test-expressjs-with-jest-and-supertest/"" rel=""nofollow noreferrer"">guide</a>, recommended by <a href=""https://jestjs.io/docs/testing-frameworks#expressjs"" rel=""nofollow noreferrer"">Jest's website</a>.</p>
<p>The problem I have is that my app is built with ES6 modules and Jest ES6 modules is experimental and it seems that it doesn't &quot;import&quot; packages.</p>
<p>I have this test <em>(took from the guide)</em></p>
<pre class=""lang-js prettyprint-override""><code>import request from 'supertest';
import app from '../app';

describe('Test the root path', () =&gt; {
    test('It should response the GET method', done =&gt; {
        request(app)
            .get('/')
            .then(response =&gt; {
                expect(response.statusCode).toBe(404);
                done();
            });
    });
});
</code></pre>
<p>And when I launched it (with <code>NODE_OPTIONS=--experimental-vm-modules npx jest</code> I had to follow this <a href=""https://jestjs.io/docs/ecmascript-modules"" rel=""nofollow noreferrer"">jest wiki page</a>), It says that</p>
<p><code>'sequelize' does not provide an export named 'DataTypes'</code> and when I launch my app normally (like with <code>npm start</code>) it works fine, without any problems.</p>
<p><em>(the complete error log):</em></p>
<pre><code>(node:49576) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 FAIL  __tests__/app_test.js
  ● Test suite failed to run

    SyntaxError: The requested module 'sequelize' does not provide an export named 'DataTypes'

      at Runtime.linkAndEvaluateModule (node_modules/jest-runtime/build/index.js:779:5)
      at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
      at runJest (node_modules/@jest/core/build/runJest.js:404:19)
      at _run10000 (node_modules/@jest/core/build/cli/index.js:320:7)
      at runCLI (node_modules/@jest/core/build/cli/index.js:173:3)
</code></pre>
<p><em>(and my Jest config)</em></p>
<pre><code>// Sync object
/** @type {import('@jest/types').Config.InitialOptions} */

export default async () =&gt; {
    return {
        verbose: true,
        transform: {},
    };
};
</code></pre>
<p>Am I doing something wrong ? Should I change to commonJS instead of ES6</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/70985255/jest-es6-modules-does-not-provide-export-named,"['node.js', 'express', 'unit-testing', 'jestjs']",3268,True,3,1
Why does my stateflow not change in my unit tests?,"<p>I have a state flow that is init to true</p>
<pre><code>private val isCreateProfileDisabledData = MutableStateFlow(true)
    
val isCreateProfileDisabled = isCreateProfileDisabledData.asStateFlow()
</code></pre>
<p>And then this function that runs on init that looks like</p>
<pre><code>fun fetchCreateProfileDisabled() {
        viewModelScope.launch {
            organizationRepository.getAllOrganizations().whenOk { 
                ...
                val isProfileCreationDisabled = (some work to figure out if true or false)
                isCreateProfileDisabledData.value = isProfileCreationDisabled
            }
        }
    }
</code></pre>
<p>And this code actually seems to work in my app. But during unit testing, the value never changes.</p>
<p>My test looks like this</p>
<pre><code>    @Test
    fun `Some Test`() = runBlockingTest {
        val mockOrg = Organization(
             isMobileProfileCreationDisabled = false
        )

        viewModel.fetchCreateProfileDisabled()
        whenever(organizationRepository.getAllOrganizations()).thenReturn(
            BaseResult.Ok(listOf(mockOrg))
        )

        viewModel.isCreateProfileDisabled.test {
            assertEquals(expectMostRecentItem(), false)
        }
    }
</code></pre>
<p>Basically when that <code>isMobileProfileCreationDisabled</code> value is false, then my stateflow should also be false. But it is always true.</p>
<p>I did try using awaitItem() instead of expectMostRecentItem() with the same result. And I also tried moving fetchCreateProfileDisabled() to inside of the turbine test before the assertEquals.</p>
<p>I set up some break points, and it never seems to hit anything after</p>
<pre><code>  organizationRepository.getAllOrganizations().whenOk {
</code></pre>
<p>but I have no idea why that is. Shouldn't that not happen since I am using whenever to mock the result?</p>
",https://stackoverflow.com/questions/71668629/why-does-my-stateflow-not-change-in-my-unit-tests,"['java', 'unit-testing', 'kotlin', 'turbine']",119,False,2,0
Pytest running indefinitely with threads,"<p>I am using PyTest to perform some unit testing for a personal project. The pytest calls a class that initialises multiple threads. As these threads run indefinitely they never close and pytest never terminates, meaning my gitlab pipeline that runs the testing automatically fails. Threads are essential to testing and mocking the calling of these threads will not solve the issue in this instance.</p>
<p>Is there a way to configure PyTest to terminate all subthreads on pass or fail? Or is there a way I can implement this behaviour using some bash trickery?</p>
<p>Thanks in advance for any assistance.</p>
<p>E.g</p>
<pre><code>Class A:
def  __init__():
    thread.start(C, daemon=True)
thread.start(D, daemon=True)
…   

Class B:
    def  __init__():
        Self.a = A()
    
    def example(self, inp):
        return self.a.function(inp)

test_B_example()
    assert a.function(“test”)
</code></pre>
<p>PyTest test_B_example -&gt; Runs forever despite having passed.</p>
<p>Tried adding sys.exit() to python code to terminate the code after all tests have been executed but did not work.</p>
",https://stackoverflow.com/questions/71560459/pytest-running-indefinitely-with-threads,"['python', 'multithreading', 'testing', 'pytest']",869,False,2,1
How to unit test firebase auth in a NextJS app?,"<p>I am trying to setup and unit test <code>firebase auth</code> in a Next JS project.
Setup:
<code>package.json</code></p>
<pre><code>&quot;firebase&quot;: &quot;^9.6.10&quot;,
&quot;firebase-admin&quot;: &quot;^10.0.2&quot;,
&quot;next&quot;: &quot;12.1.1&quot;,
</code></pre>
<p>I want to unit test the parts of the code where there is conditional rendering based on if user is logged in.</p>
<p>Firebase does not seem to have much resources for <a href=""https://firebase.google.com/docs/rules/unit-tests"" rel=""nofollow noreferrer"">unit testing</a> for authentication.</p>
<p>Error:</p>
<pre><code>


    FirebaseError: Firebase: Error (auth/invalid-api-key).

      25 |     }
      26 |
    &gt; 27 |     return firebaseClient.auth().onIdTokenChanged(async (user) =&gt; {
         |                           ^
      28 |       if (!user) {
      29 |         setUser(null);
      30 |         nookies.set(undefined, 'token', '', { path: '/' });
      


  ● Console

    console.error
      Error: Uncaught [FirebaseError: Firebase: Error (auth/invalid-api-key).]
      ...
      {
        code: 'auth/invalid-api-key',
        customData: { appName: '[DEFAULT]' }
      }

      at VirtualConsole.&lt;anonymous&gt; (node_modules/jsdom/lib/jsdom/virtual-console.js:29:45)
      at reportException (node_modules/jsdom/lib/jsdom/living/helpers/runtime-script-errors.js:70:28)
      at innerInvokeEventListeners (node_modules/jsdom/lib/jsdom/living/events/EventTarget-impl.js:341:9)
      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)

    console.error
      The above error occurred in the &lt;AuthProvider&gt; component:
      
      
</code></pre>
<p>Here is <code>AuthProvider.tsx</code> that wraps around the entire app.</p>
<pre><code>     
type AuthProviderProps = {
  children: React.ReactNode;
};
type User = firebaseClient.User;

const AuthContext = createContext&lt;{ user: User | null }&gt;({
  user: null,
});

export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element =&gt; {
  const [user, setUser] = useState&lt;User | null&gt;(null);

  // handle auth logic here...

  // listen for token changes
  // call setUser and write new token as a cookie
  useEffect(() =&gt; {
    if (typeof window !== 'undefined') {
      (window as any).nookies = nookies;
    }

    return firebaseClient.auth().onIdTokenChanged(async (user) =&gt; {
      if (!user) {
        setUser(null);
        nookies.set(undefined, 'token', '', { path: '/' });
      } else {
        const token = await user.getIdToken();
        setUser(user);
        nookies.set(undefined, 'token', token, { path: '/' });
      }
    });
  }, []);

  // force refresh the token every 10 minutes
  useEffect(() =&gt; {
    const handle = setInterval(async () =&gt; {
      const user = firebaseClient.auth().currentUser;
      if (user) await user.getIdToken(true);
    }, 10 * 60 * 1000);

    // clean up setInterval
    return () =&gt; clearInterval(handle);
  }, []);
  return &lt;AuthContext.Provider value={{ user }}&gt;{children}&lt;/AuthContext.Provider&gt;;
};

export const useAuth = () =&gt; {
  return useContext(AuthContext);
};
</code></pre>
<p>Here is the provider wrapping around the children elements in <code>_app.tsx</code></p>
<pre><code>
function MyApp({ Component, pageProps }: AppProps) {
  return (
    &lt;AuthProvider&gt;
      &lt;Header /&gt;
      &lt;MainLayout&gt;
        &lt;Component {...pageProps} /&gt;
      &lt;/MainLayout&gt;
    &lt;/AuthProvider&gt;
  );
}

export default MyApp;
</code></pre>
<p>Here is an example of the test setup that depends on the user has been logged in or not.</p>
<pre><code>
  test('if it has a logout button', () =&gt; {
    render(&lt;Sidebar /&gt;);
    const logoutButton = screen.getByRole('button', { name: /logout/i });
    expect(logoutButton).toBeInTheDocument();
  });
</code></pre>
<p>Code that depends on the user state that is logged in.</p>
<p><code>header.tsx</code></p>
<pre><code>import { useAuth } from '@/store/auth';

export const Header = () =&gt; {
const { user } = useAuth();
return (
  &lt;header className=&quot;bg-menubar text-primary-text&quot;&gt;
    &lt;nav&gt;{user ? &lt;Sidebar /&gt; : &lt;h1&gt;Not logged In&lt;/h1&gt;}&lt;/nav&gt;
  &lt;/header&gt;
);
};
</code></pre>
<p>Here is a <code>test-util.tsx</code></p>
<pre><code>import { render, RenderOptions } from '@testing-library/react';
import { FC, ReactElement } from 'react';

import { AuthProvider } from '@/store/auth';

const AllTheProviders: FC = ({ children }) =&gt; {
  return &lt;AuthProvider&gt;{children}&lt;/AuthProvider&gt;;
};

const customRender = (ui: ReactElement, options?: Omit&lt;RenderOptions, 'wrapper'&gt;) =&gt;
  render(ui, { wrapper: AllTheProviders, ...options });

export * from '@testing-library/react';
export { customRender as render };

</code></pre>
<p>I can confirm that the Keys are correct and it does work on local and allows me to sign in.</p>
",https://stackoverflow.com/questions/71848395/how-to-unit-test-firebase-auth-in-a-nextjs-app,"['javascript', 'firebase', 'jestjs', 'firebase-authentication']",408,False,2,0
TDD with Static Image results in an Image Not Found Error Gatsby,"<p>I have recently created a question previously regarding StaticImage appearing to now show up when using Jest and this project <a href=""https://github.com/testing-library/react-testing-library"" rel=""nofollow noreferrer"">@testing-library/react</a>. You can find my previous question here: <a href=""https://stackoverflow.com/questions/71445685/staticimage-not-showing-up-in-test-render-in-gatsby"">StaticImage not showing up in test render in Gatsby</a> As of writing this I haven't received a response which seems to indicate that I may have been pointing at the wrong problem.</p>
<p>To summarize, when attempting to follow TDD and make a test before implementing a solution, I attempted to make a test for rendering an image with StaticImage. I use the @testing-library/react to grab rendered react elements and ensure they are rendered correctly. However with StaticImage, it appears that the library does not render the image.</p>
<p>Originally in my first question, I believed that StaticImage from Gastby could've been a special component that for some reason didn't render when using the render method provided by @testing-library/react. However, upon understanding more about jest in general I determined that the jest-config.js file that I created as a part of Gastby's tutorial is actually redirecting any access attempts to image files and pointing them to <code>'&lt;rootDir&gt;/__mocks__/file-mock.js'</code>. Which makes me think when the StaticImage component starts rendering it attempts to access a .png file and that may trigger Jest to access the file-mock.js and attempt to resolve the image. However, in the console I get the warning 'Image could not be found.' I am currently using TypeScript and have attempted to follow the Gatsby's Guide to unit testing, but I haven't been successful thus far. Any help is appreciated!</p>
<p>The contents of my file-mock.js is:</p>
<pre><code>export default 'test-file-stub';
</code></pre>
<p>This is from the Gatsby Guide on <a href=""https://www.gatsbyjs.com/docs/how-to/testing/unit-testing/"" rel=""nofollow noreferrer"">Unit Testing</a></p>
<p>My jest-config.js looks like this:</p>
<pre><code>module.exports = {
  transform: {
    '^.+\\.[jt]sx?$': '&lt;rootDir&gt;/jest-preprocess.js',
  },
  moduleNameMapper: {
    '.+\\.(css|styl|less|sass|scss)$': `identity-obj-proxy`,
    '.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': `&lt;rootDir&gt;/__mocks__/file-mock.js`,
    '^gatsby-page-utils/(.*)$': `gatsby-page-utils/dist/$1`, // Workaround for https://github.com/facebook/jest/issues/9771
    '^gatsby-core-utils/(.*)$': `gatsby-core-utils/dist/$1`, // Workaround for https://github.com/facebook/jest/issues/9771
    '^gatsby-plugin-utils/(.*)$': [`gatsby-plugin-utils/dist/$1`, `gatsby-plugin-utils/$1`], // Workaround for https://github.com/facebook/jest/issues/9771
  },
  testPathIgnorePatterns: [`node_modules`, `\\.cache`, `&lt;rootDir&gt;.*/public`],
  transformIgnorePatterns: [`node_modules/(?!(gatsby)/)`],
  globals: {
    __PATH_PREFIX__: ``,
  },
  testURL: `http://localhost`,
  setupFiles: [`&lt;rootDir&gt;/loadershim.js`],
  testEnvironment: `jsdom`,
  setupFilesAfterEnv: ['&lt;rootDir&gt;/setup-test-env.js'],
};
</code></pre>
<p>Here is my loadershim.js:</p>
<pre><code>global.___loader = {
  enqueue: jest.fn(),
};
</code></pre>
<p>Here is my jest-preprocess.js:</p>
<pre><code>const babelOptions = {
  presets: [&quot;babel-preset-gatsby&quot;, &quot;@babel/preset-typescript&quot;],
};

module.exports = require(&quot;babel-jest&quot;).default.createTransformer(babelOptions);
</code></pre>
<p>Here is my gatsby-config.js</p>
<pre><code>/** @type {import('gatsby').GatsbyConfig} */
module.exports = {
  siteMetadata: {
    title: `new`,
    siteUrl: `https://www.yourdomain.tld`,
  },
  plugins: [
    'gatsby-plugin-image',
    'gatsby-plugin-sitemap',
    `gatsby-plugin-sass`,
    'gatsby-plugin-dts-css-modules',
    {
      resolve: 'gatsby-plugin-manifest',
      options: {
        icon: 'src/images/icon.png',
      },
    },
    'gatsby-plugin-mdx',
    'gatsby-transformer-remark',
    'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'images',
        path: './src/images/',
      },
      __key: 'images',
    },
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'pages',
        path: './src/pages/',
      },
      __key: 'pages',
    },
  ],
};
</code></pre>
",https://stackoverflow.com/questions/71471942/tdd-with-static-image-results-in-an-image-not-found-error-gatsby,"['typescript', 'jestjs', 'gatsby', 'react-testing-library']",484,False,2,1
PHP MYSQL/PDO mocking interaction/data,"<p>Recently getting back up-to-speed with unit testing. Been scouring the net for a good mock PDO SQL class for interactions/data but can't seem to one that doesn't require you to parse what the raw sql is into the mock obj during the test script.</p>
<p>This might be okay for some, but IMO it takes too much away from the test script (I'm trying to minimize complications to help sell the concept to my team at work)</p>
<p>Ideally I'd expect the test to look more like this:</p>
<pre class=""lang-php prettyprint-override""><code>public static function setUpBeforeClass()
{
    // Use PDOMock version in replace of all PDO calls   
    PDOMock::initMockMode();
    // Potentially drive data provider from a file
    $data = [
        [
            'id' =&gt; 1,
            'total' =&gt; 1,
        ],
        [
            'id' =&gt; 2,
            'total' =&gt; 1,
        ],
        [
            'id' =&gt; 3,
            'total' =&gt; 10,
        ],
    ]; 
    PDOMock::setTableData('db.example_table', $data);
}

public function testSqlMock()
{
    // Presumming the sumTableValues() method runs a simple sum query over the db.example_table using the regular \PDO class
    $total = TestClass::sumTableValues();

    $this-&gt;assertEquals(12, $total); // assertion passes due to PDOMock class using set data over live mysql data
}
</code></pre>
<p>It doesn't really need to have the fancy <code>PDOMock::initMockMode()</code> logic either as I can compromise by adding a <code>setMockMode()</code> in my sqlclass to just use the mocked version instead of <code>\PDO</code></p>
<p>Hope this makes sense; any ideas/suggestions are greatly appreciated!</p>
",https://stackoverflow.com/questions/72252625/php-mysql-pdo-mocking-interaction-data,"['php', 'mysql', 'pdo', 'phpunit', 'mockery']",53,False,1,0
Unit testing mbed application,"<p>I'm working on an mbed application and I want to be able to unit test some of the functionality. I created a test app so I could try out unit testing and I can't seem to get it to build. The TLDR of it is when I go to build the app the build fails with errors like:</p>
<pre><code>C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/CMSIS_5/CMSIS/RTOS2/RTX/Source/rtx_core_c.h:42:2: error: #error &quot;Unknown Arm Architecture!&quot;
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2015:40: error: 'fileno' was not declared in this scope; did you mean 'file'?
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2021:47: error: 'strdup' was not declared in this scope; did you mean 'StrDup'?
</code></pre>
<p>The more detailed version of it, on Windows I created a new app by:</p>
<pre><code>1. mbed-tools new
2. mbed-tools configure -m K64F -t GCC_ARM
</code></pre>
<p>Then I created a simple class to be tested <code>MyClass.h</code> and <code>MyClass.cpp</code></p>
<pre><code>#include &quot;MyClass.h&quot;

MyClass::MyClass() { }

bool MyClass::IsTwo(int number) {
    return number == 2;
}
</code></pre>
<p>And then also a simple test file <code>UNITTESTS\test_MyClass.cc</code></p>
<pre><code>#include &quot;gtest/gtest.h&quot;
#include &quot;../MyClass.h&quot;

class TestMyClass : public testing::Test {
protected:
    MyClass *cls;

    void SetUp(){
        cls = new MyClass();
    }

    void TearDown(){
        delete cls;
    }
};

TEST_F(TestMyClass, test_isTwo){
    EXPECT_TRUE(cls-&gt;IsTwo(2));
    EXPECT_FALSE(cls-&gt;IsTwo(23));
}
</code></pre>
<p>Then following the instructions from Google found <a href=""https://google.github.io/googletest/quickstart-cmake.html"" rel=""nofollow noreferrer"">here</a> I edited my root <code>CMakeList.txt</code> to be</p>
<pre><code># Copyright (c) 2022 ARM Limited. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

cmake_minimum_required(VERSION 3.19.0)

# GoogleTest requires at least C++14
set(CMAKE_CXX_STANDARD 14)

set(MBED_PATH ${CMAKE_CURRENT_SOURCE_DIR}/mbed-os CACHE INTERNAL &quot;&quot;)
set(MBED_CONFIG_PATH ${CMAKE_CURRENT_BINARY_DIR} CACHE INTERNAL &quot;&quot;)
set(APP_TARGET gtest_example)

include(${MBED_PATH}/tools/cmake/app.cmake)

project(${APP_TARGET})

# Disable tests as default configuration, use -DBUILD_TESTING to enable
option(BUILD_TESTING &quot;Run mbed os UNITTESTS&quot; ON)

add_subdirectory(${MBED_PATH})

if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME AND BUILD_TESTING)
    add_subdirectory(${MBED_PATH}/UNITTESTS) # add mbed os stubs and fakes
    add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/UNITTESTS)
endif()

include(FetchContent)
FetchContent_Declare(
        googletest
        GIT_REPOSITORY https://github.com/google/googletest.git
        GIT_TAG release-1.12.1
)
# For Windows: Prevent overriding the parent projects compiler/linker settings
set(gtest_force_shared_crt ON CACHE BOOL &quot;&quot; FORCE)
FetchContent_MakeAvailable(googletest)

add_executable(${APP_TARGET}
    main.cpp
    MyClass.cpp MyClass.h
)

target_link_libraries(${APP_TARGET} mbed-os)

mbed_set_post_build(${APP_TARGET})

option(VERBOSE_BUILD &quot;Have a verbose build process&quot;)
if(VERBOSE_BUILD)
    set(CMAKE_VERBOSE_MAKEFILE ON)
endif()
</code></pre>
<p>and the <code>UNITTESTS\CMakeLists.txt</code> file to be</p>
<pre><code>set(TEST_NAME example-unittest)

enable_testing()

add_executable(${TEST_NAME}
        test_MyClass.cc
        )

target_link_libraries(${TEST_NAME}
        GTest::gtest_main
        )
include(GoogleTest)
gtest_discover_tests(${TEST_NAME})
</code></pre>
<p>Then I ran</p>
<pre><code>cmake -S . -B cmake_build\K64F\develop\GCC_ARM -GNinja -DBUILD_TESTING=ON -DCMAKE_CXX_FLAGS=-std=c++14
</code></pre>
<p>resulting in</p>
<pre><code>-- The C compiler identification is GNU 10.3.1
-- The CXX compiler identification is GNU 10.3.1
-- The ASM compiler identification is GNU
-- Found assembler: C:/Program Files (x86)/GNU Arm Embedded Toolchain/10 2021.10/bin/arm-none-eabi-gcc.exe
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working C compiler: C:/Program Files (x86)/GNU Arm Embedded Toolchain/10 2021.10/bin/arm-none-eabi-gcc.exe - skipped
-- Detecting C compile features
-- Detecting C compile features - done
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: C:/Program Files (x86)/GNU Arm Embedded Toolchain/10 2021.10/bin/arm-none-eabi-g++.exe - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found Python3: C:/Python39/python.exe (found version &quot;3.9.7&quot;) found components: Interpreter
-- Checking for Python package prettytable -- found
-- Checking for Python package future -- found
-- Checking for Python package jinja2 -- found
-- Checking for Python package intelhex -- found
-- Found Python: C:/Python39/python.exe (found version &quot;3.9.7&quot;) found components: Interpreter
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD
-- Performing Test CMAKE_HAVE_LIBC_PTHREAD - Failed
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - not found
-- Check if compiler accepts -pthread
-- Check if compiler accepts -pthread - no
-- Could NOT find Threads (missing: Threads_FOUND)
-- Could NOT find Threads (missing: Threads_FOUND)
-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM
</code></pre>
<p>and then finally I ran</p>
<pre><code>cmake --build cmake_build\K64F\develop\GCC_ARM
</code></pre>
<p>which fails with a bunch of errors</p>
<pre><code>[75/208] Building CXX object _deps/googletest-build/googletest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.obj
FAILED: _deps/googletest-build/googletest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @_deps\googletest-build\googletest\CMakeFiles\gtest_main.dir\src\gtest_main.cc.obj.rsp -MD -MT _deps/googletest-build/googletest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.obj -MF _deps\googletest-build\googletest\CMakeFiles\gtest_main.dir\src\gtest_main.cc.obj.d -o _deps/googletest-build/googletest/CMakeFiles/gtest_main.dir/src/gtest_main.cc.obj -c C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/src/gtest_main.cc
In file included from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/gtest-message.h:55,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/gtest-assertion-result.h:46,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/gtest.h:59,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/src/gtest_main.cc:32:
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'int testing::internal::posix::FileNo(FILE*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2015:40: error: 'fileno' was not declared in this scope; did you mean 'file'?
 2015 | inline int FileNo(FILE* file) { return fileno(file); }
      |                                        ^~~~~~
      |                                        file
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'char* testing::internal::posix::StrDup(const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2021:47: error: 'strdup' was not declared in this scope; did you mean 'StrDup'?
 2021 | inline char* StrDup(const char* src) { return strdup(src); }
      |                                               ^~~~~~
      |                                               StrDup
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'FILE* testing::internal::posix::FDOpen(int, const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2065:56: error: 'fdopen' was not declared in this scope; did you mean 'fopen'?
 2065 | inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
      |                                                        ^~~~~~
      |                                                        fopen
[77/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\cmsis\device\rtos\source\mbed_rtx_idle.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\cmsis\device\rtos\source\mbed_rtx_idle.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/internal/SysTimer.h:21,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/internal/mbed_os_timer.h:21,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp:27:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/CMSIS_5/CMSIS/RTOS2/RTX/Source/rtx_lib.h:31,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/internal/mbed_os_timer.h:25,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/device/rtos/source/mbed_rtx_idle.cpp:27:
C:/Users/chris/Desktop/gtest_example/mbed-os/cmsis/CMSIS_5/CMSIS/RTOS2/RTX/Source/rtx_core_c.h:42:2: error: #error &quot;Unknown Arm Architecture!&quot;
   42 | #error &quot;Unknown Arm Architecture!&quot;
      |  ^~~~~
[78/208] Building CXX object _deps/googletest-build/googlemock/CMakeFiles/gmock_main.dir/src/gmock_main.cc.obj
FAILED: _deps/googletest-build/googlemock/CMakeFiles/gmock_main.dir/src/gmock_main.cc.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @_deps\googletest-build\googlemock\CMakeFiles\gmock_main.dir\src\gmock_main.cc.obj.rsp -MD -MT _deps/googletest-build/googlemock/CMakeFiles/gmock_main.dir/src/gmock_main.cc.obj -MF _deps\googletest-build\googlemock\CMakeFiles\gmock_main.dir\src\gmock_main.cc.obj.d -o _deps/googletest-build/googlemock/CMakeFiles/gmock_main.dir/src/gmock_main.cc.obj -c C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/src/gmock_main.cc
In file included from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/internal/gmock-port.h:57,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/internal/gmock-internal-utils.h:49,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/gmock-actions.h:145,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/gmock.h:56,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/src/gmock_main.cc:32:
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'int testing::internal::posix::FileNo(FILE*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2015:40: error: 'fileno' was not declared in this scope; did you mean 'file'?
 2015 | inline int FileNo(FILE* file) { return fileno(file); }
      |                                        ^~~~~~
      |                                        file
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'char* testing::internal::posix::StrDup(const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2021:47: error: 'strdup' was not declared in this scope; did you mean 'StrDup'?
 2021 | inline char* StrDup(const char* src) { return strdup(src); }
      |                                               ^~~~~~
      |                                               StrDup
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'FILE* testing::internal::posix::FDOpen(int, const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2065:56: error: 'fdopen' was not declared in this scope; did you mean 'fopen'?
 2065 | inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
      |                                                        ^~~~~~
      |                                                        fopen
[79/208] Building CXX object CMakeFiles/gtest_example.dir/main.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/main.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\main.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/main.cpp.obj -MF CMakeFiles\gtest_example.dir\main.cpp.obj.d -o CMakeFiles/gtest_example.dir/main.cpp.obj -c C:/Users/chris/Desktop/gtest_example/main.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\analogin.h:25,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/mbed.h:63,
                 from C:/Users/chris/Desktop/gtest_example/main.cpp:6:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/mbed.h:75,
                 from C:/Users/chris/Desktop/gtest_example/main.cpp:6:
c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\mbedcrc.h:658:2: error: #error &quot;Unknown ARM architecture for CRC optimization&quot;
  658 | #error &quot;Unknown ARM architecture for CRC optimization&quot;
      |  ^~~~~
[80/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/AnalogIn.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/AnalogIn.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\AnalogIn.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/AnalogIn.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\AnalogIn.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/AnalogIn.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/AnalogIn.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\analogin.h:25,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/AnalogIn.cpp:18:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[81/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SerialBase.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SerialBase.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\SerialBase.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SerialBase.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\SerialBase.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SerialBase.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/SerialBase.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_wait_api.h:21,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/SerialBase.cpp:18:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[82/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/FlashIAP.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/FlashIAP.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\FlashIAP.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/FlashIAP.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\FlashIAP.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/FlashIAP.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/FlashIAP.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\flashiap.h:30,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/FlashIAP.cpp:28:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[83/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/platform/cxxsupport/mstd_mutex.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/platform/cxxsupport/mstd_mutex.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\platform\cxxsupport\mstd_mutex.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/platform/cxxsupport/mstd_mutex.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\platform\cxxsupport\mstd_mutex.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/platform/cxxsupport/mstd_mutex.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/platform/cxxsupport/mstd_mutex.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\platform\cxxsupport\mstd_mutex:43,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/cxxsupport/mstd_mutex.cpp:18:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[84/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/I2C.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/I2C.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\I2C.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/I2C.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\I2C.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/I2C.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/I2C.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\i2c.h:26,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/I2C.cpp:18:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[85/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/MbedCRC.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/MbedCRC.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\MbedCRC.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/MbedCRC.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\MbedCRC.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/MbedCRC.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/MbedCRC.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\mbedcrc.h:29,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/MbedCRC.cpp:19:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/MbedCRC.cpp:19:
c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\mbedcrc.h:658:2: error: #error &quot;Unknown ARM architecture for CRC optimization&quot;
  658 | #error &quot;Unknown ARM architecture for CRC optimization&quot;
      |  ^~~~~
[86/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/platform/source/DeepSleepLock.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/platform/source/DeepSleepLock.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\platform\source\DeepSleepLock.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/platform/source/DeepSleepLock.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\platform\source\DeepSleepLock.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/platform/source/DeepSleepLock.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/platform/source/DeepSleepLock.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/source/DeepSleepLock.cpp:20:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[87/208] Building CXX object CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SPI.cpp.obj
FAILED: CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SPI.cpp.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @CMakeFiles\gtest_example.dir\mbed-os\drivers\source\SPI.cpp.obj.rsp -MD -MT CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SPI.cpp.obj -MF CMakeFiles\gtest_example.dir\mbed-os\drivers\source\SPI.cpp.obj.d -o CMakeFiles/gtest_example.dir/mbed-os/drivers/source/SPI.cpp.obj -c C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/SPI.cpp
In file included from C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/SingletonPtr.h:24,
                 from c:\users\chris\desktop\gtest_example\mbed-os\drivers\include\drivers\spi.h:27,
                 from C:/Users/chris/Desktop/gtest_example/mbed-os/drivers/source/SPI.cpp:17:
C:/Users/chris/Desktop/gtest_example/mbed-os/platform/include/platform/mbed_atomic.h:95:2: error: #error &quot;Unknown ARM architecture for exclusive access&quot;
   95 | #error &quot;Unknown ARM architecture for exclusive access&quot;
      |  ^~~~~
[88/208] Building CXX object _deps/googletest-build/googlemock/CMakeFiles/gmock.dir/src/gmock-all.cc.obj
FAILED: _deps/googletest-build/googlemock/CMakeFiles/gmock.dir/src/gmock-all.cc.obj
C:\ProgramData\chocolatey\bin\ccache.exe C:\PROGRA~2\GNUARM~1\102021~1.10\bin\AR10B2~1.EXE @_deps\googletest-build\googlemock\CMakeFiles\gmock.dir\src\gmock-all.cc.obj.rsp -MD -MT _deps/googletest-build/googlemock/CMakeFiles/gmock.dir/src/gmock-all.cc.obj -MF _deps\googletest-build\googlemock\CMakeFiles\gmock.dir\src\gmock-all.cc.obj.d -o _deps/googletest-build/googlemock/CMakeFiles/gmock.dir/src/gmock-all.cc.obj -c C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/src/gmock-all.cc
In file included from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/internal/gmock-port.h:57,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/internal/gmock-internal-utils.h:49,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/gmock-actions.h:145,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/include/gmock/gmock.h:56,
                 from C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googlemock/src/gmock-all.cc:39:
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'int testing::internal::posix::FileNo(FILE*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2015:40: error: 'fileno' was not declared in this scope; did you mean 'file'?
 2015 | inline int FileNo(FILE* file) { return fileno(file); }
      |                                        ^~~~~~
      |                                        file
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'char* testing::internal::posix::StrDup(const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2021:47: error: 'strdup' was not declared in this scope; did you mean 'StrDup'?
 2021 | inline char* StrDup(const char* src) { return strdup(src); }
      |                                               ^~~~~~
      |                                               StrDup
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h: In function 'FILE* testing::internal::posix::FDOpen(int, const char*)':
C:/Users/chris/Desktop/gtest_example/cmake_build/K64F/develop/GCC_ARM/_deps/googletest-src/googletest/include/gtest/internal/gtest-port.h:2065:56: error: 'fdopen' was not declared in this scope; did you mean 'fopen'?
 2065 | inline FILE* FDOpen(int fd, const char* mode) { return fdopen(fd, mode); }
      |                                                        ^~~~~~
      |                                                        fopen

...

ninja: build stopped: subcommand failed.
</code></pre>
",https://stackoverflow.com/questions/73241424/unit-testing-mbed-application,"['c++', 'unit-testing', 'cmake', 'googletest', 'mbed']",204,True,1,1
Eclipse &quot;error: no such file or directory&quot; while the header does exist,"<p>I'm working on automatic unit testing of ESP32 code in eclipse 2022-06 using google test.
For this I have made a new project and connected it with the ESP32 code using a header file.
I have also connected the unit test project with the ESP32 code via</p>
<pre><code>properties &gt; C/C++ General &gt; Paths and Symbols.
</code></pre>
<p>As seen in the picture below.
When running the ESP32 code I get no errors but when I try to run the unit test I get <code>&quot;fatal error: freertos/FreeRTOS.: No such file or directory&quot;</code>. However this path can be found in the EPS32 project that im testing.
Does anyone know how to solve this?
<a href=""https://i.stack.imgur.com/A4kfm.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/A4kfm.png"" alt=""enter image description here"" /></a></p>
<pre><code>#include &quot;main/main.h&quot;
</code></pre>
<p>Part of the unit test code</p>
<pre><code>#ifndef MAIN_DOT_H
#define MAIN_DOT_H

    #include &lt;stdio.h&gt;
    #include &lt;string.h&gt;
    #include &lt;stddef.h&gt;
    #include &quot;freertos/FreeRTOS.h&quot;
    #include &quot;freertos/task.h&quot;
    #include &quot;rom/ets_sys.h&quot;
    #include &quot;rom/gpio.h&quot;
    #include &quot;esp_intr_alloc.h&quot;
    #include &quot;esp_attr.h&quot;
    #include &quot;driver/timer.h&quot;
    #include &quot;esp_task_wdt.h&quot;                               
    #include &quot;soc/timer_group_struct.h&quot;
    #include &quot;soc/timer_group_reg.h&quot;
    #include &quot;driver/mcpwm.h&quot;
</code></pre>
<p>Part of the header file</p>
<pre><code>#include &quot;main.h&quot;
</code></pre>
<p>Part of the ESP32 code</p>
<p>To repeat the question, how can I solve this error?</p>
",https://stackoverflow.com/questions/73402123/eclipse-error-no-such-file-or-directory-while-the-header-does-exist,"['c', 'unit-testing', 'eclipse-cdt']",291,False,1,0
What is the value of using ModelFactories over interfaces when it comes to unit testing?,"<p>Looking at Microsoft's code for example, they create a 'ModelFactory' class for constructing objects for use in tests: <a href=""https://github.com/Azure/azure-sdk-for-net/blob/62f2223e46c33825628443d11b8267de4e72a1c6/sdk/servicebus/Azure.Messaging.ServiceBus/src/Primitives/ServiceBusModelFactory.cs"" rel=""nofollow noreferrer"">https://github.com/Azure/azure-sdk-for-net/blob/62f2223e46c33825628443d11b8267de4e72a1c6/sdk/servicebus/Azure.Messaging.ServiceBus/src/Primitives/ServiceBusModelFactory.cs</a></p>
<p>So if we need to mock a method on a service bus client which returns say, 'SubscriptionProperties', we need to obtain a new instance of this object with all the correct min/max values as the real code will run validation against those fields:</p>
<pre><code>public static SubscriptionProperties SubscriptionProperties(
            string topicName,
            string subscriptionName,
            TimeSpan lockDuration = default,
            bool requiresSession = default,
            TimeSpan defaultMessageTimeToLive = default,
            TimeSpan autoDeleteOnIdle = default,
            bool deadLetteringOnMessageExpiration = default,
            int maxDeliveryCount = default,
            bool enableBatchedOperations = default,
            EntityStatus status = default,
            string forwardTo = default,
            string forwardDeadLetteredMessagesTo = default,
            string userMetadata = default) =&gt;
            new SubscriptionProperties(topicName, subscriptionName)
            {
                LockDuration = lockDuration,
                RequiresSession = requiresSession,
                DefaultMessageTimeToLive = defaultMessageTimeToLive,
                AutoDeleteOnIdle = autoDeleteOnIdle,
                DeadLetteringOnMessageExpiration = deadLetteringOnMessageExpiration,
                MaxDeliveryCount = maxDeliveryCount,
                EnableBatchedOperations = enableBatchedOperations,
                Status = status,
                ForwardTo = forwardTo,
                ForwardDeadLetteredMessagesTo = forwardDeadLetteredMessagesTo,
                UserMetadata = userMetadata
            };
</code></pre>
<p>If SubscriptionProperties instead implemented an interface with these properties, it would be extremely easy to mock the ones we care about without any real implementation executing.</p>
<p>What are some of the values which come with this 'real implementation' ModelFactory approach when it comes to unit testing?</p>
",https://stackoverflow.com/questions/73817767/what-is-the-value-of-using-modelfactories-over-interfaces-when-it-comes-to-unit,"['c#', '.net', 'mocking']",24,True,1,1
Jest spy toHaveBeenCalled not seeing function as being hit,"<p>I am unit testing my JS file which consists of a lot of exported consts, with one of the functions calling some of the others held within the file, however I can't seem to get my test to see that it has done these calls - even though running the test with logging in the function to be called is triggered...</p>
<p>What am I doing wrong here?
I found some articles/questions and have tried what they suggest but it doesn't seem to be helping...</p>
<p><strong>MyFile.js</strong></p>
<pre><code>export func1 = (arg1) =&gt; {
    console.log('inside func1');
    // Do something
}
// More funcs here

export mainFunc = (mainArg) =&gt; {
    func1(mainArg);

    // More stuff with other funcs
}
</code></pre>
<p><strong>test.spec.js</strong></p>
<pre><code>import * as utils from './MyFile.js';

it('Should trigger func1', () =&gt; {
    const mySpy = jest.spyOn(utils, 'func1');

    utils.mainFun('something');

    expect(mySpy).toHaveBeenCalled();
    expect(mySpy).toHaveBeenCalledWith('something');
});
</code></pre>
<p>When I run this test I will see <code>inside func1</code> logged out in my console, but I will also see that my test fails:</p>
<blockquote>
<p>expect(jest.fn()).toHaveBeenCalled()</p>
<p>Expected number of calls: &gt;= 1</p>
<p>Received number of calls:    0</p>
</blockquote>
",https://stackoverflow.com/questions/74433779/jest-spy-tohavebeencalled-not-seeing-function-as-being-hit,"['javascript', 'testing', 'jestjs', 'spy', 'spyon']",526,False,1,0
How can I write a unit test to check that a React component method calls a Firebase auth method?,"<p>I'm building a React web app with a Firebase backend. I'm cool with React and Firebase, and I'm able to implement all the functionality I need without issue.</p>
<p>However, I'm also using this project as an opportunity to learn unit testing, currently using React Testing Library and Jest.</p>
<p>I can successfully test for rendered UI elements. What I'm struggling to get my head around is how I can test for a successful call of the Firebase API, for example with the below form component which allows a user to request a password reset email.</p>
<p>So, as of now, I'm able to successfully test:</p>
<ul>
<li>if the form is rendered correctly</li>
<li>if the correct UI (warning) elements are rendered when the form is submitted with an invalid or missing email address</li>
</ul>
<p>What I also want to be able to test for is:</p>
<ul>
<li>if the <code>sendPasswordResetEmail</code> method is called when the form is submitted with a valid email address</li>
</ul>
<p>I've stripped the component back to its most basic form (ignoring validation, etc, for now) to demonstrate. Users enter an email address, submit the form, and the Firebase method <code>sendPasswordResetEmail</code> is called.</p>
<p>My question is: how can I write a <em><strong>test</strong></em> that checks whether the <code>sendPasswordResetEmail</code> method is called successfully on form submit?</p>
<p>Is it even possible to test for this case?</p>
<p>Is this even the right question to ask? I'm super new to unit testing. :o)</p>
<p>Any suggestions?</p>
<p>Thanks!</p>
<pre><code>import React, { useState } from &quot;react&quot;;
import { auth } from &quot;../../lib/firebaseApp&quot;;
import { sendPasswordResetEmail } from &quot;firebase/auth&quot;;

const PasswordResetForm = (props) =&gt; {
  const [email, setEmail] = useState(null);

  const handleChange = (e) =&gt; {
    setEmail(e.target.value);
  };

  const handleSubmit = (e) =&gt; {
    e.preventDefault();

    sendPasswordResetEmail(auth, email)
      .then(() =&gt; {
        //Email sent
      })
      .catch((error) =&gt; {
        console.log(error);
      });
  };

  return (
    &lt;form noValidate onSubmit={handleSubmit}&gt;
      &lt;input type=&quot;text&quot; name=&quot;email&quot; value={email || &quot;&quot;} onChange={handleChange} /&gt;
      &lt;SubmitButton buttonText=&quot;Reset password&quot; /&gt;
    &lt;/form&gt;
  );
};

export default PasswordResetForm;
</code></pre>
<p>Here's a test I've written for one of the UI elements (for info only):</p>
<pre><code>import { render, fireEvent, screen } from &quot;@testing-library/react&quot;;
import { BrowserRouter } from &quot;react-router-dom&quot;;
import userEvent from &quot;@testing-library/user-event&quot;;
import &quot;@testing-library/jest-dom&quot;;

//Component
import PasswordResetForm from &quot;../../../components/forms/passwordresetform&quot;;

describe(&quot;Password reset form&quot;, () =&gt; {
  it(&quot;Should render an email field&quot;, () =&gt; {
    render(&lt;PasswordResetForm /&gt;, { wrapper: BrowserRouter });
    const input = screen.getByRole(&quot;textbox&quot;, { name: &quot;email&quot; });
    expect(input).toBeInTheDocument();
  });
});
</code></pre>
<p>UPDATE:</p>
<p>I've also now attempted to write a test to check whether the <code>sendPasswordResetEmail</code> method is called successfully:</p>
<pre><code>import React from &quot;react&quot;;
import { render, fireEvent, screen } from &quot;@testing-library/react&quot;;
import { BrowserRouter } from &quot;react-router-dom&quot;;
import userEvent from &quot;@testing-library/user-event&quot;;
import &quot;@testing-library/jest-dom&quot;;

import { getAuth, sendPasswordResetEmail } from &quot;firebase/auth&quot;;

//Component
import PasswordResetForm from &quot;../../../components/forms/passwordresetform&quot;;


//Mock firebase
jest.mock('firebase/auth', () =&gt; {
  return {
    getAuth: () =&gt; jest.fn(),
    sendPasswordResetEmail: () =&gt; jest.fn().mockResolvedValue({}),
  }
});



//UI tests
describe(&quot;Password reset form&quot;, () =&gt; {
  it(&quot;Should allow good email addresses and call sendPasswordResetEmail&quot;, async () =&gt; {
    render(&lt;PasswordResetForm /&gt;, { wrapper: BrowserRouter });
    const input = screen.getByRole(&quot;textbox&quot;, { name: &quot;email&quot; });
    const button = screen.getByRole(&quot;button&quot;, { name: &quot;submit&quot; });
    const value = &quot;user@domain.com&quot;;
    userEvent.type(input, value);
    fireEvent.click(button);
    expect(sendPasswordResetEmail).toBeCalledWith(getAuth(), value);
  });
});
</code></pre>
<p>However, this is giving me the following error:</p>
<pre><code>TypeError: (0 , _auth.sendPasswordResetEmail)(...).then is not a function

      42 |     if (dataValid) {
      43 |       sendPasswordResetEmail(auth, email)
    &gt; 44 |         .then(() =&gt; {
         |          ^
</code></pre>
<p>So, the question I now have is am I using <code>jest.fn().mockResolvedValue({})</code> in the right way?</p>
<p>And if so, why isn't it working?</p>
",https://stackoverflow.com/questions/74748197/how-can-i-write-a-unit-test-to-check-that-a-react-component-method-calls-a-fireb,"['javascript', 'reactjs', 'firebase', 'unit-testing', 'jestjs']",256,False,1,0
What causes the Visual Studio Modules (for C++ Projects) Window to write Yes against the Optimised Column?,"<p>What causes the Visual Studio Modules Window (for C++ Projects) to write Yes against the Optimised Column?</p>
<p>Until today I would have thought the answer to this question was simple, just make sure that all the optimisations are disabled.</p>
<p>In our main branch a colleague added a special project to bootstrap the special login code that runs for the main C++ projects to connect to the database, but in a project to be consumed by a new WPF C# App.</p>
<p>When the WPF App starts running special StartSession code runs within the Session DLL which causes the WPF App to be connected to the database.</p>
<p>If you put a breakpoint in the StartSession function then the modules window will show:</p>
<pre><code>Name               Path                        Optimized      Symbol Status    AppDomain
============       ====                        =========      =============    =========
Session.dll        C:\somepath\Session.dll     No             Symbols Loaded   [1] DefaultDomain
Session.dll        C:\somepath\Session.dll     No             Symbols Loaded   
Session.dll        C:\somepath\Session.dll     No             Symbols Loaded   
</code></pre>
<p>In the C++ Project property pages, Optimization = <strong>Disabled</strong> (/Od), Inline Function Expansion = <strong>Only __inline (/Ob1)</strong></p>
<p>All the rest are set to No or Either (all in non-bold)</p>
<p>I needed to create a similar project for my unit testing project with Catch2, so I duplicate the folder into my branch, edit the project file to change its details to reflect the new name, add a 2nd Configuration copied from the first called &quot;Catch2 Debug&quot;.</p>
<p>Then through a DLL Export I link it to my unit testing executable, but now when the module is loaded the details change</p>
<pre><code>Name               Path                                   Optimized      Symbol Status    AppDomain
============       ====                                   =========      =============    =========
Session.dll        C:\unittestpath\UnitTest.Session.dll   Yes            Symbols Loaded   [1] DefaultDomain
Session.dll        C:\unittestpath\UnitTest.Session.dll   No             Symbols Loaded   
Session.dll        C:\unittestpath\UnitTest.Session.dll   No             Symbols Loaded   
</code></pre>
<p>The reason this matters to me is that something is going wrong within the initialisation, so I need to be able to look at the contents of the variables, but when I add them to the watch window I receive the message <code>Cannot obtain value of the local variable or argument because it is not available at this instruction pointer, possibly because it has been optimized away.</code> instead of the evaluation of the variable.</p>
<p>I also tried generating the project from scratch and adding the relevant source files, however still the same result</p>
",https://stackoverflow.com/questions/73281574/what-causes-the-visual-studio-modules-for-c-projects-window-to-write-yes-aga,"['c++', 'visual-studio-debugging', 'debug-symbols']",116,False,1,0
Unit testing mocking interactions,"<p>I'm trying to implement unit testing for a large enterprise app that has multiple layers and interactions between classes.
Reading about this type of test, I see that it is not recommended to verify interaction, you should test &quot;observable results&quot;. For example:</p>
<pre><code>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>In this case, verifying that RemoveInventory is called it's wrong (according to the theory), because it is an implementation detail.
Now, how should I test that the product has been removed from the inventory, given that the database or dao classes are mocked? There's no way to know, other than check that the function that does remove the product is called and hope for the best.</p>
<p>What am I missing here? Should I implement this in a different manner?</p>
",https://stackoverflow.com/questions/73474498/unit-testing-mocking-interactions,"['java', 'unit-testing', 'junit', 'mocking']",27,False,0,0
What is the release mode in the context of numpy.testing.assert_?,"<p>I am reading into how I might use NumPy's testing tools in my own software projects. <a href=""https://en.wikipedia.org/wiki/Assertion_(software_development)"" rel=""nofollow noreferrer"">Assertions</a> are particularly useful in software testing, including unit testing. The <a href=""https://numpy.org/doc/stable/reference/routines.testing.html"" rel=""nofollow noreferrer""><code>numpy.testing.assert_</code></a> docs tell us:</p>
<blockquote>
<p>Assert that works in release mode. Accepts callable msg to allow deferring evaluation until failure. The Python built-in <code>assert</code> does not work when executing code in optimized mode (the <code>-O</code> flag) - no byte-code is generated for it. For documentation on usage, refer to the Python documentation.</p>
</blockquote>
<p>When I search the Python documentation for the literal string &quot;release mode&quot; the closest thing I find is <a href=""https://docs.python.org/3/library/devmode.html"" rel=""nofollow noreferrer"">Python Development Mode</a>. I'm not clear if that is even related to the release mode in the above sense.</p>
<p>What is the release mode in the context of NumPy's documentation?</p>
",https://stackoverflow.com/questions/73512560/what-is-the-release-mode-in-the-context-of-numpy-testing-assert,"['python', 'numpy', 'mode']",21,False,0,0
Django file based email backend,"<p>It's probably something very obvious, but I can't seem to figure it out.</p>
<p>This snippet is from Django's file based email backend (django.core.mail.backends.filebased.py)</p>
<pre><code>    def write_message(self, message):
        self.stream.write(message.message().as_bytes() + b&quot;\n&quot;)
</code></pre>
<p>My question is. How can I find out what class is <strong>message</strong> an object of?</p>
<p><strong>Context for why:</strong>
My code sends emails along various execution paths. I want to leverage Django's filebased backend, instead of firing live emails during debugging and unit testing (<em>or creating my own file based system</em>). The relevant code has a MIMEMultipart object currently (<em>with utf-8 coded text</em>) that works fine for production. I need to be able to convert that into an object that can be printed legibly by the above snippet.</p>
<p>PS: I come from a C++ background where this would've been an easy question to answer.</p>
",https://stackoverflow.com/questions/73421451/django-file-based-email-backend,"['python', 'django']",85,True,0,1
How to automatically generate unit testing routines from special syntax in method docstring / comment?,"<p>This is a mock-up of what I'm looking for:</p>
<pre class=""lang-py prettyprint-override""><code>def is_even(a, b):
    &quot;&quot;&quot;Returns True if both numbers are even.
    @AutoUnitTestTag:
    - (0,2) -&gt; True
    - (2,1) -&gt; False
    - (3,5) -&gt; False
    &quot;&quot;&quot;
    return (a % 2 == 0 and b % 2 == 0)
</code></pre>
<p>Is there a tool that could allow one to insert compact syntax-defined unit tests within a function's docstring and then automatically generate a <code>unittest_foobar.py</code> unit testing routine?</p>
<p>I'm almost sure I've seen this a while ago, but cannot find it.</p>
<p><strong>EDIT</strong>: @mkrieger1 suggested <code>doctest</code> in the comments below and after playing a bit with it, I'd say it's a pretty apt solution.
However, I'd like to let this question linger a bit longer in order to collect more suggestions, especially about more sophisticated tools.</p>
<p>If someone's interested, here's how one would use doctest in my example case:</p>
<ol>
<li>Format function in file <code>is_even.py</code> like so:</li>
</ol>
<pre><code>def is_even(a,b):
    &quot;&quot;&quot;Returns True if both numbers are even.
    &gt;&gt;&gt; is_even(0,2)
    True
    &gt;&gt;&gt; is_even(2,1)
    False
    &gt;&gt;&gt; is_even(3,5)
    False
    &quot;&quot;&quot;
    return (a % 2 == 0 and b % 2 == 0)
</code></pre>
<ol start=""2"">
<li>Then run the command <code>python3 -m doctest is_even.py</code>.
The output will look like so:</li>
</ol>
<pre><code>Trying:
    is_even(0,2)
Expecting:
    True
ok
Trying:
    is_even(2,1)
Expecting:
    False
ok
Trying:
    is_even(3,5)
Expecting:
    False
ok
1 items had no tests:
    foo2
1 items passed all tests:
   3 tests in foo2.is_even
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
</code></pre>
",https://stackoverflow.com/questions/72416363/how-to-automatically-generate-unit-testing-routines-from-special-syntax-in-metho,"['python', 'unit-testing', 'python-unittest', 'docstring']",132,True,0,1
Unit test Flask login function gives wrong response,"<p>I am trying to unit test my Flask application. But when unit testing with unittest it won't let me login.</p>
<p>This is my test script. test_register_page and test_login_page both work! The test_user_registration function works as well, but I know this is not the way to test the register function. I am now just saving it to the database. But when trying to login it  will not give  me a status_code 201. So that means my unit test for login is not working correct.</p>
<pre><code>import unittest
from damage_detection import create_app, db
from damage_detection.config import config_dict
from damage_detection.models import User


class UserTestCase(unittest.TestCase):

    def setUp(self):
        self.app=create_app(config=config_dict['testing'])
        self.appctx=self.app.app_context()
        self.appctx.push()
        self.client=self.app.test_client()
        db.create_all()

    def tearDown(self):
        db.drop_all()
        self.appctx.pop()
        self.app=None
        self.client =None

    def test_register_page(self):
        r = self.client.get(&quot;/register&quot;)
        self.assertEqual(r.status_code, 200)
        
    def test_login_page(self):
        r = self.client.get(&quot;/login&quot;)
        self.assertEqual(r.status_code, 200)

    def test_user_registration(self):
        user = User(username=&quot;testuser&quot;, email=&quot;testuser@company.com&quot;, password=&quot;password&quot;, image_file=&quot;default.jpg&quot;)
        db.session.add(user)
        users = User.query.all()
        assert user in users

    def test_login(self):
        data={
            &quot;email&quot;:&quot;testuser@company.com&quot;,
            &quot;password&quot;:&quot;password&quot;
        }
        response=self.client.post('/login',data=data)
        print(response.status_code)
    
        assert response.status_code == 201
</code></pre>
<p>This is my login function:</p>
<pre><code>@users.route(&quot;/login&quot;, methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        return redirect(url_for('main.home'))
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        if user and bcrypt.check_password_hash(user.password, form.password.data):
            login_user(user, remember=form.remember.data)
            next_page = request.args.get('next')
            return redirect(next_page) if next_page else redirect(url_for('main.home'))
        else:
            flash('Login Unsuccessful. Please check email and password', 'danger')
    return render_template('login.html', title='Login', form=form)
</code></pre>
<p>Do i need to give other data to the login function?</p>
<p>If you need more information about my files please let me know. Everything else is working correct so it is not a fault in my application code :)</p>
",https://stackoverflow.com/questions/72013296/unit-test-flask-login-function-gives-wrong-response,"['python', 'unit-testing', 'flask', 'sqlalchemy', 'python-unittest']",187,False,0,1
Unit Testing using Moq and RepoDb,"<p>I'm pretty new about Unit Testing and I need some information. I'm developing a Web API project using Dependency Injection, RepoDb as ORM (Sql Server only) and Moq in C#.</p>
<p>I deduced that I need Unit Tests and Integration Tests.</p>
<ol>
<li><p>For Integration Tests I would need to make API calls without mocking but going to create an ad hoc test database. Is it right?</p>
</li>
<li><p>For Unit Tests I should use collections instead of the database. The connection to the database is obtained <strong>at runtime</strong> starting from the customer's name (it's in <code>commonInfoService</code>):</p>
<pre><code> public class MyService : BaseDbService
 {
     private readonly IMyRelatedService _myRelatedService;
     private readonly IOtherRelatedService _otherRelatedService;

     public MyService(IConfiguration config, ILogger&lt;MyService&gt; logger, ICommonInfoService commonInfoService, IMyRelatedService myRelatedService, IOtherRelatedService otherRelatedService) : base(config, logger, commonInfoService)
     {
         _myRelatedService = myRelatedService;
         _otherRelatedService = otherRelatedService;
     }

     public async Task&lt;int&gt; CreateObject(MyObject myObject)
     {
         // TODO
     }
}
</code></pre>
</li>
</ol>
<p>There are many related services in the constructor.</p>
<p>In the Unit Test:</p>
<pre><code>[TestInitialize]
public void Setup()
{
    _loggerService = Mock.Of&lt;ILogger&lt;MyService&gt;&gt;();
    _commonInfoService = Mock.Of&lt;ICommonInfoService&gt;();
    _config = Mock.Of&lt;IConfiguration&gt;();
    // ...
}

[TestMethod]
public async Task TestCreateObjectWrongExtension()
{
    // Arrange
    Mock.Get(_commonInfoService).SetupGet(mock =&gt; mock.CustomerName).Returns(&quot;FIXEDVALUE&quot;);

    var configForSmsApi = new Dictionary&lt;string, string&gt;
    {
        {&quot;AppSettings:InstanceRootFolder&quot;, &quot;c:\\temp&quot;},
    };

    var configuration = new ConfigurationBuilder()
        .AddInMemoryCollection(configForSmsApi)
        .Build();

    Mock.Get(_myRelatedService).Setup(mock =&gt; mock.GetAllowedExtensions().Returns(&quot;.pdf&quot;);

    MyService service = new MyService(_config, _loggerService, _commonInfoService, _myRelatedService, It.IsAny&lt;IOtherRelatedService&gt;());

    MyObject myObject = new MyObject();
    myObject.Filename = &quot;test.abc&quot;;

    // Act
    // Assert
    HttpStatusException exceptionThrown = await Assert.ThrowsExceptionAsync&lt;HttpStatusException&gt;(async () =&gt; await service.CreateObject(myObject));
}
</code></pre>
<p>Is it right?
How do I get my context to replace the real database with a collection of values ​​created ad hoc?</p>
",https://stackoverflow.com/questions/72657677/unit-testing-using-moq-and-repodb,"['c#', 'unit-testing', 'dependency-injection', 'moq', 'webapi']",122,False,0,0
How to make Mocha unit test wait for async variable,"<p>I am very new to unit testing and I am trying to write a unit test on a function that reads from my database, but because the read is asynchronous the value is always undefined in my Mocha unit test. How can I do an assert on a variable which is declared asynchronously?</p>
<p>Unit Test:</p>
<pre><code>const homeController = require('../controllers/homeController');

describe('Testing home_get function', function () {
  it ('should render the home page', function () {
    const req = {};
    homeController.home_get(req, null, () =&gt;  {});
    console.log(&quot;numberUsers&quot;, numberUsers);
    assert.ok(numberUsers &gt; 0);
  });
});
</code></pre>
<p>Function I am trying to test:</p>
<pre><code>module.exports.home_get = async (req, res) =&gt; {
    requestTime = Date.now();
    numberUsers = await User.countDocuments({});
    numberViewers = await Viewer.countDocuments({});
    numberAccreditors = await Accreditor.countDocuments({});
    
    res.status('200').render('home', {numberUsers: numberUsers, numberViewers: numberViewers, numberAccreditors: numberAccreditors});
};
</code></pre>
<p>When I do an assert statement on the requestTime variable it works as intended but when I do it on the async variables the value is always undefined and I am not sure how to get the unit test to work on these async variables, also.... how would you then do a unit test to check the res.status is correct when you render home?</p>
",https://stackoverflow.com/questions/71631453/how-to-make-mocha-unit-test-wait-for-async-variable,"['node.js', 'unit-testing', 'asynchronous', 'mongoose', 'mocha.js']",808,True,0,2
testing external excel output with R testthat package,"<p>I'm trying to test a function of mine with the testthat package. The function is supposed to create an excel file, and I want to test if that excel file exists and contains the things it's supposed to contain. I tried running the function to create a simple mockup excel file and then reading in the output again, but that seems to not do anything, I'm guessing because of the localized testing environment. I also feel like writing code outside of the tests is not a good idea since it gave me a warning message about it.
Is there a way to test an external output with testthat that I don't know about? I'm new to unit testing and this package so any help would be appreciated.</p>
",https://stackoverflow.com/questions/71482856/testing-external-excel-output-with-r-testthat-package,"['r', 'unit-testing']",55,False,0,1
How to extract values of Sequelize criteria?,"<p>Lets say I have table student</p>
<pre><code>Student
id  first_name  last_name
1   Adam        First
2   Adam        Second
</code></pre>
<p>I have Javascript function that creates a criteria based on parameters it gets.</p>
<pre><code>function createCriteria(lastName, id) {
    // if either last name or id only are present then return 
    // criteria of that one parameter.
    // For example.
    // if only lastName is present return criteria {'lastName': 'First'}
    // if only id is present return criteria {[Op.in]: {'id': [1, 2]}}
    // If both are present, then consider both and return
    // {[Op.and]: [{'lastName': 'First'}, {[Op.in]: {'id': [1, 2]}}]}
}

function runQuery() {
    const criteria = createCriteria('First', [1, 2]);
    // run the sequelize query
}
</code></pre>
<p>So far all is fine. The problem I am having is unit testing the <code>createCriteria</code> function.</p>
<p>Specifically, testing nested cases like this one.</p>
<pre><code>{[Op.and]: [{'lastName': 'First'}, {[Op.in]: {'id': [1, 2]}}]}
</code></pre>
<p>Jest can test using the method <code>toHaveProperty</code>. So you can write,</p>
<pre><code>expect(criteria).toHaveProperty([Op.and]);
</code></pre>
<p>But, this only works for the first level.</p>
<p>How, would you fetch this value. <code>[{'lastName': 'First'}, {[Op.in]: {'id': [1, 2]}}]</code> which is indexed by key <code>[Op.and]</code>.</p>
<p>I might be missing how JSON or Javascript works, but <code>criteria[[Op.and]]</code> or <code>criteria.[Op.and]</code> or <code>criteria['[Op.and]']</code> does not work.</p>
<p>Sequelize Op are <a href=""https://github.com/sequelize/sequelize/blob/main/src/operators.ts#L522"" rel=""nofollow noreferrer"">symbols</a> so if you use <a href=""https://nodejs.org/en/knowledge/getting-started/how-to-use-util-inspect/"" rel=""nofollow noreferrer"">inspect</a> it will show up something like</p>
<pre><code>{[Symbol(and)]: [{'lastName': 'First'}, {[Symbol(in)]: {'id': [1, 2]}}]}
</code></pre>
<p>Does anyone know how to extract values out of JSON, which is a Sequelize criteria, as the keys are Sequelize operators, and not exactly strings or literals.</p>
",https://stackoverflow.com/questions/74168571/how-to-extract-values-of-sequelize-criteria,"['json', 'jestjs', 'sequelize.js']",15,False,0,0
How to use the JdbcTemplate that is configured and available through Spring-Boot in the JobRepository?,"<p>Hiho,</p>
<p>we use Spring-Batch 4.3.5 inside a Spring-Boot 2.6.7 service. All things work fine so far. While unit testing the use-cases, we realized that the BatchAutoConfiguration/BatchConfigurerConfiguration creates a JobRepository. This JobRepository needs and wants some JdbcOperations. Because no instance of JdbcOperations is taken from the Spring application context while initializing all the beans, the JobRepositoryFactoryBean decides to create a fresh instance of type JdbcTemplate and attach it to the JobRepository.</p>
<p>Therefore I would like to ask if there is an 'easy' possibility to attach the instance of the JdbcTemplate that is provided by Spring-Boot? Is there another possibility as overwriting the whole initialization mechanism? Do we need to provide our own BatchConfigurer?</p>
<p>Any help is really appreciated! :)</p>
",https://stackoverflow.com/questions/72319173/how-to-use-the-jdbctemplate-that-is-configured-and-available-through-spring-boot,"['java', 'spring', 'spring-boot', 'spring-batch', 'jdbctemplate']",478,True,0,1
Difference between &quot;Kafka for junit&quot; &amp; &quot;spring-kafka-test&quot;,"<p>We are using spring boot application for Kafka.</p>
<p>We want to do unit testing &amp; integration testing for Kafka producer(kafkatemplate) &amp; consumer (EventListner) application.</p>
<p>We explored couple of library for Kafka testing.
#1 Test container/ Kafka container - no access to docker images so we skipped this</p>
<p>#2 MockProducer &amp; MockConsumer not worked with kafkatemplate &amp; Kafkalietner. -- not found good working example for reference. Worked with core KafkaProducer &amp; Kafka consumer interface.</p>
<p>#3 spring-kafka-test - EmbededKafka working as expected:)</p>
<p>#4 Kafka for junit</p>
<p>Anyone used Kafka for junit for Kafka testing?</p>
<p>What are the advantages of Kafka for junit over spring-kafka-test library ?</p>
<p>When to use Kafka for junit library vs spring-kafka-test ?</p>
<p>Advantages &amp; Disadvantage of Kafka for junit ?</p>
<p>Thanks for advance.</p>
",https://stackoverflow.com/questions/73725825/difference-between-kafka-for-junit-spring-kafka-test,"['spring-boot', 'apache-kafka', 'integration-testing', 'junit4', 'spring-kafka-test']",160,False,0,0
Combine unit test with benchmarkDotNet?,"<p>Is there a way to combine Unit Testing with BenchmarkDotNet?
The idea would be that I would like to be able to write my unit tests using the AAA-pattern.
However, when running it as a benchmark-test using dotnetBenchmark, I would like to be able to not include the arrange and assert part of the benchmark-test (not include it in the code being benchmarked, since the arrange and act has nothing to do with the execution of my actual code).
By being able to benchmark my &quot;unit tests&quot; this way, I would not need to write separate benchmark tests and unit test, but be able to base them upon each other (no need for duplication of arrange or act).</p>
",https://stackoverflow.com/questions/74483598/combine-unit-test-with-benchmarkdotnet,"['c#', 'unit-testing', 'benchmarkdotnet']",340,True,0,1
GORM - Detached Criteria logical comparison - unsupported operator,"<p>I'm working on a data service in a Grails 4 API. In this data service, deleteExpired() is intended to locate photo objects that are &quot;expired&quot; and delete them.</p>
<p>For the purposes of easier unit testing, I am not using dynamic finders, but instead I have a where closure (using GORM detached criteria). However, deleteExpired() is failing with <code>Unsupported operator [-] used in query</code></p>
<p>I've also tried <code>today.minus(dateCreated)</code> instead of relying on <code>-</code>, but that is also failing with <code>No signature of method: java.util.Date.minus() is applicable for argument types: (grails.gorm.DetachedCriteria) values: [grails.gorm.DetachedCriteria@ebb0206]</code>.</p>
<p>What's the best way to do the date comparison in deleteExpired() to identify which photos should be deleted?</p>
<p><strong>PhotoDataService</strong></p>
<pre><code>package com.myproject.api

import grails.gorm.services.Service

@Service(Photo)
abstract class PhotoDataService {

    abstract Photo get(Serializable id)

    abstract List&lt;Photo&gt; findAllByPerson(Person person)

    abstract void delete(Serializable id)

    void deleteExpired() {
        Date today = new Date()

        Photo.where {
            (today.time - dateCreated.time) &gt; photoType.timeToLive
        }.list().each {delete(it)}
    }
}
</code></pre>
<p>Photos each have a photo type, which specifies the kind of photo it is as well as its time to live. Here are the photo and photo type domain objects.</p>
<p><strong>Photo</strong></p>
<pre><code>package com.myproject.api

import grails.compiler.GrailsCompileStatic
import grails.plugins.orm.auditable.Auditable
import org.grails.datastore.mapping.core.connections.ConnectionSource
import java.time.LocalDate
import java.time.Year


@GrailsCompileStatic
class Photo implements DomainClass, Auditable {

    byte[] bytes
    Person person
    PhotoType photoType
    Date dateCreated
    Date lastUpdated
    Integer width = 0
    Integer height = 0
}
</code></pre>
<p><strong>PhotoType</strong></p>
<pre><code>package com.myproject.api

import grails.plugins.orm.auditable.Auditable
import org.grails.datastore.mapping.core.connections.ConnectionSource

class PhotoType implements DomainClass, Auditable {

    private static final Integer DEFAULT_TIME_TO_LIVE = 15552000000

    String name
    String prompt
    boolean required = true
    Integer timeToLive = DEFAULT_TIME_TO_LIVE

    PhotoDimensions photoDimensions
}
</code></pre>
",https://stackoverflow.com/questions/72621240/gorm-detached-criteria-logical-comparison-unsupported-operator,"['grails', 'grails-orm']",101,False,0,0
ceedling with MPLABx and XC8,"<p>I am starting unit testing using ceedling from Windows Powershell. I have made a lot of progress getting Unity to work with the XC8 compiler. But I have a problem I can't seem to solve. Here is a bit of the build dump.</p>
<pre><code>'xc8-cc -mcpu=PIC16F18325 -gdwarf-3 -D&quot;__PIC16f18325__&quot; -D&quot;__XC8&quot; -D&quot;UNITY_INT_WIDTH=16&quot; -D&quot;UNITY_POINTER_WIDTH=16&quot; -D&quot;CMOCK_MEM_INDEX_TYPE=uint16_t&quot; -D&quot;CMOCK_MEM_PTR_AS_INT=uint16_t&quot; -D&quot;CMOCK_MEM_ALIGN=1&quot; -D&quot;CMOCK_MEM_SIZE=256&quot; -D&quot;UNITY_OUTPUT_COLOR&quot; -D&quot;TEST&quot; -D&quot;UNITY_INCLUDE_CONFIG_H&quot; -D&quot;UNITY_EXCLUDE_SETJMP_H&quot; -D&quot;UNITY_EXCLUDE_MATH_H&quot; -D&quot;UNITY_EXCLUDE_FLOAT&quot; -D&quot;CMOCK_MEM_SIZE=256&quot; -I&quot;C:/Users/timtru/MPLABXProjects/XT_Lock_PIC16F18325.X/vendor/ceedling/vendor/unity/src&quot; -I&quot;C:/Users/timtru/MPLABXProjects/XT_Lock_PIC16F18325.X/vendor/ceedling/vendor/cmock/src&quot; -I&quot;build/ceedling/generated/test/mocks&quot; -I&quot;test&quot; -I&quot;test/source&quot; -I&quot;test/support&quot; -I&quot;source&quot; -I&quot;source/mcc_generated_files&quot; -I&quot;source/mcc_generated_files/docs/doxygen_generator&quot; -I&quot;source/mcc_generated_files/drivers&quot; -I&quot;C:/Program Files/Microchip/xc8/v2.36/pic/include&quot; -I&quot;C:/Program Files/Microchip/xc8/v2.36/pic/include/c90&quot; -I&quot;C:/Program Files/Microchip/xc8/v2.36/pic/include/c99&quot; -I&quot;C:/Program Files/Microchip/xc8/v2.36/pic/include/legacy&quot; -I&quot;C:/Program Files/Microchip/xc8/v2.36/pic/include/proc&quot; -Wl,-Map=&quot;build/ceedling/generated/test/out/test_main.map&quot; -o&quot;./build/ceedling/generated/test/out/test_build.elf&quot; build/ceedling/generated/test/out/c/test_main_runner.p1 build/ceedling/generated/test/out/c/test_main.p1 build/ceedling/generated/test/out/c/unity.p1 build/ceedling/generated/test/out/c/mcc.p1 build/ceedling/generated/test/out/c/main.p1 build/ceedling/generated/test/out/c/I2_p0.p1 build/ceedling/generated/test/out/c/process_commands.p1 build/ceedling/generated/test/out/c/cmock.p1 2&gt;&amp;1'
&gt; Produced output:
C:\Program Files\Microchip\xc8\v2.36\pic\sources\c99\pic\__eeprom.c:22:9: error: use of undeclared identifier 'NVMCON1bits'
</code></pre>
<p>'NVMCON1bits is declared in pic16f18325.h file in the XC8 install directory-&quot;C:/Program Files/Microchip/xc8/v2.36/pic/include/proc&quot;, which seen as the last -I in the xc8-cc argument list. In the IDE MPLAB uses a XC.H file to inform the compiler what processor it is building for. This mechanism caused the correct &quot;processor&quot;.h file to be pulled in. &lt;xc.h&gt; necessarily appears in every source file. What is needed (in the project.yml) to get this to work?</p>
<pre><code># Notes:
# Project.yml


:project:
  :build_root: build/ceedling/generated
  :test_file_prefix: test_
  :which_ceedling: vendor/ceedling
  :use_exceptions: FALSE
  :release_build: FALSE
  :use_test_preprocessor: FALSE
  :use_auxiliary_dependencies: TRUE
  :default_tasks:
    - test:all

:environment:
  - :mcu: PIC16F18325
  - :mplabx_root: &quot;C:/Program Files/Microchip/xc8/v2.36/&quot;
  - :path:
    - &quot;C:/Program Files/Microchip/xc8/v2.36/pic/include/**&quot;
    - &quot;#{ENV['PATH']}&quot;
    - build
    - source/**
    - source/*
    - vendor/ceedling/vendor/unity/src


#:test_build:
#  :use_assembly: TRUE

#:release_build:
#  :output: MyApp.out
#  :use_assembly: FALSE



:module_generator:
  :project_root: ./
  :source_root: source/
  :test_root: test/
  
:extension:
  :object: .p1
  :executable: .elf
  :assembly: .S

:paths:
  :test:
    - +:test/**
    - -:test/support
  :source:
    - source/**
    - -:source/mcc_generated_files/docs
    - -:source/mcc_generated_files/examples
  :include:
    - &quot;C:/Program Files/Microchip/xc8/v2.36/pic/include/*&quot;
    - &quot;C:/Program Files/Microchip/xc8/v2.36/pic/include/proc/pic16f18325.h&quot;
  :support:
    - test/support
  :libraries: []

:defines:
  # in order to add common defines:
  #  1) remove the trailing [] from the :common: section
  #  2) add entries to the :common: section (e.g. :test: has TEST defined)
  :commmon: &amp;common_defines
    - __PIC16f18325__
    - __XC8
    - UNITY_INT_WIDTH=16
    - UNITY_POINTER_WIDTH=16
    - CMOCK_MEM_INDEX_TYPE=uint16_t
    - CMOCK_MEM_PTR_AS_INT=uint16_t
    - CMOCK_MEM_ALIGN=1
    - CMOCK_MEM_SIZE=256
  :test:
    - *common_defines
#    - UNITY_INCLUDE_CONFIG_H
    - UNITY_OUTPUT_COLOR #this is just here to make sure it gets removed by ceedling
    - TEST
  :test_preprocess:
    - *common_defines
    - TEST
:unity:
  :defines:
    - UNITY_INCLUDE_CONFIG_H 
    - UNITY_EXCLUDE_SETJMP_H
    - UNITY_EXCLUDE_MATH_H
    - UNITY_EXCLUDE_FLOAT
    
:cmock:
  :mock_prefix: mock_
  :when_no_prototypes: :warn
  :treat_externs: :include
  :enforce_strict_ordering: TRUE
  :fail_on_unexpected_calls: FALSE
  :exclude_setjmp_h: TRUE
  :defines:
    - CMOCK_MEM_SIZE=256
  :plugins:
    - :ignore
    - :ignore_arg
    - :callback
    - :expect_any_args
  :treat_as:
    int8:       INT8
    uint8:      HEX8
    uint16:     HEX16
    uint32:     UINT32
    int8_t:     INT8
    uint8_t:    HEX8
    uint16_t:   HEX16
    uint32_t:   UINT32
    bool:       UINT8

# Add -gcov to the plugins list to make sure of the gcov plugin
# You will need to have gcov and gcovr both installed to make it work.
# For more information on these options, see docs in plugins/gcov
:gcov:
  :reports:
    - HtmlDetailed
  :gcovr:
    :html_medium_threshold: 75
    :html_high_threshold: 90

:tools:
  :release_compiler:
    :name: &quot;Microchip XC8 Compiler&quot;
    :executable: xc8-cc
    :arguments:
      - &quot;-mcpu=#{ENV['MCU']}&quot;
      - -std=c99
      - -O1
      - -Wa,-a
      - -D&quot;$&quot;: COLLECTION_DEFINES_RELEASE_AND_VENDOR
      - -I&quot;$&quot;: COLLECTION_PATHS_SOURCE_AND_INCLUDE
      - -Iinclude/
      - -o &quot;${2}&quot;
      - -c
      - &quot;${1}&quot;

  :release_assembler:
    :name: &quot;Microchip XC8 Compiler&quot;
    :executable: xc8-cc
    :arguments:
      - &quot;-mcpu=#{ENV['MCU']}&quot;
      - -std=c99
      - -O1
      - -Wa,-a
      - -D&quot;$&quot;: COLLECTION_DEFINES_RELEASE_AND_VENDOR
      - -I&quot;$&quot;: COLLECTION_PATHS_SOURCE_AND_INCLUDE
      - -o &quot;${2}&quot;
      - -c
      - &quot;${1}&quot;

  :release_linker:
    :name: &quot;Microchip XC8 Linker&quot;
    :executable: xc8-cc
    :arguments:
      - &quot;-mcpu=#{ENV['MCU']}&quot;
      - -gdwarf-3
      - -D&quot;$&quot;: COLLECTION_DEFINES_RELEASE_AND_VENDOR
      - -I&quot;$&quot;: COLLECTION_PATHS_SOURCE_AND_INCLUDE
      - -Wl,-Map=&quot;${3}&quot;
      - -o &quot;${2}&quot;
      - &quot;{'${1}'.split(' ').map { |x| (x.include? '/out/c/') ? (Pathname(x).sub_ext('.p1')).to_s : x }.join(' ') }&quot;
      - &quot;${4}&quot;

  :test_compiler:
    :name: &quot;Microchip XC8 Compiler&quot;
    :executable: xc8-cc
    :arguments:
      - -mcpu=#{ENV['MCU']}
      - -std=c99
      - -O1
      - -Wa,-a
      - -D&quot;$&quot;: COLLECTION_DEFINES_TEST_AND_VENDOR
      - -I&quot;$&quot;: COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR
      - -Iinclude/
      - -o &quot;${2}&quot;
      - -c
      - &quot;${1}&quot;

  :test_file_preprocessor:
    :name: &quot;Microchip XC8 preprocessor&quot;
    :executable: xc8-cc
    :arguments:
      - -mcpu=#{ENV['MCU']}
      - -std=c99
      - -D&quot;$&quot;: COLLECTION_DEFINES_TEST_AND_VENDOR
      - -I&quot;$&quot;: COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR
      - &quot;${1}&quot;

  :test_includes_preprocessor:
    :name: &quot;Microchip XC8 includes preprocessor&quot;
    :executable: xc8-cc
    :arguments:
      - -mcpu=#{ENV['MCU']}
      - -std=c99
      - -D&quot;$&quot;: COLLECTION_DEFINES_TEST_AND_VENDOR
      - -I&quot;$&quot;: COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR
      - &quot;${1}&quot;

  :test_linker:
    :name: &quot;Microchip XC8 Linker&quot;
    :executable: xc8-cc
    :arguments:
      - -mcpu=#{ENV['MCU']}
      - -gdwarf-3
      - -D&quot;$&quot;: COLLECTION_DEFINES_TEST_AND_VENDOR
      - -I&quot;$&quot;: COLLECTION_PATHS_TEST_SUPPORT_SOURCE_INCLUDE_VENDOR
      - -Wl,-Map=&quot;${3}&quot;
      - -o&quot;./build/ceedling/generated/test/out/test_build.elf&quot;
      - &quot;{'${1}'.split(' ').map { |x| (x.include? '/out/c/') ? (Pathname(x).sub_ext('.p1')).to_s : x }.join(' ') }&quot;
      - &quot;${4}&quot;

  :test_fixture:
    :executable: ruby
    :name: &quot;Microchip simulator test fixture&quot;
    :stderr_redirect: :win #inform Ceedling what model of $stderr capture to use
    :arguments:
      - test/simulation/sim_test_fixture.rb

:plugins:
  :load_paths:
    - vendor/ceedling/plugins
  :enabled:
    - stdout_pretty_tests_report
    - module_generator
    - raw_output_report
    - warnings_report
</code></pre>
",https://stackoverflow.com/questions/72875396/ceedling-with-mplabx-and-xc8,"['c', 'xc8', 'ceedling', 'mplab-x']",227,False,0,1
Test reactive forms to be void when reset,"<p>I am currently working on a project made with Angular13, and since there are no more work to do this week, I decided to do some unit testing using Jest in order to improve my coding skills.</p>
<p>In this case, I want to test a method reset(), which does, as his name says, resets the form, but I can not find the way to test that.</p>
<p>I provide some code:</p>
<p><strong>component.ts</strong></p>
<pre><code>this.myForm= this.fb.group({
      a: new FormControl(),
      b: new FormControl(),
      c: new FormControl(),
    });

// Clean form
  resetForm() {
    this.myForm.get('a')?.reset();
    this.myForm.get('b')?.reset();
    this.myForm.get('c')?.reset();
  }
</code></pre>
<p>(I know you can reset all the form with <code>this.myForm.reset</code>, but I simplified the code snippet because I just want to reset some specific fields, not all the form)</p>
<p><strong>component.spec.ts</strong></p>
<pre><code>it('resets form', () =&gt; {
    const form = component.myForm;
    component.resetForm()
    expect(form.get('a')).toBe('')
    expect(form.get('b')).toBe('')
    expect(form.get('c')).toBe('')
  })
</code></pre>
<p>Am I doing it properly? What is supposed to be the value of the field when it has been reset?</p>
<p><strong>[UPDATE]</strong></p>
<pre><code>it('reset form', () =&gt; {
    const form = component.myForm;
    form.markAllAsTouched()
    form.markAsDirty()
    component.resetForm()
    form.markAsUntouched()
    form.markAsPristine()


    expect(form.get('a')).toBe(null)
    expect(form.get('b')).toBe(null)
    expect(form.get('c')).toBe(null)
  })
</code></pre>
",https://stackoverflow.com/questions/74572607/test-reactive-forms-to-be-void-when-reset,"['angular', 'unit-testing', 'testing', 'jestjs']",70,False,0,1
How do I implement a dry-run by always rolling back the transaction,"<p>I have some code that does database write operations, and I want to implement a dry-run, which means I want to execute the same code, but rollback the transaction at the end, even if no error occurred.</p>
<p>I have wrapped my code in a method annotated with <code>@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)</code> but the behavior is not what I expect. Instead of rolling back the transaction it opens a read-only transaction in the database and attempts to write, then I get the following error:</p>
<blockquote>
<p>ERROR: cannot execute INSERT in a read-only transaction</p>
</blockquote>
<p>I know the existence of the <code>@Rollback</code> annotation but it seems to be only for unit testing purposes.</p>
<p>How do I run code that writes in the database with a final rollback?</p>
",https://stackoverflow.com/questions/73649937/how-do-i-implement-a-dry-run-by-always-rolling-back-the-transaction,"['java', 'spring', 'hibernate', 'jpa']",90,False,0,0
How do you compare a 2d vector of custom objects in C++,"<p>I created an object called [Perception_Element]</p>
<p><strong>H FILE</strong></p>
<pre><code>#ifndef PERCEPTION_ELEMENT_H
#define PERCEPTION_ELEMENT_H

#include &lt;Root.h&gt;
using namespace Utilities;

namespace Perception {
    namespace Layer {
        namespace Element {
            class Perception_Element {
                public:
                    Perception_Element();

                    Perception_Element(float param_value);

                    void Set_Value(float param_value);

                    float Get_Value();

                    bool operator==(const Perception_Element element) const;

                    ~Perception_Element();

                private:
                    float value;

            };
        }
    }
}
#endif
</code></pre>
<p><strong>CPP</strong></p>
<pre><code>#include &lt;Perception_Element.h&gt;

using namespace Perception::Layer::Element;

Perception_Element::Perception_Element() {}

Perception_Element::Perception_Element(float param_value) {
    this-&gt;value = param_value;
}

void Perception_Element::Set_Value(float param_value) {
    this-&gt;value = param_value;
}

float Perception_Element::Get_Value() {
    return this-&gt;value;
}

bool Perception_Element::operator==(const Perception_Element element) const {
    return (value == element.value);
}


Perception_Element::~Perception_Element() {}

</code></pre>
<p>And then I created a class that inherits from it called Prediction</p>
<p><strong>H</strong></p>
<pre><code>#ifndef Prediction_H
#define Prediction_H

#include &lt;Perception_Element.h&gt;

using namespace Utilities;

namespace Perception {

    namespace Layer {
        namespace Element {
            class Prediction : public Perception_Element
            {
            public:
                Prediction();
                Prediction(float param_value);
                ~Prediction();
            };
        }
    }
}
#endif // !Prediction_H

</code></pre>
<p><strong>CPP</strong></p>
<pre><code>#include &lt;Prediction.h&gt;

using namespace Perception::Layer::Element;
/// &lt;summary&gt;
/// Instantiate an empty Input for a Neural Node 
/// &lt;/summary&gt;
Prediction::Prediction()
{
}

/// &lt;summary&gt;
/// Instantiate an Input for a Neural Node and assigns it a value for input
/// &lt;/summary&gt;
/// &lt;param name=&quot;param_value&quot;&gt;float&lt;/param&gt;
Prediction::Prediction(float param_value) : Perception_Element(param_value)
{
}



/// &lt;summary&gt;
/// destructor for input object
/// &lt;/summary&gt;
Prediction::~Prediction()
{
}


</code></pre>
<p>Just for Good measure the function I call is defined here</p>
<pre><code>void Layer::Dot_Product(vector&lt;vector&lt;Neural_Node&gt;&gt; param_inputs, vector&lt;vector&lt;Weight&gt;&gt; param_weights) {
    float results = 0;

    // iterate through the inputs rows to get the row index for the inputs and the outputs matrix
    for (int neural_node_row_index = 0; neural_node_row_index &lt; param_inputs.size(); neural_node_row_index++) {
            // iterate through the inputs columns to get the column index for the input and the output matrix
            for (int result_matrix_index = 0; result_matrix_index &lt; param_inputs[neural_node_row_index].size(); result_matrix_index++) {
                // iterate through the inputs columns to get the column index for the output matrix
                for (int neural_node_column_index = 0; neural_node_column_index &lt; param_inputs[neural_node_row_index].size(); neural_node_column_index++) {


                    /*
                      {    INPUT             {     OUTPUT            {        RESULT
                          {1, 2, 3, 4 }          {1, 2, 3, 4 }               {(INROW0, OUTROW0), (INROW0, OUTROW1), (INROW0, OUTROW2)}
                          {1, 2, 3, 4 }          {1, 2, 3, 4 }               {(INROW1, OUTROW0), (INROW1, OUTROW1), (INROW1, OUTROW2)}
                          {1, 2, 3, 4 }          {1, 2, 3, 4 }               {(INROW2, OUTROW0), (INROW2, OUTROW1), (INROW2, OUTROW2)}
                      }                      }                       }
                    */


                results +=
                    param_inputs[neural_node_row_index][neural_node_column_index].Get_Value()
                    *
                    param_weights[neural_node_row_index][neural_node_column_index].Get_Value();
            }
            this-&gt;predictions[neural_node_row_index][result_matrix_index].Set_Value(results);
            results = 0;

        }
     }
}

</code></pre>
<p>And now im writing unit testing and in trying to compare the matrix (2d vector) it fails</p>
<p>TEST</p>
<pre><code>

/// &lt;summary&gt;
/// Tests the dot product from the layer
/// &lt;/summary&gt;
/// &lt;param name=&quot;&quot;&gt;&lt;/param&gt;
/// &lt;param name=&quot;&quot;&gt;&lt;/param&gt;
TEST(Perception_Test, Test_Layer_Prediction_without_bias) {
    Neural_Node node1(1);
    Neural_Node node2(2);
    Neural_Node node3(3);
    Neural_Node node4(4);

    Weight weight1(1);
    Weight weight2(2);
    Weight weight3(3);
    Weight weight4(4);

    Prediction prediction30(30);

    Layer test_layer(4);


    vector&lt;vector&lt;Neural_Node&gt;&gt; test_inputs = { 
        { node1, node2, node3, node4 },
        { node1, node2, node3, node4 },
        { node1, node2, node3, node4 },
        { node1, node2, node3, node4 }
    };

    vector&lt;vector&lt;Weight&gt;&gt; test_weights = {
        {weight1,weight2,weight3,weight4},
        {weight1,weight2,weight3,weight4},
        {weight1,weight2,weight3,weight4},
        {weight1,weight2,weight3,weight4}
    };

    vector&lt;vector&lt;Prediction&gt;&gt; comparison = { 
        {prediction30, prediction30, prediction30, prediction30},
        {prediction30, prediction30, prediction30, prediction30},
        {prediction30, prediction30, prediction30, prediction30},
        {prediction30, prediction30, prediction30, prediction30}
    };

    vector&lt;vector&lt;float&gt;&gt; t1 = { {1,2,3}, {1,2,3} };
    vector&lt;vector&lt;float&gt;&gt; t2 = { {1,2,3}, {1,2,3} };

    test_layer.Dot_Product(test_inputs, test_weights);
    
    vector&lt;vector&lt;Prediction&gt;&gt; prediction_without_bias =
                         test_layer.Get_Prediction_Without_Bias();

     
    EXPECT_EQ(prediction_without_bias, comparison);
}
</code></pre>
<p>Weight, Prediction, and Neural_Node are all children classes of Perception_Element</p>
<p>I can successfully compare 1 prediction to another</p>
<p>But when it's buried in a vector of vectors it fails</p>
<p>ERROR:</p>
<blockquote>
<p>Error C2672   'operator __surrogate_func': no matching overloaded
function found</p>
</blockquote>
<p>What am I missing?</p>
<p><strong>UPDATE</strong></p>
<p>Changing the signature of my overloaded == and how I compare solved it</p>
<p>Thank you everyone</p>
<p>I have updated my code to show the working solution in the post.</p>
",https://stackoverflow.com/questions/74956806/how-do-you-compare-a-2d-vector-of-custom-objects-in-c,"['c++', 'vector', 'operator-overloading']",66,True,-2,1
Using Jasmine Unit Testing within a complex workflow based platform similar to Camunda or activiti,"<p>Using Jasmine Unit Testing with front-end JavaScript applications, you can write tests that can interact with the DOM to set up the input, run the test, and verify the results by querying the relevant HTML elements.</p>
<p>For example, the following code snippet will setup the needed DOM elements, call the function that will update the DOM using <code>updateResult()</code> function, then verify the results by reading the content of the inner text:</p>
<pre><code>function updateResult(result) {
  let element = document.getElementById('result');
  if (element) {
    element.innerText = result;
  }
}

  describe('updateResult()', function () {
    beforeAll(function () {
      const element = document.createElement('div');
      element.setAttribute('id', 'result');
      document.body.appendChild(element);
      this.element = element;
    });
    afterAll(function () {
      document.body.removeChild(this.element);
    });
    it('add result to the dom element', function () {
      updateResult('5'); //
      expect(this.element.innerText).toBe('5');
    });
  });
</code></pre>
<p><em>note: the above is a sample based on &quot;leelanarasimha&quot; simple-calculator tutorial.</em></p>
<p>Now consider a more complex scenario where you need to perform a similar test, however, the test requires complex objects to be available and a relatively large number of nested forms to be visible and filled. In a typical situation, the test is a small one, but in order to reach the point in time to run the test, you need to execute about 5 to 7 steps with complex operations which are outside the scope of the intended function, but that function depends on executing several steps so that you have all needed objects and data structures which are a dependency for the function to be tested.</p>
<p>I am finding it hard to wrap my head around how to use Jasmine Unit testing to write and execute tests for such a complex scenario.</p>
<p>Following is a simple scenario load the Jasmine Spec Runner HTML with the simple JavaScript to run the test engine:</p>
<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;meta charset=&quot;utf-8&quot;&gt;
  &lt;title&gt;Jasmine Spec Runner v4.4.0&lt;/title&gt;

  &lt;link rel=&quot;shortcut icon&quot; type=&quot;image/png&quot; href=&quot;lib/jasmine_favicon.png&quot;&gt;
  &lt;link rel=&quot;stylesheet&quot; href=&quot;lib/jasmine.css&quot;&gt;

  &lt;script src=&quot;lib/jasmine.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;lib/jasmine-html.js&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;lib/boot0.js&quot;&gt;&lt;/script&gt;
  &lt;!-- optional: include a file here that configures the Jasmine env --&gt;
  &lt;script src=&quot;lib/boot1.js&quot;&gt;&lt;/script&gt;

  &lt;!-- include source files here... --&gt;
  &lt;script src=&quot;src/calculator.js&quot;&gt;&lt;/script&gt;

  &lt;!-- include spec files here... --&gt;
  &lt;script src=&quot;spec/calculator.spec.js&quot;&gt;&lt;/script&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<pre><code>// calculator.js
let add = (a,b)=&gt;a+b;

//calculator.spec.js
/// &lt;reference path=&quot;../src/calculator.js&quot; /&gt;
describe(&quot;calculator.js&quot;, ()=&gt;{
    it(&quot;should add two numbers&quot;, ()=&gt;{
        expect(add(1,3)).toBe(4)
    })

});
</code></pre>
<p>In a typical workflow platform similar to Activity or Camunda, you develop complex forms and attach JavaScipt to add logic to control the Data Entry and perform the needed calculations and processing.</p>
<p>The main problem is that there is a large number of huge javascript programs that were not written with unit testing in mind. In a given scenario, there are 2 or 3 JavaScript functions that will interact with the HTML Form while inputting values, as a result, some REST APIs are invoked on the input event, and data is updated. Then, when clicking a button, another JavaSript function will run to perform the data summarization logic by reading the form data. The form fields are bound to variables that can be accessed using the supplied JavaScript functions to read form data (bound variables). The UI may have multiple nested subforms with repeating instances (data grid). I am thinking it is near impossibility to write JavaScript code to prepare the needed input so that the test will run. So, I am thinking of some alternatives.</p>
<h2><strong>Alternatives to implement the setup for the tests:</strong></h2>
<p><strong>Method A:</strong></p>
<ol>
<li>Write the tests assuming all the needed objects and DOM elements are available.</li>
<li>Go through the steps in the application to reach the point in time where the test can be executed.</li>
<li>Load or activate the Jasmine Unit testing spec runner which with the relevant unit tests</li>
</ol>
<p><strong>Method B:</strong></p>
<ol>
<li>Go through the steps in the application to reach the point in time where the test can be executed.</li>
<li>Extract the needed HTML with the forms and save them using static HTML</li>
<li>Extract the bound data of the forms (it is just a JSON value)</li>
<li>Write the test in such a way as to use the saved HTML and JSON to prepare the setup to run the test.</li>
</ol>
<p><strong>Method C:</strong></p>
<p>...</p>
<p>...</p>
<p>What I am looking for is the following:</p>
<ol>
<li><p>How to activate or load Jasmine from the console to kick off the test when it is ready to do so?</p>
</li>
<li><p>Is it possible to save the HTML Forms (the UI in general) and reload it back during the test and how? I can save the form data model in a JSON file and load it during the test.</p>
</li>
<li><p>Any other feedback on the above will be appreciated.</p>
</li>
</ol>
",https://stackoverflow.com/questions/74011331/using-jasmine-unit-testing-within-a-complex-workflow-based-platform-similar-to-c,"['javascript', 'unit-testing', 'jasmine', 'workflow', 'platform']",236,True,0,1
Electron - Need unit testing framework for bundled app,"<p>we are using electron framework to create <strong>WINDOWS</strong> and <strong>MAC</strong> installer. For frontend, we are using Angular to show data.
We are also using <strong>sqlite3</strong> database to store data locally in user's system using node.js.</p>
<p>Everything working fine like api calling using <strong>AXIOS</strong>, intercating with our local database(CRUD), intercating with client side(frontend) with <strong>electron-ipc-renderer</strong>, file system handling.
Our application is working properly as expected.</p>
<p>We are stuck with unit testing of our application.</p>
<p>We want to do end to end testing which will consume electrons basic libraries like:-</p>
<ul>
<li><strong>app</strong></li>
<li><strong>BrowserWindow</strong></li>
<li><strong>dialog</strong></li>
<li><strong>Menu</strong></li>
<li><strong>remote</strong></li>
<li><strong>screen</strong></li>
<li><strong>ipcMain</strong></li>
</ul>
<p>And we are using other node libraries also like <strong>axios, path, chokidar, sqlite3</strong>.</p>
<p>Has anyone achieved Unit test cases for such kind Electron App/knows anything which can help us?</p>
",https://stackoverflow.com/questions/74949787/electron-need-unit-testing-framework-for-bundled-app,"['node.js', 'unit-testing', 'electron', 'electron-builder', 'testcase']",56,False,3,0
"How to make MSTest grab all console output from unit test? Output behind WebHost.CreateDefaultBuilder() goes missing (VS2022, .NET 6, MSTest 2.2.10)","<p>I'm creating an integration test for a Web API, so I'm starting an entire application in a unit test using WebHost.CreateDefaultBuilder() and the usual setup bits.</p>
<p>While unit testing, my log framework writes to console to ease debugging of failing tests. However, console writing from within the application does not work. I see log before and after from the parts of the test that is not within the app. Currently I have to get around the issue by logging to file, but would be really nice if there was a way for console output to work.</p>
<p>Sadly with the nature of the integration test, a minimal reproduction isn't that minimal, but this reproduce the issue in 2 cases, and shows a working but very tedious workaround.</p>
<p>Project file with deps:</p>
<pre><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;
  &lt;PropertyGroup&gt;
    &lt;TargetFramework&gt;net6.0&lt;/TargetFramework&gt;
    &lt;LangVersion&gt;10.0&lt;/LangVersion&gt;
  &lt;/PropertyGroup&gt;
  &lt;ItemGroup&gt;
    &lt;PackageReference Include=&quot;Microsoft.AspNetCore.Mvc.NewtonsoftJson&quot; Version=&quot;3.1.24&quot; /&gt;
    &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;17.1.0&quot; /&gt;
    &lt;PackageReference Include=&quot;MSTest.TestAdapter&quot; Version=&quot;2.2.10&quot; /&gt;
    &lt;PackageReference Include=&quot;MSTest.TestFramework&quot; Version=&quot;2.2.10&quot; /&gt;
  &lt;/ItemGroup&gt;
&lt;/Project&gt;
</code></pre>
<p>And the actual test implementation:</p>
<pre><code>namespace Reproduce.Tests
{
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Hosting.Server.Features;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.ApplicationParts;
    using Microsoft.AspNetCore.Mvc.Controllers;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Reflection;
    using System.Threading;
    using System.Threading.Tasks;

    [TestClass]
    public class ReproduceConsoleOutIssueTest
    {
        // A log class that logs through given LogAction if given, or directly on Console if not.
        public class Logger
        {
            internal readonly List&lt;string&gt; RecordedLog = new();
            internal Action&lt;string&gt; LogAction { get; set; }

            internal void Log(string msg)
            {
                RecordedLog.Add(msg);
                var action = LogAction ?? Console.Out.WriteLine;
                action(&quot;INTERNAL LOGGING &quot; + msg);
            }
        }

        // A simple controller that tries to log
        public class MyController : ControllerBase
        {
            private readonly Logger _log;

            public MyController(Logger log) { _log = log; }

            [Route(&quot;api/test&quot;), HttpGet]
            public string Test()
            {
                _log.Log(&quot;Test was called&quot;);
                return &quot;Yay&quot;;
            }
        }

        internal class Startup
        {
            private class ControllerSelector : IApplicationFeatureProvider&lt;ControllerFeature&gt;
            {
                internal ICollection&lt;TypeInfo&gt; Controllers { get; init; }

                public void PopulateFeature(IEnumerable&lt;ApplicationPart&gt; parts, ControllerFeature feature)
                {
                    foreach (var c in Controllers) feature.Controllers.Add(c);
                }
            }

            public void ConfigureServices(IServiceCollection services)
            {
                var mvcCoreBuilder = services.AddMvcCore();
                mvcCoreBuilder.ConfigureApplicationPartManager(apm =&gt; apm.FeatureProviders.Add(
                    new ControllerSelector { Controllers = new[] { typeof(MyController).GetTypeInfo() }}
                ));
            }

            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                app.UseRouting();
                app.UseEndpoints(e =&gt; { e.MapControllers(); });
            }
        }

        [TestMethod]
        public async Task ReproduceIssueWhenDirectConsoleWriting()
        {
            // This use Console.Out.WriteLine that doesn't show the log from within controller.
            var logger = new Logger();
            await TryToReproduceIssueWithGivenLoggerAsync(logger);
        }

        [TestMethod]
        public async Task ReproduceIssueWhenLoggingThroughAction()
        {
            // Attempt to use func to run in console configured outside app but didn't help any.
            var logger = new Logger { LogAction = m =&gt; Console.WriteLine(m) };
            await TryToReproduceIssueWithGivenLoggerAsync(logger);
        }

        [TestMethod]
        public async Task WorksOnTediousContextChange()
        {
            // But if we just grab the state and log in a task/thread outside app context it works.
            var myLog = new Queue&lt;string&gt;();

            var logSent = new SemaphoreSlim(0);
            var logWritten = new SemaphoreSlim(0);
            var logWriterToken = new CancellationTokenSource();
            var logWriter = Task.Run(async () =&gt;
            {
                while (!logWriterToken.IsCancellationRequested)
                {
                    try
                    {
                        await logSent.WaitAsync(logWriterToken.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        break;
                    }
                    Console.WriteLine(myLog.Dequeue());
                    logWritten.Release();
                }
            });

            var logger = new Logger
            {
                LogAction = m =&gt;
                {
                    myLog.Enqueue(m);
                    logSent.Release();
                    logWritten.Wait();
                }
            };

            await TryToReproduceIssueWithGivenLoggerAsync(logger);
            logWriterToken.Cancel();
            await logWriter;
        }

        private async Task TryToReproduceIssueWithGivenLoggerAsync(Logger logger)
        {
            logger.Log(&quot;Starting&quot;);
            using var webHost = WebHost.CreateDefaultBuilder()
                .ConfigureServices(s =&gt;
                {
                    s.AddSingleton(this);
                    s.AddSingleton(logger);
                }).UseStartup&lt;Startup&gt;()
                .Build();
            var ctoken = new CancellationTokenSource();
            await webHost.StartAsync(ctoken.Token);

            var addr = webHost.ServerFeatures.Get&lt;IServerAddressesFeature&gt;()?.Addresses.First();
            var port = int.Parse(addr.Substring(addr.LastIndexOf(':') + 1));
            Assert.IsTrue(port &gt;= 1024 &amp;&amp; port &lt;= 65536);

            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Get, new Uri($&quot;http://localhost:{port}/api/test&quot;)));
                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                var content = await response.Content.ReadAsStringAsync();
                Assert.AreEqual(&quot;Yay&quot;, content);
            }

            ctoken.Cancel();
            await webHost.StopAsync(CancellationToken.None);
            logger.Log(&quot;Done&quot;);

            Assert.AreEqual(&quot;Starting, Test was called, Done&quot;, string.Join(&quot;, &quot;, logger.RecordedLog));
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/72235413/how-to-make-mstest-grab-all-console-output-from-unit-test-output-behind-webhost,"['c#', 'visual-studio', 'unit-testing', 'mstest', 'console.writeline']",380,False,3,1
Skipping a method execution using Mockito,"<p>I’m using Mockito for unit testing and I want to skip the execution of a method.</p>
<p>I referred to this ticket <a href=""https://stackoverflow.com/questions/55542010/skip-execution-of-a-line-using-mockito"">Skip execution of a line using Mockito</a>. Here, I assume doSomeTask() and createLink() methods are in different classes. But in my case, both the methods are in the same class (ActualClass.java).</p>
<pre><code>//Actual Class

public class ActualClass{
    
    //The method being tested
    public void method(){
        //some business logic
        validate(param1, param2);

        //some business logic
    }

    public void validate(arg1, arg2){
        //do something
    }
}

//Test class

public class ActualClassTest{

    @InjectMocks
    private ActualClass actualClassMock;

    @Test
    public void test_method(){

        ActualClass actualClass = new ActualClass();
        ActualClass spyActualClass = Mockito.spy(actualClass);

        // validate method creates a null pointer exception, due to some real time data fetch from elastic

        doNothing().when(spyActualClass).validate(Mockito.any(), Mockito.any());
        actualClassMock.method();
    }
}
</code></pre>
<p>Since there arises a null pointer exception when the validate method is executed, I’m trying to skip the method call by spying the ActualClass object as stated in the ticket I mentioned above. Still, the issue is not resolve. The validate method gets executed and creates a null pointer exception due to which the actual test method cannot be covered.</p>
<p>So, how do I skip the execution of the validate() method that is within the same class.</p>
",https://stackoverflow.com/questions/71349090/skipping-a-method-execution-using-mockito,"['java', 'unit-testing', 'junit', 'mockito', 'spy']",3178,True,3,2
Pytest does not respect DJANGO_SETTINGS_MODULE,"<p>I am having trouble with setting up database configs correctly for unit-testing purposes using pytest.</p>
<p>My goal is to create a brand new empty test database each time I run the tests.</p>
<p>I have a pytest.ini file that looks like this:</p>
<pre><code>[pytest]
DJANGO_SETTINGS_MODULE = test_settings
python_files = test_*.py
python_functions = test_*
addopts = --ds=test_settings --create-db
</code></pre>
<p>My project structure is like this:</p>
<pre><code>my_project
    app_1
    app_2
    tests
    my_project
       settings.py
    test_settings
       __init__.py
</code></pre>
<p>The test_settings/<strong>init</strong>.py file looks like this:</p>
<p>from my_project.settings import *</p>
<pre><code>POSTGRES_USER = os.getenv('POSTGRES_USER')
POSTGRES_HOST = os.getenv('POSTGRES_HOST')
POSTGRES_PASSWORD = os.getenv('POSTGRES_PASSWORD')
POSTGRES_DB = 'test_db'
POSTGRES_PORT = os.getenv('POSTGRES_PORT')

DATABASES = {
    'default': {
        'ENGINE': 'django.contrib.gis.db.backends.postgis',
        'NAME': POSTGRES_DB,
        'USER': POSTGRES_USER,
        'PASSWORD': POSTGRES_PASSWORD,
        'HOST': POSTGRES_HOST,
        'PORT': POSTGRES_PORT,
    }
}
</code></pre>
<p>And I have test cases like this:</p>
<pre><code>import pytest
from model_bakery import baker

from rest_framework.test import APIClient

from sales.models import ServiceLocation


# TODO: вынести куда-то в общий модуль
@pytest.fixture
def api_client():
    return APIClient


@pytest.mark.django_db
def test_get_service_locations(api_client):
    baker.make(ServiceLocation, _quantity=3)

    response = api_client().get('/mobile_api/v3/service_locations')

    assert response.status_code == 200
    assert len(response.json()['data']) == 3
</code></pre>
<p>When I run <code>pytest</code> command, for some reason I get assert 28 == 3 which means that python tries to connect to my original database that I use for development</p>
<p>Most surprisingly, I tried to delete one record from my development database table, so that the number of rows becomes 24 (instead of 25). But python seems to cache the database.
I am totally lost. Any ideas  what I am doing wrong ?</p>
",https://stackoverflow.com/questions/71160279/pytest-does-not-respect-django-settings-module,"['pytest', 'pytest-django']",412,False,2,0
NodeJS Jest : Testing function that imports module using require.main.require,"<p>I am trying to write unit testing using Jest for a Node JS project. It was importing all the modules using require.main.require</p>
<p>Below are the simulation of the issue. Code can be found here: <a href=""https://stackblitz.com/edit/node-jest-demo?file=index.js"" rel=""nofollow noreferrer"">https://stackblitz.com/edit/node-jest-demo?file=index.js</a></p>
<p>I have the following test file present in <em><strong>my root directory</strong></em> in which I am importing index.js</p>
<p><strong>./sample.pass.test.js</strong></p>
<pre><code>const { checkUser } = require('./index');

console.log(checkUser); // This is purely to check If i can access checkUser from this file or not

describe('Testing...', () =&gt; {
  it('Should pass', () =&gt; {
    expect(0).toBe(0);
  });
});

</code></pre>
<p>In my index.js I am importing another function using require.main.require</p>
<pre><code>const { getUserById } = require.main.require('./models/UserModel');

function checkUser(id) {
  const user = getUserById(id);
  return user ? 'Found' : 'Not Found';
}

module.exports.checkUser = checkUser;

</code></pre>
<p>The above test case is passing. But If I were to place the same test file in some other directly (like _<em>test_</em> ) then it fails.</p>
<p>E.g.: <strong>./__<em>test</em>__/sample.fail.test.js</strong></p>
<blockquote>
<p>Notice here I adjusted require statement of index since it is now one level up</p>
</blockquote>
<pre><code>const { checkUser } = require('../index');

console.log(checkUser);

describe('Testing...', () =&gt; {
  it('Should pass', () =&gt; {
    expect(0).toBe(0);
  });
});
</code></pre>
<p>The result shows it is unable to access UserModel.</p>
<pre><code>Cannot find module './models/UserModel' from '__tests__/sample.fail.test.js'

    Require stack:
      index.js
      __tests__/sample.fail.test.js

    &gt; 1 | const { getUserById } = require.main.require('./models/UserModel');
        |                                      ^
      2 |
      3 | function checkUser(id) {
      4 |   const user = getUserById(id);
</code></pre>
<p>What could be the solution in this case?</p>
<p>Thank in advance!</p>
",https://stackoverflow.com/questions/73286351/nodejs-jest-testing-function-that-imports-module-using-require-main-require,"['javascript', 'unit-testing', 'jestjs']",412,False,2,0
Writing unit tests for classes that depend on external libraries/sdks,"<p>My code consists of the following components:</p>
<p>1 - <strong>IMyService</strong>: interface that defines properties/methods of the class that will implement it.</p>
<p>2 - <strong>MyService</strong>: concrete implementation of IMyService.</p>
<pre><code>public interface IMyService 
{
    Task&lt;MyResult&gt; CreateAsync(string id, string json);
}

internal class MyService : IMyService
{
    private readonly ExternalService _externalService;

    public class MyService(ExternalService externalService) 
    {
        this._externalService = externalService;
    }

    public async Task&lt;MyResult&gt; CreateAsync(string id, string json)
    {
        ServiceResult serviceResult = await this._externalService.RunAsync(id, json);

        return new MyResult(serviceResult);
    }
}
</code></pre>
<p><strong>MyService</strong> class depends on third party library/SDK/package called <strong>ExternalService</strong> and implements method <strong>CreateAsync</strong>.</p>
<p>CreateAsync method takes 2 input parameters, invokes <strong>RunAsync</strong> method on ExternalService, receives result and creates <strong>my own</strong> class from result.</p>
<p><strong>Question 1)</strong></p>
<p>How would I approach unit testing CreateAsync method in MyService class? Is there any value in writing unit tests for it at all since it contains no logic?</p>
<p><strong>Question 2)</strong></p>
<p>ExternalService has its own Exceptions that it can throw when executing RunAsync method - should I capture exceptions thrown by RunAsync (wrapping try/catch around it) and cast them to my own Exception? For example - ExternalServiceException =&gt; MyServiceException.</p>
",https://stackoverflow.com/questions/74346661/writing-unit-tests-for-classes-that-depend-on-external-libraries-sdks,"['c#', 'unit-testing']",216,True,2,1
Unit test Xamarin Android project business logic,"<p>I have a problem with Unit testing a Xamarin Android project.</p>
<p>My setup:</p>
<ul>
<li>Shared Xamarin project</li>
<li>ClientX.Android</li>
<li>ClientX.iOS</li>
<li>Native.Android</li>
<li>Native.iOS</li>
</ul>
<p>Native.Android contains no resources, no MainActivity and no Androidmanifest. It's just shared Mono.Android code and normal business logic for it.</p>
<p>I have an Xunit testing project with which I have been able to test the Shared Xamarin project.</p>
<p>I need to test some business logic that is contained inside Native.Android but I get an error (which does make sense to me):</p>
<blockquote>
<p>Severity  Code    Description Project File    Line    Suppression State
Error NU1201  Project Client.XXXX.NativeDroid is not compatible with
netcoreapp3.1 (.NETCoreApp,Version=v3.1). Project
Client.XXX.NativeDroid supports: monoandroid12.0
(MonoAndroid,Version=v12.0)   XXX.UnitTests</p>
</blockquote>
<p>I can't find how I should go about Unit tests inside a Xamarin Android project that is not view/UI related.</p>
",https://stackoverflow.com/questions/73829380/unit-test-xamarin-android-project-business-logic,"['unit-testing', 'xamarin', 'xamarin.forms', 'xamarin.android']",246,True,2,1
Jest TypeError: Cannot read properties of undefined (reading &#39;content&#39;),"<p>I am unit testing a React component using Jest and trying to understand the best way to mock a provider. I am trying two methods:</p>
<ol>
<li>passing in a small amount of data to a <code>.Provider</code> which is throwing an error. I believe this is from the data being structured improperly and can use some help on this :)</li>
<li>mocking the Post context using <code>jest.mock('../../src/context/Post', () =&gt; jest.fn())</code> but that is throwing an error because the <code>render</code> method in the test expects the PostContext to be a React element and not a jest function.</li>
</ol>
<p>Screenshots of the errors are below.</p>
<p>Here is the test:</p>
<pre><code>import React from 'react'
import { screen, render } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import CommentBlock from '../components/postBlock/commentBlock'
import PostContext from '../../src/context/Post'

test('should render CommentBlock correctly with props', () =&gt; {
    // mocked props
    const commentId = 'commentId'
    const page = '/user'

    // mocked data
    const mockedData = {
        commentsById: [
            {
                id: commentId,
            },
        ],
        content: 'comment content',
    }

    render(
        &lt;PostContext.Provider value={mockedData}&gt;
            &lt;CommentBlock commentId={commentId} page={page} /&gt;
        &lt;/PostContext.Provider&gt;
    )
})


</code></pre>
<p>Here is the <code>CommentBlock</code> component:</p>
<pre><code>// import BlockButton from './blockButton';
import { useState, useContext } from 'react'
import { useHistory } from 'react-router-dom'
import dateformat from 'dateformat'
import { observer } from 'mobx-react-lite'

import UnirepContext from '../../context/Unirep'
import PostContext from '../../context/Post'

import { EXPLORER_URL } from '../../config'
import { Page, ButtonType } from '../../constants'
import BlockButton from './blockButton'
import MarkdownIt from 'markdown-it'

const markdown = new MarkdownIt({
    breaks: true,
    html: false,
    linkify: true,
})

type Props = {
    commentId: string
    page: Page
}

const CommentBlock = ({ commentId, page }: Props) =&gt; {
    const postContext = useContext(PostContext)
    const comment = postContext.commentsById[commentId]
    const commentHtml = markdown.render(comment.content)
    const unirepConfig = useContext(UnirepContext)
    const date = dateformat(new Date(comment.post_time), 'dd/mm/yyyy hh:MM TT')
    const history = useHistory()
    const [isEpkHovered, setEpkHovered] = useState&lt;boolean&gt;(false)

    const gotoPost = () =&gt; {
        if (page === Page.User) {
            history.push(`/post/${comment.post_id}`, { commentId: comment.id })
        }
    }

    return (
        &lt;div className=&quot;comment-block&quot;&gt;
            &lt;div className=&quot;block-header comment-block-header no-padding&quot;&gt;
                &lt;div className=&quot;info&quot;&gt;
                    &lt;span className=&quot;date&quot;&gt;{date} |&lt;/span&gt;
                    &lt;span
                        className=&quot;user&quot;
                        onMouseEnter={() =&gt; setEpkHovered(true)}
                        onMouseLeave={() =&gt; setEpkHovered(false)}
                    &gt;
                        Post by {comment.epoch_key}{' '}
                        &lt;img
                            src={require('../../../public/images/lighting.svg')}
                        /&gt;
                        {isEpkHovered ? (
                            &lt;span className=&quot;show-off-rep&quot;&gt;
                                {comment.reputation ===
                                unirepConfig.commentReputation
                                    ? `This person is very modest, showing off only ${unirepConfig.commentReputation} Rep.`
                                    : `This person is showing off ${comment.reputation} Rep.`}
                            &lt;/span&gt;
                        ) : (
                            &lt;span&gt;&lt;/span&gt;
                        )}
                    &lt;/span&gt;
                &lt;/div&gt;
                &lt;a
                    className=&quot;etherscan&quot;
                    target=&quot;_blank&quot;
                    href={`${EXPLORER_URL}/tx/${comment.id}`}
                &gt;
                    &lt;span&gt;Etherscan&lt;/span&gt;
                    &lt;img
                        src={require('../../../public/images/etherscan.svg')}
                    /&gt;
                &lt;/a&gt;
            &lt;/div&gt;
            &lt;div
                className=&quot;block-content no-padding-horizontal&quot;
                onClick={gotoPost}
            &gt;
                &lt;div
                    style={{
                        maxHeight: page == Page.Home ? '300px' : undefined,
                        overflow: 'hidden',
                    }}
                    dangerouslySetInnerHTML={{
                        __html: commentHtml,
                    }}
                /&gt;
            &lt;/div&gt;
            &lt;div className=&quot;block-buttons no-padding&quot;&gt;
                &lt;BlockButton
                    type={ButtonType.Boost}
                    count={comment.upvote}
                    data={comment}
                /&gt;
                &lt;BlockButton
                    type={ButtonType.Squash}
                    count={comment.downvote}
                    data={comment}
                /&gt;
                &lt;BlockButton type={ButtonType.Share} count={0} data={comment} /&gt;
            &lt;/div&gt;
        &lt;/div&gt;
    )
}

export default observer(CommentBlock)


</code></pre>
<p>Here is the <code>Post.ts</code> I would like to mock:</p>
<pre><code>import { createContext } from 'react'
import { makeAutoObservable } from 'mobx'

import { Post, Comment, QueryType, Vote, Draft, DataType } from '../constants'
import { makeURL, convertDataToPost, convertDataToComment } from '../utils'
import UserContext, { User } from './User'
import QueueContext, { Queue, ActionType, Metadata } from './Queue'
import UnirepContext, { UnirepConfig } from './Unirep'

const queueContext = (QueueContext as any)._currentValue as Queue
const userContext = (UserContext as any)._currentValue as User
const unirepConfig = (UnirepContext as any)._currentValue as UnirepConfig

export class Data {
    commentsById = {} as { [id: string]: Comment }
    postsById = {} as { [id: string]: Post }
    feedsByQuery = {} as { [query: string]: string[] }
    commentsByPostId = {} as { [postId: string]: string[] }
    commentsByQuery = {} as { [commentId: string]: string[] }
    votesById = {} as { [id: string]: Vote }
    votesByCommentId = {} as { [commentId: string]: string[] }
    votesByPostId = {} as { [commentId: string]: string[] }
    postDraft: Draft = { title: '', content: '' }
    commentDraft: Draft = { title: '', content: '' }

    constructor() {
        makeAutoObservable(this)
        if (typeof window !== 'undefined') {
            this.load()
        }
    }

    // must be called in browser, not in SSR
    load() {
        const storedPostDraft = window.localStorage.getItem('post-draft')
        if (storedPostDraft) {
            this.postDraft = JSON.parse(storedPostDraft)
        }

        const storedCommentDraft = window.localStorage.getItem('comment-draft')
        if (storedCommentDraft) {
            this.commentDraft = JSON.parse(storedCommentDraft)
        }
    }

    save() {
        window.localStorage.setItem(
            'post-draft',
            JSON.stringify(this.postDraft)
        )
        window.localStorage.setItem(
            'comment-draft',
            JSON.stringify(this.commentDraft)
        )
    }

    private ingestPosts(_posts: Post | Post[]) {
        const posts = [_posts].flat()
        for (const post of posts) {
            this.postsById[post.id] = post
        }
    }

    private ingestComments(_comments: Comment | Comment[]) {
        const comments = [_comments].flat()
        for (const comment of comments) {
            this.commentsById[comment.id] = comment
        }
    }

    private ingestVotes(_votes: Vote | Vote[]) {
        const votes = [_votes].flat()
        for (const vote of votes) {
            this.votesById[vote._id] = vote
        }
    }

    feedKey(query: string, epks = [] as string[]) {
        return epks.length === 0 ? query : `${query}-user`
    }

    async loadPost(id: string) {
        const apiURL = makeURL(`post/${id}`, {})
        const r = await fetch(apiURL)
        const data = await r.json()
        const post = convertDataToPost(data[0])
        this.ingestPosts(post)
    }

    async loadFeed(query: string, lastRead = '0', epks = [] as string[]) {
        const apiURL = makeURL(`post`, {
            query,
            lastRead,
            epks: epks.join('_'),
        })
        const r = await fetch(apiURL)
        const data = await r.json()
        const posts = data.map((p: any) =&gt; convertDataToPost(p)) as Post[]
        this.ingestPosts(posts)
        const key = this.feedKey(query, epks)
        if (!this.feedsByQuery[key]) {
            this.feedsByQuery[key] = []
        }
        const ids = {} as { [key: string]: boolean }
        const postIds = posts.map((p) =&gt; p.id)
        this.feedsByQuery[key] = [...this.feedsByQuery[key], ...postIds].filter(
            (id) =&gt; {
                if (ids[id]) return false
                ids[id] = true
                return true
            }
        )
    }

    async loadComments(query: string, lastRead = '0', epks = [] as string[]) {
        const apiURL = makeURL(`comment`, {
            query,
            lastRead,
            epks: epks.join('_'),
        })
        const r = await fetch(apiURL)
        const data = await r.json()
        const comments = data.map((p: any) =&gt;
            convertDataToComment(p)
        ) as Comment[]
        const key = this.feedKey(query, epks)
        this.ingestComments(comments)
        if (!this.commentsByQuery[key]) {
            this.commentsByQuery[key] = []
        }
        const ids = {} as { [key: string]: boolean }
        const commentIds = comments.map((c) =&gt; c.id)
        this.commentsByQuery[key] = [
            ...this.commentsByQuery[key],
            ...commentIds,
        ].filter((id) =&gt; {
            if (ids[id]) return false
            ids[id] = true
            return true
        })
    }

    async loadCommentsByPostId(postId: string) {
        const r = await fetch(makeURL(`post/${postId}/comments`))
        const _comments = await r.json()
        const comments = _comments.map(convertDataToComment) as Comment[]
        this.ingestComments(comments)
        this.commentsByPostId[postId] = comments.map((c) =&gt; c.id)
    }

    async loadComment(commentId: string) {
        const r = await fetch(makeURL(`comment/${commentId}`))
        const comment = await r.json()
        if (comment === null) return
        this.ingestComments(convertDataToComment(comment))
    }

    async loadVotesForCommentId(commentId: string) {
        const r = await fetch(makeURL(`comment/${commentId}/votes`))
        const votes = await r.json()
        if (votes === null) return
        this.ingestVotes(votes as Vote[])
        this.votesByCommentId[commentId] = votes.map((v: Vote) =&gt; v._id)
    }

    async loadVotesForPostId(postId: string) {
        const r = await fetch(makeURL(`post/${postId}/votes`))
        const votes = await r.json()
        if (votes === null) return
        this.ingestVotes(votes as Vote[])
        this.votesByPostId[postId] = votes.map((v: Vote) =&gt; v._id)
    }

    getAirdrop() {
        queueContext.addOp(
            async (update) =&gt; {
                if (!userContext.userState) return false

                update({
                    title: 'Waiting to generate Airdrop',
                    details: 'Synchronizing with blockchain...',
                })

                console.log('before userContext wait for sync')
                await userContext.waitForSync()
                console.log('sync complete')

                await userContext.calculateAllEpks()
                update({
                    title: 'Creating Airdrop',
                    details: 'Generating ZK proof...',
                })

                const { transaction, error } = await userContext.getAirdrop()
                if (error) throw error

                update({
                    title: 'Creating Airdrop',
                    details: 'Waiting for TX inclusion...',
                })
                await queueContext.afterTx(transaction)

                let metadata: Metadata = { transactionId: transaction }
                return metadata
            },
            {
                type: ActionType.UST,
            }
        )
    }

    publishPost(
        title: string = '',
        content: string = '',
        epkNonce: number = 0,
        minRep = 0
    ) {
        const user = (UserContext as any)._currentValue

        queueContext.addOp(
            async (updateStatus) =&gt; {
                updateStatus({
                    title: 'Creating post',
                    details: 'Generating zk proof...',
                })
                const { proof, publicSignals } = await user.genRepProof(
                    unirepConfig.postReputation,
                    epkNonce,
                    minRep
                )
                updateStatus({
                    title: 'Creating post',
                    details: 'Waiting for TX inclusion...',
                })
                const apiURL = makeURL('post', {})
                const r = await fetch(apiURL, {
                    headers: {
                        'content-type': 'application/json',
                    },
                    body: JSON.stringify({
                        title,
                        content,
                        proof,
                        proveKarma: unirepConfig.postReputation,
                        publicSignals,
                    }),
                    method: 'POST',
                })
                const { transaction, error, post: _post } = await r.json()
                if (error) throw error
                await queueContext.afterTx(transaction)
                const post = convertDataToPost(_post)
                this.postsById[post.id] = post
                this.feedsByQuery[QueryType.New].unshift(post.id)
                this.postDraft = { title: '', content: '' }
                this.save()

                return { id: transaction, transactionId: transaction }
            },
            {
                successMessage: 'Post is finalized',
                type: ActionType.Post,
            }
        )
    }

    vote(
        postId: string = '',
        commentId: string = '',
        receiver: string,
        epkNonce: number = 0,
        upvote: number = 0,
        downvote: number = 0,
        minRep = 0
    ) {
        queueContext.addOp(
            async (updateStatus) =&gt; {
                updateStatus({
                    title: 'Creating Vote',
                    details: 'Generating ZK proof...',
                })
                const { proof, publicSignals } = await userContext.genRepProof(
                    upvote + downvote,
                    epkNonce,
                    Math.max(upvote + downvote, minRep)
                )
                updateStatus({
                    title: 'Creating Vote',
                    details: 'Broadcasting vote...',
                })
                const r = await fetch(makeURL('vote'), {
                    headers: {
                        'content-type': 'application/json',
                    },
                    body: JSON.stringify({
                        upvote,
                        downvote,
                        proof,
                        minRep: Math.max(upvote + downvote, minRep),
                        publicSignals,
                        receiver,
                        dataId: postId.length &gt; 0 ? postId : commentId,
                        isPost: !!postId,
                    }),
                    method: 'POST',
                })
                const { error, transaction } = await r.json()
                if (error) throw error
                updateStatus({
                    title: 'Creating Vote',
                    details: 'Waiting for transaction...',
                })
                await queueContext.afterTx(transaction)

                if (postId) await this.loadPost(postId)
                if (commentId) await this.loadComment(commentId)

                return {
                    id: postId ? postId : commentId,
                    transactionId: transaction,
                }
            },
            {
                type: ActionType.Vote,
                metadata: { id: postId ? postId : commentId },
            }
        )
    }

    leaveComment(
        content: string,
        postId: string,
        epkNonce: number = 0,
        minRep = 0
    ) {
        queueContext.addOp(
            async (updateStatus) =&gt; {
                updateStatus({
                    title: 'Creating comment',
                    details: 'Generating ZK proof...',
                })
                const { proof, publicSignals } = await userContext.genRepProof(
                    unirepConfig.commentReputation,
                    epkNonce,
                    minRep
                )
                updateStatus({
                    title: 'Creating comment',
                    details: 'Waiting for transaction...',
                })
                const r = await fetch(makeURL('comment'), {
                    headers: {
                        'content-type': 'application/json',
                    },
                    body: JSON.stringify({
                        content,
                        proof,
                        minRep,
                        postId,
                        publicSignals,
                    }),
                    method: 'POST',
                })
                const { transaction, error } = await r.json()
                if (error) throw error
                await queueContext.afterTx(transaction)
                await Promise.all([
                    this.loadCommentsByPostId(postId),
                    this.loadPost(postId),
                ])

                this.commentDraft = { title: '', content: '' }
                this.save()

                return {
                    id: postId + '#' + transaction,
                    transactionId: transaction,
                }
            },
            {
                successMessage: 'Comment is finalized!',
                type: ActionType.Comment,
                metadata: { id: postId },
            }
        )
    }

    setDraft(type: DataType, title: string = '', content: string = '') {
        if (type === DataType.Post) {
            this.postDraft = { title, content }
        } else if (type === DataType.Comment) {
            this.commentDraft = { title, content }
        }
        this.save()
    }
}

export default createContext(new Data())
</code></pre>
<p>The error from the <code>mockedData</code>:
<a href=""https://i.stack.imgur.com/4OC7b.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/4OC7b.png"" alt=""err"" /></a></p>
<p>The error from trying to mock the Post context module (probably improperly):
<a href=""https://i.stack.imgur.com/xgYXt.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/xgYXt.png"" alt=""err mock"" /></a></p>
<p>Here is the test that throws the above error:</p>
<pre><code>import React from 'react'
import { screen, render } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import CommentBlock from '../components/postBlock/commentBlock'
import PostContext from '../../src/context/Post'

jest.mock('../../src/context/Post', () =&gt; jest.fn())

// mocked props
const commentId = 'commentId'
const page = '/user'

// mocked data for provider
const mockData = {
    content: 'comment content',
    commentsById: {
        [commentId]: {
            id: null,
        },
    },
    content: {
        title: 'title',
        content: 'content',
    },
}

const mockPostContext = () =&gt; React.createContext(mockData)

beforeAll(() =&gt; {
    PostContext.mockImplementation(mockPostContext)
})

test('should render CommentBlock correctly with props', () =&gt; {
    render(
        &lt;PostContext.Provider value={mockData}&gt;
            &lt;CommentBlock commentId={commentId} page={page} /&gt;
        &lt;/PostContext.Provider&gt;
    )
    screen.debug()
})

</code></pre>
",https://stackoverflow.com/questions/73006137/jest-typeerror-cannot-read-properties-of-undefined-reading-content,"['unit-testing', 'testing', 'jestjs']",7148,False,2,0
How to write unit tests for continuous Combine publisher without using wait(for:timeout:)?,"<p>Imagine, we have a <code>sut</code> as a publisher which publishes values continuously and never finishes. On change of some input (ex: we change some mocked @Published property which our <code>sut</code> depends on), it emits an event.</p>
<p>We're collecting these events in <code>results</code> array and then checking if there is an exact expected number of events, not less and not more.</p>
<p>The problem is - how to check there are no more events after what we expect to be emitted? Without <code>wait</code> method we don't know when it's time to check the <code>results</code> array.</p>
<p><code>wait</code> will work but it feels for me like a crutch for Combine. Because the good unit tests should be fast (see F.I.R.S.T principles of unit testing). And these <code>wait</code>s looks more like anti-pattern.</p>
<p>I also couldn't find an Apple's recommendation on this.</p>
",https://stackoverflow.com/questions/71394852/how-to-write-unit-tests-for-continuous-combine-publisher-without-using-waitfor,"['ios', 'swift', 'unit-testing', 'combine']",561,True,2,1
Need help on Jest / Vue2 configuration issue,"<p>I've a error i'm trying to solve for 2 days now without success !</p>
<p>I wanted to add some front unit testing on a Laravel mix + Vue 2 project with Jest.</p>
<p>So i've installed this in my package.json:</p>
<pre><code>{
  &quot;private&quot;: true,
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;jest&quot;,
  },
  &quot;dependencies&quot;: {
    &quot;@inertiajs/inertia&quot;: &quot;^0.11.0&quot;,
    &quot;@inertiajs/inertia-vue&quot;: &quot;^0.8.0&quot;,
    &quot;@inertiajs/progress&quot;: &quot;^0.2.7&quot;,
    &quot;vue&quot;: &quot;^2.6.14&quot;,
    &quot;vue-i18n&quot;: &quot;8&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@babel/core&quot;: &quot;^7.18.5&quot;,
    &quot;@babel/preset-env&quot;: &quot;^7.18.2&quot;,
    &quot;@vue/test-utils&quot;: &quot;^1.1.3&quot;,
    &quot;@vue/vue2-jest&quot;: &quot;^27.0.0-alpha.2&quot;,
    &quot;axios&quot;: &quot;^0.21&quot;,
    &quot;babel-core&quot;: &quot;7.0.0-bridge.0&quot;,
    &quot;babel-jest&quot;: &quot;^27.0.6&quot;,
    &quot;design-system&quot;: &quot;git+ssh://****&quot;,
    &quot;eslint&quot;: &quot;^8.8.0&quot;,
    &quot;eslint-config-prettier&quot;: &quot;^8.3.0&quot;,
    &quot;eslint-plugin-vue&quot;: &quot;^8.4.0&quot;,
    &quot;jest&quot;: &quot;^27.0.5&quot;,
    &quot;laravel-mix&quot;: &quot;^6.0.6&quot;,
    &quot;lodash&quot;: &quot;^4.17.19&quot;,
    &quot;prettier&quot;: &quot;2.5.1&quot;,
    &quot;resolve-url-loader&quot;: &quot;^5.0.0&quot;,
    &quot;sass&quot;: &quot;^1.51.0&quot;,
    &quot;sass-loader&quot;: &quot;^12.6.0&quot;,
    &quot;vue-loader&quot;: &quot;^15.9.7&quot;,
    &quot;vue-template-compiler&quot;: &quot;^2.6.14&quot;
  }
}
</code></pre>
<p>this in my babel.config.json:</p>
<pre><code>{
  &quot;presets&quot;: [
    &quot;@babel/preset-env&quot;
  ]
}
</code></pre>
<p>and this in my jest.config.js:</p>
<pre><code>module.exports = {
  testEnvironment: 'jsdom',
  verbose: true,
  // tell Jest to handle `*.vue` `*.json` `*.js`  files
  moduleFileExtensions: ['js', 'json', 'vue'],
  testMatch: ['**/tests/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'],
  moduleNameMapper: {
    '^@/(.*)$': '&lt;rootDir&gt;/resources/js/$1',
  },
  transform: {
    '.*\\.(js)$': '&lt;rootDir&gt;/node_modules/babel-jest',
    // process `*.vue` files with `vue-jest`
    '.*\\.(vue)$': '&lt;rootDir&gt;/node_modules/@vue/vue2-jest',
  },
};
</code></pre>
<p>I started to write some tests for my atoms components and everything was fine !
Jest was doing his job.</p>
<p>Then I started to test my molecules components, most of them import components from a dependency &quot;design-system&quot; (internal ressources) and when i try to test a component who import something from the design system i get this error when i type:</p>
<p><code>yarn test</code></p>
<pre><code> FAIL  tests/Front/organisms/Filters.spec.js
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default &quot;node_modules&quot; folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your &quot;node_modules&quot; files transformed, you can specify a custom &quot;transformIgnorePatterns&quot; in your config.
     • If you need a custom transformation specify a &quot;transform&quot; option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the &quot;moduleNameMapper&quot; config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    /****/****/*****/****/*****/*****/node_modules/design-system/src/index.js:2
    export { library } from &quot;@fortawesome/fontawesome-svg-core&quot;;
    ^^^^^^

    SyntaxError: Unexpected token 'export'

      22 |
      23 | &lt;script&gt;
    &gt; 24 | import { Select as ObsSelect } from 'design-system';
         | ^
      25 |
      26 | export default {
      27 |   name: 'Filters',

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.&lt;anonymous&gt; (resources/js/components/molecules/Filters.vue:24:1)
      at Object.&lt;anonymous&gt; (tests/Front/organisms/Filters.spec.js:2:1)
</code></pre>
<p>You must want to see the test file and the component as well:</p>
<pre><code>import { shallowMount } from '@vue/test-utils';
import Filters from '@/components/molecules/Filters';

describe('Filters.vue', () =&gt; {
  it('his visible', () =&gt; {
    const wrapper = shallowMount(Filters);
    expect(wrapper.isVisible()).toBe(true);
  });
});
</code></pre>
<pre><code>&lt;template&gt;
  &lt;div class=&quot;d-flex flex-column flex-lg-row filters&quot;&gt;
    &lt;obs-select
      id=&quot;country&quot;
      v-model=&quot;filters.byCountry&quot;
      class=&quot;pl-4 mr-lg-4&quot;
      :disabled=&quot;true&quot;
      :options=&quot;countryList&quot;
      :label=&quot;$t('filters.labels.country')&quot;
      @input=&quot;$emit('filterCountryUpdate', filters.byCountry)&quot;
    /&gt;
    &lt;obs-select
      id=&quot;time&quot;
      v-model=&quot;filters.byTime&quot;
      class=&quot;pl-4&quot;
      :options=&quot;timeList&quot;
      :label=&quot;$t('filters.labels.time')&quot;
      @input=&quot;$emit('filterTimeUpdate', filters.byTime)&quot;
    /&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script&gt;
import { Select as ObsSelect } from 'design-system';

export default {
  name: 'Filters',
  components: {
    ObsSelect,
  },
  data() {
    return {
      filters: {
        byCountry: 'all',
        byTime: this.$route().params.period || 'year',
      },
      countryList: [
        {
          value: 'all',
          text: this.$t('filters.countries.all'),
        },
        {
          value: 'US',
          text: this.$t('filters.countries.us'),
        },
        {
          value: 'DE',
          text: this.$t('filters.countries.de'),
        },
      ],
      timeList: [
        {
          value: 'year',
          text: this.$t('filters.time.year'),
        },
        {
          value: 'months',
          text: this.$t('filters.time.months'),
        },
      ],
    };
  },
};
&lt;/script&gt;

&lt;style lang=&quot;scss&quot;&gt;
.filters select {
  padding-right: 75px;
  min-width: 207px;
}
&lt;/style&gt;
</code></pre>
<p>Any idea ?</p>
<p>Thank you in advance for your help :)</p>
",https://stackoverflow.com/questions/72745555/need-help-on-jest-vue2-configuration-issue,"['javascript', 'vue.js', 'unit-testing', 'jestjs', 'babeljs']",399,False,1,0
xUnit-cli can&#39;t find dotnet on MacOS,"<p>I have a Xamarin forms project that I'm running on an Intel Mac. We are using XUnit for unit testing, and I would like to be able to run the tests on the command line on my Mac. The tests run inside the IDE but I can't get them to run on the command line. I have tried many different options and nothing seems to work. The current way I'm trying to get the tests to run is by using the <a href=""https://github.com/natemcmaster/xunit-cli"" rel=""nofollow noreferrer"">XUnit cli</a> tool.</p>
<p>I have dotnet installed and on my path, running<br />
<code>dotnet --version</code><br />
returns<br />
<code>6.0.110</code></p>
<p>I installed xunit-cli with the following command<br />
<code>dotnet tool install -g xunit-cli</code></p>
<p>and I've added xunit on my path, however, when I run the xunit-cli I get the following error</p>
<pre><code>You must install .NET to run this application.

App: /Users/luke/.dotnet/tools/xunit
Architecture: x64
App host version: 6.0.10
.NET location: Not found

Learn about runtime installation:
https://aka.ms/dotnet/app-launch-failed

Download the .NET runtime:
https://aka.ms/dotnet-core-applaunch?missing_runtime=true&amp;arch=x64&amp;rid=osx.13-x64&amp;apphost_version=6.0.10
</code></pre>
<p>What part of my setup is incorrect?</p>
",https://stackoverflow.com/questions/74845962/xunit-cli-cant-find-dotnet-on-macos,"['c#', 'xamarin', 'xamarin.forms', 'xunit.net', 'xunit2']",64,False,1,1
Upgrading an angular 13 app with js-cookie stops running jest unit tests successfully,"<p>I have an angular app with version 13 which is using the external dependency <strong>js-cookie</strong> to set and get some cookies in the browser.
As a test environment I am using <strong>jest</strong> with <strong>jest-preset-angular</strong>. See all dependencies of the package.json below.</p>
<p>My problem is that in angular 12 the unit tests of the component which is using <code>Cookies.set('test', '123')</code> is running perfectly fine. But with angular 13 while the functionality works and the build (ng build) is running, there is an error message when running jest unit tests:</p>
<pre><code>TypeError: Cookies.set is not a function
</code></pre>
<p>Dependencies in package.json:</p>
<pre><code>&quot;dependencies&quot;: {
    &quot;@angular/animations&quot;: &quot;^13.1.2&quot;,
    &quot;@angular/common&quot;: &quot;^13.1.2&quot;,
    &quot;@angular/compiler&quot;: &quot;^13.1.2&quot;,
    &quot;@angular/core&quot;: &quot;^13.1.2&quot;,
    &quot;@angular/forms&quot;: &quot;^13.1.2&quot;,
    &quot;@angular/platform-browser&quot;: &quot;^13.1.2&quot;,
    &quot;@angular/platform-browser-dynamic&quot;: &quot;^13.1.2&quot;,
    &quot;@angular/router&quot;: &quot;^13.1.2&quot;,
    &quot;rxjs&quot;: &quot;~6.6.7&quot;,
    &quot;tslib&quot;: &quot;^2.0.0&quot;,
    &quot;zone.js&quot;: &quot;~0.11.4&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@angular-devkit/build-angular&quot;: &quot;^13.1.3&quot;,
    &quot;@angular/cli&quot;: &quot;^13.1.3&quot;,
    &quot;@angular/compiler-cli&quot;: &quot;^13.1.2&quot;,
    &quot;@types/jest&quot;: &quot;^27.4.0&quot;,
    &quot;@types/node&quot;: &quot;^14.14.37&quot;,
    &quot;js-cookie&quot;: &quot;^3.0.1&quot;,
    &quot;codelyzer&quot;: &quot;^6.0.0&quot;,
    &quot;jest&quot;: &quot;^27.4.7&quot;,
    &quot;jest-preset-angular&quot;: &quot;11.0.1&quot;,
    &quot;ts-node&quot;: &quot;~9.1.1&quot;,
    &quot;tslint&quot;: &quot;~6.1.0&quot;,
    &quot;typescript&quot;: &quot;4.5.4&quot;
  }
</code></pre>
<p>Any idea where the change come from? Any known issues when unit testing jest in case of external dependencies with angular13?</p>
<p>I don't want to mock the methods of the external dependency <strong>js-cookie</strong>.</p>
<p>Example of the angular component:</p>
<pre><code>import {Component} from '@angular/core';
import * as Cookies from 'js-cookie';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html'
})
export class MyComponent {

  constructor() {
    Cookies.set('test', '123');
  }

}
</code></pre>
<p>Unit Test:</p>
<pre><code>import {MyComponent} from './my-component.component';

describe('MyComponent', () =&gt; {
  const component: MyComponent = new MyComponent();

  it('should create', () =&gt; {
    expect(component).toBeTruthy();
  });
});
</code></pre>
",https://stackoverflow.com/questions/70880564/upgrading-an-angular-13-app-with-js-cookie-stops-running-jest-unit-tests-success,"['angular', 'unit-testing', 'jestjs', 'js-cookie', 'jest-preset-angular']",606,True,1,1
How to simulate an Android hardware back button press in Jest with Angular?,"<p>I'm trying to do some unit testing with my Android code for an app but I'm not sure how to simulate an actual hardware back button press. I've created a mock Platform and have called &quot;mockPlatform.backButton.subscribeWithPriority&quot;, but when I run the Jest command and get back my code report, I see that it hasn't actually been called. I have if-statements inside of my &quot;subwithpriority&quot; function that check what the current router url is, but nothing inside of them has been tested. They should have been though, as I have manually set the router.url (that I injected into the TestBed) to match one of the conditions. I think perhaps I am not stimulating my hardware back button correctly - does anyone have any advice on what I should do?</p>
",https://stackoverflow.com/questions/72931245/how-to-simulate-an-android-hardware-back-button-press-in-jest-with-angular,"['android', 'angular', 'jestjs']",144,False,0,0
Testing with configuration files,"<p>my Google-fu has failed me by giving me results I don't understand, so I'm asking here.</p>
<p>I'm working on a Python project and I currently have a configuration file, which is also .py, that holds various python objects to load when everything starts. I'm trying to get some practice unit testing with pytest and I don't know exactly how to go about this issue. My guess is that I am probably going to make a dedicated testing config file that doesn't change, but I have no clue how to tell my code when to use the actual config file and when to use the testing config file. My current setup in my code is just using <code>import config</code> and setting values from it. I would greatly appreciate some help here!</p>
",https://stackoverflow.com/questions/71461458/testing-with-configuration-files,"['python', 'unit-testing', 'configuration', 'pytest', 'config']",891,True,0,2
What are the best practices for testing a FastAPI project with JWT authentication?,"<p>I have FastAPI project which does the following:</p>
<ol>
<li>Register users(unauthenticated)</li>
<li>CRUD operations on user resources(authenticated)</li>
</ol>
<p>What I want to do:</p>
<ol>
<li>Develop an automated testing framework to unit test all the APIs</li>
<li>Run that on a devops platform like jenkins regularly</li>
<li>Run it locally before deployment</li>
</ol>
<p>Some specific doubts I have:</p>
<ol>
<li>For testing, should I use the OpenAPI generated client sdk or the FastAPI client or use the python requests module?</li>
<li>Authentication should happen only once and reuse the JWT token or fresh authentication for each API test ?</li>
<li>Should I use the same pydantic modules for dev and testing or re-write them to ensure that no issues were introduced in case of updated models ?</li>
<li>How to do proper unit testing when one API requires result from multiple other APIs?</li>
</ol>
",https://stackoverflow.com/questions/72084607/what-are-the-best-practices-for-testing-a-fastapi-project-with-jwt-authenticatio,"['unit-testing', 'automated-tests', 'pytest', 'devops', 'fastapi']",2552,True,0,1
Simple checkbox test with vue unit testing library,"<p>Trying to work out something that I thought would be pretty simple!</p>
<p>I have a PrimeVue checkbox component on my page (and I'm using Vue 3, PrimeVue, vitest, @testing-library/vue and @testing-library/user-event)</p>
<pre><code>&lt;div class=&quot;field-checkbox&quot;&gt;
    &lt;Checkbox role = &quot;checkbox&quot; :aria-label=&quot;`Select all students in class ${props.className}`&quot; @change=&quot;selectAllChecked()&quot; v-model=&quot;selectAll&quot; :binary=&quot;true&quot; /&gt;
    &lt;label&gt;Select All&lt;/label&gt;
&lt;/div&gt;
</code></pre>
<p>I just want to write a test to check the checkbox and then test that it is correctly checked - not a particularly meaningful test but I'm new to these libraries (and unit testing) so want to work out how to do this stuff.</p>
<p>In my test I have:</p>
<pre><code>it(&quot;checkbox test&quot;, async() =&gt; {
    const ariaLabel = `Select all students in class ${mockProps.className}`;
    const checkbox = screen.getByRole(&quot;checkbox&quot;, { name: ariaLabel });
    await userEvent.click(checkbox);
    expect(checkbox.getAttribute('checked')).toBe(true)
});
</code></pre>
<p><strong>if I remove the 3rd and 4th lines, the test passes so it seems to be checking that the checkbox is there ok.</strong></p>
<p>Lines 3 and 4 (I hoped) would allow me to confirm that the checkbox is now checked but my test fails with</p>
<pre><code>AssertionError: expected null to be true // Object.is equality
  - Expected   &quot;true&quot;
  + Received   &quot;null&quot;
</code></pre>
<p>on the 4th line</p>
",https://stackoverflow.com/questions/73557108/simple-checkbox-test-with-vue-unit-testing-library,"['vue.js', 'unit-testing', 'vitest', 'vue-testing-library']",452,False,0,0
Code Coverage in VS2022 and SonarQube using test frameworks,"<p>We are using VS2022 for .net core web api application where we are planning to use any of the following unit test frameworks for unit testing and cove coverage. Also, the project will be configured on SonarQueb to see the detailed cove coverage.</p>
<ol>
<li>XUnit</li>
<li>NUnit</li>
<li>MSTest</li>
</ol>
<p>However, after doing some analysis we have observed that these tools doesnt actually give you the code coverage. These are used to write unit test cases only and not for code coverage.</p>
<p>So, the question is If we want to have the detailed code coverage on SonarQube for the configured project, then what are the alternative/additional things we need to implement?</p>
<p>As what we have understood writing only test cases is not going to provide actual code coverage.</p>
<p>Any help on this appreciated !</p>
",https://stackoverflow.com/questions/71934327/code-coverage-in-vs2022-and-sonarqube-using-test-frameworks,"['c#', 'unit-testing', 'asp.net-core', 'sonarqube', 'code-coverage']",2967,False,0,1
Rest end point unit testing using JWT token validation in Micronaut,"<p>Using micronaut to create rest end-point which is protected by using micronaut-jwt security</p>
<pre><code>        @Post
        @IRequirement(resourceName = ClaimType.TAG_PRODUCT, permission = {ClaimValue.TAG_OWNER,ClaimValue.TAG_CREATOR,ClaimValue.TAG_MAINTAINER })
        Mono&lt;MutableHttpResponse&lt;?&gt;&gt; post(@Body @Valid ProductModel model){
        LOG.info(String.format(&quot;Creating new product&quot;));
        return _iServiceBus.&lt;ProductModel, Mono&lt;ProductModel&gt;&gt;send(model).flatMap(item -&gt; {
                    if (item != null) {
                        try {
                            return Mono.just(HttpResponse.created(item, new URI(String.format(&quot;/%s&quot;, item.id()))));
                        } catch (URISyntaxException e) {
                            return Mono.error(new GlobalException(e));
                        }
                    } else
                        return Mono.just(HttpResponse.serverError());
                }
        ).onErrorMap(throwable -&gt; {
            throw new GlobalException(throwable);
        });}
</code></pre>
<p>Security model</p>
<pre><code>@Inherited
public @interface IRequirement {
    String resourceName();
    String[] permission();
}
</code></pre>
<p>Security rules</p>
<pre><code>@Singleton
public class AuthorityHandler implements SecurityRule {
    @Override
    public Publisher&lt;SecurityRuleResult&gt; check(HttpRequest&lt;?&gt; request, @Nullable RouteMatch&lt;?&gt; routeMatch, @Nullable Authentication authentication) {
        if (routeMatch instanceof MethodBasedRouteMatch methodBasedRouteMatch) {
            if (methodBasedRouteMatch.hasAnnotation(IRequirement.class)) {
                AnnotationValue&lt;IRequirement&gt; requiredPermissionAnnotation = methodBasedRouteMatch.getAnnotation(IRequirement.class);
                Optional&lt;String&gt; resourceIdName = requiredPermissionAnnotation.stringValue( &quot;resourceName&quot;);
                String[] permissions = requiredPermissionAnnotation.stringValues(&quot;permission&quot;);
                if (permissions.length &gt; 0 &amp;&amp; resourceIdName.isPresent() &amp;&amp; authentication != null) {
                    Map&lt;String, Object&gt; identityClaims = authentication.getAttributes();
                    if (Arrays.stream(permissions).anyMatch(element -&gt;  identityClaims.containsValue(element)))
                        return Mono.just(SecurityRuleResult.ALLOWED);
                    else
                        return Mono.just(SecurityRuleResult.REJECTED);
                }
            }
        }
        return Mono.just(SecurityRuleResult.UNKNOWN);
    }
}
</code></pre>
<p>The above end-point is protected as claims <code>owner</code>,<code>creator</code> and <code>maintainer</code></p>
<p>I am using Identity server 4 (<a href=""https://github.com/IdentityServer/IdentityServer4"" rel=""nofollow noreferrer"">https://github.com/IdentityServer/IdentityServer4</a>) to manage the identity and when the user logins in it contain the following claims in the access token</p>
<pre><code>{
  &quot;nbf&quot;: 1641548846,
  &quot;exp&quot;: 1641549046,
  &quot;iss&quot;: &quot;https://localhost:5001&quot;,
  &quot;client_id&quot;: &quot;Falcon_Identity_Server&quot;,
  &quot;sub&quot;: &quot;673533cc-7c0b-40f3-80ac-222696df385d&quot;,
  &quot;auth_time&quot;: 1641548840,
  &quot;idp&quot;: &quot;local&quot;,
  &quot;http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier&quot;: &quot;673533cc-7c0b-40f3-80ac-222696df385d&quot;,
  &quot;http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name&quot;: &quot;admin@local.com&quot;,
  &quot;http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress&quot;: &quot;admin@local.com&quot;,
  &quot;AspNet.Identity.SecurityStamp&quot;: &quot;812aa4cb-b9f1-48ac-9e39-1f0dceb6f1c4&quot;,
  &quot;identityserver&quot;: &quot;owner&quot;,
  &quot;fb_product&quot;: &quot;owner&quot;,
  &quot;fb_order&quot;: &quot;owner&quot;,
  &quot;fb_payment&quot;: &quot;owner&quot;,
  &quot;jti&quot;: &quot;179683F5CCA01EB925B45B1CA6379080&quot;,
  &quot;sid&quot;: &quot;F1D9F917D34178EDAF7A5FD24948F89D&quot;,
  &quot;iat&quot;: 1641548846,
  &quot;scope&quot;: [
    &quot;openid&quot;,
    &quot;profile&quot;,
    &quot;email&quot;
  ],
  &quot;amr&quot;: [
    &quot;pwd&quot;
  ]
}
</code></pre>
<p>The above end point is looking for those attributes</p>
<pre><code>&quot;identityserver&quot;: &quot;owner&quot;,
      &quot;fb_product&quot;: &quot;owner&quot;,
      &quot;fb_order&quot;: &quot;owner&quot;,
      &quot;fb_payment&quot;: &quot;owner&quot;,
</code></pre>
<p>For running an real application, it is working fine. I am trying to write the test case using micronaut httpclient. But not sure how can I test using micronaut test framework</p>
<p>Something I tried</p>
<pre><code>@Test
@DisplayName(&quot;Should create a JWT token&quot;)
void shouldCreateAJwtToken() {
    BearerAccessRefreshToken bearerAccessRefreshToken = null;
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(&quot;sherlock&quot;, &quot;password&quot;);
    HttpRequest request = HttpRequest.POST(&quot;/login&quot;, creds);
    HttpResponse&lt;BearerAccessRefreshToken&gt; rsp = client.toBlocking().exchange(request, BearerAccessRefreshToken.class);
    bearerAccessRefreshToken = rsp.body();

}
</code></pre>
<p>It creates a token but doesn't contain all the validation required for the above access token.</p>
<p>How do we do rest endpoint unit testing that is protected by JWT token in micronaut</p>
<p><strong>Authentication provider</strong></p>
<pre><code>@Singleton
@Requires(env = Environment.TEST)
public record AuthenticationProviderUserPasswordFixture() implements AuthenticationProvider {
    @Override
    public Publisher&lt;AuthenticationResponse&gt; authenticate(HttpRequest&lt;?&gt; httpRequest, AuthenticationRequest&lt;?, ?&gt; authenticationRequest) {
        return Flux.create(emitter -&gt; {
            if (authenticationRequest.getIdentity().equals(&quot;sherlock&quot;) &amp;&amp; authenticationRequest.getSecret().equals(&quot;password&quot;)) {
                emitter.next(AuthenticationResponse.success((String) authenticationRequest.getIdentity(), List.of(&quot;roles1&quot;, &quot;roles2&quot;)));
                emitter.complete();
            } else {
                emitter.error(AuthenticationResponse.exception());
            }
        }, FluxSink.OverflowStrategy.ERROR);
    }
}
</code></pre>
",https://stackoverflow.com/questions/70619463/rest-end-point-unit-testing-using-jwt-token-validation-in-micronaut,"['java', 'micronaut', 'micronaut-client', 'micronaut-rest']",585,False,0,1
"Unit Test Firebase Emulator (Auth, Functions, Security Rules)","<p>I am trying to setup unit tests with Node and Mocha to test Firebase Emulator. I have been following the documentation but find myself going in circles. I am stuck at creating users through the Authentication Emulator.</p>
<p>Some things I need to test:
Auth triggered functions - I will need to create users which will trigger the onCreate triggers
to fire.</p>
<p>I am coming from mobile dev, so my JS knowledge is not very mature. Any help is appreciated.</p>
<p>I have followed the following:
Security rule: this works great, but not what I need
<a href=""https://firebase.google.com/docs/rules/unit-tests"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/rules/unit-tests</a></p>
<p>Auth: not working, js not finding functions.
<a href=""https://firebase.google.com/docs/emulator-suite/connect_auth#node.js-admin-sdk"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/emulator-suite/connect_auth#node.js-admin-sdk</a></p>
<p>Functions: Also lost, offline/online mode unclear
<a href=""https://firebase.google.com/docs/functions/unit-testing"" rel=""nofollow noreferrer"">https://firebase.google.com/docs/functions/unit-testing</a></p>
",https://stackoverflow.com/questions/74567657/unit-test-firebase-emulator-auth-functions-security-rules,"['firebase', 'authentication', 'emulation']",66,False,0,0
"Mocha Error: ENOENT: no such file or directory, scandir &#39;./tests&#39;","<p>So I'm new in QA Testing, is learning in freecodecamp right now and got this code for the challenge. I've tried some TDD unit testing and worked. But when I tried a functional testing, I always got an error. Here is my code inside <code>2_functional-tests.js</code>:</p>
<pre><code>const chai = require('chai');
const assert = chai.assert;

const server = require('../server');

const chaiHttp = require('chai-http');
chai.use(chaiHttp);

suite('Functional Tests', function () {
  this.timeout(5000);'use strict'
  suite('Integration tests with chai-http', function () {
    // #1
    test('Test GET /hello with no name', function (done) {
      chai
        .request(server)
        .get('/hello')
        .end(function (err, res) {
          assert.fail(res.status, 200);
          assert.fail(res.text, 'hello Guest');
          done();
        });
    });
    // #2
    test('Test GET /hello with your name', function (done) {
      chai
        .request(server)
        .get('/hello?name=xy_z')
        .end(function (err, res) {
          assert.fail(res.status, 200);
          assert.fail(res.text, 'hello xy_z');
          done();
        });
    });
    // #3
    test('Send {surname: &quot;Colombo&quot;}', function (done) {
      chai
        .request(server)
        .put('/travellers')

        .end(function (err, res) {
          assert.fail();

          done();
        });
    });
    // #4
    test('Send {surname: &quot;da Verrazzano&quot;}', function (done) {
      assert.fail();

      done();
    });
  });
});

const Browser = require('zombie');

suite('Functional Tests with Zombie.js', function () {
  this.timeout(5000);



  suite('Headless browser', function () {
    test('should have a working &quot;site&quot; property', function() {
      assert.isNotNull(browser.site);
    });
  });

  suite('&quot;Famous Italian Explorers&quot; form', function () {
    // #5
    test('Submit the surname &quot;Colombo&quot; in the HTML form', function (done) {
      assert.fail();

      done();
    });
    // #6
    test('Submit the surname &quot;Vespucci&quot; in the HTML form', function (done) {
      assert.fail();

      done();
    });
  });
});
</code></pre>
<p>I'm running the code test using this command:</p>
<blockquote>
<p>mocha --ui tdd 2_functional-tests.js</p>
</blockquote>
<p>But I get an error of <code>ENOENT: no such file or directory, scandir './tests'</code>. I've tried to install all the required module and tried solution from any forum such clearing cache, deleting npm_modules folder, etc. I also installed all the required module from another required file, like in <em>('../server')</em> (line 4). But still got no luck. Unfortunately, I could run this code in <strong>replit.com</strong>. I'm using VS Code and got the error.</p>
<p>Any helpful response would be very appreciated!</p>
",https://stackoverflow.com/questions/74107211/mocha-error-enoent-no-such-file-or-directory-scandir-tests,"['javascript', 'node.js', 'mocha.js', 'tdd', 'chai']",45,False,0,0
How to run Multiple test cases using python unittest and init method?,"<p>I try to develop calculator to for unittest
I try to run test cases using python unittest and init method.I always getting this error.</p>
<p>error:</p>
<hr />
<p>AttributeError:'TestingClass' object has no attribute 'runTest'. Did you mean: 'subTest'?</p>
<hr />
<p>I try to fix this error using renaming method name runTest. But it only works for one test case.I want to run multiple test case.So I want to help with that.How to run multiple test cases?</p>
<p><em>this is my Calculator_test.py file</em></p>
<p><em><strong>#This is the Phython Unit Testing Module</strong></em></p>
<p>import unittest</p>
<p><em><strong>#This is the class we want to test. So, we need to import it</strong></em></p>
<p>import Calculator_steps as CalculatorClass</p>
<p>class TestingClass(unittest.TestCase):</p>
<pre><code>&quot;&quot;&quot;
The basic class that inherits unittest.TestCase
&quot;&quot;&quot;

def __init__(self, *args, **kwargs):
    super(TestingClass, self).__init__()
    self.calculator = CalculatorClass.Calculator()
</code></pre>
<p><em><strong>#Requirment 1: Verify Calculator accepts only whole numbers.</strong></em></p>
<pre><code>def runTest(self):
    with self.assertRaises(Exception):
        self.calculator.addNumbers('5.66,3.44')
</code></pre>
<p><em><strong>#Requirment 2: Verify Calculator does not accepts non numric values.</strong></em></p>
<pre><code>def test_NonNumeric(self):
    with self.assertRaises(Exception):
        self.calculator.addNumbers('5,6,e')
</code></pre>
<p><em>#This is my Calculator_steps.py file</em></p>
<p>class Calculator:</p>
<pre><code>def addNumbers(self,numberlist):
    total = &quot;&quot;
    return total
</code></pre>
",https://stackoverflow.com/questions/72878428/how-to-run-multiple-test-cases-using-python-unittest-and-init-method,"['python', 'python-unittest']",935,True,0,1
Open a port on mac for locally running spark,"<p>I am running a stand-alone Spark 3.2.1 locally, on my mac, installed via brew. This is for low-cost (free) unit testing purposes. I am starting this instance via pyspark command from terminal and able to access the instance web ui.</p>
<p>I am also trying to run spark-submit locally (from the same mac) to run a pyspark script on the pyspark instance described above. When specifying the --master :7077 I am getting the &quot;connection refused&quot; error. It does not look like the port 7077 is open on my mac.</p>
<p>How do I open the port 7077 on my mac such that I can access it from my mac via spark-submit, but other machines on the same network cannot?</p>
<p>Could someone share clear steps with explanations?</p>
<p>Much appreciated :)
Michael</p>
",https://stackoverflow.com/questions/72477254/open-a-port-on-mac-for-locally-running-spark,"['linux', 'macos', 'apache-spark', 'port', 'spark-submit']",270,False,0,1
Best practices for testing multi module android app,"<p>I have an application with 4 different modules. Network layer is separated in different module and I created a fake repository for unit testing in it.
The problem is that I cannot access that fake repository in my main module test classes (for creating test classes for viewmodels). I tried different solutions from google and none of them are working.</p>
<p>If I use something like this in gradle</p>
<pre><code>testImplementation(project(&quot;:data&quot;))
</code></pre>
<p>Test classes are still not visible.</p>
<p>My question is what are the best practices when writing tests for multi module android application? Is good practice to create one module for test and put everything related to testing from every module in that one? Or is there a way to make test classes from other modules visible in my main module?</p>
",https://stackoverflow.com/questions/73908839/best-practices-for-testing-multi-module-android-app,"['android', 'gradle', 'testing']",164,False,0,0
What is my mistake that the result of the unit test of a Shiny module doesn&#39;t make sense?,"<p>I have provided a minimal example Shiny app with two modules. The dataselect &amp; table module updates the second selectInput depending on the first selectInput and the plot module plots a timeline for the selected rows of data. I want to test the dataset &amp; table module with testthat package. I expected the result of this test to be passed, but it failed. I'm new to unit testing. What is my mistake? I appreciate any help.
This is the unit test that I have written:</p>
<pre><code>library(testthat)
library(shiny)
library(shinytest)
test_that(&quot;the right rows of data are selected &quot;, {
  testServer(dataselect_server, {
    session$setInputs(Nametype = Name1, Name=&quot;Aix galericulata&quot;)
  df&lt;-data.frame(Name1&lt;-&quot;Aix galericulata&quot;,
               Name2&lt;-&quot;Mandarin Duck&quot;,
               eventDate&lt;-&quot;2015-03-11&quot;,
               individualCount&lt;-1
  )
expect_true(identical(finalDf(), df))
  })
})
</code></pre>
<p>This is the result of the test:</p>
<pre><code>-- Warning (Line 2): the right rows of data are selected -----------------------
the condition has length &gt; 1 and only the first element will be used
Backtrace:
  1. shiny::testServer(...)
 26. shiny:::finalDf()
 28. self$.updateValue()
 29. ctx$run(...)
 36. env$runWith(self, func)
 37. shiny:::contextFunc()
 40. shiny:::.func()
 42. `&lt;reactive:finalDf&gt;`(...)

-- Warning (Line 2): the right rows of data are selected -----------------------
the condition has length &gt; 1 and only the first element will be used
Backtrace:
  1. shiny::testServer(...)
 26. shiny:::finalDf()
 28. self$.updateValue()
 29. ctx$run(...)
 36. env$runWith(self, func)
 37. shiny:::contextFunc()
 40. shiny:::.func()
 42. `&lt;reactive:finalDf&gt;`(...)

-- Warning (Line 2): the right rows of data are selected -----------------------
the condition has length &gt; 1 and only the first element will be used
Backtrace:
  1. shiny::testServer(...)
 26. shiny:::finalDf()
 28. self$.updateValue()
 29. ctx$run(...)
 36. env$runWith(self, func)
 37. shiny:::contextFunc()
 40. shiny:::.func()
 42. `&lt;reactive:finalDf&gt;`(...)

-- Failure (Line 2): the right rows of data are selected -----------------------
identical(finalDf(), df) is not TRUE

`actual`:   FALSE
`expected`: TRUE 
Backtrace:
  1. shiny::testServer(...)
 22. testthat::expect_true(identical(finalDf(), df))


Error: Test failed
</code></pre>
<hr />
<p>and this is the dataset &amp; table module code:</p>
<pre><code># Dataselect &amp; table module
dataselect_ui&lt;- function(id) {
  ns&lt;-NS(id)
  tagList(
    selectInput(ns(&quot;Nametype&quot;),&quot;Select a name type&quot;,
                choices=c(&quot;Name1&quot;,&quot;Name2&quot;,&quot;choose&quot;),selected = &quot;choose&quot;),

    selectInput(ns(&quot;Name&quot;),&quot;Select a name&quot;,
                choices=&quot;&quot;,selected = &quot;&quot;,selectize=TRUE),

    DT::DTOutput(ns(&quot;tab&quot;))
  )
}
dataselect_server &lt;- function(id) {
  moduleServer(id, function(input, output, session) {
    # Data preparation
    df&lt;-data.frame(Name1&lt;-c(&quot;Aix galericulata&quot;,&quot;Grus grus&quot;,&quot;    Alces alces&quot;),
                   Name2&lt;-c(&quot;Mandarin Duck&quot;,&quot;Common Crane&quot;  ,&quot;Elk&quot;),
                   eventDate&lt;-c(&quot;2015-03-11&quot;,&quot;2015-03-10&quot;,&quot;2015-03-10&quot;),
                   individualCount&lt;-c(1, 10, 1)
    )
    colnames(df)&lt;-c(&quot;Name1&quot;,&quot;Name2&quot;,&quot;eventDate&quot;,&quot;individualCount&quot;)

    # Putting columns Name1 and Nam2 of df in one column called nameType using melt()function
    # This format of data is needed for the choices argument of updateSelectizeInput()
    df2&lt;-reshape2::melt(df,id=c(&quot;eventDate&quot;,&quot;individualCount&quot;))
    colnames(df2)&lt;-c(&quot;eventDate&quot;,&quot;individualCount&quot;,&quot;nameType&quot;,&quot;Name&quot;)

    observeEvent(
      input$Nametype,
      updateSelectizeInput(session, &quot;Name&quot;, &quot;Select a name&quot;,
                           choices = unique(df2$Name[df2$nameType==input$Nametype]),selected = &quot;&quot;))


    # finalDf() is the data used to plot the table and plot
    finalDf&lt;-reactive({
      if(input$Name==&quot;choose&quot;){
        return(NULL)

      }
      if(input$Name==&quot;&quot;){
        return(NULL)

      }
      if(input$Nametype==&quot;choose&quot;){
        return(NULL)

      }

      # if the first selectInput is set to Name1, from df select rows their Name1 column are
      # equal to the second selectInput value
      else if(input$Nametype==&quot;Name1&quot;){
        finalDf&lt;-df[which(df$Name1==input$Name) ,]

      }
      # if the first selectInput is set to Name2, from df select rows their Name2 column are
      # equal to the second selectInput value
      else if(input$Nametype==&quot;Name2&quot;){
        finalDf&lt;-df[which(df$Name2==input$Name) ,]

      }
      return(finalDf)
    })

    output$tab&lt;-DT::renderDT({
      req(input$Name)
      datatable(finalDf(), filter = 'top',
                options = list(pageLength = 5, autoWidth = TRUE),
                rownames= FALSE)
    })

    return(
      list(&quot;finalDf&quot; = finalDf, &quot;input_Name&quot; = reactive(input$Name))
    )
  })
}
</code></pre>
<p>This is the app's other module (plot module):</p>
<pre><code># Plot module
plot_ui &lt;- function(id) {
  ns&lt;-NS(id)
  tagList(
    plotlyOutput(ns(&quot;plot&quot;))
  )
}

plot_server &lt;- function(id,input_Name ,finalDf) {
  moduleServer(id, function(input, output, session) {

    output$plot &lt;- renderPlotly({
      req(input_Name())
      p&lt;-ggplot(finalDf(),aes(x=eventDate,y=individualCount)) +geom_point(alpha=0.2, shape=21, color=&quot;black&quot;,fill=&quot;red&quot;,size=5)+
        labs( x = &quot;Date Event&quot;,y= &quot;Individual Count&quot;) +theme_bw()
      p&lt;-ggplotly(p)
      p
    })
  })
}
</code></pre>
<p>And the main app:</p>
<pre><code>source('modules/dataselect &amp; table_module.R')
source('modules/plot_module.R')


library(shiny)
library(plotly)
library(reshape2)

# application
ui &lt;- fluidPage(
               dataselect_ui(&quot;dataselect&quot;),
               plot_ui(&quot;plot1&quot;)
    )


server &lt;- function(session,input, output) {

  dataselect_outputs &lt;- dataselect_server(&quot;dataselect&quot;)
  plot_server(&quot;plot1&quot;,input_Name = dataselect_outputs$input_Name
                            ,finalDf= dataselect_outputs$finalDf)

}

shinyApp(ui = ui, server = server)
</code></pre>
<hr />
<p><strong>EDIT:</strong></p>
<p>I modified the code as per @Stéphane Laurent's recommendation:</p>
<pre><code>test_that(&quot;the right rows of data are selected&quot;, {
  testServer(dataselect_server, {
    session$setInputs(Nametype = &quot;Name1&quot;, Name=&quot;Aix galericulata&quot;)
  df&lt;-data.frame(Name1=&quot;Aix galericulata&quot;,
               Name2=&quot;Mandarin Duck&quot;,
               eventDate=&quot;2015-03-11&quot;,
               individualCount=1
  )
  expect_identical(finalDf(), df)
  })
})
</code></pre>
<p>And it returned an error:</p>
<pre><code>-- Error (Line 2): the right rows of data are selected -------------------------
Error in `module(childScope$input, childScope$output, childScope, ...)`: attempt to apply non-function
Backtrace:
  1. shiny::testServer(...)
 23. shiny::moduleServer(...)
 25. shiny::callModule(module, id, session = session)
 30. module(childScope$input, childScope$output, childScope, ...)

Error: Test failed
</code></pre>
",https://stackoverflow.com/questions/74619158/what-is-my-mistake-that-the-result-of-the-unit-test-of-a-shiny-module-doesnt-ma,"['r', 'unit-testing', 'shiny', 'shinyapps', 'shinymodules']",96,False,0,1
What does this do in C++? []() {}(),"<p>I am unit testing for code coverage, making sure that every possible code path is executed by a unit test.</p>
<p>I find that a switch/case element which merely contains a break can be breakpointed, but that the break is never hit, control just jumps to the end of the switch, presumably because of compiler optimization.</p>
<p>A colleague is arguing that that I have not adequately unit test that path.</p>
<p>So, I searched and found an S.O question - which I can not longer find - about C++ code that does nothing. The only answer that didn't also get optimized away of generate compiler or static code analysis errors was <code>[]() {}()</code>.</p>
<p>This works, insomuch as a breakpoint on it will be hit.</p>
<p>Problem solved, I guess, but what does that actually do?</p>
",https://stackoverflow.com/questions/73202761/what-does-this-do-in-c,['c++'],76,True,0,1
How to check in SystemVerilog that signal went high during simulation using ModelSim,"<p>I need to check, whether during the testbenching the particular signal went at least for a single clock cycle to logic 1.</p>
<p>I've tested following asserts, which shall be equivalent:</p>
<pre class=""lang-systemverilog prettyprint-override""><code>    initial assert property (
        @(posedge clk_tree_x.ClkRsBST_ix.clk)
            s_eventually TS.TSUpdated) else
      $error(&quot;Was not active&quot;);
</code></pre>
<p>and</p>
<pre class=""lang-sv prettyprint-override""><code>   initial begin
      assert property (@(posedge clk_tree_x.ClkRsBST_ix.clk)
               strong(##[*] TS.TSUpdated)) else
    $error(&quot;Was not active&quot;);
   end
</code></pre>
<p>In simulation using Mentor ModelSim SE64 2021.1 the results are extremely weird.</p>
<p>On <em>first simulation pass</em> the simulation completely ignores this assert. On  <em>second simulation pass</em> ModelSim apparently uses results of previous simulation to announce <em>before even the newly run simulation happens</em> that the assert triggered:</p>
<pre><code>#    Time: 2005087500 ps Started: 5 ns  Scope: tb_bst_provider.DUT.fook File: bst_provider.sv Line: 669
# ** Warning: (vsim-8777) Breakpointing based on severity while evaluating concurrent assertion is not supported.
#    Time: 2005087500 ps  Iteration: 0  Region: /tb_bst_provider/DUT File: bst_provider.sv
</code></pre>
<p>Not sure whether this is consistent behaviour to all strong properties, but it is hardly useful for any sort of unit testing, as the tests never run twice using the same parameters.</p>
<p>Is there any way how to assert that 'signal is not present through the simulation run', which actually works with modelsim?</p>
",https://stackoverflow.com/questions/71110703/how-to-check-in-systemverilog-that-signal-went-high-during-simulation-using-mode,['system-verilog-assertions'],702,True,0,1
Close GRPC Netty channel in Scala Spark App,"<p>I'm trying to cleanly close a set of channels created during processing of a Spark map function. When I introduce the &quot;shutdown/awaitTermination&quot; methods after the main processing part (right before returning the &quot;Result&quot;), I get errors in other calls. As if the channel was shutdown prematurely (due to Spark scheduling of the actual tasks, I guess). Any recommendation? I have the following flow:</p>
<pre><code>        val someDF = initialDF.mapPartitions(iterator =&gt; {
            val caller = createChannel(certificate, URI, port)

            val innerDF = iterator.map(row =&gt; {
                //do stuff with caller created above

            result
        }).toDF()
</code></pre>
<p>If I don't shutdown the channel, it runs fine (except I get some error messages in unit testing). But if I create a new channel during execution after the code as above, I end up with the following error:</p>
<blockquote>
<p>ERROR io.grpc.internal.ManagedChannelOrphanWrapper - <em>~</em>~<em>~ Channel ManagedChannelImpl{logId=41, target=blablabla:443} was not shutdown properly!!! ~</em>~<em>~</em></p>
</blockquote>
<p>How should I shutdown these channels? I'm not too bright with Spark...</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/74021837/close-grpc-netty-channel-in-scala-spark-app,"['scala', 'apache-spark', 'grpc', 'netty']",46,False,0,0
Mocking a File object in NestJs unit test with Jest,"<p>I recently started working with Nest.js and its built-in unit testing library Jest, while on a task to upload a .CSV file and perform some operations on it, I decided to also unit test the endpoint and this required me to mock the CSV file object, which I did as thus</p>
<pre><code>const mockFile = {
  fieldname: 'file',
  originalname: 'TradeHistory.csv',
  encoding: '7bit',
  mimetype: 'text/csv',
  buffer: Buffer.from(__dirname + '/../../TradeHistory.csv', 'utf8'),
  size: 51828,
}
</code></pre>
<p>I quickly ran into these issues;</p>
<ul>
<li>For file upload, I was using the @UseInterceptors() and @UploadedFile()</li>
<li>which takes a type of <strong>file: Express.Multer.File</strong></li>
<li>Which won't accept my mocked file <strong>object</strong> type as an argument</li>
</ul>
<p>So I searched for a way to convert the mocked file into a type <strong>Express.Multer.File</strong>
and after a while what worked for me turned out to be embarrassingly simple and straightforward as using the type assertion <strong>as</strong> keyword to cast the file object <strong>Express.Multer.File</strong></p>
<pre><code>const mockFile = {
  fieldname: 'file',
  originalname: 'TradeHistory.csv',
  encoding: '7bit',
  mimetype: 'text/csv',
  buffer: Buffer.from(__dirname + '/../../TradeHistory.csv', 'utf8'),
  size: 51828,
} as Express.Multer.File
</code></pre>
<p>Other ways might exist, I'm open to suggestions</p>
",https://stackoverflow.com/questions/72825349/mocking-a-file-object-in-nestjs-unit-test-with-jest,"['unit-testing', 'file-upload', 'nestjs', 'multer', 'type-assertion']",1234,False,4,0
JEST unit test script fails with TypeError: this._environment.runScript is not a function,"<p>I was assigned a task of setting up Jest unit testing for a Vue application. I had several attempts at accomplishing it and solved several issues on the way thanks to other questions here. However, now I'm stuck with the following error when I do <code>npm run test:unit</code> (&quot;test:unit&quot;: &quot;vue-cli-service test:unit&quot;):</p>
<pre><code>TypeError: this._environment.runScript is not a function

  at Runtime._execModule (node_modules/@vue/cli-plugin-unit-jest/node_modules/jest-runtime/build/index.js:856:41)
</code></pre>
<p>Following is the Jest config I added to the package.json:</p>
<pre><code>&quot;jest&quot;: {
    &quot;testEnvironment&quot;: &quot;jsdom&quot;,
    &quot;preset&quot;: &quot;ts-jest&quot;,
    &quot;moduleNameMapper&quot;: {
      &quot;\\.(css|less|sass|scss)$&quot;: &quot;&lt;rootDir&gt;/tests/mocks/styleMock.js&quot;,
      &quot;^@/(.*)$&quot;: &quot;&lt;rootDir&gt;/src/$1&quot;
    },
    &quot;transform&quot;: {
      &quot;&lt;rootDir&gt;/src/data/.+\\.(j|t)sx?$&quot;: &quot;ts-jest&quot;,
      &quot;.*\\.(vue)$&quot;: &quot;vue-jest&quot;,
      &quot;.*\\.(js)$&quot;: &quot;babel-jest&quot;
    },
    &quot;transformIgnorePatterns&quot;: [
      &quot;/node_modules/(?!vuetify)&quot;,
      &quot;&lt;rootDir&gt;/src/(?!data/.*)&quot;
    ],
    &quot;testPathIgnorePatterns&quot;: [
      &quot;/node_modules/(?!vuetify)&quot;
    ]
  }
</code></pre>
<p>Originally, I had 'node' for testEnvironment. But I've gotten the this._environment.runScript is not a function error for the first time. I've read that I could use 'jsdom' instead. For that I updated babel.config.js:</p>
<pre><code>module.exports = {
   env: {
     test: {
       presets: [['env', { targets: { node: 'current' } }]],
       plugins: ['@babel/plugin-transform-modules-commonjs'],
     },
   },
}
</code></pre>
<p>But this resulted in the error saying that babel-preset-env module is missing. As I understood, the module is not a stand-alone module anymore. So, I changed babel.config.js:</p>
<pre><code>module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        modules: 'commonjs',
        targets: {
          node: 'current',
        },
      },
    ],
  ],
}
</code></pre>
<p>And now I'm back to TypeError: this._environment.runScript is not a function. Has anyone encountered a similar problem? Would appreciate your help.</p>
",https://stackoverflow.com/questions/71117593/jest-unit-test-script-fails-with-typeerror-this-environment-runscript-is-not-a,"['javascript', 'unit-testing', 'vuejs2', 'jestjs']",3030,False,8,1
Building Antlr4&#39;s Java distribution fails because the test for the &quot;antlr4 maven plugin&quot; fails with a NullPointerException,"<p>I want to compile the ANTLR4 Java distribution using Maven. But it won't work.</p>
<p>I am probably going about this problem wrongly. There may be something very simple I am missing. Probably the way I'm calling Maven in the first place. The fact that absolutely no-one on the Internet seems to have this problem indicates as much.</p>
<h2>What happens</h2>
<p>First, my Java version:</p>
<pre><code>$ java -version
openjdk version &quot;17.0.3&quot; 2022-04-19
OpenJDK Runtime Environment Temurin-17.0.3+7 (build 17.0.3+7)
OpenJDK 64-Bit Server VM Temurin-17.0.3+7 (build 17.0.3+7, mixed mode, sharing)
</code></pre>
<p>(But note that ANLTR4 is compiled to Java 11, except for the plugin which is compiled to Java 8, according to the POM)</p>
<p>So. Get the distribution from github:</p>
<pre><code>$ git clone https://github.com/antlr/antlr4.git antlr4_30`
$ cd antlr4_30
$ git status
On branch master
Your branch is up to date with 'origin/master'.
</code></pre>
<p>Compile the projects (Maven modules)</p>
<ul>
<li><code>runtime/Java</code> (the ANTLR4 <em>core classes</em>)</li>
<li><code>tool</code> (the ANTLR4 <em>compiler</em>)</li>
<li><code>antlr4-maven-plugin</code> (the <em>maven plugin</em> that runs ANTLR4 tasks)</li>
</ul>
<pre><code>PROJECTS=&quot;runtime/Java,tool,antlr4-maven-plugin&quot;
mvn --projects &quot;$PROJECTS&quot; clean
mvn --projects &quot;$PROJECTS&quot; verify
</code></pre>
<p>Compilation works, then the tests for the <em>maven plugin</em> kick off.</p>
<p>These tests are run using another <em>maven plugin</em> by &quot;Takari&quot; for plugin unit testing: <a href=""http://takari.io/book/70-testing.html#plugin-unit-testing"" rel=""nofollow noreferrer"">Plugin Unit Testing</a>.</p>
<p>The ANTLR4 Maven plugin tests fail:</p>
<pre><code>java.lang.NullPointerException: Cannot invoke
&quot;org.apache.maven.model.Plugin.getGroupId()&quot;
because the return value of 
&quot;org.apache.maven.plugin.MojoExecution.getPlugin()&quot; 
is null
</code></pre>
<p>with the interesting part of the stack trace:</p>
<pre><code>org.apache.maven.lifecycle.internal.
DefaultMojoExecutionConfigurator.configure(DefaultMojoExecutionConfigurator.java:44)
(called by) io.takari.maven.testing.
            Maven331Runtime.lookupConfiguredMojo(Maven331Runtime.java:37)
(called by) io.takari.maven.testing.
            Maven325Runtime.executeMojo(Maven325Runtime.java:34)
(called by) io.takari.maven.testing.
            TestMavenRuntime.executeMojo(TestMavenRuntime.java:269)
(called by) org.antlr.mojo.antlr4.
            Antlr4MojoTest.processWhenDependencyRemoved(Antlr4MojoTest.java:326)
</code></pre>
<h2>So what's going on?</h2>
<p>After a lengthy trawl through the source code (code which is not straightforward to read but unfortunately lacks comments, logging or assertions, these would be useful), we find:</p>
<p>In class <code>org.antlr.mojo.antlr4.Antlr4MojoTest</code> (file <code>antlr4-maven-plugin/src/test/java/org/antlr/mojo/antlr4/Antlr4MojoTest.java</code>), the failing test cases perform the following (example of test case <code>processWhenDependencyRemoved()</code>, slightly modified &amp; commented):</p>
<pre><code>// Junit4 rule
@Rule
public final TestMavenRuntime maven = new TestMavenRuntime();

@Test
public void processWhenDependencyRemoved() throws Exception {
   Path baseDir = resources.getBasedir(&quot;dependencyRemoved&quot;).toPath();
   Path antlrDir = baseDir.resolve(&quot;src/main/antlr4&quot;);
   Path baseGrammar = antlrDir.resolve(&quot;imports/HelloBase.g4&quot;);
   MavenProject project = maven.readMavenProject(baseDir.toFile());
   MavenSession session = maven.newMavenSession(project);
   String goal = &quot;antlr4&quot;;

   // Get a &quot;org.apache.maven.plugin.MojoExecution&quot; from the 
   // &quot;io.takari.maven.testing.TestMavenRuntime&quot; instance.

   assertTrue(maven instanceof io.takari.maven.testing.TestMavenRuntime);

   MojoExecution exec = maven.newMojoExecution(goal); 

   maven.executeMojo(session, project, exec);

   ...
</code></pre>
<p>Now, <code>org.apache.maven.plugin.MojoExecution</code> (the <code>exec</code> instance) provides a <code>.getPlugin()</code> method which returns <code>null</code> instead of a valid instance of <code>org.apache.maven.model.Plugin</code> (a class generated by <code>Modello</code> when Maven itself is compiled).</p>
<p>After two stack frames, <code>org.apache.maven.lifecycle.internal.DefaultMojoExecutionConfigurator.configure()</code> is called, but then fails immediately in a chained call:</p>
<pre><code>public void configure( MavenProject project, MojoExecution mojoExecution, boolean allowPluginLevelConfig )
{
   String g = mojoExecution.getPlugin().getGroupId();
   String a = mojoExecution.getPlugin().getArtifactId();
   Plugin plugin = findPlugin( g, a, project.getBuildPlugins() );
   ...
</code></pre>
<p>Why does <code>getPlugin()</code> return <code>null</code>? From maven's <code>org.apache.maven.plugin.MojoExecution</code>, file <code>core/maven-3/maven-core/src/main/java/org/apache/maven/plugin/MojoExecution.java</code>:</p>
<pre><code>public Plugin getPlugin()
{
    if ( mojoDescriptor != null )
    {
        return mojoDescriptor.getPluginDescriptor().getPlugin();
    }
    return plugin;
}
</code></pre>
<p>I our case, <code>mojoDescriptor</code> is not null, but <code>mojoDescriptor.getPluginDescriptor().getPlugin()</code> is, which is bad.</p>
<p>I have no idea why the <code>Plugin</code> instance is not set, or even where it is supposed to be set.</p>
<p>At some point, Maven's <code>org.apache.maven.plugin.descriptor.PluginDescriptorBuilder</code> is called from Takari's <code>io.takari.maven.testing.Maven30xRuntime</code> (<a href=""https://github.com/takari/takari-plugin-testing-project/blob/master/takari-plugin-testing/src/main/java/io/takari/maven/testing/Maven30xRuntime.java"" rel=""nofollow noreferrer"">source</a>) to build <code>org.apache.maven.plugin.descriptor.PluginDescriptor</code> from the <code>plugin.xml</code> resource and that works nicely but the <code>plugin</code> member is not set at that time. The data structures are not straightforward. Below, for what it's worth, the relationship between a few of the classes.</p>
<p><a href=""https://i.stack.imgur.com/R2Wzt.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/R2Wzt.png"" alt=""Some classes of interest"" /></a></p>
",https://stackoverflow.com/questions/73914766/building-antlr4s-java-distribution-fails-because-the-test-for-the-antlr4-maven,"['maven', 'antlr4']",343,True,2,1
how to stub a function for unit testing using mocktail,"<p>i'm using mocktail package to mock my repositories for unit testing. I already tested out few of my controllers and its passing, until i encountered a error in my <code>submitPhoneNumber</code> method which I cant figure out where the problem is and what am i missing.</p>
<p>The setup is I'm stubbing my <code>controller.submitPhoneNumber</code> to answer a <code>Future.value(true)</code>,  which means success. so my expectations are  the <code>authRepository.registerWithPhoneNumber</code> method should be called 1 time and the <code>debugState.value.hasError</code> should be false. But i'm getting this error:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>No matching calls. All calls: MockFirebaseAuthRepository.registerWithPhoneNumber(+15551234567, Closure: (String) =&gt; void, Closure: () =&gt; void)
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
package:test_api                                                                                        fail
package:mocktail/src/mocktail.dart 722:7                                                                _VerifyCall._checkWith
package:mocktail/src/mocktail.dart 515:18                                                               _makeVerify.&lt;fn&gt;
test/src/features/authentication/presentation/sign_in/phone_sign_in/sign_in_controller_test.dart 41:13  main.&lt;fn&gt;.&lt;fn&gt;</code></pre>
</div>
</div>
</p>
<p>this means that the <code>controller.submitPhoneNumber</code> has not been called and the <code>debugState.value.hasError</code> is true. But in actual, my controller is working fine in both emulator and physical device.</p>
<p>I cant figure out why this is happening so maybe I made mistake on how I stubbed my function.
Appreciated so much if someone could help me figure this out.</p>
<p>Here is my test:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>void main() {



  group('controller submit phone number test', () {
    final controller = SignInController(
        formType: SignInFormType.register, authRepository: authRepository);

    test('submit phonumber success', () async {
      const phoneNumber = '+15551234567';

///this is where the error is comming from

      when(() =&gt; controller.submitPhoneNumber(phoneNumber, (e) {}, () {}))
          .thenAnswer((_) =&gt; Future.value(true));

      await controller.submitPhoneNumber(phoneNumber, (e) {}, () {});
      
      verify(() =&gt; authRepository.registerWithPhoneNumber(
          phoneNumber, (e) {}, () {})).called(1);
      expect(controller.debugState.value.hasError, false);
      expect(controller.debugState.formType, SignInFormType.register);
      expect(controller.debugState.value, isA&lt;AsyncValue&gt;());
    }, timeout: const Timeout(Duration(milliseconds: 500)));

}</code></pre>
</div>
</div>
</p>
<p>And here is my controller</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-html lang-html prettyprint-override""><code>class SignInController extends StateNotifier&lt;SignInState&gt; {
  SignInController({
    required SignInFormType formType,
    required this.authRepository,
  }) : super(SignInState(formType: formType));
  final AuthRepository authRepository;

  Future&lt;bool&gt; submitPhoneNumber(String phoneNumber,
      void Function(String e) verificationFailed, VoidCallback codeSent) async {
    state = state.copyWith(value: const AsyncValue.loading());
    final value =
        await AsyncValue.guard(() =&gt; authRepository.registerWithPhoneNumber(
              phoneNumber,
              verificationFailed,
              codeSent,
            ));
    state = state.copyWith(value: value);
    return value.hasError == false;
  }

}


final signInControllerProvider = StateNotifierProvider.autoDispose
    .family&lt;SignInController, SignInState, SignInFormType&gt;((ref, formType) {
  final authRepository = ref.watch(authRepositoryProvider);
  return SignInController(
    authRepository: authRepository,
    formType: formType,
  );
});</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/74169184/how-to-stub-a-function-for-unit-testing-using-mocktail,"['flutter', 'unit-testing', 'mocking']",587,True,1,1
Is it possible to use FyTest in Microsoft Visual Studio without CMake?,"<p>I am developing on an old legacy code in Fortran, and I am trying to implement unit testing to enable a more secure development environment. From all the options given in the Fortran Wiki on <a href=""https://fortranwiki.org/fortran/show/Unit+testing+frameworks"" rel=""nofollow noreferrer"">this page</a>, I evaluated FyTest would be the most suitable one.</p>
<p>However, to automatically run the tests, it needs a CMake build instruction, which currently I don't have installed on the company computer (I could ask for its necessity, but that is a long and tiresome process I am trying to avoid). The company software for development is Microsoft Visual Studio (version 2010). Is there a way &quot;native&quot; to Visual Studio for running FyTest? I noticed that creating a project in Visual Studio creates a &quot;solution file&quot; (<code>.sln</code>), but I don't know if it is possible to adapt it to do the same work as CMake would do...</p>
",https://stackoverflow.com/questions/72883356/is-it-possible-to-use-fytest-in-microsoft-visual-studio-without-cmake,"['visual-studio', 'cmake', 'fortran']",76,True,1,1
Functioning fake for Cosmos DB SQL API,"<p>I am maintaining a large system that I did not design or build myself. The system has exceptionally large files and services. Unit testing is extremely hard to write without splitting the services into smaller units, which do only one thing.</p>
<p>Now, the system comes with a series of integration tests that use the Cosmos DB Emulator. It takes about 8 minutes to start the Cosmos DB Emulator on the CI-pipeline and we must run the tests in sequence. All together the process takes more than 15 minutes which I think is unacceptable.</p>
<p>I am looking for a functional fake for Cosmos DB (SQL API) to use instead of the emulator. I would like to avoid writing the code myself, but a few Google-searches returned nothing usable.</p>
<p>PS. We have spent a lot of time trying to optimize the CI-pipeline.</p>
",https://stackoverflow.com/questions/72646839/functioning-fake-for-cosmos-db-sql-api,"['.net', 'azure-cosmosdb']",343,True,1,2
Reflecting Vector along Perpendicular,"<p>With much help from the SO community, I've created a program where a ball is in a triangle with a certain position and velocity. Using parametric equations, I've determined where the ball will hit the triangle. I then found the perpendicular to the side of the triangle where the ball would hit, so that I could reflect the ball off the wall, to plot its &quot;bounce&quot; trajectory. My goal is that I can plot how the ball will bounce off the walls for <em>n</em> iterations. But I've come up against a problem.</p>
<p>Even though I'm using the p5.js <code>A.reflect(B)</code> method to reflect the ball along the perpendicular, it's producing some truly strange results.
<a href=""https://i.stack.imgur.com/0Fqq8.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/0Fqq8.png"" alt=""enter image description here"" /></a>
I've tried many things (i.e., modifying the <code>getPerp()</code> function, unit testing, etc.), but to no avail. Any help would be greatly appreciated. MWE below and in <a href=""https://codepen.io/Refath/pen/jOaGLJM?editors=1010"" rel=""nofollow noreferrer""><strong>Codepen</strong></a>.</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""true"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code snippet-currently-hidden"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>let angle = 0;
let sides = [];
let vertices = [];
const len = 100;

function setup() {
    createCanvas(windowWidth, windowHeight);
    angleMode(DEGREES);

    angleOne = createSlider(0, 89, 60);
    angleOne.position(10, 10);
    angleOne.style(""width"", ""80px"");

    angleTwo = createSlider(0, 89, 60);
    angleTwo.position(10, 30);
    angleTwo.style(""width"", ""80px"");

    rotateVel = createSlider(0, 360, 60);
    rotateVel.position(10, 50);
    rotateVel.style(""width"", ""80px"");

    // Initial vertice &amp; side setup (these don't change)
    let v1 = createVector(width / 2 - len / 2, height / 2);
    let v2 = createVector(width / 2 + len / 2, height / 2);

    sides[0] = new Side(v1.x, v1.y, v2.x, v2.y, ""green"");

    vertices[0] = new Vertex(v1.x, v1.y);
    vertices[1] = new Vertex(v2.x, v2.y);
}

function draw() {
    background(255);

    let angOne = angleOne.value();
    let angTwo = angleTwo.value();
    let rotVel = rotateVel.value();
    fill(0);
    strokeWeight(0);
    textSize(15);
    text(angOne, 100, 25);
    text(angTwo, 100, 45);
    text(rotVel, 100, 65);

    let v2Offset = createVector(len * cos(-angOne), len * sin(-angOne));
    let v3Offset = createVector(-len * cos(angTwo), -len * sin(angTwo));

    vertices[2] = new Vertex(
        vertices[0].a.x + v2Offset.x,
        vertices[0].a.y + v2Offset.y
    );
    vertices[3] = new Vertex(
        vertices[1].a.x + v3Offset.x,
        vertices[1].a.y + v3Offset.y
    );

    // Update the sides
    sides[1] = new Side(
        vertices[0].a.x,
        vertices[0].a.y,
        vertices[2].a.x,
        vertices[2].a.y
    );

    sides[3] = new Side(
        vertices[1].a.x,
        vertices[1].a.y,
        vertices[3].a.x,
        vertices[3].a.y
    );

    const m1 =
        (vertices[2].a.y - vertices[0].a.y) / (vertices[2].a.x - vertices[0].a.x);

    const m2 =
        (vertices[3].a.y - vertices[1].a.y) / (vertices[3].a.x - vertices[1].a.x);

    // Calculate the y-offset relative to vertices[0]
    const b2 = (vertices[1].a.x - vertices[0].a.x) * -m2;

    const xInt = b2 / (m1 - m2);
    const yInt = xInt * m1;
    // Note xInt and yInt are relative to vertices[0]

    // draw all the things
    // sides.forEach((s) =&gt; s.show());

    // stroke(0, 255, 0);
    // strokeWeight(20);
    point(vertices[0].a.x + xInt, vertices[0].a.y + yInt);

    vertices[4] = new Vertex(vertices[0].a.x + xInt, vertices[0].a.y + yInt);

    sides[4] = new Side(
        vertices[1].a.x,
        vertices[1].a.y,
        vertices[0].a.x + xInt,
        vertices[0].a.y + yInt,
        ""blue""
    );

    sides[5] = new Side(
        vertices[0].a.x,
        vertices[0].a.y,
        vertices[0].a.x + xInt,
        vertices[0].a.y + yInt,
        ""purple""
    );

    scale(4); // so I can make the triangle actually *visible*
    translate(-width / 3, -height / 3);

    sides[0].show();
    sides[4].show();
    sides[5].show();

    vertices[0].show();
    vertices[1].show();
    vertices[4].show();

    strokeWeight(1);
    stroke(255, 0, 0);
    noFill();
    arc(vertices[0].a.x, vertices[0].a.y, 40, 40, -1 * angleOne.value(), 0, PIE);
    arc(
        vertices[1].a.x,
        vertices[1].a.y,
        40,
        40,
        -180,
        -(180 - angleTwo.value()),
        PIE
    );

    stroke(0);
    // stroke(""purple""); // Change the color
    strokeWeight(5); // Make the points 10 pixels in size

    let P1x = vertices[0].a.x;
    let P1y = vertices[0].a.y;

    let P0 = createVector(P1x + 60, P1y - 40);

    push();
    let V0 = createVector(10 * cos(rotVel), 10 * sin(-rotVel));
    pop();

    point(P0.x, P0.y);

    // point(P0.x + V0.x, P0.y + V0.y);
    strokeWeight(2);
    line(P0.x, P0.y, P0.x + V0.x, P0.y + V0.y);

    let hit = wallHit(P0, V0);
    // print(""hit[0] is"", hit[0]);
    hitPoint = createVector(P0.x + V0.x * hit[0], P0.y + V0.y * hit[0]);

    let A = createVector(
        vertices[4].a.x - vertices[1].a.x,
        vertices[4].a.y - vertices[1].a.y
    );
    // let B = p5.Vector.sub(vertices[1].a, vertices[2].a);
    // let C = p5.Vector.sub(vertices[2].a, vertices[4].a);
    // findNormal(hitPoint, A);
    setLineDash([5, 5]);
    stroke(0);

    // let perpA = getY(vertices[1].a.x - 100, hitPoint);
    // let normalA = createVector(vertices[1].a.x - 100, perpA);
    // let incVec = createVector(hitPoint.x, hitPoint.y);
    // let refVec = normalA.reflect(incVec);
    let IOne = createVector(0, 0);
    let ITwo = createVector(0, 0);
    let IThree = createVector(0, 0);

    // line(hitPoint.x, hitPoint.y, normalA.x, normalA.y);
    let AOne = createVector(P1x, P1y);
    let ATwo = createVector(vertices[1].a.x, vertices[1].a.y + 0.1);
    let AThree = createVector(
        (P1x + vertices[1].a.x) / 2,
        (P1y + vertices[1].a.y) / 2
    );
    // getPerp(AOne, ATwo, hitPoint);

    let BOne = createVector(P1x, P1y);
    let BTwo = createVector(vertices[4].a.x, vertices[4].a.y + 0.1);
    let BThree = createVector(
        (P1x + vertices[4].a.x) / 2,
        (P1y + vertices[4].a.y) / 2
    );
    // getPerp(BOne, BTwo, hitPoint);

    let COne = createVector(vertices[1].a.x, vertices[1].a.y);
    let CTwo = createVector(vertices[4].a.x, vertices[4].a.y + 0.1);
    let CThree = createVector(
        (vertices[1].a.x + vertices[4].a.x) / 2,
        (vertices[1].a.y + vertices[4].a.y) / 2
    );
    // getPerp(COne, CTwo, hitPoint);
    let incVec = createVector(hitPoint.x, hitPoint.y);
    line(P0.x, P0.y, incVec.x, incVec.y);
    let perp = getPerp(IOne, ITwo, IThree);

    let testOne = createVector(vertices[0].a.x + 20, vertices[0].a.y + 20);
    let testTwo = createVector(vertices[1].a.x + 20, vertices[1].a.y + 20);
    let refVec = testOne.reflect(testTwo);
    // line(testOne.x, testOne.y, testTwo.x, testTwo.y);

    if (hit[1] == ""t3"") {
        perp = getPerp(AOne, ATwo, hitPoint);
        refVec = perp.reflect(incVec);
    } else if (hit[1] == ""t1"") {
        perp = getPerp(BOne, BTwo, hitPoint);
        refVec = perp.reflect(incVec);
    } else {
        perp = getPerp(COne, CTwo, hitPoint);
        refVec = perp.reflect(incVec);
    }
    stroke(""black"");
    line(hitPoint.x, hitPoint.y, refVec.x, refVec.y);

    setLineDash([0, 0]);
}

function setLineDash(list) {
    drawingContext.setLineDash(list);
}

class Side {
    constructor(x1, y1, x2, y2, col = ""black"") {
        this.a = createVector(x1, y1);
        this.b = createVector(x2, y2);
        this.color = col;
    }

    show() {
        stroke(this.color);
        strokeWeight(4);
        line(this.a.x, this.a.y, this.b.x, this.b.y);
    }
}

class Vertex {
    constructor(x1, y1) {
        this.a = createVector(x1, y1);
    }

    show() {
        stroke(255, 0, 0);
        strokeWeight(10);
        point(this.a.x, this.a.y);
    }
}

function wallHit(pos, vel) {
    let P1x = vertices[0].a.x;
    let P1y = vertices[0].a.y;

    let P2x = vertices[1].a.x;
    let P2y = vertices[1].a.y;

    let P3x = vertices[4].a.x;
    let P3y = vertices[4].a.y;

    let A1 = P3y - P1y;
    let B1 = -(P3x - P1x);
    let C1 = A1 * P1x + B1 * P1y;

    let A2 = -(P3y - P2y);
    let B2 = P3x - P2x;
    let C2 = A2 * P2x + B2 * P2y;

    let A3 = -(P2y - P1y);
    let B3 = P2x - P1x;
    let C3 = A3 * P2x + B3 * P2y;

    let t1 = (C1 - A1 * pos.x - B1 * pos.y) / (A1 * vel.x + B1 * vel.y);
    let t2 = (C2 - A2 * pos.x - B2 * pos.y) / (A2 * vel.x + B2 * vel.y);
    let t3 = (C3 - A3 * pos.x - B3 * pos.y) / (A3 * vel.x + B3 * vel.y);

    let times = [t1, t2, t3];
    let posTimes = [];

    for (let i = 0; i &lt; times.length; i++) {
        times[i] = round(times[i], 2);
    }

    // console.log(""After rounding:"", times);

    for (let i = 0; i &lt; times.length; i++) {
        if (times[i] &gt; 0) {
            posTimes.push(times[i]);
        }
    }

    let hitPoint = createVector(0, 1);
    // console.log(""posTimes:"", posTimes);
    trueTime = min(posTimes);

    if (trueTime == round(t1, 2)) {
        // print(""Hit Purple"");
        return [t1, ""t1""];
        // hitPoint = createVector(P0.x + V0.x * t1, P0.y + V0.y * t1);
        // line(P0.x, P0.y, hitPoint.x, hitPoint.y);
    } else if (trueTime == round(t2, 2)) {
        // print(""Hit Blue"");
        return [t2, ""t2""];
        // hitPoint = createVector(P0.x + V0.x * t2, P0.y + V0.y * t2);
        // line(P0.x, P0.y, hitPoint.x, hitPoint.y);
    } else {
        // print(""Hit Green"");
        return [t3, ""t3""];
        // hitPoint = createVector(P0.x + V0.x * t3, P0.y + V0.y * t3);
        // line(P0.x, P0.y, hitPoint.x, hitPoint.y);
    }
}

function findNormal(pos, wall) {
    let perpVector = createVector(-wall.y, wall.x);
    strokeWeight(2);
    stroke(0);
    line(pos.x, pos.y, perpVector.x, perpVector.y);
    // line(P0.x, P0.y, hitPoint.x, hitPoint.y);
}

function getY(x, HP) {
    let perpY =
        -((vertices[4].a.x - vertices[1].a.x) / (vertices[4].a.y - vertices[1].a.y)) *
            x +
        (HP.y +
            ((vertices[4].a.x - vertices[1].a.x) / (vertices[4].a.y - vertices[1].a.y)) *
                HP.x);
    return perpY;
}

function getPerp(p1, p2, p3) {
    x1 = p1.x;
    y1 = p1.y;
    x2 = p2.x;
    y2 = p2.y;
    x3 = p3.x;
    y3 = p3.y;
    stroke(0);
    strokeWeight(2);
    line1 = line(x1, y1, x2, y2);
    m1 = (y2 - y1) / (x2 - x1);
    m2 = -1 / m1;
    b2 = y3 - x3 * m2;
    stroke(255, 0, 0);
    line(x3, m2 * x3 + b2, x1, m2 * x1 + b2);
    let final = createVector(m2 * x1 + b2 - (m2 * x3 + b2), x1 - x3);
    return final;
}</code></pre>
<pre class=""snippet-code-css lang-css prettyprint-override""><code>html,
body {
    margin: 0;
    padding: 0;
    overflow: hidden;
}</code></pre>
<pre class=""snippet-code-html lang-html prettyprint-override""><code>&lt;script src=""https://cdn.jsdelivr.net/npm/p5@1.4.1/lib/p5.min.js""&gt;&lt;/script&gt;</code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/71269144/reflecting-vector-along-perpendicular,"['javascript', 'geometry', 'p5.js']",277,True,1,1
Xml Generation from Google test does not show skipped test cases,"<p>I am using google test framework for doing unit testing in c++. I have few test cases which i have disabled using DISABLED_ before test name and some tests are skipped using GTEST_SKIP(). This is working fine and i can see the tests being disabled and skipped in the teminal log. The problem is when i am generating the xml file from the test.<br />
I am using the following command.</p>
<pre><code>--gtest_output=xml:/data/TestReport.xml
</code></pre>
<p>The generated XML</p>
<pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;testsuites tests=&quot;17&quot; failures=&quot;7&quot; disabled=&quot;3&quot; errors=&quot;0&quot; time=&quot;57.713&quot; timestamp=&quot;1970-01-04T10:31:55&quot; name=&quot;AllTests&quot;&gt;
&lt;testsuite name=&quot;UNITTEST&quot; tests=&quot;17&quot; failures=&quot;7&quot; disabled=&quot;3&quot; errors=&quot;0&quot; time=&quot;45.713&quot; timestamp=&quot;1970-01-04T10:32:04&quot;&gt;
&lt;testcase name=&quot;Test_1&quot; status=&quot;run&quot; result=&quot;skipped&quot; time=&quot;0&quot; timestamp=&quot;1970-01-04T10:32:04&quot; classname=&quot;UNITTEST&quot; /&gt;
&lt;testcase name=&quot;Test_2&quot; status=&quot;run&quot; result=&quot;completed&quot; time=&quot;0.461&quot; timestamp=&quot;1970-01-04T10:32:04&quot; classname=&quot;UNITTEST&quot; /&gt;
&lt;testcase name=&quot;Test_3&quot; status=&quot;run&quot; result=&quot;completed&quot; time=&quot;7.089&quot; timestamp=&quot;1970-01-04T10:32:05&quot; classname=&quot;UNITTEST&quot;&gt;
</code></pre>
<p>I would like to point out that the tag testsuites which is a consolidation of all the testsuite does not have an attribute skipped.
The tag testsuite which is a consolidation of all the tests also does not have the attribute skipped. However, the test Test_1 does show the result as skipped. Is there any configuration to make the count of skipped appear.</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/72226576/xml-generation-from-google-test-does-not-show-skipped-test-cases,"['xml', 'googletest']",144,True,1,1
Informix and C: How to get the last inserted serial number from bigserial field type,"<p>We have a DB with multiple tables having &quot;serial&quot; type column. The legacy C application writes the data to these tables and uses &quot;sqlerrd[2]&quot; fetch the serial number of the data just inserted.</p>
<p><code>insert into email(serial_number, email_id) values(0, 'test@test.com')</code></p>
<p>Due to serial number getting exhausted we are migrating to &quot;bigserial&quot;. However, the above logic of fetching the serial number from &quot;sqlerrd[2]&quot; dont work, since it is of type &quot;integer&quot;.</p>
<p>What is the right solution for handling this?</p>
<p>Note: As a work around we are currently making a call to <code>ifx_getbigserial</code> to fetch the serial number. However, we are concerned that, there are multiple tables and concurrent transactions as well and we are not sure, how does this API works? This API dont mention table name and our unit testing shows, we get right data, but not sure, is this the right solution.</p>
",https://stackoverflow.com/questions/71699958/informix-and-c-how-to-get-the-last-inserted-serial-number-from-bigserial-field,"['c', 'informix']",265,True,1,1
Populating a field that has no setter in abstract class,"<p>I'm working with a class <a href=""https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.eventing.reader.eventrecordwritteneventargs?view=dotnet-plat-ext-6.0"" rel=""nofollow noreferrer""><code>EventRecordWrittenEventArgs</code></a> in my unit test(s):</p>
<pre><code>public sealed class EventRecordWrittenEventArgs : EventArgs {
  public EventRecord EventRecord {get;}
  public Exception EventException {get;}
}
</code></pre>
<p>I would like to populate the <code>EventException</code> and <code>EventRecord</code> fields with my own custom data so I've created my own version of the above class called <code>EventRecordWrittenEventArgsAdaptor</code> that just has a setter in addition to getter for each field.</p>
<p>Problem is, <a href=""https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.eventing.reader.eventrecord?view=dotnet-plat-ext-6.0"" rel=""nofollow noreferrer""><code>EventRecord</code></a> is an abstract class with no setters which would mean I can't populate my own custom <code>EventRecord</code> object (which is ultimately my goal):</p>
<pre><code>public abstract class EventRecord : IDisposable {
  public abstract Guid? ProviderId {get;}
  public abstract string TaskDisplayName {get;}
  public abstract string OpcodeDispayName {get;}
  ...
}
</code></pre>
<p>My first thought was to make a <code>EventRecordAdaptor</code> class that derives from <code>EventRecord</code> and give it each field a setter but that doesn't work:</p>
<pre><code>public class EventRecordAdaptor : EventRecord {
  public override Guid? ProviderId {get;set;} // &quot;cannot override because EventRecord.Guid does not have an overrideable set accessor&quot;
}
</code></pre>
<p>How am I supposed to create my own <code>EventRecord</code> object that I can populate with whatever I want? To be clear, my end goal is to have the ability to fill <code>EventRecord</code> and <code>EventException</code> with whatever I want for the purpose of unit testing. Surely there's a way to populate this field?</p>
",https://stackoverflow.com/questions/71787581/populating-a-field-that-has-no-setter-in-abstract-class,"['c#', 'abstract-class', 'abstract']",110,True,0,3
Jest testing async code with then and catch present inside the function,"<p>I have to add unit testing to legacy code where I can make no changes inside the code hence can't refactor the code to add async/await or increase the jest version from 25.0.0</p>
<p>code file (sample code of actual implementation):</p>
<pre><code>window.getUsers = function(){
      $.get(url)
         .then(data =&gt; {
                data.forEach(val =&gt; {
                      $(&quot;.box-user .box-content&quot;).append(&quot;&lt;h1&gt;hello&lt;/h1&gt;&quot;);
                      console.log('box users content code file',document.querySelector('.box-users &gt; .box-content').innerHTML);
                 }) 
              })
         .catch(err =&gt; {})
}
</code></pre>
<p>test case i am trying to run</p>
<pre><code>import path from 'path';
import '@testing-library/jest-dom/extend-expect';
const fs = require('fs');
const html = fs.readFileSync(path.resolve(__dirname, './code-file.html'),'utf8');
const $ = require('jquery');

const mockResponse = {
    &quot;data&quot;: [
        {
            &quot;id&quot;: &quot;test id&quot;,
            &quot;name&quot;: &quot;test name&quot;,
            &quot;surname&quot;: &quot;test surname&quot;,
            &quot;jobTitle&quot;: &quot;test job title&quot;,
        }
    ],
    &quot;length&quot;: 1
};

describe(&quot;code-file&quot;,()=&gt;{

    document.documentElement.innerHTML = html;

    it(&quot;api mocking and appending html &quot;,()=&gt;{
        $.get = jest.fn().mockImplementation(() =&gt; {
            return Promise.resolve(mockResponse);
        });

        let {getUsers} = require(&quot;./code-file&quot;);
        getUsers();

        let boxUsersHtml = document.querySelector(&quot;.box-users &gt; .box-content&quot;).innerHTML;
        console.log('box users content testing file',boxUsersHtml)
    })
})
</code></pre>
<p>as you can see inner html for testing code is empty while I do see inner html of code file to have some value. I believe this is due to the async behavior where in the test case is complete and the html has not been appended yet because it is present inside a then block.</p>
<p>need to know how to execute then block before any assertions(before console in the above code) are made without making changes in actual code.</p>
<p>done function did not help link for reference <a href=""https://jestjs.io/docs/next/asynchronous#:%7E:text=Testing%20Asynchronous%20Code%201%20Promises%20Return%20a%20promise,don%27t%20use%20promises%2C%20you%20can%20use%20callbacks.%20"" rel=""nofollow noreferrer"">testing async code</a></p>
",https://stackoverflow.com/questions/74952305/jest-testing-async-code-with-then-and-catch-present-inside-the-function,"['javascript', 'jquery', 'jestjs']",34,False,0,0
How to print output in Visual Studio Test Explorer from F# and xUnit on success?,"<p>I am testing a client application that is requesting data from a database across the network. I have studied similar questions on SO, but they seem to apply several years ago before the really good nuget packages of Hedgehog and Swensen.Unquote were available. ( I am a complete newbie to unit testing).</p>
<p>Is there currently a good way, without creating an F# Class object, of forcing xUnit to print output to the Visual Studio Test Explorer without forcing it as an error?</p>
<p>The below code works to print the visits returned from the server, but only if it is &quot;in error&quot;.</p>
<p>How can I get it to print the returned values without it being marked as an error?</p>
<p>TIA</p>
<pre><code>module Tests

open Xunit
open Hedgehog
open Swensen.Unquote
open System
open Stargate.XI.Client

[&lt;Fact&gt;]
let ``Get Visits`` () =
   
   let visits = Scheduling.getVisits (new DateTime(2022,04,22))

   test &lt;@ printfn &quot;%O&quot; visits = () @&gt;
</code></pre>
<p>Edit#1
For others who want to do this, the below suggestion worked great for me with the following changes:</p>
<pre><code>[&lt;Fact&gt;]
    let ``Get Visits`` () =
       let visits = Scheduling.getVisits (new DateTime(2022,04,22))
       output.WriteLine(sprintf &quot;%A&quot; visits)      
       Assert.True(true)
</code></pre>
",https://stackoverflow.com/questions/72891421/how-to-print-output-in-visual-studio-test-explorer-from-f-and-xunit-on-success,"['visual-studio', 'f#', 'xunit']",160,True,0,1
Laravel: Testing controller and DB result,"<p>If I have a Laravel app with a form that when submitted is saved to a database, for example</p>
<p><em>FORM</em></p>
<pre><code>// ---------- snip ------
data(){
    return {
        form:this.$inertia.form({
            '_method': 'POST',
            name: null,
            age: null,
        }, {
            bag: 'savePerson',
            resetOnSuccess: false,
        }),
    }
},
methods:{
    submit() {
        this.sending = true;
        this.form.post('/test/store').then((response) =&gt; {
            this.sending = false;
        });
    },
},
// ---------- snip ------
</code></pre>
<p><em>CONTROLLER</em></p>
<pre><code>// ---------- snip ------
public function store(Request $req) 
{   
    // input field validation
    $v = Validator::make($req-&gt;all(), [
        'name' =&gt; 'required',
        'age'  =&gt; 'required|integer',
    ]);

    if ($v-&gt;fails()) {
        return Redirect::back()-&gt;withErrors($v)-&gt;withInput($req-&gt;all());
    }
    
    // flash message
    if ($req-&gt;name == 'jada') {
         return redirect()-&gt;back()-&gt;with('warning', 'beware of entanglement!!');
    }

    if ($req-&gt;name == 'chris') {
        $note = 'slapped';
    } elseif ($req-&gt;name == 'will') {
        $note = 'donut';
    } else {
        $note = 'boring';
    }
    
    // save to DB
    $person_obj = People::firstOrCreate([ 'name' =&gt; $req-&gt;name, 'age' =&gt; $req-&gt;age, 'note' =&gt; $note]);
    
    return redirect()-&gt;route('person', $person_obj-&gt;id)-&gt;with('success', 'Person saved');
} 
// ---------- snip ------
</code></pre>
<p>How would I test the controller function?</p>
<ol>
<li><p>Test that that the validation works i.e.
<code>[form:name = null, form:age = null]</code>
<code>[form:name = 'alice', form:age = 'alice']</code> should fail</p>
</li>
<li><p>Test that the flash works i.e.
<code>[form:name = 'jada', form:age = 50]</code> should return flash message <em>'beware of entanglement!!'</em></p>
</li>
<li><p>Test rows saved in DB i.e. <code>[form:name = 'chris', form:age = 57]</code> should save in DB</p>
</li>
</ol>
<pre><code> id  | name  | age |  note 
-----+-------+-----+--------
  ?  | chris | 57  | slapped
</code></pre>
<p>I understand that it is not proper unit testing since a DB is involved but I still would like to be able to simulate submitting a series of form entries and checking that the correct thing is being saved to the database. (Obviously the data is trivial in this joke example, but my actual Controller and DB is far more complicated and requires extensive testing)</p>
<p>Is this something that can be done easily in Laravel? and how would I go about it?</p>
",https://stackoverflow.com/questions/71700960/laravel-testing-controller-and-db-result,"['php', 'laravel', 'vue.js']",85,False,0,1
Unit testing OverflowException : Maximum retries of 10000 reached without finding a unique value,"<p>So I am working on some unit testing before I implement a new feature. I run my test and it fails with <code>OverflowException : Maximum retries of 10000 reached without finding a unique value</code> This is the test I'm running.</p>
<pre><code>    public function test_job_factory()
    {
        $client = Client::factory()-&gt;create();
        $accountHandler = AccountHandler::factory()-&gt;create();
        $user = User::factory()-&gt;create();

        $this-&gt;post('/login', [
            'email' =&gt; $user-&gt;email,
            'password' =&gt; 'password',
        ]);

        $user-&gt;givePermissionTo( 'manage jobs' );
        $clientContact = ClientContact::factory()-&gt;create();
        $job = Job::factory()-&gt;create();

        $this-&gt;assertTrue($job-&gt;id &gt; 0);
    }
</code></pre>
<p>The error seems to happen while creating the job itself. Tests above this test the other factories and are working.</p>
<p>Heres the JobFactory.php file:</p>
<pre><code>&lt;?php

namespace Database\Factories;

use App\Models\AccountHandler;
use App\Models\Client;
use App\Models\ClientContact;
use App\Models\Job;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory&lt;\App\Models\Job&gt;
 */
class JobFactory extends Factory
{
    protected $model = Job::class;

    /**
     * Define the model's default state.
     *
     * @return array&lt;string, mixed&gt;
     */
    public function definition()
    {
        return [
            'title'              =&gt; $this-&gt;faker-&gt;company(),
            'is_active'          =&gt; 1,
            'is_draft'           =&gt; 0,
            'client_id'          =&gt; $this-&gt;faker-&gt;unique()-&gt;numberBetween(1, Client::count()),
            'account_handler_id' =&gt; $this-&gt;faker-&gt;unique()-&gt;numberBetween(1, AccountHandler::count()),
            'eclipse_contact_id' =&gt; $this-&gt;faker-&gt;unique()-&gt;numberBetween(1, User::count()),
            'client_contact_id'  =&gt; $this-&gt;faker-&gt;unique()-&gt;numberBetween(1, ClientContact::count()),
            'description'        =&gt; $this-&gt;faker-&gt;paragraphs(1),
        ];
    }
}
</code></pre>
<p>and the migration for this (create_jobs_table.php):</p>
<pre><code>&lt;?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('jobs', function (Blueprint $table) {
            $table-&gt;id('number');
            $table-&gt;boolean( 'is_active' )-&gt;default(true);
            $table-&gt;boolean( 'is_complete' )-&gt;default(true);
            $table-&gt;string('title', 64)-&gt;nullable();
            $table-&gt;timestamps();
            $table-&gt;foreignId('author')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('users');
            $table-&gt;text('description')-&gt;nullable();
            $table-&gt;foreignId('client_id')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('clients');
            $table-&gt;foreignId('client_contact_id')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('client_contacts');
            $table-&gt;foreignId('account_handler_id')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('account_handlers');
            $table-&gt;date('expiry_date')-&gt;nullable();
            $table-&gt;date('artwork_deadline')-&gt;nullable();
            $table-&gt;date('proof_deadline')-&gt;nullable();
            $table-&gt;integer('redirect')-&gt;nullable();
            $table-&gt;boolean( 'is_draft' )-&gt;default(true);
            $table-&gt;foreignId('eclipse_contact_id')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('users');
            $table-&gt;foreignId('subscription_id')-&gt;nullable()-&gt;constrained()-&gt;references('id')-&gt;on('subscriptions');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('jobs');
    }
};
</code></pre>
<p>So what is wrong and why this loop here? I have added the minimum data that is needed to create a job so no idea what I've missed.</p>
<p>thanks</p>
<p>*** EDIT ***
I was asked to give a link to where I found the bad practice of using unique and numberBetween here is an example <a href=""https://stackoverflow.com/questions/70841813/laravel-factory-error-maximum-retries-of-10000-reached-without-finding-a-unique"">Laravel factory error &quot;Maximum retries of 10000 reached without finding a unique value&quot; when I use unique Faker method</a> this will not work as you expect!</p>
",https://stackoverflow.com/questions/72803431/unit-testing-overflowexception-maximum-retries-of-10000-reached-without-findin,"['php', 'laravel', 'phpunit', 'factory']",477,True,0,2
Unit Testing: Should I verify after testing section in a method?,"<p>I have just started Unit Testing and I am a little bit confused regarding to the following issues. Could you help me please?</p>
<p>Here is the sample service method that I am testing:</p>
<pre><code>public CommandDTO update(UUID uuid, Request request) {

    // case 1
    if (uuid == null) {
        throw new EntityNotFoundException(&quot;Not found&quot;);
    }

    final Employee employee = employeeService.findByUuid(uuid);
    
    // case 2
    if (employee.getDepartmentUuid == null) {
        throw new EntityNotFoundException(&quot;Not found&quot;);
    }

    employeeRepository.saveAndFlush(employee);

    triggerService.onEmployeeUpdate(uuid);

    return CommandDTO.builder().uuid(employee.getUuid()).build();
}
</code></pre>
<p><strong>1.</strong> When I create a test method for testing case 1, should I just write a test for expecting <code>EntityNotFoundException</code>? I mean should I write verify lines after testing exception as shown below? Or should I just test until the part that I am testing? Because if I verify the rest, in that case I will repeat the same lines for all the other tests.</p>
<pre><code>@Test
public void test_exception_when_update() {
    UUID uuid = null;
    Request request = new Request();

    assertThrows(EntityNotFoundException.class, () -&gt; {
        employeeService.update(uuid, request);
    });

    /// ???
    verify(employeeService, never()).findByUuid(any());
    verify(employeeRepository, never()).saveAndFlush(any());
    verify(triggerService, never()).onEmployeeUpdate(any());
}
</code></pre>
<p><strong>2.</strong> For the above service method, I think I should write the test methods for the following scenarios:</p>
<ul>
<li><p><code>uuid == null</code> --&gt; throw exception</p>
</li>
<li><p><code>employee.getDepartmentUuid</code> --&gt; throw exception</p>
</li>
<li><p>there is no exception and the other 3 operations are ok and then return <code>CommandDTO</code>. Then I will make assertions.</p>
</li>
</ul>
<p>Is that true?</p>
",https://stackoverflow.com/questions/71508073/unit-testing-should-i-verify-after-testing-section-in-a-method,"['java', 'unit-testing', 'testing', 'junit', 'mockito']",55,False,0,1
Swift: Unit testing delegate methods with 3rd party class as an argument,"<p>I know how to unit test with 3rd party dependencies by extending the class with your own protocol so that you can inject a mock dependency that implements that same protocol.</p>
<p>But this only seems to work if the 3rd party dependency doesn't make use of the delegate pattern, as the delegate methods tend to have arguments that have the type of the dependency:</p>
<pre><code>protocol DependencyDelegate {
  func doSomething(_ dependency: Dependency)
}
</code></pre>
<p>Ideally I'd be able to replace <code>Dependency</code> from the line above with the protocol I made the dependency conform to so that I can pass in the mock dependency during unit testing.</p>
<p>Here is the full example scenario where <code>Dependency</code> and <code>DependencyDelegate</code> are defined by a 3rd part framework:</p>
<pre><code>extension Dependency: DependencyProtocol {}

class MyClass: DependencyDelegate {
  private let dependency: DependencyProtocol

  init(dependency: DependencyProtocol) {
    self.dependency = dependency
  }

  func doSomething(_ dependency: Dependency) {

  }
}

protocol DependencyDelegate {
  func doSomething(_ dependency: Dependency) // &lt;---- How do I deal with this in unit tests?
}

class MockDependency: DependencyProtocol {
  ...
}

class MyClassTests: XCTestCase {
  func test() {
    let myClass = MyClass(dependency: MockDependency())
    myClass.doSomething(
  }
}
</code></pre>
<p>How can I unit test this delegate relationship between the dependency and my class without passing in an actual instance of <code>Dependency</code> into the delegate method of <code>MyClass</code>?</p>
",https://stackoverflow.com/questions/72036107/swift-unit-testing-delegate-methods-with-3rd-party-class-as-an-argument,"['swift', 'xcode', 'unit-testing', 'xctest']",360,False,0,1
HSQL DB in Spring/Hibernate/JPA - unable to change schema,"<p>I am using HSQL in memory Db for unit testing Java code. Its configured and brought up using Hibernate/JPA/Spring
By default its schema is PUBLIC. However the code I am testing has hardcoded schema. So I need to change the schema from PUBLIC to say ABC</p>
<p>I just figure out how to do it. I tried below approaches</p>
<ol>
<li><p>CRATE SCHEMA ABC, SET INITIAL SCHEMA ABC</p>
</li>
<li><p>ALTER CATALOG RENAME PUBLIC TO ABC</p>
</li>
</ol>
<p>I get the error 'Schema not found'</p>
<p>That led me to conclude that once setup and started, we cant change the schema. So I tried with configuring schema as a Entity Manager JPA property at env setup. I started getting 'Dependent Bean not found' error for one of the classes in &quot;domain.packages.to.scan&quot;</p>
<p>I searched a lot on the web, I couldnt find definitive answers on how to accomplish this ?</p>
",https://stackoverflow.com/questions/73808955/hsql-db-in-spring-hibernate-jpa-unable-to-change-schema,"['java', 'spring', 'hibernate', 'jpa', 'hsqldb']",36,True,0,1
Unit testing with Angular 12 - Unable to function call inside ngFor loop,"<p>I am new in unit testing and now I am not able to call function which inside <code>*ngFor</code> loop of an <code>angular 12</code> app. There is a observable that contains an array of objects and it works fine. Whole data is iterated properly.</p>
<p>This is my HTML code.</p>
<pre><code>&lt;div class=&quot;table-responsive&quot;&gt;
    &lt;table class=&quot;table table-striped&quot;&gt;
        &lt;thead&gt;
          &lt;tr&gt;
            &lt;th&gt;#&lt;/th&gt;
            &lt;th&gt;Name&lt;/th&gt;
            &lt;th&gt;Category&lt;/th&gt;
            &lt;th&gt;Action&lt;/th&gt;
          &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
          &lt;tr *ngFor=&quot;let item of games$ | async; let i = index&quot;&gt;
            &lt;td&gt;{{ i+1 }}&lt;/td&gt;
            &lt;td&gt;{{ item.name }}&lt;/td&gt;
            &lt;td class=&quot;badge-cell&quot;&gt;
               {{ item.categoryId }}
            &lt;/td&gt;
            &lt;td class=&quot;center action-cell&quot;&gt;
              &lt;button type=&quot;button&quot;
                class=&quot;delete-game btn&quot;
                (click)=&quot;deleteGame(item.id)&quot;&gt;Delete&lt;/button&gt;
            &lt;/td&gt;
          &lt;/tr&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;
&lt;/div&gt;
&lt;!-- /.table-responsive--&gt;
</code></pre>
<p>The problem rises while testing a function call inside loop. Thus, when I try to access <code>nativeElement</code> property of a <code>fixture</code> then the dynamic part of a table is <code>null</code>. Therefore <code>daleteGame</code> function is not available.</p>
<p>Here is the how <code>console.log(fixture.nativeElement)</code> look like:</p>
<pre><code>&lt;div _ngcontent-a-c74=&quot;&quot; class=&quot;table-responsive&quot;&gt;
    &lt;table _ngcontent-a-c74=&quot;&quot; id=&quot;dataTables-example&quot; class=&quot;table table-striped&quot;&gt;
        &lt;thead _ngcontent-a-c74=&quot;&quot;&gt;
            &lt;tr _ngcontent-a-c74=&quot;&quot;&gt;
                &lt;th _ngcontent-a-c74=&quot;&quot;&gt;#&lt;/th&gt;
                &lt;th _ngcontent-a-c74=&quot;&quot;&gt;Name&lt;/th&gt;
                &lt;th _ngcontent-a-c74=&quot;&quot;&gt;Category&lt;/th&gt;
                &lt;th _ngcontent-a-c74=&quot;&quot;&gt;Action&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
         //----------NO ROWS IN THE LOG------------//
        &lt;!--bindings={
          &quot;ng-reflect-ng-for-of&quot;: null
        }--&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;
&lt;/div&gt;
</code></pre>
<p>Static data is used to simulate original array(see <code>GAME_DATA</code>). This is how the tests look like:</p>
<pre><code>describe('ListGamesComponent', () =&gt; {
  let component: ListGamesComponent;
  let fixture: ComponentFixture&lt;ListGamesComponent&gt;;

  beforeEach(
    waitForAsync(() =&gt; {
      TestBed.configureTestingModule({
        imports: [HttpClientTestingModule, CommonModule],
        declarations: [ListGamesComponent],
        providers: [
          RequestService,
        ],
      })
        .compileComponents()
        .then(() =&gt; {
          fixture = TestBed.createComponent(ListGamesComponent);
          component = fixture.componentInstance as any;
          component.games$ = from([GAME_DATA]) as unknown as Observable&lt;
            IGameData[]
          &gt;;
        });
    })
  );

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

  it('should check if deleteGame was called', fakeAsync(() =&gt; {
    spyOn(component, 'deleteGame');
    
    component.games$.subscribe((data: any) =&gt; {
     // ---- logged an observable, a proper list of games is returned ----
      console.log('data: ', data);
    });
    
    fixture.detectChanges();

    let button = fixture.debugElement.query(By.css('.delete-game'));
    
    button.triggerEventHandler('click', null);
    fixture.detectChanges();
    tick();

    expect(component.deleteGame).toHaveBeenCalled();
  }));
});
</code></pre>
<p>By the way, I logged an observable inside the test and it retrieves whole data from <code>GAME_DATA</code> static file, so I don't understand why the whole table is not generated.</p>
<p><strong>UPDATE</strong></p>
<p>This is how <code>games$</code> done in component:</p>
<pre><code>export class ListGamesComponent implements OnInit {

  ngOnInit(): void {
    let pager: { index: number; size: number } = {
      index: this.pageIndex,
      size: this.pageSize,
    };
    this.games$ = this.gameService.getAllGames(pager).pipe(
      tap((data) =&gt; {
        this.totalRecords = data.totalItems;
        this.gamesList = data.games;
        
        this.setPage(1, false); // generate pagination
      }),
      pluck('games')
    );
  }
}
</code></pre>
<p>Any help is appreciated. Thanks!</p>
",https://stackoverflow.com/questions/70700401/unit-testing-with-angular-12-unable-to-function-call-inside-ngfor-loop,"['angular', 'typescript', 'unit-testing', 'jasmine', 'angular-unit-test']",950,True,0,1
Is it a bad practice to write an interactive step on a unit test?,"<p>From what I understand the main purpose of unit testing is to automatize testing.</p>
<p>But consider the following example:</p>
<p>I have an application that needs the user to read a QR code. When the user reads the QR code, the user is connected to another application. My application then checks if the user is connected.</p>
<p>So, the only way that I think to test this scenario, is to when running the test case, display a QR code in the console so that the developer read it.</p>
<p>But I think it's a bad practice.</p>
<p>So my question is: &quot;Is it a bad practice to write an interactive step on a unit test ?&quot;</p>
<p>Can anybody give me another way to test this scenario? Maybe there is some kind of tool that I dont know?</p>
<p>I'm using django in this application.</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/73253602/is-it-a-bad-practice-to-write-an-interactive-step-on-a-unit-test,"['django', 'unit-testing', 'testing', 'theory', 'developer-tools']",26,False,0,0
Wrapping a function that glibc redefines or aliases,"<p>I'm trying to wrap <code>snprintf()</code> in order to mock it for unit testing. My approach has been to follow the pattern of other mocked functions in the same project -- namely, to use <code>-Wl,--wrap=snprintf</code> in <code>LDFLAGS</code>.</p>
<pre><code>int
__wrap_snprintf(char *restrict str, size_t size, const char *restrict format,
                ...)
{
    int rc;
    va_list ap;

    va_start(ap, format);

    if (mocked) {  // global var
        check_expected_ptr(str);
        check_expected(size);
        check_expected_ptr(format);
        errno = mock_type(int);

        rc = (errno == 0) ? vsnprintf(str, size, format, ap) : -1;
    } else {
        rc = vsnprintf(str, size, format, ap);
    }

    va_end(ap);
    return rc;
}
</code></pre>
<p>On all the other test systems besides Fedora 36 ppc64le, this has worked fine. However, Fedora 36 ppc64le has added support for 128-bit long double values: <a href=""https://fedoraproject.org/wiki/Changes/PPC64LE_Float128_Transition"" rel=""nofollow noreferrer"">https://fedoraproject.org/wiki/Changes/PPC64LE_Float128_Transition</a>.</p>
<p>As part of the implementation, glibc maps <code>snprintf()</code> to <code>___ieee128_snprintf()</code>. As a result, my wrapper doesn't get called when the code calls <code>snprintf()</code>. Minimal demonstration without the wrapper linked in:</p>
<pre><code># cat test.c
#include &lt;stdio.h&gt;
void func(const char *s)
{
    char buf[16];
    snprintf(buf, 16, &quot;%s&quot;, s);
    printf(&quot;%s\n&quot;, buf);
}
int main(void)
{
    func(&quot;hello world&quot;);
}

# gcc -g -O0 -fno-builtin -fno-inline test.c -o test

# gdb ./test
...
Breakpoint 1, func (s=s@entry=0x10020020 &quot;hello world&quot;) at test.c:5
5       snprintf(buf, 16, &quot;%s&quot;, s);
(gdb) s
0x00007ffff7d54a98 in ___ieee128_snprintf (s=0x7fffffffeac0 &quot;\360\352\377\377\377\177&quot;, maxlen=16, format=0x10020010 &quot;%s&quot;) at ../sysdeps/ieee754/ldbl-128ibm-compat/ieee128-snprintf.c:24
</code></pre>
<p>Is there a way to handle this with <code>--wrap</code> as I've been doing for other mocked functions, or is this approach hopeless?</p>
<p>P.S. In <a href=""https://stackoverflow.com/q/73438635/7660197"">snprintf() optimized out despite -fno-builtin on GCC 11</a> we addressed a related issue on Ubuntu, where an implicit <code>_FORTIFY_SOURCE</code> was converting <code>snprintf()</code> to <code>__builtin___snprintf_chk()</code>. The solution was to explicitly undefine <code>_FORTIFY_SOURCE</code> in <code>CFLAGS</code>.</p>
",https://stackoverflow.com/questions/73440867/wrapping-a-function-that-glibc-redefines-or-aliases,"['c', 'gcc', 'mocking', 'linker', 'ld']",74,False,0,0
Can tsqlt table accessed outside of tSqlt scope?,"<p>I am writing a tsqlt unit testing where I am not faking the table and I am using the real SQL table ex:<strong>sendEmail</strong> to test the email sending functionality.</p>
<p>I am inserting the value like below from tsqlt to the sendEmail table</p>
<pre><code>Email: 'test@test.com'
Status : 0
Template : 'New User Creation'
</code></pre>
<p>There is an automation job outside of tsqlt that will look for these table entries which have Status :0 process the email to the sender address and update back to the table's column value as Status:1</p>
<p>But I am not seeing the automation job is able to do success with email sending during this tsqlt regression scenario. Can't we access the SQL table and its value outside use when tsqlt is running? Any guidance would be highly appreciated.</p>
<p>tSqlt will be running only in the isolated way and can't integrate with any other code or application?</p>
",https://stackoverflow.com/questions/70933984/can-tsqlt-table-accessed-outside-of-tsqlt-scope,"['sql-server', 'unit-testing', 'sql-server-2012', 'tdd', 'tsqlt']",84,False,0,0
What do I wrong while coding GORM API Unit Test?,"<p>A few days ago, I started learning Golang, PostgreSQL, and Unit tests.
I searched a lot of information about how to API unit test in GORM here and there.
I just tried to follow up Golang documentation (<a href=""https://go.dev/src/net/http/httptest/example_test.go"" rel=""nofollow noreferrer"">https://go.dev/src/net/http/httptest/example_test.go</a>) and one of the StackOverflow posts (<a href=""https://codeburst.io/unit-testing-for-rest-apis-in-go-86c70dada52d"" rel=""nofollow noreferrer"">https://codeburst.io/unit-testing-for-rest-apis-in-go-86c70dada52d</a>)</p>
<p>I am not sure I got this error message &quot;undefined: RegisterTodoListRoutes&quot;.</p>
<pre><code>handler := http.HandlerFunc(RegisterTodoListRoutes) in this line 
</code></pre>
<p>My todolist-routes.go code is</p>
<pre><code>package routes

import (
    &quot;github.com/gorilla/mux&quot;
    &quot;github.com/jiwanjeon/go-todolist/pkg/controllers&quot;
)

var RegisterTodoListRoutes = func (router *mux.Router){
    router.HandleFunc(&quot;/todo/&quot;, controllers.CreateTodo).Methods(&quot;POST&quot;)
    router.HandleFunc(&quot;/todo/&quot;, controllers.GetTodo).Methods(&quot;GET&quot;)
    router.HandleFunc(&quot;/todo/{todoId}&quot;, controllers.GetTodoById).Methods(&quot;GET&quot;)
    router.HandleFunc(&quot;/todo/{todoId}&quot;, controllers.UpdateTodo).Methods(&quot;PUT&quot;)
    router.HandleFunc(&quot;/todo/{todoId}&quot;, controllers.DeleteTodo).Methods(&quot;DELETE&quot;)
    router.HandleFunc(&quot;/complete/{todoId}&quot;, controllers.CompleteTodo).Methods(&quot;PUT&quot;)
    router.HandleFunc(&quot;/incomplete/{todoId}&quot;, controllers.InCompleteTodo).Methods(&quot;PUT&quot;)
} 
</code></pre>
<p>and my todolist-routes_test.go test code is</p>
<pre><code>package routes_test

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

func TestRegisterTodoListRoutes(t *testing.T) {
    req, err := http.NewRequest(&quot;GET&quot;, &quot;/todo/&quot;, nil)
    if err != nil {
        t.Fatal(err)
    }
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(RegisterTodoListRoutes)

        handler.ServeHTTP(rr, req)

  // Check the status code is what we expect.
  if status := rr.Code; status != http.StatusOK {
      t.Errorf(&quot;handler returned wrong status code: got %v want %v&quot;,
          status, http.StatusOK)
    }
    
    expected := `[{&quot;ID&quot;:46,&quot;title&quot;:&quot;test-title-console-check&quot;,&quot;last_name&quot;:&quot;test-description-console-check&quot;, &quot;conditions&quot;: true]`
    if rr.Body.String() != expected {
        t.Errorf(&quot;handler returned unexpected body: got %v want %v&quot;,
            rr.Body.String(), expected)
    }
}

</code></pre>
<p>Here is a link for todolist_routes.go : <a href=""https://go.dev/play/p/XoVMbK7PnLu"" rel=""nofollow noreferrer"">https://go.dev/play/p/XoVMbK7PnLu</a>
this is for test code : <a href=""https://go.dev/play/p/NddwrU5m6ss"" rel=""nofollow noreferrer"">https://go.dev/play/p/NddwrU5m6ss</a></p>
<p>I really appreciate your help!!</p>
<p>Edit 1] I found the reason why I got this error. When I remove _test above at package and run it. I got this error &quot;cannot convert Routes (type func(*mux.Router)) to type http.HandlerFunc&quot;</p>
",https://stackoverflow.com/questions/71263812/what-do-i-wrong-while-coding-gorm-api-unit-test,"['unit-testing', 'go', 'go-gorm']",113,False,0,0
list() method in API causing TypeError: &#39;list&#39; object is not callable in unit test,"<p>I'm working on code that retrieves information from Twilio's Flow system through their API. That part of the code functions fine, but when I try to mock it for unit testing, it's throwing an error from the mocked api response.</p>
<p>Here is the code being tested:</p>
<pre><code>from twilio.rest import Client


class FlowChecker:

    def __init__(self, twilio_sid, twilio_auth_token):
        self.twilio_SID = twilio_sid
        self.twilio_auth_token = twilio_auth_token
        self.client = Client(self.twilio_SID, self.twilio_auth_token)

        self.calls = self.client.calls.list()
        self.flows = self.client.studio.v2.flows

    def get_active_executions(self):
        active_executions = []
        for flow in self.flows.list():
            executions = self.client.studio.v2.flows(flow.sid).executions.list()
            for execution in executions:
                if execution._properties['status'] != 'ended':
                    active_executions.append({'flow_sid': flow.sid, 'execution': execution})
</code></pre>
<p>And here is my unit test code that's throwing the error:</p>
<pre><code>import unittest
from unittest.mock import Mock, patch
from flows.twilio_flows import FlowChecker

class FlowCheckerTest(unittest.TestCase):


    @patch('flows.twilio_flows.Client')
    def test_get_active_flows(self, mock_client):
        flow_checker = FlowChecker('fake_sid', 'fake_auth_token')
        mock_call = Mock()
        mock_flow = Mock()
        mock_flow.sid = 0
        mock_execution = Mock()
        mock_execution._properties = {'status': 'ended'}
        mock_client.calls.list().return_value = [mock_call]
        mock_client.studio.v2.flows = [mock_flow]
        mock_client.studio.v2.flows(mock_flow.sid).executions.list().return_value = [mock_execution]
        self.assertEqual(flow_checker.get_active_executions(), [])
</code></pre>
<p>And here is the error traceback:</p>
<pre><code>Ran 2 tests in 0.045s

FAILED (errors=1)

Error
Traceback (most recent call last):
  File &quot;C:\Users\Devon\AppData\Local\Programs\Python\Python310\lib\unittest\mock.py&quot;, line 1369, in patched
    return func(*newargs, **newkeywargs)
  File &quot;C:\Users\Devon\PycharmProjects\Day_35\tests\twilio_flows_test'.py&quot;, line 19, in test_get_active_flows_when_empty
    mock_client.studio.v2.flows(mock_flow.sid).executions.list().return_value = [mock_execution]
TypeError: 'list' object is not callable


Process finished with exit code 1
</code></pre>
<p>As you can see, &quot;mock_client.calls.list().return_value = [mock_call]&quot; doesn't throw any errors during <strong>init</strong>, and the first code block runs fine. It's only the mocked executions.list() that's throwing the error in the test.</p>
<p>Can anyone clear this up?</p>
<p>Thank you!</p>
<p>I've tried researching this specific issue and was unable to find information addressing it. It's a very specific deeply nested function in a vendor supplied client that I need to test, so I don't know what to try.</p>
",https://stackoverflow.com/questions/74524468/list-method-in-api-causing-typeerror-list-object-is-not-callable-in-unit-te,"['python', 'list', 'unit-testing', 'twilio', 'twilio-api']",105,False,-1,1
How to automate CI/CD pipeline unit tests for a node.js container deployment in kubernetes,"<p>I am trying to automate unit testing before deploying a node.js container to a local kubernetes cluster. It is not clear to me whether or not I need to configure this in my <code>deployment.yaml</code>, <code>Dockerfile</code>, <code>package.json</code>, or some combination of them. And once configured how to instruct Kubernetes to output any failures and exit before deploying.</p>
<p>Do I need to do as <a href=""https://stackoverflow.com/a/64655551/1551027"">this SO answer</a> suggests and write a shell script and modify environment variables? Or, is this something I can automate with Kubernetes <code>deployment.yaml</code></p>
<p>If it's useful, I am using <code>mocha</code> with <code>chai</code>. And this is being deployed from Google Cloud Source Repositories to a local Kubernetes instance.</p>
<p>Since I'm entirely new to Kubernetes, it would be great to have as much detail as possible.</p>
<p>Here is my <code>deployment.yaml</code>:</p>
<pre class=""lang-yaml prettyprint-override""><code>
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: my-app
  template:
    metadata:
      labels:
        app: my-app
    spec:
      containers:
        - name: my-app-container
          image: my-app-image
          imagePullPolicy: IfNotPresent
</code></pre>
<p>Here is my <code>Dockerfile</code>:</p>
<pre><code># Use base node 18-alpine image from Docker hub
FROM node:18-alpine

WORKDIR /MY_APP

# Copy package.json and install dependencies
COPY package*.json ./
RUN npm install

# Copy rest of the application source code
COPY . .

# Run index.js
ENTRYPOINT [&quot;node&quot;, &quot;src/index.js&quot;]
</code></pre>
<p>Here is my <code>package.json</code>:</p>
<pre class=""lang-js prettyprint-override""><code>  &quot;scripts&quot;: {
    &quot;start&quot;: &quot;node src/index.js&quot;,
    &quot;test&quot;: &quot;npm install mocha -g &amp;&amp; mocha --timeout 4000 --exit&quot;
   }
</code></pre>
<p>And here is a basic unit test I'm using to experiment with:</p>
<pre class=""lang-js prettyprint-override""><code>import { expect } from 'chai'

describe('Basic unit test', ()=&gt;{
    it('Checks if 3*3=9', () =&gt; {

        expect(3*3, 9)
    })
})
</code></pre>
",https://stackoverflow.com/questions/73748496/how-to-automate-ci-cd-pipeline-unit-tests-for-a-node-js-container-deployment-in,"['node.js', 'docker', 'unit-testing', 'kubernetes', 'cicd']",173,True,0,1
How to unit test the Refit ApiResponse&lt;T&gt;?,"<p>I'm using refit to call APIs and the response is wrapped in <code>ApiResonse&lt;T&gt;</code>. I can mock the refit call that returns a mocked <code>ApiResponse&lt;T&gt;</code> and assert. Everything works as it should except I'm not sure how I can test the api call that returns an exception.</p>
<pre><code>[Get(&quot;/customer/{id}&quot;)]
Task&lt;ApiResponse&lt;Customer&gt;&gt; GetCustomer(int id);
</code></pre>
<p>It seems if <code>ApiResponse&lt;T&gt;</code> is used Refit wraps all the exceptions that happens inside the request into <code>ApiException</code> and attaches to <code>ApiResponse&lt;T&gt;</code>.  If <code>Task&lt;T&gt;</code> is used instead, catching the <code>ApiException</code> is the responsibility of the caller.</p>
<p>I created the <code>ApiException</code> with <code>ApiException.Create()</code> but not sure where to put that in the <code>ApiResponse&lt;T&gt;</code>.  The last parameter to the <code>Create()</code> method is ApiException but the exception I create and set doesn't show up in the ApiResponse at all and therefore can't test.</p>
<pre><code>var apiResponse = new ApiResponse&lt;Customer&gt;(
    new HttpResponseMessage(BadRequest),
    null,
    null,
    await ApiException.Create(,,,Exception(&quot;Something bad happened inside the api&quot;)
 );
</code></pre>
<p>I can't get the <code>Something bad happened...</code> message in the unit test but just the 'Bad Request' message.  Am I unit testing the ApiResponse in refit right? Any help is greatly appreciated.  Thanks</p>
",https://stackoverflow.com/questions/72355253/how-to-unit-test-the-refit-apiresponset,"['c#', 'rest', 'unit-testing', 'refit']",3388,True,2,1
why my localhost don&#39;t send any data when using database interface for mocking in Golang unit test?,"<p>I'm new in golang. I want to write unit tests for my functions that save data in mongodb, that are a little complicated.
There are many nested functions. e.g. A calls B, inside B, C and D is called, finally D calls E function that has a database query like <code>Find</code>.
I followed the instructions of <a href=""https://www.youtube.com/watch?v=KC4Q2S2PACQ"" rel=""nofollow noreferrer"">RESTful API in Golang using Echo - MongoDB Unit Testing in Golang</a> in youtube.</p>
<p>So I decided to start from a little function like E.
Here is the little function that I tried to mock database relation for it:</p>
<pre><code>func LoadUserRoles(username interface{}) ([]UserRoles, error) {

    q := bson.M{&quot;username&quot;: username}
    ps := new([]UserRoles)
    if err := userRoleDB.Find(q).All(ps); err != nil {
        return nil, err
    }
    
    return *ps, nil
}
</code></pre>
<p>I created an interface that implements exactly the Find method of mgo driver. the interface is like:</p>
<pre><code>type CollectionAPI interface {
    Find(query interface{}) *mgo.Query
}
</code></pre>
<p>Then I created an instance of this interface and took instead of userRoleDB:</p>
<pre><code>var userRoleMockDB      dbinterface.CollectionAPI
</code></pre>
<p>So my LoadUserRoles function changed to:</p>
<pre><code>func LoadUserRoles(username interface{}) ([]UserRoles, error) {
    q := bson.M{&quot;username&quot;: username}

    ps := new([]UserRoles)

    if err := userRoleMockDB.Find(q).All(ps); err != nil {
        return nil, err
    }
    return *ps, nil
}
</code></pre>
<p>The result is error in connecting to db.</p>
<p><strong>Exact error:</strong></p>
<p><strong>localhost didn’t send any data.</strong></p>
<p><strong>ERR_EMPTY_RESPONSE</strong></p>
",https://stackoverflow.com/questions/72787596/why-my-localhost-dont-send-any-data-when-using-database-interface-for-mocking-i,"['database', 'unit-testing', 'go', 'mocking']",42,False,2,0
how to test one micro front end component in which other micro frontend component is being used using jest and enzyme,"<p>I have two micro frontends (written in <strong>react</strong> &amp; <strong>typescript</strong>). <strong>dashboard MFE</strong> and <strong>Common MFE</strong></p>
<p>common MFE has several component which can be consumed by dashboard independently. eg. Notification component, loader component etc...</p>
<p>MFE1 has <strong>dashboard.component.tsx</strong> and simplified version looks below,</p>
<pre><code>  import React from react
  ....
  ....
  import notificationComponent from 'common/NotificationComponent'  &lt;&lt;====This is external module or component

  // and several other component which are part of common micro frontend

  const DashboardComponent = () =&gt; {
    ...
    ...
    ...
    return (&lt;div&gt;
           &lt;notificationComponent .../&gt;
           ....
   &lt;/div&gt;)
  }

export default DashboardComponent;
</code></pre>
<p>I defined its type in remoteTypes.d.ts file as below,</p>
<p><strong>src/remoteTypes.d.ts</strong></p>
<pre><code>declare module 'common/NotificatioComponent' {
    const NotificatioComponent: React.ComponentType&lt;{ notification: { title: string, description: string, color: string } }&gt;;
    export default NotificatioComponent;
}
</code></pre>
<p>This is working fine.</p>
<p><em><strong>The problem is in unit testing of dashboard component with jest and enzyme</strong></em>.</p>
<p>when I write and run a simple test,</p>
<pre><code>test('dashboard component',()=&gt;{
   const wrapper =  mount(
            &lt;Provider store={myStore}&gt;
              &lt;Router&gt;
                &lt;DashboardComponent /&gt;
              &lt;/Router&gt;
            &lt;/Provider&gt; 
   )
})
</code></pre>
<p>it throws error as below,</p>
<blockquote>
<p>can not find module 'common/NotificationComponent' from
'src/components/dashboard.component.tsx'</p>
<p>Require Stack:<br />
'src/components/dashboard.component.tsx<br />
'src/components/dashboard.component.text.tsx</p>
</blockquote>
<p>How should I resolve this error?</p>
<hr>
<p>I'm exporting notification component as follow,</p>
<p>webpackage.config.js</p>
<pre><code>const HtmlWebpackPlugin = require('html-webpack-plugin');
const { ModuleFederationPlugin } = require('webpack').container;
const path = require('path');
const deps = require('./package.json').dependencies;
const Dotenv = require('dotenv-webpack');

module.exports = {
  entry: './src/index.ts',
  ...
  ....
  plugins: [
    new ModuleFederationPlugin({

      name: 'common',

      filename: 'remoteEntry.js',

      exposes: {
        // expose each component
        './CommonBootstrap':'./src/bootstrap',
        './NotificationComponent': './src/components/notification/components/notification.component',   &lt;&lt;===== from here
      },

      shared: {
      ....
      }
  ],
};
</code></pre>
<hr>
<p><strong>Update</strong></p>
<p>I found a good reference : <a href=""https://stackoverflow.com/questions/66387224/mocking-federated-modules-in-host-application-for-jest"">Mocking federated modules in host application for jest</a></p>
<p>and tried in similar way but I get the same error still.</p>
<pre><code>test('dashboard component',()=&gt;{



       jest.mock('common/NotificationComponent', 
         () =&gt; { 
    
          ,
         { virtual: true }
       );

       const wrapper =  mount(
                &lt;Provider store={myStore}&gt;
                  &lt;Router&gt;
                    &lt;DashboardComponent /&gt;
                  &lt;/Router&gt;
                &lt;/Provider&gt; 
       )
    })
</code></pre>
<p>but same error. what is wrong ?</p>
",https://stackoverflow.com/questions/72909100/how-to-test-one-micro-front-end-component-in-which-other-micro-frontend-componen,"['unit-testing', 'jestjs', 'enzyme', 'ts-jest', 'micro-frontend']",1691,True,2,1
"With IntelliJ/Cursive, why does clojure.test.is consider that empty-string equals any string?","<p>With  the Intellij (v. 2021.3.2) and Cursive (v. 1.12.1-2021.3) &quot;run tests&quot; feature (the green Run arrow on a test or a namespace), a simple unit test in Clojure passes when it finds that <code>&quot;X&quot;</code> equals <code>&quot;&quot;</code>.</p>
<p>Full example:</p>
<pre class=""lang-clj prettyprint-override""><code>    (ns my-test
      (:require [clojure.test :refer [deftest is run-tests]]))
    
    (deftest compare-empty
      (is (= &quot;X&quot; &quot;&quot;)))
</code></pre>
<ul>
<li>If I replace replacing <code>&quot;&quot;</code>  by <code>&quot;Y&quot;</code>, the unit testing system works as expected.</li>
<li>This issue happens even in a minimal project: I create a new  project using the &quot;bare project&quot;  wizard, optionally rename <code>src</code> to <code>test</code>, add this file, and click the Run arrow.</li>
<li>If I add <code>(run-tests)</code> and run this script directly (as an &quot;application&quot;, then this  correctly fails.</li>
<li>The issue occured in the project   which was pulled straight from  Exercism.</li>
<li>The issue occurs
<ul>
<li>If I use the Leinengen <code>project.clj</code>.</li>
<li>If I delete that and use <a href=""https://github.com/exercism/clojure/blob/main/exercises/practice/run-length-encoding/deps.edn"" rel=""nofollow noreferrer"">the<code>deps.edn</code> file</a>.</li>
<li>As mentioned, with neither.</li>
<li>Or if I added <code>deps.edn</code> to the bare project and then reload that as a Deps project.</li>
</ul>
</li>
<li>The issue occurs with Clojure 1.10 and 1.11.</li>
</ul>
<p><a href=""https://i.stack.imgur.com/WoDcP.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/WoDcP.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/72364215/with-intellij-cursive-why-does-clojure-test-is-consider-that-empty-string-equal,['clojure'],231,True,1,2
Unit testing hibernate search with elastic backend,"<p>We are using hibernate search and its orm mapper together with JPA for our Java based search services. The challenge I'm facing is to write unit tests, such as:</p>
<ul>
<li>Insert JPA entity car &quot;tesla v3&quot;</li>
<li>Search for &quot;tesla&quot;</li>
<li>Validate the JPA entity &quot;tesla v3&quot; to be contained in the result set of hibernate search</li>
</ul>
<p>To do so, my first thought was to run some kind of in-memory, single node elastic cluster, test against this cluster, and tear it down afterwards. But it seems that there exists no such thing.</p>
<p>The official documentation (<a href=""https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/"" rel=""nofollow noreferrer"">https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/</a>) does not explain unit testing for hibernate search.</p>
<p>Now I'm curious how you test your hibernate search implementations. Do I need a test instance? Do you rename your indices for testing and clear it before each test run?</p>
<p>I'm grateful for every input!</p>
",https://stackoverflow.com/questions/72430785/unit-testing-hibernate-search-with-elastic-backend,"['java', 'elasticsearch', 'junit', 'hibernate-search']",334,True,1,1
Mocking void unit tests with Mockito,"<p>Having had many issues in unit testing my application please help address my simplest issue - mocking void methods, per <a href=""https://stackoverflow.com/questions/2276271/how-to-mock-void-methods-with-mockito"">a few stack overflow articles</a> and <a href=""https://javadoc.io/static/org.mockito/mockito-core/4.3.1/org/mockito/Mockito.html#doAnswer-org.mockito.stubbing.Answer-"" rel=""nofollow noreferrer"">common references in articles</a>. My Java code in a JBPM application WorkItemHandler follows the pattern of</p>
<pre><code>public class EmailNotificationWorkItemHandler() extends AbstractLogOrThrowWorkItemHandler {
  private static Utils utils = new Utils() ; 

  public void executeWorkItem(WorkItem workItem, WorkItemManager manager) { 
    if (&lt;condition&gt;) {
            utils.insertAmsErrors(&lt;param&gt;, &lt;param&gt;, &lt;param&gt;, &lt;param&gt;, &lt;param&gt;);         
            return;
        }
 ....
     try { 
         RequiredParameterValidator.validate(this.getClass(), workItem);
...
   }
</code></pre>
<p>I have been trying to stub Utils and its insertAmsErrors method to test RequiredParameterValidator.validate used later in executeWorkItem.  The references imply that the void call to utils and its insertAmsErrors method could be a very basic stub of</p>
<pre><code>      Utils mockUtils = mock(Utils.class);

      doAnswer(new Answer&lt;Void&gt;() {
          public Void answer(InvocationOnMock invocation) {
                 Object[] args = invocation.getArguments();
                 //Mock mock = (Mock) invocation.getMock();  Doesn't solve NPE
                 return null;
            }         
      }).when(mockUtils).insertAmsErrors(any(), any(), any(), any(), any()); // NPE here
</code></pre>
<p>but the stub throws a null pointer exception at &quot;NPE here&quot;.   Utils.insertAmsErrors signature is</p>
<pre><code>public void insertAmsErrors(String id, ErrorCode error, String errorMsg, 
          StackTraceElement [] stackTrace, long processId) 
</code></pre>
<p>I also considered using a spy, per another answer in the same posting, but my unit test is not calling insertAmsErrors on an instance of Utils, but rather executeWorkItem in EmailNotificationWorkItemHandler is making such a call.</p>
<p>How should I correctly mock the Utils class and its insertAmsErrors method so that I can test RequiredParameterValidator.validate in executeWorkItem?</p>
",https://stackoverflow.com/questions/71297814/mocking-void-unit-tests-with-mockito,"['java', 'unit-testing', 'mockito', 'jbpm', 'powermockito']",396,True,1,1
How to properly unit test mongoDB CRUD result,"<p>My application mostly consists of CRUDs to/from MongoDB using <code>mongo-go-drive</code> package. This function is one of gRPC server services and all it does is calling database method <code>action.GetProducts(ctx)</code> and it returns <code>*mongo.cursor</code>. Then the result is decoded. For each document, I put the document content into a singular product struct, then append it to products slices (the <code>GetProductsResponse</code> struct is made using gRPC proto <code>repeated GetProductResponse</code> type). After appending all product into <code>GetProductsResponse</code>, I return the response to gRPC client.</p>
<p>I am also new to testing in general, how should I break down the function and do the mocking (how to mock the cursor?) for unit testing? Is it even necessary in the first place to do unit test on the function even though all it does is appending the result, or should I just go straight for the integration test and skip the unit test since it involves database I/O?</p>
<pre><code>func (s *Server) GetProducts(ctx context.Context, in *pb.EmptyRequest) (*pb.GetProductsResponse, error) {
    cursor, err := action.GetProducts(ctx)
    if err != nil {
        return nil, err
    }

    products := pb.GetProductsResponse{}

    res := model.Product{}

    for cursor.Next(ctx) {
        // Convert document to above struct
        err := cursor.Decode(&amp;res)
        if err != nil {
            return nil, fmt.Errorf(&quot;failed to decode document: %v&quot;, err)
        }

        product := &amp;pb.GetProductResponse{ProductId: res.Product_id.Hex(), Name: res.Name, Price: res.Price, Qty: int32(res.Qty)}

        products.Products = append(products.Products, product)
    }

    return &amp;products, nil
}
</code></pre>
",https://stackoverflow.com/questions/70557637/how-to-properly-unit-test-mongodb-crud-result,"['mongodb', 'go', 'testing', 'grpc']",1631,True,1,1
C# - How to inject new instance of dependency to a class which get instantiated once in the app lifetime?,"<p>Here is a class which will be instantiated only once through out the lifetime of the application</p>
<pre><code>public class SampleClass //instantiated only once
 {
  public void DoOpertation()//will be called by every incoming request
   {
     var dependentService = new SampleService();
     //do operation on dependentService instance
     ....
   }
  }
</code></pre>
<p>Method &quot;DoOpertation&quot; operation will be called many time during the application lifetime.</p>
<p>In &quot;DoOpertation&quot; method I'm instantiating 'SampleService' using 'new' keyword which I don't want to do for the below reasons</p>
<ol>
<li>It breaks single responsibility principle (SRP) as creating SampleService class instance is not SampleClass's responsibility</li>
<li>Create tight coupling between SampleClass &amp; SampleService classes which makes unit testing harder atleast</li>
</ol>
<p><em><strong>I can't use DI container for constructor injection of dependencies as SampleClass get instantiated only once in the application lifetime</strong></em> but where as every invocation of DoOpertation method (which lives inside SampleClass) requires new instance of SampleService class to work properly.</p>
<p>How to inject SampleService class new instance on every invocation of DoOpertation() without using 'new' keyword?</p>
<p><strong>Modification as per Athanasios Kataras's suggestion</strong></p>
<p>Introduced new factory class</p>
<pre><code>        public class LoggerFactory : ILoggerFactory
        {
            public IEventLog CreateLogger(string type)
            {
                if (type == &quot;Event&quot;)
                    return new EventLog();
                else
                    return null;
            }
        }

        public interface ILoggerFactory
        {
            IEventLog CreateLogger(string type);
        }
</code></pre>
<p>On the class which instantiate only once,</p>
<pre><code> public class SampleClass //instantiated only once
   {
    public void DoOpertation()//will be called by every incoming request
    {
      var eventLogBuilder = _factory.CreateLogger(&quot;Event&quot;);
     //var dependentService = new SampleService(); //replace with above simple factory class call
     //do operation on dependentService instance
     ....
   }
  }
</code></pre>
",https://stackoverflow.com/questions/70640426/c-how-to-inject-new-instance-of-dependency-to-a-class-which-get-instantiated,"['c#', 'design-patterns', 'dependency-injection', 'anti-patterns']",1838,False,1,2
window.location.href updates only after the test is done in react,"<p>I use <code>useNavigate</code> from <code>react-router-dom</code> to handle navigation. I called a <code>useNavigate</code> hook at the top level of the functional component like that: <code>const navigate = useNavigate()</code>. Inside a <code>handleClick()</code> function I use it to navigate to an another page of my website like that: <code>navigate(&quot;/home&quot;)</code>. I tried it and it is working fine, if I click on the button it takes me to homepage (http://localhost/home). However I have problems unit testing this functionality. After simulating a click on that button, the url should change so I wrote the following expectation: <code>expect(global.window.location.href).toContain('/home');</code></p>
<p>The test fails, the window location did not change. However when I tried to console log the window location in the <code>afterEach()</code> method, it shows that after the test the <code>global.window.location.href</code> equals to <code>http://localhost/home</code>. So it is working just can`t verify that in my test....</p>
<p>Why it is only change after the test? What can I do to verify that url inside the test?</p>
",https://stackoverflow.com/questions/73504213/window-location-href-updates-only-after-the-test-is-done-in-react,"['javascript', 'reactjs', 'testing', 'jestjs', 'location-href']",201,False,1,0
Why define constants in a metaclass?,"<p>I've recently inherited some code.  It has a class called <code>SystemConfig</code> that acts as a grab-bag of constants that are used across the code base.  But while a few of the constants are defined directly on that class, a big pile of them are defined as properties of a metaclass of that class.  Like this:</p>
<pre><code>class _MetaSystemConfig(type):
    @property
    define CONSTANT_1(cls):
        return &quot;value 1&quot;

    @property
    define CONSTANT_2(cls):
        return &quot;value 2&quot;

    ...

class SystemConfig(metaclass=_MetaSystemConfig):
    CONSTANT_3 = &quot;value 3&quot;
    ...
</code></pre>
<p>The class is never instantiated; the values are just used as <code>SystemConfig.CONSTANT_1</code> and so on.</p>
<p>No-one who is still involved in the project seems to have any idea why it was done this way, except that someone seems to think the guy who did it thought it made unit testing easier.</p>
<p>Can someone explain to me any advantages of doing it this way and why I shouldn't just move all the properties to the <code>SystemConfig</code> class and delete the metaclass?</p>
<p>Edit to add:  The metaclass definition doesn't contain anything other than properties.</p>
",https://stackoverflow.com/questions/74445635/why-define-constants-in-a-metaclass,"['python', 'python-3.x', 'pytest', 'python-unittest', 'pytest-mock']",59,False,1,2
How to test database methods and get code coverage xUnit ASP.NET,"<p>I initially used the <a href=""https://documentation.help/Moq/"" rel=""nofollow noreferrer"">Moq</a> library for testing, since I don't actually want to mess the data in my database. However, I quickly realized instead of running the code in some way and faking the result, it just does the latter. I need to reach a code coverage of at least 80% due to a project deadline in a couple of days, and the database is a big chuck of the code.
I have some methods for my DB in separate classes such as:</p>
<p><code>public Task&lt;bool&gt; DBEmpty();</code></p>
<p><code>public Task&lt;bool&gt; ParseToDB();</code></p>
<p><code>public Task&lt;Customer&gt; GetCustomer(int id);</code></p>
<p>I want these methods something like mocked, so I don't mess my data, but also get code coverage. Unless it is customary that database methods are traditionally marked with  <code>[ExcludeFromCodeCoverage]</code>, is it? My only previous experience with unit testing is a calculator app, I am brand new to this sport and this is the first time I use a c# testing framework (xUnit).</p>
",https://stackoverflow.com/questions/71832172/how-to-test-database-methods-and-get-code-coverage-xunit-asp-net,"['c#', 'unit-testing', 'asp.net-web-api', 'moq', 'xunit']",138,False,1,1
Mocking individual methods of external module differently each time in jest,"<p>I want to test my service methods which is dependent on the external module <code>azure-devops-extension-api</code>.</p>
<p>Currently I have created <code>__mocks__\azure-devops-extension-sdk.ts</code> and provide the custom implementation which needs to be mocked. It works fine. But there are some issues with unit testing as asked in <a href=""https://stackoverflow.com/questions/74863189/methods-called-on-jest-mocked-response-fails-with-error?noredirect=1#comment132116963_74863189"">Methods called on jest mocked response fails with error</a>.</p>
<p>But I don't have to feasibility to change values for each of the unit test. Values that needs to be provided in mock will vary based on the unit test case.</p>
<p>for example, below is my service method which uses the <code>getService()</code> method from SDK of <code>azure-devops-extension-api</code> module.</p>
<pre class=""lang-js prettyprint-override""><code>import * as SDK from 'azure-devops-extension-sdk';
// more stmts

const projectService = await SDK.getService&lt;IProjectPageService&gt;(CommonServiceIds.ProjectPageService);

const project = await projectService.getProject();
</code></pre>
<p>For first unit test, I want to mock the <code>getProject()</code> method to return a valid value and for the second unit test, I want to be a null.</p>
<p>Most common solution is the below approach, but as requested, I want the flexity to mock differently for each unit test.</p>
<pre class=""lang-js prettyprint-override""><code>jest.mock('azure-devops-extension-sdk', () =&gt; {
  return { getService: (client: any) =&gt; { id: 1, name: 'project' } };
});
</code></pre>
",https://stackoverflow.com/questions/74866462/mocking-individual-methods-of-external-module-differently-each-time-in-jest,['jestjs'],16,False,0,0
Check change of html class in Jest (Vanilla JS),"<p>Having this HTML -&gt;</p>
<pre><code>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;...&lt;/head&gt;
  &lt;body&gt;
    &lt;section class=&quot;players hidden&quot;&gt;&lt;/section&gt;
    &lt;button class=&quot;btn&quot;&gt;Play&lt;/button&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Other function calls this one, the event is assigned and works well -&gt;</p>
<pre><code>const players = document.querySelector('.players');
const playBtn = document.querySelector('.btn');

const eventListener = () =&gt; {
  playBtn.addEventListener('click', () =&gt; {
    if (players.classList.contains('hidden')) {
      players.classList.remove('hidden');
    }
  });
};

export default eventListener;
</code></pre>
<p>Now, this test always fails because it only uses the HTML I provided there -&gt;</p>
<pre><code>test('click event starts the game', () =&gt; {
  document.body.innerHTML = `
    &lt;section class=&quot;players hidden&quot;&gt;&lt;/section&gt;
    &lt;button class=&quot;btn&quot;&gt;Play&lt;/button&gt;
  `;

  const players = document.querySelector('.players');
  const playBtn = document.querySelector('.btn');
  playBtn.click();
  const myClass = players.classList.contains('hidden');
  expect(myClass).toBe(false);
});

</code></pre>
<p><code>myClass</code> will always be <code>true</code> because it's using that HTML I provided there.
My question is, how can I test the functionality of <code>eventListener.js</code>? I want to simulate that button click, remove class hidden and test if it was indeed removed as intended?</p>
<p>Somehow I have to call the <code>eventListener.js</code> but even if I do it will still test that interal HTML in the test, correct? If I go to <code>index.html</code> and remove all classes will not affect the test which makes no sense, The idea of this test is to know if in the future I change or remove classes the test would fail letting me know where is the error.</p>
<p>Is this still considered unit testing? Or would be E2E?</p>
",https://stackoverflow.com/questions/73513322/check-change-of-html-class-in-jest-vanilla-js,"['javascript', 'unit-testing', 'jestjs', 'integration-testing']",253,False,0,1
Stubbing order and process in Unit Testing function,"<p>I am starting to improve at Unit testing, but still thrown off by a few things. So I have the following service function</p>
<pre><code>const connectToService = async (connectionParams) =&gt; {
  try {
    const xmlRequest = await getLoginXml(
      connectionParams.username,
      connectionParams.password,
      connectionParams.url,
    );

    const res = await axios.post(connectionParams.msHost, xmlRequest);
    const dom = new DOMParser().parseFromString(res.data, 'text/xml');

    if (
      !dom.documentElement
        .getElementsByTagName('wsse:BinarySecurityToken')
        .item(0)
    ) {
      throw new Error('Invalid Username/Password');
    }
    return dom.documentElement
      .getElementsByTagName('wsse:BinarySecurityToken')
      .item(0).firstChild.nodeValue;
    
  } catch (e) {
    throw new Error(`Error making connection - ${e.message}`);
  }
};

module.exports = {
  connectToService,
};
</code></pre>
<p>So I have a relatively straight forward function above.  Takes <code>connectionParams</code> and injects some params using <code>getLoginXml</code>, which just returns some XML.</p>
<p>I then make a POST request with that xml and receive a response.  I then parse this response and return a token if there is one, if not, I throw an Error.</p>
<p>The thing that is throwing me is that there are a few things going on in this function, and I am not sure what to stub.</p>
<p>SO what would be the process first?  Stub <code>getLoginXml</code> and then let the rest of the function run?  And go through the file sequentially?</p>
<p>Any advice appreciated - I have done well with my integration tests, but unit test I am struggling to fully get to grips with.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/73437634/stubbing-order-and-process-in-unit-testing-function,"['node.js', 'unit-testing', 'mocha.js', 'sinon']",17,False,0,0
How to dynamically load GraphQL Queries from different files into JMeter for load testing?,"<p>My team needs to add load testing for our GraphQL API, and we decided to use JMeter because it is supported by Azure Load Testing.</p>
<p>We have several graphql files that define queries like this:</p>
<p>request.graphql</p>
<pre class=""lang-php prettyprint-override""><code>query Foo($id: Long!) {
  name
  time
}
</code></pre>
<p>With corresponding test.json files used for unit testing that defines the query name, variables for the request, and an assert that contains the expected response from our API</p>
<p>request.test.json</p>
<pre class=""lang-json prettyprint-override""><code>[
  {
    &quot;Query&quot;: &quot;Foo&quot;,
    &quot;Variables&quot;: {
      &quot;id&quot;: 001
    },
    &quot;Assert&quot;: {
      &quot;name&quot;: &quot;bar&quot;,
      &quot;time&quot;: &quot;01/01/1999&quot;
    }
  }
]
</code></pre>
<p>We have dozens of these unit tests that we want to use for load testing our API using JMeter. How would we dynamically load our queries, variables, and assertions using JMeter, and load that into Azure Load Testing?</p>
<p>This is currently my very basic test plan with one graphql HTTP request. I want to avoid manually adding every single query, so that the queries in load tests get updated when a graphql and test.json file gets changed for our API.</p>
<p><a href=""https://i.stack.imgur.com/fp4pk.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fp4pk.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/74074514/how-to-dynamically-load-graphql-queries-from-different-files-into-jmeter-for-loa,"['testing', 'graphql', 'jmeter', 'load-testing', 'azure-load-testing']",32,False,0,1
Error: Uncaught (in promise): true in jasmine test case for Angular,"<p>I'm new to angular unit testing , was trying to fix the already existing unit test case which fails the error that I getting is   <strong>Error: Uncaught (in promise): true</strong></p>
<p>The code for the unit test case is as follows</p>
<pre><code>  it('ngOnInit', fakeAsync(() =&gt; {
        // fixture.detectChanges();
        component.ngOnInit();
        tick();
        expect(component.dataConfig.industries.length).toEqual(3);
        expect(component.dataConfig.fonts.length).toEqual(2);
      }));
</code></pre>
<p>now within ngOnInit a call is made to the function  which is as below</p>
<pre><code>checkUserRole=()=&gt;{
    const requiredRoles = ['admin','developer'];
     this.hasAdminRole = this.service.checkRequiredRoles(
      requiredRoles,
      false
    );
  }
</code></pre>
<p>and within the spec.ts file they have created the stub and provided it in the provider as below</p>
<pre><code>TestBed.configureTestingModule({
      declarations: [ClientConfigComponent],
      imports: [TestingModule, ngfModule, MatDialogModule,
        MaterialModule,
        FormsModule,
        ToastrModule.forRoot(),
        BrowserAnimationsModule,
        ReactiveFormsModule,
        SharedModule
      ],
      providers: [{
        provide: MatDialogRef,
        useValue: mockDialogRef
      }, {
        provide: MAT_DIALOG_DATA, useValue: {}
      },
      { provide: HttpClient, useClass: FakeHttpService },
      {
        provide: MasterService,
        useValue: masterService
      }
      ]
    })
</code></pre>
<p>Stub</p>
<pre><code>const masterService = {
    loadTranslationConfiguration(): any {
      return of({});
    },
    checkRequiredRoles: (requiredRoles, arg) =&gt; ({}),
    saveTag(): any {
        return of(saveTags);
    },
    
  };
</code></pre>
<p>Error in detail</p>
<pre><code>Error: Uncaught (in promise): true
        error properties: Object({ rejection: true, promise: [object Promise], zone: Zone({ _parent: Zone({ _parent: null, _name: '&lt;root&gt;', _properties: Object({  }), _zoneDelegate: _ZoneDelegate({ _taskCounts: Object({ microTask: 0, macroTask: 0, eventTask: 0 }), zone: &lt;circular reference: Object&gt;, _parentDelegate: null, _forkZS: null, _forkDlgt: null, _forkCurrZone: null, _interceptZS: null, _interceptDlgt: null, _interceptCurrZone: null, _invokeZS: null, _invokeDlgt: null, _invokeCurrZone: null, _handleErrorZS: null, _handleErrorDlgt: null, _handleErrorCurrZone: null, _scheduleTaskZS: null, _scheduleTaskDlgt: null, _scheduleTaskCurrZone: null, _invokeTaskZS: null, _invokeTaskDlgt: null, _invokeTaskCurrZone: null, _cancelTaskZS: null, _cancelTaskDlgt: null, _cancelTaskCurrZone: null
</code></pre>
<p>I tried returning true from the stub of checkRequiredRoles using the <strong>of</strong> operator of the observable still it gave me same issue,I tried returning the promise the checkRequiredRoles method in service and using .then in stub it gave undefined checkRequiredRoles().then</p>
<p>I'm somewhat sure that error is with checkRequiredRoles function returning  a boolean value and not a promise</p>
<pre><code>public checkIfCurrentUserHasRequiredRoles(
    role: string[],
    RequiredRole: boolean
  ): boolean {
    
    //Some Logic

    return isTrue;
  }
</code></pre>
<p>What should i do to fix this issue where i'm going wrong ,thanks in advance for help</p>
",https://stackoverflow.com/questions/72436725/error-uncaught-in-promise-true-in-jasmine-test-case-for-angular,"['angular', 'unit-testing', 'karma-jasmine']",1153,False,0,1
mock window.addEventListener() method,"<p>How could I test this code:</p>
<pre><code>this.window.addEventListener('pathSelectedFromMfe', (customEvent: CustomEvent) =&gt; {
  this.window.location.href = customEvent.detail.path;
});
</code></pre>
<p>This is what I have tried:</p>
<p>Let's say that you want to test the <code>window.addEventListener()</code> method without modifying the <code>window.location.href</code> property when an event is received. Usually an easy way to do this would be by following this answer: <a href=""https://stackoverflow.com/questions/57674212/how-to-test-angular-event-listeners"">How to test angular event listeners?</a>. As you can see, no mock is required in that case.</p>
<p>If you proceed with the previous solution for my code, the test will fail with an error like this:
<code>Some of your tests did a full page reload!</code>.</p>
<p>Next step for me was to find out how can I test just the <code>this.window.location.href = customEvent.detail.path;</code> line and this can be done by following this answer:
<a href=""https://stackoverflow.com/questions/69537614/angular-unit-testing-window-location-href"">Angular unit testing window.location.href</a>. As you can see, a mock is being used in this case.</p>
<p>Now I believe that this solution (by using a mock) could be modified to also test the <code>window.addEventListener()</code> method, but I am not sure how to do that.</p>
",https://stackoverflow.com/questions/74559046/mock-window-addeventlistener-method,"['angular', 'mocking', 'jasmine', 'window', 'addeventlistener']",226,False,0,1
Pass SQL to Azure virtual machine using Invoke-AzVMRunCommand,"<p>I am trying to send a script to an Azure virtual machine running SQL Server to extract some user information (see below, key connection details redacted, obviously :))</p>
<p>The script runs perfectly when I run it locally on the VM, outputting exactly what I need. However, if I send exactly the same script using <em>Invoke-AzVMRunCommand</em> then only the header row gets output (i.e. the SQL query returns no data).</p>
<p>I have put lots of unit testing in and output different strings as the script executes (by assigning the <em>Invoke-AzVMRunCommand</em> to a variable and using <em>.Value.Message</em>)  - the connection to the SQL Server instance is being made fine, but for some reason the query is returning nothing when the script is being invoked remotely instead of run locally :(</p>
<p>It's driving me bananas, does anyone have any ideas why it's happening??</p>
<pre><code># Declare temporary variables for output and array to store all the lines in
#(these will eventually be passed to the script as params from the Invoke-AzVMRunCommand
$database = &quot;N/A (All databases)&quot;
$svrResourceGroupName = &quot;NFUM-303-DEV-001-UKS-RG&quot;
$tenant = &quot;Dev&quot;
$service = &quot;CRM&quot;
$server = &quot;DZ303NFUS008&quot;
$outputRolesFlag = $true
$textOutputArray = @()

# Create file name for output
$Date = Get-Date
$NOW = $Date.ToString(&quot;yyyyMMdd_HHmmss&quot;)
$fileName = $(&quot;C:\Temp\PowerShellOutput\&quot; + $server + &quot;_SQL_User_Info_$NOW.csv&quot;)

# Create header row and add to output array
if ($outputRolesFlag) {
    $outputString = &quot;Tenant,Service,Resource Group,SQL Server,Database,User Name,User Type,Role(s)&quot;
}
else {
    $outputString = &quot;Tenant,Service,Resource Group,SQL Server,Database,User Name,User Type&quot;
}

$textOutputArray += $outputString

# Connect to database
$dbConn = New-Object System.Data.SqlClient.SqlConnection
$dbConn.ConnectionString = &quot;Server=tcp:&lt;server_name&gt;,1433;User ID=&lt;username&gt;;Password=&lt;password&gt;;Connection Timeout=30;Integrated Security=true&quot;
try {
    $dbConn.Open()
}
catch {
    $errormessage = $error[0].Exception.Message
    $errormessage = $errormessage -split(': ')
    $errormessage = $errormessage[1]
    write-host -ForegroundColor Red $(&quot;Unable to connect to database due to error: &quot; + $errormessage)
    break
}

# Get local groups and their roles, store in hash table
$localGroupsAndTheirRolesAndUsers = @{}
$dbCmd = New-Object System.Data.SqlClient.SqlCommand
$dbCmd.Connection = $dbConn
$dbCmd.CommandText = &quot;select isnull(SP1.name, 'Public') as RoleName, SP2.name as GroupName from master.sys.server_role_members as SRM `
left outer join master.sys.server_principals AS SP1 on SRM.role_principal_id = SP1.principal_id `
right outer join master.sys.server_principals AS SP2 on SRM.member_principal_id = SP2.principal_id `
where sp2.type = 'G' order by GroupName&quot; 
$dataset = New-Object System.Data.DataSet
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter
$adapter.SelectCommand = $dbCmd
$adapter.Fill($dataset) | out-null
$roles = $dataset.Tables.RoleName
$groups = $dataset.Tables.GroupName


# Assign groups to info in nested hash table
for($i=0;$i -lt $groups.Count;$i++) {
    $thisGroupsUsers = @()
    $actualGroupName = $groups[$i] -split('\\')
    $actualGroupName = $actualGroupName[1]

    # Create nested hash table
    $localGroupsAndTheirRolesAndUsers[$actualGroupName] = @{}
    
    # Assign role
    $localGroupsAndTheirRolesAndUsers[$actualGroupName]['Role'] = $roles[$i]

    # Get users, add to array, then add that to nested hash
    $thisGroupsUsersObject = Get-LocalGroupMember -name $actualGroupName
    foreach ($user in $thisGroupsUsersObject ) {
        $userName = $user.Name -split ('\\')
        $userName = $userName[1]
        $thisGroupsUsers += $userName
    }
    $localGroupsAndTheirRolesAndUsers[$actualGroupName]['Users'] = $thisGroupsUsers 
}

foreach ($group in $localGroupsAndTheirRolesAndUsers.GetEnumerator()) {
    foreach($user in $localGroupsAndTheirRolesAndUsers[$group.Key]['Users']) {
        if ($outputRolesFlag) {
            $finalUserOutputString = $($user + &quot;,Windows,&quot; + $localGroupsAndTheirRolesAndUsers[$group.Key]['Role'])
        }
        else {
            $finalUserOutputString = $($user + &quot;,Windows&quot;)
        }
        $outputString = $(&quot;$tenant,$service,$svrResourceGroupName,$server,$database,$finalUserOutputString&quot;) 
        $textOutputArray += $outputString
    }
}

foreach ($line in $textOutputArray) {
    $line | Out-File -Encoding ASCII -filepath $fileName -Append
}
</code></pre>
<p>The SQL statement extracted from the above script is:</p>
<pre><code>select isnull(SP1.name, 'Public') as RoleName, SP2.name as GroupName 
from master.sys.server_role_members as SRM
left outer join master.sys.server_principals AS SP1 
on SRM.role_principal_id = SP1.principal_id
right outer join master.sys.server_principals AS SP2 
on SRM.member_principal_id = SP2.principal_id
where sp2.type = 'G' 
order by GroupName
</code></pre>
",https://stackoverflow.com/questions/71262336/pass-sql-to-azure-virtual-machine-using-invoke-azvmruncommand,"['sql-server', 'azure']",67,False,0,0
How to make sure composer version running on github action would same as composer version inside my docker container?,"<p>I'm not really sure how github actions works when running their jobs. Currently i'm facing this condition:</p>
<ul>
<li>I have devilbox docker services that includes specific php version and also has composer with specific version.</li>
<li>Currently i'm working laravel project with TDD and using artisan (php unit and laravel dusk) to do unit testing, integration testing, and browser testing (gui testing) automatically. Because i don't have PHP on my host machine, so artisan tests must be run inside the docker container, right?</li>
</ul>
<p>So now, how to make sure I can run composer build/update, php artisan test also with laravel dusk inside the docker container to make sure the tools version used is based on the tools installed in the docker container?</p>
<p>I want to get to know how to make sure the tools version used in github actions is based on the tools installed in the docker container</p>
",https://stackoverflow.com/questions/74229461/how-to-make-sure-composer-version-running-on-github-action-would-same-as-compose,"['laravel', 'docker', 'github', 'composer-php', 'github-actions']",168,True,0,1
How to close a file read with pandas,"<p>I am trying to close a file that I read with pandas data frame in the form of</p>
<p><code>df = pd.read_csv(file_name)</code></p>
<p>and not <code>example_file = open(file_name)</code> (there are some solutions with this case)</p>
<p>so I am trying to close the file after reading it or even writing to it. I am aware that python automatically closes back the file but while running unit tests, it throws resource allocation warnings, so in order to get rid of those warnings I need to have the files closed.</p>
<p>I have tried using storing the file name for example</p>
<blockquote>
<p>file_name  = &quot;randomfile.csv&quot;</p>
</blockquote>
<p>and then tried doing</p>
<blockquote>
<p>file_name.close()</p>
</blockquote>
<p>but this does not work. I have also tried using</p>
<blockquote>
<p>df.close()</p>
</blockquote>
<p>but that does not work as well.</p>
<p>The original problem is:</p>
<blockquote>
<p>ResourceWarning: Enable tracemalloc to get the object allocation traceback</p>
</blockquote>
<p>which I found out meant that I have a file opened. And this warning only shows when unit testing.</p>
",https://stackoverflow.com/questions/72999629/how-to-close-a-file-read-with-pandas,"['python', 'pandas', 'dataframe', 'csv', 'file']",701,False,0,0
"I have a Java homework problem that I cannot seem to figure out. Using regular expression and/or API classes like Pattern, Matcher is not allowed","<p>//Name this program StuPreIPv6) Each network device must be assigned an IP address. An IPv6 (IP address version 6) address is represented in the preferred format as eight groups of four hexadecimal digits. A hexadecimal digit may be 0 ~ 9 or a ~ f (or A ~ F). The groups are separated by colons (:). An example of an IPv6 address is:</p>
<pre><code>2001:0db8:85a3:0000:0000:8a2e:0370:7001
</code></pre>
<p>Write a method to decide whether a string contains a valid IPv6 address in the preferred format (each h represents a hexadecimal digit):</p>
<p>hhhh:hhhh:hhhh:hhhh:hhhh:hhhh:hhhh:hhhh</p>
<p>For this assignment, your method must loop through individual characters in the string. Approaches using regular expression and/or API classes like Pattern, Matcher will receive zero credit.</p>
<p>Start with a method stub like this one. The main() will be used for unit testing (see ch6.6).</p>
<p>// Returns true if the string parameter contains a valid IPv6
// address in the preferred format. Otherwise returns false.</p>
<pre><code>public class IPv6{ 
     public static boolean isValidPreferFormatIpv6(String address) {
     return false;
  }
  
  // for unit testing
    public static void main(String[] args) {
        System.out.println(&quot;Testing started ...&quot;);
    
    String str; // store test strings
    
    str = &quot;&quot;;
    if (isValidPreferFormatIpv6(str) != false) // if not the expected result
      System.out.println( &quot;isValidPreferFormatIpv6(&quot; + str + &quot;) failed&quot;; 

    str = &quot;0123:4567:89ab:cdef:0123:4567:89ab:cdef&quot;;
    if (isValidPreferFormatIpv6(str) != true) // if not the expected result
     System.out.println( &quot;(isValidPreferFormatIpv6(&quot; + str + &quot;) failed&quot;; 
  
// add more testing cases    


    System.out.println(&quot;Testing completed.&quot;);public class IPv6{ 
     public static boolean isValidPreferFormatIpv6(String address) {
     return false;
  }
  
  // for unit testing
    public static void main(String[] args) {
        System.out.println(&quot;Testing started ...&quot;);
    
    String str; // store test strings
    
    str = &quot;&quot;;
    if (isValidPreferFormatIpv6(str) != false) // if not the expected result
      System.out.println( &quot;isValidPreferFormatIpv6(&quot; + str + &quot;) failed&quot;; 

    str = &quot;0123:4567:89ab:cdef:0123:4567:89ab:cdef&quot;;
    if (isValidPreferFormatIpv6(str) != true) // if not the expected result
     System.out.println( &quot;(isValidPreferFormatIpv6(&quot; + str + &quot;) failed&quot;; 
  
// add more testing cases    


    System.out.println(&quot;Testing completed.&quot;);
    
</code></pre>
",https://stackoverflow.com/questions/71563819/i-have-a-java-homework-problem-that-i-cannot-seem-to-figure-out-using-regular-e,"['java', 'ipv6']",113,True,-4,1
pytest html report keep stdout without stderr,"<p>I am currently using Pytest for some unit testing, and the plugin pytest-html to generate an html report. Currently, on the captured log it would display the stderr(my test code until the line the test fails) and stdout(a customized print message saying what are the values used for this failed test).
Because my test code is long and tedious to generate everytime on stderr, I would like to not display stderr on the details/log part of each test on the html report(or display only the line where it failed), but only display stdout would be enough. I wonder if there is a way to do so? Any help appreciated, thank you!</p>
<p>To display stdout without stderr in the html report, I have tried using -s when running the time on command line, however that would display none of either stdout or stderr:&quot;no log output captured&quot;.</p>
",https://stackoverflow.com/questions/74661444/pytest-html-report-keep-stdout-without-stderr,"['python', 'pytest', 'pytest-html']",27,False,0,0
Project Reactor onErrorReturn tests not working for errors thrown in nested streams,"<p>I am trying to test a collection of nested reactive services with streams like the following:</p>
<p>Stream A subscribes to Stream B flux, Stream B flux subscribes to Stream C flux, Stream C flux subscribes to Stream D flux.</p>
<p>I have a call like</p>
<p><code>onErrorReturn( new ResponseObject(&quot;test&quot;))</code></p>
<p>on Stream A to handle any errors emitted from Stream B, C, or D.</p>
<p>I am testing the <code>onErrorReturn()</code> call with a step verifier as follows:</p>
<pre><code>StepVerifier.create( streamACall(testData))
 .expectNextMatches( response -&gt; response.getText() == &quot;test&quot;)
 .verify()
</code></pre>
<p>I then use Mockito to mock an error being returned from Stream C or D as follows:</p>
<pre><code>Mockito.when(StreamDisCalled()).thenReturn(Flux.error(new someError(&quot;Some error message&quot;)));
</code></pre>
<p>I am expecting this error to then propagate from Stream D, to Stream C, to Stream B, where it is handled by Stream A. However in unit testing I get the following stack trace instead:</p>
<pre><code>expectation &quot;expectNextMatches&quot; failed (expected: onNext(); actual: onError( someError: Some error message))
</code></pre>
<p>How can I fix this so that doOnErrorReturn()  properly catches and handles the nested error, and my test is able to verify this behavior?</p>
",https://stackoverflow.com/questions/73750490/project-reactor-onerrorreturn-tests-not-working-for-errors-thrown-in-nested-stre,"['java', 'exception', 'stream', 'mockito', 'reactor']",152,False,0,0
Spy object keeps calling to real method even when stubbed,"<p>I am working on unit testing this service method, which requires using other methods in the same class that is being tested. So I have read about <code>spy</code> and applied it to my code. However, even when stubbed, the spy object of the class that I am testing keeps executing the real methods.</p>
<p>The method that is being tested</p>
<pre><code>@Override
    public CategoryResponseDto updateCategory(Long categoryId, UpdateCategoryRequestDto requestDto) {
        CategoryEntity categoryEntity = findById(categoryId);

        modelMapper.convertToEntity(requestDto, categoryEntity);
        categoryEntity = categoryRepository.save(categoryEntity);

        return modelMapper.convertToResponse(categoryEntity, CategoryResponseDto.class);
    }
</code></pre>
<p>My code to test it</p>
<pre><code>    @Test
    public void updateCategory_ShouldReturnCategoryResponseDto_WhenDataValid() {
        CategoryEntity categoryEntity = mock(CategoryEntity.class);
        UpdateCategoryRequestDto requestDto = mock(UpdateCategoryRequestDto.class);
        CategoryCrudServiceImpl spy = Mockito.spy(categoryCrudService);
        CategoryResponseDto expectedResult = mock(CategoryResponseDto.class);

        doReturn(categoryEntity).when(spy).findById(anyLong());
        when(categoryRepository.save(categoryEntity)).thenReturn(categoryEntity);
        when(modelMapper.convertToResponse(categoryEntity, CategoryResponseDto.class)).thenReturn(expectedResult);

        CategoryResponseDto result = categoryCrudService.updateCategory(1L, requestDto);

        assertThat(result, is(expectedResult));
    }
</code></pre>
<p>So the class being tested here is <code>CategoryCrudServiceImple</code>, the instance of that class is <code>categoryCrudService</code> in my test code and I create a spy out of it <code>spy(categoryCrudService)</code>. As you can see, I stubbed the <code>findById()</code> which comes from the same <code>CategoryCrudServiceImple</code> class with <code>doReturn(categoryEntity).when(spy).findById(1L);</code> and It didn't work, I tried passing in <code>any()</code> or <code>anyLong()</code> and the real <code>findById()</code> method is still called and throws the exception of <code>ResourceNotFound</code>.</p>
<p>Could you please help me with this? Am I missing or misunderstanding anything here?</p>
<p>Thank you very much for your precious time.</p>
",https://stackoverflow.com/questions/72253305/spy-object-keeps-calling-to-real-method-even-when-stubbed,"['java', 'unit-testing', 'mockito', 'stub', 'spy']",228,False,0,1
Pytest ModuleNotFoundError when multiple Python Packages with Identical Names in Project,"<p>I have a project containing several stand-alone python packages (i.e., Google Cloud Functions). Since they are independent of another, I re-use the same name of their sub-packages. However, when I try to execute any tests, it fails since python is always looking at the sub-package which comes first in my pythonpath.</p>
<p>Here is my project structure:</p>
<pre><code>src/
├── standalone_code_1/
|   ├── src/
|   |   ├── main.py
|   |   ├── modules/
|   |   |   ├── __init__.py
|   |   |   └── my_module_a.py
|   |   └── tests/
|   |   |   └── test_main.py
├── standalone_code_2/
|   ├── src/
|   |   ├── main.py
|   |   ├── modules/
|   |   |   ├── __init__.py
|   |   |   └── my_module_b.py
|   |   └── tests/
|   |   |   └── test_main.py
</code></pre>
<p>The <code>main.py</code> files look conceptually like this</p>
<pre><code>from modules.my_module_b import method_2

def method_i_want_to_test():
    return 42

if __name__ == '__main__':
    my_value = method_2()
    print(my_value)
</code></pre>
<p>and <code>test_main.py</code>:</p>
<pre><code>from standalone_code_2.src.main import method_i_want_to_test

def test_method_i_want_to_test():
    assert 42 == method_i_want_to_test()
</code></pre>
<p>I have a shell script for unit testing</p>
<pre><code>export PYTHONPATH=$PWD/src:$PWD/src/standalone_code_1/src/:$PWD/src/standalone_code_2/src/:$PYTHONPATH
   
# Run unit tests and check code coverage on branch
python -m coverage run --source &quot;.&quot; --branch -m pytest -v
</code></pre>
<p>Upon execution of the shell script, I receive the following error:
<a href=""https://i.stack.imgur.com/IZoJl.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/IZoJl.png"" alt=""enter image description here"" /></a></p>
<p>since Python looks at the pythonpath and finds a folder <code>modules</code> belonging to <code>standalone_code_1</code> , but there is of course no <code>my_module_b.py</code>.</p>
<p>When I switch the order of the pythonpath in the shell script (i.e., <code>PYTHONPATH=$PWD/src:$PWD/src/standalone_code_2/src/:$PWD/src/standalone_code_1/src/:$PYTHONPATH</code>) then the test of <code>standalone_code_2</code> works, however, I get the very same error for my tests in <code>standalone_code_1</code>.</p>
<p>How do I make python look beyond the first occurrence of a matching folder in the pythonpath?</p>
",https://stackoverflow.com/questions/72769862/pytest-modulenotfounderror-when-multiple-python-packages-with-identical-names-in,"['python-3.x', 'pytest', 'pythonpath']",73,False,0,0
Check change of html class in Jest (Vanilla JS),"<p>Having this HTML -&gt;</p>
<pre><code>&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
  &lt;head&gt;...&lt;/head&gt;
  &lt;body&gt;
    &lt;section class=&quot;players hidden&quot;&gt;&lt;/section&gt;
    &lt;button class=&quot;btn&quot;&gt;Play&lt;/button&gt;
  &lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>Other function calls this one, the event is assigned and works well -&gt;</p>
<pre><code>const players = document.querySelector('.players');
const playBtn = document.querySelector('.btn');

const eventListener = () =&gt; {
  playBtn.addEventListener('click', () =&gt; {
    if (players.classList.contains('hidden')) {
      players.classList.remove('hidden');
    }
  });
};

export default eventListener;
</code></pre>
<p>Now, this test always fails because it only uses the HTML I provided there -&gt;</p>
<pre><code>test('click event starts the game', () =&gt; {
  document.body.innerHTML = `
    &lt;section class=&quot;players hidden&quot;&gt;&lt;/section&gt;
    &lt;button class=&quot;btn&quot;&gt;Play&lt;/button&gt;
  `;

  const players = document.querySelector('.players');
  const playBtn = document.querySelector('.btn');
  playBtn.click();
  const myClass = players.classList.contains('hidden');
  expect(myClass).toBe(false);
});

</code></pre>
<p><code>myClass</code> will always be <code>true</code> because it's using that HTML I provided there.
My question is, how can I test the functionality of <code>eventListener.js</code>? I want to simulate that button click, remove class hidden and test if it was indeed removed as intended?</p>
<p>Somehow I have to call the <code>eventListener.js</code> but even if I do it will still test that interal HTML in the test, correct? If I go to <code>index.html</code> and remove all classes will not affect the test which makes no sense, The idea of this test is to know if in the future I change or remove classes the test would fail letting me know where is the error.</p>
<p>Is this still considered unit testing? Or would be E2E?</p>
",https://stackoverflow.com/questions/73513322/check-change-of-html-class-in-jest-vanilla-js,"['javascript', 'unit-testing', 'jestjs', 'integration-testing']",253,False,0,1
Stubbing order and process in Unit Testing function,"<p>I am starting to improve at Unit testing, but still thrown off by a few things. So I have the following service function</p>
<pre><code>const connectToService = async (connectionParams) =&gt; {
  try {
    const xmlRequest = await getLoginXml(
      connectionParams.username,
      connectionParams.password,
      connectionParams.url,
    );

    const res = await axios.post(connectionParams.msHost, xmlRequest);
    const dom = new DOMParser().parseFromString(res.data, 'text/xml');

    if (
      !dom.documentElement
        .getElementsByTagName('wsse:BinarySecurityToken')
        .item(0)
    ) {
      throw new Error('Invalid Username/Password');
    }
    return dom.documentElement
      .getElementsByTagName('wsse:BinarySecurityToken')
      .item(0).firstChild.nodeValue;
    
  } catch (e) {
    throw new Error(`Error making connection - ${e.message}`);
  }
};

module.exports = {
  connectToService,
};
</code></pre>
<p>So I have a relatively straight forward function above.  Takes <code>connectionParams</code> and injects some params using <code>getLoginXml</code>, which just returns some XML.</p>
<p>I then make a POST request with that xml and receive a response.  I then parse this response and return a token if there is one, if not, I throw an Error.</p>
<p>The thing that is throwing me is that there are a few things going on in this function, and I am not sure what to stub.</p>
<p>SO what would be the process first?  Stub <code>getLoginXml</code> and then let the rest of the function run?  And go through the file sequentially?</p>
<p>Any advice appreciated - I have done well with my integration tests, but unit test I am struggling to fully get to grips with.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/73437634/stubbing-order-and-process-in-unit-testing-function,"['node.js', 'unit-testing', 'mocha.js', 'sinon']",17,False,0,0
How to dynamically load GraphQL Queries from different files into JMeter for load testing?,"<p>My team needs to add load testing for our GraphQL API, and we decided to use JMeter because it is supported by Azure Load Testing.</p>
<p>We have several graphql files that define queries like this:</p>
<p>request.graphql</p>
<pre class=""lang-php prettyprint-override""><code>query Foo($id: Long!) {
  name
  time
}
</code></pre>
<p>With corresponding test.json files used for unit testing that defines the query name, variables for the request, and an assert that contains the expected response from our API</p>
<p>request.test.json</p>
<pre class=""lang-json prettyprint-override""><code>[
  {
    &quot;Query&quot;: &quot;Foo&quot;,
    &quot;Variables&quot;: {
      &quot;id&quot;: 001
    },
    &quot;Assert&quot;: {
      &quot;name&quot;: &quot;bar&quot;,
      &quot;time&quot;: &quot;01/01/1999&quot;
    }
  }
]
</code></pre>
<p>We have dozens of these unit tests that we want to use for load testing our API using JMeter. How would we dynamically load our queries, variables, and assertions using JMeter, and load that into Azure Load Testing?</p>
<p>This is currently my very basic test plan with one graphql HTTP request. I want to avoid manually adding every single query, so that the queries in load tests get updated when a graphql and test.json file gets changed for our API.</p>
<p><a href=""https://i.stack.imgur.com/fp4pk.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fp4pk.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/74074514/how-to-dynamically-load-graphql-queries-from-different-files-into-jmeter-for-loa,"['testing', 'graphql', 'jmeter', 'load-testing', 'azure-load-testing']",32,False,0,1
Unit test/functionnal test in Symfony : how to test if a route in a controller does what I want,"<p>I am totally a newbie in unit testing. I have this Symfony route (which is totally dumb, just for the exemple) :</p>
<pre class=""lang-php prettyprint-override""><code>    /**
     * @Route(&quot;/change-label/{question}&quot;, name=&quot;admin_question_change_label&quot;)
     */

    public function changeQuestionLabel(Question $question, EntityManagerInterface $em) {

        $question-&gt;setLabel('Test');

        $em-&gt;flush();

        $this-&gt;render('home/index.html.twig');

    }
</code></pre>
<p>What I want to do is to test automatically if this route actually changes the label property of any given Question object.
I'd like to write a test like : &quot;take a Question in the db, and if the Question's label, after i called the route 'admin_question_change_intitule' is 'Test', then that's ok.&quot;</p>
<p>Here's the pseudo code version :</p>
<pre class=""lang-php prettyprint-override""><code>public function testLabelChanged(): void
    {
        
        //take a question in the DB
        
        //call the route admin_question_change_intitule and pass it the question
        
        //if the question label is now 'Test', that's ok
    }
</code></pre>
<p>But I absolutely don't know what kind of test to write (unit or functional), and how to write it properly, or even if unit/functional tests are meant to do that. I have the feeling that unit tests are there just to test response status code, or validations, things like that, and not meant for larger tests.</p>
<p>Could you guide me and show me how to do that ?</p>
",https://stackoverflow.com/questions/73679635/unit-test-functionnal-test-in-symfony-how-to-test-if-a-route-in-a-controller-d,"['unit-testing', 'symfony', 'testing', 'routes']",59,False,0,0
JUnit5 - Rest API controller having custom spring validator is failing,"<p>I have a controller that accepts path parameter called 'jobName'. The @ValidateJobName is the custom validator that validates the user input. If the input is wrong then it throws the error below</p>
<blockquote>
<p>&quot;Invalid Job name, valid job names are: vendor, service, product,
pricing, currency, contract&quot;</p>
</blockquote>
<p>The issue I am facing is that, when I am testing my rest controller API the test case always fails by returning the above error even when the job name is one of the acceptable values but when I remove @ValidateJobName custom annotation from the controller my test cases gets passed.</p>
<p>The @ValidateJobName and Controller works all good when triggered from Postman client but when I do unit testing the test case fails.</p>
<p>I have tried lot of blogs and googled but could not get a solution, Below are my Controller and JUnit testcase.</p>
<p>Please help!</p>
<p><strong>JobController.java</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-html lang-html prettyprint-override""><code>@Validated
@Slf4j
@RestController
public class JobController {
 
    @Autowired
    ReportService reportService;
 
    @Autowired
    ReportConfig reportConfig;
 
    @RequestMapping(value = ""/importjob/{jobName}"", method = RequestMethod.GET)
    ResponseEntity&lt;DataIntegrationResponse&gt; getReport(@PathVariable @ValidateJobName String jobName) throws Exception {
    log.info(""Received a request to launch the "" + jobName + "" Job"");
    return reportService.getReport(jobName);
    }
}</code></pre>
</div>
</div>
</p>
<p><strong>JobControllerTest.java</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-html lang-html prettyprint-override""><code>@ExtendWith(MockitoExtension.class)
@WebMvcTest(JobController.class)
@AutoConfigureMockMvc
public class JobControllerTest {
 
    @MockBean
    ReportService reportService;
    
    @MockBean
    ReportConfig rep;
    
    @MockBean
    JobMapping jmap;
 
    @Autowired
    public MockMvc mockMvc;
    
  
    @Test
    public void testGetReport() throws Exception {
    String jobNameInput=""vendor"";
    HttpStatus httpStatus = HttpStatus.OK;
    String fitsReportName = ""idex_fits_vendor.csv"";
    String jobName = ""WFitsVendorJob"";
    String jobStatus = ""STARTED"";
    Long jobInstanceId = 1022L;
    String message = ""WFitsVendorJob triggered successfully."";
 
    DataIntegrationResponse response = new DataIntegrationResponse(LocalDateTime.now(), httpStatus, fitsReportName, jobName, jobStatus, jobInstanceId, message);    
 
    ResponseEntity&lt;DataIntegrationResponse&gt; responseEntity = new ResponseEntity&lt;DataIntegrationResponse&gt;(response, HttpStatus.OK);
    
    Mockito.when(reportService.getReport(jobNameInput)).thenReturn(responseEntity);
    
    mockMvc.perform(get(""/importjob/{jobName}"", ""vendor"")).andExpect(status().isOk());
 
    }</code></pre>
</div>
</div>
</p>
<p><strong>JobNameValidator.java</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-html lang-html prettyprint-override""><code>@Component

public class JobNameValidator implements ConstraintValidator&lt;ValidateJobName, String&gt;{

    @Autowired
    private JobMapping jobMap;

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value!=null &amp;&amp; !jobMap.getMappings().containsKey(value)) { return false; }
        return true;
    }

}</code></pre>
</div>
</div>
</p>
<p><strong>ValidateJobName.java - interface</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-html lang-html prettyprint-override""><code>@Documented
@Constraint(validatedBy = JobNameValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
public @interface ValidateJobName {
    String message() default ""Invalid Job name, valid job names are: vendor, service, product, pricing, currency, contract"";
    Class&lt;?&gt;[] groups() default {};
    Class&lt;? extends Payload&gt; [] payload() default {};
}
 </code></pre>
</div>
</div>
</p>
",https://stackoverflow.com/questions/73747837/junit5-rest-api-controller-having-custom-spring-validator-is-failing,"['rest', 'junit', 'mockito', 'junit5', 'spring-validator']",126,False,0,1
Unit testing SwiftUI/Combine @Published boolean values,"<p>I am trying to acquaint myself with unit testing some view models in SwiftUI. The view model currently has two <code>@Published</code> boolean values that publish changes when an underlying <code>UserDefaults</code> property changes. For my unit tests, I have followed <a href=""https://www.swiftbysundell.com/tips/avoiding-mocking-userdefaults/"" rel=""nofollow noreferrer"">this guide</a> on how to setup <code>UserDefaults</code> for testing so my production values are not modified. I am able to test the default value as such:</p>
<pre><code>func testDefaultValue() {
     XCTAssertFalse(viewModel.canDoThing)
}
</code></pre>
<p>How would I go about toggling the <code>@Published</code> value then ensuring my view model has received the changes? So for instance, I have a reference to my mock user defaults in my XCTestCase. I attempted to do the following with zero success:</p>
<pre><code>func testValueTogglesToTrue() {
     defaults.canDoThing = true
     XCTAssertTrue(viewModel.canDoThing)
</code></pre>
<p>}</p>
<p>The thought being that updating the underlying user defaults value that is publishing changes to the published value in the view model will notify our view model. The above does not do anything to the view model variable. Do I need to subscribe to the publisher and use sink to accomplish this?</p>
",https://stackoverflow.com/questions/70809030/unit-testing-swiftui-combine-published-boolean-values,"['unit-testing', 'swiftui', 'combine']",879,True,3,1
Testing Pinia changes in a Vue 3 Component Unit Test,"<p>I have a component in my Vue 3 app which displays a checkbox.  The checkbox can be manually checked by the user but it can also be checked/unchecked as a result of a Pinia state change. I'm pretty new to Unit Testing but I would assume that a good unit test for this component would include checking whether or not the checkbox reacts to the Pinia state correctly.  However, in my Unit Test, when I change the Pinia state, the checkbox value does not change (the component itself works fine, it's only in the Unit Test that this does not work).  Does anyone know what I am doing wrong?</p>
<p>As well as calling the store action to update the state I have also tried store.$patch and that doesn't work either.</p>
<p>This is my component:</p>
<pre><code>&lt;template&gt;
  &lt;div class=&quot;field-checkbox&quot;&gt;
    &lt;Checkbox role=&quot;checkbox&quot; :aria-label=&quot;displayName&quot; @change=&quot;checkGroupMember()&quot; v-model=&quot;checked&quot; :binary=&quot;true&quot; /&gt;
    &lt;label&gt;{{displayName}}&lt;/label&gt;
  &lt;/div&gt;
&lt;/template&gt;

&lt;script setup lang=&quot;ts&quot;&gt;
import { useContactBookStore } from &quot;@/stores/contactBookStore&quot;;
import { ref, watch } from &quot;vue&quot;;
import { storeToRefs } from &quot;pinia&quot;;
const store = useContactBookStore();
const props = defineProps({
  groupMember: { type:Object, required: true }
});
const checked = ref(false);
const { getCheckedGroupMembers } = storeToRefs(store)
const displayName = ref(props.groupMember.title + &quot; &quot; + props.groupMember.firstName + &quot; &quot; + props.groupMember.lastName);

// set the initial value of the checkbox
updateCheckBox();

// watch the value of getCheckedGroupMembers in the store and if it
// changes re-evaluate the value of the checkbox
watch(getCheckedGroupMembers , () =&gt; {
  updateCheckBox();
},{ deep: true })

// when the checkbox is checked/unchecked, run the checkUser method
// in the store
function checkGroupMember() {
  const groupMember = {
    id:props.groupMember.id,
    title:props.groupMember.title,
    firstName:props.groupMember.firstName,
    lastName:props.groupMember.lastName
  }
  store.checkGroupMember(groupMember,checked.value);
}

// the checkbox is checked if the user is among the checked users
// in the store
function updateCheckBox() {
  const groupMember = {
    id: props.groupMember.id,
    title: props.groupMember.title,
    firstName: props.groupMember.firstName,
    lastName: props.groupMember.lastName
  }
  const exists = getCheckedGroupMembers.value.find((member) =&gt; member.id === groupMember.id)
  checked.value = !!exists;
}

&lt;/script&gt;
</code></pre>
<p>and this is my Unit Test:</p>
<pre><code>import { render, screen } from &quot;@testing-library/vue&quot;;
import GroupMember from &quot;@/components/ContactBook/GroupMember.vue&quot;;
import { describe, it, vi, expect, beforeEach, afterEach } from &quot;vitest&quot;;
import { createTestingPinia } from &quot;@pinia/testing&quot;;
import PrimeVue from &quot;primevue/config&quot;;

import { createPinia, setActivePinia } from &quot;pinia&quot;;
import Checkbox from 'primevue/checkbox';
import { useContactBookStore } from &quot;@/stores/contactBookStore&quot;;

describe(&quot;GroupMember&quot;, () =&gt; {

  const mockUser:GroupMember = {id:&quot;TT001&quot;,title:&quot;Mr&quot;,firstName:&quot;Ted&quot;,lastName:&quot;Tester&quot;}

  let mockProps = {groupMember:mockUser};

  render(GroupMember, {
    props: mockProps,

    global: {
      components: {Checkbox},
      plugins: [PrimeVue,
        createTestingPinia({
          initialState: {contactBook:{checkedGroupMembers:[mockUser]}},
          stubActions: false,
          createSpy: vi.fn,
          fakeApp:true
        }),
      ],
    },
  });

  setActivePinia(createPinia());

  it(&quot;Displays the user name in the correct format&quot;, async() =&gt; {
    const displayName = mockProps.groupMember.title + &quot; &quot; + mockProps.groupMember.firstName + &quot; &quot; + mockProps.groupMember.lastName;
    screen.getByText(displayName)
  });

  it(&quot;Shows the checkbox initially checked&quot;, async() =&gt; {
    let checkbox:any;
    const displayName = mockProps.groupMember.title + &quot; &quot; + mockProps.groupMember.firstName + &quot; &quot; + mockProps.groupMember.lastName;
    checkbox = screen.getAllByRole(&quot;checkbox&quot;, { name: displayName })[1]
    expect(checkbox.checked).toBe(true)
  });

  it(&quot;Should display the checkbox as unchecked when the store is updated&quot;, async() =&gt; {
    let checkbox:any;
    const displayName = mockProps.groupMember.title + &quot; &quot; + mockProps.groupMember.firstName + &quot; &quot; + mockProps.groupMember.lastName;
    checkbox = screen.getAllByRole(&quot;checkbox&quot;, { name: displayName })[1]
    const store = useContactBookStore();
    await store.checkGroupMember(mockUser,false);
    //await store.$patch({checkedGroupMembers:[]})  // this didn't work either
    expect(checkbox.checked).toBe(false)
  });
});
</code></pre>
<p>this is the error I get when the test runs:</p>
<pre><code>54|     expect(checkbox.checked).toBe(false)
       |                             ^
     55|   });
     56| });

  - Expected   &quot;false&quot;
  + Received   &quot;true&quot;
</code></pre>
",https://stackoverflow.com/questions/74300254/testing-pinia-changes-in-a-vue-3-component-unit-test,"['unit-testing', 'vuejs3', 'pinia', 'vitest', 'vue-testing-library']",1252,True,2,1
jasmine unit-testing: Can&#39;t trigger change event in custom angular dropdown component,"<p>I am working on unit-testing with jasmine and karma an angular component. In the template-component a custom dropdown component is used:</p>
<pre><code>   &lt;div class=&quot;my-modal-body&quot;&gt;
        &lt;form [formGroup]=&quot;form&quot; class=&quot;form-horizontal&quot;&gt;
            &lt;div class=&quot;padding-dropdown&quot;&gt;
                &lt;my-form-wrapper
                    label=&quot;Dateiformat&quot;
                    labelClass=&quot;col-lg-4 two-col-label-size&quot;
                    inputClass=&quot;col-lg-8 two-col-input-size&quot;
                &gt;
                    &lt;my-dropdown
                        [items]=&quot;exportOptionen&quot;
                        formControlName=&quot;dateiTyp&quot;
                        (selectedChange)=&quot;exportFileChange($event)&quot;
                    &gt;
                    &lt;/my-dropdown&gt;
                &lt;/my-form-wrapper&gt;
            &lt;/div&gt;
</code></pre>
<p>In my testing I try to test the value change, but can't get it working. However I try to set the value, the exportFileChange is not triggered.
And I know that the component is correct, because it's already in production. So it has to be the test that errors.</p>
<p>Here is my test:</p>
<pre><code>    it('dateiTyp auswahl excel', waitForAsync(() =&gt; {
        spyOn(component, 'exportFileChange');
        dateiTyp.setValue('Excel');
        component.dateiTyp.setValue('Excel', { emitEvent: true });
        fixture.detectChanges();
        fixture.whenStable().then(
            () =&gt; {
                expect(component.exportFileChange).toHaveBeenCalled();
                let exDiv = fixture.debugElement.query(By.css(&quot;#excelExportDiv&quot;));
                expect(exDiv).not.toBeNull();
            }
        );
    }));
</code></pre>
<p>When changing the selection the exportFileChange(event) method should be called and in the template an div appears. The exportFileChange-Method in the component just changes an boolean.
I tested changing the boolean in the test and that worked, but the event still wasn't triggered.</p>
<p>Here are the most relevant parts of the setup:</p>
<pre><code>describe('ExportModalComponent', () =&gt; {
   [...]
   let dateiTyp: jasmine.SpyObj&lt;FormControl&gt;;
   let dateiTypChange: Subject&lt;string&gt;;
[...]

beforeEach( waitForAsync(() =&gt; {
[...]
  dateiTyp = jasmine.createSpyObj('dateiTyp', ['value', 'setValue']);
  formGroup.get.withArgs('dateiTyp').and.returnValue(dateiTyp);
  dateiTypChange = new Subject();
  Object.defineProperty(dateiTyp, 'valueChanges', { value: dateiTypChange });
[...]

</code></pre>
<p>and my-dropdown.component.d.ts:</p>
<pre><code>export declare class myDropdownComponent implements ControlValueAccessor, OnInit, OnChanges 
{ [...] }
</code></pre>
<p>I can change the ExportModal-template or the ExportModal-component but I can't change the implementation or use of myDropdownComponent.</p>
<p>I am grateful for every help!</p>
<p>Thanks!</p>
",https://stackoverflow.com/questions/71175706/jasmine-unit-testing-cant-trigger-change-event-in-custom-angular-dropdown-comp,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",1573,True,2,1
ANTLR4 grammar rule that cannot be reached from start rule affects language,"<p>The following minimal grammar shows the issue:</p>
<pre><code>grammar test;

call : exp LP exp RP ;

exp : exp LP exp RP | ID;

ID : [a-z] ;
LP : '(' ;
RP : ')' ;
Newline : '\r\n' | '\n' ;
</code></pre>
<p>If I use <code>call</code> as the start rule, then the generated parser will gladly parse the following input:</p>
<pre><code>f(x)
</code></pre>
<p>(tried it in <a href=""http://lab.antlr.org/"" rel=""nofollow noreferrer"">ANTLR lab</a>, which probably uses the java target, and locally using a C++ target with ANTLR 4.9.3).</p>
<p>If I now add the following rule to the grammar, but keep <code>call</code> as the start rule, then the same input does not match <code>call</code> anymore.</p>
<pre><code>callWithNewline : call Newline;
</code></pre>
<p><a href=""https://i.stack.imgur.com/indJ5.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/indJ5.png"" alt=""unexpected error"" /></a></p>
<p>Why does <code>callWithNewline</code> affect whether <code>call</code> matches?</p>
<p>If I change the input to have a newline character after it will suddenly match <code>call</code> in ANTLR lab (even though the newline is not part of the match of course), but not in the C++ target, so the targets have slightly different behavior here.</p>
<p>I ran into this behavior while unit testing subrules, it does appear that parsing a full grammar which contains this kind of subgrammar somewhere lower in the hierarchy does not lead to issues.</p>
<p><strong>Edit</strong></p>
<p>The issue still occurs if I remove the ambiguity</p>
<pre><code>grammar test;

callWithNewline : call Newline ;

call : exp LP ID RP ;

exp : exp LP ID RP | ID;

ID : [a-z] ;
LP : '(' ;
RP : ')' ;
Newline : '\r\n' | '\n' ;
</code></pre>
",https://stackoverflow.com/questions/74357697/antlr4-grammar-rule-that-cannot-be-reached-from-start-rule-affects-language,"['antlr', 'antlr4']",66,False,2,0
How do I resolve conflicting assertion types in Angular?,"<p>I am developing an Angular application that uses the Jasmine framework for regular unit testing and the Cypress framework for end-to-end testing.</p>
<p>While I have had no trouble conducting my E2E tests with Cypress, the <code>spec.</code> files used with Jasmine inside my source code folder <code>src</code> all underline the <code>toBe</code> method calls in red and display the following error message:</p>
<p><code>TS2339: Property 'toBe' does not exist on type 'Assertion'</code></p>
<p>A code sample for one my tests is displayed below:</p>
<pre><code>it('Should have a category of \'A\'', () =&gt; {(
    expect(category.category).toBe('A');
})
</code></pre>
<p>After doing research, I have discovered that the problem is due to both frameworks using the same assertion library. I have tried applying solutions from the following two posts but neither have worked.</p>
<ul>
<li><p><a href=""https://stackoverflow.com/questions/58999086/cypress-causing-type-errors-in-jest-assertions"">Cypress causing type errors in jest assertions</a></p>
</li>
<li><p><a href=""https://stackoverflow.com/questions/69291905/how-do-i-resolve-conflicting-type-identifiers-for-cypress-and-jquery"">How do I resolve conflicting type identifiers for Cypress and jQuery?</a></p>
</li>
</ul>
<p>Both solutions suggest editing one or more of the <code>tsconfigjson</code> files, though since I have started to use Cypress at version 10 and above, the <code>cypress</code> root folder has not come with its own config file.</p>
",https://stackoverflow.com/questions/74851654/how-do-i-resolve-conflicting-assertion-types-in-angular,"['angular', 'jasmine', 'cypress', 'assertion']",120,False,2,0
How to write Test Driven Development in .Net core MS Test in VS 2019?,"<p>We have been developing REST APIs in .Net core 3.1 and using MS TEST - Test Project in Visual Studio 2019 for unit testing.</p>
<p>Now we have a hard rule to follow <em><strong>Test Driven Development</strong></em>. In theory I can understand that TDD will involve writing tests to implement a requirement and continuously iterate through RED GREEN and REFACTOR cycles.</p>
<p>Now my question is, if I have a endpoint which will <strong>get all books according to author id from DB</strong>, like following endpoint</p>
<pre><code>httpget : api/boooks/authors/1006 
</code></pre>
<p>which will return a response, <strong>what all cases/ test methods should I write in the Test class of MSTest project, so that I can say that, I have followed Test Driven Development</strong> ?</p>
<p>Before TDD, I will write a TestMethod for the Service method which will call the Database layer and get the author information from SQL DB. SO only 1 test method with different input to mock, will be written.</p>
<p>I am very new to TDD hence the question. Any comment is helpful</p>
",https://stackoverflow.com/questions/72026271/how-to-write-test-driven-development-in-net-core-ms-test-in-vs-2019,"['c#', 'visual-studio', 'tdd', 'mstest']",219,True,1,2
Unit Testing with Jest for Strapi v4,"<p>I am trying to perform unit tests with Jest for the new version of Strapi, v4 which was just released a couple of weeks ago. In accordance with their documentation, the old guide for unit testing no longer runs as expected. I have, however, modified the code to work to a certain extent. Currently I have the following:</p>
<p><code>./test/helpers/strapi.js</code>:</p>
<pre class=""lang-js prettyprint-override""><code>const Strapi = require(&quot;@strapi/strapi&quot;);

let instance;

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

    await instance.server.mount();
  }
  return instance;
}

module.exports = {
  setupStrapi
};
</code></pre>
<p><code>./tests/app.test.js</code>:</p>
<pre class=""lang-js prettyprint-override""><code>const fs = require(&quot;fs&quot;);
const { setupStrapi } = require(&quot;./helpers/strapi&quot;);

beforeAll(async () =&gt; {
  await setupStrapi();
});

afterAll(async () =&gt; {
  const dbSettings = strapi.config.get(&quot;database.connection.connection&quot;);

  //close server to release the db-file
  await strapi.server.destroy();

  //DATABASE_FILENAME=.tmp/test.db

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

    if (fs.existsSync(tmpDbFile)) {
      fs.unlinkSync(tmpDbFile);
    }
  }
});

it(&quot;should return hello world&quot;, async () =&gt; {
  await request(strapi.server.httpServer).get(&quot;/api/hello&quot;).expect(200); // Expect response http code 200
});

</code></pre>
<p><code>./config/env/test/database.js</code></p>
<pre class=""lang-js prettyprint-override""><code>const path = require(&quot;path&quot;);

module.exports = ({ env }) =&gt; ({
  connection: {
    client: &quot;sqlite&quot;,
    connection: {
      filename: path.join(
        __dirname,
        &quot;../../../&quot;,
        env(&quot;DATABASE_FILENAME&quot;, &quot;.tmp/test.db&quot;)
      ),
    },
    useNullAsDefault: true,
  },
});

</code></pre>
<p>The route <code>/api/hello</code> is a custom API endpoint. This works perfectly when running <code>strapi develop</code>, and all permissions are set correctly.</p>
<p>The tests run, but every endpoint that is not <code>/</code> or <code>/admin</code> returns <code>403 Forbidden</code>, meaning there is a problem with the permissions. It would seem that the database file <code>.tmp/data.db</code> (used in development) is not replicated correctly in <code>.tmp/test.db</code>. In other words, this is close to working, but the permissions for API endpoints are not set correctly.</p>
<p>I have been searching through StackOverflow and the Stapi Forums over the past few days but to no avail. I would greatly appreciate some pointers as to how to fix this :)</p>
",https://stackoverflow.com/questions/70974645/unit-testing-with-jest-for-strapi-v4,"['javascript', 'node.js', 'unit-testing', 'jestjs', 'strapi']",1083,True,1,2
Spring Boot @RestController @Autowired null in Unit tests,"<p>I can't understand why @Autowiring my @RestController class is returning null.
I want to do a basic unit test before doing an integrated test but its failing.
In fact anything that is being @Autowired is showing null in the test package.</p>
<p>I have a very simple test, I just want to see the basic works:</p>
<p>A very simple example:</p>
<pre><code>@Component
public class SimpleComponent {

    public int add(int a, int b){
        return a + b;
    }

}
</code></pre>
<p>And the test:</p>
<pre><code>class SimpleComponentTest {

    @Autowired
    private SimpleComponent component;

    @Test
    public void givenSimpleComponentShouldNotBeNull(){
        assertNotNull(component);//How on earth does this fail?
    }


}
</code></pre>
<p>Here is the code from the Controller class:</p>
<pre><code>@RestController
public class EmployeeAccountApi {

    @PostMapping(&quot;/register&quot;)
    public String register(){
        return &quot;Registering!&quot;;
    }

}

public class EmployeeAccountApiUnitTest {

    @Autowired
    private EmployeeAccountApi employeeAccountApi;

    @Test
    public void testAutowiring(){
        assertNotNull(employeeAccountApi);//Fails, Can't understand why
    }

}
</code></pre>
<p>This works with the @Mock annotation:
But I dont want to mock it as that is the class I am unit testing.
I want to test that the method returns a basic string.
Question is why isn't it working?</p>
<pre><code>@ExtendWith(MockitoExtension.class)
public class EmployeeAccountApiUnitTest {

    @Mock
    private EmployeeAccountApi employeeAccountApi;

    @Test
    public void testAutowiring(){
        assertNotNull(employeeAccountApi);//This works
    }

}
</code></pre>
<p>Even if I get the Employee Service that clearly worked and tested in the previous test also is null in this class:</p>
<pre><code>public class EmployeeAccountApiUnitTest {

    @Autowired
    private EmployeeAccountApi employeeAccountApi;

    @Autowired
    private EmployeeService service;

    @Test
    public void testAutowiring(){
        //assertNotNull(employeeAccountApi);
        assertNotNull(service);
    }

}
</code></pre>
<p>Why is @Autowired null in the Test?
Mocking is working fine</p>
<p>Plenty of similar questions but they are too specific and not provide any basic information</p>
",https://stackoverflow.com/questions/71766354/spring-boot-restcontroller-autowired-null-in-unit-tests,"['java', 'spring-boot', 'annotations', 'junit5', 'autowired']",1577,True,1,2
Simplifying AWS SDK GO v2 testing/mocking,"<p>Amazon has a super useful article describing how to <a href=""https://aws.github.io/aws-sdk-go-v2/docs/unit-testing/"" rel=""noreferrer"">unit test AWS SDK Go v2</a>.  I understand their motivation to depart from the &quot;old&quot; way of unit testing the v1 API, which I think aligns with this <a href=""https://github.com/golang/go/wiki/CodeReviewComments#interfaces"" rel=""noreferrer"">CodeReviewComment</a>.</p>
<p>However, I'm running into a situation that is causing some havoc for me.</p>
<p>Let's say I'm calling <code>s3.HeadObject()</code> and, if some arbitrary condition is met, I then call <code>s3.GetObject()</code>.  So, I design my API so that I can create client APIs for each of these operations separately (in pseudoGo).</p>
<pre><code>type HeadObjectAPIClient interface {
    HeadObject(ctx context.Context, params *s3.HeadObjectInput, optFns ...func(*s3.Options)) (*s3.HeadObjectOutput, error)
}

func GetHeadObject(api HeadObjectAPIClient, params...) (*s3.HeadObjectOutput, error) {
    /* setup logic */
    return api.HeadObject( /* params */ )
}

type GetObjectAPIClient interface {
    GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error)
}

func GetObject(api GetObjectAPIClient, params...) (*s3.GetObjectOutput, error) {
    /* setup logic */
    return api.GetObject( /* params */ )
}

func DoSomething(headAPI HeadObjectAPIClient, getAPI GetObjectAPIClient, params...) error {
    headOutput, err := GetHeadObject(headAPI, ...params...)
    if err != nil {
        return err
    }
    // process headOutput then ...
    getOutput, err := GetObject(getAPI, ...params...)
    if err != nil {
        return err
    }
    // process getOutput
}
</code></pre>
<p>So, the <code>DoSomething</code> method is taking two APIs in addition to other parameters.  My natural inclination is to just make some kind of struct:</p>
<pre><code>type DoSomethingService struct {
    headAPI HeadObjectAPIClient
    getAPI GetObjectAPIClient
}

func (s DoSomethingService) DoSomething(params...) error {
    headOutput, err := GetHeadObject(s.headAPI, ...params...)
    if err != nil {
        return err
    }
    // process headOutput then ...
    getOutput, err := GetObject(s.getAPI, ...params...)
    if err != nil {
        return err
    }
    // process getOutput
}
</code></pre>
<p>Maybe that is ok ... but then I ask, well why not just make en embedded interface and avoid the struct:</p>
<pre><code>type DoSomethingAPIClient interface {
    HeadObjectAPIClient
    GetObjectAPIClient
}

func DoSomething2(api DoSomethingAPIClient, params...) error {
    headOutput, err := GetHeadObject(api, ...params...)
    if err != nil {
        return err
    }
    // process headOutput then ...
    getOutput, err := GetObject(api, ...params...)
    if err != nil {
        return err
    }
    // process getOutput
}
</code></pre>
<p>I can probably think of a couple more ways to make this happen, but I think I've made my point.</p>
<p>I'm looking for a good strategy to enable testing/mocking, while avoiding proliferating client interfaces for every single call into the SDK.</p>
",https://stackoverflow.com/questions/72235425/simplifying-aws-sdk-go-v2-testing-mocking,"['unit-testing', 'go', 'mocking', 'aws-sdk-go-v2']",2242,False,9,0
React Native: replacing formik with react-hook-form break Unit Test with Jest,"<p>I did a POC with <code>react-hook-form</code> to see if it's a better lib to replace <code>formik</code>. My pull request is just replacing the lib and is visible here: <a href=""https://github.com/pass-culture/pass-culture-app-native/pull/3564"" rel=""nofollow noreferrer"">https://github.com/pass-culture/pass-culture-app-native/pull/3564</a></p>
<p>It seems OK, however, we can still see re-render of the whole screen for both of the lib so it's unclear at this stage which one we will take for our app, which host at the moment 19 form and will grow.</p>
<p>Unit testing are now broken, we test with <code>@testing-library/react-native</code>, this is the error and it is not understandable:</p>
<pre><code>ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      56 |   const isAbsolutePosition = position === 'absolute' || !!withGoBackButton || !!RightComponent
      57 |   return (
    &gt; 58 |     &lt;Header&gt;
         |                           ^
      59 |       {!!isAbsolutePosition &amp;&amp; &lt;SpacerAbsolutePosition height={height + top} /&gt;}
      60 |       &lt;ColorContainer
      61 |         backgroundColor={backgroundColor}

      at Object.get StatusBar [as StatusBar] (node_modules/react-native/index.js:99:12)
      at src/ui/components/headers/PageHeader.tsx:58:27
      at Object.invokeGuardedCallbackProd (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11308:10)
      at invokeGuardedCallback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11499:31)
      at flushPassiveEffectsImpl (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14560:11)

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      51 |      * On Android, keyboardWillHide does not exist and keyboardDidHide is then used https://github.com/facebook/react-native/issues/3468
      52 |      */
    &gt; 53 |     if (Platform.OS === 'android') {
         |                                         ^
      54 |       handleKeyboardWillHide(e)
      55 |     }
      56 |     // If needed, implement iOS behavior here

      at Object.get Keyboard [as Keyboard] (node_modules/react-native/index.js:218:12)
      at src/ui/components/keyboard/useKeyboardEvents.ts:53:41
      at invokePassiveEffectCreate (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14504:20)
      at Object.invokeGuardedCallbackProd (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11308:10)
      at invokeGuardedCallback (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11499:31)

 RUNS  src/features/profile/pages/ChangePassword/tests/ChangePassword.native.test.tsx
/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/node_modules/scheduler/cjs/scheduler.development.js:60
        throw e;
        ^

TypeError: _reactNative.StatusBar.setBarStyle is not a function
    at /home/dka/workspace/github.com/pass-culture/pass-culture-app-native/src/ui/components/headers/PageHeader.tsx:58:37
    at Object.invokeGuardedCallbackProd (/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11308:10)
    at invokeGuardedCallback (/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:11499:31)
    at flushPassiveEffectsImpl (/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14560:11)
    at unstable_runWithPriority (/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/node_modules/scheduler/cjs/scheduler.development.js:468:12)
    at runWithPriority (/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:2486:10)
    at flushPassiveEffects (/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14464:14)
    at /home/dka/workspace/github.com/pass-culture/pass-culture-app-native/node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14341:11
    at workLoop (/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/node_modules/scheduler/cjs/scheduler.development.js:417:34)
    at flushWork (/home/dka/workspace/github.com/pass-culture/pass-culture-app-native/node_modules/scheduler/cjs/scheduler.development.js:390:14)

Node.js v18.7.0
</code></pre>
<h2>What we expect</h2>
<p>We expect unit test to pass, as it does in the main branch with <code>formik</code></p>
<pre class=""lang-bash prettyprint-override""><code>git clone --single-branch --branch master https://github.com/pass-culture/pass-culture-app-native.git
cd pass-culture-app-native
yarn
nvm use # or preceed with `nvm install 18` if you don't have node 18
yarn test:unit src/features/profile/pages/ChangePassword/tests/ChangePassword.native.test.tsx
</code></pre>
<h2>What is happening (with reproduction)</h2>
<p>This error does not happen with <code>formik</code>, this is how to reproduce:</p>
<pre class=""lang-bash prettyprint-override""><code>git clone --single-branch --branch react-hook-form-poc https://github.com/pass-culture/pass-culture-app-native.git
cd pass-culture-app-native
yarn
nvm use # or preceed with `nvm install 18` if you don't have node 18
yarn test:unit src/features/profile/pages/ChangePassword/tests/ChangePassword.native.test.tsx
</code></pre>
<p>Logging <code>StatusBar</code> from <code>react-native@0.68.2</code> in the component shows:</p>
<pre><code>    [Function: StatusBar] {
      _propsStack: [],
      _defaultProps: {
        backgroundColor: { value: 'black', animated: false },
        barStyle: { value: 'dark-content', animated: false },
        translucent: false,
        hidden: { value: false, animated: false, transition: 'fade' },
        networkActivityIndicatorVisible: false
      },
      _updateImmediate: null,
      _currentValues: null,
      currentHeight: null,
      _updatePropsStack: [Function (anonymous)]
    }
</code></pre>
<p>We also have issue with <code> _reactNative.Keyboard.addListener is not a function</code>, it seems it does not work with react-native well.</p>
<h2>Workaround</h2>
<pre><code>// don't know why we need this
jest.unmock('react-native')
</code></pre>
<h2>Question</h2>
<p>Any clue what is going wrong here? Thanks in advance</p>
",https://stackoverflow.com/questions/73769539/react-native-replacing-formik-with-react-hook-form-break-unit-test-with-jest,"['javascript', 'reactjs', 'react-native', 'jestjs', 'react-hook-form']",160,False,1,0
Pylint w0212-Warning while doing unittests,"<p>we often use this double underscore prefix for internal methods of our classes. This usually raises a W0212 during unit-testing, because we call the proctected methods directly e.g. <code>TestClass().__my_private_method()</code>.</p>
<p>I know that in Python there are no private methods. Nevertheless I find this practice of using the underscore prefix good for structural reasons, e.g., it makes it quite obvious to other developers how to use a class.</p>
<p>Now I found this fix for the W0212-Warning from the <a href=""https://vald-phoenix.github.io/pylint-errors/plerr/errors/classes/W0212.html"" rel=""nofollow noreferrer"">phoenix-github-page</a>:</p>
<pre><code>class Foo:
    def __bar(self):
        pass

    def baz(self):
        return self.__bar()


foo = Foo()
foo.baz()
</code></pre>
<p>Based on this you could create a method for unittest without disabling W0212 like this:</p>
<pre><code>class SomeClass:
    &quot;&quot;&quot; some docstring
    &quot;&quot;&quot;
    def __init__(self) -&gt; None:
        self.myattr = 1

    def __my_protected_method(self):
        return self.myattr + 1

    def __another_protected_method(self):
        return self.myattr + 2

    def method_for_unittests(self, method_name):
        if method_name == &quot;my_protected_method&quot;:
            return self.__my_protected_method()
        if method_name == &quot;another_protected_method&quot;:
            return self.__another_protected_method()
        return None
</code></pre>
<p>This seems like a nicer solution than using a seperate <code>.pylintrc</code> (suggested <a href=""https://stackoverflow.com/questions/57602259/disable-pylint-protected-access-just-for-unit-tests"">here</a>). This begs the following questions:</p>
<ol>
<li>Does my solution make sense or should we just stick with <code>#pylint: disable=protected-access</code>?</li>
<li>Or do you maybe have a better solution using a special decorator? I saw something <a href=""https://stackoverflow.com/questions/24833362/pylint-warning-w0212-with-properties-accessing-a-protected-member-how-to-avoi"">here</a>, which made me curious. I have little experience writing decorators, therefore the comparatively naive question.</li>
</ol>
",https://stackoverflow.com/questions/71725271/pylint-w0212-warning-while-doing-unittests,"['python', 'private', 'pylint']",413,True,1,1
Python testing - multiple `tox` environments with parallel runs and coverage reporting,"<p>I'm having a hard time figuring out a configuration for Python unit testing that combines:</p>
<ol>
<li>Multiple environments (specifying e.g. versions of python or dependency packages) given as <code>tox</code> environments</li>
<li>Parallel running of the <code>tox</code> environments, for speed (some things being tested take a while to run)</li>
<li>Reporting of test coverage</li>
</ol>
<p>I've tried using a <code>tox.ini</code> file like the following (and then running it with <code>python -m tox --parallel=auto</code>), but I can't figure out how to do the <code>combine</code> step at the end, rather than in each environment:</p>
<pre><code>[tox]
envlist = py{38,39}-more_itertools{812,813,814}

[testenv]
deps = pytest
       coverage
       more_itertools812: more_itertools&gt;=8.12,&lt;8.13
       more_itertools813: more_itertools&gt;=8.13,&lt;8.14
       more_itertools814: more_itertools&gt;=8.14,&lt;8.15
commands = python -m coverage run --parallel -m pytest
           python -m coverage combine
           python -m coverage xml
           python -m coverage html
</code></pre>
<p>If I don't use <code>--parallel</code> inside the <code>commands</code> section, all the environments try to write to the same <code>.coverage</code> file, and they hit various race conditions, causing death. (I opened <a href=""https://github.com/nedbat/coveragepy/issues/1514"" rel=""nofollow noreferrer"">a ticket for this</a>.)</p>
<p>I'm trying to avoid a solution that requires post-processing after running <code>tox</code>, if possible.  Not sure if that's possible.</p>
<p>I need to support both <code>pytest</code> and <code>unittest</code> based test suites, FWIW.  Not sure if that rules out using <a href=""https://pytest-cov.readthedocs.io/"" rel=""nofollow noreferrer""><code>pytest-cov</code></a> or not, but I've also seen the above race condition happening if I use <code>commands = python -m pytest --cov=.</code> in my <code>tox.ini</code>.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/74945783/python-testing-multiple-tox-environments-with-parallel-runs-and-coverage-rep,"['python', 'unit-testing', 'parallel-processing', 'coverage.py']",237,False,1,1
Xcode UI test plans : show attachment previews in test results,"<p>In the Apple <a href=""https://developer.apple.com/xcode-cloud/"" rel=""nofollow noreferrer"">overview page of Xcode Cloud</a>, I can see this image of the result of a test executed with Xcode Cloud:</p>
<p><a href=""https://i.stack.imgur.com/fOMR3.jpg"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/fOMR3.jpg"" alt=""Xcode cloud with full attachements preview"" /></a></p>
<p>The attachements of the test are displayed as a full image. But on my side, the attachements are displayed inline and not as a <strong>full image preview</strong>. I can still QuickLook them but they are always collapsed.</p>
<p><a href=""https://i.stack.imgur.com/q11iX.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/q11iX.png"" alt=""My Xcode with inline attachements"" /></a></p>
<p>I created an extensions of <code>XCTestCase</code> to easily generate screenshot attachements for my UI tests:</p>
<pre class=""lang-swift prettyprint-override""><code>extension XCTestCase {
    /// Take a screenshot of a given app and add it to the test attachements.
    /// - Parameters:
    ///   - app: The app to take a screenshot of.
    ///   - name: The name of the screenshot.
    func takeScreenshot(of app: XCUIApplication, named name: String) {
        let screenshot = app.windows.firstMatch.screenshot()
        let attachment = XCTAttachment(screenshot: screenshot)
        #if os(iOS)
        attachment.name = &quot;Screenshot-\(name)-\(UIDevice.current.name).png&quot;
        #else
        attachment.name = &quot;Screenshot-\(name)-macOS.png&quot;
        #endif
        attachment.lifetime = .keepAlways
        add(attachment)
    }
}
</code></pre>
<p>And use it like so on my UI Test:</p>
<pre class=""lang-swift prettyprint-override""><code>final class LocalizationTests: XCTestCase {
    override class var runsForEachTargetApplicationUIConfiguration: Bool {
        true
    }

    func testLaunchScreen() throws {
        let app = XCUIApplication()
        app.launch()

        takeScreenshot(of: app, named: &quot;Launch&quot;)
    }
}
</code></pre>
<p>Here is also my test plan configuration:</p>
<p><a href=""https://i.stack.imgur.com/Z29Tn.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Z29Tn.png"" alt=""My test plan configuration"" /></a></p>
<p>There are a lot of WWDC sessions about Xcode Cloud and unit testing, but I couldn't find one of them that talks about this feature. Maybe I'm missing something really obvious, but this feature would be a super nice addition to my workflow. I'm using Xcode 14.1 (14B47b) and macOS Ventura 13.0.1 (22A400).</p>
<p>Does anyone know if it is possible to replicate the behavior showed on the Apple website? Thanks in advance for your help.</p>
",https://stackoverflow.com/questions/74432314/xcode-ui-test-plans-show-attachment-previews-in-test-results,"['swift', 'xcode', 'xctest', 'xcode-ui-testing', 'xcode-cloud']",330,True,1,1
How to unit test a class that uses inversifyjs to inject dependencies,"<p>I have inherited a react project that uses inversify ioc.  It all works well but I'm having trouble writing unit tests.  I'm sure my issue is caused by a problem in my configuration somewhere.</p>
<p>I'm getting this error when running the tests...</p>
<p>C:\xxx\src\app\services\auth\JWTAuthentication.service.ts:31
constructor(@(0, _inversify.inject)(_ICookieStorage.ICookieStorageService$)                     ^
SyntaxError: Invalid or unexpected token</p>
<p>So it seems to me that it can't resolve the @inject in my constructor...</p>
<pre><code>constructor(@inject(ICookieStorageService$) cookieStorageService: ICookieStorageService) {
    ...code here
  }
</code></pre>
<p>In the root index.ts of my application, I wrap the application in</p>
<pre><code>import { Provider } from 'inversify-react';
&lt;Provider container={container}&gt;
    ...the app
&lt;/Provider&gt;
</code></pre>
<p>and container is defined in inversify.config.ts.</p>
<p>Obviously this doesn't get wired up when running tests.  I'm not sure how to fix my issue.  There is almost zero information out there on unit testing with inversify.</p>
<p>I've tried putting import 'reflect-metadata'; everywhere.  That didn't help.  Also, I don't use babel.</p>
<p>I must need to define a mock for the dependency.  But no matter what I try, it doesn't seem to understand the @inject bit.</p>
<p>Please help if you can.</p>
",https://stackoverflow.com/questions/72179062/how-to-unit-test-a-class-that-uses-inversifyjs-to-inject-dependencies,['inversifyjs'],300,False,1,1
Problems with mockito. Unit test,"<p>I'm unit testing with mockito and I get nulls in the repository, after doing a .save().</p>
<p>My test:</p>
<pre><code>....
    @BeforeEach
    void setUp() {
        // USUARIO
        user = new User();
        user.setUserName(&quot;Username A&quot;);
        user.setPassword(&quot;Pass A&quot;);
        user.setConfirmPassword(&quot;Pass A&quot;);
    }


    @MockitoSettings(strictness = Strictness.LENIENT)
    @Test
    void createUserNoExistValidConfirmation() throws Exception {
        User userToPassParam = new User();
        userToPassParam.setUserName(&quot;Username_Aa&quot;);
        userToPassParam.setPassword(&quot;Pass A&quot;);
        userToPassParam.setConfirmPassword(&quot;Pass A&quot;);
        // checkUserNameAvailable
        Mockito.when(userDaoRepository.findByUserName(userToPassParam.getUserName())).thenReturn(Optional.ofNullable(user));
        // -- checkPasswordValid
        Mockito.when(bCryptPasswordEncoder.encode(userToPassParam.getPassword())).thenReturn(user.getPassword());
        // -- save
        Mockito.when(userDaoRepository.save(userToPassParam)).thenReturn(user);

        User userToCallServiceImpl = new User();
        userToCallServiceImpl.setUserName(&quot;Username A&quot;);
        userToCallServiceImpl.setPassword(&quot;Pass A&quot;);
        userToCallServiceImpl.setConfirmPassword(&quot;Pass A&quot;);
        User user = userServiceImpl.createUser(userToCallServiceImpl); // HERE GET NULLS

        System.out.println(&quot;User: &quot; + user);
        System.out.println(&quot;this.user: &quot; + this.user);
        Assertions.assertEquals(user.getUserName(), this.user.getUserName());
    }
.....
</code></pre>
<p>value of userToPassParam passed parameter:  <a href=""https://i.stack.imgur.com/JfiNf.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JfiNf.png"" alt=""enter image description here"" /></a>
the expected object
<a href=""https://i.stack.imgur.com/pGu20.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/pGu20.png"" alt=""enter image description here"" /></a></p>
<p>I only treat 3 values of the object, &quot;userName, password, confirmPassword&quot; the other values do not matter to me.</p>
<p>When I try to pass the test:  userServiceImpl</p>
<pre><code>@Override
public User createUser(User user) throws Exception {
    if (checkUserNameAvailable(user) &amp;&amp; checkPasswordValid(user)) {
        // cogemos el estado de la DB para más adelante: user = save()
        String encodePassword = bCryptPasswordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        user = userDaoRepository.save(user);
    }
    return user;
}
</code></pre>
<p><a href=""https://i.stack.imgur.com/tcWWx.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/tcWWx.png"" alt=""enter image description here"" /></a></p>
<p>The user has a &quot;before save&quot; value. Right when it saves I get a null.
<a href=""https://i.stack.imgur.com/FAZZm.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/FAZZm.png"" alt=""enter image description here"" /></a></p>
<p>After repository.save(object) the object returned by the .save &quot;mock object&quot; is null.</p>
<p>I don't understand very well why the .save returns null, when in the &quot;when&quot; I specify what to return.
It's as if mockito didn't intercept the .save() to return the object.</p>
<p>Note: I use Junit 5, Mockito 4.6.1</p>
<p>I am expecting the .save() to return the &quot;user&quot; as I specified in my @BeforeEach void setUp() {...}.
Mockito.when(userDaoRepository.save(userToPassParam)).thenReturn(user);
That is, the intercept of the .save() so that it returns the object.</p>
",https://stackoverflow.com/questions/74317529/problems-with-mockito-unit-test,"['spring-boot', 'junit', 'mockito', 'spring-test']",55,True,1,1
Logging AssertionError exceptions &amp; pytest unit testing in Python,"<p>I've been implementing logging to my python app, and I've stumbled upon what looks like a contradiction between unit testing &amp; logging. I'm looking for the best practice here, thanks in advance for your help !</p>
<pre class=""lang-py prettyprint-override""><code># app.py
def my_function(foo: int) -&gt; int:
   assert isinstance(foo, (int))

   return foo * 2
</code></pre>
<p>The associated unit test</p>
<pre class=""lang-py prettyprint-override""><code># test_my_function.py
import pytest
from app import my_function

def test_wrong_type_input():
    test_input = '3'

    with pytest.raises(AssertionError):
        my_function(test_input)
</code></pre>
<p>The two files above work OK, and the unit test campaign ends with a successful status.
However, I'm implementing logging to my app and I noticed that if I do pass an object other than a <code>int</code> to my function, <strong>the AssertionError is not passed to the logger</strong>, and this would lead to a more complicated root cause analysis in production.</p>
<p>Looking for answers on this, the <code>logging</code> documentation mentions capturing exception with a <code>try/except</code> statement. The new <code>app.py</code> would be the following :</p>
<pre class=""lang-py prettyprint-override""><code># app.py
import logging

def my_function(foo: int) -&gt; int:
    try:
        assert isinstance(foo, (int))
    except:
        logging.exception(&quot;Input `foo` did not meet the function's requirements&quot;)

    return foo * 2
</code></pre>
<p>However, now my unit test fails because the AssertionError is captured by the <code>try/except</code>.</p>
<p>What's the best practice here ?
How can I get both :</p>
<ul>
<li>getting the full traceback in logs when experiencing an Exception</li>
<li>while still be able to use the <code>pytest.raises(AssertionError)</code> logic ?</li>
</ul>
<p>Thanks in advance !</p>
",https://stackoverflow.com/questions/71102030/logging-assertionerror-exceptions-pytest-unit-testing-in-python,"['python', 'unit-testing', 'logging', 'pytest', 'assertion']",996,False,0,1
Pass AWS SQSClient mockClient to a typescript class,"<p>I'm trying to unit test some code where the class has a constructor taking in an SQSClient object used to get messages off an sqs queue! Surprise! Very simple stuff. So I want to mock the client so I can write some unit tests around the code without actually calling the queue. I'm trying to model my code from examples here:</p>
<p><a href=""https://www.npmjs.com/package/aws-sdk-client-mock"" rel=""nofollow noreferrer"">https://www.npmjs.com/package/aws-sdk-client-mock</a></p>
<p>In my unit test I simply create the mock client and try to pass it into my class:</p>
<pre><code>const sqsMockClient = mockClient(SQSClient);
sqsMockClient.onAnyCommand().resolves({});

const blClass: BLClass = new BLClass(sqsMockClient);
</code></pre>
<p>This won't run, the test output says the type is <strong>not assignable to parameter of type 'SQSClient'</strong> because it's not an actual SQSClient. If I instantiate an actual SQSClient and pass that it will run but will attempt to actually hit the queue and pull messages down. I'm wanting to build out the mock above to return a static message for unit testing purposes.</p>
<p>Any idea what I could do differently to enable the mock to work?</p>
",https://stackoverflow.com/questions/70948475/pass-aws-sqsclient-mockclient-to-a-typescript-class,"['javascript', 'typescript', 'mocking']",879,False,0,1
Problem mocking delegate with Moq in .Net Core 3.1,"<p>I'm having issues mocking a delegate that returns an <code>IHttpClient</code>. This is by requirement of the client, and I cannot change the implementation.</p>
<p>The code looks something like this:</p>
<p><strong>Delegate</strong>:</p>
<pre><code>namespace Foo.Http
{
    public delegate IHttpClient FooHttpClientProvider(string name);
}
</code></pre>
<p><strong>Test class</strong>:</p>
<pre><code>[SetUp]
public void SetUp()
{
    Mock&lt;FooHttpClientProvider&gt;().Setup(x =&gt; x(&quot;HttpClient&quot;)).Returns(Mock&lt;IHttpClient&gt;().Object);
}
</code></pre>
<p>When I do this, I get the following exception:</p>
<blockquote>
<p>System.InvalidCastException : Unable to cast object of type 'Foo.Http.FooHttpClientProvider' to type 'Moq.IMocked`1[Foo.Http.FooHttpClientProvider]'.</p>
</blockquote>
<p>Any ideas? Is this even possible?</p>
<p><strong>Edit:</strong> Some extra information: the service I need to test gets injected with a FooHttpClientProvider. We use a global Mock with Autofac that registers the services we need. Since I can't pass the provider as a parameter, I can't instantiate a new Mock for FooHttpClientProvider and pass it to my service as a parameter; I need to set it up in the global mock. This further complicates things.</p>
<p>The code of the service looks something like this:</p>
<pre><code>private readonly FooHttpClientProvider _client;

    public FooService(
        FooHttpClientProvider fooClient)
    {
        
        _client = fooClient(&quot;HttpClient&quot;);
    }

public async Task&lt;OutputDto&gt; GetAsync(Request request)
{

        var accessToken = await _AuthService.GetAccessTokenAsync();

        try
        {
            var response =
                await ExecuteGet&lt;OutputDto&gt;(
                $&quot;{FooConfig.BaseUrl}someEntpoint{GetQueryParams(request)}&quot;, accessToken);
           return response;
        }
        catch(Exception ex)
        {
          //Exception handling
        }
}
</code></pre>
<p>The service itself it's working correctly. The problem only arises when trying to mock it for unit testing.</p>
",https://stackoverflow.com/questions/70587012/problem-mocking-delegate-with-moq-in-net-core-3-1,"['c#', '.net', 'unit-testing', 'asp.net-core', 'mocking']",242,True,0,2
Is it possible to enable keychain without code signing?,"<p>I develop a pod library with a demo application. I release it through a CI pipeline with several steps, especially:</p>
<ul>
<li>unit testing and code coverage generation for Sonar</li>
<li>doc generation with Jazzy</li>
<li>demo app deployment to AppCenter.</li>
</ul>
<p>Since the build may take a lot of time, I was doing an optimization by passing to jazzy all the parameters to generate the code coverage with one build (jazzy -x test, etc).</p>
<p>However, the new version uses the keychain SO the unit tests need to use the demo app with the keychain entitlement. They don't pass with jazzy with the error &quot;Missing entitlements&quot;. After digging through it, I found that jazzy forces &quot;CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO&quot; even if different values are passed with -x, due to some issue since XCode 11.</p>
<pre><code>Command line invocation:
    /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -configuration Debug -workspace MYAPP.xcworkspace -scheme MYAPPDemo -sdk iphonesimulator15.5 -destination &quot;name=iPhone 8&quot; -derivedDataPath Build/ -enableCodeCoverage YES test CODE_SIGN_IDENTITY= CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO
</code></pre>
<p>I believe the keychain won't work without signing (it sounds logic) but I am not sure. <strong>Is is true? If yes, is it possible to provide the keychain without signing, or to allow the signing somehow?</strong></p>
",https://stackoverflow.com/questions/73865605/is-it-possible-to-enable-keychain-without-code-signing,"['keychain', 'xcodebuild', 'entitlements', 'jazzy']",53,False,0,0
Maintaining two pyfakefs file systems in pytest with additional files,"<p>I'm trying to write unit tests using <code>pytest</code> for a configuration system that should look in a couple of different places for config files. I can use <code>pyfakefs</code> via the <code>fs</code> plugin to create a fixture that provides a set of files, including a config file in one location, but I'd like to have unit testing that both locations are checked and that the correct one is preferred.</p>
<p>My initial thought was that I could create the first fixture and then add a file:</p>
<pre><code>@pytest.fixture()
def fake_files(fs):
    fs.create_file('/path/to/datafile', contents=&quot;Foo&quot;)
    yield fs

@pytest.fixture()
def user_config(fake_files):
    fake_files.create_file('/path/to/user/config', contents=&quot;Bar&quot;)
    yield fake_files
</code></pre>
<p>The idea behind this is that any test using <code>fake_files</code> would not find the config, but that using <code>user_config</code> would. However, unit tests using that <code>user_config</code> fixture do not find the file. Is this possible?</p>
<p>There is quite a lot more added in the first fixture in reality, so maintaining the two systems as two completely separate fixtures duplicates code and I am unclear if the underlying fs object can even be used in parallel.</p>
",https://stackoverflow.com/questions/71265827/maintaining-two-pyfakefs-file-systems-in-pytest-with-additional-files,"['python', 'pytest', 'pyfakefs']",288,False,0,0
How to use http.ResponseWriter and http.request as argument(Unit Testing) with Golang language,"<p>I just getting started learning Golang and PostgreSQL. For now, I tried to make Unit testing for CreateTodo function.
My CreateTodo function is</p>
<pre><code>func CreateTodo(w http.ResponseWriter, r *http.Request) {
    CreateTodo := &amp;models.Todo{}
    utils.ParseBody(r, CreateTodo)
    CreateTodoList := CreateTodo.CreateTodo()
    res, _ := json.Marshal(CreateTodoList)
    w.WriteHeader(http.StatusOK)
    w.Write(res)
}
</code></pre>
<p>I tried to make Unit Test for this function... So far I wrote some codes like</p>
<pre><code>func TestCreateTodo(t *testing.T) {
    dbData := &amp;models.Todo{
        Title: &quot;test-title-console-check&quot;,
        Description: &quot;test-description-console-check&quot;,
        Condition: true,
    }

    utils.ParseBody(r, dbData) // r should be r *http.Request

    submittedTodo := dbData.CreateTodo()
    res, _ := json.Marshal(submittedTodo)
    r.WriteHeader(http.StatusOK) // r should be r *http.Request
    r.Write(res)

    fmt.Println(&quot;res: &quot;, res)
}
</code></pre>
<p>This is ParseBodu function in utils folder</p>
<pre><code>func ParseBody(r *http.Request, x interface{}) {
    if body, err := ioutil.ReadAll(r.Body); err == nil {
        if err := json.Unmarshal([]byte(body), x); err != nil {
            return
        }
    }
}
</code></pre>
<p>Here, I have a problem with passing net/http(r *http.Request). I am not sure how to pass this function like argument... I tried to receive it in TestCreateTodo(t *testing.T, r *http.Request) but not working what I expected.</p>
<p>Is there any way to unit test for CreateTodo function??</p>
<p>I really appreciate your help!</p>
<p>Edit 1]</p>
<p>I tried to make a global variable</p>
<pre><code>var readData *http.Request
var writeData http.ResponseWriter
</code></pre>
<p>and using it in the function. The reason why I make it global variables is that I usually use it in the funcs like &lt;w http.ResponseWriter, r *http.Request&gt;, so I thought I can use as global vars too.</p>
<p>so I edit my code as</p>
<pre><code>var readData *http.Request
var writeData http.ResponseWriter

func TestCreateTodo(t *testing.T) {
    // w := httptest.NewRecorder()
    dbData := &amp;models.Todo{
        Title: &quot;test-title-console-check&quot;,
        Description: &quot;test-description-console-check&quot;,
        Condition: true,
    }

    utils.ParseBody(readData, dbData)

    submittedTodo := dbData.CreateTodo()
    res, _ := json.Marshal(submittedTodo)
    writeData.WriteHeader(http.StatusOK)
    writeData.Write(res)

    fmt.Println(&quot;res: &quot;, res)
}
</code></pre>
<p>But I got this error
<a href=""https://i.stack.imgur.com/Huuot.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/Huuot.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/71262072/how-to-use-http-responsewriter-and-http-request-as-argumentunit-testing-with-g,"['unit-testing', 'go']",4761,True,0,1
Unit test for persistance layer,"<p>In my company we are starting with unit testing and for what I understand unit test should not use a connection with a real database. My question is, how should I test the persistance layer? like for instance, if a query returns the expected results.</p>
<p>I've read that you can use Mockito to mock the database results, but It doesn't make sense to me in this case.</p>
<pre><code>    @Test
    public void happyPathScenario(){
        Customer sampleCustomer = new Customer();
        sampleCustomer.setFirstName(&quot;Susan&quot;);
        sampleCustomer.setLastName(&quot;Ivanova&quot;);
    
        EntityManager entityManager = mock(EntityManager.class);
        when(entityManager.find(Customer.class,1L)).thenReturn(sampleCustomer);
    
        CustomerReader customerReader = new CustomerReader();
        customerReader.setEntityManager(entityManager);
    
        String fullName = customerReader.findFullName(1L);
        assertEquals(&quot;Susan Ivanova&quot;,fullName);
    }
</code></pre>
<p>It would be impossible for this test to fail. So, how can I apply this to a real world case? I have a function that queries actual customers and shows them to the user on a table, this happens on a JSF Bean (which is the responsible for the presentation layer). If a use mockito to mock the results of the query, theres nothing left to test (maybe the table render or some other thing?).</p>
<p>For the persistance layer, should I apply integration test or is there a &quot;correct&quot; way to use unit test?</p>
",https://stackoverflow.com/questions/72716333/unit-test-for-persistance-layer,"['unit-testing', 'junit', 'mocking', 'mockito', 'integration-testing']",17,False,0,0
Node module type declarations clash in Typescript,"<p>I'm trying to setup unit testing and e2e testing for my Vue 3 project. For Unit test I use Jest and for e2e test I use Nightwatch.  I'm confronting this below problem after installed both dependencies:
&quot;
node_modules/@types/jest/index.d.ts:45:15 - error TS2451: Cannot redeclare block-scoped variable 'expect'.</p>
<p>45 declare const expect: jest.Expect;
~~~~~~</p>
<p>node_modules/@types/nightwatch/globals.d.ts:11:11
11     const expect: typeof chaiExpect;
~~~~~~
'expect' was also declared here.</p>
<p>node_modules/@types/nightwatch/globals.d.ts:11:11 - error TS2451: Cannot redeclare block-scoped variable 'expect'.</p>
<p>11     const expect: typeof chaiExpect;
~~~~~~</p>
<p>node_modules/@types/jest/index.d.ts:45:15
45 declare const expect: jest.Expect;
~~~~~~
'expect' was also declared here.</p>
<p>Found 2 errors in 2 files.</p>
<p>Errors  Files
1  node_modules/@types/jest/index.d.ts:45
1  node_modules/@types/nightwatch/globals.d.ts:11&quot;</p>
<p>So far I have tried this solution to override the node module's type definition: <a href=""https://medium.com/@elenasufieva/handling-type-declarations-clash-in-typescript-b05b10723f47"" rel=""nofollow noreferrer"">https://medium.com/@elenasufieva/handling-type-declarations-clash-in-typescript-b05b10723f47</a></p>
<p>but it didn't work.</p>
",https://stackoverflow.com/questions/74150769/node-module-type-declarations-clash-in-typescript,"['typescript', 'vue.js', 'unit-testing', 'jestjs', 'nightwatch']",21,False,0,0
"How to test a function passed as parameter (validate, filter) to inquirer.prompt in Jest Unit Testing?","<p>I'm trying to mock method inquirer.prompt in a unit testing, which has several questions (in the example I put only two examples).</p>
<pre><code>return prompt([
{
    type: 'input',
    name: 'name1',
    message: 'Question 1?',
    filter: (fieldValue: string) =&gt; fieldValue.trim(),
    validate: (fieldValue: string) =&gt;   showValidationResults(fieldValue, validateFieldIsNotEmpty),
},
{
    type: 'input',
    name: 'name2',
    message: 'Question 2?',
    validate: (fieldValue: string) =&gt;   showValidationResults(fieldValue, validateFieldIsNotEmpty),
},
...
]);
    
</code></pre>
<p>I need to reach a certain unit test coverage so I want to check that the filter and validate functions are being correctly called.</p>
<p>I am only finding solutions that suggest to extract those functions to their own method and then call them directly from the unit test, but this is not a good solution for me because the unit test doesn't still know if the lines of filter and validate are being called,  makes the code less clean.</p>
<p>Also, I would prefer not to call private methods directly from the unit test instead of calling the main method of the class.</p>
<p>Is there a way that I could mock prompt so I can inject the answers to the questions and then check that the filter and validate portions are executed?</p>
",https://stackoverflow.com/questions/74879707/how-to-test-a-function-passed-as-parameter-validate-filter-to-inquirer-prompt,"['typescript', 'unit-testing', 'jestjs', 'inquirerjs']",265,True,0,1
Unit testing that a method was called in another object&#39;s method in Python,"<p>Most of my unit testing experience is with Java and now I'm turning to Python. I need to test whether a method (from object B) gets called inside another method (in object A).</p>
<p>In Java the test method would have to pass a mock or spy version of B to A's constructor to be used when the B method is invoked. <strong>Do I need to do the same in Python? Or is there a simpler way?</strong> (I raise the possibility of the latter, because it seems, from what little I know, that Python is relatively relaxed about enforcing isolation between different components.)</p>
<p>Below is how I do this the &quot;Java way.&quot; There are two Python files under test (for objects A and B) and a test program. Notice that object A's constructor had to be modified to accommodate testing.</p>
<h2>obj_a.py</h2>
<pre><code>from obj_b import *

class ObjA:

    def __init__(self, *args):
        if len(args) &gt; 0:
            self.objb = args[0] # for testing
            return
        self.objb = ObjB()

    def methodCallsB(self, x, y):
        return self.objb.add(x, y)
</code></pre>
<h2>obj_b.py</h2>
<pre><code>class ObjB:

    def add(self, x, y):
        return x + y
</code></pre>
<h2>test.py</h2>
<pre><code>import unittest
from unittest.mock import patch, Mock
from obj_a import *
from obj_b import *

class TTest(unittest.TestCase):
    @patch(&quot;obj_b.ObjB&quot;)
    def test_shouldCallBThroughA(self, mockB):
        # configure mock
        mockB.add = Mock(return_value=137)
        obja = ObjA(mockB)

        # invoke test method
        res = obja.methodCallsB(4, 7)
        print(&quot;result: &quot; + str(res))

        # assess results
        self.assertEqual(137, res)
        mockB.add.assert_called_once()
        args = mockB.add.call_args[0] # Python 3.7
        print(&quot;args: &quot; + str(args))
        self.assertEqual((4, 7), args)

if __name__ =='__main__':
    unittest.main()

</code></pre>
<p><strong>Again, is there a simpler way to test that ObjB::add is called from ObjA?</strong></p>
",https://stackoverflow.com/questions/74306497/unit-testing-that-a-method-was-called-in-another-objects-method-in-python,"['python', 'unit-testing', 'mocking', 'python-unittest', 'spying']",336,True,0,1
Unit Testing Replace remote API Server with predefined response,"<p>So, I have a server running FastAPI which will make a API call to a remote API upon request.
I am developping unit-testing for this application, but here comes the question:
Can I, for the purpose of the test, replace a legit remote API server response by a predefined response ?</p>
<p>Example of the tests runned:</p>
<pre class=""lang-py prettyprint-override""><code>from fastapi.testclient import TestClient
from web_api import app

client = TestClient(app)


def test_get_root():
    response = client.get('/')
    assert response.status_code == 200
    assert response.json() == {&quot;running&quot;: True}

</code></pre>
<p>And the my server</p>
<pre class=""lang-py prettyprint-override""><code>from fastapi import FastAPI

app = FastAPI()

@app.get(&quot;/&quot;)
def home():
    return {&quot;running&quot;: True}
</code></pre>
<p>This is a simple example, but on other endpoints of my API I would call an external remote API</p>
<pre class=""lang-py prettyprint-override""><code>  def call_api(self, endpoint:str, params:dict):
        url = self.BASEURL + urllib.parse.quote(endpoint)
        try:
            response = requests.get(url, params=params)
            response.raise_for_status()
        except requests.exceptions.HTTPError as error:
            print(error)
        return response
</code></pre>
<p>Because I want to test the response of MY API, I would like to replace the remote API with a predefined response.</p>
<p>Also, one user request can end-up in multiple background API requests with transformed pieces of data.</p>
<h3>Edit</h3>
<p>Here are some more details on the structure of the application:</p>
<pre><code>@app.get(&quot;/stuff/.......&quot;,  
         # lots of params
        )
def get_stuff_from_things(stuff:list, params):
    api = API(api_key=...)
    # Do some stuff with the params
    things = generate_things_list(params)
    api.search_things(params)
    # Check the result
    # do some other stuff
    return some_response


</code></pre>
<pre><code>class API:
    BASE_URL = 'https://api.example.com/'

    def search_things(self, params):
        # Do some stuff
        # like putting stuff in the params
        for s in stuff:
            s.update(self.get_thing(params)) # -&gt; get_thing()
        # Do some more stuff
        return stuff

    # get_thing &lt;- search_things
    def get_thing(self, params...):
        #  Some stuff
        results = self.call_api('something', params) # -&gt; call_api()
        json = results.json()
        #  Some more stuff
        things = []
        for thing in json['things']:
            t = Thing(thing)
            things.append(t)
        return things

    # call_api &lt;- get_thing
    def call_api(self, endpoint:str, params:dict):
        url = self.BASEURL + urllib.parse.quote(endpoint)
        try:
            response = requests.get(url, params=params)
            response.raise_for_status()
        except requests.exceptions.HTTPError as error:
            print(error)
        self.last_response = response
        return response


</code></pre>
<p><em>Nb. That is pseudo-code, I simplified the functions by removing the parameters, etc.</em></p>
<p>I hope it is clear, thanks for your help.</p>
",https://stackoverflow.com/questions/72958118/unit-testing-replace-remote-api-server-with-predefined-response,"['python', 'pytest', 'fastapi']",226,True,0,2
Redis Connection Failed,"<p>So I have a redis code like this</p>
<pre><code> public class RedisConnectorHelper
    {
        static RedisConnectorHelper()
        {
            RedisConnectorHelper.lazyConnection = new Lazy&lt;ConnectionMultiplexer&gt;(() =&gt;
             {
 
                 string redisServer = WebConfigurationManager.AppSettings[&quot;RedisServer&quot;];
                 if (redisServer == null)
                 {
                     redisServer = &quot;localhost&quot;;
                 }
                 return ConnectionMultiplexer.Connect(redisServer+ &quot;,allowAdmin=true,abortConnect=false,ssl=True,&quot;);
             }, System.Threading.LazyThreadSafetyMode.PublicationOnly);
        }
</code></pre>
<p>Here is the part where the caching has been implemented,</p>
<pre><code>      public List&lt;Division&gt; GetDivisons()
        {
                  if (CacheManager.Instance.IsDataSaved(CacheKey.Divisions))
                  {
                      return CacheManager.Instance.GetData&lt;List&lt;Division&gt;&gt;(CacheKey.Divisions);
                  }

                  else
                  {
                      CacheManager.Instance.SaveData&lt;List&lt;Division&gt;&gt;(CacheKey.Divisions, _notebookEntities.Divisions.ToList(), 30, ExpiryTimeUnit.Minutes);
                      return _notebookEntities.Divisions.ToList();
              } 
        }
</code></pre>
<p>And the unit testing part,</p>
<pre><code>
   [Test]
        public void GetDivisons()
        {
            var result = _notebookService.GetDivisons();
            Assert.NotNull(result);
        }
</code></pre>
<p>but as soon as I uncomment the unit test which is shown below,the exception (shown below) occurs and the azure pipeline build fails, but passes as soon as I comment the unit test.</p>
<p>Here is the Exception,</p>
<p><em>StackExchange.Redis.RedisConnectionException : It was not possible to connect to the redis server(s). Error connecting right now. To allow this multiplexer to continue retrying until it's able to connect, use abortConnect=false in your connection string or AbortOnConnectFail=false; in your code.   at StackExchange.Redis.ConnectionMultiplexer.ConnectImpl(ConfigurationOptions configuration, TextWriter log, Nullable`1 serverType, EndPointCollection endpoints)
at StackExchange.Redis.ConnectionMultiplexer.Connect(ConfigurationOptions configuration, TextWriter log)
at StackExchange.Redis.ConnectionMultiplexer.Connect(String configuration, TextWriter log)</em></p>
<p>Is there any way to figure out what is the cause of it. i have tried with <em>abortConnect=true &amp; false</em> and also with ssl=true but nothing works, as soon as I set to <em>abortConnect= true</em> I get a <em>RedisTimeOutException</em></p>
",https://stackoverflow.com/questions/74850400/redis-connection-failed,"['asp.net-mvc', 'redis', 'nunit', 'stackexchange.redis', 'azure-redis-cache']",137,False,0,0
How to chain rxjs observables,"<p>I'm currently building an Angular header component which makes use of <a href=""https://material.angular.io/cdk/layout/api#BreakpointObserver"" rel=""nofollow noreferrer"">the CDK's Breakpoint Observer</a> to return a string of &quot;mobile&quot;, &quot;desktop&quot;, or &quot;tablet&quot; according to which breakpoint is currently active.</p>
<p>I then have a service which uses an RXJS behaviour subject to keep track of which NavLink Id (string value) the user clicked on last.</p>
<p>I'd like to use both the active breakpoint and linkID returned by the service in a single piece of logic like this:</p>
<p><div class=""snippet"" data-lang=""js"" data-hide=""false"" data-console=""true"" data-babel=""false"">
<div class=""snippet-code"">
<pre class=""snippet-code-js lang-js prettyprint-override""><code>    this.breakpoints$ = this.breakpointObserver
    .observe([Breakpoint.SmallAndBelow, Breakpoint.Medium, Breakpoint.Large])
    .subscribe(({ breakpoints }) =&gt; {
      this.activeBreakpoint =
        breakpoints[Breakpoint.Large] === true
          ? 'desktop'
          : breakpoints[Breakpoint.Medium] === true
          ? 'tablet'
          : 'mobile';
    });
    
    this.$headerServiceSub = this.headerService.selectedLinkId.subscribe((link) =&gt; {
      if (this.headerService.previousSelectedLinkId === this.hostAttrId &amp;&amp; !link &amp;&amp; this.activeBreakpoint === 'mobile') {
        setTimeout(() =&gt; {
          this.elRef.nativeElement.focus();
        }, 100);
      }
      this.selectedLink = link;
    });</code></pre>
</div>
</div>
</p>
<p>This code does work as expected in the browser however when unit testing Jest reports <strong>&quot;Test suite failed to run
TypeError: Converting circular structure to JSON&quot;</strong></p>
<p>I believe this is because both the breakpoint observer and the BehaviorSubject used to store the linkID are asynchronous so <code>this.activeBreakpoint</code> will not necessarily have a value when the <code>this.headerService.selectedLinkId.subscribe</code> method is run. If this is the case is there a way I can chain the two methods to ensure <code>this.activeBreakpoint</code> always has a value?</p>
",https://stackoverflow.com/questions/73281238/how-to-chain-rxjs-observables,"['angular', 'rxjs', 'rxjs-observables']",146,False,0,1
Is there a common pattern to instantiate a library class as a singleton and have the library able to access that instance internally?,"<p>Say I have a library project which provides a class <code>MyService</code>.</p>
<p>I'd like clients to be able to instantiate MyService as a singleton and at the same time, I'd like the library to be able to access that singleton internally.</p>
<p>Now I can do the standard <code>MyService.getInstance()</code> sort of thing, but that doesn't lead to a very testable code if my library has <code>MyService.getInstance()</code> calls all over the place.</p>
<p>Perhaps any classes in the library that need an instance of MyService can take in MyService as a constructor parameter:</p>
<pre><code>class MyTestableClass(val myService: MyService) {
    // Now this class can be unit tested with a mock/fake MyService
}
</code></pre>
<p>But at some higher level in the library I'm still going to have to pass <code>MyService.getInstance()</code> to this class.</p>
<p>Is there a standard pattern to accomplish this? Basically I want the client to be able to instantiate MyService as a singleton and also have the library able to access that instance internally, while having the ability to swap out the singleton instance with a mock/fake for unit testing.</p>
",https://stackoverflow.com/questions/72580216/is-there-a-common-pattern-to-instantiate-a-library-class-as-a-singleton-and-have,"['java', 'kotlin', 'design-patterns']",98,False,0,1
Using in memory context in service layer unit tests,"<p>I have a service called UserService (this is obviously made up)</p>
<pre><code>private readonly IAuthenticationService _authenticationService;
private readonly IUserRepository _userRepository;

public UserService(
    IUserRepository userRepository,
    IAuthenticationService authenticationService)
{
    _userRepository = userRepository;
    _authenticationService = authenticationService;
}

public async Task UpdateUser(UserDTO userDTO)
{
    var authenticationDetails = await _authenticationService.Authenticate(userDTO.Id);

    if (authenticationDetails.Success)
    {
        var user = _userRepository.GetUser(userDTO.Id);
        user.Update(userDTO);

        _userRepository.SaveChanges();
    }
}
</code></pre>
<p>The IUserRepository implementation looks like this:</p>
<pre><code>public UserRepository : Repository
{
    private readonly UserContext _userContext;

    public UserRepository(UserContext context) : base(context)
    {
        _userContext = context;
    }

    ...
}
</code></pre>
<p>What I want to do, is have two service tests like these:<br>
<strong>UpdateUser_WithSuccessfulAuthentication_UpdatesUser</strong><br>
<strong>UpdateUser_WithFailedAuthentication_DoesNothing</strong></p>
<p>If following correct unit testing principles, I want to only consider the output (in this case, check if the user has been updated).
This way I can test the business logic inside the service method UpdateUser (which in this case is that single condition that checks if the user is authenticated. In reality there might be some more complex logic).</p>
<p><strong>Currently I have considered one option for this, but haven't been able to make it work:</strong></p>
<p>I can mock the IAuthenticationService using Moq, and have an in-memory-database context that would be used for the IUserRepository. So the first unit test would look something like this:</p>
<pre><code>public void UpdateUser_WithSuccessfulAuthentication_UpdatesUser()
{
    // Arrange
    var authenticationServiceMock = new Mock&lt;IAuthenticationService&gt;(); 
    var contextOptions = new DbContextOptionsBuilder&lt;UserContext&gt;()
          .UseInMemoryDatabase(&quot;Db&quot;)
          .Options;

    using var context = new UserContext(contextOptions);
    var userRepository = new UserRepository(context);

    var userService = new UserService(userRepository, authenticationServiceMock.Object);
    
    ... setup the authentication service methods, in this case Authenticate

    var userDTOToCreate = GetUserTestDoubleToCreate();
    var userDTOToUpdate = GetUserTestDoubleToUpdate();

    userRepository.Insert(userDTOToCreate);
    
    // Act
    userService.UpdateUser(userDTOToUpdate);

    // Assert
    ... assert user was updated etc.

}
</code></pre>
<p>The problem with this is I cannot use the context inside this service since it has already been disposed.</p>
<p>I have no other ideas on how to do this.</p>
",https://stackoverflow.com/questions/74476482/using-in-memory-context-in-service-layer-unit-tests,"['c#', 'asp.net', '.net', 'unit-testing', 'moq']",104,False,0,0
error: cannot declare pointer to ‘void’ member,"<p>I have the following scenario: I have a third party library and a header associated with it, that I'm using in my project. I completed my project and now I'm unit testing my code and I want to use a stub library, created by myself, for the third party library.</p>
<p>The header for the third party library contains structures that looks like this:</p>
<pre><code>typedef struct{
    int (*init)(int * var);
    void (*close)(void);
} AInterface
</code></pre>
<p>To create my stub version, I created a .cpp file, in which I include the header, and started to implement it like this:</p>
<pre><code>int AInterface::*init(int* var)
{
    return 0;
}

void AInterface::*close(void)
{}
</code></pre>
<p>But when I compile my code I get the following error: &quot;stub.cpp:76:33: error: cannot declare pointer to ‘void’ member <br>
void AInterface::*close(void)&quot;</p>
<p>I have searched the internet but with no success.</p>
<p>My questions are:</p>
<ul>
<li>what I am doing wrong here?</li>
<li>is there another way to implement the stub?</li>
</ul>
<p>I have also tried to implement the stub like this:</p>
<pre><code>int initAInterface(int * var);

int (AInterface::*init)(int * var) = &amp;initAInterface;

int initAInterface(int* var)
{
    return 0;
}
</code></pre>
<p>But I get the following error:</p>
<pre><code>error: cannot convert ‘int (*)(int*)’ to ‘int (AInterface::*)(int*)’ in initialization
 int (AInterface::*init)(int* var) = &amp;initAInterface;
</code></pre>
<p>Also I have no main in my stub .cpp file.</p>
",https://stackoverflow.com/questions/72768785/error-cannot-declare-pointer-to-void-member,['c++'],122,True,0,1
How to get the duration time of each test cases in Cmocka?,"<p>I was learning how to work with <a href=""https://cmocka.org/"" rel=""nofollow noreferrer"">CMocka</a> unit-testing framework in my C project.</p>
<p>So far everything goes well, and I can also generate a HTML report from CMocka's XML output by <a href=""https://github.com/inorton/junit2html"" rel=""nofollow noreferrer"">junit2html</a>. When I read about what's in the report, I saw that there's an item called &quot;Duration&quot; which was always being zero in each of my test cases. After checking the CMocka XML output file and its source code, I assumed the function of calculating the duration time is not enabled.</p>
<p>In the XML outputfile, every test case showed that <code>&lt;testcase name=&quot;test_MyFunctionName&quot; time=&quot;0.000&quot; &gt;</code>.</p>
<p>In the cmocka.c, I found <code>HAVE_STRUCT_TIMESPEC</code> wasn't defined. But even I used <code>-DHAVE_STRUCT_TIMESPEC</code> while compiling, it still not worked.</p>
<p>Besides I found a function called <code>clock_gettime</code> (please refer to the code below) and didn't find its definition. Maybe this is the reason why cmocka couldn't calculate the duration time? but how can I use this function?</p>
<pre><code>#ifdef HAVE_CLOCK_REALTIME
#define CMOCKA_CLOCK_GETTIME(clock_id, ts) clock_gettime((clock_id), (ts))
#else
#define CMOCKA_CLOCK_GETTIME(clock_id, ts)
#endif
</code></pre>
<p>Here's my environment and the screenshot of my html test report. Thanks for you time!</p>
<ul>
<li>Windows 10</li>
<li>gcc 9.2.0</li>
<li>cmocka 1.1.5</li>
</ul>
<p><a href=""https://i.stack.imgur.com/I9zZF.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/I9zZF.png"" alt=""enter image description here"" /></a></p>
",https://stackoverflow.com/questions/73217121/how-to-get-the-duration-time-of-each-test-cases-in-cmocka,"['c', 'xml', 'unit-testing', 'cmocka']",110,False,0,0
Jest SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse,"<p>I am unit testing a React/Typescript component with Jest and React Testing Library and running into this error: <code>SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse</code>.</p>
<p>I understand that you get this error when you try to do <code>JSON.parse(undefined)</code>. I am trying to figure out why this is happening in my test.</p>
<p>The test routes to the <code>/new</code> route where the <code>NewPage</code> component is rendered then the error is thrown when it hits this line <code>const state = JSON.parse(JSON.stringify(location.state))</code> (see component below).</p>
<p>It seems like this has to be mocked somehow in Jest but not sure how to go about doing this.</p>
<p><code>test</code></p>
<pre><code>test('AppRouter should navigate to /new', () =&gt; {
    window.history.pushState({}, '', '/new')
    render(
        &lt;BrowserRouter&gt;
            &lt;AppRouter /&gt;
        &lt;/BrowserRouter&gt;
    )
})
</code></pre>
<p>Error:
<a href=""https://i.stack.imgur.com/hlNs3.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/hlNs3.png"" alt=""error"" /></a></p>
<p>Component that is throwing the error:</p>
<pre><code>import { useEffect, useContext } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import { observer } from 'mobx-react-lite'

import UserContext from '../../context/User'
import PostContext from '../../context/Post'
import WritingField from '../../components/writingField/writingField'
import BasicPage from '../basicPage/basicPage'
import { DataType } from '../../constants'

const NewPage = () =&gt; {
    const history = useHistory()
    const location = useLocation&lt;Location&gt;()
    const state = JSON.parse(JSON.stringify(location.state))
    const isConfirmed = state.isConfirmed
    const userContext = useContext(UserContext)
    const postContext = useContext(PostContext)

    useEffect(() =&gt; {
        console.log('Is this new page being confirmd? ' + isConfirmed)
    }, [])

    const preventPropagation = (event: any) =&gt; {
        event.stopPropagation()
    }

    const submit = async (
        title: string,
        content: string,
        epkNonce: number,
        reputation: number
    ) =&gt; {
        if (!userContext.userState) {
            throw new Error('Should not be able to create post without login')
        }
        postContext.publishPost(title, content, epkNonce, reputation)
        history.push('/')
    }

    return (
        &lt;BasicPage&gt;
            &lt;h3&gt;Create post&lt;/h3&gt;
            &lt;WritingField
                type={DataType.Post}
                submit={submit}
                submitBtnName=&quot;Post - 5 points&quot;
                onClick={preventPropagation}
            /&gt;
        &lt;/BasicPage&gt;
    )
}

export default observer(NewPage)

</code></pre>
<p>It should also be noted that I am not rendering this component directly; it is being navigated <em>to</em> from my router component. I do not believe this is the cause of the issue though.</p>
<p>Thanks.</p>
<p>EDIT:</p>
<p>I am trying to currently mock out the location and history hooks that the component uses and have tried this code which throws the same error but may be getting closer:</p>
<pre><code>const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () =&gt; ({
    ...jest.requireActual('react-router-dom'),
    useHistory: () =&gt; ({
        push: mockHistoryPush,
    }),
    useLocation: () =&gt; ({
        pathname: &quot;/&quot;
    })
}));
</code></pre>
",https://stackoverflow.com/questions/72974524/jest-syntaxerror-unexpected-token-u-in-json-at-position-0-at-json-parse,"['reactjs', 'unit-testing', 'testing', 'jestjs', 'react-testing-library']",701,False,0,1
How to reset firestore unit testing my Cloud Functions with jest,"<p>I followed the Cloud Functions recommendation and created my unit testing in online mode, everything makes sense to me, but I am getting inconsistency when I am debugging. I just trying to reset the firestore state by resetting and seeding the database.</p>
<p>When I run my test suite separately, they work perfectly; if I run all the test suites together appear all the errors, I am pretty sure that this is related to the beforeEach hooks but idk how to fix them.</p>
<p>I have 3 test suites, I will share with you 1 of them and the function responsible of the reset of the firestore.</p>
<pre class=""lang-js prettyprint-override""><code>// eslint-disable-next-line spaced-comment
    /// &lt;reference types=&quot;jest&quot; /&gt;

    import { cleanup, getDb, initializeFirebase, makeChange, resetDb, wrap } from './util';
    initializeFirebase();

    import { streamerIsOffline, streamerIsOnline } from './__fixtures__/onStreamerUpdateSnaps';
    import { getScheduler, SchedulerClientWrapper } from './../utils/SchedulerClientWrapper';
    import onStreamerUpdate from '../onStreamerUpdate';

    const db = getDb();

    jest.mock('./../utils/SchedulerClientWrapper');

    const mockedGetScheduler = jest.mocked(getScheduler, true);

    const wrapped = wrap(onStreamerUpdate);

    const schedulerClientWrapper = new SchedulerClientWrapper();
    const mockedPause: jest.Mock = jest.fn();
    const mockedResume: jest.Mock = jest.fn();
    const mockedJobIsEnabled: jest.Mock = jest.fn();


    schedulerClientWrapper.pause = mockedPause;
    schedulerClientWrapper.resume = mockedResume;
    schedulerClientWrapper.jobIsEnabled = mockedJobIsEnabled;

    describe('onStreamerUpdate', () =&gt; {
      beforeEach(
          async () =&gt; {
            await resetDb(); //I am resetting firestore here
            mockedGetScheduler.mockClear();
            jest.resetAllMocks();
          });

      it('should resume the scheduledJob when the first streamer becomes online',
          async () =&gt; {
            await updateStreamerStatus('64522496', true); //I am preparing the setup here

            const beforeSnap = streamerIsOffline;
            const afterSnap = streamerIsOnline;

            const change = makeChange(beforeSnap, afterSnap);

            mockedGetScheduler.mockReturnValue(schedulerClientWrapper);

            mockedJobIsEnabled.mockResolvedValue(false);

            await wrapped(change);

            expect(mockedJobIsEnabled).toBeCalled();
            expect(mockedResume).toBeCalled();
            expect(mockedPause).not.toBeCalled();
          });
          
      afterAll(() =&gt; {
        cleanup();
      });
      
    });

    const updateStreamerStatus = async (streamerId: string, isOnline: boolean) =&gt; {
      const stremersRef = db.collection('streamers');

      const query = stremersRef.where('broadcasterId', '==', streamerId);
      const querySnapshot = await query.get();
      console.log('streamers', (await stremersRef.get()).docs.map((doc) =&gt; doc.data())); //I am debugging here
      const streamerDocId = querySnapshot.docs[0].id;
      await stremersRef.doc(streamerDocId).update({ isOnline });
    };
</code></pre>
<p>And you can find the functions that wipe and seed firestore below:</p>
<pre class=""lang-js prettyprint-override""><code>import firebaseFunctionsTest from 'firebase-functions-test';
import { getApp, getApps, initializeApp, cert } from 'firebase-admin/app';
import { getFirestore } from 'firebase-admin/firestore';

const projectId = 'latamqchallengetest';

export const { wrap, cleanup, firestore: firestoreTestData, makeChange } = firebaseFunctionsTest({
  databaseURL: `https://${projectId}.firebaseio.com`,
  storageBucket: `${projectId}.appspot.com`,
  projectId: projectId,
}, './../google-credentials/latamqchallengetest-firebase-adminsdk.json');

export const initializeFirebase = () =&gt; {
  if (getApps().length &lt;= 0) {
    initializeApp({
      credential: cert('./../google-credentials/latamqchallengetest-firebase-adminsdk.json'),
    });
  }
  return getApp();
};

export const getDb = () =&gt; {
  initializeFirebase();
  const db = getFirestore();
  return db;
};

export const wipeDb = async () =&gt; {
  const db = getDb();
  const collections = await db.listCollections();
  const deletePromises = collections.map((collectionRef) =&gt;
    db.recursiveDelete(collectionRef));

  Promise.all([...deletePromises]);
};

export const seed = async () =&gt; {
  const db = getDb();
  await db.collection('streamers').add({
    broadcasterId: '64522496',
    broadcasterName: 'ITonyl',
    color: '1565C0',
    description: 'Sr. Truchita',
    isOnline: false,
    puuid: 'kRQyIDe5TfLhWtn8jXgo_4Zjlfg4rPypXWiPCXrkTMUsiQT3TYVCkVO6Au3QTdd4x-13CbluPA53dg',
    summonerId: '9bnJOmLXDjX-sgPjn4ZN1_-f6m4Ojd2OWlNBzrdH0Xk2xw',
  });
  await db.collection('streamers').add({
    broadcasterId: '176444069',
    broadcasterName: 'Onokenn',
    color: '424242',
    description: 'El LVP Player',
    isOnline: false,
    puuid: 'Gbfj8FyB6OZewfXgAwvLGpkayA6xyevFfEW7UZdrzA6saKVTyntP4HxhBQFd_EIGa_P1xC9eVdy8sQ',
    summonerId: 'pPWUsvk_67FuF7ky1waWDM_gho-3NYP4enWTtte6deR3CjxOGoCfoIjjNw',
  });
};

export const resetDb = async () =&gt; {
  await wipeDb();
  await seed();
};
</code></pre>
<p>Sometimes I find that firestore has 4 records, other times it has 0 records, 2 records and so on .. I don't know why I await the promises before each test.</p>
<p>I expect to keep the same state before each test, can you help me please?</p>
",https://stackoverflow.com/questions/73779342/how-to-reset-firestore-unit-testing-my-cloud-functions-with-jest,"['unit-testing', 'google-cloud-firestore', 'jestjs']",213,True,0,1
Invalid JSON in Tests Authentifications PHPUnit,"<p>Good morning all , I did a complete migration of my symfony 2.8 application to version 5.4. I am now at the unit testing stage. I copied the tests to my new project, however I'm having some difficulties with the API authentication. I launched the unit tests without modification with the classic configuration of rest bundle. In my tests, I test the authentication of a user upstream in order to recover the rights necessary to test the different endpoints. When I want to authenticate with _username, and _password, I get the following error in my response content:</p>
<pre><code>&lt;!-- Invalid JSON. (400 Bad Request) --&gt;
</code></pre>
<p>Here is the content of my authUser function of my abstract class which allows to authenticate the user :</p>
<pre><code>&lt;?php

namespace WORD\UserBundle\Tests\Model;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Client;

abstract class AbstractAuthTestCase extends WebTestCase
{
    /**
         * @var Client
         */
        protected $client = null;
    
        /**
         * ContainerInterface
         */
        //protected $container;
    
    //    public function setUp(): void
    //    {
    //        self::ensureKernelShutdown();
    //        $this-&gt;client = static::createClient();
    //       // $this-&gt;container = $this-&gt;client-&gt;getContainer();
    //        $this-&gt;client-&gt;setServerParameter('HTTPS', true);
    //        $this-&gt;client-&gt;setServerParameter('HTTP_HOST', self::$container-&gt;getParameter('api_host'));
    //        $this-&gt;client-&gt;setServerParameter('HTTP_CONTENT_TYPE', 'application/json');
    //    }
    
        public function authUser($username='stack.fr', $password='overflow', $referer='https://stack.over.local/')
        {
            $this-&gt;newClient();
            $this-&gt;client-&gt;setServerParameter('HTTP_REFERER', $referer);
    
            $this-&gt;client-&gt;request('POST', '/api/login_check', array(
                '_username' =&gt; $username,
                '_password' =&gt; $password,
            ));
    
            $response = json_decode($this-&gt;client-&gt;getResponse()-&gt;getContent(), true);
    
            if (isset($response['token'])) {
                $this-&gt;client-&gt;setServerParameter('HTTP_AUTHORIZATION', 'Bearer ' . $response['token']);
            }
    
            return $response;
        }
    
        private function newClient()
        {
            $this-&gt;client = static::createClient();
            //$this-&gt;container = $this-&gt;client-&gt;getContainer();
            $this-&gt;client-&gt;setServerParameter('HTTPS', true);
            $this-&gt;client-&gt;setServerParameter('HTTP_HOST', self::$container-&gt;getParameter('api_host'));
            $this-&gt;client-&gt;setServerParameter('HTTP_CONTENT_TYPE', 'application/json');
        }
    }
</code></pre>
<p>Could you tell me if I forgot something please? I'm working on Symfony 5.4 with the FOS/RESTBundle 3.4</p>
<p>According to the documentation, this test method is still functional on symfony. 5 version. Thank you for your help</p>
",https://stackoverflow.com/questions/74286056/invalid-json-in-tests-authentifications-phpunit,"['php', 'symfony', 'fosrestbundle']",74,True,0,1
How do I properly create a unit test for a class method while stubbing other methods in Scala?,"<p>I have a class and a method I am testing (<code>SUTClass.a()</code> in the example solution below). I want to create a test case that:</p>
<ol>
<li>runs the body of <code>a()</code> while subordinated methods are stubbed (<code>b()</code>, <code>c()</code>)</li>
<li>verify that <code>b()</code> and <code>c()</code> have been called exactly one time</li>
</ol>
<p>The reason to stub methods that are not under test is that they could do some expensive disk/network operation. Also, in unit testing, you are <em>supposed</em> to isolate the code under test as much as possible.</p>
<p>In a solution I came up with I inject stubbed <code>b()</code> and <code>c()</code> as parameters to <code>a()</code>. However, if there are more methods to stub (think of <code>d()</code>, <code>e()</code> etc) the solution becomes a mess. Is there a better way?</p>
<p>As an alternative solution (when class under test is a Scala <code>object</code>) it is advised to create file <code>src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker</code>. However I consider it a poor approach.</p>
<p>Related posts:</p>
<ul>
<li><a href=""https://github.com/mockito/mockito-scala#mocking-scala-object"" rel=""nofollow noreferrer"">https://github.com/mockito/mockito-scala#mocking-scala-object</a></li>
</ul>
<p>Solution:</p>
<pre><code>import org.mockito.MockitoSugar.{doNothing, mock, times, verify}
import org.scalatest.FlatSpec

trait SUTClassMethods {
  def a( b: ()=&gt;Unit, c: ()=&gt;Unit )
  def b()
  def c()
}
class SUTClass extends SUTClassMethods {
  def a( b: () =&gt; Unit = b, c: () =&gt; Unit = c ): Unit = {
    println(&quot;Hello from a()&quot;)
    b()
    c()
  }
  def b(): Unit = println(&quot;Actual implementation of b()&quot;)
  def c(): Unit = println(&quot;Actual implementation of c()&quot;)
}

class DependencyInjectionTest extends FlatSpec {
  behavior of &quot;a()&quot;
  it should &quot;make call to b() and c() but actual implementations must not be executed&quot; in {
    val mockSUTClass = mock[SUTClassMethods]
    doNothing.when(mockSUTClass).b()
    doNothing.when(mockSUTClass).c()
    (new SUTClass).a(mockSUTClass.b, mockSUTClass.c)
    verify(mockSUTClass, times(1)).b()
    verify(mockSUTClass, times(1)).c()
  }
}
</code></pre>
<p>I am using Scala 2.11 and here is excerpt from my <code>build.sbt</code>:</p>
<pre><code>scalaVersion := &quot;2.11.12&quot;
libraryDependencies += &quot;org.scalatest&quot; %% &quot;scalatest&quot; % &quot;3.0.8&quot; % Test
libraryDependencies += &quot;org.mockito&quot; %% &quot;mockito-scala&quot; % &quot;1.16.32&quot; % Test
</code></pre>
",https://stackoverflow.com/questions/73895727/how-do-i-properly-create-a-unit-test-for-a-class-method-while-stubbing-other-met,"['scala', 'unit-testing', 'dependency-injection']",207,False,0,0
NullPointerException whenever I try to use output from one method in another method,"<p>Can I get a bit of help debugging the Java code below? I'm new to Java and I'm currently getting a NullPointerException error for the remove() method.</p>
<p>From the tests I've run, it looks like the setString() and getString() methods work fine, but when I try to use the output from getString() in the remove() method, I get the NullPointerExceptionError.</p>
<pre><code>import java.util.*;

public class CustomString {
    
    //instance variables

    String myString;
    boolean isSet;

    //constructor

    //initializes myString to null
    //initializes isSet to false
    public CustomString() {

    }


    // methods 
    
    public void setString(String string) {
        this.myString = string;
        this.isSet = true;
    }


    public String getString() {
        return this.myString;
    }

    /*
    Returns a new string version of the current string where the alphabetical
    characters specified in the given arg, are removed 
    */
    public String remove(String arg) {
        String removedChars = &quot;&quot;; //declare output string
        String inputString  = getString(); //get input string to be altered

        for (int i = 0; i &lt; inputString.length(); i++) { //iterate over myString
            if (Character.isAlphabetic(inputString.charAt(i))) {
                //...code continues...
</code></pre>
<p>I've also noticed that it seems to run fine if I explicitly hardcode the desired string like so:</p>
<pre><code>public String remove(String arg) {
    String removedChars = &quot;&quot;;
    String inputString  = &quot;DESIRED INPUT STRING&quot;;

    for (int i = 0; i &lt; inputString.length(); i++) {
        if (Character.isAlphabetic(inputString.charAt(i))) {
            //...code continues...
</code></pre>
<p>Any help would be greatly appreciated! Sorry in advance for any bad forum etiquette, I'm pretty new to stack overflow. I've been lurking, but so far I haven't been able to find a fix that works for my particular case.</p>
<p>EDIT: Sorry, I forgot to mention that the code is part of an assignment where we learn about unit testing. The setString function is fed arguments, then the code we write has to pass the assertEquals tests below:</p>
<pre><code>import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class CustomStringTest {

    //declare custom string for testing
    CustomString myCustomString;

    @BeforeEach
    public void setUp() throws Exception {
        //initialize custom string for testing
        this.myCustomString = new CustomString();
    }

    @Test
    void testGetString() {
        
        //string should be null to start, before setting it
        assertNull(this.myCustomString.getString());
        
        this.myCustomString.setString(&quot;hello&quot;);
        assertEquals(&quot;hello&quot;, this.myCustomString.getString());
        
        this.myCustomString.setString(&quot;Ar10CCfg&quot;);
        assertEquals(&quot;Ar10CCfg&quot;, this.myCustomString.getString());

        this.myCustomString.setString(&quot;k()soP OQ*(34&quot;);
        assertEquals(&quot;k()soP OQ*(34&quot;, this.myCustomString.getString());
    }
    
    @Test
    void testSetString() {
        
        //string should be null to start, before setting it
        assertNull(this.myCustomString.getString());

        this.myCustomString.setString(&quot;Good-bye!&quot;);
        assertEquals(&quot;Good-bye!&quot;, this.myCustomString.getString());
        
        this.myCustomString.setString(&quot;Ar10CCfg&quot;);
        assertEquals(&quot;Ar10CCfg&quot;, this.myCustomString.getString());

        this.myCustomString.setString(&quot;k()soP OQ*(34&quot;);
        assertEquals(&quot;k()soP OQ*(34&quot;, this.myCustomString.getString());
    }
    
    @Test
    void testRemove() {
        assertEquals(&quot;&quot;, this.myCustomString.remove(&quot;&quot;));
        
        this.myCustomString.setString(null);
        assertEquals(&quot;&quot;, this.myCustomString.remove(&quot;&quot;));
        
        this.myCustomString.setString(&quot;my lucky numbers are 6, 8, and 19.&quot;);
        assertEquals(&quot;my lucky numbes e 6, 8, nd 19.&quot;, this.myCustomString.remove(&quot;ra6&quot;));

        this.myCustomString.setString(&quot;Ar10CCfg&quot;);
        assertEquals(&quot;A10g&quot;, this.myCustomString.remove(&quot;crvf10&quot;));

        this.myCustomString.setString(&quot;k()soP OQ*(34&quot;);
        assertEquals(&quot;()oP O*(34&quot;, this.myCustomString.remove(&quot;()k 3QS4&quot;));
        
    }
///...tests continue...
</code></pre>
",https://stackoverflow.com/questions/73657423/nullpointerexception-whenever-i-try-to-use-output-from-one-method-in-another-met,"['java', 'methods']",46,True,-1,1
Debugging (breakpoints / etc) in VSCode with different makefiles for parts of the codebase,"<p>I'm working on an ESP-IDF based project that runs on ESP32 microcontrollers.</p>
<p>The project has a bunch of different C++ libraries (ESP-IDF calls them <code>components</code>) I've written. Normally I compile the whole project and it gets installed on the ESP32, and everything works great.</p>
<p>I've been writing tests, and how I make the tests work is a little different than the standard build process. For each set of tests, I am testing just one of my C++ components. (for instance &quot;Wireless&quot; or &quot;UserInputs&quot;, etc) I mock out the rest of my components and the ESP-IDF code that my code uses, and this lets me just test &quot;Wireless&quot;, for instance.</p>
<p>To do this, I'm using <code>CppUTest</code> and a series of makefiles. The makefile structure is based on the structure here: <a href=""https://github.com/memfault/interrupt/tree/master/example/unit-testing/minimal"" rel=""nofollow noreferrer"">https://github.com/memfault/interrupt/tree/master/example/unit-testing/minimal</a></p>
<p>And here's the article I followed that is describing that makefile/testing setup.
<a href=""https://interrupt.memfault.com/blog/unit-testing-basics#setting-up-cpputest"" rel=""nofollow noreferrer"">https://interrupt.memfault.com/blog/unit-testing-basics#setting-up-cpputest</a></p>
<p>So, there's a main makefile, and it finds all the per-component makefiles. Those per-component makefiles specify which <code>.cpp</code> files to compile, what folders to find your imports in, where your tests are, etc. And all that works great.</p>
<p>The situation I'm in is that I want to be able to run the debugger in VSCode to set breakpoints, pause execution, and inspect my variables at a given point in my code.</p>
<p>Just doing this in the tests is enough. I don't need debugger in my main ESP-IDF build process.</p>
<p>But I'm having the most challenging time working with this kind of setup. Because there's not just ONE make file.</p>
<p>Here's the core of what I want to do. I want to be able to set a breakpoint, and then do something to tell my code to compile with a given list of <code>.cpp</code> files, and header import locations. Just like in those per-component test make files. And I want my code to execute to that breakpoint and then give me the sauce in VSCode.</p>
<p>Any suggestions on how I can work in this direction would be very helpful.</p>
",https://stackoverflow.com/questions/74023308/debugging-breakpoints-etc-in-vscode-with-different-makefiles-for-parts-of-th,"['c++', 'unit-testing', 'makefile', 'cpputest']",126,True,0,1
How do I give my JSON schema an absolute URL for its $id when I haven&#39;t published it yet because it hasn&#39;t been tested yet?,"<p>I'm putting together JSON schemas and I'd like to use $ref to DRY my schemas. I'll have many schemas that will each use common subschemas. I want to unit test my schemas before publishing them by writing unit tests that assert that, given certain input, the input is deemed valid or invalid, using a JSON schema library that I trust to be correct (so that I'm just testing my schemas, not the library).</p>
<p>Where I get confused is that in order to load my schemas before I've published them (which I want to do while running tests locally and during CI/CD), I need to use relative local paths like this:</p>
<pre><code>&quot;pet&quot;: { &quot;$ref&quot;: &quot;file://./schemas/components/pet.schema.json&quot; }
</code></pre>
<p>That's because that pet schema hasn't been published to a URL yet. It hasn't been verified by automated tests that it's correct yet. This works well enough for running tests, and it also worked well for packaging inside a Docker image so that the schemas could be loaded from disk as the app starts up.</p>
<p>But then, if I were to give one of the top level schemas to someone (that leverages $ref) after publishing it to an absolute URL, it wouldn't load in their program because of that path that I used that worked only for my unit testing.</p>
<p>I found that I had to publish my schemas using absolute URLs in order for them to be used in consuming programs. I ended up publishing the schemas <a href=""https://mattwelke.github.io/go-jsonschema-ref-docker-example/schemas/person.1-0-0.schema.json"" rel=""nofollow noreferrer"">https://mattwelke.github.io/go-jsonschema-ref-docker-example/schemas/person.1-0-0.schema.json</a> and <a href=""https://mattwelke.github.io/go-jsonschema-ref-docker-example/schemas/components/pet.1-0-0.schema.json"" rel=""nofollow noreferrer"">https://mattwelke.github.io/go-jsonschema-ref-docker-example/schemas/components/pet.1-0-0.schema.json</a> that way. I tested that they worked fine in a consuming program by writing the program:</p>
<pre class=""lang-golang prettyprint-override""><code>package main

import (
    &quot;fmt&quot;

    &quot;github.com/xeipuuv/gojsonschema&quot;
)

func main() {
    schemaLoader := gojsonschema.NewReferenceLoader(&quot;https://mattwelke.github.io/go-jsonschema-ref-docker-example/schemas/person.1-0-0.schema.json&quot;)

    jsonStr := `
    {
        &quot;name&quot;: &quot;Matt&quot;,
        &quot;pet&quot;: {
            &quot;name&quot;: &quot;Shady&quot;
        }
    }
    `

    documentLoader := gojsonschema.NewStringLoader(jsonStr)

    result, err := gojsonschema.Validate(schemaLoader, documentLoader)
    if err != nil {
        panic(fmt.Errorf(&quot;could not validate: %w&quot;, err))
    }

    if result.Valid() {
        fmt.Printf(&quot;The document is valid.\n&quot;)
    } else {
        fmt.Printf(&quot;The document is not valid. See errors:\n&quot;)
        for _, desc := range result.Errors() {
            fmt.Printf(&quot;- %s\n&quot;, desc)
        }
    }
}
</code></pre>
<p>Which resulted in the following expected output:</p>
<pre><code>The document is valid.
</code></pre>
<p>So I'm confused about this &quot;chicken and egg&quot; situation.</p>
<p>I was able to publish schemas that could be used, as long as I didn't unit test them before publishing them.</p>
<p>And I was able to unit test schemas as long as:</p>
<ul>
<li>I didn't want to publish them in the form that was verified by the unit testing to be correct.</li>
<li>I'm okay with my application loading them via HTTPS as it starts up instead of loading them from disk. I'm worried about this because I don't want a web server to be a point of failure for my app starting up.</li>
</ul>
<p>I would appreciate some insight in how one might accomplish both goals.</p>
",https://stackoverflow.com/questions/71374864/how-do-i-give-my-json-schema-an-absolute-url-for-its-id-when-i-havent-publishe,"['unit-testing', 'go', 'jsonschema']",737,True,3,1
Xunit Unit Testing for Dot Net core application,"<p>I recently started learning Unit Testing and now have the requirement write unit tests using Xunit and Moq for dot net core application.</p>
<p>I can write some very basic but when it comes to write them for complex classes , I am kind of stuck.</p>
<p>Below is the class I will be writing tests for.</p>
<pre><code> public class AgeCategoryRequestHandler : IInventoryRequestHandler&lt;InventoryRequest, HandlerResult&gt;
{
    private readonly IRepositoryResolver _repositoryResolver;
    Hotels.HBSI.Logging.ILogger logger;
    public AgeCategoryRequestHandler(IRepositoryResolver repositoryResolver, Hotels.HBSI.Logging.ILogger iLogger)
    {
        _repositoryResolver = repositoryResolver;
        logger = iLogger;
    }

    public async Task&lt;HandlerResult&gt; Run(InventoryRequest inventoryRequest)
    {
        var result = await ProcessRequest(inventoryRequest);
        return CreateResponse(inventoryRequest, result);
    }

    private async Task&lt;int&gt; ProcessRequest(InventoryRequest inventoryRequest)
    {
        logger.Info(&quot;AgeCategory requesthandler processrequest start&quot;);
        var repository = _repositoryResolver.ResolveEstabAgeCategory();
        if (repository is not null)
        {
            return await repository.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories)
           .ConfigureAwait(false);
        }
        logger.Info(&quot;AgeCategory requesthandler processrequest complete&quot;);
        return InernalError.reponotfound;
    }
    public HandlerResult CreateResponse(InventoryRequest inventoryRequest, int resultCount)
    {
        var requestCount = inventoryRequest.EstabAgeCategories.Count;
        var handlerResult = new HandlerResult() { Id = RequestHandlerEnum.AgeCategrory.ToInt() };
        if (requestCount &gt; 0 &amp;&amp; resultCount &lt; requestCount)
        {
            handlerResult.IsSuccess = false;
            handlerResult.ErrorCode = OTAErrorType.InvalidAgeCategory.ToInt();
        }
        else if (requestCount &gt; 0 || requestCount == resultCount)
        {
            handlerResult.IsSuccess = true;
            handlerResult.ErrorCode = 0;
        }
        return handlerResult;
    }
}
</code></pre>
<p>Just to start , IRepositoryResolver and ILogger are in the constructor so I have created mock for these but unable to go beyond that as I am still in initial phase of learning.</p>
<p>Could someone explain me the steps/approach to accomplish this?.</p>
<p>Edit : What I have done so far is below ( can't figure out what are the things to be done and where to start or write )</p>
<p>Edit 2 : Did some more modifications to my test code , can someone comment if I am in right direction ? what else can I test ?</p>
<pre><code> public class AgeCategoryRequestHandlerTest
{
    private AgeCategoryRequestHandler _ageCategoryRequestHandler;

    private readonly Mock&lt;AgeCategoryRequestHandler&gt; _ageCategory = new Mock&lt;AgeCategoryRequestHandler&gt;();

    private readonly Mock&lt;Hotels.HBSI.Logging.ILogger&gt; _mockLogger = new Mock&lt;Hotels.HBSI.Logging.ILogger&gt;();
    private readonly Mock&lt;IRepositoryResolver&gt; _mockRepositoryResolver = new Mock&lt;IRepositoryResolver&gt;();
    public AgeCategoryRequestHandlerTest()
    {

        _ageCategoryRequestHandler = new AgeCategoryRequestHandler(_mockRepositoryResolver.Object, _mockLogger.Object);


    }


    [Fact]


   public async void  Testtt()

    {
        var fixture = new Fixture();
        var inventory = fixture.Create&lt;InventoryRequest&gt;();
        var hndlr = fixture.Create&lt;HandlerResult&gt;();

        hndlr.ErrorCode = 0;
        int resultCount = 3;

        await _ageCategoryRequestHandler.Run(inventory);

        HandlerResult response =   _ageCategoryRequestHandler.CreateResponse(inventory, resultCount);

        Assert.Equal(hndlr.ErrorCode, response.ErrorCode);

     
    }
</code></pre>
<p>Tried running Chris B suggested code , was getting type conversion error  <code>EstabAgeCategories  = new List&lt;int&gt;</code></p>
<p>Now I have used fixture for creating automatic objects and did some assert values. Below is the code sample</p>
<pre><code>           var fixture = new Fixture();
        var inventoryRequest = fixture.Create&lt;InventoryRequest&gt;();
        
        _mockRepository
            .Setup(x =&gt; x.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories))
            .ReturnsAsync(6);

        _mockRepositoryResolver
            .Setup(x =&gt; x.ResolveEstabAgeCategory())
            .Returns(_mockRepository.Object);

        // act
        var result = await _ageCategoryRequestHandler.Run(inventoryRequest);

        // assert
        _mockRepository
            .Verify(x =&gt; x.InsertUpdateEstabAgeCategoryDetail(inventoryRequest.EstabAgeCategories), Times.Once);

        Assert.True(result.Id == 6);
        Assert.True(result.ErrorCode == 0);
        Assert.True(result.IsSuccess);
</code></pre>
",https://stackoverflow.com/questions/73700179/xunit-unit-testing-for-dot-net-core-application,"['asp.net-core', '.net-core', 'azure-functions', 'moq', 'xunit.net']",177,True,2,1
What exactly happens when a MonoBehaviour is created with new?,"<p>I'm aware that it's &quot;not allowed&quot;; I did this by accident and it will thoroughly be removed from my final build. Obviously there's a good reason for that rule.</p>
<p>The weird thing is, it's in a unit testing component, and it still works perfectly in spite of the warning. I was filling a list with a few constructed instances of a class inheriting from MonoBehaviour, just to ensure that a function was doing what I wanted it to do, and I get this warning; but the test seems to run fine. Additionally, this is a warning, not an true error, which likely also has a reason.</p>
<p>Out of curiosity, as my understanding is clearly incomplete, can someone explain, and if possible provide a link to documentation explaining, why it is that Unity does not allow a behavior which it is clearly quite capable of? Why does it forbid this, and, in the event that the warning was ignored, what would be the drawbacks?</p>
<p>Thank you for completing my comprehension of it.</p>
",https://stackoverflow.com/questions/70774032/what-exactly-happens-when-a-monobehaviour-is-created-with-new,"['c#', 'unity-game-engine', 'mono', 'warnings', 'compiler-warnings']",608,True,1,2
Accurate testing of functions that require /proc,"<p>Suppose I have a function that reads the contents of a file into some buffer e.g.</p>
<pre><code>template &lt;class T&gt;
static std::streamsize ReadContents(const std::filesystem::path&amp; path, T&amp; buff, size_t max) 
{
   ...
   std::ifstream input(path.c_str(), std::ios::in | std::ios_base::binary);
   auto bytesRead = input.readsome(reinterpret_cast&lt;char *&gt;(buff.data()), static_cast&lt;std::streamsize&gt;(max));
   ...
   return bytsRead
}
</code></pre>
<p>Normally, this would be simple to unit test as I could provide some known files into the function so can test all return paths, size, buffer contents, etc.</p>
<p>If I wanted to test this function with files from /proc e.g. <code>/proc/meminfo</code> it worked ok in the unit test too because I created a fake virtual filesystem with known files and simply pointed the code at it.</p>
<p>When using the code in a real environment it failed however because <code>readsome</code> will not read files of zero sizes in the virtual file system. The fix of course for that is to replace <code>readsome</code> with <code>read</code> and <code>gcount</code> combo to get the same functionality but it made me think about how it would be possible to have accurate unit testing of code where you need to test reading files in the virtual filesystem without actually using the real files on the host.</p>
<p>I'm using c++ and gtest. Any idea of a pattern to solving this problem; pipes maybe?</p>
",https://stackoverflow.com/questions/73787705/accurate-testing-of-functions-that-require-proc,"['c++', 'unit-testing', 'googletest']",74,False,1,0
Unit Testing Azure Functions With Dependency Injection,"<p>I haven't written any Azure functions in quite a long time, and thought I'd refresh myself today, but I've clearly forgotten how to write appropriate unit tests for them. I have the following Function - it picks a random quote from a list;</p>
<pre><code>public class QuoteFunction
{
    private readonly IQuoteBank _repository;

    public QuoteFunction(IQuoteBank repository)
    {
        _repository = repository;
    }

    [FunctionName(&quot;GetQuote&quot;)]
    public async Task&lt;IActionResult&gt; Run(
        [HttpTrigger(AuthorizationLevel.Function, &quot;get&quot;, &quot;post&quot;, Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation(&quot;C# HTTP trigger function processed a request.&quot;);
        Quote quote = _repository.getQuote();
        return new OkObjectResult(quote);
    }
}
</code></pre>
<p>and it uses dependency injection to obtain the list of quotes - I have the following in Startup;</p>
<pre><code>public override void Configure(IFunctionsHostBuilder builder)
{
    builder.Services.AddSingleton&lt;IQuoteBank, QuoteBank&gt;();
    builder.Services.AddLogging();
}
</code></pre>
<p>which is injected into the constructor of the Function. as shown in the first snippet.</p>
<p>What I am struggling with is how I can use Moq to force the quote (which is randomly selected) to be consistent. I know I can mock the Interface IQuoteBank - but there is no where I can pass this mock object into the Run method.</p>
<p>So what I want to know is how I can pass a mock object to make the same quote be produced for unit testing? Has anyone done anything like this before? any examples in github?</p>
<p>I'm pretty sure I did a few years ago, just cant remember at all.</p>
",https://stackoverflow.com/questions/74817239/unit-testing-azure-functions-with-dependency-injection,"['c#', 'azure', 'unit-testing', 'azure-functions', 'moq']",313,True,1,1
How to test environment variables before all tests and fail if an env is undefined?,"<p>Is there a way to test <code>env</code> before all tests and not to proceed if an <code>env</code> is <code>undefined</code>. I initially tried to define my <code>dotenv</code> in <em>package.json</em>:</p>
<pre><code>&quot;jest&quot;: {
    &quot;verbose&quot;: true,
    &quot;testEnvironment&quot;: &quot;node&quot;,
    &quot;roots&quot;: [
      &quot;__tests__&quot;,
      &quot;bin&quot;,
      &quot;src&quot;
    ],
    &quot;setupFiles&quot;: [
      &quot;&lt;rootDir&gt;/__tests__/env-setup.js&quot;
    ],
    &quot;modulePathIgnorePatterns&quot;: [
      &quot;&lt;rootDir&gt;/docs&quot;,
      &quot;&lt;rootDir&gt;/__tests__/files&quot;,
      &quot;&lt;rootDir&gt;/__tests__/helpers&quot;,
      &quot;&lt;rootDir&gt;/__tests__/env-setup&quot;
    ]
  },
</code></pre>
<p>and after reading <a href=""https://stackoverflow.com/a/58953365/1952287"">Test process.env with Jest</a> but that didn't work so wrote my test as:</p>
<p>file <code>/__tests__/env.test.js</code>:</p>
<pre><code>import dotenv from 'dotenv'
dotenv.config()

const envObj = {
  foo: process.env.FOO,
  bar: process.env.BAR,
}

describe('env tests', () =&gt; {
  Object.keys(envObj).map((k, i) =&gt; {
    it(`testing ${Object.keys(envObj)[i]}`, () =&gt; {
      expect(envObj[k]).toBeDefined()
      if (envObj[k] === undefined) new Error(`Missing env variable for &quot;${Object.keys(envObj)[i]}&quot;`)
    })
  })
})
</code></pre>
<p>and while this will error out after the test is still proceeds with all tests. After my research I did find <a href=""https://jestjs.io/docs/api#beforeallfn-timeout"" rel=""nofollow noreferrer""><code>beforeAll</code></a> and wrote:</p>
<p>file <code>/__tests__/env.index.js</code>:</p>
<pre><code>import dotenv from 'dotenv'
dotenv.config()

const envObj = {
  foo: process.env.FOO,
  bar: process.env.BAR,
}

beforeAll(() =&gt; {
  return new Promise((res, rej) =&gt; {
    Object.keys(envObj).map((k, i) =&gt; {
      if (envObj[k] === undefined)
        rej(new Error(`Missing env variable for &quot;${Object.keys(envObj)[i]}&quot;`))
    })
    res()
  })
})
</code></pre>
<p>but then my issue is this has to be before every file and it still runs further tests. Further research to see if this has been asked I've read through:</p>
<ul>
<li><a href=""https://stackoverflow.com/questions/48989643/how-to-reset-module-imported-between-tests"">how to reset module imported between tests</a></li>
<li><a href=""https://stackoverflow.com/questions/68643820/how-do-i-mock-env-variables-in-jest"">How do I mock <code>.env</code> variables in Jest?</a></li>
<li><a href=""https://stackoverflow.com/questions/50259025/using-env-files-for-unit-testing-with-jest"">Using .env files for unit testing with jest</a></li>
<li><a href=""https://stackoverflow.com/questions/71489696/how-can-i-mock-a-env-dev-js-file-using-jest"">How can I mock a env.dev.js file using Jest?</a></li>
<li><a href=""https://stackoverflow.com/questions/59319610/set-env-variable-when-running-jest"">set env variable when Running jest</a></li>
<li><a href=""https://stackoverflow.com/questions/61781150/jest-test-not-reading-environment-variables-with-dotenv"">Jest test not reading environment variables with dotenv</a></li>
<li><a href=""https://stackoverflow.com/questions/63934104/environment-variables-undefined-in-nextjs-when-running-jest"">Environment variables undefined in NextJS when running Jest</a></li>
<li><a href=""https://stackoverflow.com/questions/72592581/using-environment-variables-in-node-and-jest"">Using environment variables in Node and Jest</a></li>
</ul>
<p>In Jest is there a way to run an env test before all tests and the first instance a variable is <code>undefined</code> it will stop any further tests?</p>
",https://stackoverflow.com/questions/73057043/how-to-test-environment-variables-before-all-tests-and-fail-if-an-env-is-undefin,"['node.js', 'unit-testing', 'jestjs', 'environment-variables', 'es6-modules']",934,False,1,0
What scope does unit testing cover in a weakly typed language?,"<p>The best way I can express my question is with an example.</p>
<pre class=""lang-js prettyprint-override""><code>class foo{
  constructor(size) {
    this.bar = new Array(size);
  }
  baz(index) {
    this.body[index] = true;
  }
}
</code></pre>
<p>Ignoring the constructor, assume we're unit testing <code>baz()</code>. baz is <strong>logically</strong> expected to take an input <code>index</code> that's between <code>0</code> and <code>bar.length - 1</code>, but the following can also compile:</p>
<ol>
<li><code>baz(['hey'])</code></li>
<li><code>baz(5) // with an array size of 2</code></li>
<li><code>baz(true)</code></li>
<li><code>baz('0')</code></li>
</ol>
<p>Now, I've been doing a lot of research on <strong>what</strong> we're actually testing with unit tests, and the best answer I can gather from what I read all around, is that, we're testing the function's behavior within the bounds of its logical contract with what/who's calling it. AKA, test implementation while implicitly assuming that <strong>it' called correctly</strong>.</p>
<p>I'm fully satisfied with this, but what I want to know is, where do we draw that line? None of the examples above will cause a typeerror, but I can disregard 1,3 and probably 4 if I'm to follow what I learned above.</p>
<p>But should I care about 2? Or do I also assume that the function's 'contract' will be upheld not only in terms of the inputs' implicit typing, but also their logical bounds.</p>
<p>Should I test and account for example 2 in my code?</p>
",https://stackoverflow.com/questions/72955017/what-scope-does-unit-testing-cover-in-a-weakly-typed-language,"['javascript', 'unit-testing', 'testing']",28,True,1,1
How to expose entire Rust structure to Python at once,"<p>I'm a Rust newbie exploring language features with the possible result of recommending Rust as a replacement for C/C++ for our next FW iteration. One important topic is Python interop for unit testing and modeling. I've got this far exposing a Rust struct:</p>
<pre><code>#[pyclass]
pub struct RustStruct {
    #[pyo3(get, set)] integer: i32,
    #[pyo3(get, set)] float: f32
}
</code></pre>
<p>There are a few things that bother me about this:</p>
<ul>
<li>I have to set the accessibility for every member separately.</li>
<li>I have to modify the original struct code to expose it to Python. Unlike
pybind11 for instance, where the original struct definition is
untouched, and the pybind code exposes it to Python.</li>
<li>The code won't
compile in a setting where pyo3 is not present.</li>
</ul>
<p>Ideally, I'd like to be able take existing Rust structures in an application, and say &quot;please expose this to Python for me, in such a way that I can instantiate and modify the Rust structure in Python, and without having to modify the source code for the existing structure&quot;.</p>
<p>I hope this all makes sense. Are there ways to get closer to this goal?</p>
",https://stackoverflow.com/questions/74341312/how-to-expose-entire-rust-structure-to-python-at-once,"['python', 'rust', 'pyo3']",162,False,1,0
Mocking function to unit test Serverless Lambda,"<p>I am really struggling to understand unit testing within a Serverless Application.  So I obviously have my handler, and I have a single Lambda function</p>
<pre><code>const responses = require('../utils/jsonResponse');
const someConnector = require('../services/connectToService/connectToService');

module.exports = async (event) =&gt; {
  const connectionParams = {
    //some env variables
  };

  try {
    const token = await someConnector.connectToService(connectionParams);
    return responses.status(token, 200);
  } catch (e) {
    return responses.status(
      `Issue connecting to service - ${e.message}`,
      500,
    );
  }
};
</code></pre>
<p>So this Lambda function is pretty straight forward, gets some environment variables, and awaits a response from a service.  It then returns the response.</p>
<p>So I have already done integration tests for this which is fine, but now I wanted to do a Unit test.  I wanted to test this function in isolation, so essentially I want to mock <code>connectToService</code> to return my own responses.</p>
<p>So I came up with the following</p>
<pre><code>require('dotenv').config();

const { expect } = require('chai');
const sinon = require('sinon');
let sandbox = require(&quot;sinon&quot;).createSandbox();
const LambdaTester = require('lambda-tester');
const handler = require('../../../handler');
const msConnector = require('../../../services/connectToService/connectToService');

describe('Testing handler', async (done) =&gt; {
  describe('endpoint someEndpoint returns 200', () =&gt; {
    it('Should resolve with 200', async () =&gt; {
      before(() =&gt; {
        sandbox = sinon.createSandbox();
        sandbox.stub(msConnector, 'connectToService').resolves('some-token');
      });
      afterEach(() =&gt; {
        sandbox.restore();
      });
      await LambdaTester(handler.someEndpoint)
        .expectResult((result) =&gt; {
          console.log(result);
          expect(result.statusCode).to.equal(200);
        });
    });
  });
  done();
});
</code></pre>
<p><code>msConnector</code> is the filename of the service, <code>connectToService</code> is the function name.  What I want to do is not invoke this function, but return some-token when my Lambda calls it.</p>
<p>However, I have the <code>console.log</code>, and what I get from that is the real token, not some-token.</p>
<p>This tells me that the mocked function is really being called and executed and returning the real value.</p>
<p>So how can I mock this to make sure it returns <code>some-token</code>?</p>
<p>Thanks</p>
<p><strong>Service function</strong></p>
<pre><code>const { DOMParser } = require('@xmldom/xmldom');
const axios = require('axios');
const { loginRequest } = require('./xml/login');


const connectToService = async (connectionParams) =&gt; {
  //this injects config details into XML
  const xmlRequest = loginRequest(
    connectionParams.username,
    connectionParams.password,
    connectionParams.url,
  );

  const config = {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': xmlRequest.length,
    },
  };

  const token = await axios
    .post(connectionParams.msHost, xmlRequest, config)
    .then((res) =&gt; {
      const dom = new DOMParser().parseFromString(res.data, 'text/xml');

      if (
        dom.documentElement
          .getElementsByTagName('wsse:secToken')
          .item(0)
      ) {
        return dom.documentElement
          .getElementsByTagName('wsse:secToken')
          .item(0).firstChild.nodeValue;
      }
      throw new Error('Invalid Username/Password');
    })
    .catch((err) =&gt; {
      throw new Error(`Error making connection - ${err.message}`);
    });

  return token;
};

module.exports = {
  connectToService,
};
</code></pre>
",https://stackoverflow.com/questions/73416601/mocking-function-to-unit-test-serverless-lambda,"['node.js', 'unit-testing', 'lambda', 'mocking', 'serverless-framework']",280,True,1,1
Best practice for invoke-ing a tool that internally calls `exec`?,"<p>pipenv uses click, and uses click's <a href=""https://click.palletsprojects.com/en/5.x/api/#click.Context.invoke"" rel=""nofollow noreferrer"">invoke</a> method <a href=""https://github.com/pypa/pipenv/blob/9d532123d1c6d7e8067bd7b9e374f48f54e142d6/tests/integration/conftest.py#L376"" rel=""nofollow noreferrer"">in its unit test suite</a> to test itself.</p>
<p>This does not work great when unit testing the <code>pipenv run</code> command, which <a href=""https://github.com/pypa/pipenv/blob/9d532123d1c6d7e8067bd7b9e374f48f54e142d6/pipenv/core.py#L2670-L2674"" rel=""nofollow noreferrer"">internally uses <code>execve</code></a>. In the context of a single threaded test run this means our test runner (<code>pytest</code>) process gets completely replaced by whatever we're <code>exec</code>-ing, and the test suite immediately and silently exits.</p>
<p>(This bug on the pipenv issue tracker talks about this in more detail: <a href=""https://github.com/pypa/pipenv/issues/4909"" rel=""nofollow noreferrer"">https://github.com/pypa/pipenv/issues/4909</a>)</p>
<p>Is there a best practice for how to handle situations like this with click? Should we not be using click's <code>invoke</code> at all, and instead using regular old <code>subprocess</code>? Or perhaps <code>invoke</code> could optionally run the command in a subprocess rather than the current process? Or maybe there's a best practice for cli apps that use click to detect if they're being run via <code>invoke</code> and just be careful <em>not</em> to do anything in the <code>exec</code> family (this is basically what pipenv does right now: if the <code>CI</code> env var is set, then <code>pipenv run</code> triggers a subprocess rather than using <code>execve</code>).</p>
",https://stackoverflow.com/questions/73995157/best-practice-for-invoke-ing-a-tool-that-internally-calls-exec,['python-click'],14,False,1,0
Quarkus unable to load the cassandra custom retry policy class,"<p>I am working on a task to migrate Quarkus from 1.x to 2.x and Quarkus integration with embedded Cassandra failed in unit testing with error -</p>
<p>Caused by: java.lang.IllegalArgumentException: Can't find class com.mind.common.connectors.cassandra.CassandraCustomRetryPolicy
(specified by advanced.retry-policy.class)</p>
<pre><code>                    **Custom retry policy**

public class CassandraCustomRetryPolicy implements RetryPolicy {

    public CassandraCustomRetryPolicy(DriverContext context, String profileName) {
    }
 //override methods
}

               ****quarkus test be like** -**

@QuarkusTest
@QuarkusTestResource(CassandraTestResource.class)
class Test {}


       **CassandraTestResource class start the embedded cassandra** 



 public class CassandraTestResource implements QuarkusTestResourceLifecycleManager {
    
        private Cassandra cassandra;
    
        @Override
        public Map&lt;String, String&gt; start() {
            cassandra = new CassandraBuilder().version(&quot;3.11.9&quot;)
                    .addEnvironmentVariable(&quot;JAVA_HOME&quot;, getJavaHome())
                    .addJvmOptions(&quot;-Xms512M -Xmx512m&quot;).build();
    
            cassandra.start();
    }
</code></pre>
<p>I have override the default Cassandra driver policy in application.conf inside resource folder.</p>
<pre><code>  datastax-java-driver {
          basic.request {
            timeout = ****
            consistency = ***
            serial-consistency = ***
          }
          advanced.retry-policy {
            class = com.mind.common.connectors.cassandra.CassandraCustomRetryPolicy
          }
</code></pre>
<p>I have observed that my custom retry policy class comes under banned resource in QuarkusClassLoader.java-</p>
<pre><code>String resourceName = sanitizeName(name).replace('.', '/') + &quot;.class&quot;;
                boolean parentFirst = parentFirst(resourceName, state);
                if (state.bannedResources.contains(resourceName)) {
                    throw new ClassNotFoundException(name);
                }
</code></pre>
<p>I have captured the following logs -</p>
<p>java.lang.ClassNotFoundException: com.mind.common.connectors.cassandra.CassandraCustomRetryPolicy
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:438)
at io.quarkus.bootstrap.classloading.QuarkusClassLoader.loadClass(QuarkusClassLoader.java:414)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:315)
at com.datastax.oss.driver.internal.core.util.Reflection.loadClass(Reflection.java:57)
at com.datastax.oss.driver.internal.core.util.Reflection.resolveClass(Reflection.java:288)
at com.datastax.oss.driver.internal.core.util.Reflection.buildFromConfig(Reflection.java:235)
at com.datastax.oss.driver.internal.core.util.Reflection.buildFromConfigProfiles(Reflection.java:194)
at com.datastax.oss.driver.internal.core.context.DefaultDriverContext.buildRetryPolicies(DefaultDriverContext.java:359)
at com.datastax.oss.driver.internal.core.util.concurrent.LazyReference.get(LazyReference.java:55)
at com.datastax.oss.driver.internal.core.context.DefaultDriverContext.getRetryPolicies(DefaultDriverContext.java:761)
at com.datastax.oss.driver.internal.core.session.DefaultSession$SingleThreaded.init(DefaultSession.java:339)
at com.datastax.oss.driver.internal.core.session.DefaultSession$SingleThreaded.access$1100(DefaultSession.java:300)
at com.datastax.oss.driver.internal.core.session.DefaultSession.lambda$init$0(DefaultSession.java:146)
at io.netty.util.concurrent.PromiseTask.runTask(PromiseTask.java:98)
at io.netty.util.concurrent.PromiseTask.run(PromiseTask.java:106)
at io.netty.channel.DefaultEventLoop.run(DefaultEventLoop.java:54)
at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:986)
at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:834)</p>
<p>I am using quarkus version 2.7.2.Final with cassandra driver version 4.14.0</p>
",https://stackoverflow.com/questions/71792133/quarkus-unable-to-load-the-cassandra-custom-retry-policy-class,"['cassandra', 'quarkus', 'datastax-java-driver', 'embedded-cassandra']",324,True,1,2
Testing of even easy behaviour leads to a jungle of testing functions,"<p>Until today I had a hard time with unit testing. For this reason I just started to read a book <a href=""https://livebook.manning.com/book/the-art-of-unit-testing-second-edition/chapter-1"" rel=""nofollow noreferrer"">&quot;The art of Unit Testing&quot;</a>.<br />
The author states that each &quot;unit of work&quot; has entry and exit points and that there should be a unit test for each exit point.<br />
An &quot;exit point&quot; could be:</p>
<ul>
<li>A return value of a function (also an exception)</li>
<li>A state change (for example of a class property)</li>
<li>A third party system called (E-Mail service)</li>
</ul>
<p>The entry point is usually a function call.</p>
<p>I was now eager to try this in one of my examples and I was successful. But for a price that I cannot accept.  My tests are a huge amount of functions and I would like to get your opinion about them.</p>
<p>The test class I want to use is easy:</p>
<pre><code>public class RoleAssignement
{
    public string RoleId { get; }
    public string EnterpriseId { get; }
    public List&lt;string&gt; SiteIds { get; }

    public RoleAssignement(string roleId, string enterpriseScopeId)
    {
        Ensure.ThrowIfNull(roleId);
        Ensure.ThrowIfNull(enterpriseScopeId);
        Ensure.ThrowIfIdNotValid(roleId);
        Ensure.ThrowIfIdNotValid(enterpriseScopeId);

        RoleId = roleId;
        EnterpriseId = enterpriseScopeId;
    }

    public RoleAssignement(string roleId, List&lt;string&gt; siteScopeIds)
    {
        Ensure.ThrowIfNull(roleId);
        Ensure.ThrowIfNull(siteScopeIds);
        Ensure.ThrowIfIdNotValid(roleId);
        foreach(var id in siteScopeIds)
        {
            Ensure.ThrowIfIdNotValid(id);
        }
        RoleId = roleId;
        SiteIds = siteScopeIds;
    }
}
</code></pre>
<p>You can see that I have just three properties. One of them (RoleId) must be set always. The other two parameters should be exclusively set (if one is null, the other must be set and vice versa).</p>
<p>In the language of the book I have two &quot;entry points&quot; - my two constructors.</p>
<p>But I have ten exit points that are:</p>
<pre><code>1 If roleId is null for the first constructor, an exception should be thrown.  
2 If roleId is null for the second constructor, an exception should be thrown.  
3 If enterpriseScopeId is null for the first constructor, an exception should be thrown.  
4 If siteScopeId is null for the second constructor, an exception should be thrown.  
5, 6, 7, 8 If any of the four parameters have an invalid id, an exception should be thrown.  
9 If the first constructor was called with the correct parameters, RoleId and EnterpriseId should be set but SiteIds should be null.  
10 If the second constructor was called =&gt; vice versa.  
</code></pre>
<p>If I write my unit tests now, I get a long list of testing functions - one of each exit point. I pasted this in the end of my question.</p>
<p>The thing is: Am I really on the right way here? I have a very easy test class now and the tests for it seem to explode in a huge jungle of tests.<br />
Testing each possible exit point with its own function will slow me down in my coding and because the tests are testing such an <em>easy behaviour</em> they are also worthless for me.</p>
<p>Or are they?</p>
<p>But what will happen if I start to test the more complicated things? I will have a project with 1000 lines of production code and 10000 lines of tedious test functions.</p>
<p>I think I misunderstood something, but I don't know what I misunderstood. Or am I okay with my tests and I have to live with this from now?</p>
<p>Here is my testing code - all tests are passing. I even wrote them following TDD:</p>
<p><a href=""https://i.stack.imgur.com/JDc3F.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/JDc3F.png"" alt=""enter image description here"" /></a></p>
<p>Testing code: ~100 lines<br />
Production code: ~30 lines</p>
<p>Really?</p>
<pre><code>using CP.Admin.Core.SDK.ValueObjects;
using DataHive.Validations.Exceptions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;

namespace CP.Admin.Tests
{
    [TestClass]
    public class RoleAssignementTests
    {
        [TestMethod]
        public void RoleAssignementFirst_NullRoleIdParameter_ThrowsArgumentNullException()
        {
            Action useConstructor = () =&gt;
            {
                var roleAssignement = new RoleAssignement(null, &quot;62500ac55988223c8b9b28fc&quot;);
            };
            Assert.ThrowsException&lt;ArgumentNullException&gt;(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementFirst_InvalidRoleIdParameter_ThrowsIdNotValidException()
        {
            Action useConstructor = () =&gt;
            {
                var roleAssignement = new RoleAssignement(&quot;invalidId&quot;, &quot;62500ac55988223c8b9b28fc&quot;);
            };
            Assert.ThrowsException&lt;IdNotValidException&gt;(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementFirst_NullEnterpriseScopeIdParameter_ThrowsArgumentNullException()
        {
            Action useConstructor = () =&gt;
            {
                string param = null;
                var roleAssignement = new RoleAssignement(&quot;62500ac55988223c8b9b28fc&quot;, param);
            };
            Assert.ThrowsException&lt;ArgumentNullException&gt;(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementFirst_InvalidEnterpriseScopeIdParameter_ThrowsArgumentNullException()
        {
            Action useConstructor = () =&gt;
            {
                var roleAssignement = new RoleAssignement(&quot;62500ac55988223c8b9b28fc&quot;, &quot;invalidId&quot;);
            };
            Assert.ThrowsException&lt;IdNotValidException&gt;(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementSecond_NullRoleIdParameter_ThrowsArgumentNullException()
        {
            Action useConstructor = () =&gt;
            {
                var param = new List&lt;string&gt; { &quot;62500ac55988223c8b9b28fc&quot; };
                var roleAssignement = new RoleAssignement(null, param);
            };
            Assert.ThrowsException&lt;ArgumentNullException&gt;(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementSecond_InvalidRoleIdParameter_ThrowsIdNotValidException()
        {
            Action useConstructor = () =&gt;
            {
                var param = new List&lt;string&gt; { &quot;62500ac55988223c8b9b28fc&quot; };
                var roleAssignement = new RoleAssignement(&quot;invalidId&quot;, param);
            };
            Assert.ThrowsException&lt;IdNotValidException&gt;(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementSecond_NullSiteScopeIdParameter_ThrowsArgumentNullException()
        {
            Action useConstructor = () =&gt;
            {
                List&lt;string&gt; param = null;
                var roleAssignement = new RoleAssignement(&quot;62500ac55988223c8b9b28fc&quot;, param);
            };
            Assert.ThrowsException&lt;ArgumentNullException&gt;(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementSecond_InvalidSiteScopeIdParameter_ThrowsIdNotValidException()
        {
            Action useConstructor = () =&gt;
            {
                var param = new List&lt;string&gt; { &quot;invalidId&quot; };
                var roleAssignement = new RoleAssignement(&quot;62500ac55988223c8b9b28fc&quot;, param);
            };
            Assert.ThrowsException&lt;IdNotValidException&gt;(useConstructor);
        }
        [TestMethod]
        public void RoleAssignementFirst_ParametersAreOkay_AllValuesAreCorrect()
        {
            var roleAssignement = new RoleAssignement(&quot;62500ac55988223c8b9b28fc&quot;, &quot;62500ac55988223c8b9b28fc&quot;);
            Assert.IsNotNull(roleAssignement.RoleId);
            Assert.IsNotNull(roleAssignement.EnterpriseId);
            Assert.IsNull(roleAssignement.SiteIds);
        }
        [TestMethod]
        public void RoleAssignementSecond_ParametersAreOkay_AllValuesAreCorrect()
        {
            var param = new List&lt;string&gt; { &quot;62500ac55988223c8b9b28fc&quot; };
            var roleAssignement = new RoleAssignement(&quot;62500ac55988223c8b9b28fc&quot;, param);
            Assert.IsNotNull(roleAssignement.RoleId);
            Assert.IsNotNull(roleAssignement.SiteIds);
            Assert.IsNull(roleAssignement.EnterpriseId);
        }
    }
}
</code></pre>
",https://stackoverflow.com/questions/71796213/testing-of-even-easy-behaviour-leads-to-a-jungle-of-testing-functions,"['c#', 'unit-testing', 'automated-tests', 'mstest']",96,True,1,1
Unit testing + Mocking eBPF programs in python incl emulating kernel to user-space interactions,"<p>So I need to get some mocking+testing done on a very specific kind of python code: it is an eBPF(Berkely packet filter) program using python, which in essence runs a C program in kernel space through a python script via the BPF Compiler Collection BCC
eg code:</p>
<pre><code>from bcc import BPF
# define BPF program
prog = &quot;&quot;&quot;
int hello(void *ctx) {
    bpf_trace_printk(&quot;Hello, World!\\n&quot;);
    return 0;
}
&quot;&quot;&quot;
# load BPF program
b = BPF(text=prog)
b.attach_kprobe(event=b.get_syscall_fnname(&quot;clone&quot;), fn_name=&quot;hello&quot;)
# header
print(&quot;%-18s %-16s %-6s %s&quot; % (&quot;TIME(s)&quot;, &quot;COMM&quot;, &quot;PID&quot;, &quot;MESSAGE&quot;))
# format output
while 1:
    try:
        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
    except ValueError:
        continue
    print(&quot;%-18.9f %-16s %-6d %s&quot; % (ts, task, pid, msg))

</code></pre>
<p>I want to now write tests for the C and the Python code without the 2 interfering (I would even be satisfied with some basic python unit testing). Any &amp; all possible approaches to the problem are welcome, or even a general direction to look for info on this kind of testing, really just looking to address the following concerns:
<strong>Can I easily mock the kernel interactions when testing the python code?
Can I emulate a message coming from the kernel to user-space?
Can I test a message that’s just larger or just smaller than the expected message size?</strong></p>
<p>I tried looking into the topic for days, to no avail so even pointing me in the right direction would be greatly appreciated...</p>
",https://stackoverflow.com/questions/74699652/unit-testing-mocking-ebpf-programs-in-python-incl-emulating-kernel-to-user-spa,"['python', 'unit-testing', 'linux-kernel']",61,True,0,1
Azure.Messaging.EventGrid vs Azure.EventGrid IotHubDeviceTelemetryEventData missing Constructor?,"<p>I am attempting to use the newer Azure.Messaging.EventGrid over the traditional Azure.EventGrid. I am getting hung up on my unit tests attempting to create object of type IotHubDeviceTelemetryEventData(). In the older library, I was able to create this no problem using the following convention.</p>
<pre><code>  return new object[]
            {
                new
                {
                    id = &quot;73813f6e-4d43-eb85-d6f1-f2b6a0657731&quot;,
                    topic = &quot;testTopic&quot;,
                    data = new IotHubDeviceTelemetryEventData &lt;-- New Up the object (no problem!) 
                    {
                        Body = body} &lt;-- Body has a setter. Great!
                    ,
                    eventType = &quot;Microsoft.Devices.DeviceTelemetry&quot;,
                    subject = &quot;devices/b82bfa90fb/gw-uplink&quot;,
                    dataVersion = &quot;1.0&quot;
                }
</code></pre>
<p>With the latest offering however, all of this is removed for some reason.</p>
<p>Old documentation with constructor etc (<a href=""https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.eventgrid.models.iothubdevicetelemetryeventdata.-ctor?view=azure-dotnet"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/api/microsoft.azure.eventgrid.models.iothubdevicetelemetryeventdata.-ctor?view=azure-dotnet</a></p>
<p>New documentation with no constructor, no setter on the body (DeviceTelemetry is sealed) etc:
<a href=""https://learn.microsoft.com/en-us/dotnet/api/azure.messaging.eventgrid.systemevents.iothubdevicetelemetryeventdata?view=azure-dotnet"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/dotnet/api/azure.messaging.eventgrid.systemevents.iothubdevicetelemetryeventdata?view=azure-dotnet</a></p>
<p>Anyone run into this? I would like to get off the old but I have existing unit tests that logically create TelemetryEventData and send to the function. I see no way of unit testing this ? I have tried mocking IotHubDeviceTelemetryEventData  with
<code>_mockHubTelemEventData.setup(c =&gt; c.Body).Returns(foo)</code>
but this as well throws me an error of no setter on Body.</p>
<p>Super frustrating.
Other attempts have included creating EventGridEvent() but this as well is missing core functionality as the EventGridEvent.parse won't find any object of type Body.
<code> EventGridEvent[] egEvents = EventGridEvent.ParseMany(BinaryData.FromStream(req.Body));</code></p>
",https://stackoverflow.com/questions/74034321/azure-messaging-eventgrid-vs-azure-eventgrid-iothubdevicetelemetryeventdata-miss,"['c#', 'azure', 'azure-functions', 'azure-iot-hub', 'azure-eventgrid']",194,True,0,1
"Django - How to include all form logic in modelForm and not in a Createview, so that form can be unittested without also testing the view?","<p>I have a <code>Campaign</code> Model, and a <code>CampaignCreateForm</code> which is a ModelForm. The Campaign model has a <code>contact_list</code> field of type <code>JSONField</code>. When a user is creating a campaign using the <code>CampaignCreateForm</code> they upload a CSV file which is processed to create the JSON data for the <code>contact_list</code> field.</p>
<p>What is the best way to approach this so that I can test the form separately from the view?</p>
<p>I've built this using a <code>CampaignCreateView</code> which inherits from CreateView, and included the logic to parse the CSV file and create the JSON data in the views  <code>form_valid</code> method, but this makes unit-testing the form (and any form field validation) impossible. I want to test the functions included in the forms <code>clean</code> method. With my current approach the view and form must be tested together, and that feels wrong.</p>
<p>How can I create the form such that all the logic for the form (processing the CSV file to create the JSON data and discarding the uploaded file) is handled in the form only?</p>
<p>My current CreateView and ModelForm are below:</p>
<p>View:</p>
<pre class=""lang-py prettyprint-override""><code>class CampaignCreateView(LoginRequiredMixin, CreateView):

    model = Campaign
    form_class = CampaignCreateForm  # required if you want to use a custom model form, requires `model` also
    template_name = &quot;writing/campaign_create.html&quot;

    def get_success_url(self):
        &quot;&quot;&quot; If model has get_absolute_url() defined, then success_url or get_success_url isnt neccessary
        &quot;&quot;&quot;

        user = User.objects.get(username=self.kwargs.get(&quot;username&quot;))
        return reverse(&quot;writing:campaigns&quot;, kwargs={&quot;username&quot;: user.username})

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs.update({&quot;user&quot;: self.request.user})
        return kwargs

    def form_valid(self, form):
        &quot;&quot;&quot; by default, form_valid redirects  to success_url
        &quot;&quot;&quot;

        form.instance.user = self.request.user
        form.instance.image_url = f&quot;https://picsum.photos/seed/{randrange(10000)}/500/300&quot;

        file = form.cleaned_data[&quot;contact_list_file&quot;]
        file_content = file.open(&quot;r&quot;)
        json_contact_list = csv_to_json(file_content)
        form.instance.contact_list = json_contact_list

        contact_list = json.loads(json_contact_list)  # as python dict
        form.instance.items = len(contact_list)

        response = super().form_valid(form)

        log_campaign_progress(pk=form.instance.pk, status=&quot;t2h-created&quot;, stage=&quot;campaign&quot;)
        enqueue_handwriting_generation(campaign_pk=form.instance.pk)

        return response

</code></pre>
<p>Form:</p>
<pre class=""lang-py prettyprint-override""><code>class CampaignCreateForm(forms.ModelForm):

    contact_list_file = forms.FileField(required=True)

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop(
            &quot;user&quot;
        )  # To get request.user. Do not use kwargs.pop('user', None) due to potential security hole
        super().__init__(*args, **kwargs)

    class Meta:
        model = Campaign
        fields = (&quot;name&quot;, &quot;message&quot;, &quot;contact_list_file&quot;)

    def clean(self):

        # Cammpaign name is unique for the user
        try:
            Campaign.objects.get(name=self.cleaned_data[&quot;name&quot;], user=self.user)
        except Campaign.DoesNotExist:
            pass
        else:
            self.add_error(
                &quot;name&quot;,
                ValidationError(
                    _(&quot;You've already created a campaign with this name&quot;), code=&quot;BadCampaignName&quot;
                ),
            )

        # if an error is attached to a field then the field is removed from cleaned_data
        self = check_message_length(self)
        self = check_message_text_is_valid(self)
        self = check_file_is_valid(self)
        self = check_message_tags_exist_in_contact_list(self)
        return self.cleaned_data

</code></pre>
<p>Model:</p>
<pre class=""lang-py prettyprint-override""><code># TimeStampedModel inherits form models.Model
class Campaign(TimeStampedModel):
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
    )

    order = models.ForeignKey(
        Order,
        on_delete=models.SET_NULL,
        null=True,
    )

    name = models.CharField(max_length=80)
    notes = models.CharField(max_length=2000, null=False, blank=True)
    message = models.TextField(
        max_length=1800,
        null=False,
        blank=False,
    )
    contact_list = models.JSONField(null=True)
    items = models.PositiveIntegerField(null=False, blank=False)
    purchased = models.BooleanField(default=False, null=False)

    def __str__(self):
        return self.name

    class Meta:
        ordering = [&quot;-modified&quot;]
        unique_together = (&quot;user&quot;, &quot;name&quot;)

    ... more fields
</code></pre>
",https://stackoverflow.com/questions/72728276/django-how-to-include-all-form-logic-in-modelform-and-not-in-a-createview-so,"['python', 'django', 'django-views', 'django-forms']",63,False,0,0
How can I keep unit testing in Unity after introducing security rules to firestore?,"<p>I am using cloud firestore + cloud functions + firestore auth to support my game.</p>
<p>I developed the main part of the app with unit tests in the app plus typescript tests for cloud functions. Now I want to add security rules to secure the data.</p>
<p>When I do so, requiring the calls to be authenticated, all my unit tests in unity (naturally) fails, as I do not authenticate a user but mocks them as data representation of the user in the db.</p>
<p>I want to keep using my unit tests in unity but still requiring the real db to demand authentication.</p>
<p>I have tried to look around for mock auth, or auth test environment, but found nothing except the library <a href=""https://firebase.google.com/docs/reference/emulator-suite/rules-unit-testing/rules-unit-testing"" rel=""nofollow noreferrer"">rules-unit-testing</a>.</p>
<p>I see the content of it with specialized logic for mocking user, making me think that I am understanding this the wrong way by trying to do this in unity. My question is, <strong>How to continue to do game tests in unity, which requires interacting with the firestore server, while keeping security rules?</strong></p>
",https://stackoverflow.com/questions/74476873/how-can-i-keep-unit-testing-in-unity-after-introducing-security-rules-to-firesto,"['unit-testing', 'authentication', 'unity-game-engine', 'google-cloud-firestore', 'firebase-security']",49,True,0,1
Integrating Postman Requests with Unit Testing Framework,"<p>Say you have developed a number of Postman Requests in a collection. Such requests are huge and complex and they are used to test end-points or perform certain actions such as creating a sample test case for testing be carried out on the web application.</p>
<p>All such requests can, in theory, be scripted using NodeJS, PowerShell, or C#, and within the context of Unit Testing Framework such as Pester, NUnit, Jest, Selenium, Chia, Mocha …etc.</p>
<p>However, we want to take advantage of the work done in Postman and we need to script the invocation of such Postman requests in a given collection, to be executed against a given Environment. All the other details such as Environment Configurations, Authentication, Request Boyd, Request Header …etc. are all configured properly in Postman.</p>
<p>Now I have setup my local dev environment testing project using vscode, C#/PowerShell, Selenium WebDriver and NUnit. I want to script the test case in C# (NUnit) or PowerShell (Pester) to invoke the relevant Postman requests to be executed against the intended environment.</p>
<p>How is this possible?</p>
<p>I appreciate your help.</p>
<p>Tarek</p>
",https://stackoverflow.com/questions/71428699/integrating-postman-requests-with-unit-testing-framework,"['c#', 'unit-testing', 'visual-studio-code', 'frameworks', 'postman']",649,True,0,1
Windows two usernames and user paths (normal and corrupted name) referencing to the same user folder content (gitlab and local machine),"<p>I have an issue where both on my Windows machine and a gitlab Windows runner where I have two usernames and valid user path (the &quot;base&quot;, and a &quot;corrupted&quot; one). For example, on my local machine:</p>
<pre><code>C:\Users&gt;dir /A

 Directory of C:\Users

10/23/2021  08:51 PM    &lt;DIR&gt;          .
10/23/2021  08:51 PM    &lt;DIR&gt;          ..
10/23/2021  11:27 PM    &lt;SYMLINKD&gt;     All Users [C:\ProgramData]
10/23/2021  11:27 PM    &lt;DIR&gt;          Default
10/23/2021  11:27 PM    &lt;JUNCTION&gt;     Default User [C:\Users\Default]
10/24/2021  12:13 AM               174 desktop.ini
08/22/2022  03:58 PM    &lt;DIR&gt;          J.S.E
10/23/2021  08:35 PM    &lt;DIR&gt;          Public
               1 File(s)            174 bytes
               7 Dir(s)  220,413,632,512 bytes free
</code></pre>
<p>but I can do both:</p>
<pre><code>C:\Users&gt;cd C:\Users\J.S.E

C:\Users\J.S.E&gt;
</code></pre>
<p>and a &quot;corrupted&quot;</p>
<pre><code>C:\Users&gt;cd C:\Users\JS2896~1.E

C:\Users\JS2896~1.E&gt;
</code></pre>
<p>both these paths point to the same folder content, but I can't figure out where this <code>JS2896~1.E</code> comes from.</p>
<p>I noticed this issue while doing some unit testing in python:</p>
<p>I would have a script with a section similar to:</p>
<pre><code>PID_SYNC_FILEPATH = pathlib.Path(tempfile.gettempdir()) / PID_SYNC_FILENAME
</code></pre>
<p>That would use that path to create a file. File found at:</p>
<pre><code>C:\\Users\\J.S.E\\AppData\\Local\\Temp\\test_kernel_pid
</code></pre>
<p>But when doing checks on the file content during tests (pytest), I would create the path in a similar way but I would then run into (notice the corrupted user name):</p>
<pre><code> FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\JS2896~1.E\\AppData\\Local\\Temp\\test_kernel_pid'
</code></pre>
<p><strong>Basically the issue is: both paths are valid (ex: can be processed with cd in the shell of with pathlib in python), but sometimes are not interpreted as equivalent, causing issues. Anyone knows what is up with that &quot;corrupted username path&quot;</strong></p>
<p>Note: same issue with gitlab Windows runners: two users, runner10 -&gt; <code>C:\\Users\\runner10</code> and RU4A94~1 -&gt; <code>C:\\Users\\RU4A94~1</code></p>
",https://stackoverflow.com/questions/73451079/windows-two-usernames-and-user-paths-normal-and-corrupted-name-referencing-to,"['python-3.x', 'windows', 'file', 'path']",21,True,0,1
replace ILogger&lt;T&gt; in servicecollection for integration tests,"<p>I have some integration tests and for logging we used</p>
<pre><code>serviceCollection.AddLogging() 
</code></pre>
<p>now we need to test that some info is logged in the dependency services where the injected services are ILogger</p>
<p>All the examples I found are for Mock&lt;ILogger&gt;.Object injected directly in the constructor. But that does not apply to me since the logger is for a dependency service and not the constructed one.</p>
<p>Is there an example on how to replace ILogger or ILoggerFactory for unit testing in ServiceCollection.</p>
<p>Edit: how the unit tests look like</p>
<pre><code>var serviceCollection = new ServiceCollection().AddLogging();
....
serviceCollection.Replace(ServiceDescriptor.Singleton&lt;IDependecyService&gt;, IDependecyService, _ =&gt; mockService.Object);
....
var serviceProvider = serviceCollection.BuildServiceProvider();
var sut = new Sut(serviceProvider.GetService&lt;IService&gt;(), ....);
</code></pre>
<p>The sut does not have any logging injected</p>
<p>IService needs to be injected the IDependecyService</p>
<p>IDependecyService need to be injected the ILogger
and this logger I need to mock.</p>
<p>Like I already said the serviceCollection has the ILogger&lt;&gt; and IFactoryLogger but I do not know how to replace them in order to give my mock of ILogger</p>
<p>This is just an example but there are other services with their own ILogger but I need to mock for now only the ILogger the other ILogger&lt;&gt; should remain as AddLogging has done it.</p>
",https://stackoverflow.com/questions/73526730/replace-iloggert-in-servicecollection-for-integration-tests,"['c#', 'integration-testing']",357,True,0,1
Cannot Send emails via SES:SendEmail from AWS Staging account but can send emails via ses:SendEmail for AWS Development account,"<p>We need to be able to send email via SES whenever there are daily failures in our data. We deploy our code from Dev (AWS DEV) to Staging (AWS Stage) and from Staging (AWS Stage) to Production once unit and SA testing is done (Note: Account Id's are fictional)</p>
<blockquote>
<p>When unit testing in AWS Development, <em>we can send emails via SES
without any issues</em>. However, when we try to do the same testing via
AWS Staging, we get this error:</p>
</blockquote>
<pre><code>User `arn:aws:sts::98756432117:assumed-role/Lambda-S3-Dynamo-glue/stage-smb-daily-email-log-fails' is not authorized to perform `ses:SendEmail' on resource `arn:aws:ses:us-west-2:123456789012:identity/dev
</code></pre>
<p>We have the AWSAmazonSESFullAccess policy already added to the AWS Dev, Prod, and Staging Lambda-S3-Dynamo-Glue roles too.</p>
<blockquote>
<p>The Trusted Relationship entity <em>Lambda-S3-Dynamo-Glue</em> role for the AWS DEV  and the <em>Lambda-S3-Dynamo-glue</em>  role for AWS Stage are both set to AWS production's Lambda-S3-Dynamo-Glue role:</p>
</blockquote>
<pre><code>{
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
    {
        &quot;Effect&quot;: &quot;Allow&quot;,
        &quot;Principal&quot;: {
            &quot;Service&quot;: &quot;lambda.amazonaws.com&quot;,
            &quot;AWS&quot;: &quot;arn:aws:iam::123456789012:role/Lambda-S3-Dynamo-Glue&quot;
        },
        &quot;Action&quot;: &quot;sts:AssumeRole&quot;
    }
]
</code></pre>
<p>}</p>
<blockquote>
<p>In production, the trusted relationship entity for its <em>Lambda-S3-Dynamo-Glue</em> is set to:</p>
</blockquote>
<pre><code>{
&quot;Version&quot;: &quot;2012-10-17&quot;,
&quot;Statement&quot;: [
    {
        &quot;Sid&quot;: &quot;AllowProdResourceToUse&quot;,
        &quot;Effect&quot;: &quot;Allow&quot;,
        &quot;Principal&quot;: {
            &quot;Service&quot;: &quot;lambda.amazonaws.com&quot;
        },
        &quot;Action&quot;: &quot;sts:AssumeRole&quot;
    },
    {
        &quot;Sid&quot;: &quot;AllowDevResourceToUse&quot;,
        &quot;Effect&quot;: &quot;Allow&quot;,
        &quot;Principal&quot;: {
            &quot;AWS&quot;: [
                &quot;arn:aws:iam::743074301111:role/Lambda-S3-Dynamo-Glue&quot;,
                &quot;arn:aws:iam::743074301111:user/lwabanski&quot;
            ]
        },
        &quot;Action&quot;: &quot;sts:AssumeRole&quot;
    },
    {
        &quot;Sid&quot;: &quot;AllowStageResourceToUse&quot;,
        &quot;Effect&quot;: &quot;Allow&quot;,
        &quot;Principal&quot;: {
            &quot;AWS&quot;: [
                &quot;arn:aws:iam::98756432117:role/Lambda-S3-Dynamo-glue&quot;,
                &quot;arn:aws:iam::98756432117:user/tvasquez&quot;
            ]
        },
        &quot;Action&quot;: &quot;sts:AssumeRole&quot;
    }
]
</code></pre>
<p>}</p>
<p>This is supposed to allow AWS Stage and AWS Dev to use Production's role in order to send email via SES including other actions.
Thanks for any helpful suggestion and comments.</p>
",https://stackoverflow.com/questions/72902132/cannot-send-emails-via-sessendemail-from-aws-staging-account-but-can-send-email,"['aws-lambda', 'amazon-iam', 'amazon-ses']",98,False,0,0
Make all EF Core model properties virtual for mocking in unit tests with Moq and xUnit?,"<p>I am using the <a href=""https://learn.microsoft.com/en-us/ef/core/testing/choosing-a-testing-strategy#repository-pattern"" rel=""nofollow noreferrer"">repository pattern</a> as suggested by the documentation for unit testing in EF Core. I have reached a point in my code where I am not able to fully test a method properly as a result of doing operations on the models from EF Core and not the DB Context.</p>
<p>An example of what I mean is below:</p>
<p><strong>Code to be tested</strong>:</p>
<pre><code>    private static void AddToUserScore(Members member)
    {
        var basePoints = 2;

        if (member.HintAsked)
        {
            basePoints--;
            member.HintAsked = false;
        }

        if (member.LocationHintAsked)
        {
            basePoints--;
            member.LocationHintAsked = false;
        }

        member.UserScore += basePoints;
    }
</code></pre>
<p><strong>EF Core Context Model itself:</strong></p>
<pre><code>public class Members
{
    public int MemberId { get; set; }
    public int AppId { get; set; }
    public string Username { get; set; }
    public int UserScore { get; set; }
    public string QuestionIds { get; set; }
    public int CurrentQuestionNumber { get; set; }
    public int LocationId { get; set; }
    public bool HintAsked { get; set; }
    public bool LocationHintAsked { get; set; }
}
</code></pre>
<p><strong>Unit test sample:</strong></p>
<pre><code> var fakeMemberMock = Fixture.Create&lt;Mock&lt;Members&gt;&gt;();
 fakeMemberMock.SetupSet(members =&gt; members.HintAsked = false);
 fakeMemberMock.VerifyGet(members =&gt; members.HintAsked, Times.Exactly(1));
</code></pre>
<p>Since none of my model's properties are virtual, this will result in an error at runtime.</p>
<p>I want to know if there is any reason I should <strong>not</strong> make my EF Core models all virtual for
this purpose.</p>
<p>I am not to sure of any sideffects this may have with interaction with my database or any pros and cons of doing this. I know virtual is generally placed on navigational properties but i do not know wether doing this on normal properties is a good idea or not.</p>
<p>Feel free to mention another method of going about what I am attempting that would be simpler.</p>
<p>Thanks in advance.</p>
",https://stackoverflow.com/questions/71517076/make-all-ef-core-model-properties-virtual-for-mocking-in-unit-tests-with-moq-and,"['c#', 'asp.net', 'entity-framework', 'unit-testing', 'moq']",387,True,0,1
verify Dapr service invocation in a unit test,"<p>How can I write a unit test that verifies a Dapr service was invoked (<a href=""https://docs.dapr.io/developing-applications/building-blocks/service-invocation/service-invocation-overview/"" rel=""nofollow noreferrer"">Service invocation</a>) when I'm using the <code>InvokeMethodAsync</code> method that takes in the <code>HttpMethod</code>, <code>appId</code>, <code>methodName</code>, <code>TRequest data</code> and <code>CancellationToken</code> (<a href=""https://learn.microsoft.com/en-us/dotnet/architecture/dapr-for-net-developers/getting-started#:%7E:text=open%20the%20index.cshtml.cs%20file%20in%20the%20pages%20folder%2C%20and%20replace%20its%20contents%20with%20the%20following%20code%3A"" rel=""nofollow noreferrer"">the one used in this sample?</a>)</p>
<p><em>usage:</em></p>
<pre class=""lang-cs prettyprint-override""><code>await _daprClient.InvokeMethodAsync&lt;IEnumerable&lt;WeatherForecast&gt;&gt;(
            HttpMethod.Get, &quot;MyBackEnd&quot;, &quot;weatherforecast&quot;);
</code></pre>
<p><em>test code:</em></p>
<pre class=""lang-cs prettyprint-override""><code>[TestMethod(&quot;MyFrontEnd should call weatherforecast endpoint on MyBackEnd service&quot;)]
public async Task TestMethod1()
{
    //arrange
    var daprClientMock = new Mock&lt;DaprClient&gt;();
    var weatherForecastController = 
        new WeatherForecastController(Mock.Of&lt;ILogger&lt;weatherForecastController&gt;&gt;(), daprClientMock.Object);

    //act
    var forecasts = await weatherForecastController.Get();

    //assert
    daprClientMock.Verify(daprClient =&gt;
        daprClient.InvokeMethodAsync&lt;IEnumerable&lt;string&gt;&gt;(HttpMethod.Get
            , &quot;MyBackEnd&quot;, &quot;weatherforecast&quot;, default(CancellationToken))
        , Times.Once());
}
</code></pre>
<p><em>library method source:</em></p>
<pre class=""lang-cs prettyprint-override""><code>public abstract class DaprClient : IDisposable
{
    //snippet of method I'm invoking
    public Task&lt;TResponse&gt; InvokeMethodAsync&lt;TRequest, TResponse&gt;(HttpMethod httpMethod
        , string appId, string methodName, TRequest data
        , CancellationToken cancellationToken = default(CancellationToken))
    {
        HttpRequestMessage request = CreateInvokeMethodRequest(httpMethod
            , appId, methodName, data);
        return InvokeMethodAsync&lt;TResponse&gt;(request, cancellationToken);
    }
}
</code></pre>
<p><a href=""https://github.com/dapr/dotnet-sdk/blob/master/src/Dapr.Client/DaprClient.cs#L381"" rel=""nofollow noreferrer"">source</a></p>
<p><em>error message when running my current test:</em></p>
<blockquote>
<p>Test method MyFrontEnd.BlahControllerTests.TestMethod1 threw exception:
System.NotSupportedException: Unsupported expression: daprClient =&gt; daprClient.InvokeMethodAsync&lt;IEnumerable&gt;(HttpMethod.Get, &quot;MyBackEnd&quot;, &quot;weatherforecast&quot;, CancellationToken)
Non-overridable members (here: DaprClient.InvokeMethodAsync) may not be used in setup / verification expressions.</p>
</blockquote>
<hr />
<h3>My research/thinking</h3>
<p>This is something I would want to test right?  Service invocation verification is a valid use case when unit testing, right?</p>
<p>Assuming that is correct, the <a href=""https://github.com/dapr/dotnet-sdk/blob/master/src/Dapr.Client/DaprClient.cs"" rel=""nofollow noreferrer"">DaprClient</a> is an <code>abstract</code> class (ok, I guess that works) but the method I'm calling isn't.</p>
<p>I'm guessing I have to call the abstract version of <a href=""https://github.com/dapr/dotnet-sdk/blob/291f73758d9231e72198c124c6286643fc8795df/src/Dapr.Client/DaprClient.cs#L356"" rel=""nofollow noreferrer"">InvokeMethodAsync</a> then?  And then I should create my own method that does what the above code is doing so I don't create any DRY violations ⚠️?</p>
<p>But when I look into <a href=""https://github.com/dapr/dotnet-sdk/blob/master/src/Dapr.Client/DaprClient.cs#L307"" rel=""nofollow noreferrer"">CreateInvokeMethodRequest</a>, that's <code>abstract</code> so how the heck does this work then? 🤔</p>
",https://stackoverflow.com/questions/72267436/verify-dapr-service-invocation-in-a-unit-test,"['c#', 'unit-testing', 'moq', 'dapr']",732,True,0,2
How to mock an ATL COM object in googletest unit tests,"<p>I am working on a legacy project that makes massive use of ATL COM objects. The task is to extend the unit testing (googletest) by the capability of mocking COM objects, or the smart pointers accessing them. To illustrate, I created a small example project with a single <code>ATL simple object</code>, which only exports the method <code>methodB</code> (part of idl file):</p>
<pre class=""lang-cpp prettyprint-override""><code>
    object,
    uuid(070a4996-d9cf-4434-a823-3ea9043de394),
    dual,
    nonextensible,
    pointer_default(unique)
]
interface IMyATLObj : IDispatch
{
    [id(1)] HRESULT methodB([in] SHORT in, [out, retval] SHORT *out);
};
</code></pre>
<p>The objects are accessed using smart pointers of base type <code>_com_ptr_t</code>, such as in this example:</p>
<pre><code>#include &lt;comdef.h&gt;
#include &quot;.../ATLExample_i.h&quot;

_COM_SMARTPTR_TYPEDEF(IMyATLObj, __uuidof(IMyATLObj));

IMyATLObjPtr create() {
    IMyATLObjPtr objPtr;
    objPtr.CreateInstance(__uuidof(MyATLObj));
        
    return objPtr;
}

void use(IMyATLObjPtr objPtr) {
    short val = 0;

    objPtr-&gt;methodB(1, &amp;val);

    std::cout &lt;&lt; val &lt;&lt; std::endl;
}
</code></pre>
<p>Now the question is how I can test the function <code>use(...)</code> without actually creating a COM object. Of course I can create a wrapper class as a facade to all COM interactions that I can mock as usual, e.g.:</p>
<pre><code>class MyObjFacade {
public:
  MyObjFacade() {
    objPtr.CreateInstance(__uuidof(MyATLObj));
  }

  virtual short methodB(short in) {
    short val;
    if (objPtr-&gt;methodB(in, &amp;val) == S_OK)
      return val;
    else
      throw;
  }

  IMyATLObjPtr objPtr;
};

class MYObjMock : public MyObjFacade {
public: 
  MOCK_METHOD1(methodB, short(short in));
};
</code></pre>
<hr />
<pre><code>    void use(MyObjFacade *objPtr) {
      short val = 0;

      val = objPtr-&gt;methodB(1);

      std::cout &lt;&lt; val &lt;&lt; std::endl &lt;&lt; std::flush;
    }
</code></pre>
<hr />
<pre><code>    TEST_F(COMMockTest, Test1) {
      MYObjMock mock;

      EXPECT_CALL(mock, methodB(_)).WillOnce(Return(43));

      use(&amp;mock);
    }
</code></pre>
<p>But that would obviously leave me with lots of boiler plate code and (possibly) unnessessary changes - this solution would probably not be well adopted. I am looking for an elegant solution that, for example, either introduces a mock object into <code>IMyATLObjPtr</code> mocks the pointer object itself. However, I don't really know where to start because all the available interfaces are generated by ATL and are not easily accessible.</p>
<p>Any ideas?</p>
",https://stackoverflow.com/questions/74446731/how-to-mock-an-atl-com-object-in-googletest-unit-tests,"['c++', 'com', 'googletest', 'atl', 'googlemock']",67,False,0,0
Integration/Widget test using Stacked Architecture by FilledStacks which is based od get_it,"<p>In my project I use Stacked Architecture with <a href=""https://www.filledstacks.com/post/flutter-and-provider-architecture-using-stacked/#inversion-of-control"" rel=""nofollow noreferrer"">Inversion of Control</a>. In Unit Testing it works perfectly fine but when it comes to Widget/Integration Testing I am getting an error right at the start.</p>
<p>My code:</p>
<pre><code>import 'package:flutter_test/flutter_test.dart';
import 'package:my_project/ui/start_up/startup_viewmodel.dart';

void main() {
  testWidgets(
    &quot;Simple widget test&quot;,
    (WidgetTester tester) async {
      await tester.pumpWidget(StartUpView());
    },
  );
}
</code></pre>
<p>The error that I get:</p>
<pre><code>══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following assertion was thrown building StartUpView:
Object/factory with  type AuthService is not registered inside GetIt.
(Did you accidentally do GetIt sl=GetIt.instance(); instead of GetIt sl=GetIt.instance;
Did you forget to register it?)
'package:get_it/get_it_impl.dart':
Failed assertion: line 372 pos 7: 'instanceFactory != null'

The relevant error-causing widget was:
  StartUpView
  StartUpView:file:path/my_project/lib/app/app.router.dart:87:37
</code></pre>
<p>From the error log I see that it is actually the <strong>AuthService</strong> which is causing the problem. The class is registered as a <strong>LazySingleton</strong> in <em>app.dart</em> and I realized that the program really crashes in <em>startup_viewmodel.dart</em>:</p>
<pre><code>  final _authService = locator&lt;AuthService&gt;();
  final _navigationService = locator&lt;NavigationService&gt;();
</code></pre>
<p>(Switching this to lines cause to replace <strong>AuthService</strong> with <strong>NavigationService</strong> in error message).</p>
<p>Suggestions about <em>get_it</em> didn't help me much because in all of the files &quot;get_it&quot; didn't comes once (even in my <em>pubspec.yaml</em>). I also tried solutions from <a href=""https://stackoverflow.com/questions/62548585/how-to-use-get-it-flutter-dependency-injection-in-the-widget-test"">this thread</a> but it didn't resolve the issue.</p>
<p>The <em>app.router.dart</em> is a generated code based on <em>app.dart</em>. In its 87. line there is:</p>
<pre><code>    StartUpView: (data) {
      return MaterialPageRoute&lt;dynamic&gt;(
        builder: (context) =&gt; const StartUpView(),
        settings: data,
      );
    },
</code></pre>
<p>Lastly I tried using <em>integration_test_driver</em> and running test through <em>flutter test</em> command with no improvement.</p>
<p>So the simple question is...</p>
<h2>How to Widget Test using Stacked Architecture?</h2>
<p>Any help would be greatly appreciated.</p>
",https://stackoverflow.com/questions/73078693/integration-widget-test-using-stacked-architecture-by-filledstacks-which-is-base,"['flutter', 'dart', 'testing', 'integration-testing', 'stacked']",359,False,0,1
Unit test Google tag manager Initialization and events,"<p>I am trying to Unit test Google tag manager code in React project. Following is what I want to test precisely:</p>
<ol>
<li>If Google tag manager is initialized with given properties</li>
<li>Check if events are getting fired fine and are being pushed to DataLayer in window object</li>
</ol>
<p>Sample component with gtm initialization in useEffect:</p>
<pre><code> useEffect(() =&gt; {
    if (!isLoading) {
      try {
        let dataLayer = {
          userProject: 'project-ui'
        }
        if (typeof data.id !== 'undefined') {
          dataLayer = {
            userId: data.id,
            userProject: 'project-ui'
          }
        }

        const tagManagerArgs = {
          gtmId: process.env.REACT_APP_GTAG_TRACKING,
          dataLayer
        }

        TagManager.initialize(tagManagerArgs)
      } catch (e) {/**/ }
    }
}, [isLoading])
</code></pre>
<p>I am trying to cover mutation of <code>if (typeof data.id !== 'undefined')</code> as well is <code>!isLoading</code> here. This is the exact goal.</p>
<p>please note data is coming from react-query:</p>
<pre><code>const { isLoading, data } = useQuery([USER_TRACKING_ID], () =&gt;
getLoggedInUserProfile())
</code></pre>
<p>Code I have written so far for Unit Testing:</p>
<pre><code>  test(&quot;Ga loads&quot;, async () =&gt; {
    window.dataLayer = {
      push: jest.fn().mockImplementation(config =&gt; {
        config.eventCallback()
      }),
    }

    render(
      &lt;QueryClientProvider client={queryClient}&gt;
        &lt;BrowserRouter&gt;
          &lt;Provider store={store}&gt;
            &lt;MainContainer /&gt;
          &lt;/Provider&gt;
        &lt;/BrowserRouter&gt;
      &lt;/QueryClientProvider&gt;
    )
    const { result, waitFor } = renderHook(() =&gt; useCustomHook(), {
      wrapper: createWrapper()
    })
  
    await waitFor(() =&gt; result.current.isSuccess)

    console.log('test data: ', result.current)
    console.log('data layer data: ', window.dataLayer) // this is throwing undefined
    const eventSpy  = jest.spyOn(TagManager, 'initialize')


    expect(result.current.data).toEqual({
      &quot;employeeId&quot;: &quot;797979878&quot;,
      &quot;name&quot;: &quot;UserFirstName lastName&quot;,
      &quot;userEmail&quot;: &quot;UserFirstName.lastName@mywebsite.com&quot;,
      &quot;loginTime&quot;: 1652073402000
    })
    expect(window.dataLayer.push).toHaveBeenCalled()
    // expect(eventSpy).toHaveBeenCalled()
  })
</code></pre>
<p>Sample code for one of the dataLayer push I want to test:</p>
<pre><code>    const messageBoardhandler = () =&gt; {
    try {
      dataLayer.push({
        event: 'NotificationBoard',
        userId: queryClient.getQueryData('USER_TRACKING_ID').id,
        category: 'MessageBoard',
        action: 'NotificationClicked',
        label: 'NotificationIcon',
        value: ''
      })
    } catch (e) { /* */ }
    dispatch(appCategoryAction.setAppCategoryFlyer(false))
    if (!pinMessageBoard) {
      dispatch(messageBoardActions.setMessageBoardChatFlyer(true))
    }
  }
</code></pre>
<p>I want to understand first of as I tried to mock the react-query for data, how shall I render the component and in what order, and how can I get this initialization to be tested.</p>
<p>I tried taking multiple approach:</p>
<ol>
<li>Tried directly asserting on Data Layer array from window which turns out is undefined.</li>
<li>Tried using jest mock to import <a href=""https://www.npmjs.com/package/react-gtm-module"" rel=""nofollow noreferrer"">TagManager library</a> that I am using to load gtag and mock TagManager.initialize and no luck.</li>
</ol>
",https://stackoverflow.com/questions/72169373/unit-test-google-tag-manager-initialization-and-events,"['reactjs', 'unit-testing', 'jestjs', 'react-testing-library', 'react-query']",994,False,0,0
Don&#39;t understand problem with nested Rust macro,"<p>I'm just getting going with Rust, and am trying to smooth over a couple inconveniences using macros. The first is that the derive Defaults macros don't support const functions so they don't support static objects. For this, I got help and adapted this macro I was given, it works well:</p>
<pre><code>#[macro_export]
macro_rules! define_struct_with_const_defaults {
  ($v:vis struct $name:ident { $($f_name:ident: $f_type:ty = $f_default:expr),* $(,)? }) =&gt; {
      #[derive(Clone,Copy)]
      $v struct $name {
          $(
              $f_name: $f_type,
          )*
      }
      
      impl $name {
          pub const fn new() -&gt; $name {
              $name {
                  $(
                      $f_name: $f_default,
                  )*
              }
          }
      }     
  }
}
</code></pre>
<p>So the next thing I wanted to do was get painless structure access for unit testing with python going. So I thought I could do something like this:</p>
<pre><code>use pyo3::prelude::*;

#[macro_export]
macro_rules! define_struct_with_const_defaults {
  ($v:vis struct $name:ident { $($f_name:ident: $f_type:ty = $f_default:expr),* $(,)? }) =&gt; {
      #[derive(Clone,Copy)]
      #[pyclass]
      $v struct $name {
          $(
              #[pyo3(get, set)] $f_name: $f_type,
          )*
      }
      
      impl $name {
          pub const fn new() -&gt; $name {
              $name {
                  $(
                      $f_name: $f_default,
                  )*
              }
          }
      }
  }
}
</code></pre>
<p>But that doesn't work, the complaint is &quot;cannot find attribute <code>pyclass</code> in this scope&quot;</p>
<p>On the other hand, if I do this, it works:</p>
<pre><code>use pyo3::prelude::*;

#[pyclass]
struct bar {
  baz: i32,
}
</code></pre>
<p>This is beyond my level of understanding. It seems to be related to nesting macros, I'm wondering whether it has something to do with order of evaluation.</p>
<p>Eventually, I'd like to conditionally compile the pyo3 stuff with a config macro, depending on whether I'm in a unit test environment, but I can't even get this far ...</p>
<p>Any help would be appreciated in understanding what is going on here.</p>
",https://stackoverflow.com/questions/74439306/dont-understand-problem-with-nested-rust-macro,"['rust', 'macros']",60,True,0,1
Unit Testing - How to build tests around domain entities with lots of encapsulation and many internal states,"<p>Admittedly, very new to Unit Testing right now but I'm wanting to make sure I don't end up with a testing project that ends up being a nightmare to maintain.</p>
<p>The big challenge for me right now is how to test behaviors of an entity when it requires the object to be in a certain state, which is achieved through any number of prior method calls.  There are no public setters to properties.  I am messing around with SpecimenBuilders in AutoFixture, and have a &quot;default state&quot; object builder that creates the entity using its public constructor, but then I get stuck.</p>
<p>Ideally, I'd like to build off this concept and have other builders that create that same entity type but in other states beyond the default, using the SpecimenBuilder that creates the entity in the default state without having to repeat code, and then calling the method to get the entity to next state.  Or maybe I'm off track completely here on what I'm thinking.  Perhaps I need to just create custom Object Mothers for all this.</p>
<p>I'm open to any suggestions on the best way to approach things.  Thanks so much.</p>
",https://stackoverflow.com/questions/72144471/unit-testing-how-to-build-tests-around-domain-entities-with-lots-of-encapsulat,"['c#', 'unit-testing', '.net-5', 'xunit', 'autofixture']",319,False,2,0
I&#39;m switching from Vuex to Pinia in Vue 3 and my unit tests are now failing. I can&#39;t seem to be able to create custom mock actions,"<p>Here's a simple example on the forgot password reset page of my app, I would want to bypass the server side and just have the password reset to succeed on click so I would write a test and use the custom test store like so:</p>
<pre><code>const customStore = {
  state() {
    return {
      Authentication: {
        passwordResetSuccess: false,
      },
    };
  },
  mutations: {
    SET_RESET_PASSWORD_SUCCESS(state) {
      state.Authentication.passwordResetSuccess = true;
    },
  },
  actions: {
    forgotPasswordResetPassword() {
      this.commit('SET_RESET_PASSWORD_SUCCESS');
    },
  },
};
</code></pre>
<p>Then I could include the custom store in my beforeEach() and it worked great. I've tried everything I can think of to get this to work with pinia, but it doesn't seem to work.</p>
<p>I'm using jest along with vue/test-utils.</p>
<p>I basically tried just creating the test pinia store, but I can't figure out how to get the component to use the custom test store.</p>
<pre><code>const useCustomStore = defineStore('AuthenticationStore', {
  state: () =&gt; ({
    passwordResetSuccess: false,
  }),
  actions: {
    forgotPasswordResetPassword() {
      this.passwordResetSuccess = true;
    },
  },
});


const authenticationStore = useCustomStore();
</code></pre>
<p>I can't directly add it as a plugin because it can't find an active instance of pinia.</p>
<p>I went through this guide: <a href=""https://pinia.vuejs.org/cookbook/testing.html#unit-testing-a-store"" rel=""nofollow noreferrer"">https://pinia.vuejs.org/cookbook/testing.html#unit-testing-a-store</a></p>
<p>and I also tried using jest mock as described here: <a href=""https://stackoverflow.com/a/71407557/4697639"">https://stackoverflow.com/a/71407557/4697639</a></p>
<p>But it still failed.</p>
<p>If anyone has any idea how to create a custom store that can be used by the component and actually hits the custom actions, I could really use some help figuring this out. Thank you!!</p>
",https://stackoverflow.com/questions/74482359/im-switching-from-vuex-to-pinia-in-vue-3-and-my-unit-tests-are-now-failing-i-c,"['vue.js', 'unit-testing', 'vuejs3', 'vuex', 'pinia']",434,True,1,1
SignalR HubContext Clients is null after running Unit test on it with Mock client proxy,"<p>I have the following 2 files, one, which is a <code>HubController</code> class and the other, which is a Unit test class.</p>
<p><code>HubController.cs</code>:</p>
<pre><code>using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace SignalR.Controllers
{
    [Route(&quot;api/[controller]&quot;)]
    [ApiController]
    public class HubController : ControllerBase
    {
        private readonly IHubContext&lt;HothHub&gt; _hubContext;

        public HubController(IHubContext&lt;HothHub&gt; hubContext)
        {
            _hubContext = hubContext;
        }

        [HttpPost(&quot;{id}&quot;)]  // POST /api/values/xyz
        public async Task PostAsync(string id)
        {
            Trace.TraceInformation(&quot;update Post()&quot;);

            // Make a call to the client based on the connection ID and call client method
            await _hubContext.Clients.Client(id).SendAsync(&quot;hubToClientUpdate&quot;);

            //return Ok();
        }
    }
}
</code></pre>
<p><code>Tests.cs</code>:</p>
<pre><code>using Xunit;
using Moq;
using System.Dynamic;
using SignalR;
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
using SignalR.Controllers;
using Microsoft.AspNet.SignalR.Hubs;
using System;

namespace TestSignalR
{
    public class Tests
    {
        [Fact]
        public async Task HubsAreMockableViaDynamic()
        {
            bool sendCalled = false;
            var mockClients = new Mock&lt;IHubCallerConnectionContext&lt;dynamic&gt;&gt;();
            // The IHubCallerConnectionContext interface is the proxy object with, which you invoke methods on the client
            dynamic all = new ExpandoObject();
            // This is the client proxy object where we define the method, which we will invoke on the client
            all.SendAsync = new Action&lt;string&gt;((method) =&gt;
            {
                sendCalled = true;
            });
            // Define the function that will be called on the client when HubController calls its PostAsync method
            // The test engine will call the PostAsync method in HubController, which in turn calls this method postAsync here
            mockClients.Setup(m =&gt; m.All).Returns((ExpandoObject)all);
            // Setting up the mock client so when the All property is called we return an instance of the Client proxy, which in this case
            // is the dynamic object all
            var hubContext = new Mock&lt;IHubContext&lt;MyHub&gt;&gt;();
            // Created a mock of the IHubContext object required by the HubController class
            hubContext.Setup(x =&gt; x.Clients).Returns(mockClients.Object as IHubClients);
            // Set up the mock of the IHubContext object so that when the Clients property is called, then the instance of the mock client
            // object is returned
            HubController hubController = new HubController(hubContext.Object);
            // Created an instance of the HubController class, which is needed to call the PostAsync function in it
            await hubController.PostAsync(&quot;id&quot;);
            Assert.True(sendCalled);
        }
    }
}
</code></pre>
<p>I also have a <code>MyHub.cs</code> file, which derives from the <code>Hub</code> class but this class doesn't contain anything useful for my test.</p>
<pre><code>using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace SignalR
{
    public class MyHub : Hub
    {
        public string GetConnectionId() =&gt; Context.ConnectionId;
    }
}
</code></pre>
<p>Now the issue I'm having is that when I either run a test on HubsAreMockableViaDynamic() or run a debug on it, it will return me the following error,
<a href=""https://i.stack.imgur.com/ZNI5V.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/ZNI5V.png"" alt=""hubContext Clients is null"" /></a></p>
<p>This test has come about after following the documentation from Microsoft here <a href=""https://learn.microsoft.com/en-us/aspnet/signalr/overview/testing-and-debugging/unit-testing-signalr-applications"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/signalr/overview/testing-and-debugging/unit-testing-signalr-applications</a>. Now I suspect the problem is with this line here, <code>hubContext.Setup(x =&gt; x.Clients).Returns(mockClients.Object as IHubClients);</code> in Tests.cs, which is causing the problem. Without the cast there is the following,</p>
<blockquote>
<p>Severity   Code    Description Project File    Line    Suppression State
Error   CS1503  Argument 1: cannot convert from 'Microsoft.AspNetCore.SignalR.IHubClients' to 'Microsoft.AspNetCore.SignalR.IHubClients'   TestSignalR C:\Sourcesafe\2023\Integration\WebhookBot\WebhookBot\TestSignalR\Tests.cs   38  Active</p>
</blockquote>
<p>I'm quite new to <code>SignalR</code> and <code>Mock</code> objects so I'm stuck as to why this isn't working after following the documentation from Microsoft. Is there anyone who could shed some light into why this issue is happening and how to resolve it please?
Thanks!</p>
",https://stackoverflow.com/questions/74275669/signalr-hubcontext-clients-is-null-after-running-unit-test-on-it-with-mock-clien,"['c#', 'unit-testing', 'signalr', 'xunit', 'signalr-hub']",33,False,1,0
NGXS : store.reset disables dispatchers in Jasmine unit tests,"<p>I am having trouble with an unexpected behavior while unit testing my NGXS store with Jasmine.</p>
<p>Here, I am trying to test the DeleteAlerts action :</p>
<pre><code>  @Action(DeleteAlerts)
  deleteAlerts(ctx: StateContext&lt;AlertStateModel&gt;, action: DeleteAlerts) {
    return this.alertService.deleteAlerts(action.alertIds).pipe(
      map(response =&gt; {
          if (response.ok) {
            action.alertIds.forEach(alertId =&gt; {
              ctx.setState(patch({
                alerts: removeItem&lt;UniqueAlert&gt;(alert =&gt; alert.alertIds.includes(alertId))
              }));
            });
          } else {
            throw new Error('Server failed to respond.');
          }
        }
      ));
  }
</code></pre>
<p>but the store must first be populated with dummy data.</p>
<p>I created this mock :</p>
<pre><code>  const alertsMock = new Alerts({
alerts: [new UniqueAlert({alertIds: ['test1']}),
  new UniqueAlert({alertIds: ['test2']}),
  new UniqueAlert({alertIds: ['test3']})]
  });
</code></pre>
<p>My store looks like this :</p>
<pre><code> export interface AlertStateModel {
  alerts: UniqueAlert[];
}
</code></pre>
<p>I then tried to populate the store with the mock :</p>
<pre><code>store.reset({alerts: alertsMock.alerts})
</code></pre>
<p>However, when I do this in my test, the <code>DeleteAlerts</code> action does not dispatch when calling <code>store.dispatch(new DeleteAlerts(alertIds))</code></p>
<p>Here is the part I do not understand : The action does dispatch when replacing the <code>store.reset</code> method with a <code>GetAlerts</code> dispatch, which is directed to load the alerts from a mocked service :</p>
<p>The GetAlerts action :</p>
<pre><code>  @Action(GetAlerts)
  public getAlerts(ctx: StateContext&lt;AlertStateModel&gt;) {
    return this.alertService.getAlerts().pipe(
      tap(fetchedAlerts =&gt; {
        ctx.setState({alerts: fetchedAlerts.alerts});
      })
    );
  }
</code></pre>
<p>This test passes :</p>
<pre><code>  it('should delete one alert from the store when DeleteAlerts is dispatched', () =&gt; {
    spyOn(alertService, 'getAlerts').and.returnValue(of(alertsMock));
    store.dispatch(new GetAlerts());
    spyOn(alertService, 'deleteAlerts').and.returnValue(of(new HttpResponse({status: 200})));
    store.dispatch(new DeleteAlerts(['test2']));
    store.selectOnce(AlertState).subscribe(data =&gt; {
      expect(data.alerts).toEqual(alertsMock.alerts.filter(alert =&gt; !alert.alertIds.includes('test2')));
    });
  });
});
</code></pre>
<p>This test does not :</p>
<pre><code>  it('should delete one alert from the store when DeleteAlerts is dispatched', () =&gt; {
    store.reset({alerts: alertsMock.alerts});
    spyOn(alertService, 'deleteAlerts').and.returnValue(of(new HttpResponse({status: 200})));
    store.dispatch(new DeleteAlerts(['test2']));
    store.selectOnce(AlertState).subscribe(data =&gt; {
      expect(data).toEqual(alertsMock.alerts.filter(alert =&gt; !alert.alertIds.includes('test2')));
    });
  });
</code></pre>
<p>On top of that, you might have noticed that my expectation is on <code>data</code>, rather than <code>data.alerts</code> on the non-functional test. This is another behavior I would like to understand, since the selector should return the state, which contains a nested <code>alerts</code> object.</p>
<p><strong>Why aren't the two tests equivalent, and why does the selector not return the expected object when using <code>store.reset</code> to populate the store ?</strong></p>
<p>Regarding why the <code>alertsMock</code> contains a nested <code>alerts</code> object ; that is the format of the data returned by the alertService.</p>
",https://stackoverflow.com/questions/72726207/ngxs-store-reset-disables-dispatchers-in-jasmine-unit-tests,"['angular', 'typescript', 'jasmine', 'state-management', 'ngxs']",231,False,1,1
Cmocka - should we all be creating one executable per test for isolating static variables?,"<h2>Failure</h2>
<p>Given the following cmocka test with a static variable in a dependency:</p>
<p><code>main.c</code></p>
<pre><code>#include &lt;stdarg.h&gt;
#include &lt;stddef.h&gt;
#include &lt;setjmp.h&gt;
#include &lt;cmocka.h&gt;
#include &quot;dependency.h&quot;

void test1(void** state) {
    increment();
    assert_int_equal(1, get_incrementer());
}

void test2(void** state) {
    increment();
    assert_int_equal(1, get_incrementer());
}

int main() {
    const struct CMUnitTest tests[] = {
        cmocka_unit_test(test1),
        cmocka_unit_test(test2),
    };
    return cmocka_run_group_tests(tests, NULL, NULL);
}
</code></pre>
<p><code>dependency.h</code></p>
<pre><code>void increment();
int get_incrementer();
</code></pre>
<p><code>dependency.c</code></p>
<pre><code>static int incrementer = 0;

void increment() {
    ++incrementer;
}

int get_incrementer() {
    return incrementer;
}
</code></pre>
<p>(compile with <code>gcc main.c dependency.c -lcmocka</code> and run)</p>
<p>I get the following output:</p>
<pre><code>[==========] Running 2 test(s).
[ RUN      ] test1
[       OK ] test1
[ RUN      ] test2
[  ERROR   ] --- 0x1 != 0x2
[   LINE   ] --- main.c:14: error: Failure!
[  FAILED  ] test2
[==========] 2 test(s) run.
[  PASSED  ] 1 test(s).
[  FAILED  ] 1 test(s), listed below:
[  FAILED  ] test2

 1 FAILED TEST(S)
</code></pre>
<p>This is because <code>incrementer</code> is not &quot;reset&quot; between each test.</p>
<p>This is just a minimal example to demonstrate a point. In reality, my dependency is deep down into the code which I'm calling in my test.</p>
<h2>Alternative to Just Make It Work</h2>
<p>But If I separate each test into its own executable with its own test group, I'm able to reset <code>incrementer</code> for each test as one would expect.</p>
<h2>Questions</h2>
<ul>
<li><em>Is the only way to achieve test isolation with cmocka to separate each test into its own executable?</em></li>
</ul>
<p>It shocked me when I found that this was happening. I'm new to C and C testing and I had always thought that test isolation was a critical part of a unit testing framework. It doesn't make sense to me why there would even be test groups to begin with, as most of the time you will be testing code with dependencies where a static variable is used somewhere, and would therefore be making one executable per test.</p>
",https://stackoverflow.com/questions/71118831/cmocka-should-we-all-be-creating-one-executable-per-test-for-isolating-static,"['c', 'unit-testing', 'static', 'cmocka']",359,True,1,1
Python Unit Test examples don&#39;t apply?,"<p>I am currently unit testing my Python Code. As I am only learning python (self taught) I started off with making a game - A custom game with no real use case just to have &quot;functional&quot; code.</p>
<p>A player has a limit of how many items they can carry in their inventory. So I have the following (note: there is more in player, but isn't needed for the rest of this case)</p>
<pre><code>class Player:
def __init__(self):
    self.inventory: list = []
    
def drop_item(self, index):
    self.inventory.pop(index)
    
</code></pre>
<p>My test case is as follows (importing unittest and Player)</p>
<pre><code>class TestPlayer(unittest.TestCase):

def test_drop_item(self):
    p = Player()
    p.inventory = [&quot;A&quot;, &quot;B&quot;]
    inv_len = len(p.inventory)
    print(f&quot;Player's currently holds {inv_len} item's&quot;)
    p.drop_item(1)
    self.assertIs(inv_len, 1, &quot;Passed&quot;)
</code></pre>
<p><em>I did run into the issue of drop_item freaking out because it didn't have a self case, hence why the test has the p = player() - this fixed it thought is this technically right?</em></p>
<p>I get the slight issue of:</p>
<pre><code>line X, in test_drop_item self.assertIs(inv_len, 1, &quot;Passed&quot;) 
AssertionError: 2 is not 1 : Passed
</code></pre>
<p>Where it should have popped &quot;B&quot; from the list just leaving [&quot;A&quot;] in the list</p>
<p>Now to pivot to the example that I had found, that does work:</p>
<pre><code>def add(x, y):
&quot;&quot;&quot;Add Function&quot;&quot;&quot;
return x + y

class TestAdd(unittest.TestCase):
    def test_add(self):
        result = add(10, 5)
        self.assertEqual(result, 15)
</code></pre>
<p>I know they are different in terms of what they are trying to test however I feel like there &quot;isn't anything wrong&quot; in what I currently have. I am missing something here? Could it be to do with something how my pop works?</p>
",https://stackoverflow.com/questions/73678656/python-unit-test-examples-dont-apply,"['python', 'unit-testing', 'python-3.10']",35,False,1,1
"Roslyn code fix runs an extra time, unit tests fail - too many iterations","<p>I'm working on a somewhat 'Hello World' type analyzer+code fix with the C# Roslyn API, and running into a test failure which I don't understand and haven't had much luck in tracking down any additional information on thus far.</p>
<p>I have a suite of tests covering the typical basic use cases for the analyzer and its code fix:</p>
<ul>
<li>Various cases which do not trigger the diagnostic
<ul>
<li>These tests all pass just fine</li>
</ul>
</li>
<li>Various cases which should trigger the diagnostic, and the available code fix, and the result of the code fix
<ul>
<li>These tests all fail only because of performing 1 too many iterations - the actual fix does generate the expected/correct code</li>
</ul>
</li>
</ul>
<p>Here's one of the failing tests:</p>
<pre class=""lang-cs prettyprint-override""><code>[Test]
public async Task ClassGenericTaskReturnTypeMethodWithNoCancellationTokenShouldTriggerDiagnosticWithCorrectCodeFix()
{
    var test = @&quot;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Foo
    {   
        public Task&lt;int&gt; Bar(int baz)
        {
            throw new NotImplementedException(&quot;&quot;Not real code&quot;&quot;);
        }
    }
}
&quot;;

    var fixtest = @&quot;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Threading;

namespace ConsoleApplication1
{
    class Foo
    {   
        public Task&lt;int&gt; Bar(int baz, CancellationToken cancellationToken)
        {
            throw new NotImplementedException(&quot;&quot;Not real code&quot;&quot;);
        }
    }
}
&quot;;

    var expected = VerifyCS.Diagnostic(AsyncMissingCancellationTokenAnalyzer.DiagnosticId)
                        .WithLocation(13, 3)
                        .WithArguments(&quot;Bar&quot;, &quot;Foo&quot;);
    await VerifyCS.VerifyCodeFixAsync(test, expected, fixtest);
}
</code></pre>
<p>This test fails with these messages (stack traces omitted):</p>
<pre><code>Multiple failures or warnings in test:
  1)   Context: Iterative code fix application
Expected '1' iterations but found '2' iterations.
  Expected: 1
  But was:  2

  2)   Context: Fix all in document
Expected '1' iterations but found '2' iterations.
  Expected: 1
  But was:  2
</code></pre>
<p>I have debugged the tests, and I can see that it is hitting my code fix code twice, but I don't know why that would be the case. Analyzer + code fix:</p>
<p>Analyzer:</p>
<pre class=""lang-cs prettyprint-override""><code>[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class AsyncMissingCancellationTokenAnalyzer : DiagnosticAnalyzer
{
    public const string DiagnosticId = &quot;AsyncCancellation1000&quot;;

    // You can change these strings in the Resources.resx file. If you do not want your analyzer to be localize-able, you can use regular strings for Title and MessageFormat.
    // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/Localizing%20Analyzers.md for more on localization
    private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.AnalyzerTitle), Resources.ResourceManager, typeof(Resources));
    private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.AnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources));
    private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.AnalyzerDescription), Resources.ResourceManager, typeof(Resources));
    private const string Category = &quot;Usage&quot;;

    private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);

    public override ImmutableArray&lt;DiagnosticDescriptor&gt; SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }

    public override void Initialize(AnalysisContext context)
    {
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
        context.EnableConcurrentExecution();

        // TODO: Consider registering other actions that act on syntax instead of or in addition to symbols
        // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/Analyzer%20Actions%20Semantics.md for more information
        context.RegisterSyntaxNodeAction(AnalyzeSymbol, SyntaxKind.MethodDeclaration);
    }

    private const string CancellationTokenFullName = &quot;System.Threading.CancellationToken&quot;;
    private const string TaskFullName = &quot;System.Threading.Tasks.Task&quot;;
    private const string GenericTaskFullName = &quot;System.Threading.Tasks.Task`1&quot;;
    private const string ValueTaskFullName = &quot;System.Threading.Tasks.ValueTask&quot;;
    private const string GenericValueTaskFullName = &quot;System.Threading.Tasks.ValueTask`1&quot;;

    private static void AnalyzeSymbol(SyntaxNodeAnalysisContext context)
    {
        var compilation = context.Compilation;
        var syntax = (MethodDeclarationSyntax)context.Node;

        // identify async (returning) methods
        var semanticReturnType = context.SemanticModel.GetTypeInfo(syntax.ReturnType);
        if (semanticReturnType.Type is INamedTypeSymbol namedReturnType)
        {
            if (namedReturnType.IsGenericType)
            {
                if (!SymbolEqualityComparer.Default.Equals(
                        namedReturnType.OriginalDefinition,
                        compilation.GetTypeByMetadataName(GenericTaskFullName)
                    )
                &amp;&amp; !SymbolEqualityComparer.Default.Equals(
                        namedReturnType.OriginalDefinition,
                        compilation.GetTypeByMetadataName(
                            GenericValueTaskFullName
                        )
                    ))
                {
                    // Return type is some generic but not Task&lt;T&gt; or ValueTask&lt;T&gt;
                    // this is not an async method - code is compliant
                    return;
                }
            }
            else if (!SymbolEqualityComparer.Default.Equals(
                        namedReturnType,
                        compilation.GetTypeByMetadataName(TaskFullName)
                    )
                &amp;&amp; !SymbolEqualityComparer.Default.Equals(
                        namedReturnType,
                        compilation.GetTypeByMetadataName(ValueTaskFullName)
                    ))
            {
                // Return type is something non-generic but not Task or ValueTask
                // this is not an async method - code is compliant
                return;
            }
        }

        var cancellationTokenTypeSymbol = compilation.GetTypeByMetadataName(CancellationTokenFullName);
        foreach (var parameterSyntax in syntax.ParameterList.Parameters)
        {
            var parameterType =  context.SemanticModel.GetTypeInfo(parameterSyntax.Type);
            if (SymbolEqualityComparer.Default.Equals(parameterType.Type, cancellationTokenTypeSymbol))
            {
                // found a CancellationToken parameter - code is compliant
                return;
            }
        }
        
        // For all such symbols, produce a diagnostic.
        var containingType = (TypeDeclarationSyntax)syntax.Parent;
        var diagnostic = Diagnostic.Create(
            Rule,
            syntax.GetLocation(),
            syntax.Identifier.ValueText,
            containingType.Identifier.ValueText);

        context.ReportDiagnostic(diagnostic);
    }
}
</code></pre>
<p>Code Fix:</p>
<pre class=""lang-cs prettyprint-override""><code>[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AsyncMissingCancellationTokenCodeFixProvider)), Shared]
public class AsyncMissingCancellationTokenCodeFixProvider : CodeFixProvider
{
    public sealed override ImmutableArray&lt;string&gt; FixableDiagnosticIds
    {
        get { return ImmutableArray.Create(AsyncMissingCancellationTokenAnalyzer.DiagnosticId); }
    }

    public sealed override FixAllProvider GetFixAllProvider()
    {
        // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/FixAllProvider.md for more information on Fix All Providers
        return WellKnownFixAllProviders.BatchFixer;
    }

    public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)
    {
        // TODO: Replace the following code with your own analysis, generating a CodeAction for each fix to suggest
        var diagnostic = context.Diagnostics.First();

        // Register a code action that will invoke the fix.
        context.RegisterCodeFix(
            CodeAction.Create(
                title: CodeFixResources.CodeFixTitle,
                createChangedDocument: d =&gt; AddCancellationTokenParameterAsync(
                    context, diagnostic, d),
                equivalenceKey: nameof(CodeFixResources.CodeFixTitle)),
            diagnostic);

        return Task.CompletedTask;
    }

    private async Task&lt;Document&gt; AddCancellationTokenParameterAsync(
        CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken)
    {
        var syntaxRoot = await context.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
        var root = (CompilationUnitSyntax)syntaxRoot;

        // Find the type declaration identified by the diagnostic.
        var diagnosticSpan = diagnostic.Location.SourceSpan;
        var methodDecl = (MethodDeclarationSyntax)root.FindNode(diagnosticSpan);

        // required using directive
        var namespaceQualifiedName = SyntaxFactory.QualifiedName(
            SyntaxFactory.IdentifierName(&quot;System&quot;),
            SyntaxFactory.IdentifierName(&quot;Threading&quot;));
        var namespaceUsingDirective = SyntaxFactory.UsingDirective(namespaceQualifiedName)
            .NormalizeWhitespace()
            .WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed);

        var tokenParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier(&quot;cancellationToken&quot;))
            // The using directive will be present, so do not need to use FQN
            .WithType(SyntaxFactory.ParseTypeName(nameof(CancellationToken)));
        var newMethodDecl = methodDecl.AddParameterListParameters(tokenParameter);

        var document = context.Document;
        var newRoot = root;
        if (root.Usings.All(u =&gt; u.Name.ToString() != &quot;System.Threading&quot;))
        {
            newRoot = root.AddUsings(namespaceUsingDirective);
        }

        newRoot = newRoot.ReplaceNode(methodDecl, newMethodDecl);
        return document.WithSyntaxRoot(newRoot);
    }
}
</code></pre>
<p>This code ends up being very similar to <a href=""https://stackoverflow.com/questions/36948218/add-a-parameter-to-a-method-with-a-roslyn-codefixprovider"">another question</a> - same idea for the analyzer + fix, but it has no mention of the unit testing side of this.</p>
<p>Relevant project info:</p>
<pre class=""lang-xml prettyprint-override""><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;
    &lt;PropertyGroup&gt;
        &lt;TargetFramework&gt;net6.0&lt;/TargetFramework&gt;
    &lt;/PropertyGroup&gt;
    &lt;ItemGroup&gt;
        &lt;PackageReference Include=&quot;coverlet.collector&quot; Version=&quot;3.1.2&quot; /&gt;
        &lt;PackageReference Include=&quot;FakeItEasy&quot; Version=&quot;7.3.1&quot; /&gt;
        &lt;PackageReference Include=&quot;FluentAssertions&quot; Version=&quot;6.7.0&quot; /&gt;
        &lt;PackageReference Include=&quot;nunit&quot; Version=&quot;3.13.3&quot; /&gt;
        &lt;PackageReference Include=&quot;NUnit.Analyzers&quot; Version=&quot;3.3.0&quot; /&gt;
        &lt;PackageReference Include=&quot;NUnit3TestAdapter&quot; Version=&quot;4.2.1&quot;&gt;
            &lt;PrivateAssets&gt;all&lt;/PrivateAssets&gt;
            &lt;IncludeAssets&gt;runtime; build; native; contentfiles; analyzers; buildtransitive&lt;/IncludeAssets&gt;
        &lt;/PackageReference&gt;
        &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;17.3.0&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis&quot; Version=&quot;4.2.0&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.CSharp.Analyzer.Testing.NUnit&quot; Version=&quot;1.1.1&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.CSharp.CodeFix.Testing.NUnit&quot; Version=&quot;1.1.1&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.CSharp.CodeRefactoring.Testing.NUnit&quot; Version=&quot;1.1.1&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.VisualBasic.Analyzer.Testing.NUnit&quot; Version=&quot;1.1.1&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.VisualBasic.CodeFix.Testing.NUnit&quot; Version=&quot;1.1.1&quot; /&gt;
        &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.VisualBasic.CodeRefactoring.Testing.NUnit&quot; Version=&quot;1.1.1&quot; /&gt;
    &lt;/ItemGroup&gt;
&lt;/Project&gt;
</code></pre>
",https://stackoverflow.com/questions/73411356/roslyn-code-fix-runs-an-extra-time-unit-tests-fail-too-many-iterations,"['c#', 'unit-testing', 'nunit', 'roslyn', 'roslyn-code-analysis']",152,False,1,1
Error messages displayed when a test fails using MochaJs,"<p>I am using Mocha with chai to perform unit testing. But I can't comprehend the error messages displayed when a test fails.</p>
<p>For instance, I have a simple api, that only accepts alpha characters for certain inputs. If the user attempts to submit something like &quot;3rror&quot;, the api will return a status of 403, or some other error code.</p>
<p>With Mocha I can assert something like : <code>response.should.have.status(403);</code> to check the server is catching and serving invalid requests appropriately.</p>
<p>However; with Mocha, I am completely lost when trying to reason out why or what caused an error to occur. Did I write a bad test, did my sanitization/validation middleware fail, am I even connected to my server, or am I failing to handle invalid requests and/or errors appropriately?</p>
<p>Below is an example of an error message Mocha provides for the mentioned case.</p>
<pre><code> Uncaught TypeError: Cannot read properties of undefined (reading 'should')
      at C:\...\test.js:53:43
      at Test.Request.callback (node_modules\chai-http\node_modules\superagent\lib\node\index.js:716:12)
      at IncomingMessage.&lt;anonymous&gt; (node_modules\chai-http\node_modules\superagent\lib\node\index.js:916:18)
      at IncomingMessage.emit (node:events:539:35)
      at endReadableNT (node:internal/streams/readable:1345:12)
      at processTicksAndRejections (node:internal/process/task_queues:83:21)
</code></pre>
<p>I understand it gave the wrong status code, but these error messages don't really help me understand what went wrong. Did I just goof an write a bad test, or did my app fail? So I am here to ask for help.</p>
<p>How can I better understand these errors reported when a test fails using Mocha?</p>
",https://stackoverflow.com/questions/72609846/error-messages-displayed-when-a-test-fails-using-mochajs,"['node.js', 'unit-testing', 'mocha.js', 'chai']",58,False,1,0
Classist Unit Testing - Avoiding Mocks,"<p>I am trying to follow the Classist approach for Unit Testing. I try to only mock external dependencies (external API, file system, etc...). I try to separate data access code (EF Core) from core domain classes, allowing me to test those core classes without those dependencies.</p>
<p>In the following class:</p>
<pre><code>using System;
using System.Threading.Tasks;
using Cornerstone.Services;
using MediatR;
using Cornerstone.Entities.Cornerstone.Actions.LDAP;
using Cornerstone.Entities.Cornerstone.Actions;

namespace Cornerstone.Features.Actions.ActionExecuters
{
    public class AddUserActionExecuter : IActionExecuter
    {
        private readonly LdapService ldapService;
        private readonly AddUserAction action;
        private readonly IMediator mediator;

        public AddUserActionExecuter(LdapService ldapService, AddUserAction action, IMediator mediator)
        {
            this.ldapService = ldapService ?? throw new ArgumentNullException(nameof(ldapService));
            this.action = action ?? throw new ArgumentNullException(nameof(action));
            this.mediator = mediator;
        }

        public async Task&lt;bool&gt; CanExecute()
        {
            var sourceContact = await mediator.Send(new GetContactForActionQuery(action));
            return !string.IsNullOrWhiteSpace(action.SamAccountName) 
                &amp;&amp; !string.IsNullOrWhiteSpace(action.Email) 
                &amp;&amp; !string.IsNullOrWhiteSpace(sourceContact.FirstName) 
                &amp;&amp; !string.IsNullOrWhiteSpace(sourceContact.Surname) 
                &amp;&amp; !string.IsNullOrWhiteSpace(action.Ou) 
                &amp;&amp; action.Groups.Count &gt; 0;
        }

        public async Task&lt;ExecutionResult&gt; Execute()
        {
            var sourceContact = await mediator.Send(new GetContactForActionQuery(action));
            ldapService.CreateUserAccount(action.Ou, action.SamAccountName, action.Password, action.UniqueCN, action.Email,  sourceContact.FirstName, sourceContact.Surname, action.Email);
            ldapService.AddUserToGroups(action.SamAccountName, action.Groups.ToArray());
            return new ExecutionResult { Successful = true };
        }

    }
}
</code></pre>
<p>you can see that I am using MediatR to send queries. Using MediatR, I am fetching a Contact that corresponds to a <code>SourceContactId</code> property on the <code>AddUserAction</code> class.</p>
<p>If I want to unit test the logic in the <code>CanExecute</code> method, I can see two choices:</p>
<ol>
<li>Mock the MediatR handler and make it return a contact I prepared</li>
<li>Create a new class like <code>AddAdUserActionExecuter_Helper</code> that has a method <code>bool CheckCanExecute(AddUserAction action, Contact contact)</code> and move the logic there, then I would call this from the original <code>CanExecute</code> and unit test only the new method which now has no dependency on MediatR.</li>
</ol>
<p><strong>My question is</strong>: in number 2 which may be the option more inline with my design choices,  given that there is only one user for this introduced method, doesn't it seem like we're adding a new class and exposing its method just for the sake of testing?</p>
",https://stackoverflow.com/questions/70980628/classist-unit-testing-avoiding-mocks,"['c#', 'unit-testing', 'refactoring', 'mediatr']",68,False,1,0
Unit Test for multiple condition in Java?,"<p>I am new in Unit Testing and I have sometimes such situations with multiple conditions. However, I am not sure if I re-mock or verify the same cases for each test.</p>
<p>For example, I am trying to write Unit Tests for the following service method:</p>
<pre><code>public void create(Request request) {
    
    // code omitted

    if (!employeeService.existsByUuid(uuid)) {
        throw new EntityNotFoundException(&quot;Not found&quot;);
    }

    EmployeeDTO employee = employeeService.save(...);
    
    if (!departmentService.existsByUuid(employee.getDepartment())) {
        throw new EntityNotFoundException(&quot;Not found&quot;);
    }
}
</code></pre>
<p>I think I need to write my tests for the following scenarios:</p>
<p><strong>1.</strong> when <code>employeeService.existsByUuid(uuid) == false</code>, then throw new EntityNotFoundException. then verify <code>employeeService.save()</code> and <code>departmentService.existsByUuid()</code> is never called.</p>
<p><strong>2.</strong> when <code>employeeService.existsByUuid(uuid) == true</code> then <code>employeeService.save()</code> is called and I assert the values. and then verify <code>employeeService.save()</code> and <code>departmentService.existsByUuid()</code> is never called.</p>
<p><strong>3.</strong> when <code>departmentService.existsByUuid() == false</code> then throw new EntityNotFoundException. At this stage, I also mock <code>employeeService.existsByUuid(uuid)</code> as <code>true</code> so that test passes the first condition. However, I am not sure if do I need to assert the second part; <code>employeeService.save()</code> is called and I assert the values. Do I assert of the returned values or just verify that method is called 1 time. Because I already asserted its value and the 3rd test is just for the 3rd condition.</p>
<p>Any idea for this kind of scenarios when we have multiple condition and may need to re-test the same condition again and again?</p>
",https://stackoverflow.com/questions/71496398/unit-test-for-multiple-condition-in-java,"['java', 'unit-testing', 'testing', 'junit', 'mockito']",1773,True,-1,2
Can clang-tidy warnings from selected code branches be suppressed?,"<p>I use LLVM version 12.0.0.</p>
<p>Let's assume that there is library code that contains some weird code for testing purposes. This code will never be accessed during normal library use, but is only there for unit testing.</p>
<p>Now if a project uses that library and performs static code analysis with <code>clang-tidy</code>, then <code>clang-tidy</code> might report potential errors related to that code that is anyway considered unreachable. Please consider this minimal example:</p>
<pre><code>#include &lt;iostream&gt;

// Code that is part of a library

class Test
{
  public:
    int number;
};

Test instance;

const Test&amp; getMemory(bool fork)
{
    if (fork)
    {
        return instance;
    }
    else
    {
        // PROBLEM SOURCE!
        // I want to suppress all clang-tidy warnings that are related to this line, because the code will never be
        // executed. It is only there for testing purposes.
        return *(new Test);
    }
}

// Project code

int test(bool fork)
{
    // PROBLEM WARNING!
    Test myInstance = getMemory(fork);

    myInstance.number = 123;

    std::cout &lt;&lt; &quot;Number is &quot; &lt;&lt; myInstance.number &lt;&lt; std::endl;

    return 0;
}
</code></pre>
<p>Adding <code>// NOLINTNEXTLINE</code> to the <code>PROBLEM SOURCE</code> position won't help. <code>clang-tidy</code> finds the actual misuse at the <code>PROBLEM WARNING</code> position. There I could add <code>// NOLINTNEXTLINE</code>, but I don't want to clutter my project with suppression statements for warnings that are part of a library or another project.</p>
<p>Also I don't want to completely suppress clang-tidy warnings related to the library. There might be valuable information for other parts of its code.</p>
<p>So is there a possibility to selectively suppress clang-tidy warnings related to certain code branches? It should not be a suppression of warnings for selected lines of these branches (since <code>clang-tidy</code> doesn't find an error there), but a suppression of warnings at <strong>other code positions</strong> that are <strong>related</strong> to these lines.</p>
",https://stackoverflow.com/questions/73728581/can-clang-tidy-warnings-from-selected-code-branches-be-suppressed,"['c++', 'suppress-warnings', 'static-code-analysis', 'clang-tidy']",39,False,0,0
Angular CDK Overlay - Mocking overlay component in unit test,"<p>I've created an <a href=""https://github.com/MintPlayer/mintplayer-ng-bootstrap/tree/offcanvas-single-instance/libs/mintplayer-ng-bootstrap/src/lib/components/offcanvas"" rel=""nofollow noreferrer"">offcanvas component for angular</a>, but I can't get my unit tests to work.</p>
<p>Here's the <a href=""https://github.com/MintPlayer/mintplayer-ng-bootstrap/blob/offcanvas-single-instance/libs/mintplayer-ng-bootstrap/src/lib/components/offcanvas/components/offcanvas-host/offcanvas-host.component.spec.ts"" rel=""nofollow noreferrer"">failing unit test</a> (offcanvas-host.component):</p>
<pre><code>describe('BsOffcanvasHostComponent', () =&gt; {
  let component: BsOffcanvasTestComponent;
  let fixture: ComponentFixture&lt;BsOffcanvasTestComponent&gt;;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      imports: [ CommonModule, OverlayModule ],
      declarations: [
        // Unit to test
        BsOffcanvasHostComponent,
      
        // Mock dependencies
        BsOffcanvasMockComponent,
        BsOffcanvasHeaderMockComponent,
        BsOffcanvasBodyMockComponent,
        BsOffcanvasContentMockDirective,

        // Testbench
        BsOffcanvasTestComponent,
      ]
    })
    .compileComponents();
  });

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

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

type OffcanvasPosition = 'top' | 'bottom' | 'start' | 'end';

@Component({
  selector: 'bs-offcanvas-test',
  template: `
    &lt;bs-offcanvas [(show)]=&quot;isOffcanvasVisible&quot; [position]=&quot;position&quot; [hasBackdrop]=&quot;true&quot; (backdropClick)=&quot;isOffcanvasVisible = false&quot;&gt;
        &lt;div *bsOffcanvasContent&gt;
            &lt;bs-offcanvas-header&gt;
                &lt;h5&gt;Offcanvas&lt;/h5&gt;
            &lt;/bs-offcanvas-header&gt;
            &lt;bs-offcanvas-body&gt;
                &lt;span&gt;Content&lt;/span&gt;
            &lt;/bs-offcanvas-body&gt;
        &lt;/div&gt;
    &lt;/bs-offcanvas&gt;`
})
class BsOffcanvasTestComponent {
  isOffcanvasVisible = false;
  position: OffcanvasPosition = 'start';
}

@Directive({ selector: '[bsOffcanvasContent]' })
class BsOffcanvasContentMockDirective {
  constructor(offcanvasHost: BsOffcanvasHostComponent, template: TemplateRef&lt;any&gt;) {
    offcanvasHost.content = template;
  }
}

@Component({
  selector: 'bs-offcanvas-holder',
  template: `
    &lt;div&gt;
      &lt;ng-container *ngTemplateOutlet=&quot;contentTemplate&quot;&gt;&lt;/ng-container&gt;
    &lt;/div&gt;`,
  providers: [
    { provide: BsOffcanvasComponent, useExisting: BsOffcanvasMockComponent }
  ]
})
class BsOffcanvasMockComponent {
  constructor(@Inject(OFFCANVAS_CONTENT) contentTemplate: TemplateRef&lt;any&gt;) {
    this.contentTemplate = contentTemplate;
  }

  contentTemplate: TemplateRef&lt;any&gt;;
}

@Component({
  selector: 'bs-offcanvas-header',
  template: `
    &lt;div class=&quot;offcanvas-header&quot;&gt;
      &lt;ng-content&gt;&lt;/ng-content&gt;
    &lt;/div&gt;`
})
class BsOffcanvasHeaderMockComponent {}

@Component({
  selector: 'bs-offcanvas-body',
  template: `
    &lt;div class=&quot;offcanvas-body&quot;&gt;
      &lt;ng-content&gt;&lt;/ng-content&gt;
    &lt;/div&gt;`
})
class BsOffcanvasBodyMockComponent {}
</code></pre>
<p>which tests the <a href=""https://github.com/MintPlayer/mintplayer-ng-bootstrap/blob/offcanvas-single-instance/libs/mintplayer-ng-bootstrap/src/lib/components/offcanvas/components/offcanvas-host/offcanvas-host.component.ts"" rel=""nofollow noreferrer"">following component</a>:</p>
<pre><code>ngAfterViewInit() {
    const injector = Injector.create({
      providers: [
        { provide: OFFCANVAS_CONTENT, useValue: this.content },
      ],
      parent: this.rootInjector,
    });
    const portal = new ComponentPortal(BsOffcanvasComponent, null, injector);
    const overlayRef = this.overlayService.create({
      scrollStrategy: this.overlayService.scrollStrategies.block(),
      positionStrategy: this.overlayService.position().global()
        .top('0').left('0').bottom('0').right('0'),
      hasBackdrop: false
    });

    this.component = overlayRef.attach&lt;BsOffcanvasComponent&gt;(portal); // &lt;-- The test fails here

    this.component.instance.backdropClick
      .pipe(takeUntil(this.destroyed$))
      .subscribe((ev) =&gt; {
        this.backdropClick.emit(ev);
      });

    this.viewInited$.next(true);
}
</code></pre>
<p>The error message is</p>
<pre><code>Error: NG0302: The pipe 'async' could not be found in the 'BsOffcanvasComponent' component!. Find more at https://angular.io/errors/NG0302
</code></pre>
<p><a href=""https://github.com/PieterjanDeClippel/failing-unit-test"" rel=""nofollow noreferrer"">Here's a minimal reproduction of the issue</a></p>
<p>How can tell the angular TestingModule to use the mock component instead of the initial component type when calling</p>
<pre><code>overlayRef.attach&lt;BsOffcanvasComponent&gt;(portal)
</code></pre>
<p>command in my unit test?</p>
<h1>EDIT</h1>
<p>Sadly I'm still not getting it to work. Usually for unit testing in angular there are mainly 3 cases:</p>
<h2>Components referenced through the use of the tagname in the template of the UTT (unit-to-test)</h2>
<p>This you solve by creating a MockComponent with the same tagname and inputs/outputs.</p>
<h2>Ancestoral components injected in the UTT</h2>
<p>This you solve by creating a MockComponent with a <code>provide</code>r on the decorator</p>
<pre><code>@Component({
  selector: 'bs-offcanvas-holder',
  template: ``,
  providers: [
    { provide: BsOffcanvasComponent, useExisting: BsOffcanvasMockComponent }
  ]
})
class BsOffcanvasMockComponent {}
</code></pre>
<h2>Component types called directly from the UTT</h2>
<pre><code>this.component = overlayRef.attach&lt;BsOffcanvasComponent&gt;(portal);
</code></pre>
<p>Here I should be able to use the <code>BsOffcanvasMockComponent</code> instead, without having the unit-test dragging the other file in the TestBed. So how can I solve this? Off course I can mock the CDK <code>Overlay</code> service, but this still leaves me with the above line of code in my UTT, where the <code>BsOffcanvasComponent</code> is litterally being dragged into the Testbed.</p>
",https://stackoverflow.com/questions/71440717/angular-cdk-overlay-mocking-overlay-component-in-unit-test,"['angular', 'unit-testing', 'angular-jest', 'angular-cdk-overlay']",2410,True,0,2
Angular: Testing apis from component,"<p>I have started learning how to test angular projects. So far basic unit testing is working fine for me but for the dependency testing especially when API services are injected into the component I am facing issue for providing <code>HttpClient</code>. I have tried different solutions but none is working for me.</p>
<p><strong>Service</strong></p>
<pre><code>// Present in HttpClientService file
getDisposition() {
  return this.http.get&lt;{ message: string, data: { dispositionList: Disposition[] } }&gt;(`${this.URL}/disposition/get`);
}

// Present in FileProcessService file
deleteMedia(media: string) {
    return this.http.delete&lt;{ message: string }&gt;(`${this.URL}/certificate/delete?certificate=${media}`);
}
</code></pre>
<p><strong>add-edit-activity.component.ts</strong></p>
<pre><code>import { HttpEventType } from '@angular/common/http';
import { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { AssignedPerson } from '@model/assigned-person.model';
import { Disposition } from '@model/disposition.model';
import { mimeTypes } from '@model/mime-type';
import { FileProcessService } from '@service/file-process.service';
import { HttpClientService } from '@service/http-client.service';
import { DeleteComponent } from '@shared/delete/delete.component';
import { CustomErrorStateMatcher } from '@validator/error-state-matcher';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-add-edit-activity',
  templateUrl: './add-edit-activity.component.html',
  styleUrls: ['./add-edit-activity.component.css']
})
export class AddEditActivityComponent implements OnInit {

  constructor(private fb: FormBuilder, private sanitizer: DomSanitizer, private dialogRef: MatDialogRef&lt;AddEditActivityComponent&gt;, @Inject(MAT_DIALOG_DATA) public data: any,
    private _http: HttpClientService, private _fileService: FileProcessService, private toastr: ToastrService, private dialog: MatDialog,) { }

  re = new RegExp(/^[a-zA-Z-]*/, 'g');
  ISOstamp = { T: ' ', Z: '000' };
  matcher = new CustomErrorStateMatcher();
  dispositionList: Disposition[] = [];
  assignedPersonList: AssignedPerson[] = [];
  filterAssignedPersonList: AssignedPerson[] = [];
  uploaded = false;
  uploadProgress = false;
  fileURL: SafeUrl;
  activityForm = this.fb.group({
    gaugeId: [this.data.gaugeId, Validators.maxLength(9)], createTimeStamp: [{ value: new Date().toISOString().replace(/[TZ]/g, m =&gt; this.ISOstamp[m]), disabled: true }],
    user: [{ value: sessionStorage.getItem('username'), disabled: true }], disposition: ['', [Validators.required, Validators.maxLength(30)]],
    assignedPersonName: ['', Validators.maxLength(30)], department: ['', Validators.maxLength(20)],
    shift: ['', Validators.maxLength(1)], remark: ['', Validators.maxLength(50)],
    calibrationDate: ['', Validators.maxLength(10)], attachment: ['', Validators.maxLength(255)]
  });

  @ViewChild('file') certificate: ElementRef;

  ngOnInit(): void {
    this.data.type.match(this.re)[0] === 'Update' &amp;&amp; this.setFormValues();
    this._http.getDisposition().subscribe(response =&gt; this.dispositionList = response.data.dispositionList);
    this._http.getAssignedPerson().subscribe(response =&gt; this.assignedPersonList = this.filterAssignedPersonList = response.data.assignedToList);
  }

  get GaugeId() {
    return this.activityForm.get('gaugeId');
  }

  get TimeStamp() {
    return this.activityForm.get('createTimeStamp');
  }

  get Attachment() {
    return this.activityForm.get('attachment');
  }

  get Disposition() {
    return this.activityForm.get('disposition');
  }

  get DispositionValue() {
    return this.dispositionList.map(e =&gt; e.dispositionType).indexOf(this.Disposition.value) &lt; 0;
  }

  get AssignedTo() {
    return this.activityForm.get('assignedPersonName');
  }

  get AssignedToValue() {
    return this.assignedPersonList.map(e =&gt; `${e.firstName} ${e.lastName}`).indexOf(this.Disposition.value) &lt; 0;
  }

  private async setFormValues() {
    this.activityForm.patchValue({ ...this.data });
    if (this.data.attachment) {
      this.uploadProgress = true;
      this.uploaded = true;
      await this.fetchUploadedFile(this.data.attachment, mimeTypes[this.data.attachment.split('.')[1]]);
      this.activityForm.markAsPristine();
    }
  }

  searchAssignedPerson(event) {
    if (event.target.value) {
      this.filterAssignedPersonList = [];
      for (let person of this.assignedPersonList) {
        if (person.firstName.toLowerCase().startsWith(event.target.value.toLowerCase())) {
          this.filterAssignedPersonList.push(person);
        }
      }
    } else { this.filterAssignedPersonList = this.assignedPersonList }
  }

  upload(event) {
    const file: File = event.target.files[0];
    this.certificate.nativeElement.value = '';
    if (file.size &gt; (20 * 1000 * 1000)) { // Checking if File size is above 20MB
      this.toastr.error('Size of ' + file.name + ' is above 20MB');
      return;
    }
    const fd = new FormData();
    fd.append('certificate', file, file.name);
    this.processAttachment(fd);
  }

  private processAttachment(file: FormData) {
    this._fileService.uploadMedia(file).subscribe(event =&gt; {
      if (event.type === HttpEventType.UploadProgress) { this.uploadProgress = true }
      if (event.type === HttpEventType.Response) {
        let media = event.body.data.Certificate;
        this.fetchUploadedFile(media.fileName, media.fileType);
        this.toastr.info(event.body.message);
      }
    }, error =&gt; {
      this.toastr.error(error.error.message);
      this.uploadProgress = false;
    });
  }

  private async fetchUploadedFile(file: string, mimeType: string) {
    try {
      let response = await this._fileService.getMedia(file).toPromise();
      this.fileURL = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(new Blob([response], { type: mimeType })));
      this.uploaded = true;
      this.uploadProgress = false;
      this.activityForm.patchValue({ attachment: file });
      this.Attachment.markAsDirty();
    } catch (error) {
      this.uploadProgress = false;
      this._fileService.processError(error.error)
    }
  }

  deleteFile() {
    this.dialog.open(DeleteComponent, {
      width: '350px', disableClose: true
    }).afterClosed().subscribe(response =&gt; {
      if (response) {
        this._fileService.deleteMedia(this.Attachment.value).subscribe(response =&gt; {
          this.toastr.info(response.message);
          this.activityForm.patchValue({ attachment: '' });
          this.Attachment.markAsDirty();
          this.uploaded = false;
        }, error =&gt; this.toastr.error(error.error.message));
      }
    });
  }

  async doAction() {
    let message = '';
    if (this.data.type.match(this.re)[0] === 'Add') {
      message = await (await this._http.addActivityLog(this.activityForm.getRawValue()).toPromise()).message;
    } else {
      message = await (await this._http.updateActivityLog(this.GaugeId.value, this.TimeStamp.value, this.activityForm.getRawValue()).toPromise()).message;
    }
    this.dialogRef.close(message);
  }
}
</code></pre>
<p><strong>add-edit-activity.component.spec.ts</strong></p>
<pre><code>import { ComponentFixture, TestBed, tick } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { FileProcessService } from '@service/file-process.service';
import { HttpClientService } from '@service/http-client.service';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';
import { AddEditActivityComponent } from './add-edit-activity.component';

describe('AddEditActivityComponent', () =&gt; {
  let component: AddEditActivityComponent;
  let fixture: ComponentFixture&lt;AddEditActivityComponent&gt;;
  let _http: HttpClientService, _file: FileProcessService;

  beforeEach(async () =&gt; {
    await TestBed.configureTestingModule({
      declarations: [AddEditActivityComponent],
      imports: [FormsModule, ReactiveFormsModule],
      providers: [
        { provide: MatDialogRef, useValue: {} },
        { provide: MAT_DIALOG_DATA, useValue: { type: 'Add Activity Log', gaugeId: 'W-001' } },,
        { provider: HttpClientService, useValue: null },
        { provider: FileProcessService, useValue: null }
      ]
    }).compileComponents();
  });

  beforeEach(() =&gt; {
    fixture = TestBed.createComponent(AddEditActivityComponent);
    component = fixture.debugElement.componentInstance;
    _http = fixture.debugElement.injector.get(HttpClientService);
    _file = fixture.debugElement.injector.get(FileProcessService);
    fixture.detectChanges();
  });
  
  // These 2 tests throwing error.
  it('SHOULD mock http service', () =&gt; {
    let spy = spyOn(_http, 'getDisposition').and.callFake(() =&gt; {
      return of({
        message: '',
        data: { dispositionList: [] }
      }).pipe(delay(100));
    });
    component.ngOnInit();
    tick(100);
    expect(component.dispositionList).toEqual([]);
  });

  it('SHOULD mock file service', () =&gt; {
    let spy = spyOn(_file, 'deleteMedia').and.callFake((file: string) =&gt; {
      return of({ message: '' }).pipe(delay(100));
    });
    component.deleteFile();
    tick(100);
    expect(component.uploaded).toBe(false);
  });
});
</code></pre>
<p>The error that am getting for those 2 tests (I'm providing the error of 1 test case, the same is coming for the 2nd one also):</p>
<blockquote>
<ol>
<li>SHOULD mock http service
AddEditActivityComponent
Error: Invalid provider for the NgModule 'DynamicTestModule' - only instances of Provider and Type are allowed, got: [..., ..., ...,
..., ?undefined?, ..., ...]
at throwInvalidProviderError (node_modules/@angular/core/<strong>ivy_ngcc</strong>/fesm2015/core.js:240:1)
at providerToFactory (node_modules/@angular/core/<strong>ivy_ngcc</strong>/fesm2015/core.js:11550:1)
at providerToRecord (node_modules/@angular/core/<strong>ivy_ngcc</strong>/fesm2015/core.js:11521:1)
at R3Injector.processProvider (node_modules/@angular/core/<strong>ivy_ngcc</strong>/fesm2015/core.js:11424:1)
Error:  : could not find an object to spy upon for getDisposition() Usage: spyOn(, ) Error:  :
could not find an object to spy upon for getDisposition() Usage:
spyOn(, )
at </li>
</ol>
</blockquote>
<p>Anyone, please help what's the exact error happening with my test cases? Stuck here for almost 2 days.</p>
",https://stackoverflow.com/questions/71169935/angular-testing-apis-from-component,"['javascript', 'angular', 'unit-testing', 'jasmine', 'karma-jasmine']",175,False,0,1
How to avoid columns written in wrong order in pyspark?,"<p>I'm working on a data lake where I use AWS Glue for ETL with PySpark. I ran into an issue with a few records where the values end up in the wrong column after the resulting DF is written to a file.</p>
<p>The two first rows in the following example have incorrect column order such as <strong>customer_postal_code</strong> being <strong>lb</strong>. The three rows after that show correct values:</p>
<pre><code>+-----------------+--------------------+----------------+------------+-------------+
|total_weight_unit|customer_postal_code|from_postal_code|from_density|service_level|
+-----------------+--------------------+----------------+------------+-------------+
|4.070000171661377|                  lb|           96863|     17406.0|        447.0|
|12.34000015258789|                  lb|           96863|     17406.0|        447.0|
|               lb|               78665|           76051|      1258.0|     standard|
|               lb|               06708|           17406|       447.0|     standard|
|               lb|               67357|           63376|      1705.0|     standard|
|               lb|               91730|           17406|       447.0|     standard|
</code></pre>
<p>I'm using a custom transform to return a DynamicFrame with the DF in the shape I'm expecting like this:</p>
<pre><code>extracted_fields_node = extract_db_fields(
        glue_context,
        DynamicFrameCollection(
            {&quot;source_node&quot;: source_node},
            glue_context
        ),
    )
</code></pre>
<p>Here's the definition of extract_db_fields:</p>
<pre><code>def extract_db_fields(glue_context: GlueContext, dfc: DynamicFrameCollection) -&gt; DynamicFrameCollection:
    data_frame = dfc.select(list(dfc.keys())[0]).toDF()
    df_base = extract_db_fields_df(data_frame)
    glue_df = DynamicFrame.fromDF(
        df_base, glue_context, &quot;extract_partner_fields&quot;
    )
    return DynamicFrameCollection({&quot;ExtractFieldsTransform&quot;: glue_df}, glue_context)
</code></pre>
<p>I chose to process the DynamicFrame as a Spark DataFrame with a <strong>extract_db_fields_df</strong> function to allow for simple Spark unit testing. Here's a snippet of how I extract one of the fields that is the wrong value when written to a file:</p>
<pre><code>df = df.withColumn(&quot;total_weight&quot;,
                           col(&quot;shipments_totalWeight&quot;).cast(DoubleType()))
</code></pre>
<p>Some notable details:</p>
<ul>
<li>The data that is processed by <strong>extract_db_fields</strong> is a DF of three joined datasets.</li>
<li>Before writing to a file, I repartition by <strong>1</strong> to create a single file for discovery and analysis by an ML team.</li>
<li>I've verified the source data does not include values like the ones shown above.</li>
</ul>
",https://stackoverflow.com/questions/73938664/how-to-avoid-columns-written-in-wrong-order-in-pyspark,"['apache-spark', 'pyspark', 'aws-glue']",159,False,0,0
Patching a function from within the same package is not patching,"<p>I am using the builtin unittest library. I am trying to test a function,in this example <code>a</code>, which calls function <code>b</code>. Both of these functions are at the top level of the package and are not class based functions. I have read the unittest documentation about where to patch and have found that you must use the patch against the function (<code>a</code>) importing the other function (<code>b</code>)and not patching the function itself (<code>b</code>), but all the answers and documentation seem to only reference class based functions.</p>
<p>I have the following heirarchy:</p>
<pre><code>mypkg
|- __init__.py
|- a.py
|- b.py
|- test
  |- __init__.py
  |- test_a.py
</code></pre>
<p>top level <code>__init__.py</code>:</p>
<pre><code>from .a import a
from .b import b
__all__ = ['a','b']
</code></pre>
<p>a.py:</p>
<pre><code>import .b import b

def a():
  ...
  functionB({&quot;USERNAME&quot;: username, &quot;OTHER&quot;: other})
</code></pre>
<p>b.py:</p>
<pre><code>def b(**kwargs):
 // do stuff with kwargs like calling APIs etc
 // This function doesn't return anything
</code></pre>
<p>test_a.py:</p>
<pre><code>import unittest
from unittest.mock import patch
from ..a import a

fake_return_value = &quot;heythere&quot;

class TestFunctionA(unittest.TestCase):
 @patch('mypkg.a.b', return_value=fake_return_value)
 # @patch('mympkg.b') # Doesn't work, does not override the original function
 def test_mytest(self, mocked_func):
   a()
   mocked_func.assert_called_once_with(stuff)
</code></pre>
<p>Running the above tests with the patch call that is uncommented leads to the test being ran and the original function being called, not the mock function.</p>
<p>What am I doing wrong here? I didn't think it would be this hard to unit test, I come from unit testing React apps, so this is a little frustrating but I assume user error. All the documentation and googling I've done so far seems that this should work, or at least the patch variant commented out above. Is this because of my package structure and trying to mock functions in the same package or?</p>
",https://stackoverflow.com/questions/72378519/patching-a-function-from-within-the-same-package-is-not-patching,"['python', 'python-unittest']",331,True,0,2
Unit Testing Angular Component Library,"<p>I'm having no luck unit-testing an angular component library in isolation. I see this question in a few places, but no workable solutions.</p>
<p>The library works in a development environment when it accompanies the parent projects.</p>
<p><a href=""https://i.stack.imgur.com/cwT1d.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/cwT1d.png"" alt=""Angular Component Library File Structure"" /></a></p>
<p>I've tried many iterations of <code>npm i</code> and <code>ng test</code> with no luck :(</p>
<p>My latest is on the projects/interface-commons and this is my exception</p>
<pre><code>An unhandled exception occurred: Cannot find module '@angular-devkit/build-angular/package.json'
</code></pre>
<p>My research has led me to the following questions:</p>
<ol>
<li>Can an Angular library be unit-tested using Karma/Jasmin without a parent project?</li>
<li>If so, can you suggest a good resource?</li>
</ol>
<p>If not...</p>
<p>I get much closer running <code>ng test</code> from a parent directory. At least the Karma web page opens :\  The first problem I encounter is:</p>
<p><code>error TS2307: Cannot find module '@angular/core' or its corresponding type declarations.</code></p>
<p>I've been able to get past this by running <code>npm i</code> on the library's dist folder; which seems counter-intuitive to me.</p>
<p>Now I'm running into:</p>
<p><code>error TS2591: Cannot find name 'require'. Do you need to install type definitions for node? Try </code>npm i --save-dev @types/node<code> and then add 'node' to the types field in your tsconfig.</code></p>
<p>I've followed numerous suggestions to fix this, but have to ask?</p>
<p>AM I'm missing some fundamental piece of knowledge here? Am I going about this the right way or is my flayling due to something I don't know that I don't know?</p>
<p>Thanks
Dave</p>
",https://stackoverflow.com/questions/74535569/unit-testing-angular-component-library,"['angular', 'unit-testing']",17,False,0,0
MSTest method thows &quot;Object reference not set to an instance of an object&quot; while a Main class return no error in .Net core,"<p>I am just learning ADO.NET with C# and trying to do basic CRUD operation. I am introduced to Mstest framework and are required to create a unit testing class to test the code.</p>
<p>However, all the test method return &quot;Object reference not set to an instance of an object&quot; exception, even though the same code run in the main class just fine</p>
<p>To be more exact, here is my <code>Create</code> method:</p>
<pre><code>public int Create(Category entity)
{
     string ConString = ConfigurationManager.ConnectionStrings[&quot;ConnectionString&quot;].ConnectionString;
     using (SqlConnection connection = new SqlConnection(ConString))
     {
          string sql =    &quot;INSERT INTO Categories\n&quot; +
                          &quot;VALUES(@name, @status)&quot;;
          SqlCommand command = new SqlCommand(sql, connection);
          command.Parameters.AddWithValue(&quot;@name&quot;, entity.Name);
          command.Parameters.AddWithValue(&quot;@status&quot;, entity.Status);

          int affectedRows=0;
          try { 
              connection.Open();
              Console.WriteLine(&quot;Connection Established Successfully&quot;);
              affectedRows = command.ExecuteNonQuery();
              if(affectedRows &gt; 0)
              {
                  Console.WriteLine(&quot;Add success&quot;);
                  return affectedRows;
              }
              else
              {
                  Console.WriteLine(&quot;Add failed&quot;);
                  return 0;
              }
          }
          catch(Exception ex)
          {
                    Console.WriteLine(&quot;Something went wrong:&quot;);
                    Console.WriteLine(ex.Message);
                    return 0;
          }
      }
}
</code></pre>
<p>basically, the insert a <code>Category</code> object into <code>Categories</code> table, return <code>1</code> if success and <code>0</code> if not</p>
<p>The problem is when I test it, in Unit Test class:</p>
<pre><code>    [TestMethod]
    public void CreateCategoryTest()
    {
        int? result;
        try
        {
            Category category = new Category();
            {
                Name = &quot;something&quot;;
                Status = 1;
            }
            CategoryRepository categoryRepository = new CategoryRepository();

            result = categoryRepository.Create(entity: category);
          
            Console.WriteLine(&quot;RESULTTTTTTTTTTTTTTTTTTTTT: &quot; + result);
            
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            result = 0;
        }
        
        Assert.AreEqual(1, result);
    }
</code></pre>
<p>and in Main class:</p>
<pre><code>    public static void Main(string[] args)
    {
        int? result;
        try
        {
            Category category = new Category();
            {
                Name = &quot;something&quot;;
                Status = 1;
            }
            CategoryRepository categoryRepository = new CategoryRepository();

            result = categoryRepository.Create(entity: category);
          
            Console.WriteLine(&quot;RESULTTTTTTTTTTTTTTTTTTTTT: &quot; + result);
            
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
</code></pre>
<p>basically, the same code, yet in the Main class everything is fine, another row was inserted to the database, the application return correctly, etc.</p>
<p>Even the <code>GetOne()</code> and <code>GetList()</code> method are fine,</p>
<p>The Test Method throws the Exception on the line where I call the <code>Create()</code> method:</p>
<pre><code>result = categoryRepository.Create(entity: category);
</code></pre>
<p>All other statements, like declaration of <code>Category</code> or <code>CategoryRepository</code> is getting through, indicating that the test project indeed had reference to the main project, but somehow only the method inside, which was all public, keep throwing error</p>
<p>So my question is: what exactly cause it, and how can I fix it?</p>
",https://stackoverflow.com/questions/72586882/mstest-method-thows-object-reference-not-set-to-an-instance-of-an-object-while,"['c#', 'visual-studio', '.net-core', 'ado.net', 'mstest']",43,False,0,0
Angular Testing and required input type=&quot;file&quot; form validation,"<p>I have a case where I use <code>NgForm</code> validation on an <code>input[type=&quot;file]</code>.</p>
<p>The code works fine in a real case scenario (browser usage).
However on the testing part itself I have a code that prevent the actual form data submission (including the file) if there is an error in the ngForm (by checking <code>ngForm.valid</code>).</p>
<p>The following test is considering that the ngForm.valid === false so the test fails:</p>
<pre><code>it('should do a SubsectionSave save on submit and attach file', async () =&gt; {
      const dataTransfer = new DataTransfer();
      dataTransfer.items.add(await testGetExampleFile()); // testGetExampleFile returns a valid File object
      // set file and trigger event
      const inputDebugEl  = fixture.debugElement.query(By.css('input[type=file]'));
      inputDebugEl.nativeElement.files = dataTransfer.files;
      inputDebugEl.nativeElement.dispatchEvent(new InputEvent('change'));
      fixture.detectChanges();
      await fixture.whenStable();

      component.submit(); // this submit function checks the .valid on the ngForm, but does nothing

      // expect(a-backend-save-call).toBeDone();
      // but nothing is done because the submit() stops at the .valid checking
});
</code></pre>
<p>The way to put a file into the input from the test case itself was inspired by <a href=""https://stackoverflow.com/questions/55356093/how-to-write-the-unit-testing-for-the-file-upload-method-in-the-angular-7-or-2"">How to write the unit testing for the file upload method in the Angular 7 (or 2+)</a></p>
<p>I have checked the ngForm.controls before the ngForm.valid check (in the actual implementation) and there are multiple required fields but the only one to be marked as invalid (cause: required) is this required input-file.</p>
<p>Is there a way to force angular to detect the new presence of the new file?</p>
<p>I tried a mix of <code>fixture.detectChanges();</code>, waiting for 1sec after the change event being raised,  <code>await fixture.whenStable();</code> at several places after nativeElement files being set, but nothing worked.</p>
<p>How to deal with required input file within angular component tests ?</p>
",https://stackoverflow.com/questions/71781521/angular-testing-and-required-input-type-file-form-validation,"['angular', 'unit-testing', 'testing']",240,True,0,1
Swift Mocking Unit/ UI Testing,"<p>Basically I have a fairly large project built in MVP for which I need to incorporate UI and Unit testing wherever applicable.
The project has a large number of API calls, the client has requested that API calls be <strong>mocked</strong> within the App (Dummy data). So basically I need two targets in the App, one most likely the Production and the other just for testing where it does not contact the server and just mocks the requests and sends static pre defined Json data to the response handlers for the app to function with. The solution that I initially thought of was creating a global bool value and depending on the project target selected (Production (Bool value = False),Testing (Bool value = True)) so wherever a request is being made in the code, it would check this bool value and then choose to go with either the Testing Dummy Request (which returns static pre defined Json DATA to the response handler) or Live API request. But this kinda makes the code messy.
I'm fairly new to Unit/UI testing so Id appreciate any suggestions.
Thanks in advance :).</p>
",https://stackoverflow.com/questions/73111575/swift-mocking-unit-ui-testing,"['swift', 'xcode', 'unit-testing', 'mocking', 'xcode-ui-testing']",174,False,0,0
How come the preprocessor directives in my header are not seeing the macro I put above the #include in source? (C code),"<p>I am attempting some conditional compilation for unit testing static functions in C. (roughly following the method outlined in this answer <a href=""https://stackoverflow.com/a/593437/8347016"">https://stackoverflow.com/a/593437/8347016</a>)</p>
<p>I have it set up like so:</p>
<p>check_blah.c</p>
<pre><code>#define UNIT_TEST 1   
#include &quot;blah.h&quot;
#include &quot;testframework.h&quot;

... 
</code></pre>
<p>blah.h</p>
<pre><code>#if UNIT_TEST
#define u_static
#else
#define u_static static
#endif

...

#if UNIT_TEST
void foo(/* some parameters */)
#endif
</code></pre>
<p>blah.c</p>
<pre><code>#include &quot;blah.h&quot;
...
u_static void foo(/*some parameters */) {
  /* some definition */ 
}
...
</code></pre>
<p>And just to cover my bases, here is how the files are compiled in make</p>
<pre><code>check_blah: check_blah.c blah.o testframework.o
    gcc check_blah.c blah.o testframework.o -o check_blah

blah.o: blah.c blah.h
    gcc -c blah.c -o blah.h

testframework.o: /* similar to above */
</code></pre>
<p>If I compile check_blah without it having any references to foo, and then run gdb info functions, I see that foo is considered static even though UNIT_TEST is defined.  Even more confusing, the compiler somehow does recognize UNIT_TEST as defined.  In an experiment I defined a macro, SPEEP to be 10 if UNIT_TEST was defined and 100 otherwise.  Then in check_blah.c I set some int to SPEEP and then printed it.  It would print 10!  So the line #define ustatic MUST be being hit as well, but somehow it isn't since foo remains static.</p>
<p>If I take the line #define UNIT_TEST 1 and move it to the top of blah.h, everything seems to work (i.e, info functions claims foo is not static).</p>
<p>So does anyone know the reason for this awkward (and inconsistent looking) behavior with preprocessor macros and directives?</p>
",https://stackoverflow.com/questions/72509221/how-come-the-preprocessor-directives-in-my-header-are-not-seeing-the-macro-i-put,"['c', 'unit-testing', 'makefile', 'macros', 'preprocessor']",51,False,0,0
Testing Service layer in Kotlin Spring Boot when back end is using Spring Security,"<p>I'm looking to try and test my back end Service layer (ideally along with my Controller layer too). However, I'm not sure how I would be able to go about doing this.</p>
<p>I saw that I can use Mockito to do this, however, I was not able to figure out how to apply this with what I currently have.</p>
<p>I have the entity, then repository, service and then finally controller.</p>
<p>My services have the main logic for the application within. For example, saving an entity, fetching and updating.</p>
<p>My controller (which is a restcontroller) is what my front end client interfaces with in order to call the service methods.</p>
<p>My service has an interface like below:</p>
<pre><code>interface CompanyService {

    fun saveCompany(company: Company): Company

    fun saveCompany(form: CompanyController.SaveCompanyForm): Company

    fun getCompany(name: String): Company

    fun getCompany(id: Long): Company

    fun getCompanies(): MutableList&lt;Company&gt;

    fun addContactToCompany(firstName: String, lastName: String, companyName: String)

    fun saveContact(contact: Contact): Contact

    fun saveContact(form: CompanyController.SaveContactForm): Contact

    fun saveContact(contact: Contact, companyName: String): Contact

    fun getContact(firstName: String, lastName: String): Contact

    fun getContact(id: Long): Contact

    fun getContacts(): MutableList&lt;Contact&gt;
}
</code></pre>
<p>and then a CompanyServiceImpl:</p>
<pre><code>@Service
@Transactional
class CompanyServiceImpl(
    private val companyRepository: CompanyRepository,
    private val contactRepository: ContactRepository,
) : CompanyService {
    private val log = logger&lt;CompanyServiceImpl&gt;()

    override fun saveCompany(company: Company): Company {
        log.info(&quot;Saving Company ${company.name} to database&quot;)
        return companyRepository.save(company)
    }
...
}
</code></pre>
<p>My question as the subject says is how I would go about unit testing this so I don't have to manually do it which is both time consuming as well as it being &quot;not the right way of doing it&quot;.</p>
<p>Ideally I'd like to have my controllers tested the same way, however I have Spring Security enabled and am unsure if this would get in the way in any way.</p>
",https://stackoverflow.com/questions/74132108/testing-service-layer-in-kotlin-spring-boot-when-back-end-is-using-spring-securi,"['spring-boot', 'unit-testing', 'kotlin', 'testing', 'mockito-kotlin']",110,False,0,0
MuleSoft - mock httpClient.send for extension unit tests,"<p>I have created a custom extension (Connector), which sends an HttpRequest (using <code>org.mule.runtime.http.api.client.HttpClient</code> and the related classes).</p>
<p>The extension's unit tests file contains the following test, to which I've added a simple Mockito mock to throw a TimeoutException when the HTTP request is being sent:</p>
<pre><code>public class DemoOperationsTestCase extends MuleArtifactFunctionalTestCase {

  /**
   * Specifies the mule config xml with the flows that are going to be executed in the tests, this file lives in the test resources.
   */
  @Override
  protected String getConfigFile() {
    return &quot;test-mule-config.xml&quot;;
  }

  @Test
  public void executeSayHiOperation() throws Exception {
      HttpClient httpClient = mock(HttpClient.class);
      HttpRequest httpRequest = mock(HttpRequest.class);
      when(httpClient.send(any(HttpRequest.class), anyInt(), anyBoolean(), any(HttpAuthentication.class))).thenThrow(new TimeoutException());
      String payloadValue = ((String) flowRunner(&quot;sayHiFlow&quot;).run()
                                      .getMessage()
                                      .getPayload()
                                      .getValue());
      assertThat(payloadValue, is(&quot;Hello Mariano Gonzalez!!!&quot;));
  }
}
</code></pre>
<p>The test should fail because the function should throw a TimeoutException, it is what I want for now.</p>
<p>The code that is being tested is as follows (redacted for convenience):</p>
<pre><code>HttpClient client = connection.getHttpClient();
HttpResponse httpResponse = null;
String response = &quot;N/A&quot;;
HttpRequestBuilder builder = HttpRequest.builder();

try {
    httpResponse = client
            .send(builder
                    .addHeader(&quot;Authorization&quot;, authorization)
                    .method(&quot;POST&quot;)
                    .entity(new ByteArrayHttpEntity(&quot;Hello from Mule Connector!&quot;.getBytes()))
                    .uri(destinationUrl)
                    .build(),
                    0, false, null);
    response = IOUtils.toString(httpResponse.getEntity().getContent());
} catch (IOException e) {
    e.printStackTrace();
    throw new ModuleException(DemoError.NO_RESPONSE, new Exception(&quot;Failed to get response&quot;));
} catch (TimeoutException e) {
    e.printStackTrace();
    throw new ModuleException(DemoError.NO_RESPONSE, new Exception(&quot;Connection timed out&quot;));
}
</code></pre>
<p>But I always get the &quot;Failed to get response&quot; error message, which is what I get when I run the Connector with a nonexistent server, therefore the mock isn't working (it actually tries to send an HTTP request).</p>
<p>I am new to Java unit testing, so it might be a general mocking issue and not specific to MuleSoft - though I came across other questions (such as <a href=""https://stackoverflow.com/questions/44584554/mockito-when-is-not-working"">this one</a> and <a href=""https://stackoverflow.com/questions/20542361/mocking-apache-httpclient-using-mockito"">this one</a>), I tried the suggestions in the answers and the comments, but I get the same error. I even tried to use thenReturn instead of thenThrow, and I get the same error - so the mock isn't working.</p>
<p>Any idea why this is happening?</p>
",https://stackoverflow.com/questions/74042838/mulesoft-mock-httpclient-send-for-extension-unit-tests,"['java', 'unit-testing', 'mockito', 'mulesoft']",91,False,0,0
How to mock class methods inside another class methods which we would like to implement unit test using Junit and Mockito?,"<p>My code does 3 things in summary:</p>
<ul>
<li>If-else block to check some conditions (I want to test only that part)</li>
<li>Kill some application using put request (Which I want to mock and do not execute during unit test)</li>
<li>Create http connection to get Json string to check conditions (Which I want to mock and use pre-defined json object in assert method instead)</li>
</ul>
<p><strong>Here is my method which I would like to implement unit testing for if-else conditions:</strong></p>
<pre><code>public String checkYarnApplications() throws IOException {

    String infoMessage = null;

    ObjectGetter objectGetter = new ObjectGetter(getUrlAddress());

    JSONObject j = objectGetter.objectGetter();

    // Initialize stringbuilder to build slack message
    StringBuilder stringBuilder = new StringBuilder();

    // Iterate through number of existing yarn application
    for (int i = 0; i &lt; j.getJSONObject(&quot;apps&quot;).getJSONArray(&quot;app&quot;).length(); i++){

        JSONObject name = j.getJSONObject(&quot;apps&quot;)
                .getJSONArray(&quot;app&quot;)
                .getJSONObject(i);

        String state = name.get(&quot;state&quot;).toString();

        // Check if application is in Running state
        if (state.equals(&quot;RUNNING&quot;)){

            // Get elapsed time for each running application and convert it to hour
            int elapsed_time = name.getInt(&quot;elapsedTime&quot;)/3600000;
            // Get application name
            String app_name = name.get(&quot;name&quot;).toString();
            // Get application queue_name
            String queue_name = name.get(&quot;queue&quot;).toString();
            // Get application user_name
            String user_name = name.get(&quot;user&quot;).toString();

            // Check if pyspark applications last longer than specified time in config.properties
            if (app_name.startsWith(&quot;pyspark-shell&quot;) &amp;&amp; elapsed_time &gt; getSparkCheckTime()){
                String app_id = name.get(&quot;id&quot;).toString();
                String infoMessageSpark = &quot;pyspark application &quot; + app_id + &quot; has been killed because it takes longer than &quot; +
                        getSparkCheckTime() + &quot; hours. Elapsed Time:&quot; + elapsed_time + &quot; hours&quot;;
                infoMessage = infoMessageSpark;
                logger.info(infoMessageSpark);
                logger.info(name.toString());
                // Kill yarn application
                AppKiller appKiller = new AppKiller(String.format(&quot;%s%s/state?user.name=atlasapp&quot;,getUrlAddress(),app_id));
                appKiller.appKiller();
                // Add info message to slackmessage string builder
                stringBuilder.append(infoMessageSpark);
                stringBuilder.append(&quot;\n&quot;);
            }
            // Check if self_bi applications last longer than specified time in config.properties
            else if (!queue_name.equals(&quot;yarn-system&quot;) &amp;&amp; !queue_name.equals(&quot;hudi&quot;) &amp;&amp; !queue_name.equals(&quot;hepsistream&quot;) &amp;&amp;
                    !app_name.equals(&quot;Bzip2Hdfs&quot;) &amp;&amp; !user_name.equals(&quot;spark&quot;) &amp;&amp; !user_name.equals(&quot;yarn-ats&quot;) &amp;&amp;
                    !app_name.startsWith(&quot;pyspark-shell&quot;) &amp;&amp; !queue_name.equals(&quot;llap&quot;) &amp;&amp; elapsed_time &gt; getappCheckTime()){
                String app_id = name.get(&quot;id&quot;).toString();
                String infoMessageSb = queue_name + &quot; application, &quot; + app_id + &quot; has been killed because it takes longer than &quot;
                        + getappCheckTime() + &quot; hours. Elapsed Time:&quot; + elapsed_time + &quot; hours&quot;;
                infoMessage = infoMessageSb;
                logger.info(infoMessageSb);
                logger.info(name.toString());
                // Kill yarn application
                AppKiller appKiller = new AppKiller(String.format(&quot;%s%s/state?user.name=atlasapp&quot;,getUrlAddress(),app_id));
                appKiller.appKiller();
                // Add info message to slackmessage string builder
                stringBuilder.append(infoMessageSb);
                stringBuilder.append(&quot;\n&quot;);
            }
            // Check if any application except hudi, llap last longer than specified time in config.properties and send them to slack channel
            else if (!queue_name.equals(&quot;hudi&quot;) &amp;&amp; !queue_name.equals(&quot;llap&quot;) &amp;&amp; !queue_name.equals(&quot;hepsistream&quot;) &amp;&amp;
                    !queue_name.equals(&quot;yarn-system&quot;) &amp;&amp; !user_name.equals(&quot;yarn-ats&quot;) &amp;&amp;
                    !app_name.startsWith(&quot;pyspark-shell&quot;) &amp;&amp; !app_name.equals(&quot;Bzip2Hdfs&quot;) &amp;&amp; !user_name.equals(&quot;spark&quot;) &amp;&amp;
                    elapsed_time &gt; getCheckTime()){
                logger.info(&quot;Application_id: &quot; + name.get(&quot;id&quot;).toString() + &quot; is running longer than &quot; +  getCheckTime() + &quot; hours&quot;);
                String textMessage =&quot;Elapsed time: &quot; + elapsed_time + &quot; hours&quot; + &quot;, &quot; +
                        &quot;Application_Id: &quot; + name.get(&quot;id&quot;).toString() + &quot;, &quot; +
                        &quot;Username: &quot; + name.get(&quot;user&quot;).toString() + &quot;, &quot; +
                        &quot;Queuename:&quot; + name.get(&quot;queue&quot;).toString() + &quot;, &quot; +
                        &quot;Usage:&quot; + name.get(&quot;clusterUsagePercentage&quot;).toString();
                stringBuilder.append(textMessage);
                stringBuilder.append(&quot;\n&quot;);
            }
        }

    }
}
</code></pre>
<p><em>Some notes about the code:</em></p>
<ol>
<li>ObjectGetter is another class created to get Json object using http connection</li>
<li>Appkiller is another class created to kill some application using put request if conditions are met</li>
</ol>
<p><strong>I tried to mock both of them and only test if-else conditions using test code below:</strong></p>
<pre><code>class YarnModelTest {

private YarnModel yarnModel;
private static final ObjectGetter objectGetter = mock(ObjectGetter.class);
private static final AppKiller appKiller = mock(AppKiller.class);

@Before
public void setup() throws IOException {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    try (InputStream input = classloader.getResourceAsStream(&quot;config.properties&quot;)) {

        Properties properties = new Properties();

        // load a properties file
        properties.load(input);
        ObjectMapper mapper = new ObjectMapper();
        Map&lt;String, Object&gt; map = mapper.readValue(properties.getProperty(&quot;jsonString&quot;), Map.class);
        Scenerio scenerio = new Scenerio(map);
        when(objectGetter.objectGetter()).thenReturn((JSONObject) scenerio.getJsonObject());
        Mockito.doNothing().when(objectGetter).objectGetter();
        Mockito.doNothing().when(appKiller).appKiller();

    }
}

@Test
void checkSparkCheckTime() {
    YarnModel yarnModel = new YarnModel(&quot;http://localhost:8080&quot;, 24, 48, 24, &quot;http://localhost:7070&quot;);
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    try (InputStream input = classloader.getResourceAsStream(&quot;config.properties&quot;)) {

        Properties properties = new Properties();

        // load a properties file
        properties.load(input);
        String test = properties.getProperty(&quot;sparkTest&quot;);
        ObjectMapper mapper = new ObjectMapper();
        Map&lt;String, Object&gt; map = mapper.readValue(properties.getProperty(&quot;jsonString&quot;), Map.class);
        assertEquals(test, yarnModel.checkYarnApplications());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code></pre>
<p>}</p>
<p>Some notes about test code:</p>
<ol>
<li>Properties using to get pre-defined json string form comparison in unit test</li>
<li>yarnModel.checkYarnApplications() method returns some string according to conditions and I only would like to check if they are equal or not.</li>
</ol>
<p><strong>Problem:</strong></p>
<p>I am getting below error and as I understand from error my mocks are not correct and code still trying to create http connection. Any advice will be appreciated</p>
<pre><code>java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:607)
at java.net.Socket.connect(Socket.java:556)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
at sun.net.www.http.HttpClient.&lt;init&gt;(HttpClient.java:242)
at sun.net.www.http.HttpClient.New(HttpClient.java:339)
at sun.net.www.http.HttpClient.New(HttpClient.java:357)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1223)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1162)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1056)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:990)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1567)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1495)
at java.net.URL.openStream(URL.java:1093)
at com.fasterxml.jackson.core.TokenStreamFactory._optimizedStreamFromURL(TokenStreamFactory.java:211)
at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:1055)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3561)
at com.hepsiburada.Utils.ObjectGetter.objectGetter(ObjectGetter.java:33)
at com.hepsiburada.Model.YarnModel.checkYarnApplications(YarnModel.java:77)
at com.hepsiburada.Model.YarnModelTest.checkSparkCheckTime(YarnModelTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
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$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
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:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
</code></pre>
",https://stackoverflow.com/questions/71363291/how-to-mock-class-methods-inside-another-class-methods-which-we-would-like-to-im,"['java', 'unit-testing', 'testing', 'junit', 'mockito']",1276,True,0,1
Automatically resolve undefined references from missing library with stubs?,"<p>I am building some unit testing stuff for a C/(C++) project that was developed for MSVC. I need to port it to g++ / MinGw. There is a library (DLL) that was build with VS. I can not get this library to link with the rest of the code, i always get undefined reference errors. It seems that the name mangeling between MSVC and g++ not compatible. Unfortunately I can not recompile the library with g++ because it uses some Microsoft Stuff that is incompatible with g++ (MFC/AFX).</p>
<p>So I wonder if there is any way to tell g++ to replace all undefined references with simple stub functions that just return 0 or Null.</p>
<p>Because I dont really need any of the functions, and I won't even call functions that call any of the missing functions. I just want to have something there so that the project compiles without changing the code that i want to test.</p>
<p>Is there any way to do that? Is there a tool that maybe extracts all the exposed functions and creates a replacement lib that only contains the stub functions?</p>
",https://stackoverflow.com/questions/71593938/automatically-resolve-undefined-references-from-missing-library-with-stubs,"['c++', 'visual-studio', 'gcc', 'mingw']",112,False,0,0
testing form fields as a shadow dom elements with react testing-library and jest,"<p>We have our own web component and using the same with react component as generic-component. I am trying to test those <strong>custom elements</strong> which are created inside the shadow dom for our form-fields.
Now there are multiple input fields in my form. I am only able to access one but not others i.e only one field. I am using react-hook-form to handle the form stimulation.</p>
<p>I tried the below query and looped over each input to get the element</p>
<pre><code>const customInput = document.querySelectorAll(&quot;hds-input&quot;)
customInput.shadowRoot.querySelector(&quot;input[name='mapName']&quot;)
</code></pre>
<pre><code>  it(&quot;check form input fields with dummy values&quot;, async () =&gt; {
    render(&lt;Order3DMaps /&gt;);
    const form = document.querySelector(&quot;form&quot;);
    expect(form).toBeInTheDocument();

    expect(screen.getByText(&quot;Basic Information&quot;)).toBeInTheDocument();
    //get the field and add use input value
    const hdsInput = document.querySelectorAll(&quot;hds-input&quot;);
    hdsInput.forEach((element) =&gt; {
      const mapName = element.shadowRoot.querySelector(&quot;input[name='mapName']&quot;);
      const rawDataSiteName = element.shadowRoot.querySelector(&quot;input[name='rawDataSiteName']&quot;); 
      userEvent.type(mapName, &quot;testmapname&quot;);
      const organizationId = element.querySelector(
        &quot;input[name='organizationId']&quot;
      );
      expect(organizationId).toBeDisabled();
    });
</code></pre>
<p>In the above test case <strong>rawDataSiteName</strong> is always null. However, when I debug in the browser console and see the dom element, it's present but not accessible while writing a test case.</p>
<p>My idea here is to get the element and do <strong>userEvent</strong> like type and click on form fields to cover the unit testing. However, after spending a lot of time got to know that the <strong>testing library</strong> is not supporting shadow-dom which I found strange. As it is a dom testing library it should support all the dom.</p>
<p>Please help me to understand what I am missing here. Any help is appreciated.
Thanks</p>
",https://stackoverflow.com/questions/74929633/testing-form-fields-as-a-shadow-dom-elements-with-react-testing-library-and-jest,"['javascript', 'reactjs', 'jestjs', 'react-testing-library', 'react-hook-form']",1036,False,0,0
How to mock class methods inside another class methods which we would like to implement unit test using Junit and Mockito?,"<p>My code does 3 things in summary:</p>
<ul>
<li>If-else block to check some conditions (I want to test only that part)</li>
<li>Kill some application using put request (Which I want to mock and do not execute during unit test)</li>
<li>Create http connection to get Json string to check conditions (Which I want to mock and use pre-defined json object in assert method instead)</li>
</ul>
<p><strong>Here is my method which I would like to implement unit testing for if-else conditions:</strong></p>
<pre><code>public String checkYarnApplications() throws IOException {

    String infoMessage = null;

    ObjectGetter objectGetter = new ObjectGetter(getUrlAddress());

    JSONObject j = objectGetter.objectGetter();

    // Initialize stringbuilder to build slack message
    StringBuilder stringBuilder = new StringBuilder();

    // Iterate through number of existing yarn application
    for (int i = 0; i &lt; j.getJSONObject(&quot;apps&quot;).getJSONArray(&quot;app&quot;).length(); i++){

        JSONObject name = j.getJSONObject(&quot;apps&quot;)
                .getJSONArray(&quot;app&quot;)
                .getJSONObject(i);

        String state = name.get(&quot;state&quot;).toString();

        // Check if application is in Running state
        if (state.equals(&quot;RUNNING&quot;)){

            // Get elapsed time for each running application and convert it to hour
            int elapsed_time = name.getInt(&quot;elapsedTime&quot;)/3600000;
            // Get application name
            String app_name = name.get(&quot;name&quot;).toString();
            // Get application queue_name
            String queue_name = name.get(&quot;queue&quot;).toString();
            // Get application user_name
            String user_name = name.get(&quot;user&quot;).toString();

            // Check if pyspark applications last longer than specified time in config.properties
            if (app_name.startsWith(&quot;pyspark-shell&quot;) &amp;&amp; elapsed_time &gt; getSparkCheckTime()){
                String app_id = name.get(&quot;id&quot;).toString();
                String infoMessageSpark = &quot;pyspark application &quot; + app_id + &quot; has been killed because it takes longer than &quot; +
                        getSparkCheckTime() + &quot; hours. Elapsed Time:&quot; + elapsed_time + &quot; hours&quot;;
                infoMessage = infoMessageSpark;
                logger.info(infoMessageSpark);
                logger.info(name.toString());
                // Kill yarn application
                AppKiller appKiller = new AppKiller(String.format(&quot;%s%s/state?user.name=atlasapp&quot;,getUrlAddress(),app_id));
                appKiller.appKiller();
                // Add info message to slackmessage string builder
                stringBuilder.append(infoMessageSpark);
                stringBuilder.append(&quot;\n&quot;);
            }
            // Check if self_bi applications last longer than specified time in config.properties
            else if (!queue_name.equals(&quot;yarn-system&quot;) &amp;&amp; !queue_name.equals(&quot;hudi&quot;) &amp;&amp; !queue_name.equals(&quot;hepsistream&quot;) &amp;&amp;
                    !app_name.equals(&quot;Bzip2Hdfs&quot;) &amp;&amp; !user_name.equals(&quot;spark&quot;) &amp;&amp; !user_name.equals(&quot;yarn-ats&quot;) &amp;&amp;
                    !app_name.startsWith(&quot;pyspark-shell&quot;) &amp;&amp; !queue_name.equals(&quot;llap&quot;) &amp;&amp; elapsed_time &gt; getappCheckTime()){
                String app_id = name.get(&quot;id&quot;).toString();
                String infoMessageSb = queue_name + &quot; application, &quot; + app_id + &quot; has been killed because it takes longer than &quot;
                        + getappCheckTime() + &quot; hours. Elapsed Time:&quot; + elapsed_time + &quot; hours&quot;;
                infoMessage = infoMessageSb;
                logger.info(infoMessageSb);
                logger.info(name.toString());
                // Kill yarn application
                AppKiller appKiller = new AppKiller(String.format(&quot;%s%s/state?user.name=atlasapp&quot;,getUrlAddress(),app_id));
                appKiller.appKiller();
                // Add info message to slackmessage string builder
                stringBuilder.append(infoMessageSb);
                stringBuilder.append(&quot;\n&quot;);
            }
            // Check if any application except hudi, llap last longer than specified time in config.properties and send them to slack channel
            else if (!queue_name.equals(&quot;hudi&quot;) &amp;&amp; !queue_name.equals(&quot;llap&quot;) &amp;&amp; !queue_name.equals(&quot;hepsistream&quot;) &amp;&amp;
                    !queue_name.equals(&quot;yarn-system&quot;) &amp;&amp; !user_name.equals(&quot;yarn-ats&quot;) &amp;&amp;
                    !app_name.startsWith(&quot;pyspark-shell&quot;) &amp;&amp; !app_name.equals(&quot;Bzip2Hdfs&quot;) &amp;&amp; !user_name.equals(&quot;spark&quot;) &amp;&amp;
                    elapsed_time &gt; getCheckTime()){
                logger.info(&quot;Application_id: &quot; + name.get(&quot;id&quot;).toString() + &quot; is running longer than &quot; +  getCheckTime() + &quot; hours&quot;);
                String textMessage =&quot;Elapsed time: &quot; + elapsed_time + &quot; hours&quot; + &quot;, &quot; +
                        &quot;Application_Id: &quot; + name.get(&quot;id&quot;).toString() + &quot;, &quot; +
                        &quot;Username: &quot; + name.get(&quot;user&quot;).toString() + &quot;, &quot; +
                        &quot;Queuename:&quot; + name.get(&quot;queue&quot;).toString() + &quot;, &quot; +
                        &quot;Usage:&quot; + name.get(&quot;clusterUsagePercentage&quot;).toString();
                stringBuilder.append(textMessage);
                stringBuilder.append(&quot;\n&quot;);
            }
        }

    }
}
</code></pre>
<p><em>Some notes about the code:</em></p>
<ol>
<li>ObjectGetter is another class created to get Json object using http connection</li>
<li>Appkiller is another class created to kill some application using put request if conditions are met</li>
</ol>
<p><strong>I tried to mock both of them and only test if-else conditions using test code below:</strong></p>
<pre><code>class YarnModelTest {

private YarnModel yarnModel;
private static final ObjectGetter objectGetter = mock(ObjectGetter.class);
private static final AppKiller appKiller = mock(AppKiller.class);

@Before
public void setup() throws IOException {
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    try (InputStream input = classloader.getResourceAsStream(&quot;config.properties&quot;)) {

        Properties properties = new Properties();

        // load a properties file
        properties.load(input);
        ObjectMapper mapper = new ObjectMapper();
        Map&lt;String, Object&gt; map = mapper.readValue(properties.getProperty(&quot;jsonString&quot;), Map.class);
        Scenerio scenerio = new Scenerio(map);
        when(objectGetter.objectGetter()).thenReturn((JSONObject) scenerio.getJsonObject());
        Mockito.doNothing().when(objectGetter).objectGetter();
        Mockito.doNothing().when(appKiller).appKiller();

    }
}

@Test
void checkSparkCheckTime() {
    YarnModel yarnModel = new YarnModel(&quot;http://localhost:8080&quot;, 24, 48, 24, &quot;http://localhost:7070&quot;);
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    try (InputStream input = classloader.getResourceAsStream(&quot;config.properties&quot;)) {

        Properties properties = new Properties();

        // load a properties file
        properties.load(input);
        String test = properties.getProperty(&quot;sparkTest&quot;);
        ObjectMapper mapper = new ObjectMapper();
        Map&lt;String, Object&gt; map = mapper.readValue(properties.getProperty(&quot;jsonString&quot;), Map.class);
        assertEquals(test, yarnModel.checkYarnApplications());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code></pre>
<p>}</p>
<p>Some notes about test code:</p>
<ol>
<li>Properties using to get pre-defined json string form comparison in unit test</li>
<li>yarnModel.checkYarnApplications() method returns some string according to conditions and I only would like to check if they are equal or not.</li>
</ol>
<p><strong>Problem:</strong></p>
<p>I am getting below error and as I understand from error my mocks are not correct and code still trying to create http connection. Any advice will be appreciated</p>
<pre><code>java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:607)
at java.net.Socket.connect(Socket.java:556)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
at sun.net.www.http.HttpClient.&lt;init&gt;(HttpClient.java:242)
at sun.net.www.http.HttpClient.New(HttpClient.java:339)
at sun.net.www.http.HttpClient.New(HttpClient.java:357)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1223)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1162)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1056)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:990)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1567)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1495)
at java.net.URL.openStream(URL.java:1093)
at com.fasterxml.jackson.core.TokenStreamFactory._optimizedStreamFromURL(TokenStreamFactory.java:211)
at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:1055)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3561)
at com.hepsiburada.Utils.ObjectGetter.objectGetter(ObjectGetter.java:33)
at com.hepsiburada.Model.YarnModel.checkYarnApplications(YarnModel.java:77)
at com.hepsiburada.Model.YarnModelTest.checkSparkCheckTime(YarnModelTest.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
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$7(TestMethodTestDescriptor.java:214)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at java.util.ArrayList.forEach(ArrayList.java:1259)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
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:114)
at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:71)
at com.intellij.rt.junit.IdeaTestRunner$Repeater$1.execute(IdeaTestRunner.java:38)
at com.intellij.rt.execution.junit.TestsRepeater.repeat(TestsRepeater.java:11)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:35)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:235)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:54)
</code></pre>
",https://stackoverflow.com/questions/71363291/how-to-mock-class-methods-inside-another-class-methods-which-we-would-like-to-im,"['java', 'unit-testing', 'testing', 'junit', 'mockito']",1276,True,0,1
Automatically resolve undefined references from missing library with stubs?,"<p>I am building some unit testing stuff for a C/(C++) project that was developed for MSVC. I need to port it to g++ / MinGw. There is a library (DLL) that was build with VS. I can not get this library to link with the rest of the code, i always get undefined reference errors. It seems that the name mangeling between MSVC and g++ not compatible. Unfortunately I can not recompile the library with g++ because it uses some Microsoft Stuff that is incompatible with g++ (MFC/AFX).</p>
<p>So I wonder if there is any way to tell g++ to replace all undefined references with simple stub functions that just return 0 or Null.</p>
<p>Because I dont really need any of the functions, and I won't even call functions that call any of the missing functions. I just want to have something there so that the project compiles without changing the code that i want to test.</p>
<p>Is there any way to do that? Is there a tool that maybe extracts all the exposed functions and creates a replacement lib that only contains the stub functions?</p>
",https://stackoverflow.com/questions/71593938/automatically-resolve-undefined-references-from-missing-library-with-stubs,"['c++', 'visual-studio', 'gcc', 'mingw']",112,False,0,0
Testing Service layer in Kotlin Spring Boot when back end is using Spring Security,"<p>I'm looking to try and test my back end Service layer (ideally along with my Controller layer too). However, I'm not sure how I would be able to go about doing this.</p>
<p>I saw that I can use Mockito to do this, however, I was not able to figure out how to apply this with what I currently have.</p>
<p>I have the entity, then repository, service and then finally controller.</p>
<p>My services have the main logic for the application within. For example, saving an entity, fetching and updating.</p>
<p>My controller (which is a restcontroller) is what my front end client interfaces with in order to call the service methods.</p>
<p>My service has an interface like below:</p>
<pre><code>interface CompanyService {

    fun saveCompany(company: Company): Company

    fun saveCompany(form: CompanyController.SaveCompanyForm): Company

    fun getCompany(name: String): Company

    fun getCompany(id: Long): Company

    fun getCompanies(): MutableList&lt;Company&gt;

    fun addContactToCompany(firstName: String, lastName: String, companyName: String)

    fun saveContact(contact: Contact): Contact

    fun saveContact(form: CompanyController.SaveContactForm): Contact

    fun saveContact(contact: Contact, companyName: String): Contact

    fun getContact(firstName: String, lastName: String): Contact

    fun getContact(id: Long): Contact

    fun getContacts(): MutableList&lt;Contact&gt;
}
</code></pre>
<p>and then a CompanyServiceImpl:</p>
<pre><code>@Service
@Transactional
class CompanyServiceImpl(
    private val companyRepository: CompanyRepository,
    private val contactRepository: ContactRepository,
) : CompanyService {
    private val log = logger&lt;CompanyServiceImpl&gt;()

    override fun saveCompany(company: Company): Company {
        log.info(&quot;Saving Company ${company.name} to database&quot;)
        return companyRepository.save(company)
    }
...
}
</code></pre>
<p>My question as the subject says is how I would go about unit testing this so I don't have to manually do it which is both time consuming as well as it being &quot;not the right way of doing it&quot;.</p>
<p>Ideally I'd like to have my controllers tested the same way, however I have Spring Security enabled and am unsure if this would get in the way in any way.</p>
",https://stackoverflow.com/questions/74132108/testing-service-layer-in-kotlin-spring-boot-when-back-end-is-using-spring-securi,"['spring-boot', 'unit-testing', 'kotlin', 'testing', 'mockito-kotlin']",110,False,0,0
MuleSoft - mock httpClient.send for extension unit tests,"<p>I have created a custom extension (Connector), which sends an HttpRequest (using <code>org.mule.runtime.http.api.client.HttpClient</code> and the related classes).</p>
<p>The extension's unit tests file contains the following test, to which I've added a simple Mockito mock to throw a TimeoutException when the HTTP request is being sent:</p>
<pre><code>public class DemoOperationsTestCase extends MuleArtifactFunctionalTestCase {

  /**
   * Specifies the mule config xml with the flows that are going to be executed in the tests, this file lives in the test resources.
   */
  @Override
  protected String getConfigFile() {
    return &quot;test-mule-config.xml&quot;;
  }

  @Test
  public void executeSayHiOperation() throws Exception {
      HttpClient httpClient = mock(HttpClient.class);
      HttpRequest httpRequest = mock(HttpRequest.class);
      when(httpClient.send(any(HttpRequest.class), anyInt(), anyBoolean(), any(HttpAuthentication.class))).thenThrow(new TimeoutException());
      String payloadValue = ((String) flowRunner(&quot;sayHiFlow&quot;).run()
                                      .getMessage()
                                      .getPayload()
                                      .getValue());
      assertThat(payloadValue, is(&quot;Hello Mariano Gonzalez!!!&quot;));
  }
}
</code></pre>
<p>The test should fail because the function should throw a TimeoutException, it is what I want for now.</p>
<p>The code that is being tested is as follows (redacted for convenience):</p>
<pre><code>HttpClient client = connection.getHttpClient();
HttpResponse httpResponse = null;
String response = &quot;N/A&quot;;
HttpRequestBuilder builder = HttpRequest.builder();

try {
    httpResponse = client
            .send(builder
                    .addHeader(&quot;Authorization&quot;, authorization)
                    .method(&quot;POST&quot;)
                    .entity(new ByteArrayHttpEntity(&quot;Hello from Mule Connector!&quot;.getBytes()))
                    .uri(destinationUrl)
                    .build(),
                    0, false, null);
    response = IOUtils.toString(httpResponse.getEntity().getContent());
} catch (IOException e) {
    e.printStackTrace();
    throw new ModuleException(DemoError.NO_RESPONSE, new Exception(&quot;Failed to get response&quot;));
} catch (TimeoutException e) {
    e.printStackTrace();
    throw new ModuleException(DemoError.NO_RESPONSE, new Exception(&quot;Connection timed out&quot;));
}
</code></pre>
<p>But I always get the &quot;Failed to get response&quot; error message, which is what I get when I run the Connector with a nonexistent server, therefore the mock isn't working (it actually tries to send an HTTP request).</p>
<p>I am new to Java unit testing, so it might be a general mocking issue and not specific to MuleSoft - though I came across other questions (such as <a href=""https://stackoverflow.com/questions/44584554/mockito-when-is-not-working"">this one</a> and <a href=""https://stackoverflow.com/questions/20542361/mocking-apache-httpclient-using-mockito"">this one</a>), I tried the suggestions in the answers and the comments, but I get the same error. I even tried to use thenReturn instead of thenThrow, and I get the same error - so the mock isn't working.</p>
<p>Any idea why this is happening?</p>
",https://stackoverflow.com/questions/74042838/mulesoft-mock-httpclient-send-for-extension-unit-tests,"['java', 'unit-testing', 'mockito', 'mulesoft']",91,False,0,0
testing form fields as a shadow dom elements with react testing-library and jest,"<p>We have our own web component and using the same with react component as generic-component. I am trying to test those <strong>custom elements</strong> which are created inside the shadow dom for our form-fields.
Now there are multiple input fields in my form. I am only able to access one but not others i.e only one field. I am using react-hook-form to handle the form stimulation.</p>
<p>I tried the below query and looped over each input to get the element</p>
<pre><code>const customInput = document.querySelectorAll(&quot;hds-input&quot;)
customInput.shadowRoot.querySelector(&quot;input[name='mapName']&quot;)
</code></pre>
<pre><code>  it(&quot;check form input fields with dummy values&quot;, async () =&gt; {
    render(&lt;Order3DMaps /&gt;);
    const form = document.querySelector(&quot;form&quot;);
    expect(form).toBeInTheDocument();

    expect(screen.getByText(&quot;Basic Information&quot;)).toBeInTheDocument();
    //get the field and add use input value
    const hdsInput = document.querySelectorAll(&quot;hds-input&quot;);
    hdsInput.forEach((element) =&gt; {
      const mapName = element.shadowRoot.querySelector(&quot;input[name='mapName']&quot;);
      const rawDataSiteName = element.shadowRoot.querySelector(&quot;input[name='rawDataSiteName']&quot;); 
      userEvent.type(mapName, &quot;testmapname&quot;);
      const organizationId = element.querySelector(
        &quot;input[name='organizationId']&quot;
      );
      expect(organizationId).toBeDisabled();
    });
</code></pre>
<p>In the above test case <strong>rawDataSiteName</strong> is always null. However, when I debug in the browser console and see the dom element, it's present but not accessible while writing a test case.</p>
<p>My idea here is to get the element and do <strong>userEvent</strong> like type and click on form fields to cover the unit testing. However, after spending a lot of time got to know that the <strong>testing library</strong> is not supporting shadow-dom which I found strange. As it is a dom testing library it should support all the dom.</p>
<p>Please help me to understand what I am missing here. Any help is appreciated.
Thanks</p>
",https://stackoverflow.com/questions/74929633/testing-form-fields-as-a-shadow-dom-elements-with-react-testing-library-and-jest,"['javascript', 'reactjs', 'jestjs', 'react-testing-library', 'react-hook-form']",1036,False,0,0
Eclipse unable to resolve maven test dependency,"<p>I'm running into a bit of a strange issue with eclipse 4.18 that I'm hoping someone can help me with. My project is a jetty webapp that does some communication with an external server over FTP. I'm using mockftpserver (<a href=""https://mockftpserver.org/"" rel=""nofollow noreferrer"">https://mockftpserver.org/</a>) to assist with unit testing the code that needs to communicate with the FTP server.</p>
<p>I have the library dependency defined in the pom as</p>
<pre><code> &lt;dependency&gt;
    &lt;groupId&gt;org.mockftpserver&lt;/groupId&gt;
    &lt;artifactId&gt;MockFtpServer&lt;/artifactId&gt;
    &lt;version&gt;3.0.0&lt;/version&gt;
    &lt;scope&gt;test&lt;/scope&gt;
 &lt;/dependency&gt;
</code></pre>
<p>I then have an import defined in my test class like</p>
<pre><code>package my.project.test;
import org.mockftpserver.fake.FakeFtpServer;

public class TestGuiceModule extends GuiceModule {
}
</code></pre>
<p>Nothing too exotic going on, and maven seems to be able to run the compile. Eclipse however does not seem to be able to see the library. I have a bunch of errors along the lines of</p>
<blockquote>
<p>The import org.mockftpserver cannot be resolved.</p>
</blockquote>
<p>I double checked the build path and I can see the library listed under 'Maven Dependencies' and the package structure of the jar matches my import statement. Even stranger, I have other 'test' scoped dependencies in the pom.xml and eclipse is detecting those just fine. I'm at a bit of a loss as to why it is having an issue with this one particular library. Any suggestions on what I could do to track this down?</p>
",https://stackoverflow.com/questions/71426198/eclipse-unable-to-resolve-maven-test-dependency,"['java', 'eclipse', 'maven', 'unit-testing', 'mocking']",138,False,0,1
Pytest does not output junitxml when running in Databricks repo,"<p>We have a Databricks platform where repos and files in repos are enabled.  As such, we can have .py files within the repos which can be called by Databricks notebooks.</p>
<p>We are currently testing the viability of running our unit tests on Databricks clusters instead of using a (PySpark) image in our Git / CI environment.</p>
<p>The repo within Databricks looks like</p>
<pre><code>| - notebook
| - mycode.py
| - mycode_test.py
</code></pre>
<p>Here, <code>mycode.py</code> contains a function that applies a transformation on a Spark Dataframe. The file <code>mycode_test.py</code> contains an unit test build with <strong>pytest</strong> (and some fixtures to create test data and handling the Spark session / Spark context).</p>
<p>We run pytest from the notebook, instead of from the command line.  Hence, the Databricks notebook looks like:</p>
<pre class=""lang-py prettyprint-override""><code>import pytest

retcode = pytest.main(['-k', 'mycode_test',
                       '-o', 'cache_dir=/dbfs/FileStore/',
                       '--junitxml', '/dbfs/FileStore/pytestreport.xml',
                       '-v'
                      ]
                     )
</code></pre>
<p>This code snippet runs fine on a standard Databricks cluster (with runtime 10.4 LTS and pytest installed) and the results of the unit testing are printed out below the cell.</p>
<p>However, no output is stored at the cache directory or the pointer for the junit xml file.</p>
<p>Questions:</p>
<ul>
<li>Are we missing something here?</li>
<li>Can we assume that it actually generated output at an unknown location because the <code>pytest.main</code> did not crash?</li>
<li>Are the .fuse-mounts within Databricks causing the issue here?</li>
</ul>
",https://stackoverflow.com/questions/72799347/pytest-does-not-output-junitxml-when-running-in-databricks-repo,"['python', 'pytest', 'databricks']",347,True,0,1
Mock a third party library Class in C#,"<p>Let's say I have a class like this:</p>
<pre><code>    public class PersonProcessor()
    {
        private MySqlDbConn sqlConn;

        public PersonProcessor(MySqlDbConn sqlConn)
        {
            this.sqlConn = sqlConn;
        }

        public SqlResult GetAllPersons()
        {
            var query = &quot;select * from person&quot;;
            var result = sqlConn.executeQuery(query);
            return result;
        }

        // Some other methods I want to test as well
    }
</code></pre>
<p>How would I go on about unit testing this class?
I'd like to test the <code>GetAllPersons()</code> method without actually having to create a real connection to a real database (this is especially the case when I do any write operations)</p>
<p>This is what I have so far: To create an instance of my <code>PersonProcessor</code> class I need to give the class a Sql connection. Unfortunately the <strong>Sql connection object is from a third party library</strong>, in this case from a SQL library. This means that I am unable to create a Mock object of it to generate a fake connection, which should return predefined values, because Moq only supports abstract classes and interfaces.</p>
<p>How do I solve this problem? Should I just create a wrapper class, which calls the exact same functions and implements an interface and then restructure the entire programm to se the wrapper classe with the interface just to unit test a simple function?</p>
<p>I don't believe that my idea would be the best solution and wonder what else could be done to fix this problem. Is there mayybe another way to mock entire tird party classes?</p>
",https://stackoverflow.com/questions/74642906/mock-a-third-party-library-class-in-c,"['c#', 'unit-testing', 'mocking', 'moq']",291,False,0,0
Nunit 3: Test a Controller that uses IHttpClientFactory as Constructor Parameter,"<p><strong>Update 20221024</strong>: I have used Ruikai Feng's solution in order to use Mockoon with my tests. I realize this is not a correct approach from a unit testing approach and am working to change my approach.</p>
<p><strong>Update 20221019</strong>: I have been using moq to mock out the IHttpClientFactory. The reason why I wanted to instantiate it was to call mock apis created in a tool called Mockoon which replicates apis. I have been so far unable to call these APIs likely because I have not yet properly mocked the ihttpclientfactory. I appreciate all the feedback as the solution is still ongoing at this time.</p>
<p>I am using a .NET 6 Web API controller with IHttpClientFactory to perform external API calls. As such, I have the following constructor:</p>
<pre class=""lang-cs prettyprint-override""><code>public MyController(IHttpClientFactory httpClientFactory)
{
  _httpClientFactory = httpClientFactory;
}
</code></pre>
<p>This works because in my <code>Program.cs</code> I add an HTTP Client to my <code>builder.Services</code>.</p>
<p>In my tests, how do I instantiate/set up the <code>httpClientFactory</code> for the controller because I need it to instantiate my controller: <code>var controller = new MyController(httpClientFactory);</code> generates an error since there isn't any settings added.</p>
<p>I ran into a similar issue with configurations from appsettings.json and resolved with <code>ConfigurationBuilder</code> but there doesn't seem to be a similar one for <code>IHttpClientFactory</code>.</p>
<p>If you need any more information, please let me know. Thanks!</p>
",https://stackoverflow.com/questions/74063191/nunit-3-test-a-controller-that-uses-ihttpclientfactory-as-constructor-parameter,"['c#', 'asp.net-core', '.net-core', 'dotnet-httpclient', 'httpclientfactory']",477,True,2,2
Custom Module with Custom Python Package - Module not found error,"<p>I wrote a custom python package for Ansible to handle business logic for some servers I manage. I have multiple files and they reference each other by re-importing the package.</p>
<p>So my package named <code>&lt;MyCustomPackage&gt;</code> has functions <code>&lt;Function1&gt; &lt;Function2&gt; &lt;Function3&gt;</code>, etc all in their own files... Some of these functions reference functions in the same package, so to do that the file has:</p>
<pre><code>import MyCustomPackage
</code></pre>
<p>at the top. I did it this way instead of a relative import because I'm also unit testing these and mocking would not work with relative paths because of a <code>__init__</code> file in the test directory which was needed for test discovery. The only way I could mock was through importing the package itself. Seemed simple enough.</p>
<p>The problem is with Ansible. These packages are in <code>module_utils</code>. I import them with:</p>
<pre><code>from ansible.module_utils.MyCustomPackage import MyCustomPackage
</code></pre>
<p>but when I use the commands I get module not found errors - and traced it back to the <code>import MyCustomPackage</code> statement in the package itself.</p>
<p>So - how should I be structuring my package? Should I try again with relative file imports, or have the package modify the path so it's found with the friendly name?</p>
<p>Any tips would be helpful! Or if someone has a module they've written with Python modules in <code>module_utils</code> and unit tests that they'd be willing to share, that'd be great also!</p>
",https://stackoverflow.com/questions/73655599/custom-module-with-custom-python-package-module-not-found-error,"['python', 'ansible']",146,False,2,0
Why doesn&#39;t ASP.NET Core support resource claims in token based authorization?,"<p>So here's what we're doing: we create a backend solution for a large IoT system and every IoT device has an identifier.</p>
<p>Also there are users and when logging in, they get an access token (JWT style + refresh token), which also includes to which IoT device (by their identifier) they have which type of access (example: read data, set configuration, etc...).</p>
<p>We have implemented custom authorization attributes with a system to parse the JWT and determine, if the token bearer has the required access right.</p>
<p>Here's an example:</p>
<p>User &quot;crimson&quot; has &quot;read&quot; and &quot;write&quot; access to device with ID &quot;A599&quot;. Looks somewhat like this:</p>
<p><code>&quot;sub&quot;: &quot;crimson&quot;, &quot;dar&quot;: [&quot;did&quot;: &quot;A599&quot;, &quot;arl&quot;: [&quot;r&quot;, &quot;w&quot;]]</code></p>
<p>Forgive me if the JSON is not correct, but I think you see what I'm doing.</p>
<p>Also we have the following custom attribute now:</p>
<p><code>[RequiresDeviceAccessRights(deviceIdParameterName: &quot;deviceId&quot;, requiredDeviceAccessRights: new [] {&quot;r&quot;})]  [HttpGet]  [Route(&quot;/{deviceId}/airpressure&quot;)] public ActionResult&lt;AirPressureInfo&gt; GetAirPressureAnalysis(string deviceId)</code></p>
<p>I really wonder now why we had to invest like 2 developer weeks into this authorization system when Microsoft claims that &quot;you don't need to create your own authorization attributes, if you do, then we have done something wrong&quot;.</p>
<p>Any ideas?</p>
<p>I wanted to have a system for resource claim based authorization using JWT, instead of having to basically hack into ASP.NET Core and &quot;abuse&quot; &quot;use this only for unit testing&quot; Microsoft APIs.</p>
",https://stackoverflow.com/questions/71703216/why-doesnt-asp-net-core-support-resource-claims-in-token-based-authorization,"['c#', 'asp.net-core', 'asp.net-authorization']",473,True,1,1
Unit Testing Sudoku - should the tests try to be independent of the data structure for the Sudoku board?,"<p>I'm learning unit testing and TDD in python and have got the basics mastered with pytest.</p>
<p>I've started a learning project of writing a sudoku solver and one thing I'm realising is that at the start I'm not currently sure how I want to store the data for the sudoku board.  Many talks warn about testing behaviour over implementation.  Would the board data structure count as implementation?</p>
<p>It's very hard to write a test that is independent of the board data structure.</p>
<p>For example you could store the values of each cell as an integer (eg 1) or a string (eg '1') and the board as a whole can be a dict (using cell label like 'A1' or 'C5' etc as keys), list (flat or 2d) or a 81 character string.</p>
<p>So I might start with</p>
<pre><code>hardboard = [
    [0, 0, 0, 0, 0, 0, 4, 0, 0],
    [0, 0, 1, 0, 7, 0, 0, 9, 0],
    [5, 0, 0, 0, 3, 0, 0, 0, 6],
    [0, 8, 0, 2, 0, 0, 0, 0, 0],
    [7, 0, 0, 0, 0, 0, 9, 2, 0],
    [1, 2, 0, 6, 0, 5, 0, 0, 0],
    [0, 5, 0, 0, 0, 0, 0, 4, 0],
    [0, 7, 3, 9, 0, 8, 0, 0, 0],
    [6, 0, 0, 4, 5, 0, 2, 0, 0]
]
</code></pre>
<p>but then decide to use a dict</p>
<pre><code>hardboard = {'A1': 0, 'A2': 0, 'A3': 0, ... 'I9': 0} 
</code></pre>
<p>So how should I start?  The only solution I can think of is to commit to one format, at least in terms how I represent the board in tests, even if the actual code uses a different data structure later and has to translate.  But in my TDD noobiness I'm unsure if this is a good idea?</p>
",https://stackoverflow.com/questions/73673852/unit-testing-sudoku-should-the-tests-try-to-be-independent-of-the-data-structu,"['python', 'unit-testing', 'sudoku']",58,True,1,1
A question of redundancy re Git branch updates and CI/CD flows,"<p>We are using gihub to manage our CI/CD pipeline and I noticed that on a PR, every update I run to align the PR with target branch, I trigger the whole unit testing flow, since the head of the branch has changed, I want to explore if this is not a redundant action that can be excluded, if at all.</p>
<p>The testing flow triggers on every push into a published branch, which means that anything that was merged has passed all the tests. This essentially means that any update I run on my branch would include all those PRs that passed the full test flow, so my question is, why would I need to run a full test flow on every update to my branch?</p>
<p>Think about the situation where you have a large team and right before release everyone is putting their PRs in, moreover, after every PR gets merged, my PR would need a new update, which means another test run, github doesn't have &quot;merge after tests complete successfully&quot;, so that means that I'm in a race to merge quickly before the next PR merges in, and if I don't &gt; update &gt; test run, would be happy to get your feedback on this.</p>
<p>Thx,
Bud</p>
",https://stackoverflow.com/questions/72958106/a-question-of-redundancy-re-git-branch-updates-and-ci-cd-flows,"['git', 'github', 'continuous-integration']",60,False,1,1
How to hide Scala.JS types from JVM code?,"<p>I've been practicing leveraging as much JVM code as possible in Scala.JS in order to benefit from unit testing pure JVM logic, which is of course much faster. At some point though, you run into the issue where the function you'd like to implement in the JVM cannot be written without passing a JS object to it, even if you do not call any methods of this object (it's effectively an <code>AnyRef</code> for all intents and purposes).</p>
<p>For instance, in a React JS application, maybe you have some if/else logic for deciding which components to return from your JVM function in order for React to render. The components are just objects (<code>AnyRef</code>) as far as the JVM is concerned, but on the JS side they need to be upcasted back to component types:</p>
<p>I'm naively solving this using:</p>
<pre class=""lang-scala prettyprint-override""><code>// convert to AnyRef at compile-time before passing to a JVM function:
type Jvm = AnyRef
def toJvm(elements: ReactElement*): Seq[Jvm] = elements : Seq[Jvm]
</code></pre>
<p>Then your JVM function decides which to render:</p>
<pre class=""lang-scala prettyprint-override""><code>def whichToRender(isDayTime: Boolean, jvm: Seq[Jvm]): Seq[Jvm] = {
  if (isDayTime) {
    Seq(jvm.head)
  } else {
    Seq.empty[Jvm]
  }
}
</code></pre>
<p>But the downside is in order to convert back to JS, I must use <code>asInstanceOf</code>, which suffers a runtime cost:</p>
<pre class=""lang-scala prettyprint-override""><code>def toJs(elements: Seq[Jvm]): Seq[ReactElement] = elements.asInstanceOf[Seq[ReactElement]]
</code></pre>
<p>So is there anyway to <em>hide</em> the underlying type of the React Component so that the JVM just <em>Sees</em> an Object but the underlying type is still recoverable, at compile-time to avoid runtime cost with type casting?</p>
",https://stackoverflow.com/questions/71514865/how-to-hide-scala-js-types-from-jvm-code,"['scala', 'jvm', 'scala.js']",27,False,1,0
Jetpack Compose handling both a string and string resource identifier for a Text Composable,"<p>In a viewModel, it may be desirable to have a <code>String</code> property that equals a user-defined value, or a localisable string resource if this user-defined value is null or empty. For example, in an application about pets, a user could name their dog <code>&quot;Pepper&quot;</code>. But, if no name has been provided, then it is feasible to default to a localisable string, <code>&quot;Dog&quot;</code> via a resource - <code>R.strings.dog_title</code>.</p>
<p>The issue is that the string resource, <code>R.strings.dog_title</code>, is of type <code>Int</code>, whereas the user-defined name is of type <code>String</code>, and a <code>Text</code> composable only takes <code>String</code> or <code>AnnotatedString</code> as a parameter.</p>
<p>This leads to an awkward choice between missing out on testability by placing logic in the view, or injecting the application context into the viewModel to get the string value from the string resource - both of which I'm wanting to avoid.</p>
<p>My current approach involves passing both values via the <code>uiState</code>, and then checking the name, before defaulting to the string resource:</p>
<pre class=""lang-kotlin prettyprint-override""><code>// UISTATE
data class ViewUiState (
   val string: String? = null,
   @StringRes val stringRes: Int,
)

// VIEWMODEL
val uiState = mutableStateOf(ViewUiState(stringRes = 0))
   private set
// In the ViewModel, we might get the type of pet currently being shown (e.g. 'Dog')
...
uiState.value = uiState.copy(stringRes = R.string.dog_title)
...


// COMPOSE SCREEN
val uiState by viewModel.uiState

if (!uiState.string.isNullOrEmpty()) {
   Text(uiState.string)
} else { 
   Text(stringResource(uiState.stringResId))
}
</code></pre>
<p>The only issue with this approach is that I now miss out on unit testing the null check, as the logic no longer lives in the viewModel.</p>
<p>To keep the logic in the viewModel, it is possible to inject the context and then get the string value using <code>getString(R.strings.dog_title)</code>. However, its always felt better practice to avoid injecting the context wherever possible.</p>
",https://stackoverflow.com/questions/74458452/jetpack-compose-handling-both-a-string-and-string-resource-identifier-for-a-text,"['android', 'unit-testing', 'android-jetpack-compose', 'android-viewmodel']",1079,True,1,2
Bean is always null when using @TestConfiguration in Spring Boot,"<p>I am using a simple TestConfiguration call in my application to initialize a service bean within the test class:</p>
<pre><code>    @TestConfiguration
    static class UserServiceConfiguration {
        @Bean
        public UserService userService() {
            return new UserServiceImpl() {

            };
        }
    }

    @Autowired
    private UserService userService;

</code></pre>
<p>When I try running any tests within the class, I immediately get a &quot;this.userService is null&quot; error and the test fails out with a null pointer exception.</p>
<p>I've tried some different fixes, including:</p>
<ul>
<li>Putting the TestConfiguration in its own class and importing it via the @Import annotation</li>
<li>Adding @Primary to the bean as well as giving it a unique name in the @Bean annotation.</li>
</ul>
<p>A breakpoint in the TestConfiguration return is not called, so it appears as if the service is not being automatically wired to that version.</p>
<p>Note I am new to unit testing in Spring boot and our application is a few years old with various configurations in different places. I am wondering if something else is interfering with the TestConfiguration, but my understanding was that it was supposed to override the service and ignore those configurations? I just cannot figure out why it is not being called.</p>
<p>I am using Spring Boot 2.5.4, Java 18.</p>
<p>Complete code of Test Class:</p>
<pre><code>
import static org.assertj.core.api.Assertions.assertThat;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.test.context.junit4.SpringRunner;

import com.evotext.user.service.UserService;
import com.evotext.user.service.UserServiceImpl;

@RunWith(SpringRunner.class)
public class UserServiceTest {

    @TestConfiguration
    static class UserServiceConfiguration {
        @Bean
        public UserService userService() {
            return new UserServiceImpl() {

            };
        }
    }

    @Autowired
    private UserService userService;
    
    
    
    @Test
    public void getCurrentUserSession() {
        
        long l = userService.countTotalUsers();
        assertThat(l == 1);
    }
    
}
</code></pre>
<p>The service class itself is an interface and the implemented version is annotated with @Service and @Transactional, no name is specified.</p>
",https://stackoverflow.com/questions/72455004/bean-is-always-null-when-using-testconfiguration-in-spring-boot,"['java', 'spring', 'spring-boot', 'junit']",430,False,1,2
Do &#39;dotnet build&#39; and &#39;dotnet test&#39; commands treat the -o/--output argument differently?,"<p>I'm trying to create a Dockerfile for running unit tests inside a container.</p>
<p>I currently have the following Dockerfile:</p>
<pre><code>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR &quot;/src&quot;

COPY [&quot;ProjectName/ProjectName.csproj&quot;, &quot;ProjectName/&quot;]
RUN dotnet restore &quot;ProjectName/ProjectName.csproj&quot;
COPY . .
WORKDIR &quot;/src/ProjectName&quot;
RUN dotnet build &quot;ProjectName.csproj&quot; -c Release -o /app/build

FROM build AS test
ENTRYPOINT [&quot;dotnet&quot;, &quot;test&quot;, &quot;ProjectName.csproj&quot;, &quot;-c:Release&quot;, &quot;-o:\&quot;/app/build\&quot;&quot;, &quot;--no-build&quot;]
</code></pre>
<p>The idea here is that it will build an image with binaries stored in <code>/app/build</code> and then execute the <code>dotnet test</code> command without rebuilding the project and knowing where the binaries are (because of the <code>-o:&quot;/app/build&quot;</code> parameter).</p>
<p>It builds fine, I can <code>-it bash</code> into the container and confirm that the assemblies are stored in the <code>/app/build</code> directory. However, once I try to execute the tests, it produces some weird error:</p>
<blockquote>
<p>Test run for /src/ProjectName/app/build/ProjectName.dll (.NETCoreApp,Version=v6.0)</p>
<p>Microsoft (R) Test Execution Command Line Tool Version 17.2.0 (x64)</p>
<p>Copyright (c) Microsoft Corporation.  All rights reserved.</p>
<p>The argument /src/ProjectName/app/build/ProjectName.dll is invalid. Please use the /help option to check the list of valid arguments.</p>
</blockquote>
<p>As I understand this, instead of treating the <code>-o:/app/build</code> as a directory in the root of the file system, it appends it to the current directory:</p>
<p>/src/ProjectName/<strong>app/build</strong>/ProjectName.dll</p>
<p>I can work around this and not specify the output directory at all, it is not critical for a unit testing container, however, I want to understand what the cause of the problem is.</p>
<p>Is it a .NET CLI bug or am I doing something wrong here?</p>
<p>Thank you.</p>
",https://stackoverflow.com/questions/73101307/do-dotnet-build-and-dotnet-test-commands-treat-the-o-output-argument-diff,"['docker', '.net-6.0']",133,False,1,0
Scalding Unit Test - How to Write A Local File?,"<p>I work at a place where scalding writes are augmented with a specific API to track dataset meta data. When converting from normal writes to these special writes, there are some intricacies with respect to Key/Value, TSV/CSV, Thrift ... datasets. I would like to compare the binary file is the same prior to conversion and after conversion to the special API.</p>
<p>Given I cannot provide the specific api for the metadata-inclusive writes, I only ask how can I write a unit test for <code>.write</code> method on a <code>TypedPipe</code>?</p>
<pre><code>implicit val timeZone: TimeZone = DateOps.UTC
implicit val dateParser: DateParser = DateParser.default
implicit def flowDef: FlowDef = new FlowDef()
implicit def mode: Mode = Local(true)

val fileStrPath = root + &quot;/test&quot;

println(&quot;writing data to &quot; + fileStrPath)

TypedPipe
  .from(Seq[Long](1, 2, 3, 4, 5))
  // .map((x: Long) =&gt; { println(x.toString); System.out.flush(); x })
  .write(TypedTsv[Long](fileStrPath))
  .forceToDisk
</code></pre>
<p>The above doesn't seem to write anything to local (OSX) disk.</p>
<p>So I wonder if I need to use a <code>MiniDFSCluster</code> something like this:</p>
<pre><code>def setUpTempFolder: String = {
  val tempFolder = new TemporaryFolder
  tempFolder.create()
  tempFolder.getRoot.getAbsolutePath
}
val root: String = setUpTempFolder
println(s&quot;root = $root&quot;)
val tempDir = Files.createTempDirectory(setUpTempFolder).toFile
val hdfsCluster: MiniDFSCluster = {
  val configuration = new Configuration()
  configuration.set(MiniDFSCluster.HDFS_MINIDFS_BASEDIR, tempDir.getAbsolutePath)
  configuration.set(&quot;io.compression.codecs&quot;, classOf[LzopCodec].getName)
  new MiniDFSCluster.Builder(configuration)
    .manageNameDfsDirs(true)
    .manageDataDfsDirs(true)
    .format(true)
    .build()
}
hdfsCluster.waitClusterUp()
val fs: DistributedFileSystem = hdfsCluster.getFileSystem
val rootPath = new Path(root)
fs.mkdirs(rootPath)
</code></pre>
<p>However, my attempts to get this MiniCluster to work haven't panned out either - somehow I need to link the MiniCluster with the Scalding write.</p>
<p>Note: The Scalding <code>JobTest</code> framework for unit testing isn't going to work due actual data written is sometimes wrapped in bijection codec or setup with case class wrappers prior to the writes made by the metadata-inclusive writes APIs.</p>
<p>Any ideas how I can write a local file (without using the Scalding REPL) with either Scalding alone or a MiniCluster? (If using the later, I need a hint how to read the file.)</p>
",https://stackoverflow.com/questions/73158649/scalding-unit-test-how-to-write-a-local-file,['scalding'],25,False,0,1
Extracting return value in gevent from a method which returns 2 values,"<p><strong>Note</strong>: I am getting this error in unit testing. Haven't been able to deploy it to dev/prod. could it be anything to do with app context? how to create one in py.test?</p>
<p>I recently converted a code which was doing multiple io calls to multithreaded. I used gevent to do so. Here is simplified version of the code (removing all necessary identifiable information)</p>
<pre><code>ge_results = {}

if random_condition_is_true():
    ge_results['first_key'] = Greenlet.spawn(another_service.fetch_data, ids, another_id)
    

ge_results['second_key'] = Greenlet.spawn(some_other_method, ids)

if another_condition_is_true():
    ge_results['third_key'] = Greenlet.spawn(third_method_call_which_returns_two_values, ids=ids)

results = gevent.joinall(list(ge_results.values()))

if 'first_key' in ge_results:
    first_key = ge_results['first_key'].value

if 'third_key' in ge_results:
    third_data_set = ge_results['third_key'].value[1]
</code></pre>
<p>The issue is happening on <code>third_data_set</code>. The <code>third_method_call_which_returns_two_values</code> method return 2 values, and i am trying to assign second value to <code>third_data_set</code> but i am unable to do so.</p>
<p>When i look into this value using pdb, I see these values</p>
<pre><code>(Pdb) xx = greenlets_result_map['third_key']
(Pdb) xx
&lt;Greenlet at 0x7f3350203a70: third_method_call_which_returns_two_values(AA1(..., qwe=[d,d,d,d], data_i_want=[DataIWant(BB=BB1(...)&gt;
</code></pre>
<p>Here it is visible that I receive a <code>Greenlet</code> object which has <code>AA1</code> object. Which then has <code>data_i_want</code>. But i am unable to get it.</p>
<p>When i do <code>xx.value</code> it says <code>NoneType</code>. If i try <code>xx[1].value</code>, i get error that its not subscriptable</p>
<p>I am not sure how to get this value.</p>
<p>Just to be clear, methods which are returning only one value are working perfectly fine with <code>greenlets_result_map['key'].value</code> code.</p>
<hr />
<p><strong>Update</strong></p>
<p>An interesting thing that i have noticed that if a method has been called then the greenlet has <code>_run</code> value otherwise method name.</p>
<p>For example, here is the output of <code>ge_results['first_key']</code></p>
<pre><code>(Pdb) ge_results['first_key']
(Pdb) &lt;Greenlet at 0x7f3350203830: _run&gt;
</code></pre>
<p>See there is <code>_run</code> here. But here is the output for <code>ge_results['second_key']</code></p>
<pre><code>(Pdb) ge_results['second_key']
(Pdb) &lt;Greenlet at 0x7f3350203950: some_other_method([])&gt;
</code></pre>
<p>See it doesn't have <code>_run</code>. Am i not joining them all?</p>
",https://stackoverflow.com/questions/73942312/extracting-return-value-in-gevent-from-a-method-which-returns-2-values,"['python-3.x', 'multithreading', 'gevent', 'python-3.9', 'greenlets']",123,False,0,0
How to manually test my typescript library in a browser?,"<p>I've some typescript code that creates an svg element that I used in a react project that I'd like to isolate into a separate project which I can distribute on npm.</p>
<p>I'm trying to figure out how to test the library I'm developing. I'm not talking about unit testing but merely load the library in a test html page to see if it works.</p>
<p>I've spent the past few days reading about javascript/typescript modules, bundling tools like webpack, but I'm still confused about how to approach this.</p>
<p>So far, I've managed to write my typescript library in <code>src/lib.ts</code>, and have a separate <code>test/</code> folder with an html page <code>test/index.html</code> and a simple typescript file <code>test/test.ts</code> that imports my library and then adds the svg element it defines in the html body.</p>
<p>In order for it all to function in a browser so that I can test it, I have webpack bundle <code>test/test.ts</code> into a <code>test-bundle/test.js</code>. The html page actually loads <code>test-bundle/test.js</code> with a <code>&lt;script src=&quot;../test-bundle/test.js&quot;&gt;&lt;/script&gt;</code></p>
<p>I'd like to know if this looks like a correct way to do it. I'm a bit confused with how to work with typescript in the browser and I'm wondering if I'm taking a convoluted approach to do something simple: call my lib from a browser for testing it.</p>
",https://stackoverflow.com/questions/71785758/how-to-manually-test-my-typescript-library-in-a-browser,['typescript'],405,False,0,1
tox refuses to use deps setting in py38 and various pip problems,"<p>I have a Django project that i'm trying to set up unit testing with tox in.<br>
here is the directory structure:</p>
<pre><code>+ djangoProject
|
+-.github
+-.pytest
+-.tox
+- api
+- blog
+- djangoProject
+- templates
|
+ .gitignore
+ manage.py
+ pyproject.toml
+ requirements.txt
+ requirements_dev.txt
+ setup.cfg
+ tox.ini
</code></pre>
<p>Here are the various config files<br>
<code>tox.ini</code>:</p>
<pre><code>[tox]
minversion = 3.8.0
envlist = py38, py39, py310, flake8
isolated_build = true

[testenv]
setenv =
    PYTHONPATH = {toxinidir}
deps =
    -r{toxinidir}/requirements_dev.txt
commands =
    pytest --basetemp={envtmpdir}

[testenv:flake8]
basepython = python3.8
deps = flake8
commands = flake8
</code></pre>
<p><code>pyproject.toml</code>:</p>
<pre><code>[build-system]
requires = [&quot;setuptools&gt;=42.0&quot;, &quot;wheel&quot;]
build-backend = &quot;setuptools.build_meta&quot;

[tool.pytest.ini_options]
testpaths = [
    &quot;api&quot;,
    &quot;blog&quot;,
    &quot;djangoProject&quot;
]
DJANGO_SETTINGS_MODULE = &quot;djangoProject.settings&quot;
python_files = &quot;tests.py test_*.py *_tests.py&quot;
</code></pre>
<p><code>setup.cfg</code>:</p>
<pre><code>[options]
packages =
    api
    blog
    djangoProject
    templates

[flake8]
max-line-length = 210
exclude =
    .git,
    .github,
    .pytest_cache,
    __pycache__,
    docs/source/conf.py,
    old,
    build,
    dist,
    venv,
    migrations
</code></pre>
<p><code>requirements_dev.txt</code>:</p>
<pre><code>Django~=4.0.3
djangorestframework~=3.13.1
django-gravatar2~=1.4.4
psycopg2~=2.9.3
beautifulsoup4~=4.10.0
pytest-django~=4.5.2
tox~=3.24.5
flake8~=4.0.1
</code></pre>
<p>I'm developing on Pycharm and Linux Mint 20.3 (in a HyperV VM)</p>
<p>Here is the output when I try to run <code>tox</code>: <br></p>
<pre><code>(venv) dafrandle@linux-mint-VM:\~/PycharmProjects/djangoProject$ tox
py38 inst-nodeps: /home/dafrandle/PycharmProjects/djangoProject/.tox/.tmp/package/1/UNKNOWN-0.0.0.tar.gz
ERROR: invocation failed (exit code 1), logfile: /home/dafrandle/PycharmProjects/djangoProject/.tox/py38/log/py38-10.log
=============================================================================================================== log start ===============================================================================================================
Processing ./.tox/.tmp/package/1/UNKNOWN-0.0.0.tar.gz
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'error'
error: subprocess-exited-with-error
 
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─\&gt; \[6 lines of output\]
No parent package detected, impossible to derive `name`
running egg_info
writing UNKNOWN.egg-info/PKG-INFO
writing dependency_links to UNKNOWN.egg-info/dependency_links.txt
writing top-level names to UNKNOWN.egg-info/top_level.txt
error: package directory 'templates' does not exist
\[end of output\]
 
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
 
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─\&gt; See above for output.
 
note: This error originates from a subprocess, and is likely not a problem with pip.
 
================================================================================================================ log end ================================================================================================================
py39 create: /home/dafrandle/PycharmProjects/djangoProject/.tox/py39
py39 installdeps: -r/home/dafrandle/PycharmProjects/djangoProject/requirements_dev.txt
ERROR: invocation failed (exit code 1), logfile: /home/dafrandle/PycharmProjects/djangoProject/.tox/py39/log/py39-1.log
=============================================================================================================== log start ===============================================================================================================
Collecting Django\~=4.0.3
Using cached Django-4.0.3-py3-none-any.whl (8.0 MB)
Collecting djangorestframework\~=3.13.1
Using cached djangorestframework-3.13.1-py3-none-any.whl (958 kB)
Collecting django-gravatar2\~=1.4.4
Using cached django_gravatar2-1.4.4-py2.py3-none-any.whl (7.9 kB)
Collecting psycopg2\~=2.9.3
Using cached psycopg2-2.9.3.tar.gz (380 kB)
Preparing metadata (setup.py): started
Preparing metadata (setup.py): finished with status 'done'
Collecting beautifulsoup4\~=4.10.0
Using cached beautifulsoup4-4.10.0-py3-none-any.whl (97 kB)
Collecting pytest-django\~=4.5.2
Using cached pytest_django-4.5.2-py3-none-any.whl (20 kB)
Collecting tox\~=3.24.5
Using cached tox-3.24.5-py2.py3-none-any.whl (85 kB)
Collecting flake8\~=4.0.1
Using cached flake8-4.0.1-py2.py3-none-any.whl (64 kB)
Collecting asgiref\&lt;4,\&gt;=3.4.1
Using cached asgiref-3.5.0-py3-none-any.whl (22 kB)
Collecting sqlparse\&gt;=0.2.2
Using cached sqlparse-0.4.2-py3-none-any.whl (42 kB)
Collecting pytz
Using cached pytz-2022.1-py2.py3-none-any.whl (503 kB)
Collecting soupsieve\&gt;1.2
Using cached soupsieve-2.3.1-py3-none-any.whl (37 kB)
Collecting pytest\&gt;=5.4.0
Using cached pytest-7.1.1-py3-none-any.whl (297 kB)
Collecting virtualenv!=20.0.0,!=20.0.1,!=20.0.2,!=20.0.3,!=20.0.4,!=20.0.5,!=20.0.6,!=20.0.7,\&gt;=16.0.0
Using cached virtualenv-20.14.0-py2.py3-none-any.whl (8.8 MB)
Collecting six\&gt;=1.14.0
Using cached six-1.16.0-py2.py3-none-any.whl (11 kB)
Collecting toml\&gt;=0.9.4
Using cached toml-0.10.2-py2.py3-none-any.whl (16 kB)
Collecting packaging\&gt;=14
Using cached packaging-21.3-py3-none-any.whl (40 kB)
Collecting py\&gt;=1.4.17
Using cached py-1.11.0-py2.py3-none-any.whl (98 kB)
Collecting filelock\&gt;=3.0.0
Using cached filelock-3.6.0-py3-none-any.whl (10.0 kB)
Collecting pluggy\&gt;=0.12.0
Using cached pluggy-1.0.0-py2.py3-none-any.whl (13 kB)
Collecting pycodestyle\&lt;2.9.0,\&gt;=2.8.0
Using cached pycodestyle-2.8.0-py2.py3-none-any.whl (42 kB)
Collecting mccabe\&lt;0.7.0,\&gt;=0.6.0
Using cached mccabe-0.6.1-py2.py3-none-any.whl (8.6 kB)
Collecting pyflakes\&lt;2.5.0,\&gt;=2.4.0
Using cached pyflakes-2.4.0-py2.py3-none-any.whl (69 kB)
Collecting pyparsing!=3.0.5,\&gt;=2.0.2
Using cached pyparsing-3.0.7-py3-none-any.whl (98 kB)
Collecting tomli\&gt;=1.0.0
Using cached tomli-2.0.1-py3-none-any.whl (12 kB)
Collecting iniconfig
Using cached iniconfig-1.1.1-py2.py3-none-any.whl (5.0 kB)
Collecting attrs\&gt;=19.2.0
Using cached attrs-21.4.0-py2.py3-none-any.whl (60 kB)
Collecting distlib\&lt;1,\&gt;=0.3.1
Using cached distlib-0.3.4-py2.py3-none-any.whl (461 kB)
Collecting platformdirs\&lt;3,\&gt;=2
Using cached platformdirs-2.5.1-py3-none-any.whl (14 kB)
Building wheels for collected packages: psycopg2
Building wheel for psycopg2 (setup.py): started
Building wheel for psycopg2 (setup.py): finished with status 'error'
error: subprocess-exited-with-error
 
× python setup.py bdist_wheel did not run successfully.
│ exit code: 1
╰─\&gt; \[38 lines of output\]
running bdist_wheel
running build
running build_py
creating build
creating build/lib.linux-x86_64-3.9
creating build/lib.linux-x86_64-3.9/psycopg2
copying lib/\_json.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/\_range.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/errors.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/\_ipaddress.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/extras.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/pool.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/__init__.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/errorcodes.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/tz.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/extensions.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/sql.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
running build_ext
building 'psycopg2.\_psycopg' extension
creating build/temp.linux-x86_64-3.9
creating build/temp.linux-x86_64-3.9/psycopg
x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC &quot;-DPSYCOPG_VERSION=2.9.3 (dt dec pq3 ext lo64)&quot; -DPSYCOPG_DEBUG=1 -DPG_VERSION_NUM=120009 -DHAVE_LO64=1 -DPSYCOPG_DEBUG=1 -I/home/dafrandle/PycharmProjects/djangoProject/.tox/py39/include -I/usr/include/python3.9 -I. -I/usr/include/postgresql -I/usr/include/postgresql/12/server -I/usr/include/libxml2 -I/usr/include/mit-krb5 -c psycopg/adapter_asis.c -o build/temp.linux-x86_64-3.9/psycopg/adapter_asis.o -Wdeclaration-after-statement
In file included from psycopg/adapter_asis.c:28:
./psycopg/psycopg.h:35:10: fatal error: Python.h: No such file or directory
35 | #include \&lt;Python.h\&gt;
|          ^\~\~\~\~\~\~\~\~\~
compilation terminated.
 
      It appears you are missing some prerequisite to build the package from source.
      
      You may install a binary package by installing 'psycopg2-binary' from PyPI.
      If you want to install psycopg2 from source, please install the packages
      required for the build and try again.
      
      For further information please check the 'doc/src/install.rst' file (also at
      &lt;https://www.psycopg.org/docs/install.html&gt;).
      
      error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1
      [end of output]
 
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for psycopg2
Running setup.py clean for psycopg2
Failed to build psycopg2
Installing collected packages: pytz, mccabe, iniconfig, django-gravatar2, distlib, tomli, toml, sqlparse, soupsieve, six, pyparsing, pyflakes, pycodestyle, py, psycopg2, pluggy, platformdirs, filelock, attrs, asgiref, virtualenv, packaging, flake8, Django, beautifulsoup4, tox, pytest, djangorestframework, pytest-django
Running setup.py install for psycopg2: started
Running setup.py install for psycopg2: finished with status 'error'
error: subprocess-exited-with-error
 
× Running setup.py install for psycopg2 did not run successfully.
│ exit code: 1
╰─\&gt; \[40 lines of output\]
running install
/home/dafrandle/PycharmProjects/djangoProject/.tox/py39/lib/python3.9/site-packages/setuptools/command/install.py:34: SetuptoolsDeprecationWarning: setup.py install is deprecated. Use build and pip and other standards-based tools.
warnings.warn(
running build
running build_py
creating build
creating build/lib.linux-x86_64-3.9
creating build/lib.linux-x86_64-3.9/psycopg2
copying lib/\_json.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/\_range.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/errors.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/\_ipaddress.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/extras.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/pool.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/__init__.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/errorcodes.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/tz.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/extensions.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
copying lib/sql.py -\&gt; build/lib.linux-x86_64-3.9/psycopg2
running build_ext
building 'psycopg2.\_psycopg' extension
creating build/temp.linux-x86_64-3.9
creating build/temp.linux-x86_64-3.9/psycopg
x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC &quot;-DPSYCOPG_VERSION=2.9.3 (dt dec pq3 ext lo64)&quot; -DPSYCOPG_DEBUG=1 -DPG_VERSION_NUM=120009 -DHAVE_LO64=1 -DPSYCOPG_DEBUG=1 -I/home/dafrandle/PycharmProjects/djangoProject/.tox/py39/include -I/usr/include/python3.9 -I. -I/usr/include/postgresql -I/usr/include/postgresql/12/server -I/usr/include/libxml2 -I/usr/include/mit-krb5 -c psycopg/adapter_asis.c -o build/temp.linux-x86_64-3.9/psycopg/adapter_asis.o -Wdeclaration-after-statement
In file included from psycopg/adapter_asis.c:28:
./psycopg/psycopg.h:35:10: fatal error: Python.h: No such file or directory
35 | #include \&lt;Python.h\&gt;
|          ^\~\~\~\~\~\~\~\~\~
compilation terminated.
 
      It appears you are missing some prerequisite to build the package from source.
      
      You may install a binary package by installing 'psycopg2-binary' from PyPI.
      If you want to install psycopg2 from source, please install the packages
      required for the build and try again.
      
      For further information please check the 'doc/src/install.rst' file (also at
      &lt;https://www.psycopg.org/docs/install.html&gt;).
      
      error: command '/usr/bin/x86_64-linux-gnu-gcc' failed with exit code 1
      [end of output]
 
note: This error originates from a subprocess, and is likely not a problem with pip.
error: legacy-install-failure
 
× Encountered error while trying to install package.
╰─\&gt; psycopg2
 
note: This is an issue with the package mentioned above, not pip.
hint: See above for output from the failure.
 
================================================================================================================ log end ================================================================================================================
ERROR: could not install deps \[-r/home/dafrandle/PycharmProjects/djangoProject/requirements_dev.txt\]; v = InvocationError('/home/dafrandle/PycharmProjects/djangoProject/.tox/py39/bin/python -m pip install -r/home/dafrandle/PycharmProjects/djangoProject/requirements_dev.txt', 1)
py310 create: /home/dafrandle/PycharmProjects/djangoProject/.tox/py310
py310 installdeps: -r/home/dafrandle/PycharmProjects/djangoProject/requirements_dev.txt
ERROR: invocation failed (exit code 1), logfile: /home/dafrandle/PycharmProjects/djangoProject/.tox/py310/log/py310-1.log
=============================================================================================================== log start ===============================================================================================================
Traceback (most recent call last):
File &quot;/usr/lib/python3.10/runpy.py&quot;, line 196, in \_run_module_as_main
return \_run_code(code, main_globals, None,
File &quot;/usr/lib/python3.10/runpy.py&quot;, line 86, in \_run_code
exec(code, run_globals)
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/__main__.py&quot;, line 29, in \&lt;module\&gt;
from pip.\_internal.cli.main import main as \_main
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/\_internal/cli/main.py&quot;, line 9, in \&lt;module\&gt;
from pip.\_internal.cli.autocompletion import autocomplete
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/\_internal/cli/autocompletion.py&quot;, line 10, in \&lt;module\&gt;
from pip.\_internal.cli.main_parser import create_main_parser
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/\_internal/cli/main_parser.py&quot;, line 8, in \&lt;module\&gt;
from pip.\_internal.cli import cmdoptions
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/\_internal/cli/cmdoptions.py&quot;, line 23, in \&lt;module\&gt;
from pip.\_internal.cli.parser import ConfigOptionParser
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/\_internal/cli/parser.py&quot;, line 12, in \&lt;module\&gt;
from pip.\_internal.configuration import Configuration, ConfigurationError
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/\_internal/configuration.py&quot;, line 26, in \&lt;module\&gt;
from pip.\_internal.utils.logging import getLogger
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/\_internal/utils/logging.py&quot;, line 27, in \&lt;module\&gt;
from pip.\_internal.utils.misc import ensure_dir
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/\_internal/utils/misc.py&quot;, line 39, in \&lt;module\&gt;
from pip.\_internal.locations import get_major_minor_version
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/\_internal/locations/__init__.py&quot;, line 14, in \&lt;module\&gt;
from . import \_distutils, \_sysconfig
File &quot;/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/lib/python3.10/site-packages/pip/\_internal/locations/\_distutils.py&quot;, line 9, in \&lt;module\&gt;
from distutils.cmd import Command as DistutilsCommand
ModuleNotFoundError: No module named 'distutils.cmd'
 
================================================================================================================ log end ================================================================================================================
ERROR: could not install deps \[-r/home/dafrandle/PycharmProjects/djangoProject/requirements_dev.txt\]; v = InvocationError('/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/bin/python -m pip install -r/home/dafrandle/PycharmProjects/djangoProject/requirements_dev.txt', 1)
flake8 inst-nodeps: /home/dafrandle/PycharmProjects/djangoProject/.tox/.tmp/package/1/UNKNOWN-0.0.0.tar.gz
ERROR: invocation failed (exit code 1), logfile: /home/dafrandle/PycharmProjects/djangoProject/.tox/flake8/log/flake8-7.log
=============================================================================================================== log start ===============================================================================================================
Processing ./.tox/.tmp/package/1/UNKNOWN-0.0.0.tar.gz
Installing build dependencies: started
Installing build dependencies: finished with status 'done'
Getting requirements to build wheel: started
Getting requirements to build wheel: finished with status 'error'
error: subprocess-exited-with-error
 
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─\&gt; \[6 lines of output\]
No parent package detected, impossible to derive `name`
running egg_info
writing UNKNOWN.egg-info/PKG-INFO
writing dependency_links to UNKNOWN.egg-info/dependency_links.txt
writing top-level names to UNKNOWN.egg-info/top_level.txt
error: package directory 'templates' does not exist
\[end of output\]
 
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
 
× Getting requirements to build wheel did not run successfully.
│ exit code: 1
╰─\&gt; See above for output.
 
note: This error originates from a subprocess, and is likely not a problem with pip.
 
================================================================================================================ log end ================================================================================================================
\___\_ summary \___\_
ERROR:   py38: InvocationError for command /home/dafrandle/PycharmProjects/djangoProject/.tox/py38/bin/python -m pip install --no-deps -U .tox/.tmp/package/1/UNKNOWN-0.0.0.tar.gz (exited with code 1)
ERROR:   py39: could not install deps \[-r/home/dafrandle/PycharmProjects/djangoProject/requirements_dev.txt\]; v = InvocationError('/home/dafrandle/PycharmProjects/djangoProject/.tox/py39/bin/python -m pip install -r/home/dafrandle/PycharmProjects/djangoProject/requirements_dev.txt', 1)
ERROR:   py310: could not install deps \[-r/home/dafrandle/PycharmProjects/djangoProject/requirements_dev.txt\]; v = InvocationError('/home/dafrandle/PycharmProjects/djangoProject/.tox/py310/bin/python -m pip install -r/home/dafrandle/PycharmProjects/djangoProject/requirements_dev.txt', 1)
ERROR:   flake8: InvocationError for command /home/dafrandle/PycharmProjects/djangoProject/.tox/flake8/bin/python -m pip install --no-deps -U .tox/.tmp/package/1/UNKNOWN-0.0.0.tar.gz (exited with code 1)
</code></pre>
<p>their is multiple problems here</p>
<p>1: both py38 envs don't use my requirements and instead run pip with --no-deps and goes after some file that doesn't exist<br>
2: in py38 envs the wheel fails to build - this is probably because of #1 but I'm not sure.<br>
3: In all other envs the wheel for psycopg2 fails to build and it also fails to install using setup.py<br></p>
<p>I have tried removing lines from the tox.ini to get a different output to try and locate the issue if it was in the ini files but found nothing.</p>
<p>when I add things to my project with pip manually or using PyCharm's package manger <strong>inclduing psycopg2</strong> it all works fine so I don't know why it wont work in tox</p>
<p>I don't know what I'm doing wrong</p>
<p>I was working off this tutorial video:
<a href=""https://www.youtube.com/watch?v=DhUpxWjOhME"" rel=""nofollow noreferrer"">https://www.youtube.com/watch?v=DhUpxWjOhME</a></p>
<p>it's not for a Django project but everything before the tox part I was able to get running fine</p>
",https://stackoverflow.com/questions/71700514/tox-refuses-to-use-deps-setting-in-py38-and-various-pip-problems,"['python', 'pip', 'tox']",3179,True,0,2
How to test if output function recieved is are correct or not using GTEST/GMOCK,"<p>I am trying implemnent the GTEST/GMOCK framework for unittesting the C-code. I am using the MSVS 2017. The adaptation is completed.</p>
<p>Here,
I have the matlab generated code. This autogenerated code we have simulating in the PC level which has the .Net GUI for giving the inputs (This GUI is now will be replaced by GTEST framework from which we will be invoking the input functions). Whenever I call any function (Give any input) we will confirming the functionality by checking the logs.</p>
<p>The C functions we are invoking are all <strong>void functions</strong> but there are separate(different) output function <strong>(are also void type)</strong> from which we will be confirming the functionality.</p>
<p>Now I need to implement the unit testing is the same way. On calling the input function <strong>(Which are void type)</strong> I need to verify that if the output functions <strong>(void type)</strong> that received are correct or not. Here we don’t have any return values. Is there any way to implement this idea?Currently the EXPECT_CALL is actually checking if the function call is there or not even if I pass wrong argument the test says passed. So I am stuck here.</p>
<p>The implemetation is as below :</p>
<pre class=""lang-cpp prettyprint-override""><code>/*
============================================================================
 Name        : tesp.cpp
Author      : Siddhartha V
 ============================================================================
 */

#include &lt;gmock/gmock.h&gt;
#include &lt;gtest/gtest.h&gt;

#include &lt;iostream&gt;

#include &quot;pch.h&quot;

class Testfuncs {
 public:
  virtual ~Testfuncs() {}
  virtual voidoutput_Func1(RsuCtrl_t rtu_Id, HuStat_t rtu_RsuStatSeat);
  virtual void output_Func2() = 0;
  virtual void Input_Func1(int Stat) = 0;
  virtual void Input_Func2(int Stat) = 0;
};

class MockTestfuncs : public Testfuncs {
 public:
  MockTestfuncs() : Testfuncs() {}
  MOCK_METHOD(void, output_Func1, (RsuCtrl_t rtu_Id, HuStat_t rtu_RsuStatSeat),
              (override));
  MOCK_METHOD(void, output_Func2, (), (override));
  MOCK_METHOD(void, Input_Func1, (intStat), (override));
  MOCK_METHOD(void, Input_Func2, (int Stat), (override));
};

TEST(TestVC, Read_UpdateInProgress) {
  std::chrono_literals;
  m_VInput.ECall_Active = 1;
  SetInputs(&amp;m_Input);
  EXPECT_FALSE(0, output_func_n(void));
  std::this_thread::sleep_for(9s);
}

TEST(MockTestfuncs, output_Func1) {
  MockTestfuncs Testfuncs;
  std::this_thread::sleep_for(5s);
  //***setting the input @@@@@
  Input_Func2((int)1);
  using ::testing::_;
  using ::testing::AllOf;
  using ::testing::Args;
  using ::testing::Lt;
  EXPECT_CALL(Testfuncs, Input_Func1((int)1));
  Testfuncs.Input_Func1((int)1);
  EXPECT_CALL(Testfuncs, Input_Func2((int)1));
  Testfuncs.Input_Func2((int)1);
  EXPECT_CALL(Testfuncs, output_Func1).Times(1);
  Testfuncs.output_Func1((RsuCtrl_t)1, (HuStat_t)2);
  ASSERT_TRUE(100, Input_Func2((int)1));
  std::this_thread::sleep_for(1s);
}

TEST(TestVC, RSUF_testEXP_TRUE) { EXPECT_FALSE(1, Input_Func1((int)1)); }

TEST(TestVC, RSUF_testEXP_EQ) { EXPECT_TRUE(1, Input_Func1((int)1)); }

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&amp;argc, argv);
  std::cout &lt;&lt; &quot;Gtest main is printing&quot;;
  return RUN_ALL_TESTS();
}
</code></pre>
<p>Any suggestion will help me a lot.</p>
<p>regards,
Siddhartha V</p>
",https://stackoverflow.com/questions/71949458/how-to-test-if-output-function-recieved-is-are-correct-or-not-using-gtest-gmock,"['unit-testing', 'googletest', 'googlemock']",165,False,0,0
Azure pipeline hosted agent connection to Azure SQL database in unit testing of the database,"<p>I am deploying a database to an Azure SQL Server with Azure Pipelines. The deployment is working really well. So I added the creation and deployment of a temporary database (one that is removed at the end of the pipeline) for unit testing of my USP's.</p>
<p>I created a unit test .dll with SSDT. I configured the app.config and tested it on my laptop in Visual Studio. On my laptop it works, the unit tests are run an all pass.</p>
<p>I tried to connect to the server with the credentials from the app.config in SSMS. The connection is established.</p>
<p>But, I cant get the pipeline (or hosted agent) task to connect to the database from within the pipeline.</p>
<p>I tried adding the IP of the agent to the server whitelist. I checked the &quot;allow azure services to access the database&quot;. These did not solve the problem.</p>
<p>The error I get is this:</p>
<blockquote>
<p>Initialization method
BuilEnDeployTest_Unittest.SqlServerUnitTest001.TestInitialize threw
exception. System.Data.SqlClient.SqlException:
System.Data.SqlClient.SqlException: A transport-level error has
occurred when receiving results from the server. (provider: TCP
Provider, error: 0 - An existing connection was forcibly closed by the
remote host.) ---&gt; System.ComponentModel.Win32Exception: An existing
connection was forcibly closed by the remote host.</p>
</blockquote>
<p>pipeline yml:</p>
<pre><code>trigger:
- test

name: $(TeamProject)_$(Date:yyyyMMdd)$(Rev:_r)

variables:
- group: &quot;DatabaseDeploy&quot;
- name:  databaseName
  value: sqldb-AzureDevOps_$(Build.BuildNumber)
#- name: ExecutionContext.__Database__
#  value: $(variables.databaseName)

stages:

### Building the code in the Pull-Request

- stage: Build
  displayName: Build the project

  jobs:
  - job: Build
    displayName: Build DB project
    pool:
      vmImage: windows-latest

    steps:


    - script: echo '$(Build.BuildNumber)'
      displayName: BuildName

    #- powershell: 
    #    Get-ChildItem -Path $(Agent.WorkFolder)\1\s\BuilEnDeployTest_Unittest -recurse
    #  displayName: Folder structure

    #- script: echo '$(Agent.WorkFolder)\1\s\BuilEnDeployTest_Unittest\app.config'
    #  displayName: app.config

    - powershell: 
         Get-Content -path $(Agent.WorkFolder)/1/s/BuilEnDeployTest_Unittest/app.config
      displayName: app.config

    - powershell: &gt;
         (Get-Content -path $(Agent.WorkFolder)/1/s/BuilEnDeployTest_Unittest/app.config -Raw) 
         -replace 'MyDatabase', '$(databaseName)' 
         -replace 'MyServer', '$(ServerName_unittst).database.windows.net'
         -replace 'MyUser', '$(DatabaseUser_unittst)'
         -replace 'MyPassword', '$(DatabasePassword_unittst)'| Set-Content -Force -Path $(Agent.WorkFolder)/1/s/BuilEnDeployTest_Unittest/app.config

    - powershell: 
         Get-Content -path $(Agent.WorkFolder)/1/s/BuilEnDeployTest_Unittest/app.config
      displayName: app.config
    
    - task: VSBuild@1
      displayName: Building the database project
      inputs:
        solution: '**\*.sln'

    - task: CopyFiles@2
      displayName: Copy Build Artifacts
      inputs:
        SourceFolder: '$(agent.builddirectory)\s'
        Contents: '**'
        TargetFolder: '$(build.artifactstagingdirectory)'

         
        
   ### In the commands below, 'pipeline' is used instead of 'Container', allthough
   ### 'Container' is often seen in the online documentation. 
   ### I have noticed that changing 'pipeline' to 'Container' breaks my code
   ### I haven't spend time in figuring out why. It could be because of the path I use 
   ### down the line. 

    - task: PublishPipelineArtifact@1
      displayName: Publish Build Artifacts
      inputs:
        PathtoPublish: '$(Build.ArtifactStagingDirectory)'
        ArtifactName: 'database'
        publishLocation: 'pipeline'

#### Unit testing the Pull-Request

- stage: Unit_testing
  displayName: Database UnitTest
  condition: and(succeeded(), eq(variables['Build.Reason'], 'PullRequest'))


  jobs:
  - job: Deploy_to_temporary_database
    displayName: Deploy to temporary database
    pool:
      vmImage: windows-latest

 

    steps:

    ############ Create the Azure Resources as defined in the AzureSQLARMTemplate.json

    ## When the Azure SQL server does not exist it is also created by the ARM deployment.
    
    ## NOTE: I experienced errors when deleting and recreating the Azure SQL server. This could be 
    ## because of the little time between deletion and creation. 
    ## Deployment through the ARM template can deal with an existing server. In that case
    ## the server creation is skipped. So best to not delete the Azure SQL server untill the project
    ## is abandoned. 

    - task: AzurePowerShell@5
      displayName: 'Create unittest DB'
      inputs:
        azureSubscription: $(connectedServiceNameARM)
        ScriptType: 'FilePath'
        ScriptPath: './ARMtemplate/CreateAzureSQLAndDB.ps1'
        ScriptArguments: -azuresqlserverName $(ServerName_unittst) -sqlserverAdminLogin $(DatabaseUser_unittst) -sqlserverAdminPassword $(DatabasePassword_unittst) -databaseName $(databaseName) -Location 'northeurope' -ResourceGroupName 'rg-temp' -TemplateFile ARMtemplate\AzureSQLARMTemplate.json
        azurePowerShellVersion: 'LatestVersion'





    ############ Download the build artifacts from the build stage

    - task: DownloadPipelineArtifact@2
      displayName: 'Download artifacts'
      inputs: 
        buildType: 'current'
        artifactName: 'database'
        targetPath: '$(Pipeline.Workspace)/database'

    - powershell: 
        Get-ChildItem -Path $(Pipeline.Workspace)/database -recurse
      displayName: Folder structure

    - powershell: 
         Get-Content -path $(Pipeline.Workspace)/database/a/BuilEnDeployTest_Unittest/bin/Debug/BuilEnDeployTest_Unittest.dll.config
      displayName: BuilEnDeployTest_Unittest.dll.config

    ############ Deploy the database dacpac file to the newly created database

    - task: SqlAzureDacpacDeployment@1
      displayName: 'Deploy unittest DB'
      inputs:
        connectedServiceNameARM: $(connectedServiceNameARM)
        ServerName: $(ServerName_unittst).database.windows.net
        DatabaseName: $(databaseName)
        SqlUsername: $(DatabaseUser_unittst)
        SqlPassword: $(DatabasePassword_unittst)
        DacpacFile: $(Pipeline.Workspace)/database/a/$(dacpacfile_location)
        PublishProfile: $(Pipeline.Workspace)/database/a/$(publishprofile_location)

    ## Create a firewall rule for the IP adress of the build agent

    - task: AzurePowerShell@5
      displayName: 'Add buildserver public ip'
      inputs:
        azureSubscription: $(connectedServiceNameARM)
        ScriptType: InlineScript
        Inline: |
          $ip = (Invoke-WebRequest -uri &quot;http://ifconfig.me/ip&quot;).Content
          $AzureSQLFirewallRule = Get-AzSqlServerFirewallRule -ResourceGroupName 'rg-temp' -ServerName $(ServerName_unittst) -FirewallRuleName &quot;azuredevops&quot;
          if ($AzureSQLFirewallRule -eq $null) {New-AzSqlServerFirewallRule -ResourceGroupName 'rg-temp' -ServerName $(ServerName_unittst) -FirewallRuleName &quot;azuredevops&quot; -StartIpAddress $ip -EndIpAddress $ip}
        azurePowerShellVersion: 'LatestVersion'     

    ############ Run the unittest

    - task: VSTest@2
      inputs:
        testAssemblyVer2: $(Pipeline.Workspace)/database/a/$(Unittestdll_location)
        testConfiguration: 'Debug'
        runOnlyImpactedTests: true
        runInParallel: false

    ############ Delete the newly created database
         
    - task: AzurePowerShell@5
      displayName: 'Delete unittest DB'
      inputs:
        azureSubscription: $(connectedServiceNameARM)
        ScriptType: 'FilePath'
        ScriptPath: './ARMtemplate/CleanupAzureSQLAndDB.ps1'
        ScriptArguments: -azuresqlserverName $(ServerName_unittst) -databaseName $(databaseName) -ResourceGroupName 'rg-temp'
        azurePowerShellVersion: 'LatestVersion'

     ## Delete a firewall rule for the IP adress of the build agent

    - task: AzurePowerShell@5
      displayName: 'remove buildserver public ip'
      inputs:
        azureSubscription: $(connectedServiceNameARM)
        ScriptType: InlineScript
        Inline: |
          $ip = (Invoke-WebRequest -uri &quot;http://ifconfig.me/ip&quot;).Content
          Remove-AzSqlServerFirewallRule -ResourceGroupName 'rg-temp' -ServerName $(ServerName_unittst) -FirewallRuleName &quot;azuredevops&quot;
        azurePowerShellVersion: 'LatestVersion'


## Deploying the merged result to the database

- stage: Deploy_to_tst
  displayName: Deploy
  condition: and(succeeded(), ne(variables['Build.Reason'], 'PullRequest'))

  jobs:
  - job: Deploy
    displayName: Deploy
    pool:
      vmImage: windows-latest
  
    steps:
    - task: DownloadPipelineArtifact@2
      inputs: 
        buildType: 'current'
        artifactName: 'database'
        targetPath: '$(Pipeline.Workspace)/database'

    - powershell: 
        #Get-ChildItem -Path $(Pipeline.Workspace)/database -recurse
        #Get-ChildItem -Path $(Agent.Workspace) -recurse

    - task: SqlAzureDacpacDeployment@1
      displayName: 'Deploying the database to Azure'
      inputs:
        connectedServiceNameARM: $(connectedServiceNameARM)
        ServerName: $(Server_tst)
        DatabaseName: $(DatabaseName_tst)
        SqlUsername: $(DatabaseUser_tst)
        SqlPassword: $(DatabasePassword_tst)
        DacpacFile: $(Pipeline.Workspace)/database/a/$(dacpacfile_location)
        PublishProfile: $(Pipeline.Workspace)/database/a/$(publishprofile_location)
</code></pre>
",https://stackoverflow.com/questions/73691636/azure-pipeline-hosted-agent-connection-to-azure-sql-database-in-unit-testing-of,"['azure', 'unit-testing', 'azure-devops', 'azure-pipelines', 'azure-sql-server']",214,True,0,1
How do I test a general exception in a unit test of my C# Console Application?,"<p>I'm curious as to how I can test against a general exception with unit tests, I am using MSTest for this and NSubstitute for mocking services.</p>
<p>This is a method from my C# Console application, it uploads a file and it's contents to Microsoft Azure.  Logically all that exists is this method since I'm still in the unit testing phase but it makes the assumption the filename and the content will be passed to it when the time comes.</p>
<pre><code>public async Task UploadBlob(string fileName, string content, bool overwrite = false)
{
    using MemoryStream stream = new(Encoding.UTF8.GetBytes(content));
    var blobClient = _container.GetBlobClient(fileName);

    try
    {
        // Upload to azure storage
        await blobClient.UploadAsync(stream, overwrite);
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}
</code></pre>
<p>You can see that we use a try/catch for the upload async portion of this method, for any number reasons this upload could fail and the exception would therefore be caught.  I'm trying to mock this up in my unit test so that I can simulate this outcome but I am not sure how we can test this.</p>
<p>I've searched around and I couldn't find any resources with this sort of scenario, in my application I have more than once instance of a potential exception within a method, at the moment there is no code coverage for this and I'd like to have something in place that can simulate the failure.</p>
<p>I have started my unit test but I've hit a road block and not sure how to test</p>
<pre><code>private readonly FileRepository _sut;
private readonly BlobServiceClient _bsc = Substitute.For&lt;BlobServiceClient&gt;();
private readonly BlobContainerClient _bcc = Substitute.For&lt;BlobContainerClient&gt;();
private readonly BlobClient _bc = Substitute.For&lt;BlobClient&gt;();

public FileRepositoryTests()
{
    _bsc.GetBlobContainerClient(default).ReturnsForAnyArgs(_bcc);
    _bcc.GetBlobClient(default).ReturnsForAnyArgs(_bc);
    _sut = new FileRepository(_blobServiceClient);
}

[TestMethod]
public async Task UploadBlob_FailesToUpload_ThrowsException()
{
    // Arrange
    var fileName = &quot;2022-01-01file.txt&quot;;
    var fileContent = &quot;Hello, world!&quot;;

    // Act
    ...This is just calling the service but I need to simulate the exception
    var result = _sut.UploadBlob(fileName, fileContent);

    // Assert
    ...Need to assert the exception but I have to mock it first
}
</code></pre>
<p>Any help is appreciated</p>
",https://stackoverflow.com/questions/72217691/how-do-i-test-a-general-exception-in-a-unit-test-of-my-c-console-application,"['c#', 'unit-testing']",188,True,0,1
std::ostream class member variable to be used as std::ofstream or std::ostringstream,"<p>I'm struggling with streams. I would like to have FileWriter that writes MyObject data to file or to a stringstream. I don't want the interface of write() to take the file path or the stringstream becouse I may have other concrete writers that serialize to some different devices (i.e. socket). So I need to pass the file path or the stringstream to the FileWriter constructor. I need to have a stringstream as an alternative to a filePath so that I can easily implement unit testing.</p>
<p>Here is a sketch of the classes I have described:</p>
<pre><code>class IObjectWriter {
virtual void write(MyObject&amp; o) = 0;    
};

class FileWriter : public IObjectWriter {

FileWriter(const std::string&amp; filePath) {
    std::ofstream os(filePath, std::ios::out);
    // assign in some way os to stream member variable
}

FileWriter(std::ostringstream&amp; so) {
    // assign in some way os to stream member variable
}

void write(MyObject&amp; o) override {
    stream &lt;&lt; o.getSomeValue();
}   

private:
    std::ostream stream;    
};
</code></pre>
<p>The problem I could not solve is to &quot;assign&quot; the ofstream and ostringstream to the ostream member so that the write() call can write independently on file or stingstream.</p>
<p>Problems I've run into:</p>
<ul>
<li>std::ostream does not have a default constructor</li>
<li>streams not assignable or copyable</li>
<li>not able to use the same rdbuf for ofstream and ostringstream</li>
</ul>
<p>Possible solutions or ideas:</p>
<ul>
<li>use shared_ptr for the member variable, but that means the FileWriter constructor should be modified to accept a shared_ptr for the ostringstream.</li>
<li>I don't think using a std::ostream&amp; for the member variable is a good idea, because of the lifecycle handling of the passes ostringstream</li>
</ul>
",https://stackoverflow.com/questions/71971899/stdostream-class-member-variable-to-be-used-as-stdofstream-or-stdostringst,"['c++', 'ostream']",392,True,0,1
Spring boot testing : NoClassDefFound exception,"<p>I'm using the latest version of Spring boot and an old test fails.</p>
<p>I'm having</p>
<pre><code>Caused by: java.lang.IllegalStateException: Failed to introspect annotated methods on class
Caused by: java.lang.NoClassDefFoundError: MyClass
</code></pre>
<p>My config is</p>
<ul>
<li>spring boot 2.7.2</li>
<li>gradle 7.5</li>
<li>a structure using idiomatic gradle (multiproject and composite build)</li>
</ul>
<p>The subproject failing is the spring-boot-application. The class not found exists inside the src/main/java</p>
<p>The test failing is under src/test/java, annotated with</p>
<p><code>@SpringJUnitConfig(classes = ApplicationServiceAspectTestConfigSuccessListener.class)</code> because it is using <code>@Inject</code> fields.</p>
<p>I understand it is not perfect (unit testing depending on injection ; prefer integration test)</p>
<p>When I debug this test, the classloader tries to use a JarLoader and searches inside the <code>spring-boot-application-default.jar</code>. The jar structure is <code>BOOT-INF / META-INF / org...</code> The  class not found is inside the <code>BOOT-INF/classes/org/xxxx</code>. The jar loader failed :/</p>
<p>My question is : why searching inside the jar and not the build/classes/org/xxx ? and why is the JarLoader not finding the class ?</p>
<p><strong>Update 1</strong>
I think I have a lead. I created a gradle precompiles quality plugins which uses java-text-fixtures. When enable the java-text-fixtures produces two jars and the problem comes from here.</p>
<p>I don't really understand why for the moment (why 2 jars and not only the text-fixtures one).</p>
<p><strong>Update 2</strong>
Ok seems I ran across <a href=""https://github.com/gradle/gradle/issues/11696"" rel=""nofollow noreferrer"">https://github.com/gradle/gradle/issues/11696</a></p>
",https://stackoverflow.com/questions/73195453/spring-boot-testing-noclassdeffound-exception,"['spring-boot', 'gradle', 'testing']",83,False,0,0
Remove Jest error &quot;consider using the jsdom test environment&quot;,"<p>the context is the following: I am learning unit testing using Jest. My current enviroment is Jest with Webpack as I am using ES6 Modules. In my current project, I'm only testing JavaScript logic, not the UI. Ideally, Jest would skip over my imported files and only test functions in my current file. The test suite was working as expected, until I imported a DOM rendering file into my main JS file (import './display.js'). I see this error in every test I run.</p>
<pre><code>import './display.js';
import './style.css';
import {pubSub, ps} from './subscriptions.js';
import {Gameboard, tiles} from './gameboard.js'
</code></pre>
<p>If I don't add import './display.js', I get this error:
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.</p>
<p>I did try installing jsdom as well, but nothing happens.
I also tried adding './display.js' to an excluded files list in my package.json, but that didn't work either.
I used:
collectCoverageFrom: ['!src/display.js']</p>
<p>This is my package.json:</p>
<pre><code>{
  &quot;name&quot;: &quot;battleship&quot;,
  &quot;jest&quot;: {
    &quot;collectCoverageFrom&quot;: [
      &quot;!src/display.js&quot;
    ]
  },
  &quot;version&quot;: &quot;1.0.0&quot;,
  &quot;description&quot;: &quot;&quot;,
  &quot;private&quot;: true,
  &quot;scripts&quot;: {
    &quot;test&quot;: &quot;jest --coverage&quot;,
    &quot;build&quot;: &quot;webpack&quot;,
    &quot;watch&quot;: &quot;jest --watch *.js&quot;
  },
  &quot;repository&quot;: {
    &quot;type&quot;: &quot;git&quot;,
    &quot;url&quot;: &quot;git+https://github.com/itsaflamingo/Battleship.git&quot;
  },
  &quot;author&quot;: &quot;&quot;,
  &quot;license&quot;: &quot;ISC&quot;,
  &quot;bugs&quot;: {
    &quot;url&quot;: &quot;https://github.com/itsaflamingo/Battleship/issues&quot;
  },
  &quot;homepage&quot;: &quot;https://github.com/itsaflamingo/Battleship#readme&quot;,
  &quot;devDependencies&quot;: {
    &quot;@babel/preset-env&quot;: &quot;^7.18.6&quot;,
    &quot;css-loader&quot;: &quot;^6.7.1&quot;,
    &quot;html-webpack-plugin&quot;: &quot;^5.5.0&quot;,
    &quot;jest&quot;: &quot;^28.1.2&quot;,
    &quot;style-loader&quot;: &quot;^3.3.1&quot;,
    &quot;webpack&quot;: &quot;^5.73.0&quot;,
    &quot;webpack-cli&quot;: &quot;^4.10.0&quot;
  },
  &quot;dependencies&quot;: {
    &quot;acorn&quot;: &quot;^8.7.1&quot;,
    &quot;acorn-import-assertions&quot;: &quot;^1.8.0&quot;,
    &quot;ajv&quot;: &quot;^6.12.6&quot;,
    &quot;ajv-keywords&quot;: &quot;^3.5.2&quot;,
    &quot;ansi-regex&quot;: &quot;^5.0.1&quot;,
    &quot;boolbase&quot;: &quot;^1.0.0&quot;,
    &quot;browserslist&quot;: &quot;^4.21.1&quot;,
    &quot;buffer-from&quot;: &quot;^1.1.2&quot;,
    &quot;camel-case&quot;: &quot;^4.1.2&quot;,
    &quot;caniuse-lite&quot;: &quot;^1.0.30001361&quot;,
    &quot;chrome-trace-event&quot;: &quot;^1.0.3&quot;,
    &quot;clean-css&quot;: &quot;^5.3.0&quot;,
    &quot;clone-deep&quot;: &quot;^4.0.1&quot;,
    &quot;colorette&quot;: &quot;^2.0.19&quot;,
    &quot;commander&quot;: &quot;^2.20.3&quot;,
    &quot;cross-spawn&quot;: &quot;^7.0.3&quot;,
    &quot;css-select&quot;: &quot;^4.3.0&quot;,
    &quot;css-what&quot;: &quot;^6.1.0&quot;,
    &quot;cssesc&quot;: &quot;^3.0.0&quot;,
    &quot;dom-converter&quot;: &quot;^0.2.0&quot;,
    &quot;dom-serializer&quot;: &quot;^1.4.1&quot;,
    &quot;domelementtype&quot;: &quot;^2.3.0&quot;,
    &quot;domhandler&quot;: &quot;^4.3.1&quot;,
    &quot;domutils&quot;: &quot;^2.8.0&quot;,
    &quot;dot-case&quot;: &quot;^3.0.4&quot;,
    &quot;electron-to-chromium&quot;: &quot;^1.4.173&quot;,
    &quot;enhanced-resolve&quot;: &quot;^5.10.0&quot;,
    &quot;entities&quot;: &quot;^2.2.0&quot;,
    &quot;envinfo&quot;: &quot;^7.8.1&quot;,
    &quot;es-module-lexer&quot;: &quot;^0.9.3&quot;,
    &quot;escalade&quot;: &quot;^3.1.1&quot;,
    &quot;eslint-scope&quot;: &quot;^5.1.1&quot;,
    &quot;esrecurse&quot;: &quot;^4.3.0&quot;,
    &quot;estraverse&quot;: &quot;^4.3.0&quot;,
    &quot;events&quot;: &quot;^3.3.0&quot;,
    &quot;fast-deep-equal&quot;: &quot;^3.1.3&quot;,
    &quot;fast-json-stable-stringify&quot;: &quot;^2.1.0&quot;,
    &quot;fastest-levenshtein&quot;: &quot;^1.0.12&quot;,
    &quot;find-up&quot;: &quot;^4.1.0&quot;,
    &quot;function-bind&quot;: &quot;^1.1.1&quot;,
    &quot;glob-to-regexp&quot;: &quot;^0.4.1&quot;,
    &quot;graceful-fs&quot;: &quot;^4.2.10&quot;,
    &quot;has&quot;: &quot;^1.0.3&quot;,
    &quot;has-flag&quot;: &quot;^4.0.0&quot;,
    &quot;he&quot;: &quot;^1.2.0&quot;,
    &quot;html-minifier-terser&quot;: &quot;^6.1.0&quot;,
    &quot;htmlparser2&quot;: &quot;^6.1.0&quot;,
    &quot;icss-utils&quot;: &quot;^5.1.0&quot;,
    &quot;import-local&quot;: &quot;^3.1.0&quot;,
    &quot;interpret&quot;: &quot;^2.2.0&quot;,
    &quot;is-core-module&quot;: &quot;^2.9.0&quot;,
    &quot;is-plain-object&quot;: &quot;^2.0.4&quot;,
    &quot;isexe&quot;: &quot;^2.0.0&quot;,
    &quot;isobject&quot;: &quot;^3.0.1&quot;,
    &quot;jest-worker&quot;: &quot;^27.5.1&quot;,
    &quot;jsdom&quot;: &quot;^20.0.0&quot;,
    &quot;json-parse-even-better-errors&quot;: &quot;^2.3.1&quot;,
    &quot;json-schema-traverse&quot;: &quot;^0.4.1&quot;,
    &quot;kind-of&quot;: &quot;^6.0.3&quot;,
    &quot;loader-runner&quot;: &quot;^4.3.0&quot;,
    &quot;locate-path&quot;: &quot;^5.0.0&quot;,
    &quot;lodash&quot;: &quot;^4.17.21&quot;,
    &quot;lower-case&quot;: &quot;^2.0.2&quot;,
    &quot;lru-cache&quot;: &quot;^6.0.0&quot;,
    &quot;merge-stream&quot;: &quot;^2.0.0&quot;,
    &quot;mime-db&quot;: &quot;^1.52.0&quot;,
    &quot;mime-types&quot;: &quot;^2.1.35&quot;,
    &quot;nanoid&quot;: &quot;^3.3.4&quot;,
    &quot;neo-async&quot;: &quot;^2.6.2&quot;,
    &quot;no-case&quot;: &quot;^3.0.4&quot;,
    &quot;node-releases&quot;: &quot;^2.0.5&quot;,
    &quot;nth-check&quot;: &quot;^2.1.1&quot;,
    &quot;p-limit&quot;: &quot;^2.3.0&quot;,
    &quot;p-locate&quot;: &quot;^4.1.0&quot;,
    &quot;p-try&quot;: &quot;^2.2.0&quot;,
    &quot;param-case&quot;: &quot;^3.0.4&quot;,
    &quot;pascal-case&quot;: &quot;^3.1.2&quot;,
    &quot;path-exists&quot;: &quot;^4.0.0&quot;,
    &quot;path-key&quot;: &quot;^3.1.1&quot;,
    &quot;path-parse&quot;: &quot;^1.0.7&quot;,
    &quot;picocolors&quot;: &quot;^1.0.0&quot;,
    &quot;pkg-dir&quot;: &quot;^4.2.0&quot;,
    &quot;postcss&quot;: &quot;^8.4.14&quot;,
    &quot;postcss-modules-extract-imports&quot;: &quot;^3.0.0&quot;,
    &quot;postcss-modules-local-by-default&quot;: &quot;^4.0.0&quot;,
    &quot;postcss-modules-scope&quot;: &quot;^3.0.0&quot;,
    &quot;postcss-modules-values&quot;: &quot;^4.0.0&quot;,
    &quot;postcss-selector-parser&quot;: &quot;^6.0.10&quot;,
    &quot;postcss-value-parser&quot;: &quot;^4.2.0&quot;,
    &quot;pretty-error&quot;: &quot;^4.0.0&quot;,
    &quot;punycode&quot;: &quot;^2.1.1&quot;,
    &quot;randombytes&quot;: &quot;^2.1.0&quot;,
    &quot;rechoir&quot;: &quot;^0.7.1&quot;,
    &quot;relateurl&quot;: &quot;^0.2.7&quot;,
    &quot;renderkid&quot;: &quot;^3.0.0&quot;,
    &quot;resolve&quot;: &quot;^1.22.1&quot;,
    &quot;resolve-cwd&quot;: &quot;^3.0.0&quot;,
    &quot;resolve-from&quot;: &quot;^5.0.0&quot;,
    &quot;safe-buffer&quot;: &quot;^5.2.1&quot;,
    &quot;schema-utils&quot;: &quot;^3.1.1&quot;,
    &quot;semver&quot;: &quot;^7.3.7&quot;,
    &quot;serialize-javascript&quot;: &quot;^6.0.0&quot;,
    &quot;shallow-clone&quot;: &quot;^3.0.1&quot;,
    &quot;shebang-command&quot;: &quot;^2.0.0&quot;,
    &quot;shebang-regex&quot;: &quot;^3.0.0&quot;,
    &quot;source-map&quot;: &quot;^0.6.1&quot;,
    &quot;source-map-js&quot;: &quot;^1.0.2&quot;,
    &quot;source-map-support&quot;: &quot;^0.5.21&quot;,
    &quot;strip-ansi&quot;: &quot;^6.0.1&quot;,
    &quot;supports-color&quot;: &quot;^8.1.1&quot;,
    &quot;supports-preserve-symlinks-flag&quot;: &quot;^1.0.0&quot;,
    &quot;tapable&quot;: &quot;^2.2.1&quot;,
    &quot;terser&quot;: &quot;^5.14.1&quot;,
    &quot;terser-webpack-plugin&quot;: &quot;^5.3.3&quot;,
    &quot;tslib&quot;: &quot;^2.4.0&quot;,
    &quot;update-browserslist-db&quot;: &quot;^1.0.4&quot;,
    &quot;uri-js&quot;: &quot;^4.4.1&quot;,
    &quot;util-deprecate&quot;: &quot;^1.0.2&quot;,
    &quot;utila&quot;: &quot;^0.4.0&quot;,
    &quot;watchpack&quot;: &quot;^2.4.0&quot;,
    &quot;webpack-merge&quot;: &quot;^5.8.0&quot;,
    &quot;webpack-sources&quot;: &quot;^3.2.3&quot;,
    &quot;which&quot;: &quot;^2.0.2&quot;,
    &quot;wildcard&quot;: &quot;^2.0.0&quot;,
    &quot;yallist&quot;: &quot;^4.0.0&quot;
  },
  &quot;keywords&quot;: []
}
</code></pre>
<p>This is my webpack.config:</p>
<pre><code>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    mode: 'development',
    entry: {
      index: './src/index.js',
      print: './src/print.js',
      display: './src/display.js',
      subscriptions: './src/subscriptions.js'
    },
    plugins: [
      new HtmlWebpackPlugin({
        title: 'Battleship',
      }),
    ],
     output: {
      filename: '[name].bundle.js',
       path: path.resolve(__dirname, 'dist'),
       clean: true,
     },
     module: {
        rules: [
          {
            test: /\.css$/i,
            use: ['style-loader', 'css-loader'],
          },
        ],
      },
   };
</code></pre>
<p>This is the test I am running for index.js:</p>
<pre><code>import {Ship, Players, playerBoats} from './index';

test('factory function returns object', () =&gt; {
    expect(Ship('Carrier', 5)).toMatchObject({
        boatName: 'Carrier',
        length: 5,
        hitSpot: [],
        sunk: false,
    });
})

test('when hit, factory function returns modified object', () =&gt; {
    expect(Ship('Destroyer', 2).isHit(1, playerBoats)).toMatchObject({
        boatName: 'Destroyer',
        coordinates: [],
        length: 2,
        hitSpot: [1],
        sunk: false,
    });
})

test('player can attack computer multiple times', () =&gt; {
    expect(Players().Player().playerAttack(4)).toMatchObject({
        boatName: 'Carrier',
        coordinates: [2, 3, 4],
        length: 5,
        hitSpot: [2, 4],
        sunk: false,
    })
})

</code></pre>
<p>I am running Linux on Chromebook and using VS Code, I'm not sure if that makes a difference. I just want to be able to skip UI tests with Jest.</p>
",https://stackoverflow.com/questions/72885468/remove-jest-error-consider-using-the-jsdom-test-environment,"['javascript', 'unit-testing', 'webpack', 'jestjs', 'jsdom']",787,False,0,1
"Best practise of test database configuration for pytest, SQLAlchemy + FastAPI","<p>I have built one of my services using FastAPI(0.75.1), SQLAlchemy(1.4.34) with pytest(7.1.1) and factory boy (3.2.1) for unit-testing.</p>
<p>I have managed to set up testsession mechanism with test database.
I have been writing unit-tests for some time actively using factories, but the further I go, the more I face the problem of parallel sessions.
My current TestSession setup looks like this</p>
<pre><code>TestSessionLocal = orm.scoped_session(
    sessionmaker(
        autoflush=False, bind=engine
    )
)
</code></pre>
<p>And this is what I am importing when declaring factories</p>
<pre><code>class FooFactory(factory.alchemy.SQLAlchemyModelFactory):
    bar = factory.Faker('last_name')

    class Meta:
        model = Foo
        sqlalchemy_session = TestSessionLocal
        sqlalchemy_session_persistence = 'commit'
</code></pre>
<p>With time I get more and more errors because of parallel test sessions that can't either create and object or cannot tear them down.</p>
<p>My question is - am I correct to assume that I need to decrease the number of testsessions running throughout all tests to one? So, it should be the only session that manages factories, in-test changes and changes that must occur on the part of application running in the test mode?
In that case - what is the best way to make sure that at least inside unit tests I am using only one session to create objects via factories and to do all other stuff? Should I go after fixture that set up test session and then fixtures that set up factories working on that session?</p>
",https://stackoverflow.com/questions/73699499/best-practise-of-test-database-configuration-for-pytest-sqlalchemy-fastapi,"['python', 'sqlalchemy', 'pytest', 'fastapi', 'factory-boy']",489,False,0,0
Dart Unit Tests - Await Results of an Async Function in Class Constructor,"<p>I have a <code>FooViewModel</code> that is supposed to check Cloud Firestore for a <code>mainFoo</code> upon initialization, and set a <code>mainFoo</code> property to this value if one is found.</p>
<p>Since it's looking at cloud Firestore, it's an asynchronous function.</p>
<p>The view is supposed to show an empty value view if no <code>mainFoo</code> exists, and a view showing the <code>mainFoo</code> if one does exist.</p>
<p>This works fine in practice, but where I'm struggling is my unit testing.</p>
<p>I want to test that this method is called when the viewModel is initialized, and that it does set the <code>mainFoo</code> if one does exist. But setting my result to <code>mainFoo</code> seems to happen before <code>loadMainFoo</code> has completed, and result still ends up as null.</p>
<p>Here's the basics of what's in the class:</p>
<pre><code>class FooViewModel extends BaseViewModel {
  // MARK
  // Properties
  Foo? mainFoo;

  FooViewModel() {
    loadMainFoo();
  }

  /// Returns the mainFoo if there is one.
  Future&lt;Foo&gt;? loadMainFoo() async {
      // Code in here to load the Foo from Firestone, and sets the mainFoo to the Foo that gets loaded.
  }
}
</code></pre>
<p>My test sets <code>sut</code> to a new instance of <code>FooViewModel</code>, which will also trigger <code>loadMainFoo</code>. The next line is to set my result to the <code>mainFoo</code> property in <code>sut</code>.</p>
<p>This is where the issue seems to happen - I know that <code>loadMainFoo</code> is being called, but <code>result</code> is getting set before <code>loadMainFoo</code> has finished, and it still ends up as null.</p>
<p>Is there any way to make sure result doesn't get set until I can be sure <code>loadMainFoo</code> has completed?
As far as I know I can't make the constructors asynchronous.</p>
<pre><code>      test('Makes sure mainFoo exists after logic performed', () async {
        // ARRANGE
        sut = FooViewModel();

        // ACT
        var result = sut.mainFoo;

        // ASSERT
        expect(result != null, true);
      });
</code></pre>
",https://stackoverflow.com/questions/73352477/dart-unit-tests-await-results-of-an-async-function-in-class-constructor,"['unit-testing', 'dart', 'async-await']",43,True,0,1
No EntityManager with actual transaction available for current thread - cannot reliably process &#39;remove&#39; call,"<h3>API Requests using Postman</h3>
<ul>
<li>I tried to send HTTP requests to the java backend web server application and perform CRUD operations. <code>GET</code> operations are working fine and gave back the proper response but save, update and delete operations gave the following error.</li>
<li>Please note that there are three customer records in my database and I tried to send HTTP requests as follows;</li>
</ul>
<ol>
<li>GET http://localhost:8080/tms/api/v1/customers   ---&gt; Successful ✔</li>
<li>GET http://localhost:8080/tms/api/v1/customers/3   ---&gt; Successful ✔</li>
<li>DELETE http://localhost:8080/tms/api/v1/customers/3   ---&gt; Unsuccessful ❌</li>
</ol>
<h3>Error Log</h3>
<pre><code>Customer ID: 2
02-Feb-2022 09:59:11.271 SEVERE [http-nio-8080-exec-2] com.myapp.web.api.exceptionhandler.AppWideExceptionHandler.globalExceptionHandler null
    javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'remove' call
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:295)
        at com.sun.proxy.$Proxy80.remove(Unknown Source)
        at com.myapp.web.dal.CrudDAOImpl.delete(CrudDAOImpl.java:67)
        at com.myapp.web.business.custom.impl.CustomerBOImpl.deleteCustomer(CustomerBOImpl.java:79)
        at com.myapp.web.api.CustomerController.deleteCustomer(CustomerController.java:116)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
        at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)
        at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)
        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:1067)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
        at org.springframework.web.servlet.FrameworkServlet.doDelete(FrameworkServlet.java:931)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
        at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:687)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:359)
        at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)
        at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
        at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:889)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1735)
        at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
        at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)
</code></pre>
<h3>API Layer</h3>
<ol>
<li>CustomerController.java</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.api;

import com.myapp.web.api.util.ApiUtil;
import com.myapp.web.business.custom.CustomerBO;
import com.myapp.web.dto.CustomerDTO;
import com.myapp.web.exception.IdFormatException;
import com.myapp.web.exception.RecordNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(origins = &quot;http://localhost:8080&quot;)
@RequestMapping(&quot;/api/v1/customers&quot;)
@RestController
public class CustomerController {

    @Autowired
    private CustomerBO customerBO;

    /**
     * Get all customers list.
     *
     * @return List&lt;CustomerDTO&gt; customersList.
     */
    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public List&lt;CustomerDTO&gt; getAllCustomers() throws Exception {
        return customerBO.getAllCustomers();
    }

    /**
     * Get customer by customer ID.
     *
     * @return CustomerDTO customer object.
     * @throws IdFormatException       if the ID is not an Integer.
     * @throws RecordNotFoundException if matching customer record not found,
     */
    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE,
            value = &quot;/{id:\\d}&quot;)
    public CustomerDTO getCustomerByID(@PathVariable(name = &quot;id&quot;) String id) throws Exception {
        System.out.println(&quot;CustomerID: &quot; + id);

        Integer customerID = ApiUtil.getIntegerId(id);

        CustomerDTO customer = customerBO.getCustomerByID(customerID);
        System.out.println(&quot;Customer Result: &quot; + customer);

        /* If customer not found. */
        if (customer == null) throw new RecordNotFoundException();
        return customer;
    }

    /**
     * Delete customer by Customer ID.
     */
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @DeleteMapping(value = &quot;/{id:\\d}&quot;)
    public void deleteCustomer(@PathVariable String id) throws Exception {
        Integer customerID = ApiUtil.getIntegerId(id);
        System.out.println(&quot;Customer ID: &quot; + customerID);
        customerBO.deleteCustomer(customerID);
    }

}
</code></pre>
<h3>Business Layer</h3>
<ol>
<li>SuperBO.java</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.business;

public interface SuperBO {
}
</code></pre>
<ol start=""2"">
<li>CustomerBOImpl.java</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.business.custom.impl;

import com.myapp.web.business.custom.CustomerBO;
import com.myapp.web.business.custom.util.mapper.CustomerDTOMapper;
import com.myapp.web.dal.custom.CustomerDAO;
import com.myapp.web.dto.CustomerDTO;
import com.myapp.web.entity.Customer;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@NoArgsConstructor
@Transactional
@Service
public class CustomerBOImpl implements CustomerBO {

    @Autowired
    private CustomerDAO customerDAO;

    @Autowired
    private CustomerDTOMapper mapper;

    @Override
    public void deleteCustomer(int customerID) throws Exception {
        /* delete. */
        this.customerDAO.delete(customerID);
    }

    @Transactional(readOnly = true)
    @Override
    public CustomerDTO getCustomerByID(int customerID) throws Exception {
        /* get customer by customer ID. */
        return this.mapper.getCustomerDTO(this.customerDAO.get(customerID));
    }

    @Transactional(readOnly = true)
    @Override
    public List&lt;CustomerDTO&gt; getAllCustomers() throws Exception {
        /* get all customers. */
        return this.mapper.getCustomerDTOs(this.customerDAO.getAll());
    }
}
</code></pre>
<ol start=""3"">
<li>CustomerDTOMapper.java</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.business.custom.util.mapper;

import com.myapp.web.dto.CustomerDTO;
import com.myapp.web.entity.Customer;
import org.mapstruct.Mapper;

import java.util.List;

@Mapper(componentModel = &quot;spring&quot;)
public abstract class CustomerDTOMapper {

    /*  -------------------- Customer  -------------------- */
    public abstract Customer getCustomer(CustomerDTO customerDTO);

    public abstract CustomerDTO getCustomerDTO(Customer customer);

    public abstract List&lt;CustomerDTO&gt; getCustomerDTOs(List&lt;Customer&gt; customerList);
}
</code></pre>
<h3>Data Access Layer</h3>
<ol>
<li>SuperDAO.java</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.dal;

import javax.persistence.EntityManager;

public interface SuperDAO {
    EntityManager getEntityManager();
}

</code></pre>
<ol start=""2"">
<li>CrudDAO.java</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.dal;

import com.myapp.web.entity.SuperEntity;

import java.io.Serializable;
import java.util.List;

public interface CrudDAO&lt;T extends SuperEntity&lt;Serializable&gt;, PK extends Serializable&gt; extends SuperDAO {

    /**
     * saving an entity and return the entity.
     *
     * @return T SuperEntity. */
    T save(T entity) throws Exception;

    void update(T entity) throws Exception;

    void delete(PK key) throws Exception;

    T get(PK key) throws Exception;

    List&lt;T&gt; getAll() throws Exception;
}
</code></pre>
<ol start=""3"">
<li>CrudDAOImpl.java</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.dal;

import com.myapp.web.entity.SuperEntity;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public class CrudDAOImpl&lt;T extends SuperEntity&lt;Serializable&gt;, K extends Serializable&gt; implements CrudDAO&lt;T, K&gt; {

    private final Class&lt;T&gt; entityClass;
    @PersistenceContext
    private EntityManager entityManager;

    public CrudDAOImpl() {
        this.entityClass =
                (Class&lt;T&gt;) (((ParameterizedType) (this.getClass().getGenericSuperclass())).getActualTypeArguments()[0]);
    }

    /**
     * This method is used to pass the EntityManager to the lower level classes that extend the CrudDAOImpl class.
     */
    public EntityManager getEntityManager() {
        return this.entityManager;
    }

    @Override
    public void delete(K key) throws Exception {
        this.entityManager.remove(key);
    }

    @Override
    public T get(K key) throws Exception {
        return this.entityManager.find(this.entityClass, key);
    }

    @Override
    public List&lt;T&gt; getAll() throws Exception {
        List&lt;T&gt; resultList = (List&lt;T&gt;) this.entityManager.
                createQuery(&quot;SELECT e FROM &quot; + this.entityClass.getName() + &quot; e&quot;).getResultList();
        return resultList;
    }
}
</code></pre>
<ol start=""4"">
<li>CustomerDAO.java</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.dal.custom;

import com.myapp.web.dal.CrudDAO;
import com.myapp.web.entity.Customer;

public interface CustomerDAO extends CrudDAO&lt;Customer, Integer&gt; {
}
</code></pre>
<ol start=""5"">
<li>CustomerDAOImpl.java</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.dal.custom.impl;

import com.myapp.web.dal.CrudDAOImpl;
import com.myapp.web.dal.custom.CustomerDAO;
import com.myapp.web.entity.Customer;
import org.springframework.stereotype.Repository;

@Repository
public class CustomerDAOImpl extends CrudDAOImpl&lt;Customer, Integer&gt; implements CustomerDAO {
}
</code></pre>
<h3>Here's what I have tried.</h3>
<p>I tried unit testing. BO layer and DAO layer unit test case worked as intended but when I check the API by sending HTTP request using Postman, save, update and delete cannot be performed using the API.</p>
<ol>
<li>CustomerDAOImplTest.java ----&gt; TEST PASSED ! ✔</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.dal.custom.impl;

import com.myapp.web.WebAppConfig;
import com.myapp.web.WebRootConfig;
import com.myapp.web.dal.custom.CustomerDAO;
import com.myapp.web.entity.Customer;
import com.myapp.web.entity.enumeration.GenderTypes;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static org.junit.Assert.*;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebRootConfig.class, WebAppConfig.class})
public class CustomerDAOImplTest {

    @Autowired
    private CustomerDAO customerDAO;

    @Test
    public void checkCustomerDAO() {
        assertNotNull(customerDAO);
    }

    @Transactional
    @Test
    public void getCustomerByID() throws Exception {
        assertNotNull(customerDAO);

        Customer customer = this.customerDAO.get(10);
        System.out.println(&quot;GET Customer Entity: &quot; + customer);
        assertNotNull(customer);
    }

    @Test
    public void getAllCustomers() throws Exception {
        List&lt;Customer&gt; customersList = this.customerDAO.getAll();
        assertEquals(2, customersList.size());
    }


    @Transactional
    @Test
    public void deleteCustomer() throws Exception {
        assertNotNull(this.customerDAO);

        /* delete */
        this.customerDAO.delete(3);

        Customer customerFromDB = this.customerDAO.get(10);
        assertNull(customerFromDB);
    }
}
</code></pre>
<p><a href=""https://i.stack.imgur.com/N6bbx.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/N6bbx.png"" alt=""CustomerDAOImplTest-delete"" /></a></p>
<ol start=""2"">
<li>CustomerBOImpl.java ----&gt; TEST PASSED ! ✔</li>
</ol>
<pre class=""lang-java prettyprint-override""><code>package com.myapp.web.business.custom.impl;

import com.myapp.web.WebAppConfig;
import com.myapp.web.WebRootConfig;
import com.myapp.web.business.custom.CustomerBO;
import com.myapp.web.dto.CustomerDTO;
import com.myapp.web.entity.enumeration.GenderTypes;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {WebRootConfig.class, WebAppConfig.class})
public class CustomerBOImplTest {

    @Autowired
    private CustomerBO customerBO;

    @Test
    public void checkCustomerBO() {
        assertNotNull(customerBO);
    }

    //    @Transactional
    @Test
    public void deleteCustomer() throws Exception {
        assertNotNull(this.customerBO);

        /* delete */
        this.customerBO.deleteCustomer(3);

        CustomerDTO customerDTOFromDB = this.customerBO.getCustomerByID(10);
        assertNull(customerDTOFromDB);
    }

}
</code></pre>
<p><a href=""https://i.stack.imgur.com/7xL6v.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/7xL6v.png"" alt=""CustomerBOImplTest-delete"" /></a></p>
<h3>pom.xml dependencies</h3>
<pre class=""lang-xml prettyprint-override""><code>
&lt;dependencies&gt;

    &lt;!-- Servlet-API --&gt;
    &lt;!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;javax.servlet&lt;/groupId&gt;
        &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt;
        &lt;version&gt;4.0.1&lt;/version&gt;
        &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;!-- MySQL connector --&gt;
    &lt;!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;mysql&lt;/groupId&gt;
        &lt;artifactId&gt;mysql-connector-java&lt;/artifactId&gt;
        &lt;version&gt;8.0.27&lt;/version&gt;
        &lt;scope&gt;compile&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;!-- SLF4J for logging--&gt;
    &lt;!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-jdk14 --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.slf4j&lt;/groupId&gt;
        &lt;artifactId&gt;slf4j-jdk14&lt;/artifactId&gt;
        &lt;version&gt;2.0.0-alpha1&lt;/version&gt;
        &lt;scope&gt;compile&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;!-- Junit4 for unit testing --&gt;
    &lt;!-- https://mvnrepository.com/artifact/junit/junit --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;junit&lt;/groupId&gt;
        &lt;artifactId&gt;junit&lt;/artifactId&gt;
        &lt;version&gt;4.13.2&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;!-- Apache Commons Validator --&gt;
    &lt;!-- https://mvnrepository.com/artifact/commons-validator/commons-validator --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;commons-validator&lt;/groupId&gt;
        &lt;artifactId&gt;commons-validator&lt;/artifactId&gt;
        &lt;version&gt;1.7&lt;/version&gt;
    &lt;/dependency&gt;


    &lt;!-- mapstruct --&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;!-- lombok  --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;
        &lt;artifactId&gt;lombok&lt;/artifactId&gt;
        &lt;version&gt;1.18.22&lt;/version&gt;
        &lt;scope&gt;provided&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;!-- Hibernate --&gt;
    &lt;!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.hibernate&lt;/groupId&gt;
        &lt;artifactId&gt;hibernate-core&lt;/artifactId&gt;
        &lt;version&gt;5.6.3.Final&lt;/version&gt;
    &lt;/dependency&gt;


    &lt;!-- Apache Commons Codecs --&gt;
    &lt;!-- https://mvnrepository.com/artifact/commons-codec/commons-codec --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;commons-codec&lt;/groupId&gt;
        &lt;artifactId&gt;commons-codec&lt;/artifactId&gt;
        &lt;version&gt;1.15&lt;/version&gt;
    &lt;/dependency&gt;


    &lt;!-- Spring Data Access ==================================================================== --&gt;

    &lt;!--Spring ORM --&gt;
    &lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-orm --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-orm&lt;/artifactId&gt;
        &lt;version&gt;5.3.14&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!-- Apache Commons DBCP --&gt;
    &lt;!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.apache.commons&lt;/groupId&gt;
        &lt;artifactId&gt;commons-dbcp2&lt;/artifactId&gt;
        &lt;version&gt;2.9.0&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!-- Spring Data Access - Spring AOP - Aspectj ========================================== --&gt;
    &lt;!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.aspectj&lt;/groupId&gt;
        &lt;artifactId&gt;aspectjrt&lt;/artifactId&gt;
        &lt;version&gt;1.9.7&lt;/version&gt;
    &lt;/dependency&gt;


    &lt;!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.aspectj&lt;/groupId&gt;
        &lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt;
        &lt;version&gt;1.9.7&lt;/version&gt;
        &lt;scope&gt;runtime&lt;/scope&gt;
    &lt;/dependency&gt;

    &lt;!-- Spring Web MVC =================================================================== --&gt;
    &lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt;
        &lt;version&gt;5.3.15&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!-- JACKSON DATABIND --&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.13.1&lt;/version&gt;
    &lt;/dependency&gt;

    &lt;!--Jackson Datatype--&gt;
    &lt;!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;com.fasterxml.jackson.datatype&lt;/groupId&gt;
        &lt;artifactId&gt;jackson-datatype-jsr310&lt;/artifactId&gt;
        &lt;version&gt;2.13.1&lt;/version&gt;
    &lt;/dependency&gt;


    &lt;!--Spring TestContext Framework--&gt;
    &lt;!-- https://mvnrepository.com/artifact/org.springframework/spring-test --&gt;
    &lt;dependency&gt;
        &lt;groupId&gt;org.springframework&lt;/groupId&gt;
        &lt;artifactId&gt;spring-test&lt;/artifactId&gt;
        &lt;version&gt;5.3.15&lt;/version&gt;
        &lt;scope&gt;test&lt;/scope&gt;
    &lt;/dependency&gt;

&lt;/dependencies&gt;

</code></pre>
<h3>Development Enviroment</h3>
<ol>
<li>Java 8</li>
<li>Tomcat 9</li>
</ol>
<p>I refer to these following questions and answers but, I could not fix the issue. I would appreciate some help to fix the
error and, understand the error.</p>
<ol>
<li><a href=""https://stackoverflow.com/a/32552558/12898581"">https://stackoverflow.com/a/32552558/12898581</a></li>
<li><a href=""https://stackoverflow.com/q/43901381/12898581"">javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread</a></li>
<li><a href=""https://www.wilfriedbarth.com/til/2018-03-31-spring-transactional-annotation/"" rel=""nofollow noreferrer"">https://www.wilfriedbarth.com/til/2018-03-31-spring-transactional-annotation/</a></li>
</ol>
",https://stackoverflow.com/questions/70950905/no-entitymanager-with-actual-transaction-available-for-current-thread-cannot-r,"['java', 'spring', 'spring-mvc', 'java-8']",1019,False,4,0
Correct way to hint that a class is implementing a Protocol?,"<p>On a path of improvement for my Python dev work. I have interest in testing interfaces defined with Protocol at CI/deb building time, so that if a interface isn't actually implemented by a class we will know immediately after the unit tests run.</p>
<p>My approach was typing with Protocol and using implements runtime_checkable to build unit test.   That works, but the team got into a little debate about how to <em>indicate</em> a concretion was implementing a Protocol without busting runtime_checkable. In C++/Java you need inheritance to indicate implementations of interfaces, but with Python you don't necessarily need inheritance.  The conversation centered on whether we should be inheriting from a Protocol interface class.</p>
<p>Consider this code example at the end which provides most of the gist of the question. We were thinking about Shape and indicating how to hint to a future developer that Shape is providing IShape, but doing so with inheritance makes the runtime_checkable version of isinstance unusable for its purpose in unit-testing.</p>
<p>There is a couple of paths to improvement here:</p>
<p>We could find a better way to hint that Shape implements IShape which doesn't involve direct inheritance.
We could find a better way to check if an interface is implemented at test deb package build time. Maybe runtime_checkable is the wrong idea.</p>
<p>Anyone got guidance on how to use Python better?
Thanks!</p>
<pre><code>
from typing import (
    Protocol,
    runtime_checkable
)
import dataclasses

@runtime_checkable
class IShape(Protocol):
    x: float


@dataclasses.dataclass
class Shape(IShape):
    foo:float = 0.

s  = Shape()
# evaluates as True but doesnt provide the interface. Undermines the point of the run-time checkable in unit testing
assert isinstance(s, IShape)
print(s.x)  # Error.  Interface wasnt implemented




#
# Contrast with this assert
#
@dataclasses.dataclass
class Goo():
    x:float = 1

@dataclasses.dataclass
class Hoo():
    foo: float = 1

g = Goo()
h = Hoo()
assert isinstance(g, IShape)  # asserts as true
# but because it has the interface and not because we inherited.
print(g.x)


assert isinstance(h, IShape)  # asserts as False which is what we want

</code></pre>
",https://stackoverflow.com/questions/73069962/correct-way-to-hint-that-a-class-is-implementing-a-protocol,"['python', 'unit-testing', 'typing']",1411,True,4,1
Issue with navigating to another page using React testing library &amp; AWS Amplify,"<p>I have an application that is set up to navigate any unauthenticated user to the &quot;/&quot; Route. I use AWS Cognito for authentication and aws-amplify library to interact with Cognito.</p>
<p>Let's consider two pages Page A and Page B.
The user reaches Page A from Page B. Following is a general flow of interactions:</p>
<p>Page B -&gt; click something -&gt; Page A -&gt; do something -&gt; Hit Back -&gt; Page B</p>
<p>The user can hit a back button to go back to Page A.</p>
<p>While unit testing this functionality, the following issue occurs:
When I try to mock going back from a Page A to another Page B and expecting to see some info on Page B based on an action done from Page A, I notice that, on hitting Back, the route is actually &quot;/&quot; and not the route for Page B in the test.</p>
<p>The information that needs to be saved between the back and forth is passed between these components using the React Context API.</p>
<p>Whenever I try mocking going back from Page A, and expecting to fall to Page B, the history.location.pathname is always &quot;/&quot; while the testing DOM is showing that of Page A.</p>
<p>Am I missing something in the mocking? I have also tried to mock the authentication, but no luck.</p>
<p>Following is a code snippet of the test:</p>
<pre><code>import { API, Auth } from 'aws-amplify';
import { createMemoryHistory } from 'history';


test('Should see files uploaded if user goes back and chooses the same option', async () =&gt; {
  Auth.signIn = jest.fn().mockImplementation(() =&gt; {
    return Promise.resolve();
  });

  Auth.currentAuthenticatedUser = jest.fn().mockImplementation(() =&gt; {
    return Promise.resolve({ attributes: {} });
  });

  // mock history object
  const history = createMemoryHistory();
  history.push('', {});

  render(
    &lt;MockTheme&gt;
      &lt;Router history={history}&gt;
        &lt;AddStationProvider&gt;
          &lt;AddTimeSeriesFiles /&gt; //Page A
        &lt;/AddStationProvider&gt;
      &lt;/Router&gt;
    &lt;/MockTheme&gt;
  );

  fireEvent.click(screen.getByRole('button', { name: /Back/ }));
  expect(history.location.pathname).toBe('/add-station-options'); // URL of Page B
});
</code></pre>
<p>And this is the outcome:</p>
<pre><code>expect(received).toBe(expected) // Object.is equality                                                                                                                                       
Expected: &quot;/add-station-options&quot;                                                                                                       
Received: &quot;/&quot;                                                                                                                          

  412 |
  413 |   fireEvent.click(screen.getByRole('button', { name: /Back/ }));
&gt; 414 |   expect(history.location.pathname).toBe('/add-station-options');
</code></pre>
<p>Here is how the main App.tsx looks like</p>
<pre><code>&lt;UserContext.Provider
value={{
  user,
  isLoadingUser,
  handleSignIn,
  handleSignOut,
  handleUpdateAttributes,
  handleConfirmEmailChange,
  handleChangePassword,
}}
&gt;
&lt;div className={classes.root}&gt;
  &lt;ErrorProvider&gt;
    &lt;SuccessProvider&gt;
      &lt;ErrorBoundary&gt;
          &lt;ErrorBoundary&gt;
            &lt;Switch&gt;
              &lt;AddStationProvider&gt;
                &lt;PrivateRoute exact path={urls.addTimeSeriesFiles}&gt;
                  &lt;AddTimeSeriesFiles /&gt;
                &lt;/PrivateRoute&gt;
                &lt;PrivateRoute exact path={urls.addStationOptions}&gt;
                  &lt;AddStationOptions /&gt;
                &lt;/PrivateRoute&gt;
                &lt;PrivateRoute exact path={urls.addStationInfo}&gt;
                  &lt;AddStationInfoPage /&gt;
                &lt;/PrivateRoute&gt;
              &lt;/AddStationProvider&gt;
            &lt;/Switch&gt;
          &lt;/ErrorBoundary&gt;
      &lt;/ErrorBoundary&gt;
    &lt;/SuccessProvider&gt;
  &lt;/ErrorProvider&gt;
&lt;/div&gt;
&lt;/UserContext.Provider&gt;
</code></pre>
",https://stackoverflow.com/questions/72647534/issue-with-navigating-to-another-page-using-react-testing-library-aws-amplify,"['reactjs', 'unit-testing', 'testing', 'react-router', 'react-testing-library']",137,False,2,0
Unit Testing Passport Strategy / NestJS Guard,"<p>I have a JWTGuard() decorator which follows the implementation as described in <a href=""https://docs.nestjs.com/security/authentication#jwt-functionality"" rel=""nofollow noreferrer"">https://docs.nestjs.com/security/authentication#jwt-functionality</a></p>
<p>It looks like so:</p>
<pre class=""lang-js prettyprint-override""><code>import { ExecutionContext, Injectable } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { IS_PUBLIC_ROUTE } from '../decorators/public-route.decorator';

@Injectable()
export class JWTAuthenticationGuard extends AuthGuard('jwt') {
  constructor(private readonly reflector: Reflector) {
    super();
  }
 canActivate(context: ExecutionContext): Promise&lt;boolean&gt; {
    const isPublic = this.reflector.getAllAndOverride&lt;boolean&gt;(
      IS_PUBLIC_ROUTE,
      [context.getHandler(), context.getClass()],
    );

    if (isPublic) return true;

    return super.canActivate(context)
  }
}
</code></pre>
<p>It works as expected, but having difficulty unit testing the guard. In short, I want to test three things:</p>
<ul>
<li>If IS_PUBLIC_ROUTE is set, then canActivate() returns true ✅ this unit test works</li>
<li>If an expired/invalid/incorrectly signed token is passed, canActivate() returns false ❌</li>
<li>If a valid token is found, canActivate() returns true ❌</li>
</ul>
<p>I tried to follow <a href=""https://github.com/jmcdo29/testing-nestjs/blob/master/apps/complex-sample/src/cat/cat.guard.spec.ts"" rel=""nofollow noreferrer"">https://github.com/jmcdo29/testing-nestjs/blob/master/apps/complex-sample/src/cat/cat.guard.spec.ts</a> which just tests a bare guard, not extending a Passport Guard.</p>
<p>Tests are setup as follows:</p>
<pre class=""lang-js prettyprint-override""><code>  let guard: JWTAuthenticationGuard;
  const reflector = new Reflector();

  beforeEach(() =&gt; {
    guard = new JWTAuthenticationGuard(reflector);
    passport.use('jwt', new JWTStrategy());
  });
</code></pre>
<p>The first test (should return false)</p>
<pre class=""lang-js prettyprint-override""><code> it('should return false if no authorization token is found', () =&gt; {
    const context = createMock&lt;ExecutionContext&gt;();

    const result = guard.canActivate(context);

    expect(result).toBe(false);
  });
</code></pre>
<p>My test never even makes it to the <code>expect()</code> clause, as it has thrown an UnauthorisedException and the test suite exits entirely.</p>
<p>I tried debugging inside the canActivate() method, and checking the type of super.canActivate() which tells me that it's a pending promise. I tried awaiting it, but still says its Pending, I tried wrapping in a try/catch, but the catch block never runs. Reading through the code of passport's AuthGuard, it never throws either.</p>
<p>I tried to add a valid token:</p>
<pre class=""lang-js prettyprint-override""><code>it('should return false if no authorization token is found', async () =&gt; {
    const context = createMock&lt;ExecutionContext&gt;();
    expect(context.switchToHttp()).toBeDefined();
    context.switchToHttp().getRequest.mockReturnValue({
      headers: {
        Authorization:
          'Bearer ey...[truncated]...dE',
      },
    });

    const result = await guard.canActivate(context);

    expect(result).toBe(true);
</code></pre>
<p>however I still just get an UnauthorisedException thrown from god knows where at the <code>result = guard.can...</code> line, and still never makes it to the expect.</p>
<p>Any guidance would be appriciated.</p>
",https://stackoverflow.com/questions/73904339/unit-testing-passport-strategy-nestjs-guard,"['unit-testing', 'nestjs', 'passport.js']",430,False,1,0
Allowance is returned zero even after approval,"<p>I was unit testing my contract and within the tests i approved that the smart contract should be able to spend the tokens of the msg.sender (the owner) and then tried to transferFrom function to transfer the tokens from the msg.sender to the contract. However, the first obstacle i faced was that the allowance is returned as zero when i called the transferFrom function. <strong>Now i was able to relearn that the transferFrom function should be another transaction for it to be able to work and i console loged all the variables making sure that the allowance is being changed when calling the approve function. However when i recall the transferFrom the error persists and shows me Insufficient balance!</strong></p>
<p>`
This is my deposit function where the transferFrom is called only if the approval was a success</p>
<pre><code>/**
     * @notice addEth is a user function where the user chooses the pool and sends eth to it, funding it
     * @param depositAmount is the eth being sent from the user to the pool
     * @param poolId_ is the address of the pool being chosen by the user
     */
    function deposit(uint256 depositAmount, uint256 poolId_) public{
        
        // Check if the pool is either closed or paused or exists
        Pool storage p = checkIfPoolExistsOrClosed(poolId_);

        // Make sure the eth being sent is not equal to zero
        if (depositAmount &lt;= 0) revert WrongAmount();

        // Check if the pool is empty, if it is the price of token is 1
        if(p.valueInPool == 0) {
            tokensForUser = depositAmount;
        }else {
            // Get the amount of tokens to be minted to the user
            tokensForUser = (depositAmount /
                (p.valueInPool/
                IProperSubsetERC20(p.poolTokenAddress).totalSupply()));
        }
        
        // check if the approval was a success
        if(!contractIsApproved[msg.sender]) revert ApprovalFailed();

        // Send the USDC tokens to the fund contract
        bool transfer  = IProperSubsetUSDC(usdcAddress).transferFrom(msg.sender, address(this), depositAmount);

        // Send the USDC tokens to the fund contract
        // (bool success,)=usdcAddress.delegatecall(abi.encodeWithSignature('transfer(address,uint256)', address(this), depositAmount));

        // Call the ERC20 contract to mint tokens to user
        IProperSubsetERC20(p.poolTokenAddress).mint(msg.sender, tokensForUser);

        // Update the amount of liquidity in the pool
        p.valueInPool = p.valueInPool + depositAmount;

        // Emit event after adding eth to pool
        emit Deposit(msg.sender, poolId_, depositAmount);
    }
</code></pre>
<p>This is my approval function where i call the approve function to add an allowance</p>
<pre><code>    /**
     * @notice function to approve contract to spend the user's USDC tokens
     * @param amount of usdt willing to give the contract approval for spending
     */
    function approveUser(uint256 amount) public returns(bool){

        // Approve spending the msg.sender tokens
        (bool success,) =    usdcAddress.delegatecall(abi.encodeWithSignature('approve(address,uint256)', address(this), amount));

        // If the approve function is succesfull we update the map to show that this address is approved
        if(success){
            contractIsApproved[msg.sender] = true;
        }
        // Return if the function is successfull
        return success;
    }
</code></pre>
<p>`</p>
<p>Now these are the tests where the approve and the transferFrom function are called</p>
<pre><code>it(&quot;Try approving for user 1 the transfer of their tokens from the contract&quot;, async function() {
      await deployFunds.connect(signers[1]).approveUser(1000);
    })

    it(&quot;Try depositing and the price of the pool tokens should be equal to one since it is new&quot;, async function() {
      const tx = await deployFunds.connect(signers[1]).deposit(1000, 2);
      const receipt = await tx.wait();
      
      filter = receipt.events?.filter((x) =&gt; {return x.event == &quot;Deposit&quot;});
      poolId = filter.length &gt; 0 ? filter[0].args[1] : '0x000';
      tokensForUser = filter.length &gt; 0 ? filter[0].args[2]: &quot;0&quot;;
      mintedTokens = await deployERC20.balanceOf(user1);
      expect(filter.length).above(0);
      expect(poolId).to.equal(2);
      expect(tokensForUser).to.equal(1000);
    })
</code></pre>
<p>I tried console logging all the variables being changed in the approve function and everything was checking out but when i console log the allowance when calling the transferFrom is is printed as zero. I then tried to put the approve function and the transferFrom in each transaction alone and still the error persists as Insufficient allowance</p>
",https://stackoverflow.com/questions/74591265/allowance-is-returned-zero-even-after-approval,"['solidity', 'smartcontracts', 'erc20']",259,True,1,1
Can you create a file that you can&#39;t access for unit testing to test for a permission error,"<p>I am in the process of creating a function that will loop over a large amount of files. However, the function will not have access to all of the files. I have added something to the main part of the function which catches the permission errors. However, I am wanting to create a unit test to test for that so I don't need to run it over the large amount of data.</p>
<p>for the unit test, I am currently using <code>pytest</code> and <code>tmpdir</code> to generate the temporary files and for unit testing. I am trying to make one of the files I generate result in a permission error but I can't figure out how. I have looked at using <code>os.chmod(file, ...)</code> but that can't change the permissions on the file to what I want.</p>
<p>Is there a way to make it so that the when I try to access the file I've made, it throws up a permission error? The section in the function that throws up the permission error is an <code>os.stat(file)</code> function.</p>
<p>Edit: In addition, the reason I may not be able to access the files is that they may be in directories that I cannot access. Is there a way to create fake temporary directories with files in but I don't have permission to access the files in the directory?</p>
",https://stackoverflow.com/questions/71175974/can-you-create-a-file-that-you-cant-access-for-unit-testing-to-test-for-a-permi,"['python', 'unit-testing']",263,False,1,0
XUnit - how to test a controller with a feature toggle,"<p>I have some sample c# code that demonstrates feature management in .net core.</p>
<p>I have this class that exposes an endpoint:</p>
<pre><code>namespace Widgets.Controllers
{
    [Authorize]       
    public class FeatureToggleSampleController : ControllerBase
    {

        private readonly IFeatureManagerSnapshot featureManager;

        public FeatureToggleSampleController(
                              IFeatureManagerSnapshot featureManager)
        {
            this.featureManager = featureManager;
        }

        [Route(&quot;toggles/demo&quot;)]
        [HttpGet]
        [FeatureGate(nameof(WidgetToggles.sampleToggleName))]
        public string ShowSampleToggle(MeFunctionsRequest request)
        {
              return &quot;sample toggle is enabled&quot;;

        }
    }
}
</code></pre>
<p>we are using a filter, to have the feature mana</p>
<pre><code>[FilterAlias(&quot;WidgetsFeatures&quot;)]
public class WidgetFeaturesFilter : IWidgetFeaturesFilter
    {
        private readonly IServiceScopeFactory scopeFactory;

        public WidgetFeaturesFilter(IServiceScopeFactory scopeFactory)
        {
            this.scopeFactory = scopeFactory;
        }

        public Task&lt;bool&gt; EvaluateAsync(FeatureFilterEvaluationContext context)
        {
            using var scope = scopeFactory.CreateScope();
            var featureRepo = scope.ServiceProvider.GetService&lt;IGenericRepository&lt;WidgetFeature&gt;&gt;();
            var feature = featureRepo.Retrieve(filter: &quot;[Name] = @FeatureName&quot;, filterParameters: new { context.FeatureName }).FirstOrDefault();
            return Task.FromResult(feature != null &amp;&amp; feature.Enabled);
        }
    }
</code></pre>
<p>In our startup, we add the service like this:</p>
<pre><code>services.AddFeatureManagement(Configuration.GetSection(&quot;FeatureManagement&quot;)).AddFeatureFilter&lt;WidgetsFeaturesFilter&gt;();
</code></pre>
<p>And, this is the json file where we define the toggles:</p>
<pre><code>{
  &quot;FeatureManagement&quot;: {
    &quot;sampleToggleName&quot;: {
      &quot;EnabledFor&quot;: [
        {
          &quot;Name&quot;: &quot;WidgetsFeatures&quot;
        }
      ]
    }
  }
}
</code></pre>
<p>When the bool is true in the database, hitting http://localhost/toggles/demo returns the &quot;sample toggle is enabled&quot; method message.  And when I change the value in the database to false, it 404s in the browser.  Everything seems to be working as far as the toggle logic itself.</p>
<p>Now I want to demo how to unit test controllers and other modules that use feature toggles.</p>
<p>So far I have written two unit test code based on a sample i found.  The first one works - although I'm not sure if it's because i've written the test correctly.  But gives me the string I'm looking for.</p>
<p>The second one fails because the mock is not working.  I've asked the mockFeatureManager to return false as far as the toggle status, but it still behaves as if the toggle is enabled.</p>
<pre><code>[Collection(&quot;UnitTests&quot;)]
public class FeatureToggleSampleControllerShould
{


    [Fact]
    public async void Return_String_If_Toggle_Enabled()
    {
        var mockFeatureManager = new Mock&lt;IFeatureManagerSnapshot&gt;();
        mockFeatureManager
            .Setup(x=&gt;x.IsEnabledAsync(nameof(WidgetsFeatureToggles.sampleToggleName)))
            .Returns(Task.FromResult(true));

        var featureManager = mockFeatureManager.Object;
        Assert.True(await featureManager.IsEnabledAsync(nameof(WidgetsFeatureToggles.sampleToggleName)));

        var sampleControler = new FeatureToggleSampleController(TestHelper.Appsettings,featureManager);
        Assert.Equal(&quot;sample toggle is enabled&quot;,sampleControler.ShowSampleToggle());
    }

    [Fact]
    public async void Return_404_If_Toggle_Enabled()
    {
        var mockFeatureManager = new Mock&lt;IFeatureManagerSnapshot&gt;();
        mockFeatureManager
            .Setup(x=&gt;x.IsEnabledAsync(nameof(WidgetsFeatureToggles.sampleToggleName)))
            .Returns(Task.FromResult(false));

        var featureManager = mockFeatureManager.Object;
        Assert.False(await featureManager.IsEnabledAsync(nameof(WidgetsFeatureToggles.sampleToggleName)));
        var sampleControler = new FeatureToggleSampleController(TestHelper.Appsettings,featureManager);
        try{
            sampleControler.ShowSampleToggle();
        } catch (Exception ex) {
            Assert.Contains(&quot;404&quot;,ex.Message);
        }
    }
}
</code></pre>
<p>I don't think the bug is with the actual code, but the unit test.
But any tips would be appreciated.</p>
<p><strong>EDIT 2</strong></p>
<p>This was the post I was using as an example:  <a href=""https://stackoverflow.com/questions/69269748/ifeaturemanager-unit-testing"">IFeatureManager Unit Testing</a></p>
<p>In my case, I'm not using azure ...</p>
",https://stackoverflow.com/questions/73531244/xunit-how-to-test-a-controller-with-a-feature-toggle,"['c#', 'visual-studio-code', 'moq', 'xunit', 'featuretoggle']",414,False,1,0
"Development, Staging and Production environments in serverless solutions (AWS)","<p>I have developed an API using flask + postgreSQL and the users registration process was ministered by such infrastructure. I then decided to change the infrastructure in general. I decided to use NestJS + dynamoDB + cognito. In other words, I decided to go serverless!
However, I am finding quite hard to understand how to organize my project into development, staging and production environments.</p>
<p>To sum up, I have two questions</p>
<hr />
<ol>
<li>How to perform unit testing in serverless environments?</li>
<li>How to create a  development mode for testing and developing features locally?</li>
</ol>
<hr />
<p>I will give an example for each question in order to clarify what my doubts are.</p>
<p><strong>Example for (1)</strong></p>
<p>In the first architecture using flask + postgreSQL I created a script that would wipe out the entire local database and create a mock data with the goal of executing functions so the API could be tested. But since I have no local environment, should I replicate the entire production environment in AWS in order to test it?</p>
<p><strong>Example for (2)</strong></p>
<p>Usually when I was testing new features in the API I would erase and create new mock data, and my coworkers would do the same in their local machines. In other words, each developer had their local system ready to be &quot;screwed&quot; haha without disturbing other developers' work.
How could I do something similar in dynamoDB / serveless architecture?</p>
",https://stackoverflow.com/questions/74468309/development-staging-and-production-environments-in-serverless-solutions-aws,"['amazon-web-services', 'amazon-dynamodb', 'serverless', 'aws-serverless']",112,True,1,1
How to Unit Test Azure EventHub with EventDataBatch and EventHubProducerClient,"<p>I have biz code that finds changes (candidates) in a DB and publishes (sends) them to azure event hub via EventHubProducerClient, but finding it very hard in unit tests that my candidates are publishing correctly when introducing EventDataBatch to work within the publishing limits.</p>
<p>I used to just mock the client and Stub out EventHubProducerClient's SendAsync capturing (actually i had a custom matcher, but effectively it's just capturing for purpose of comparing) the EventData's that were sent to make sure my candidates are going out correctly.</p>
<p>But when i hit 1M send event limits for my batch i wanted to leverage EventDataBatch to make sure i stay under the limit.  However i'm finding EventDataBatch rather frusturating as it's sealed and all it's interesting stuff (like getting to the events like AmqpProducer does <a href=""https://github.com/Azure/azure-sdk-for-net/blob/6011385c397ffa881d9d7e6bf8c448ad4ee47665/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpProducer.cs#L233"" rel=""nofollow noreferrer"">https://github.com/Azure/azure-sdk-for-net/blob/6011385c397ffa881d9d7e6bf8c448ad4ee47665/sdk/eventhub/Azure.Messaging.EventHubs/src/Amqp/AmqpProducer.cs#L233</a>) are internal methods...so short of verifying the count...there's really no much i can do outside of using reflection (which is what i've ended up doing).</p>
<p>Am i missing something here?  or was this just an oversite in v4 to v5 upgrade (where ToEnumerable() was dropped on EventDataBatch )</p>
<p>Closest i found was <a href=""https://stackoverflow.com/questions/67275134/eventhubproducerclient-unit-testing-in-c-sharp"">EventHubProducerClient unit testing in c#</a> but seems like the answer was skipping on the important nuance of EventDataBatch's unit testability problems.</p>
",https://stackoverflow.com/questions/73299792/how-to-unit-test-azure-eventhub-with-eventdatabatch-and-eventhubproducerclient,"['c#', 'azure', 'unit-testing', 'azure-eventhub']",857,True,0,1
C# Library class accessing a resource file,"<p>I recently made a API on AWS API Gateway. To make accessing it easier, I created a dev kit library to make accessing the Gateway methods easier (using .Net 6). To make getting the API URI's easier to access and store, I put all of the URI's into a json file in the library.</p>
<p>When doing unit testing on the library itself, everything passed. The library accesses the json file with the below code</p>
<pre><code>using (StreamReader reader = new StreamReader(Path.Combine(Directory.GetCurrentDirectory(), &quot;Resources\\config.json&quot;)))
            {
                json = reader.ReadToEnd();
            }
</code></pre>
<p>I published the library as a Nuget package and then installed it on a .Net web app. When the app tries calls a method from this dev kit, it throws the following error:</p>
<p>Message=Could not find a part of the path 'C:\Projects*ParentFolder**Subfolder**ProjectFolder*\Resources\config.json'</p>
<p>Which the file path given is the file path of the project, not the filepath that leads to the config.json file. So the question is, how do you structure the file path to access a file if it is in a library that is designed to be a stand alone library like a dev kit? Or is it just a bad idea and should I approach storing the URI's for the methods in a different manner?</p>
<p>FYI - the I do know the issue has nothing to do with the AWS API Gateway or Lambda functions. Those are running correctly and performing in a consistent manner.</p>
<p>TIA!</p>
",https://stackoverflow.com/questions/74147765/c-library-class-accessing-a-resource-file,"['c#', 'directory']",25,False,0,1
Jasmine-compatible TypeScript object equality library,"<p>Disclaimer: TypeScript (and more generally JavaScript) object equality functions have been discussed en-masse here (e.g., <a href=""https://stackoverflow.com/a/63496057"">https://stackoverflow.com/a/63496057</a>) and everywhere else (e.g., <a href=""https://bobbyhadz.com/blog/typescript-object-comparison"" rel=""nofollow noreferrer"">https://bobbyhadz.com/blog/typescript-object-comparison</a>).
I am <strong>not</strong> looking for any code snippets (there are more than enough in <a href=""https://stackoverflow.com/questions/201183"">How to determine equality for two JavaScript objects?</a>). There are various libraries (<a href=""https://www.npmjs.com/package/underscore"" rel=""nofollow noreferrer"">underscore</a>, <a href=""https://www.npmjs.com/package/lodash"" rel=""nofollow noreferrer"">lodash</a>, <a href=""https://www.npmjs.com/package/fast-deep-equal"" rel=""nofollow noreferrer"">fast-deep-equal</a>, <a href=""https://www.npmjs.com/package/fast-equals"" rel=""nofollow noreferrer"">fast-equal</a>, <a href=""https://www.npmjs.com/package/nano-equal"" rel=""nofollow noreferrer"">nano-equal</a>, etc.) for object equality checking, but it's hard to understand the differences between them.</p>
<p>What I miss in most questions and answers about TypeScript object equality is <strong>unit testing</strong>.<br />
Because the testing framework decides what should be considered &quot;equal&quot;.<br />
I use <em>Jasmine</em> for unit tests, thus the <a href=""https://jasmine.github.io/api/edge/matchers.html#toEqual"" rel=""nofollow noreferrer""><code>toEqual(…)</code></a> method governs object equality.</p>
<p>For example, <code>JSON.stringify(…)</code> is not consistent with Jasmine's <code>toEqual(…)</code> because <code>JSON.stringify(…)</code> is sensitive to property order:</p>
<pre class=""lang-js prettyprint-override""><code>JSON.stringify({a:1, b:2}) != JSON.stringify({b:2, a:1});

expect({a:1, b:2}).toEqual({b:2, a:1});
</code></pre>
<p>For <em>full consistency</em>, an equality check would have to yield the same result as Jasmine's <code>toEqual(…)</code> for every conceivable input.</p>
<p>I am aware that Jasmine supports <a href=""https://jasmine.github.io/tutorials/custom_equality"" rel=""nofollow noreferrer"">custom equality testers</a>, but these should only be used for special cases.</p>
<p>Question: Are any of the aforementioned equality libraries <strong>fully consistent</strong> with <a href=""https://jasmine.github.io/index.html"" rel=""nofollow noreferrer"">Jasmine</a>'s <code>toEqual(…)</code>?<br />
If none of them are, which are the edge cases that yield different results than Jasmine?</p>
<p><em>[Edit: Rephrased the question to avoid asking for subjective advice on off-site libraries; added two more equality libraries to the list; clarified what I mean by full consistency with Jasmine.]</em></p>
",https://stackoverflow.com/questions/73243125/jasmine-compatible-typescript-object-equality-library,"['javascript', 'typescript', 'jasmine', 'object-equality']",82,False,0,0
Trying to understand Xunit service test in tutorial,"<p>I have been following this <a href=""https://henriquesd.medium.com/creating-an-application-from-scratch-using-net-core-and-angular-part-6-76daa358db41"" rel=""nofollow noreferrer"">tutorial</a> and trying to understand this Xunit test for an update service.</p>
<p>The service is as follows:</p>
<pre><code>public async Task&lt;Category&gt; Update(Category category)
{
  if (_categoryRepository.Search(c =&gt; c.Name == category.Name &amp;&amp; c.Id != category.Id).Result.Any())
    return null;

  await _categoryRepository.Update(category);
  return category;
}
</code></pre>
<p>And the Xunit test:</p>
<pre><code>[Fact]
public async void Update_ShouldNotUpdateCategory_WhenCategoryDoesNotExist()
{
  var category = new Category()
  {
    Id = 1,
    Name = &quot;Test Category 1&quot;
  };

  var categoryList = new List&lt;Category&gt;()
  {
    new Category()
    {
        Id = 2,
        Name = &quot;Test Category 2&quot;
    }
  };

  _categoryRepositoryMock.Setup(c =&gt; c.Search(c =&gt; c.Name == category.Name &amp;&amp; c.Id != category.Id))
      .ReturnsAsync(categoryList);

  var result = await _categoryService.Update(category);

  Assert.Null(result);
}
</code></pre>
<p>I know that from this authors notes about what the test is supposed to do is contradicting what the method name's <em>when-condition</em> (It's about 3/4 the way the linked tutorial page):</p>
<ul>
<li>The method does not update a category when the updated category name already exists.</li>
</ul>
<p>The test is returning null, but I'm not sure if it's doing it for the right reason.</p>
<p>Is it that it can't find the category in the mock repo? As I tried adding a category in hopes that it would find the category and fail the test, but it still came back as null:</p>
<pre><code>new Category()
{
  Id = 1,
  Name = &quot;Test Category One&quot;
}
</code></pre>
<p>Or is it that the mocking of the validation which returns categoryListing and even though it is not the correct record (as it's name is not a match) enough to cause the null? (I'm guessing it is this one)</p>
<p>I am new to unit testing, but it doesn't feel like a good test shouldn't the mock repository be preloaded with records and then the updated record have it's validation tested against it? I'm guessing this would just be another way of doing this, however, how would I change the code to accomplish that?</p>
",https://stackoverflow.com/questions/72516488/trying-to-understand-xunit-service-test-in-tutorial,"['c#', 'unit-testing', 'moq', 'xunit.net']",167,True,0,1
Flutter tests: `throwsA` followed by `ensureInitialized() + returnsNormally` breaks the test,"<p>I'm unit testing a feature using Flutter tests and dividing tests by groups.
<br />
I've noticed that if I don't use <code>TestWidgetsFlutterBinding.ensureInitialized()</code> I get some error in the <code>fetchTripList</code> asynchronous method, so I wrote a test for it when FlutterBinding is not initialized (see the first group in the picture). It works fine as long as I do not initialize the FlutterBinding in the group <code>SetUp(...)</code>.
<br />
Then, in the next test group, I use the <code>ensureInitialized()</code> method so that <code>fetchTripList</code> returns normally. However, I get a TestFailure because it seems that FlutterBinding was not initialized... Moreover, subsequent similar tests that require FlutterBinding to be initialized succeed.</p>
<p>The &quot;Null check operator ...&quot; refers to an Exception thrown by <code>await rootBundle.loadString(...)</code> in the <code>fetchTripList</code> method.</p>
<p>Things I've tried:</p>
<ul>
<li>I've tried to comment out the first test group, and everything succeeded.</li>
<li>I've tried to move the first test group at the end of the test suite, but that failed because FlutterBinding was already (and permanently) initialized.</li>
<li>I've tried to remove the <code>late</code> + <code>setUp(...)</code> initialization in favor of a plain inline allocation/initialization, but nothing changed.</li>
</ul>
<p>At this point, I'm guessing different options:</p>
<ol>
<li><em>returnsNormally</em> should not be wrapped by an <code>await expectLater(...)</code></li>
<li>there is an alternative to <code>throwsA(...)</code> I could make use of</li>
<li>I should create a new file only for the first group (it's not something I'd like to do)</li>
</ol>
<p><a href=""https://i.stack.imgur.com/WLUe1.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/WLUe1.png"" alt=""Test suite screenshot"" /></a></p>
<p>Does anyone have an idea of what could be the issue or how to solve this riddle?</p>
",https://stackoverflow.com/questions/70612129/flutter-tests-throwsa-followed-by-ensureinitialized-returnsnormally-bre,"['flutter', 'dart', 'testing']",228,False,0,1
convert normal function to generator and keeping code structure,"<p>Generators are elegant and memory-efficient, so I'd like to convert normal functions producing sequences to generators. But I haven't found an easy conversion method, by <strong>easy</strong> I mean it is best to be done <strong>automatically</strong> by some tools, maybe simple as string or regex replacement(<code>return</code> to <code>yield</code>, for example). If the conversion cannot always be easy, refactoring may introduce bugs. Of course unit testing can capture some bugs, but if the normal function is already fully tested, I doubt the necessity writing extra tests for the generator.</p>
<p>Let me give an example, normal function <code>normalize</code> accepts a <code>src</code> parameter, if <code>src</code> is a <code>list</code>, then return the list, otherwise return one list with <code>src</code> as sigle item. Here for simplicity we suppose <code>src</code> is provided by the caller as either a <code>list</code> or a simple scalar.</p>
<h2>test</h2>
<pre class=""lang-py prettyprint-override""><code>f = normalize # replace with other conversions
assert list(f(2)) == [2]
assert list(f([1, 2])) == [1, 2]
</code></pre>
<h2>normal function</h2>
<pre class=""lang-py prettyprint-override""><code>def normalize(src):
    if isinstance(src, list):
        return src
    return [src]
</code></pre>
<p>Now I convert it to generator, adding one <code>else</code> block, test passes:</p>
<h2>generator which introducs new code blocks</h2>
<pre class=""lang-py prettyprint-override""><code>def normalize_generator(src):
    if isinstance(src, list):
        for x in src:
            yield x
    else:
        yield src
</code></pre>
<p>What I want is keeping the code structure of <code>normalize</code>, only replacing some keywords, like following, of course test will fail.</p>
<h2>generator keeping code structure, test fails:</h2>
<pre class=""lang-py prettyprint-override""><code>def normalize_generator_no_else(src):
    if isinstance(src, list):
        for x in src:
            yield x
    yield src
</code></pre>
<blockquote>
<p>test result fail: left is [1, 2, [1, 2]], right is [1, 2]</p>
</blockquote>
<p>I basically understand this behaviour, it seems <code>yield</code> continues code in following lines. I've searched and found <a href=""https://stackoverflow.com/questions/3276528/does-python-yield-imply-continue"">similar question Does python yield imply continue?</a> but I haven't found a solution to my question.</p>
",https://stackoverflow.com/questions/74104878/convert-normal-function-to-generator-and-keeping-code-structure,"['python', 'generator', 'yield']",42,True,0,1
Multiple tests fail when ran on Jenkins after migration,"<p>I recently migrated a Unit Testing suite to Junit 5.8.2 and Mockito 4.5.1 + Mockito Inline to allow static mocking. Powermock was removed.</p>
<p>2000+ tests were migrated and they all run successfully when ran inside the IDE (IntelliJ). Both with the IDEA and Gradle runner.</p>
<p>However, when Jenkins attempts to run them there are over 900 failed tests. Some of the exceptions thrown.</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);
</code></pre>
<pre><code>org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Boolean cannot be returned by someMethod()
someMethod() should return Date`
</code></pre>
<p>I understand what causes these errors as I've seen them multiple times during the migration so this is not a duplicate asking for the solution.(Unless there's something different with the Jenkins environment) The code that throws such exceptions should not be throwing them. And it does not in the IDE. It's thrown exclusively in Jenkins.</p>
<p>An additional exception which I have never seen before is thrown as well.</p>
<pre><code>org.mockito.exceptions.misusing.UnfinishedMockingSessionException: 
Unfinished mocking session detected.
Previous MockitoSession was not concluded with 'finishMocking()'.
For examples of correct usage see javadoc for MockitoSession class.
</code></pre>
<p>Most of the exceptions are of this type.
However, the MockitoSession inteface is not used anywhere in the test suite. All mocks are initialized with <code>@ExtendWith(MockitoExtension.class)</code></p>
<p>I have no idea what could be causing this.</p>
<p>Jenkins is running the same versions of Java/Junit/Mockito/Spring as the code in the IDE.
It seems clear to me that the different environments are causing the issue. However, what could be the difference and how would I go about finding it?</p>
<p>I attempted to reproduce the results locally but was unable to. Any ideas towards that are also welcome.</p>
",https://stackoverflow.com/questions/73623109/multiple-tests-fail-when-ran-on-jenkins-after-migration,"['java', 'unit-testing', 'jenkins', 'mockito', 'junit5']",268,True,0,1
Why is Singleton bad for unit tests?,"<p>I'm currently delving into the discussion about Singleton yes or no, and it seems that one of the main criticism about singleton is that it's hard to unit test applications that use singleton, and I'm trying to figure out why.</p>
<p>I want to refer to  this thread:
<a href=""https://stackoverflow.com/questions/25273210/why-is-a-singleton-class-hard-to-test"">Why is a singleton class hard to test?</a></p>
<p>In short, the accepted answer there explains that when you have a class <code>OtherClass</code> that uses a singleton class <code>MySingleton</code>, and say that the Singleton class's methods does something like write to a file, connect to a database, etc. you don't want to do these things in unit tests, you want to mock out that object.</p>
<p>So instead of singleton, you can use Dependency Injection. We want to have a <code>MyNonSingleton</code> class that implements some interface, to instantiate and object of it, and pass it in the ctor of <code>OtherClass</code>. This way, in unit tests, we can mock the <code>MyNonSingleton</code> with a mock class that implements the interface.</p>
<p>Now my question: Assuming that when unit testing, we have a separate application in which we use the tested-out class, I don't understand what is the difference between the 2 approaches? With <code>MySingleton</code> - you can provide a mock implementation of <code>MySingleton</code> exactly as you would provide a mock implementation that implements the same  interface that <code>MyNonSingleton</code> implements, so why is singleton bad for unit tests?</p>
",https://stackoverflow.com/questions/71668747/why-is-singleton-bad-for-unit-tests,"['c++', 'singleton']",554,False,0,0
How do I debug why xcode won&#39;t run my unit tests?,"<p>I recently started working on an old ios app which doesn't have unit tests. I am not an ios developer myself. Due to circumstances I feel compelled to start writing unit tests.</p>
<p>App has multiple dependencies added using cocoapods. One of them is a framework which we maintain ourselves.</p>
<p>I am trying to run the dummy testExample that is auto-generated while creating a project. It doesn't have any code.
When I run the test xcode builds &amp; installs the app. App shows the splash screen. But after that nothing happens.
I also tried running the test from command line in case it would print any errors. But it shows
<code>Testing started for configuration 'Configuration 1'</code>
and stops.</p>
<p>I have tried all the remedies I could find on stackoverflow and apple's forum. Typical ios project troubleshooting like deleting folders, etc. have also been tried. I am completely stuck without any error message.</p>
<p>I tried running the dummy test in a newly created project on the same xcode &amp; device and it ran.</p>
<p>How can I debug this issue? Is something in the app code stopping the unit tests from running. How can I make sure that all the right checkboxes are checked and the build configs all correct? Is there a comprehensive list somewhere of steps required to set up unit testing?</p>
<p>Xcode version - 13.4.1 Test device - iphone 11, ios version 15.6</p>
",https://stackoverflow.com/questions/73467916/how-do-i-debug-why-xcode-wont-run-my-unit-tests,"['ios', 'xcode', 'unit-testing']",248,False,0,0
Single Unit Test Takes ~40-50ms But 10 Copies Majority Takes Less Than 1ms,"<p><a href=""https://i.stack.imgur.com/RAmyG.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/RAmyG.png"" alt=""enter image description here"" /></a></p>
<p>Fixture</p>
<pre><code>    public class AllFixture : IDisposable
    {
        public AllFixture()
        {
            var mappingConfig = new MapperConfiguration(mc =&gt; { mc.AddProfile(new UserStoryProfile()); });
            var mapper = mappingConfig.CreateMapper();

            List&lt;UserStory&gt; userStories = new()
            {
                new UserStory
                {
                    UserStoryId = 1,
                    Title = &quot;One&quot;,
                    Content = &quot;User story one.&quot;
                },
                new UserStory
                {
                    UserStoryId = 2,
                    Title = &quot;Two&quot;,
                    Content = &quot;User story two.&quot;
                }
            };

            Repository = new Mock&lt;IUserStoryRepository&gt;();
            Repository.Setup(x =&gt; x.GetUserStories()).Returns(userStories);
            Controller = new UserStoriesController(Repository.Object, mapper);
        }

        public Mock&lt;IUserStoryRepository&gt; Repository { get; set; }
        public UserStoriesController Controller { get; set; }

        public void Dispose()
        {

        }
    };
</code></pre>
<p>Test</p>
<pre><code>    [Collection(&quot;Controller Collection&quot;)]
    public class ControllerTestSuite
    {
        private readonly AllFixture _allFixture;

        public ControllerTestSuite(AllFixture allFixture)
        {
            this._allFixture = allFixture;
        }

        [Fact]
        public void Controller_GetUserStories_Returns_Ok1()
        {


            // Arrange
            //IUserStoryRepository rpo = _allFixture.Repository.Object;
            UserStoriesController ctr = _allFixture.Controller;

            // Act
            IActionResult result = ctr.GetUserStories();
            var items = result as OkObjectResult;

            var i = items.Value as List&lt;UserStory&gt;;

            // Assert
            Assert.NotNull(result);
            Assert.NotNull(items);
            
        }
</code></pre>
<p>Tests 1 through 10 as shown in the screenshot are all <em>identical</em> code.  The number at the end of each test name is just to prevent test name clash errors; there is no distinction in code between each test.</p>
<p>Why then, if I run <em>one</em> test by itself do I see a duration of ~40-50ms but if I copy/paste 10 of these and run all 10 at once do I see majority durations of less than 1ms?</p>
<p>In many runs of all 10 tests there is <em>always</em> one test that takes ~40-50ms to run, and this skews the overall run time of these tests.</p>
<p>I'm running Visual Studio 2022 Enterprise (Live Unit Testing disabled), xUnit, .NET 6 with the following CPU and Memory:</p>
<p><a href=""https://i.stack.imgur.com/zXo9d.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/zXo9d.png"" alt=""enter image description here"" /></a></p>
<p><a href=""https://i.stack.imgur.com/xahVW.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/xahVW.png"" alt=""enter image description here"" /></a></p>
<p>Also tests are set to run in parallel.  Can someone please explain to me what's going on to cause this?  Thanks!</p>
<p><a href=""https://i.stack.imgur.com/siR1O.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/siR1O.png"" alt=""enter image description here"" /></a></p>
<p>Well these profiler times don't make sense to me when compared to the duration reported in Test Explorer.  The one I have highlighted for example took more than 1 millisecond but less than the 39ms and then there is the 265ms time on that same line.  All times in Test Explorer were either under 1ms or that 39ms.  How much should I rely on Test Explorer duration times?</p>
<p>Jason</p>
",https://stackoverflow.com/questions/70546646/single-unit-test-takes-40-50ms-but-10-copies-majority-takes-less-than-1ms,"['c#', 'visual-studio', 'unit-testing', '.net-core', 'xunit']",92,False,0,0
Emulator Unit Test Fails Saying &quot;Unable to establish connection on channel&quot;,"<p>I use <a href=""https://pub.dev/packages/get_it"" rel=""nofollow noreferrer"">get_it</a> for simple dependency injection. I have a function that I made sure is called when the app initializes as below:</p>
<pre class=""lang-dart prettyprint-override""><code>void initDI() {
  // ... the other providers and repositories ...

  //--------- //
  // Firebase //
  //--------- //
  // i reference these instances everywhere when i wanna access them
  // such as providers, repositories, etc.
  GetIt.I.registerLazySingleton&lt;FirebaseAuth&gt;(() =&gt; FirebaseAuth.instance);
  GetIt.I.registerLazySingleton&lt;FirebaseFirestore&gt;(
    () =&gt; FirebaseFirestore.instance,
  );
  GetIt.I.registerLazySingleton&lt;FirebaseFunctions&gt;(
    () =&gt; FirebaseFunctions.instance,
  );
}
</code></pre>
<p>In my <code>test</code> directory, I have a file named <code>initializers.dart</code>, which has setup functions for tests for convenience. One that concerns us is as follows:</p>
<pre class=""lang-dart prettyprint-override""><code>// test/initializers.dart

Future&lt;void&gt; initFirebaseEmulatorUse() async {
  // ensure widget bindings get initialized because firebase requires this for some reason
  WidgetsFlutterBinding.ensureInitialized();
  // initialize firebase app
  await Firebase.initializeApp();
  // use functions emulator because there is no mock or fake package for functions, which is reasonable
  FirebaseFunctions.instance.useFunctionsEmulator('localhost', 5001);

  // unregister default references
  GetIt.I.unregister&lt;FirebaseAuth&gt;();
  GetIt.I.unregister&lt;FirebaseFirestore&gt;();

  // register with mocks and fakes
  GetIt.I.registerLazySingleton&lt;FirebaseAuth&gt;(() =&gt; MockFirebaseAuth());
  GetIt.I.registerLazySingleton&lt;FirebaseFirestore&gt;(
    () =&gt; FakeFirebaseFirestore(),
  );
}
</code></pre>
<p>And, an example test is as follows:</p>
<pre class=""lang-dart prettyprint-override""><code>// import initializers, we'll need them
import '../initializers.dart';

void main() {
  // use in setUpAll, once and for all
  late FirebaseFirestore firebaseFirestore;

  setUpAll(() {
    // returning future here because i've seen setUpAll must return
    // an instance of Future when it has to do something in the future
    // so, marking it as async is not enough it seems
    return Future(() async {
      WidgetsFlutterBinding.ensureInitialized(); // just to be double sure
      initDI();
      await initFirebaseEmulatorUse();
      firebaseFirestore = GetIt.I.get(); // get an instance of firestore
    });
  });

  tearDownAll(() {
    return Future(() async {
      // ... do something to clear all documents in firestore? ...
      // ... so it won't affect other tests? ...
      // i need to access `firebaseFirestore` instance here to do it
    });
  });

  test('do tests', () async {
    // ... test stuff ...
  });
}
</code></pre>
<p>However, this fails saying:</p>
<pre><code>PlatformException(channel-error, Unable to establish connection on channel., null, null)
FirebaseCoreHostApi.initializeCore
✖ (setUpAll)
LateInitializationError: Local 'firebaseFirestore' has not been initialized.
dart:_internal                                        LateError._throwLocalNotInitialized
main.&lt;fn&gt;.&lt;fn&gt;
===== asynchronous gap ===========================
dart:async                                            new Future
main.&lt;fn&gt;

✖ (tearDownAll)
Exited (1)
</code></pre>
<p>When I go to the line where it throws this error, it actually throws <em>in the <code>tearDownAll</code></em>.</p>
<p>Troubleshooting for a while, I think we've got two problems:</p>
<ul>
<li><code>firebaseFirestore</code> is not initialized while in <code>tearDownAll</code>. While I have it initialized in <code>setUpAll</code>, that probably means the <code>Future</code> I return from <code>setUpAll</code> does not finish fast enough until I reach <code>tearDownAll</code>. That's my guess.</li>
<li>That &quot;Unable to establish connection on channel&quot; message is, I believe, because somehow the Firebase cannot connect to my local emulator.</li>
</ul>
<p>I've been trying to solve these with different methods for hours but couldn't find a way to solve it. Any blog post about setting up Firebase Emulator + Unit Testing is also appreciated. The posts that I've found so far couldn't get me figure out how I can connect to my local Firebase emulator. Thanks in advance.</p>
<hr />
<h1>Environment</h1>
<ul>
<li>Firebase Tools 11.19.0</li>
<li>get_it: ^7.2.0</li>
<li>firebase_core: ^2.3.0</li>
<li>firebase_auth: ^4.1.3</li>
<li>cloud_firestore: ^4.1.0</li>
<li>firebase_crashlytics: ^3.0.6</li>
<li>cloud_functions: ^4.0.5</li>
<li>firebase_analytics: ^10.0.6</li>
<li>fake_cloud_firestore: ^2.1.0 as dev</li>
<li>firebase_auth_mocks: ^0.9.2 as dev</li>
</ul>
<h2>Flutter Doctor</h2>
<pre><code>[✓] Flutter (Channel stable, 3.3.9, on Fedora Linux 36 (KDE Plasma) 6.0.14-200.fc36.x86_64, locale en_US.UTF-8)
    • Flutter version 3.3.9 on channel stable at /home/erayerdin/.local/lib/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision b8f7f1f986 (4 weeks ago), 2022-11-23 06:43:51 +0900
    • Engine revision 8f2221fbef
    • Dart version 2.18.5
    • DevTools version 2.15.0

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
    • Android SDK at /home/erayerdin/.sdks/android/
    • Platform android-33, build-tools 33.0.0
    • ANDROID_SDK_ROOT = /home/erayerdin/.sdks/android
    • Java binary at: /var/lib/snapd/snap/android-studio/125/android-studio/jre/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
    • All Android licenses accepted.

[✓] Chrome - develop for the web
    • Chrome at google-chrome

[✓] Linux toolchain - develop for Linux desktop
    • clang version 14.0.5 (Fedora 14.0.5-2.fc36)
    • cmake version 3.25.1
    • ninja version 1.10.2
    • pkg-config version 1.8.0

[✓] Android Studio (version 2021.3)
    • Android Studio at /var/lib/snapd/snap/android-studio/125/android-studio
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

[✓] VS Code
    • VS Code at /snap/code/current
    • Flutter extension version 3.56.0

[✓] Connected device (2 available)
    • Linux (desktop) • linux  • linux-x64      • Fedora Linux 36 (KDE Plasma) 6.0.14-200.fc36.x86_64
    • Chrome (web)    • chrome • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
</code></pre>
",https://stackoverflow.com/questions/74904111/emulator-unit-test-fails-saying-unable-to-establish-connection-on-channel,"['flutter', 'firebase', 'unit-testing', 'dart']",68,False,0,0
How to input generic objects from unit test to C# .NET 6 minimal web API setup? Or get test server working without minimal code?,"<p>I'm trying to update how the company I work in initialize ASP.NET web apps and web APIs. First of all, because in our older 3.1 .NET Core setup we have no way to access a test server, and have to run integration tests through a socket on localhost, but also to try and keep our code more up to date.</p>
<p>Being blocked by the new magic of minimal APIs I've tried to search for how to NOT use minimal APIs, but haven't found anything that have helped me define my own Program.cs and put the code there in a way that make a test server available for unit tests.</p>
<p>I've used docs to set up a unit test using a test server, but when unit testing, I want to be able to create instances of objects in unit tests and supply everything I want into app init code in Program.cs. I want to be able to specify what command line arguments to use for the test. I want to be able to set a flag that makes the normal app init skip doing something. When I want to supply a mock/stub, I don't want the one running in production to be created first and then replaced.</p>
<p>The .NET 6 minimal code feature looks to me like an anti-feature. Why introduce new parser complexities, magic, automatic class generation and sacrifice (or obfuscate) flexibility with unit testing, just to make hello world applications save a few lines of code?</p>
<p>Some stuff that I have tested:</p>
<ul>
<li>Creating a partial Program.cs implementation doesn't work, as Program.cs can't access those members for some reason.</li>
<li>There is no &quot;this.&quot; I can use in magic Program.cs parts either. I guess the magic Program.cs exports into static contexts or hide the instance.</li>
<li>There is no member in the auto-generated Program class that I've found where I can insert something on creation. I've tried to misuse services to inject stuff, but they are not available prior to &quot;var app = builder.Build();&quot; statement which is too late.</li>
<li>If I try to debug and look into implementation of the magic Program class I'm just thrown into my minimal code which hides the details..</li>
</ul>
<p>A static variable works, but that makes us unable to run multiple unit tests in parallel. I was hoping for a workaround by creating a static dictionary of dictionaries, and be able to send through a string key for the app to use to lookup it's test bits I want to inject, but even just passing that string key I haven't found a way to do yet, and having to implement this to begin with sounds horrible.</p>
<p>Some talk about app config files, but I want to be able to control this in code in unit tests and not in files, which is just a more horrific way of using static bits.</p>
<p>How are unit tests supposed to input a test context as input to Program.cs execution?</p>
",https://stackoverflow.com/questions/73374677/how-to-input-generic-objects-from-unit-test-to-c-net-6-minimal-web-api-setup,"['.net', 'unit-testing', '.net-6.0', 'minimal-apis', 'asp.net-core-minimal-hosting-model']",339,True,0,2
How to initialize a Postgresql database in a Flask app with SQLAlchemy,"<p>The <a href=""https://flask.palletsprojects.com/en/2.0.x/patterns/sqlalchemy/"" rel=""nofollow noreferrer"">Flask tutorial</a> (and many <a href=""https://stackabuse.com/using-sqlalchemy-with-flask-and-postgresql/"" rel=""nofollow noreferrer"">other tutorials</a> <a href=""https://realpython.com/flask-by-example-part-2-postgres-sqlalchemy-and-alembic/"" rel=""nofollow noreferrer"">out there</a>) suggests that the <code>engine</code>, the <code>db_session</code> and the <code>Base</code> (an instance of <code>declarative_metadata</code>) are all created at import-time.</p>
<p>This creates some problems, one being, that the URI of the DB is hardcoded in the code and evaluated only once.
One solution is to wrap these calls in functions that accept the <code>app</code> as a parameter, which is what I've done. Mind you - each call caches the result in <code>app.config</code>:</p>
<pre><code>def get_engine(app):                                                                           
    &quot;&quot;&quot;Return the engine connected to the database URI in the config file.
    Store it in the config for later use.
    &quot;&quot;&quot;
    engine = app.config.setdefault(
        'DB_ENGINE', create_engine(app.config['DATABASE_URI'](), echo=True))
    return engine                                                                              
                                                                                               
def get_session(app):                                                                          
    &quot;&quot;&quot;Return the DB session for the database in use
    Store it in the config for later use.
    &quot;&quot;&quot;                          
    engine = get_engine(app)
    db_session = app.config.setdefault(
        'DB_SESSION', scoped_session(sessionmaker(
            autocommit=False, autoflush=False, bind=engine)))
    return db_session
                                                                                               
def get_base(app):                     
    &quot;&quot;&quot;Return the declarative base to use in DB models.
    Store it in the config for later use.
    &quot;&quot;&quot;                                                                                        
    Base = app.config.setdefault('DB_BASE', declarative_base())
    Base.query = get_session(app).query_property()
    return Base                                
</code></pre>
<p>In <code>init_db</code>, I call all those functions, but there's still code smell:</p>
<pre><code>def init_db(app):
    &quot;&quot;&quot;Initialise the database&quot;&quot;&quot;
    create_db(app)
    engine = get_engine(app)
    db_session = get_session(app)
    base = get_base(app)

    if not app.config['TESTING']:
        import flaskr.models
    else:
        if 'flaskr.models' not in sys.modules:
            import flaskr.models
        else:
            import flaskr.models
            importlib.reload(flaskr.models)

    base.metadata.create_all(bind=engine)
</code></pre>
<p>The smell is of course the hoops I have to go through to import and create all models.
The reason for the code above is that, when unit testing, <code>init_db</code> is called once for each test (in <code>setup()</code>, as <a href=""https://flask.palletsprojects.com/en/2.0.x/tutorial/tests/"" rel=""nofollow noreferrer"">suggested in the same tutorial</a>), but the import will only be performed the first time, and <code>create_all</code> will therefore work only that time.</p>
<p>Not only that, now with a session shared for the duration of the app, I have problems in parametrized negative unit tests (that is, parametrized unit tests that expect some sort of failures): the first instance of the test will trigger a failure (e.g. login failure, see <a href=""https://flask.palletsprojects.com/en/2.0.x/tutorial/tests/"" rel=""nofollow noreferrer""><code>test_login_validate_input</code> in the tutorial</a>) and exit correctly, while all subsequent will bail out early because the <code>db_session</code> should be rolled back first. Clearly there's something wrong with the DB initialization.</p>
<p>What is the Right Way(TM) to initialize the database?</p>
",https://stackoverflow.com/questions/70684400/how-to-initialize-a-postgresql-database-in-a-flask-app-with-sqlalchemy,"['python', 'postgresql', 'flask', 'sqlalchemy']",619,True,0,1
Can I instantiate an object inside the class that it was passed into (as a parameter)?,"<p>I have a Dashboard component, inside which I want to display multiple Charts (these charts can be line charts, bubble charts, you name it). For this example, I want to display a LineChart. You can see LineChart being passed in as the chartType value.</p>
<pre><code>import React from 'react';
import Chart from './Chart';
import LineChart from '../LineChart';

const Dashboard = function () {

  return (
    &lt;div&gt;
      &lt;Chart chartType={LineChart} /&gt;
    &lt;/div&gt;
  );
};
</code></pre>
<p>Chart acts like a generic wrapper, all it does is handle rendering, it shouldn't matter what chartType it is given as a parameter. If a LineChart obj is passed into it, it should render the LineChart component, if a ScatterChart obj then the ScatterChart component.</p>
<pre><code>class Chart extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      data: [],
    };
    this.ref = React.createRef();
    
    this.myChartObj = new LineChart(props); // I DONT WANT THIS AS IT IS HARDCODING THE LINE CHART TYPE
    // this.myChartObj = new props.chartType(props); // DOESNT WORK
  }

  componentDidMount() {
    this.myChartObj.create(this.ref.current);
  }

  componentDidUpdate() {
    this.myChartObj.update(this.ref.current);
  }

  render() {
    return (
      &lt;div ref={this.ref} role=&quot;graphics-datachart&quot; /&gt;
    );
  }
}
</code></pre>
<p>So <strong>I'm wondering how to instantiate a new LineChart object inside Chart's constructor</strong> by using the ChartType param. As you can see in the code, it's currently hardcoded with <code>this.chartObj = new LineChart(props);</code> Ideally, the solution would be something like this: <code>this.chartObj = new props.chartType(props);</code> because there's no hardcoding but it doesn't work and throws <em>A constructor name should not start with a lowercase letter</em> error.</p>
<p>Could anyone assist? Surely it should be OK to pass a class as a parameter and later use that parameter value to instantiate a new object of that class..? Any help would be greatly appreciated, thank you!</p>
<p>Edit: I'm aware that the error is being generated by my linter, but the question still stands as to how I instantiate an obj from a parameter. I'm getting a similar error in unit testing, which means that simply silencing my linter won't fit anything: <code>TypeError: props.chartType is not a constructor</code></p>
<p><a href=""https://i.stack.imgur.com/9AIvG.png"" rel=""nofollow noreferrer"">Unit test results*</a></p>
<p>note: I'm using &quot;chartType&quot; in the stack question but its equivalent to d3Chart in screenshot</p>
",https://stackoverflow.com/questions/70757302/can-i-instantiate-an-object-inside-the-class-that-it-was-passed-into-as-a-param,"['javascript', 'reactjs']",38,False,2,0
What is Babel&#39;s purpose in relation to Jest?,"<p>I have an API project where I've been successfully using Jest (<code>v26.x</code> because code coverage doesn't work with <code>v27.x</code> on Windows 10 for me) for unit testing. I've run into a situation where I'm trying to achieve sufficient code coverage on a module I'm testing, but not all functions in that module have been exported, so this is impeding my ability to achieve this.</p>
<p>I came across the NPM package <code>rewire</code>, which worked beautifully, as it allowed me to mock any functions I wanted. The only problem is that code coverage doesn't acknowledge the lines tested via <code>rewire</code> and the devs in the Jest GitHub said they don't plan to support this.</p>
<p>So then I saw a couple of  posts that people were successfully using <code>babel-plugin-rewire</code> to achieve the same thing as <code>rewire</code>, but that code coverage lines were successfully being acknowledged with this package. However, I cannot get this setup to work.</p>
<p>I think I understand the basics of Babel, as it pertains to browsers. It will take newer JS code and transpile/polyfill so that older JS code is generated that will work with older browsers of your choice.</p>
<p>But then I started seeing stuff about <code>babel-jest</code> and Babel being integrated into Jest and so on. Aside from the fact that I can't get <code>babel-plugin-rewire</code> to work, I feel like I don't even understand the basics of how Babel and Jest work together, or why Jest needs Babel.</p>
<p>What is the relationship between Babel and Jest?</p>
",https://stackoverflow.com/questions/71532211/what-is-babels-purpose-in-relation-to-jest,"['javascript', 'unit-testing', 'jestjs', 'babeljs', 'babel-jest']",375,False,1,0
How to Build Mutlipart Http Request with Serialized XML and PDF Attachment?,"<p>I am attempting to build an Http Request for a Post call to an API. The API documentation states I should send a content type of:</p>
<blockquote>
<p>multipart/mixed;type=&quot;text/xml&quot;;boundary=&quot;MIME-Boundary&quot;</p>
</blockquote>
<p>It provides this example (redacted for length):</p>
<blockquote>
<p>--MIME-Boundary<br />
Content-Type: Application/XML<br />
Content-Location: RN-Service-Content<br />
Content-ID: pidxv10_invoice_xml</p>
<p>[xml content redacted]</p>
<p>--MIME-Boundary<br />
Content-Type: application/pdf<br />
Content-Transfer-Encoding: base64<br />
Content-ID: Attachment1</p>
<p>[pdf base 64 content redacted]</p>
<p>--MIME-Boundary--</p>
</blockquote>
<p>I stumbled upon the class MultiPartFormDataContent. I feel like this has gotten me close but I don't know if this is correct. If it is the class I should use I'm uncertain how to use it to match the provided example. I'm unit testing this code:</p>
<pre><code>        public HttpRequestMessage BuildRequest(Models.InvoiceDTO invoiceDto, string pdfPath)
        {
            Invoice openInvoice = invoiceDto.MapOpenInvoiceData();
            string serializedInvoice = openInvoice.Serialize();

            string base64PDF = ConvertPdfFile(pdfPath);

            MultipartFormDataContent formData = BuildContent(serializedInvoice, base64PDF);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, apiSettings.EndpointURL)
            {
                Content = formData
            };

            return request;
        }

        public string ConvertPdfFile(string filePath)
        {
            Byte[] bytes = File.ReadAllBytes(filePath);
            return Convert.ToBase64String(bytes);
        }

        public MultipartFormDataContent BuildContent(string serializedInvoice, string base64PDF)
        {
            MultipartFormDataContent formData = new MultipartFormDataContent();
            formData.Headers.Add(&quot;Content-ID&quot;, &quot;Attachment1&quot;);
            formData.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(&quot;application/pdf&quot;);
            
            formData.Add(new StringContent(base64PDF));
            formData.Add(new StringContent(serializedInvoice, Encoding.UTF8, &quot;application/pidx.v10+xml&quot;));

            return formData;
        }
</code></pre>
<p>For the sake of visualizing what I have I am executing request.Content.ReadAsStringAsync().Result in a test harness. When I do that I get:</p>
<blockquote>
<p>--df45d3bb-617f-44c3-8aa4-b0f1411571bc<br />
Content-Type: text/plain; charset=utf-8<br />
Content-Disposition: form-data</p>
<p>[pdf content redacted]<br />
--df45d3bb-617f-44c3-8aa4-b0f1411571bc<br />
Content-Type: application/pidx.v10+xml; charset=utf-8<br />
Content-Disposition: form-data</p>
<p>[xml content redacted]<br />
--df45d3bb-617f-44c3-8aa4-b0f1411571bc--</p>
</blockquote>
<p>I have a GUID where the example has the text --MIME Boundary. Is &quot;--MIME Boundary&quot; supposed to be in my content or is this MIME Boundary an example placeholder?</p>
<p>For both the PDF and XML content, how do I set their respective properties for Content ID, Content Location, Content Transfer Encoding?</p>
",https://stackoverflow.com/questions/70935446/how-to-build-mutlipart-http-request-with-serialized-xml-and-pdf-attachment,"['c#', 'dotnet-httpclient']",186,False,1,0
Vue 2 Coverage issue : Getting different behaviour for vue 2 and vue 3,"<p>I have setup unit testing using installation instructions from <a href=""https://v1.test-utils.vuejs.org/"" rel=""nofollow noreferrer"">https://v1.test-utils.vuejs.org/</a></p>
<p>Tests are running properly. But the coverage is coming incorrectly.</p>
<p>It's not showing coverage for all the lines. It shows coverage in the first line and doesn't show coverage anywhere else. Don't know what's the issue is here.</p>
<p>This is not working with Vue 2. But with Vue 3 its working.</p>
<p>Package:
{
&quot;name&quot;: &quot;vue_three_without_ts&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;core-js&quot;: &quot;^3.8.3&quot;,
&quot;vue&quot;: &quot;^3.2.13&quot;
},
&quot;devDependencies&quot;: {
&quot;@babel/core&quot;: &quot;^7.12.16&quot;,
&quot;@babel/eslint-parser&quot;: &quot;^7.12.16&quot;,
&quot;@vue/cli-plugin-babel&quot;: &quot;~5.0.0&quot;,
&quot;@vue/cli-plugin-eslint&quot;: &quot;~5.0.0&quot;,
&quot;@vue/cli-plugin-unit-jest&quot;: &quot;~5.0.0&quot;,
&quot;@vue/cli-service&quot;: &quot;~5.0.0&quot;,
&quot;@vue/test-utils&quot;: &quot;^2.0.0-0&quot;,
&quot;@vue/vue3-jest&quot;: &quot;^27.0.0-alpha.1&quot;,
&quot;babel-jest&quot;: &quot;^27.0.6&quot;,
&quot;eslint&quot;: &quot;^7.32.0&quot;,
&quot;eslint-plugin-vue&quot;: &quot;^8.0.3&quot;,
&quot;jest&quot;: &quot;^27.0.5&quot;
}
}</p>
<p><a href=""https://i.stack.imgur.com/7UiOd.png"" rel=""nofollow noreferrer"">Vue3</a></p>
<p>package:
{
&quot;name&quot;: &quot;vue_two_without_ts&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;core-js&quot;: &quot;^3.8.3&quot;,
&quot;vue&quot;: &quot;^2.6.14&quot;
},
&quot;devDependencies&quot;: {
&quot;@babel/core&quot;: &quot;^7.12.16&quot;,
&quot;@babel/eslint-parser&quot;: &quot;^7.12.16&quot;,
&quot;@vue/cli-plugin-babel&quot;: &quot;~5.0.0&quot;,
&quot;@vue/cli-plugin-eslint&quot;: &quot;~5.0.0&quot;,
&quot;@vue/cli-plugin-unit-jest&quot;: &quot;~5.0.0&quot;,
&quot;@vue/cli-service&quot;: &quot;~5.0.0&quot;,
&quot;@vue/test-utils&quot;: &quot;^1.1.3&quot;,
&quot;@vue/vue2-jest&quot;: &quot;^27.0.0-alpha.2&quot;,
&quot;babel-jest&quot;: &quot;^27.0.6&quot;,
&quot;eslint&quot;: &quot;^7.32.0&quot;,
&quot;eslint-plugin-vue&quot;: &quot;^8.0.3&quot;,
&quot;jest&quot;: &quot;^27.0.5&quot;,
&quot;vue-template-compiler&quot;: &quot;^2.6.14&quot;
}
}</p>
<p><a href=""https://i.stack.imgur.com/B4Hsn.png"" rel=""nofollow noreferrer"">Vue2</a></p>
",https://stackoverflow.com/questions/72674342/vue-2-coverage-issue-getting-different-behaviour-for-vue-2-and-vue-3,"['vuejs2', 'vue-component', 'vuejs3']",296,False,0,0
Unit testing Google Play Store Billing with Node,"<p>I want to write unit tests to test how my backend handles subscriptions and purchases in my android app. I am using the <a href=""https://developers.google.com/android-publisher/api-ref/rest/v3/monetization.subscriptions"" rel=""nofollow noreferrer"">Google Play Developer API</a> to create subscriptions and <a href=""https://developer.android.com/google/play/billing/rtdn-reference"" rel=""nofollow noreferrer"">real-time developer notifications</a> (RTDN) to listen for updates.</p>
<p>Is there a way to test either the Google Play Developer API or RTDN programatically? My goals are to do the following without using the frontend:</p>
<ol>
<li>Create subscriptions and test fake users paying for subscriptions</li>
<li>Send RTDN of the <a href=""https://developer.android.com/google/play/billing/rtdn-reference#sub"" rel=""nofollow noreferrer"">SubscriptionNotification</a> type to test how my backend handles subscription updates
<ul>
<li>I was able to publish a <a href=""https://developer.android.com/google/play/billing/rtdn-reference#test"" rel=""nofollow noreferrer"">TestNotification</a> using RTDN from the Google Play console, but the test notification does not allow me to test any logic related to updating user/payment information in the back end.</li>
</ul>
</li>
</ol>
<p>All the information I found surrounding <a href=""https://developer.android.com/google/play/billing/test"" rel=""nofollow noreferrer"">testing Google Play billing integration</a> requires an implemented UI. The Google support docs for <a href=""https://support.google.com/googleplay/android-developer/answer/6062777?hl=en"" rel=""nofollow noreferrer"">testing in-app billing</a> also do not have any information to test integration without implementing the frontend, and the <a href=""https://developers.google.com/android-publisher"" rel=""nofollow noreferrer"">Google Play Developer API Docs</a> don't have information regarding unit testing.</p>
<p>Is there any way to make test Google Play Store payments on the backend (with Node) without implementing any front-end functionality?</p>
<p>I figured there must be some way this is supported but I have look around a lot and have not found anything helpful. Are tests like these not supported with Google Play's billing system?</p>
<p>Thank you!</p>
",https://stackoverflow.com/questions/73239719/unit-testing-google-play-store-billing-with-node,"['android', 'unit-testing', 'google-play', 'google-play-developer-api', 'google-play-billing']",165,False,0,0
Using Python&#39;s `unittest` module to compose tests of functions in a separate file,"<p>I have an issue with getting my unit tests to resolve calls to the S.U.T.'s functions. The S.U.T. is defined in a separate file, but in the same project. I've considerable Python experience, but I've never tried to deploy code in a conventional way (which generally suggests conventional testing). The directory structure I'm using seems to be in line with PyPI convention, but I'm missing the step on executing unit tests.</p>
<p><strong>Note 1:</strong> I have tried reviewing the official <code>unittest</code> module's API documentation &amp; tutorials, as well as some unofficial docs. There's not a lot bridging the gap between new, undeployed project and downloading projects already deployed.</p>
<p><strong>Note 2:</strong> I'm not interested in using any third-party unit testing framework. I'd like to stick to <code>unittest</code> module and its conventions. I'm hoping to keep the original project as cross-platform and third-party dependency-light as possible.</p>
<p><strong>Note 3:</strong> Adding <code>import mfut</code> or <code>from mfut import conditionallyClose</code> statements to <code>all_tests.py</code> results in <code>ModuleNotFoundError: No module named 'mfut'</code>. I'm sure this has something to do with the <code>PYTHONPATH</code>, but changing that environment variable strikes me as fragile. I'm hoping there's a more robust way.</p>
<p>Below is merely an example toy problem, but the test cases for the original project aren't much more sophisticated.</p>
<hr />
<p>Given the following Python 3 project directory structure:</p>
<pre><code>My Fun Unit Testing
    ├───src
    │   └───mfut
    │       └───mfut.py
    │
    └───tests
        └───all_tests.py
</code></pre>
<p>and the following contents of file <code>mfut.py</code>:</p>
<pre><code>import math
def conditionallyClose(x1, x2):
    if math.abs(x1) &lt; 1:
        return math.isclose(x1, x2)
    if math.abs(x1) &lt; 1e6:
        return math.isclose(x1, x2, rel_tol=0.10)
    return math.isclose(x1, x2, rel_tol=0.001)
</code></pre>
<p>and the following contents of <code>all_tests.py</code>:</p>
<pre><code>from unittest import TestCase
from math import inf
class onlyTestCase(TestCase):
    def testConditionallyClose_mag1(self):
        self.assertTrue(conditionallyClose(0.05, 0.06))

    def testConditionallyClose_mag6(self):
        self.assertTrue(conditionallyClose(1200000, 1085000))

    def testConditionallyClose_magInf(self):
        self.assertTrue(conditionallyClose(inf, inf))
</code></pre>
<p>what is the Python 3 convention (or requirement) for getting the <code>conditionallyClose(...)</code> calls in <code>all_tests.py</code> to resolve?</p>
",https://stackoverflow.com/questions/73706427/using-pythons-unittest-module-to-compose-tests-of-functions-in-a-separate-fil,"['python', 'unit-testing', 'build', 'conventions', 'project-organization']",83,False,-1,1
Python unit tests having unintended side affects on class,"<p>I am programming a tree for an assignment. Part of this assignment requires us to update the 'imbalance' of the tree at a Node-level. I have an instance variable 'imbalance' that tracks this for each node. Each time I push to the tree I must update this variable.</p>
<p>When unit-testing this creates a problem: the instance variable is not 'reset' or otherwise has unpredictable behaviour between tests because (I believe) of the way the unit tests cache the class. If I change this variable under the first test it will pass all the assertions but on subsequent tests it will fail because it is persisting between them and causing weird problems. I also have to use a getter to access the imbalance variable from each instance of the node.</p>
<p>I know how to fix this, but unfortunately, I cannot change the unit tests (they are fixed for the assignment) so how do I keep track of this variable and change it without having side affects on other unit tests?</p>
<p>EDIT: ~ full disclosure ~ I'm only sharing this expressly for the purpose of diagnosing issues with the unit tests not to seek out help with the actual data structure. Here's two unit tests that demonstrate the odd issue:</p>
<pre><code>def setUp(self):
    &quot;&quot;&quot;
    Set up the tree to be used throughout the test
    This is the tree given in the sample
    A(5)
    /   \
    C(2) D(8)
    /
    B(10)
    &quot;&quot;&quot;

    self.A = Node(5)
    self.B = Node(10)
    self.C = Node(2)
    self.D = Node(8)
    self.C.add_left_child(self.B)
    self.A.add_left_child(self.C)
    self.A.add_right_child(self.D)

def test_get_imbalance(self):
    &quot;&quot;&quot;
    Test that the sample tree returns the correct imbalance
    &quot;&quot;&quot;
    assert_equal(self.A.get_imbalance(), 4, &quot;A has an imbalance of 4&quot;)
    assert_equal(self.C.get_imbalance(), 10, &quot;C has an imbalance of 10&quot;)
    assert_equal(self.D.get_imbalance(), 0, &quot;D has no imbalance&quot;)
    assert_equal(self.B.get_imbalance(), 0, &quot;B has no imbalance&quot;)

def test_update_weight(self):
    &quot;&quot;&quot;
    Test that the sample tree updates the weight correctly
    &quot;&quot;&quot;
    #self.A.update_weight(10)
    assert_equal(self.A.get_imbalance(), 4, &quot;A has an imbalance of 4&quot;)
    assert_equal(self.C.get_imbalance(), 10, &quot;C has an imbalance of 10&quot;)
    assert_equal(self.D.get_imbalance(), 0, &quot;D has no imbalance&quot;)
    assert_equal(self.B.get_imbalance(), 0, &quot;B has no imbalance&quot;)
</code></pre>
<p>Exactly the same! But the second yields the default value created in <strong>init</strong> for the relevant var whereas the one above returns the correct value. Hope that gives a better idea.</p>
",https://stackoverflow.com/questions/71635847/python-unit-tests-having-unintended-side-affects-on-class,"['python', 'unit-testing', 'tree', 'automated-tests', 'nodes']",84,True,0,1
C unit testing with Unity / Ceedling: How to avoid code duplication when testing multiple function inputs?,"<p>I'm new to unit testing and I'm wondering about best practices and how these are applied using Unity / Ceedling.
I'm especially wondering how to avoid code duplication when testing multiple function inputs, but at the same time keeping it clear what is tested. Does it make sense to use loops or should every test be called separately? Is it normal to define each test with a different input as a separate test case? Does Ceedling offer some frame work for testing a function with multiple inputs?</p>
<p>An example: I have a function LoadR1IntoR2 which copies the content of the register specified by R1 into the register specified by R2. R1 and R2 can be seen as enumerations which specify the registers A..E, H and L, and are defined by u8_Input1: Byte 6..7 -&gt; don't care; Byte 3..5 -&gt; specify R2; Byte 0..2 -&gt; specify R1. ps_GPRegs contains the registers which values should be manipulated.
Here's the function declaration:</p>
<pre><code>b LoadR1IntoR2(GeneralPurposeRegs *ps_GPRegs, u8 u8_Input1, u8 u8_Input2, u8 u8_Input3);
</code></pre>
<p>R1 and R2 can both take 7 different values (0..5, 7; 6 is undefined) which means there are at least 49 different combinations to test.</p>
<p>In my current solution I have defined one general test macro for this scenario and call it for every possible combination of R1 and R2:</p>
<pre><code>#define TEST_LOAD_R1_INTO_R2(target, source, value) \
/* .. macro stuff and test assertions etc .. */

void test_LoadR1IntoR2(void) 
{
    /* .. initialisation .. */
    TEST_LOAD_R1_INTO_R2(A, A, 99)
    TEST_LOAD_R1_INTO_R2(A, B, 100)
    TEST_LOAD_R1_INTO_R2(A, C, 101)
    TEST_LOAD_R1_INTO_R2(A, D, 102)
    TEST_LOAD_R1_INTO_R2(A, E, 103)
    TEST_LOAD_R1_INTO_R2(A, L, 104)
    TEST_LOAD_R1_INTO_R2(A, H, 105)
    TEST_LOAD_R1_INTO_R2(B, A, 106)
    /* .. and so on .. */

}
</code></pre>
<p>I also thought about defining a new function:</p>
<pre><code>void loadR1IntoR2_test(GeneralPurposeRegs *ps_GPRegs, enum_R e_R1, enum_R e_R2, u8 u8_TestValue);
</code></pre>
<p>and calling this function either in a loop within test_LoadR1IntoR2 for using just one test case or defining 49 test cases and calling loadR1IntoR2_test with different inputs.</p>
",https://stackoverflow.com/questions/74738104/c-unit-testing-with-unity-ceedling-how-to-avoid-code-duplication-when-testing,"['c', 'unit-testing', 'ceedling']",49,False,0,1
AST and Language Service Plugin,"<p>I would like to create a vscode extension which can help with unit testing and &quot;live&quot; debugging.</p>
<p>Lets say you have the following code:</p>
<pre class=""lang-js prettyprint-override""><code>/*1*/ export class Test {
/*2*/   public add(a: any, b: any): any {
/*3*/     return a + b;
/*4*/   }
/*5*/ }
</code></pre>
<p><strong>Live debugging:</strong><br />
New option in the context menu to test the <code>add</code> function (e.g. something similar to current Peek Definition) where you can provide the function input and check the output in a new smaller editor.</p>
<p><strong>Unit test generation:</strong><br />
After you wrote an input and checked the output you can simply generate a new unit test from it.</p>
<p>Now I'm only at the beginning of this project but it seems like getting type information is much more complicated than I expected.<br />
First I would like to get some simple type information (based on cursor position) e.g.:</p>
<ul>
<li>Line 1 is a class</li>
<li>Line 2-4 is a function</li>
<li>Line 5 is a class</li>
</ul>
<p>After hours of Google search I think what I have to do is to implement my own <a href=""https://github.com/Microsoft/TypeScript/wiki/Writing-a-Language-Service-Plugin"" rel=""nofollow noreferrer"">TypeScript Language Service Plugin</a> and use it somehow in my extension.</p>
<p>My questions:</p>
<ol>
<li>Is there any extension similar to my idea which I could use?</li>
<li>Is there an easier way to get the type information I need?</li>
<li>Am I on a right track at all?</li>
<li>Do you have some material about how to use this language service plugin from extension?</li>
</ol>
<p><strong>P.S.</strong> I know that it won't be easy (e.g. several states with different visibility), but good practice for a home project.</p>
",https://stackoverflow.com/questions/73756694/ast-and-language-service-plugin,['vscode-extensions'],44,False,0,0
Can/should I run Jest alongside webpack?,"<p>I am pretty new to unit testing, and I am trying to understand best practice for whether and, if so, how to run Jest alongside webpack.</p>
<p>For context, I am used to using ESLint in the following way. I use <a href=""https://webpack.js.org/plugins/eslint-webpack-plugin/"" rel=""nofollow noreferrer"">eslint-webpack-plugin</a> and configure it so that webpack outputs an error and/or fails the build if there is a linting error. I use this setup for both the development build (using <a href=""https://webpack.js.org/configuration/dev-server/"" rel=""nofollow noreferrer"">webpack-dev-server</a>) and the production build so that I can be made aware of and address linting issues as they arise. I also use <a href=""https://github.com/okonet/lint-staged"" rel=""nofollow noreferrer"">lint-staged</a> and <a href=""https://typicode.github.io/husky/#/"" rel=""nofollow noreferrer"">husky</a> to set up a pre-commit hook that runs ESLint before commits for a similar reason.</p>
<p>So, my inclination when learning Jest was to use a similar setup, where tests will be run as part of the webpack compilation process and errors will be obvious and intrusive so that I can address/resolve them as they arise. I tried following the tutorials for Babel and webpack on the Jest site, but I cannot get webpack to throw any errors, and I'm not even sure if it's even running Jest at all to be honest. I looked to see how <a href=""https://create-react-app.dev/"" rel=""nofollow noreferrer"">create-react-app</a> and <a href=""https://github.com/vercel/next.js/tree/canary/examples/with-jest-babel"" rel=""nofollow noreferrer"">create-next-app</a> have Jest set up. They both include an npm script for testing, but it seems users are supposed to run that script manually, separately from the dev/build processes, or as part of a CI workflow.</p>
<p>Any advice appreciated!</p>
",https://stackoverflow.com/questions/73154688/can-should-i-run-jest-alongside-webpack,"['unit-testing', 'webpack', 'jestjs']",20,False,0,0
How to serialize object rather than stringify when using ForContext,"<p>I want to support serializing additional relevant data with a Serilog log but I want to ensure that this data is written in valid JSON. It will be captured and stored separately by my own log event sink.</p>
<p>For this example I have an optional object property called &quot;additionalDetails&quot;</p>
<p>I can use the following to write the log information and the additionalDetails can be extracted as JSON:</p>
<pre><code>int messageId = 99;
var additionalDetails = new {SomeId = 1, SomeValue = &quot;This is a test value&quot;};
logger.Information(&quot;Test Log Entry: {messageId} Additional Details: {@additionalDetails}&quot;, 
    messageId, additionalDetails);
</code></pre>
<p>In my Sink I can retrieve the &quot;additionalDetails&quot; as JSON from the logEvent.Properties and write it. However, I don't want to necessarily include the AdditionalDetails in every log message text.</p>
<p>What I would like is:</p>
<pre><code>int messageId = 99;
var additionalDetails = new {SomeId = 1, SomeValue = &quot;This is a test value&quot;};
logger
    .ForContext(&quot;additionalDetails&quot;, additionalDetails)
    .Information(&quot;Test Log Entry: {messageId}&quot;, 
    messageId);
</code></pre>
<p>The problem here is that while the Sink can see the additionalDetails value, it isn't coming back as valid JSON, but the default stringified value. For unit testing I am validating that the stored object is complete, which puts a bit of a blocker if I cannot convert that stringified value back into an object.</p>
<p>On a whim I tried: <code>.ForContext(&quot;@additionalDetails&quot;, additionalDetails)</code> and &quot;{@additionalDetails}&quot; but that was no joy.</p>
<p>I also found a recommendation to write the object as a string using <code>JsonConvert.Serialize(additionalDetails)</code> but that ended up causing extra quote escaping in the resulting string captured by the Sink <code>logEvent.Properties[&quot;additionalDetails&quot;].ToString()</code>.</p>
<p>Is there a way that <code>ForContext</code> can serialize an object like with the &quot;{@additionalDetails}&quot;, or include the &quot;{@additionalDetails}&quot; and parameter in the <code>.Information()</code> etc. calls without the parameter being rendered in the message? (sounds rather silly round-about)</p>
",https://stackoverflow.com/questions/74188175/how-to-serialize-object-rather-than-stringify-when-using-forcontext,"['c#', 'serilog']",188,False,0,2
How to initialize a struct with random data in C?,"<p>Assuming we have the following complex struct (in C). It includes fixed-length arrays, members of varying sizes, enums and other structs. This struct is not packed, and cannot be packed.</p>
<pre><code>struct {
    uint8_t smallNum;
    /* uint8_t align0 */
    /* uint8_t align1 */
    /* uint8_t align2 */
    uint32_t arrayOfBigNums[5];
    bool isFalse;
    /* uint8_t align0 */
    /* uint8_t align1 */
    /* uint8_t align2 */
    struct myOtherStruct;
    /* uint8_t align0 */
    enum mySmallEnum;
...
    uint8_t aByte;
    /* uint8_t align0 */
    /* uint8_t align1 */
} myStruct;
</code></pre>
<p>We would like to initialize this struct with random data for unit testing. The test includes taking this struct, serializing it, writing it to flash, reading it, deserializing it, and then checking that the data hasn't changed.</p>
<p>Either generate all possible values, or generate a small randomized subset and test it. So how would one go about doing this?</p>
<p>The immediate solution would be the following:</p>
<pre><code>myStruct testData = {0};
myStruct readData = {0};
testData.smallNum = rand();
testData.arrayOfBigNums[0] = rand();
testData.arrayOfBigNums[1] = rand();
....
testData.aByte = rand();
save(&amp;testData);
load(&amp;readData);
int ret = memcmp(&amp;readData, &amp;testData, sizeof(myStruct)); 
// ret == 0. Good!
</code></pre>
<p>But this solution isn't scalable. Adding another field to the struct, or increasing the array would require changing the unit test. Also, it'd be a long init function, prone to human error.</p>
<p>Another solution would be to generate a random array of bytes, and then <code>memcpy</code> it into our struct. Although this is a great idea, in practice it won't work because our struct isn't packed. Some bytes are and always will be 0.</p>
<pre><code>myStruct testData = {0};
myStruct readData = {0};
uint8_t* randomData = genRandomData(sizeof(myStruct));
memcpy((uint8_t*)&amp;testData, randomData, sizeof(myStruct));
save(&amp;testData);
load(&amp;readData);
int ret = memcmp(&amp;readData, &amp;testData, sizeof(myStruct)); 
// ret != 0 because deserialization will fill the struct properly. 
// Ignoring junk bytes in padding
</code></pre>
<p>My current working solution is to iteratively improve on the previous one. Initialize a struct with 0xff, cast it to a byte array and mask it with everything. <a href=""https://patchwork.ozlabs.org/project/gcc/patch/573D050A.7030100@gmail.com/"" rel=""nofollow noreferrer"">You get a compiler warning</a> but to my knowledge it's harmless.</p>
<pre><code>myStruct structMask = {MACRO_TO_FILL_WITH_MANY(-1)};
myStruct testData = {0};
myStruct readData = {0};
uint8_t* randomData = genRandomData(sizeof(myStruct));
memcpy((uint8_t*)&amp;testData, randomData, sizeof(myStruct));
for(size_t i = 0; i &lt; sizeof(myStruct); i++){
    ((uint8_t*)&amp;testData)[i] &amp;= ((uint8_t*)&amp;structMask)[i];
}
save(&amp;testData);
load(&amp;readData);
int ret = memcmp(&amp;readData, &amp;testData, sizeof(myStruct)); 
// ret != 0 because deserialization will fill the struct properly. 
// Ignoring junk bytes in padding
</code></pre>
<p>This solution is also not optimal, because it doesn't take into account enum limitations. Types like bool (from stdbool.h) are stored as 0/1 which is nice, but enums can still have undefined values. So we'd need to manually modulo all enum values.</p>
<p>Looking for more generic / robust solutions.</p>
",https://stackoverflow.com/questions/73316796/how-to-initialize-a-struct-with-random-data-in-c,"['c', 'unit-testing', 'struct', 'storage']",287,True,3,3
vuejs sample app npm run dev not working throwing Error: Cannot find module &#39;node:url&#39;,"<p>I am new to vuejs I am following the below steps to create my vue js app in the local system.</p>
<p>Step:</p>
<blockquote>
<p>npm init vue@latest</p>
</blockquote>
<p>✔ Project name: … <strong>VueDemo</strong>
✔ Add TypeScript? … No / Yes
✔ Add JSX Support? … No / Yes
✔ Add Vue Router for Single Page Application development? … No / Yes
✔ Add Pinia for state management? … No / Yes
✔ Add Vitest for Unit testing? … No / Yes
✔ Add Cypress for both Unit and End-to-End testing? … No / Yes
✔ Add ESLint for code quality? … No / Yes
✔ Add Prettier for code formatting? … No / Yes</p>
<p>Scaffolding project in ./<strong>VueDemo</strong>
Done.</p>
<p>cd VueDemo
npm install
npm run dev</p>
<p>It's throwing the following error in the console:</p>
<blockquote>
<p>failed to load config from
/Users/ashok/MyStudy/Vue/VueDemo/vite.config.js error when starting
dev server: Error: Cannot find module 'node:url' Require stack:</p>
<ul>
<li>/Users/ashok/MyStudy/Vue/VueDemo/vite.config.js</li>
<li>/Users/ashok/MyStudy/Vue/VueDemo/node_modules/vite/dist/node/chunks/dep-0fc8e132.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:889:15)
at Function.Module._load (internal/modules/cjs/loader.js:745:27)
at Module.require (internal/modules/cjs/loader.js:961:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object. (/Users/ashok/MyStudy/Vue/VueDemo/vite.config.js:31:23)
at Module._compile (internal/modules/cjs/loader.js:1072:14)
at Object._require.extensions. [as .js] (file:///Users/ashok/MyStudy/Vue/VueDemo/node_modules/vite/dist/node/chunks/dep-0fc8e132.js:63096:24)
at Module.load (internal/modules/cjs/loader.js:937:32)
at Function.Module._load (internal/modules/cjs/loader.js:778:12)
at Module.require (internal/modules/cjs/loader.js:961:19)</li>
</ul>
</blockquote>
<p>Package.json file:</p>
<pre><code>{
  &quot;name&quot;: &quot;vuedemo&quot;,
  &quot;version&quot;: &quot;0.0.0&quot;,
  &quot;scripts&quot;: {
    &quot;dev&quot;: &quot;vite&quot;,
    &quot;build&quot;: &quot;vite build&quot;,
    &quot;preview&quot;: &quot;vite preview --port 4173&quot;
  },
  &quot;dependencies&quot;: {
    &quot;vue&quot;: &quot;^3.2.37&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;@vitejs/plugin-vue&quot;: &quot;^3.0.1&quot;,
    &quot;vite&quot;: &quot;^3.0.4&quot;
  }
} 
</code></pre>
<p>vite.config.js:</p>
<pre><code>import { fileURLToPath, URL } from 'node:URL

import { defineConfig } from 'vite'
import Vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})
</code></pre>
",https://stackoverflow.com/questions/73586656/vuejs-sample-app-npm-run-dev-not-working-throwing-error-cannot-find-module-nod,"['javascript', 'vue.js']",3508,True,3,2
Why am I getting &quot;Invalid hook call&quot; in react monorepo,"<h2>Intro</h2>
<p>I've a react monorepo, managed with <code>lerna</code> and <code>yarn workspace</code>, and there are 3 packages inside:</p>
<ul>
<li>React Native application for iOS and Android with customized Metro bundler</li>
<li>Web application created with CRA 5 with customized webpack config by using CRACO</li>
<li>Common: are common functions, logic and custom hooks to share the logic between the RN app and the webapp</li>
</ul>
<p>In the common package, before start testing, I had only modules that containing types and I had installed thos as dev dependencies. <strong>With this configuration everything was working</strong>, the web and mobile app starts without errors.</p>
<hr />
<h2>Problem</h2>
<p>Problems arrived when I wanted to test custom hooks in the common package (for test the shared logic). I've runned jest (already used to test some classes and unit testing some pure functions) and it correctly spit off an error that said that it cannot find react module. That's correct because I installed just @types/react and react was a peerDependency.</p>
<p>After install React in the common package as a devDependency, Jest work as intended, but the mobile app and the web app saying the same thing:</p>
<pre><code>Warning: Invalid hook call. Hooks can only be called inside of the body of a function component.
This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
</code></pre>
<p>The thing that I don't get is <strong>why am I getting this error</strong>??
I've already use <code>nohoist</code> option on react and react native with this config:</p>
<pre class=""lang-json prettyprint-override""><code>{
  &quot;workspaces&quot;: {
    &quot;packages&quot;: [
      &quot;packages/*&quot;
    ],
    &quot;nohoist&quot;: [
      &quot;**/react-native&quot;,
      &quot;**/react-native/**&quot;,
      &quot;**/react&quot;,
      &quot;**/react/**&quot;
    ]
  },
}
</code></pre>
<p>I've this configuration in the root <code>package.json</code>.</p>
<p>This is my <code>metro.config.js</code> used by React Native:</p>
<pre class=""lang-js prettyprint-override""><code>const path = require('path');
const Resolver = require('metro-resolver');

const watchFolders = [
  //Relative path to packages directory
  path.join(__dirname, 'node_modules'),
  path.join(__dirname, '..', 'common'),
  path.join(__dirname, '..', '..', 'node_modules'),
];

module.exports = {
  transformer: {
    getTransformOptions: async () =&gt; ({
      transform: {
        experimentalImportSupport: false,
        inlineRequires: true,
      },
    }),
  },
  resolver: {
    // This was added to enable Metro to handle the symlinks that yarn
    // workspaces places in the node_modules folder.
    extraNodeModules: new Proxy(
      {},
      {
        get: (target, name) =&gt; {
          return path.join(__dirname, `node_modules/${name}`);
        },
      },
    ),
    // Make sure we use the local copy of react and react-native
    resolveRequest: (context, realModuleName, platform, moduleName) =&gt; {
      const clearContext = { ...context, resolveRequest: undefined };
      const module =
        moduleName === 'react' || moduleName === 'react-native'
          ? path.join(__dirname, 'node_modules', realModuleName)
          : realModuleName;
      return Resolver.resolve(clearContext, module, platform);
    },
  },
  watchFolders,
};
</code></pre>
<p>and this is my <code>craco.config.js</code> use by the CRA web project:</p>
<pre class=""lang-js prettyprint-override""><code>const path = require('path');
const { getLoader, loaderByName } = require('@craco/craco');
const { CracoAliasPlugin } = require('react-app-alias');

const packages = [];
packages.push(path.join(__dirname, '../common'));

module.exports = {
  webpack: {
    configure: (webpackConfig, arg) =&gt; {
      const { isFound, match } = getLoader(
        webpackConfig,
        loaderByName('babel-loader'),
      );
      if (isFound) {
        const include = Array.isArray(match.loader.include)
          ? match.loader.include
          : [match.loader.include];

        match.loader.include = include.concat(packages);
      }

      return webpackConfig;
    },
  },
  plugins: [
    {
      plugin: CracoAliasPlugin,
      options: {
        alias: {
          react: './node_modules/react',
        },
      },
    },
  ],
};

</code></pre>
<p>I don't understand why both bundlers are getting the wrong modules, I'm already use alias and resolver in the correct way to avoid this.</p>
<p>Any suggestion?</p>
",https://stackoverflow.com/questions/73033933/why-am-i-getting-invalid-hook-call-in-react-monorepo,"['reactjs', 'react-native', 'monorepo', 'yarn-workspaces', 'metro-bundler']",611,False,2,0
Integration testing authorized endpoints with already specified authentication schemes,"<p>I am trying to set up integration tests for my ASP.NET Web API with authorized endpoints.</p>
<p>I have followed the documentation from Microsoft to add mock authentication to the integration tests to allow the test client to access the authorized endpoints. <a href=""https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0"" rel=""nofollow noreferrer"">https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-6.0</a></p>
<p>E.g.</p>
<pre><code>builder.ConfigureTestServices(services =&gt;
{
    services.AddAuthorization(options =&gt;
    {
        options.DefaultPolicy = new AuthorizationPolicyBuilder()
            .AddAuthenticationSchemes(&quot;Test&quot;)
            .RequireAuthenticatedUser()
            .Build();
    });
}
</code></pre>
<p>This works fine if you are using default authentication schemes that you can change on the startup of your integration tests to use the test scheme. But, my authorized endpoints are using specified <code>AuthenticationSchemes</code> so the test scheme will never be authorized for the endpoint. E.g.</p>
<pre><code>[Authorize(AuthenticationSchemes = &quot;Scheme1,Scheme2&quot;)]
public class AppVersionController : ControllerBase
{
    ...
}
</code></pre>
<p>I can get around this issue by specifying an environment variable when testing, checking this and dynamically adding the test scheme to the authorized endpoint. Yet, this adds a lot of test-specific logic to the app, which isn't nice to have in the main project.</p>
<p>This would work:</p>
<pre><code>// Test scheme added dynamically from an environment variable to get the below result
[Authorize(AuthenticationSchemes = &quot;Scheme1,Scheme2,Test&quot;)]
public class AppVersionController : ControllerBase
{
    ...
}
</code></pre>
<p>I get this done by creating a custom attribute that looks basically like this:</p>
<pre><code>public class AuthorizeAll : AuthorizeAttribute
{
    public AuthorizeAll()
    {
        var authenticationSchemes = &quot;Scheme1,Scheme2&quot;;
        if (Environment.GetEnvironmentVariable(&quot;ASPNETCORE_ENVIRONMENT&quot;) == &quot;Testing&quot;)
        {
            authenticationSchemes += &quot;,Test&quot;;
        }
        AuthenticationSchemes = authenticationSchemes;
    }
}
</code></pre>
<p>I just don't like how we will have to continue to maintain this test authentication scheme in the application layer as well as the security concerns with this approach.</p>
<h2>Questions</h2>
<p>What is the best way to authorize endpoints for .NET integration tests when specific authentication schemes are set?</p>
<p>Is it good practice to check environment variables in the app when unit testing to run specific logic that the tests need to work?</p>
<p>The main authentication scheme used at the moment is using JWTs, so is there a better way to mock JWTs for the tests?</p>
",https://stackoverflow.com/questions/73793608/integration-testing-authorized-endpoints-with-already-specified-authentication-s,"['c#', 'authorization', 'asp.net-core-webapi', 'integration-testing', '.net-6.0']",1130,True,1,2
Typescript Clean Architecture and In-Memory Database/ Repository,"<p>I am implementing clean architecture in my current project and I am struggling with repositories and data sources and terminology.</p>
<p>I would like to test my <code>useCases</code> with in-memory repository because I only care about my business logic at this stage. But I cannot make sense of the terminology and would like to ask about it.</p>
<p>I defined a base <code>DataSource</code> like this:</p>
<pre><code>export interface DataSource&lt;T&gt; {    
    create(request: any): Promise&lt;T&gt;

    // more methods here but removed for simplicity
}
</code></pre>
<p>Then I defined my interface for <code>Patient</code> like this:</p>
<pre><code>export interface PatientRepository {
    createPatient(patient: Patient): Promise&lt;void&gt;

    // more methods here but removed for simplicity
}
</code></pre>
<p>I will be using a <code>Sequelize</code> for production and for unit testing just a local array of <code>entities</code>.</p>
<p>If I am doing an implementation of the <code>PatientRepository</code> do I:</p>
<p><strong>Option 1</strong></p>
<p>I create a <code>PatientSequelizeRepository</code> which will implement the methods in my contract and it will extend an abstract <code>SequelizeRepository</code> that implements the <code>DataSource</code> contract. Then I would also create a <code>PatientInMemoryRepository</code> which will implement the same methods and it will extend and abstract <code>InMemoryRepository</code> that implements the <code>DataSource</code> contract. Then in my <code>use-case</code> I import the <code>PatientInMemoryRepository</code> and in my composition of the <code>app</code> I would import the <code>PatientSequelizeRepository</code>?</p>
<p><strong>Option 2</strong></p>
<p>I create one implementation of the <code>PatientRepository</code> and assign a <code>data-source</code> into constructor because the methods for the <code>PatientRepository</code> are the same. I would also have a generic <code>InMemoryDataSource</code> and <code>SequelizeDataSource</code> that would both implement the <code>DataSource</code> contract. So by default I am constructing the repository with <code>Sequelize</code> implementation but I am also giving the opportunity to use other data sources if needed</p>
<pre><code>export class PatientRepositoryImpl implements PatientRepository {
    constructor(dataSource: DataSource&lt;Patient&gt;) { }
    
    async createPatient(patient: Patient) {
       return this.dataSource.create(patient)
    }
}

export const patientRepository = new PatientRepositoryImpl(new SequelizeDataSource())
</code></pre>
<p>Here I get confused of the naming. I am inserting a <code>SequelizeDataSource</code> into the constructor, but should I create a <code>PatientSequelizeDataSource</code>, insert this into the constructor and do the same with <code>PatientInMemoryDataSource</code>? What would be the best action here? Is there maybe an option 3 I haven't thought about?</p>
",https://stackoverflow.com/questions/74516719/typescript-clean-architecture-and-in-memory-database-repository,"['typescript', 'clean-architecture']",285,False,0,1
Is it possible to use json features of Sqlite with Entity Framework Core,"<p>From what I have found on the web, Sqlite has a Json extension which support the Json operators <code>-&gt;</code> and <code>-&gt;&gt;</code> but that it's not included by default. Is there a way to enable this extension when using Entity Framework Core?</p>
<p>My situation is, I'm using Entity Framework Core with a PostgreSQL database in production but I'm using an Sqlite in memory database for unit tests.</p>
<p>I am executing some SQL in a repository that I'm having trouble unit testing. It uses PostgreSQLs Json operator <code>-&gt;&gt;</code> but when the unit tests try to run it with Sqlite, it doesn't recognise the operator.</p>
<p>The line of code in question is</p>
<pre class=""lang-cs prettyprint-override""><code>dbContext.Database.ExecuteSqlInterpolatedAsync($&quot;DELETE FROM clients.client_history WHERE new_value -&gt;&gt; 'id' = {clientId.ToString()}&quot;);
</code></pre>
<p>I understand that Sqlite is not going to be a perfect match to PostgreSQL in all situations but it would be helpful if it could match the behaviour a bit more in this scenario. Using PostgreSQL for the unit tests is not a practical solution for us due to performance / overhead in setting up the database. Currently, this is the only part of my repository where Sqlite doesn't match the behaviour of PostgreSQL closely enough to be useful.</p>
<p>I'm using .Net6 with Entity Framework Core 6. I'm developing on Windows and deploying to Linux based Docker / Kubernetes (depending on environment). We currently plan on upgrading to .Net7 / EF Core 7 at some point in the future (once it has been RTW, obviuosly) so if EF Core 7 introduces a solution to this, that would be useful to know, even if EF Core 6 can't do it.</p>
",https://stackoverflow.com/questions/73971298/is-it-possible-to-use-json-features-of-sqlite-with-entity-framework-core,"['c#', 'sqlite', '.net-core', 'entity-framework-core', 'sqlite-json1']",305,False,0,1
How to close connection of a WCF client instantiated via interface?,"<p>I have a WCF client that has been instantiated via its interface on my MVC 4 project  controller like this:</p>
<pre><code>private readonly ILMS_Service lms_client;

public ProductsController(ILMS_Service client)
{
    lms_client = client;
}

public ProductsController()
{
    lms_client = new LMS_ServiceClient();
}
</code></pre>
<p>I can access the operation contracts from the client, but what I noticed on this implementation is that there's no <code>.Open()</code> and <code>.Close()</code> methods as I would normally access with <code>LMS_Client lms_client = new LMS_ServiceClient();</code>. I cannot use this conventional way initializing the WCF client since I need to be able to pass mock WCF client from my unit tests. With this, I have to initialize the WCF client via it's interface and have to make a constructor to pass the mock service whenever I test.</p>
<p>Correct me if I'm wrong but I have found <a href=""https://stackoverflow.com/questions/27924045/disposing-of-a-wcf-client-instantiated-via-an-interface"">this post</a>, however it doesn't tell me anything where to implement the <code>Dispose()</code> method (e.g. to the Controller or on the <code>.svc</code> file of the WCF project?). And I think <a href=""https://stackoverflow.com/a/573925/8331324"">this answer</a> doesn't seem to have unit testing in mind. It seems to implement the interface for every call of the methods on the WCF; in which, it is not mockable. In addition, I have also found <a href=""https://johan.driessen.se/posts/do-not-forget-to-close-your-wcf-serviceclients/"" rel=""nofollow noreferrer"">this blog</a> which is the closest to my scenario, but is this a good way of closing the connection via a destructor? Where do you implement it? On the Controller calling the method or the on the <code>.svc</code> file of the WCF project?</p>
<p>It would be great if someone could enlighten me or show me a good way of opening/closing WCF client connection with this implementation through an example. Any help would be appreciated. Thanks!</p>
",https://stackoverflow.com/questions/73934666/how-to-close-connection-of-a-wcf-client-instantiated-via-interface,"['c#', 'unit-testing', 'wcf', 'asp.net-mvc-4']",99,True,0,2
Restrict GitLab pipeline/job based on whether the source is a merge commit,"<p>I am specifically <strong>not</strong> talking about <em>merge <strong>requests</strong></em>, which I know I can restrict jobs for with with <code>only:</code> or <code>except:</code> statements, and which have ample questions on the site already. I want to restrict certain jobs (expensive testing) from running for <em>merge <strong>commits</strong></em> - for a merge request to be merged, unit testing must pass, so it makes no sense to run unit tests again right after merging.</p>
<p>But the only answer I found to that requirement was to restrict tests from ever running on the <code>master</code> branch completely, and we still want to be able to run tests there, we just don't want the tests to run if the commit was a merge commit coming from a merge request where the tests already ran (we only allow merging if tests pass). So simply restricting tests from running on the <code>master</code> branch is not a good solution for us.</p>
<p>I also found multiple references to <code>$CI_PIPELINE_SOURCE</code> containing <code>&quot;merge_request_event&quot;</code> if the pipeline was triggered by merging a merge request, but that doesn't seem to be the case in current GitLab instances. Instead, the variable contains <code>&quot;push&quot;</code>, which seems like a bug or at least a misnomer, considering no pushes are involved when I click <em>Merge now</em> on a merge request.</p>
<p>So I am looking for a <code>.gitlab-ci.yml</code> declaration which will prevent a job from running if the pipeline was triggered by a merge commit, but still allow it to run if a pipeline is created on the same branch for any other reason than a merge commit.</p>
",https://stackoverflow.com/questions/71109968/restrict-gitlab-pipeline-job-based-on-whether-the-source-is-a-merge-commit,"['gitlab', 'gitlab-ci']",570,True,0,1
xUnit testing controller with error when instantiating JWT token provider,"<p>I have a controller in my WebAPI (not MVC or Core) using .Net 4.8 that I'm trying to test with xUnit.</p>
<p>Before I proceed, the way it is setup may not be correct for unit testing, but it is what I have been given and I don't know any better at this stage, any pointers in this regard is welcome.</p>
<p>The main problem in the controller is the immediate declaration/instantiation of ApiOAuthProvider. As it creates the object, it in-turn does an immediate declaration/instantiation of JwtTokenProvider. This is where the error occurs, inner exception:</p>
<blockquote>
<p>Message &quot;Could not load file or assembly
'System.Configuration.ConfigurationManager, Version=0.0.0.0,
Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'. The system cannot
find the file specified.&quot;</p>
</blockquote>
<p>But I'm jumping ahead I'll show the code</p>
<p><strong>Controller:</strong></p>
<pre><code>using System.Net;
using System.Net.Http;
using System.Web.Http;
using TA.Services.BL.BusinessLogic;
using TA.Services.WebAPI.Providers;
using TA.Services.DTO.DTO;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using TA.Services.BL.Interface;

namespace TA.Services.WebAPI.Controllers
{
  public class AccountsController : ApiController
  {
    private readonly ApiOAuthProvider _jwtTokenProvider = new ApiOAuthProvider();
    private readonly ICommonBL _commonBL;
    private readonly ISystemSettingsBL _systemSettingsBL;

    public AccountsController(ICommonBL commonBL, ISystemSettingsBL systemSettingsBL)
    {
      _commonBL = commonBL;
      _systemSettingsBL = systemSettingsBL;
    }
    ...
    // GET: JwtToken
    [HttpPost]
    //[EnableCors(&quot;*&quot;, &quot;*&quot;, &quot;*&quot;)]
    public JObject Token(User loginUserCredentials)
    {
      // first check the user name &amp; password is valid one before generating token for that user.
      var user = _commonBL.GetUserInformation(loginUserCredentials.UserName);
      var accessToken = _jwtTokenProvider.GenerateToken(user);
      return accessToken;
    }
  }
}
</code></pre>
<p><strong>ApiOAuthProvider:</strong></p>
<pre><code>namespace TA.Services.WebAPI.Providers
{
  using Microsoft.Owin.Security;
  using Microsoft.Owin.Security.OAuth;
  using Newtonsoft.Json.Linq;
  using System;
  using System.Collections.Generic;
  using System.Security.Claims;
  using System.Web.Http.Cors;
  using TA.Services.DTO.DTO;
  using static TA.Services.WebAPI.Providers.JWTHelper;

  [EnableCors(&quot;*&quot;, &quot;*&quot;, &quot;*&quot;)]
  public class ApiOAuthProvider : OAuthAuthorizationServerProvider
  {
    private readonly JwtTokenProvider _jwtTokenProvider = new JwtTokenProvider();

    [EnableCors(&quot;*&quot;, &quot;*&quot;, &quot;*&quot;)]
    public JObject GenerateToken(User userDetail)
    {
      ...
      return tokenResponse;
    }
    public static AuthenticationProperties CreateProperties(string userName, Status apiData)
    {
      ...
      return new AuthenticationProperties(data);
    }
  }
}
</code></pre>
<p><strong>JwtTokenProvider:</strong></p>
<pre><code>namespace TA.Services.WebAPI.Providers
{
  using System;
  using System.Configuration;
  using System.Security.Claims;
  using System.Text;
  using System.Web.Configuration;
  using System.Web;
  using Microsoft.Owin.Security;
  using TA.Services.BL.Interface;
  using TA.Services.DTO.DTO;
  using System.IdentityModel.Tokens.Jwt;
  using Microsoft.IdentityModel.Tokens;

  public class JwtTokenProvider : ISecureDataFormat&lt;AuthenticationTicket&gt;
  {
    private static string plainTextSecurityKey = ((MachineKeySection)ConfigurationManager.GetSection(&quot;system.web/machineKey&quot;)).ValidationKey;
    private readonly Microsoft.IdentityModel.Tokens.SymmetricSecurityKey _signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(plainTextSecurityKey));
    private readonly IAuditsBL _auditsBL;

    public string Protect(AuthenticationTicket data)
    {
      var signedAndEncodedToken = string.Empty;
      ...
      return signedAndEncodedToken;
    }

    public AuthenticationTicket Unprotect(string signedAndEncodedToken)
    {
      ClaimsIdentity idenity = null;
      ...
      return new AuthenticationTicket(idenity, new AuthenticationProperties());
    }
  }
}
</code></pre>
<p><strong>My xUnit test class:</strong></p>
<pre><code>using Moq;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Principal;
using System.Web.Http;
using TA.Services.BL.Interface;
using TA.Services.DTO.DTO;
using TA.Services.WebAPI.Controllers;
using TA.Services.WebAPI.Providers;
using Xunit;

namespace TA.Services.WebAPI.Tests.Controllers
{
  public class AccountsControllerTests : BaseUnitTest
  {
    private readonly Mock&lt;ICommonBL&gt; _commonBLMock;
    private readonly Mock&lt;ISystemSettingsBL&gt; _systemSettingsBLMock;
    private readonly AccountsController _accountsController;

    public AccountsControllerTests()
    {
      _commonBLMock = new Mock&lt;ICommonBL&gt;();
      _systemSettingsBLMock = new Mock&lt;ISystemSettingsBL&gt;();
      _accountsController = new AccountsController(_commonBLMock.Object, _systemSettingsBLMock.Object);
    }
    ...
  }
}
</code></pre>
<p>The exception occurs here in JwtTokenProvider:</p>
<pre><code>private readonly Microsoft.IdentityModel.Tokens.SymmetricSecurityKey _signingKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(plainTextSecurityKey));
</code></pre>
<p><strong>StackTrace:</strong></p>
<pre><code>at TA.Services.WebAPI.Providers.JwtTokenProvider..ctor() in C:\TA\Repos\April 20 2021\TADev\Service\TA.Services\TA.Services.WebAPI\Providers\JwtTokenProvider.cs:line 19 
at TA.Services.WebAPI.Providers.ApiOAuthProvider..ctor() in C:\TA\Repos\April 20 2021\TADev\Service\TA.Services\TA.Services.WebAPI\Providers\ApiOAuthProvider.cs:line 23 
at TA.Services.WebAPI.Controllers.AccountsController..ctor(ICommonBL commonBL, ISystemSettingsBL systemSettingsBL) in C:\TA\Repos\April 20 2021\TADev\Service\TA.Services\TA.Services.WebAPI\Controllers\AccountsController.cs:line 27 
at TA.Services.WebAPI.Tests.Controllers.AccountsControllerTests..ctor() in C:\TA\Repos\April 20 2021\TADev\Service\TA.Services\Testing\TA.Services.WebAPI.Tests\Controllers\AccountsControllerTests.cs:line 26
</code></pre>
<p><strong>Sub-questions:</strong></p>
<ol>
<li><p>Maybe I'm going down the wrong path, however should I mock ApiOAuthProvider, in order to do that I need to inject it, in order to do that, I need to create an interface and registry it as a service, but this doesn't sound right.</p>
</li>
<li><p>Do I just need to create a valid token.</p>
</li>
<li><p>Maybe it really can't find the System.Configuration.ConfigurationManager</p>
</li>
</ol>
<p><strong>Main Question:</strong> How should I go about resolving this?</p>
<p><strong>Note:</strong> The application works just fine outside of this test, under normal execution.</p>
<p><strong>[Update]</strong> Changed controller have ApiOAuthProvider injected</p>
<pre><code>  public class AccountsController : ApiController
  {
    private readonly ApiOAuthProvider _jwtTokenProvider;
    private readonly ICommonBL _commonBL;
    private readonly ISystemSettingsBL _systemSettingsBL;

    public AccountsController(ApiOAuthProvider jwtTokenProvider, ICommonBL commonBL, ISystemSettingsBL systemSettingsBL)
    {
      _commonBL = commonBL;
      _systemSettingsBL = systemSettingsBL;
      _jwtTokenProvider = jwtTokenProvider;
    }
</code></pre>
<p>Added ApiOAuthProvider to services in startup:</p>
<pre><code>services.AddSingleton&lt;ApiOAuthProvider&gt;();
</code></pre>
<p>Changed test script:</p>
<pre><code>  public class AccountsControllerTests : BaseUnitTest
  {
    private readonly Mock&lt;ApiOAuthProvider&gt; _apiOAuthProviderMock;
    private readonly Mock&lt;ICommonBL&gt; _commonBLMock;
    private readonly Mock&lt;ISystemSettingsBL&gt; _systemSettingsBLMock;
    private readonly AccountsController _accountsController;

    public AccountsControllerTests()
    {
      _apiOAuthProviderMock = new Mock&lt;ApiOAuthProvider&gt;();
      _commonBLMock = new Mock&lt;ICommonBL&gt;();
      _systemSettingsBLMock = new Mock&lt;ISystemSettingsBL&gt;();
      _accountsController = new AccountsController(_apiOAuthProviderMock.Object, _commonBLMock.Object, _systemSettingsBLMock.Object);
    }
    ...
</code></pre>
<p>Debugged the test and it kept going until it got to the same error. Doesn't seem to mock very well without an interface.</p>
<p><strong>[Update End]</strong></p>
",https://stackoverflow.com/questions/72724624/xunit-testing-controller-with-error-when-instantiating-jwt-token-provider,"['c#', 'unit-testing', 'asp.net-web-api', 'oauth-2.0', 'moq']",133,False,0,0
Using API-tests as Unit-tests in a microservice-application (heresy),"<p><em>Question contains heretic content user discretion advised.</em></p>
<p>My Company codes a website with many very small microservices. I have the task to write unitTests.</p>
<p>I figured it would take a lot of mocking because we have a lot of inter-service communication. Those APIs are very likely to change -&gt; mocks break easily.</p>
<p>So instead of all the pain of these mocks i decided to write api-tests checking for expected error-messages, status code, correct calculations and checked the res-obj against our swagger-documentation.</p>
<p>I even did TDD with these api-tests and I must say it worked really well. But it doesn't have much in common with unit-testing</p>
<p>What do you guys think about this?</p>
<p>Positive:</p>
<ul>
<li>even tho i Test a API my &quot;Units&quot; are pretty small</li>
<li>tests don't need that much maintenance</li>
<li>tests are written very fast because no mocking is required.</li>
<li>I only need a few tests to catch all the errors. Good error-handling indicates location of error pretty well.</li>
<li>units are very intertwined anyways. Services are extremely dependent.</li>
<li>errors of depending services are always being catched and logged. I then just run the test of the underlying service.</li>
<li>I can fix &quot;integration errors&quot; locally with my unit-tests</li>
</ul>
<p>Negative:</p>
<ul>
<li>If error is not perfectly logged it takes some time to find out where the error originated from.</li>
<li>Tests are not that performant. It takes about 20 seconds per service. Probably more as soon as they grow.</li>
<li>Some tests depend on the unit before them.</li>
</ul>
",https://stackoverflow.com/questions/73908794/using-api-tests-as-unit-tests-in-a-microservice-application-heresy,"['unit-testing', 'microservices', 'web-api-testing']",57,False,0,0
Tests stall for no obvious reason,"<p>I have been happily unit testing in Laravel 9 for the last few days and am gradually getting the hang of how to write tests for various circumstances. I ran many tests and was learning a lot when suddenly, for no obvious reason, the php artisan test command stopped working properly. Starting at about 11am today, the very first test in the very first test case executes successfully and then the whole thing just stalls: no other tests are attempted. There are no error messages and waiting prolonged periods doesn't result in the tests restarting on their own.</p>
<p>I've tried doing a CTRL-C to break out of the test and then started again. Same result. I've tried closing the terminal window, opening another and running php artisan test again. I've tried using a different terminal window outside of VS Code altogether. Same result. I've tried closing and re-opening VS Code. Same result. I've even rebooted the computer (I'm running Windows 10) but am getting exactly the same result. I just can't get beyond the first test in the first test case.</p>
<p>I can't think of anything else to try. The second test case has been run successfully many times so I can't believe it is the problem. Can anyone suggest what the problem might be and how I can get past it?</p>
<p>I'm using PHPUnit 9.x.</p>
<pre><code>UPDATE
</code></pre>
<p>As per Matias' suggestion, I ran <code>php artisan test -vvv</code> on my test suite. (I also renamed all of the files in the Unit Test directory so that they wouldn't run, except for the two ExampleTest test cases that were generated by Laravel, one for feature testing and one for unit testing.) The very long stacktrace pointed to an inability of the tests to connect to my local MySQL database. That made sense because I hadn't restarted XAMPP after the reboot. (Then again, I didn't see the urgency because none of the code I was testing used the database; they dealt with strings, arrays and collections.) I restarted XAMPP, including Apache and MySQL. Now, all tests the ExampleTest test cases completed. I renamed my Helper2Txxx.php to Helper2Test.php and assumed it would run smoothly now. Unfortunately, that <em>didn't</em> happen. Helper2Text.php don't run at all: the testing stopped as soon as the ExampleTest had finished.</p>
<p>I commented out all but the most trivial test in Helper2Test and it ran successfully. I uncommented a few tests at a time until I found the one that made all of the test cycle stop and that (unsurprisingly) turned out to be the last one I had written. Further investigation revealed that a small function I'd written to help with the testing was running into a memory error:</p>
<pre><code>Fatal error: Allowed memory size of 536870912 bytes exhausted (tried to allocate 264257536 bytes) in C:\Laravel\laragigs\tests\Unit\Helper2Test.php on line 154
</code></pre>
<p>It looks very much like I have to fix up my small function but I won't be able to do that to untilmorrow sometime. My working theory is that this memory error is the big problem that somehow breaks artisan test; somehow this kept the successful tests earlier in Helper2Test from displaying so that I had no idea where/why the test command was failing.</p>
<p>I'll update here as I learn more. I <em>think</em> I will be able to fix this problem myself but I'll leave the problem open in case I turn out to be wrong.</p>
<pre><code>UPDATE 2
</code></pre>
<p>Everything is working now. I reworked my small function to accomplish the same thing via explode() instead of strtok() and it now works perfectly with no memory issues.</p>
<p>Thank you, Matias, for reminding me that I can get diagnostics by using the -vvv subcommand! That was the critical step in figuring out what was wrong.</p>
",https://stackoverflow.com/questions/74723492/tests-stall-for-no-obvious-reason,"['laravel', 'phpunit']",141,False,0,0
Consuming files in UnitTests running in Azure DevOps Pipeline,"<p>I am running a collection of unit tests in an Azure DevOps Pipeline. The unit testing framework in use is MSTest.</p>
<p>Some unit tests load files that are inside the repo. Therefore the Property <code>Copy to Output Directory</code> is set to <code>Copy Always</code>.<br />
Down below you can see the property being set inside the <code>csproj</code> file.</p>
<pre class=""lang-xml prettyprint-override""><code>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;
  &lt;!-- shortened csproj file --&gt;

  &lt;ItemGroup&gt;
    &lt;None Update=&quot;TestFiles\sample.xml&quot;&gt;
      &lt;CopyToOutputDirectory&gt;Always&lt;/CopyToOutputDirectory&gt;
    &lt;/None&gt;
  &lt;/ItemGroup&gt;

&lt;/Project&gt;
</code></pre>
<h2>Test Method</h2>
<p>Inside the test, the file gets loaded as seen in the next code block.</p>
<pre class=""lang-cs prettyprint-override""><code>var path = Path.Join(&quot;TestFiles&quot;, &quot;sample.xml&quot;);
var fileStream = File.OpenRead(path);
</code></pre>
<h3>Local Run</h3>
<blockquote>
<p>I set the <code>verbosity</code> to <code>detailed</code> in order to see if the file gets copied or not.</p>
</blockquote>
<p>Running <code>dotnet test .\Project\Project.csproj --logger trx --verbosity detailed</code> locally, everything works as expected with the test results.<br />
Same applies for running the tests in Visual Studio.</p>
<h3>Pipeline</h3>
<p>I execute the tests inside an Azure DevOps Pipeline with the <code>DotNetCoreCLI</code> task.</p>
<pre class=""lang-yaml prettyprint-override""><code>trigger:
- none

pool:
  vmImage: ubuntu-latest

steps:
- task: DotNetCoreCLI@2
  displayName: Run Unit Tests
  inputs:
    command: test
    projects: Project/Project.csproj
    arguments: --verbosity detailed
</code></pre>
<p>I extracted the generated command from the pipeline logs: <code>/usr/bin/dotnet test /home/vsts/work/1/s/Project/Project.csproj --logger trx --results-directory /home/vsts/work/_temp --verbosity detailed</code>. I don't see any significant differences between my local command compared to the one being generated by the pipeline.</p>
<h4>MSBuild</h4>
<p>Indeed inspecting the local <strong>and</strong> Azure DevOps Pipeline logs, the file gets copied as expected.</p>
<pre><code>Copying file from &quot;/home/vsts/work/1/s/Project/TestFiles/sample.xml&quot; to &quot;/home/vsts/work/1/s/Project/bin/Debug/net6.0/TestFiles/sample.xml&quot;.
</code></pre>
<h4>Test Error</h4>
<p>The path matches the one from the MSBuild log <code>/home/vsts/work/1/s/Project/bin/Debug/net6.0/TestFiles/sample.xml</code>. Then again, I get a <code>FileNotFoundException</code>:</p>
<pre><code>System.IO.FileNotFoundException: Could not find file '/home/vsts/work/1/s/Project/bin/Debug/net6.0/TestFiles/sample.xml'.
</code></pre>
<h4><em>Pipeline debugging</em></h4>
<p>I tried to list all files inside the output directory adding the <code>continueOnError</code> key to the test task.</p>
<pre class=""lang-yaml prettyprint-override""><code># ...
tasks:
# ...
- script: ls -la /home/vsts/work/1/s/Project/bin/Debug/net6.0
- script: ls -la /home/vsts/work/1/s/Project/bin/Debug/net6.0/TestFiles
</code></pre>
<p>The first script action already fails with the following error message:</p>
<pre><code>ls: cannot access '/home/vsts/work/1/s/Project/bin/Debug/net6.0': No such file or directory
</code></pre>
<blockquote>
<p>At this point I'm just lost and don't know what to do about this seemingly simple problem... Any suggestions how I get the files containing test data to the unit test? Where is my mistake?</p>
</blockquote>
<h2>Update 1</h2>
<p>I tried to switch to xUnit. But it gave me the same <code>FileNotFoundException</code> as before. I don't think it's a problem with the test itself but with the Azure DevOps Pipeline environment.</p>
",https://stackoverflow.com/questions/74717913/consuming-files-in-unittests-running-in-azure-devops-pipeline,"['c#', '.net', 'azure-pipelines', 'devops', 'mstest']",473,True,2,1
Testing Azure Function - how to create fake HTTP request that includes an item in HttpContext,"<p>We have an azure functions project and it looks like the previous dev used a similar approach as described here for unit testing:
<a href=""http://dontcodetired.com/blog/post/Mocking-HttpRequest-Body-Content-When-Testing-Azure-Function-HTTP-Trigger-Functions"" rel=""nofollow noreferrer"">http://dontcodetired.com/blog/post/Mocking-HttpRequest-Body-Content-When-Testing-Azure-Function-HTTP-Trigger-Functions</a></p>
<p>It works well, except that I now need to inject a fake value for the the following string:</p>
<pre><code> HttpContext.Items[&quot;MS_AzureFunctionsRequestID&quot;]
</code></pre>
<p>cus at some point in the code, we do this:</p>
<pre><code> req.HttpContext.Items[&quot;MS_AzureFunctionsRequestID&quot;].ToString()
</code></pre>
<p>And right now, the unit test is failing because the fake request object doesn't include this field.</p>
<p>I've tried a few different things but so far, no dice.</p>
<p>Assuming I'm using the following code, where can I inject this fake string:</p>
<pre><code>private static Mock&lt;HttpRequest&gt; CreateMockRequest(object body)
{            
    var ms = new MemoryStream();
    var sw = new StreamWriter(ms);
 
    var json = JsonConvert.SerializeObject(body);
 
    sw.Write(json);
    sw.Flush();
 
    ms.Position = 0;
 
    var mockRequest = new Mock&lt;HttpRequest&gt;();
    mockRequest.Setup(x =&gt; x.Body).Returns(ms);
 
    return mockRequest;
}
</code></pre>
<p>I've tried to add an additional &quot;sw.Write()&quot; line and play around with the contents but I can't seem to get it working.</p>
<p>Thanks.</p>
<p>EDIT 1</p>
<p>So I changed the above method so it has one additional line:</p>
<pre><code>private static Mock&lt;HttpRequest&gt; CreateMockRequest(object body)
{            
    var ms = new MemoryStream();
    var sw = new StreamWriter(ms);
 
    var json = JsonConvert.SerializeObject(body);
 
    sw.Write(json);
    sw.Flush();
 
    ms.Position = 0;
 
    var mockRequest = new Mock&lt;HttpRequest&gt;();
    mockRequest.Setup(x =&gt; x.Body).Returns(ms);
    mockRequest.Setup(x =&gt;x.HttpContext.Items.Add(&quot;MS_AzureFunctionsRequestID&quot;, REQID));

    return mockRequest;
}
</code></pre>
<p>REQID is a new private const that has been defined in the same class as the CreateMockRequest() method.</p>
<p>This is the method that ultimately calls this code:</p>
<pre><code>    [Fact]
    public async void post_request_should_be_stored_in_queue_and_storage_table(){
       
        var messageQueue = TestFactory.CreateAzureStorageQueue();                        
        var request = TestFactory.CreateWidgetHTTPRequest();
        Console.Write(request.HttpContext.Items[&quot;MS_AzureFunctionsRequestID&quot;].ToString());

        
        var storageTable = TestFactory.SaveToStorageTable();              
        var widgetRequest = new WidgetRequest(storageTable);
        
        var response = (OkObjectResult)await widgetRequest.CreateWidget(request, messageQueue, logger);
        Assert.NotNull(response);
        Assert.True(((AzureStorageQueueTestClient&lt;string&gt;)messageQueue).Messages.Count &gt; 0);
    }
</code></pre>
<p>When it hits the console.write - the field is null.
Can I call setup on the mock object twice?<br />
how do I set x.body and x.HttpContext?</p>
<p><strong>EDIT 2</strong></p>
<p>I found this post:  <a href=""https://stackoverflow.com/questions/45239728/how-to-mock-httpcontext-current-items-with-nunit-and-rhino-mocks"">How to mock HttpContext.Current.Items with NUnit and Rhino Mocks</a></p>
<p>I'm trying to use the answer to adapt my code, but when I try to create the httpContext object, i'm getting a CS0144 error</p>
<p>&quot;Cannot create an instance of the abstract type or interface 'HttpContext'
&quot;Cannot create an instance of the abstract type or interface 'HttpResponse'</p>
<p>The code I'm playing around with so far just has this:</p>
<pre><code>    [Fact]
    public void can_create_http_context()
    { 
        const string REQUEST_GUID_FIELD_NAME = &quot;RequestGUID&quot;;        
        var httpContext = new HttpContext(new HttpRequest(&quot;&quot;, &quot;http://google.com&quot;, &quot;&quot;), new HttpResponse(new StringWriter()));

        HttpContext.Current = httpContext;


    }
</code></pre>
",https://stackoverflow.com/questions/71619847/testing-azure-function-how-to-create-fake-http-request-that-includes-an-item-i,"['c#', 'unit-testing', 'moq']",1241,False,2,0
How to mock the DOM with support for loading ES6 modules?,"<p>I've built a Node app, and am adding unit tests.  In my unit test file I need to create a mock DOM which has support for <code>&lt;script type='module'&gt;</code> tags.  In other words, into my mock DOM I need to insert HTML which loads a JavaScript file JS via a <code>&lt;script type='module'&gt;</code> tag.  Other than jest-dom, what options do I have to create such a mock DOM?</p>
<p><strong>Of Note</strong></p>
<ul>
<li>The jsdom package <a href=""https://github.com/jsdom/jsdom/issues/2475"" rel=""nofollow noreferrer"">does not have such support</a>.</li>
<li>The jest-dom package has such support.  But if possible, I would like to use Tape for my unit testing instead of Jest.</li>
</ul>
<p>If there are no other options, how might I get around my issue?  Would I have to refactor my code so it does not use such a tag?  Or at least, refactor things so my unit tests don't depend on that tag?</p>
<p><strong>Motivation Behind Question</strong></p>
<p>The motivation for this is this.  In my project I have an HTML file which renders a simple form to the DOM, and a separate JS module which is loaded on the same page and serves as the form handler (i.e. it makes a specific fetch request when the submit button is clicked). I originally had an integration test written using Jest (using jest-dom as the mock DOM), which does the following:</p>
<ul>
<li>Renders the HTML to the test DOM.</li>
<li>Populates the form  elements with test data.</li>
<li>Clicks the submit button in the test DOM.</li>
<li>Asserts that the correct fetch request is made.</li>
</ul>
<p>There were no issues with that test. I'm now trying to refactor my automated tests away from Jest to Tape, with jsdom as the mock DOM.</p>
<p>Thanks.</p>
",https://stackoverflow.com/questions/70654946/how-to-mock-the-dom-with-support-for-loading-es6-modules,"['javascript', 'unit-testing', 'dom', 'mocking']",169,False,1,0
How to debug NUnit tests in Visual Studio 2022,"<p>I'm very new to Unit Testing and trying to implement NUnit in a C# Dotnet Core 3.1 project.
I think the test is working, but I'd really like to debug (and single-step through) the test to make sure everything is working.</p>
<p>However, when I right-click on a test and select &quot;debug&quot;, two things happen (or not):</p>
<ol>
<li>I get an error saying that &quot;There were build errors. Would you like to continue and run tests from the last successful build?&quot; (and when I look in the output window, there are no errors but two warnings saying that &quot;ProjectData: Could not find project with GUID adf53ed2...&quot;.</li>
<li>Debugging doesn't happen (no breakpoints are hit) but the test &quot;runs&quot; and passes.</li>
</ol>
<p>I found a thread on Stackoverflow that said you had to set up an external program in the debug settings, but VS2022 does not have those screens or settings.</p>
<p>UPDATE: I created a stupid-simple dotnet core console project (and added NUnit in the same way) and debugging works just fine. So, it's something about the project I'm trying to add test to: it is a dotnet core 3.1 web project.</p>
<p>2nd UPDATE: so I created a stupid-simple dotnet core web project (and added NUnit) and debugging works just fine. So, it's something about my project (and probably related to that error message saying it can't find project guid: xxxxxxx (don't have it any longer).</p>
<p>3rd UPDATE: so I DELETED the NUnit test project (again) and re-created it and left it dirt-simple (just whatever VS2022 creates on open) and it debugs! Now to start adding code and find out what breaks it!</p>
<p>Thoughts?</p>
<p>TIA,</p>
",https://stackoverflow.com/questions/74209846/how-to-debug-nunit-tests-in-visual-studio-2022,"['c#', '.net-core', 'nunit', 'asp.net-core-3.1', 'visual-studio-2022']",346,True,1,2
CMake add_executable() failing to make executable and 3rd party library failing to untar,"<h2>Problem Background</h2>
<p>I am trying to incorporate UnitTest++ into my linux-based C++17 project template. I have done this on windows pretty easily, but I am running into major issues on linux for some reason.</p>
<p>I used Cmake 3.21 on Windows and I am <strong>currently using CMake 3.17.5 on Linux</strong>.</p>
<p>I downloaded the UnitTest++ source code from the <a href=""https://github.com/unittest-cpp/unittest-cpp"" rel=""nofollow noreferrer"">UnitTest++ Github</a>. and proceeded to throw the tar.gz into my 3rdParty folder in my ProjectTemplate. I have had major trouble getting it to build. So I have stripped out everything except for the one 3rd party library I added and the things that folder affects. So at this point all the main() functions are very simple. I am just expecting to see executables that do nothing.</p>
<h2>Problem Points</h2>
<ul>
<li>The main executable gets made, but the unit testing executable
(testExecutable) does not get made.</li>
<li>The build fully finishes with no errors even though an executable
failed to be made.</li>
<li>The UnitTest++ 3rd party library fails to untar with no errors
output.</li>
</ul>
<p>I have included the build output.</p>
<p>Why is the testExecutable not getting made? More importantly, why is my UnitTest++ failing to untar?</p>
<h2>Directory Structure</h2>
<pre><code>ProjectTemplate
    +3rdParty
        -CMakeLists.txt (3rd party cmake)
        -unittest-cpp-2.0.0.tar.gz
    +build
    +src
        -ClassTemplate.cpp (just a plain class file - compiles fine)
        -ClassTemplate.hpp (just a plain class file - compiles fine)
        -main.cpp (basic int main function)
    +UnitTests
        -CMakeLists.txt (unit test cmake)
        -UnittestcppMain.cpp (basic int main function)
    -CMakeLists.txt (root cmake)
    
</code></pre>
<h2>Build Output</h2>
<p>Output from cmake generation / configure</p>
<pre><code>[main] Configuring folder: ProjectTemplate 
[proc] Executing command: /usr/bin/cmake3 --no-warn-unused-cli -DCMAKE_EXPORT_COMPILE_COMMANDS:BOOL=TRUE -DCMAKE_BUILD_TYPE:STRING=Debug -DCMAKE_C_COMPILER:FILEPATH=/opt/rh/devtoolset-8/root/usr/bin/gcc -DCMAKE_CXX_COMPILER:FILEPATH=/opt/rh/devtoolset-8/root/usr/bin/g++ -S/path/to/ProjectTemplate -B/path/to/ProjectTemplate/build -G &quot;Unix Makefiles&quot;
[cmake] Not searching for unused variables given on the command line.
[cmake] -- The CXX compiler identification is GNU 8.3.1
[cmake] -- Check for working CXX compiler: /opt/rh/devtoolset-8/root/usr/bin/g++
[cmake] -- Check for working CXX compiler: /opt/rh/devtoolset-8/root/usr/bin/g++ - works
[cmake] -- Detecting CXX compiler ABI info
[cmake] -- Detecting CXX compiler ABI info - done
[cmake] -- Detecting CXX compile features
[cmake] -- Detecting CXX compile features - done
[cmake] Made it to this
[cmake] -- Configuring done
[cmake] -- Generating done
[cmake] -- Build files have been written to: /path/to/ProjectTemplate/build
</code></pre>
<p>output from build</p>
<pre><code>[main] Building folder: ProjectTemplate 
[build] Starting build
[proc] Executing command: /usr/bin/cmake3 --build /path/to/ProjectTemplate/build --config Debug --target ExecutableName -j 18 --
[build] Scanning dependencies of target ExecutableLib
[build] [ 25%] Building CXX object CMakeFiles/ExecutableLib.dir/src/ClassTemplate.cpp.o
[build] [ 50%] Linking CXX static library libExecutableLib.a
[build] [ 50%] Built target ExecutableLib
[build] Scanning dependencies of target ExecutableName
[build] [ 75%] Building CXX object CMakeFiles/ExecutableName.dir/src/main.cpp.o
[build] [100%] Linking CXX executable ExecutableName
[build] [100%] Built target ExecutableName
[build] Build finished with exit code 0
</code></pre>
<h1>UPDATE</h1>
<p>Thanks to 273K a solution was pointed out. I had accidentally switched my target from &quot;All&quot; to &quot;ExecutableName&quot; in VSCode. I have included a screenshot of the problem area and what it had to be set to in order to avoid this problem for future users who might be using VSCode and stumble on this question.</p>
<p>This is the bottom edge of VSCode, this is where the CMake extension puts it build options.</p>
<p><a href=""https://i.stack.imgur.com/RsVPF.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/RsVPF.png"" alt=""Fix"" /></a></p>
",https://stackoverflow.com/questions/72039195/cmake-add-executable-failing-to-make-executable-and-3rd-party-library-failing,"['c++', 'c++11', 'cmake']",302,True,0,1
Roslyn Source Generators Unit Testing error CS0234: The type or namespace name &#39;Console&#39; does not exist in the namespace &#39;System&#39;,"<p>I am trying to write a unit test for a simple Roslyn Source Generator based on the <a href=""https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.cookbook.md#generated-class"" rel=""nofollow noreferrer"">example here</a>.</p>
<p>Successfully ran both MsTest as well XUnit Tests as demonstrated in the <a href=""https://github.com/dotnet/roslyn/blob/main/docs/features/source-generators.cookbook.md#unit-testing-of-generators"" rel=""nofollow noreferrer"">Section B of the Unit testing of generators in the cookbook here</a>.</p>
<p>My full solution that I ran is <a href=""https://github.com/AvtsVivek/RoslynTuts/tree/main/src/Ex30001031"" rel=""nofollow noreferrer"">here for you to see</a>.</p>
<p>The problem is as follows. I added a bit more code to the generator. It now looks as below.</p>
<pre class=""lang-cs prettyprint-override""><code>            context.AddSource(&quot;MyGeneratedFile.cs&quot;, SourceText.From(@&quot;
namespace GeneratedNamespace
{
    public class GeneratedClass
    {
        public static void GeneratedMethod()
        {
            // generated code
            System.Console.WriteLine(&quot;&quot;Hello...&quot;&quot;);
        }
    }
}&quot;, Encoding.UTF8));
        }
</code></pre>
<p>Note that I <a href=""https://github.com/AvtsVivek/RoslynTuts/blob/487d4d34741c0cf06996ccb51117ec37e8655265/src/Ex30001031/SimpleCustomGenerator/CustomGenerator.cs#L23"" rel=""nofollow noreferrer"">added the following line</a></p>
<pre><code>System.Console.WriteLine(&quot;&quot;Hello...&quot;&quot;);
</code></pre>
<p>Now when I run the test, the test fails. Looking <a href=""https://github.com/AvtsVivek/RoslynTuts/blob/487d4d34741c0cf06996ccb51117ec37e8655265/src/Ex30001031/SimpleCustomGenerator.xUnitTests/CustomGeneratorTests.cs#L45"" rel=""nofollow noreferrer"">into the diagnostic object</a> I see the following error.</p>
<blockquote>
<p>error CS0234: The type or namespace name 'Console' does not exist in the namespace 'System' (are you missing an assembly reference?)</p>
</blockquote>
<p>Definitely I am missing something.</p>
<p>New to Roslyn stuff, so how can I make the test pass? How do I add some references to the assembly that holds System namespace?</p>
<p>One way is to simply comment out <a href=""https://github.com/AvtsVivek/RoslynTuts/blob/487d4d34741c0cf06996ccb51117ec37e8655265/src/Ex30001031/SimpleCustomGenerator.xUnitTests/CustomGeneratorTests.cs#L47"" rel=""nofollow noreferrer"">the offending line</a>, and yes its passing that way. But I am curious. How do I attach the required assembly that it is looking for?</p>
<h2>Update</h2>
<p>As @Youssef13 suggested, I added the <a href=""https://github.com/AvtsVivek/RoslynTuts/blob/f1f0eac633e666894ea4e18b2510a724d5ea00bb/src/Ex30001031/SimpleCustomGenerator.xUnitTests/CustomGeneratorTests.cs#L70"" rel=""nofollow noreferrer"">MetadataReference for the console type</a></p>
<p>So that issue is gone, but now the following appears.</p>
<blockquote>
<p>error CS0012: The type 'Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'</p>
</blockquote>
<p>I tried to add <a href=""https://github.com/AvtsVivek/RoslynTuts/blob/f1f0eac633e666894ea4e18b2510a724d5ea00bb/src/Ex30001031/SimpleCustomGenerator.xUnitTests/CustomGeneratorTests.cs#L71"" rel=""nofollow noreferrer"">another MetadataReference for System.Object here</a>, but this did not resolve it, the above persists.</p>
<p>How do I add a ref to System.Runtime?</p>
<h2>Update 2.</h2>
<p>Now I resolved it <a href=""https://github.com/AvtsVivek/RoslynTuts/blob/fe1737671579d7edec7d032b048d2505285746b5/src/Ex30001031/SimpleCustomGenerator.xUnitTests/CustomGeneratorTests.cs#L74"" rel=""nofollow noreferrer"">by adding the ref</a> as follows. <a href=""https://github.com/AvtsVivek/RoslynTuts/blob/fe1737671579d7edec7d032b048d2505285746b5/src/Ex30001031/SimpleCustomGenerator.xUnitTests/CustomGeneratorTests.cs#L74"" rel=""nofollow noreferrer"">Take a look at it here</a>.</p>
<pre class=""lang-cs prettyprint-override""><code>var systemRuntime = Assembly.Load(&quot;System.Runtime, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a&quot;);
var systemRuntimeRef = MetadataReference.CreateFromFile(systemRuntime.Location);
</code></pre>
",https://stackoverflow.com/questions/71900940/roslyn-source-generators-unit-testing-error-cs0234-the-type-or-namespace-name,"['roslyn', 'sourcegenerators', 'csharp-source-generator']",363,True,0,1
Unexpected behaviour - unable to access new elements in an array driven by an NSFetchedResultController (SwiftUI),"<p>I have a SwiftUI app that uses the MVVM design pattern in places where the underlying logic driving the View is either verbose or unit testing is advisable. In certain places I have taken to using a NSFetchedResultsController in conjunction with @Published properties and, early in development, this behaved as I would expect.</p>
<p>However, I have now encountered a situation where an addition to the CoreData store triggers controllerDidChangeContent and the array populated by controller.fetchedObjects has an appropriate number of elements but, for reasons I cannot fathom, I am unable to access the newest elements.</p>
<p>There is a certain amount of data processing which, as I'm working with an array by this point, I didn't think would cause a problem. I'm more suspicious that relationships may be responsible in some way and/or faulting is responsible (although adjusting faulting behaviour on the underlying fetch request failed to resolve the issue).</p>
<p>Interestingly, some similar code elsewhere in the app that uses @FetchRequest (because the View is simpler and so a ViewModel wasn't considered necessary) doesn't seem to suffer from the same problem.</p>
<p>Normally scattering debugging around has put me back on track but not today! I've included the console output - as you can see, as new entries (timestamped) are added, the total observation count increases but the most property which should reflect the most recent observation does not change. Any pointers would be gratefully received as always.</p>
<p>I can't really prune the code on this without losing context - apologies in advance for the verbosity ;-)</p>
<p><strong>ViewModel:</strong></p>
<pre><code>extension ParameterGridView {
    final class ViewModel: NSObject, ObservableObject, NSFetchedResultsControllerDelegate {
        @Published var parameters: [Parameter] = []

        @Published var lastObservation: [Parameter : Double] = [:]

        @Published var recentObservation: [Parameter : Double] = [:]

        let patient: Patient

        private let dataController: DataController

        private let viewContext: NSManagedObjectContext

        private let frc: NSFetchedResultsController&lt;Observation&gt;

        var observations: [Observation] = []

        init(patient: Patient, dataController: DataController) {
            self.patient = patient
            self.dataController = dataController
            self.viewContext = dataController.container.viewContext

            let parameterFetch = Parameter.fetchAll
            self.parameters = try! dataController.container.viewContext.fetch(parameterFetch)

            let observationFetch = Observation.fetchAllDateSorted(for: patient)
            self.frc = NSFetchedResultsController(
                fetchRequest: observationFetch,
                managedObjectContext: dataController.container.viewContext,
                sectionNameKeyPath: nil,
                cacheName: nil)
            try! self.frc.performFetch()

            observations = self.frc.fetchedObjects ?? []

            super.init()
            frc.delegate = self

            updateHistoricalObservations()
        }

        // MARK: - METHODS
        /// UI controls for entering new Observations default to the last value entered
        /// This function calculates the median value for the Parameter's reference range to be used in the event no historical observations are available
        /// - Parameter parameter: Parameter used to derive start value
        /// - Returns: median value for the Parameter's reference range
        func medianReferenceRangeFor(_ parameter: Parameter) -&gt; Double {
            let rangeMagnitude = parameter.referenceRange.upperBound - parameter.referenceRange.lowerBound

            return parameter.referenceRange.lowerBound + (rangeMagnitude / 2)
        }

        /// Adds a new Observation to the Core Data store
        /// - Parameters:
        ///   - parameter: Parameter for the observation
        ///   - value: Observation value
        func addObservationFor(_ parameter: Parameter, with value: Double) {
            _ = Observation.create(in: viewContext,
                                   patient: patient,
                                   parameter: parameter,
                                   numericValue: value)

            try! viewContext.save()
        }

        /// Obtains clinically relevant historical observations from the dataset for each Parameter
        /// lastObservation = an observation within the last 15 minutes
        /// recentObservation= an observation obtained within the last 4 hours
        /// There may be better names for these!
        private func updateHistoricalObservations() {
            let lastObservationTimeLimit = Date.now.offset(.minute, value: -15)!.offset(.second, value: -1)!
            let recentObservationTimeLimit = Date.now.offset(.hour, value: -4)!.offset(.second, value: -1)!

            Logger.coreData.debug(&quot;New Observations.count = \(self.observations.count)&quot;)
            let sortedObs = observations.sorted(by: { $0.timestamp &lt; $1.timestamp })
            let newestObs = sortedObs.first!
            let oldestObs = sortedObs.last!
            Logger.coreData.debug(&quot;Newest obs: \(newestObs.timestamp) || \(newestObs.numericValue)&quot;)
            Logger.coreData.debug(&quot;Oldest obs: \(oldestObs.timestamp) || \(oldestObs.numericValue)&quot;)

            for parameter in parameters {
                var twoMostRecentObservatonsForParameter = observations
                    .filter { $0.cd_Parameter == parameter }
                    .prefix(2)

                if let last = twoMostRecentObservatonsForParameter
                    .first(where: { $0.timestamp &gt; lastObservationTimeLimit }) {
                    lastObservation[parameter] = last.numericValue
                    twoMostRecentObservatonsForParameter.removeAll(where: { $0.objectID == last.objectID })
                } else {
                    lastObservation[parameter] = nil
                }

                recentObservation[parameter] = twoMostRecentObservatonsForParameter
                    .first(where: { $0.timestamp &gt; recentObservationTimeLimit })?.numericValue
            }
        }

        // MARK: - NSFetchedResultsControllerDelegate conformance
        internal func controllerDidChangeContent(_ controller: NSFetchedResultsController&lt;NSFetchRequestResult&gt;) {
            let newObservations = controller.fetchedObjects as? [Observation] ?? []
            observations = newObservations
            updateHistoricalObservations()
        }
    }
}
</code></pre>
<p><strong>NSManagedObject subclass:</strong></p>
<pre><code>extension Observation {
    // Computed properties excluded to aid clarity

    class func create(in context: NSManagedObjectContext,
                      patient: Patient,
                      parameter: Parameter,
                      numericValue: Double? = nil,
                      stringValue: String? = nil) -&gt; Observation {
        precondition(!((numericValue != nil) &amp;&amp; (stringValue != nil)), &quot;No values sent to initialiser&quot;)

        let observation = Observation(context: context)
        observation.cd_Patient = patient
        observation.timestamp = Date.now
        observation.parameter = parameter
        if let value = numericValue {
            observation.numericValue = value
        } else {
            observation.stringValue = stringValue!
        }

        try! context.save()
        
        return observation
    }

    static var fetchAll: NSFetchRequest&lt;Observation&gt; {
        let request = Observation.fetchRequest()
        request.sortDescriptors = [NSSortDescriptor(keyPath: \Observation.cd_timestamp, ascending: true)]

        return request
    }

    static func fetchAllDateSorted(for patient: Patient) -&gt; NSFetchRequest&lt;Observation&gt; {
        let request = fetchAll
        request.sortDescriptors = [NSSortDescriptor(keyPath: \Observation.cd_timestamp, ascending: true)]
        request.predicate = NSPredicate(format: &quot;%K == %@&quot;, #keyPath(Observation.cd_Patient), patient)

        return request
    }

    static func fetchDateSorted(for patient: Patient, and parameter: Parameter) -&gt; NSFetchRequest&lt;Observation&gt; {
        let patientPredicate = NSPredicate(format: &quot;%K == %@&quot;, #keyPath(Observation.cd_Patient), patient)
        let parameterPredicate = NSPredicate(format: &quot;%K == %@&quot;, #keyPath(Observation.cd_Parameter), parameter)
        let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [patientPredicate, parameterPredicate])

        let request = fetchAll
        request.predicate = compoundPredicate

        return request
    }
}
</code></pre>
<p><strong>Console output:</strong> (note observation count increments but the most recent observation does not change)
<a href=""https://i.stack.imgur.com/9gDFB.png"" rel=""nofollow noreferrer""><img src=""https://i.stack.imgur.com/9gDFB.png"" alt=""Console debug output"" /></a></p>
",https://stackoverflow.com/questions/71416548/unexpected-behaviour-unable-to-access-new-elements-in-an-array-driven-by-an-ns,"['mvvm', 'core-data', 'swiftui', 'nsfetchedresultscontroller']",43,True,-1,1
How do I add unit tests for scenarios that are dependent on values received from Url that loads the React Application using React Testing Library,"<p>I am working on React Application which renders form fields that are dependent on the values received from Url which loads this Application.
I am adding Unit tests to my Application using <code>Jest</code> and <code>React Testing Library</code>.</p>
<p>Below is an example of scenario’s that I need to cover in unit testing:</p>
<p>If I have value coming from the Url in this form type='A'. And my React component has if/else conditions to render page based one of the three possible values for type say A,B and C. Unit tests are always going to the else part and considering the value C.
Hence I am unable to unit test the scenarios for type='A' and type='B'.
And this is also reducing the coverage as I am not covering all the branches.</p>
<p>I tried updating the state for unit tests in test file but that did not help.
On going though some of the already answered questions and React Testing Library docs, It says that React Testing Library allows you test flows that are based on user interaction and does not recommend testing internal details like updating state etc.</p>
<p>There is no user triggered action on this Application which decides the value for type, as the type value is received from the Url and Url is dependent on path that user has taken to reach this Application (multiple entry points to this Application).</p>
<p>Is there a way I can mock this type value or add trigger to load the application by providing mock URL, so that I can cover other areas of my application as well as increase the branch coverage of the coverage report.</p>
<p>Thanks</p>
",https://stackoverflow.com/questions/73934501/how-do-i-add-unit-tests-for-scenarios-that-are-dependent-on-values-received-from,"['reactjs', 'jestjs', 'react-testing-library']",54,False,0,0
Unit testing functions that call WordPress core functions,"<p>Need to write a php unit test for <code>init()</code>.</p>
<pre><code>namespace My\Space;

class MyClass{
   public function init(){
       add_action('my_hook','my_function',10,0);
   }
}
</code></pre>
<p>All the test needs to do is assert that <code>add_action()</code> was called with the correct parameters.  If <code>add_action()</code> was a method of another class (lets call it <code>class WP_Functions</code>), then an instance of that class could be passed into the constructor of <code>MyClass</code> and used in <code>init()</code> to do the <code>add_action()</code>.  If so, Unit testing could pass in a mock of <code>WP_Functions</code> that asserts that <code>add_action()</code> be called with the desired input parameters.  But now that <code>add_action()</code> is not a class method, what is the best solution?</p>
<p>Here is what I've tried:</p>
<ul>
<li><p>Let <code>add_action()</code> run as it is defined by WordPress.  Remove actions from <code>my_hook</code>, call <code>init()</code> and then assert all the correct values are set in <code>$wp_filter['my_hook']</code>. Simple enough for the above case but gets complicated for functions that have conditions and/or add/remove many hooks/filters.</p>
</li>
<li><p>Define mock version <code>add_action()</code> in the <code>My\Space</code> namespace and make it simply <code>var_dump()</code> the input parameters.  Then all the test needs to do is expect that <code>init()</code> will outputs the <code>var_dump</code> for the desired parameters.  This works well but requires <code>add_action()</code> be redefined for every namespace in which its used.  This becomes difficult to manage when there are many namespaces and/or many other functions similar to <code>add_action()</code> that require mock versions.  Also can get complicated if the callback function is member of <code>MyClass</code> such that it is specified as <code>[ $this, 'callback_name' ]</code>.  Plus, it utilizes <code>var_dump()</code> for a non-intended purpose.</p>
</li>
<li><p>Create a public method of <code>MyClass</code> that called <code>add_action</code> that calls the WordPress <code>add_action()</code>.  If so, testing can create a mock of <code>MyClass</code> that expects it's <code>add_action</code> method to be called with the desired parameters.  However, this requires an extra function call.  Plus it would require every class that calls <code>add_action()</code> to somehow have it's own <code>add_action</code> method.</p>
</li>
</ul>
<p>Is there a better solution?</p>
",https://stackoverflow.com/questions/73666538/unit-testing-functions-that-call-wordpress-core-functions,"['wordpress', 'unit-testing', 'mocking']",37,False,0,0
Using Vue3 with modules in asp.net razor pages,"<p>At the end of the nightmarish razor code my employer wants us to write, I need to load a script block to run Vue3 on top of the rendered html.</p>
<p>Unfortunately, what I need to be able to do is way beyond the simple things they were doing with vue. I have already created various components that I want to use, and I was loading them in my standalone vueJs project in main.js.</p>
<p>However this doesn't work in their simplistic format, it fails on &quot;import&quot; which can't be done outside of a module:</p>
<pre><code>@section Scripts{
  &lt;script src=&quot;https://unpkg.com/vue@3&quot;&gt;&lt;/script&gt;
  &lt;script&gt;
    import { createApp } from &quot;vue&quot;;
    import PopupManager from &quot;/vue3/src/services/PopupManager.js&quot;;
    //import Validator from &quot;/src/services/Validator.js&quot;;
    import dayjs from &quot;dayjs&quot;;
    import App from &quot;./App.vue&quot;;
    import Datepicker from '/vue3/node_modules/vuepic/vue-datepicker';
    import '/vue3/node_modules/vue-datepicker/dist/main.css'
    import PopUp from &quot;/vue3/src/controls/PopUp.vue&quot;;
    const app = Vue.createApp({
      data(){ 
        return { 
            model: @Html.Raw(JsonSerializer.Serialize(Model))
        };
      },
    })

    app.provide(&quot;dayjs&quot;, dayjs);
    app.config.globalProperties.$dayJs = dayjs;
    app.provide(&quot;PopUpManager&quot;, PopupManager);
    app.config.globalProperties.$popUpManager = PopupManager;
    app.provide(&quot;Validator&quot;, Validator);
    app.config.globalProperties.$validator = Validator;
    app.component(&quot;DatePicker&quot;, Datepicker);
    app.component(&quot;PopUp&quot;, PopUp);
    app.mount('#vueAppRoot');
  &lt;/script&gt;
}
</code></pre>
<p>So how do I create modules out my components that I can load?</p>
<p>I have seen stack overflow answers that discuss &quot;vue-template-compiler&quot; in this context but they are extremely opaque about:</p>
<ul>
<li><p>How you setup the project.</p>
</li>
<li><p>How you use it in the razor pages.</p>
</li>
</ul>
<p>It doesn't help that the &quot;vue-template-compiler&quot; project has such terrible documentation itself.</p>
<p>I also don't like the idea of just pointing to a cdn and not compiling the modules or unit testing them. I would like for them to be built like they would for a real vueJs app.</p>
<p>I have a partial answer. You have to load your components as javascript in the script section:</p>
<pre><code>@section Scripts {
  &lt;script type=&quot;text/javascript&quot; src=&quot;https://unpkg.com/vue@3.2.40&quot;&gt;&lt;/script&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;~/js/vue/icons/IconHelp.js&quot;&gt;&lt;/script&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;~/js/vue/icons/IconState.js&quot;&gt;&lt;/script&gt;
  &lt;script type=&quot;text/javascript&quot;&gt;
    const { createApp, ref, computed } = Vue;
    let vueApp = createApp({
      data() { return {
        model: @Html.Raw(JsonSerializer.Serialize(Model)),
        data: {
          acceptedAddress: false,
        },
      },
      methods: {
        showPopup() {
            this.$popUpManager.showPopup(&quot;AddressPopup&quot;, null);
        },
      }
    });
    vueApp.component(&quot;IconHelp&quot;, IconHelp);
    vueApp.component(&quot;IconState&quot;, IconState);

    vueApp.mount('#vueAppRoot');
    console.log(typeof IconHelp);
  &lt;/script&gt;
}
</code></pre>
<p>This also means that you have to write the components like this:</p>
<pre><code>const IconState = {
  template:
    `&lt;span class=&quot;icon iconState&quot;&gt;
      &lt;svg viewBox=&quot;0 0 15192 15190&quot;&gt;
        &lt;path :class=&quot;{ medGray: !complete, iconColor: complete }&quot; d=&quot;M7596 0c4195,0 7596,3400 7596,7595 0,4195 -3401,7595 -7596,7595 -4195,0 -7596,-3400 -7596,-7595 0,-4195 3401,-7595 7596,-7595z&quot;/&gt;
        &lt;template v-if=&quot;!complete&quot;&gt;
          &lt;path class=&quot;lightGray&quot; d=&quot;M7596 748c3782,0 6848,3066 6848,6847 0,3782 -3066,6847 -6848,6847 -3782,0 -6848,-3065 -6848,-6847 0,-3781 3066,-6847 6848,-6847z&quot;/&gt;
        &lt;/template&gt;
        &lt;template v-else&gt;
          &lt;path class=&quot;white&quot; d=&quot;M12087 6142c422,-423 422,-1113 0,-1536 -423,-422 -1113,-422 -1536,0l-4196 4196 -1714 -1714c-422,-423 -1113,-423 -1535,0 -423,423 -423,1113 0,1536l2481 2481c423,423 1113,423 1536,0l4964 -4963z&quot;/&gt;
        &lt;/template&gt;
      &lt;/svg&gt;
    &lt;/span&gt;`,
  name: &quot;IconState&quot;,
  props: {
    complete: {
      type: Boolean,
      default: true,
    },
  },
};
</code></pre>
<p>And of course any stylesheet has to be global, loaded separately.</p>
<p>On top of this ASP.Net javaScript debugging seems totally messed up on the ill-conceived project I'm working on.</p>
<p>I'm getting an error about:</p>
<pre><code>Uncaught SyntaxError: Unexpected token ':' (and a line number in the generated razor page)
</code></pre>
<p>but clicking on it doesn't show any code. Lovely. Any suggestions on how to make javaScript debugging actually work would be very helpful.</p>
",https://stackoverflow.com/questions/73975354/using-vue3-with-modules-in-asp-net-razor-pages,"['vue.js', 'vuejs3', 'razor-pages']",662,False,0,1
Is it a good idea to instantiate a class A in constructor B (While the constructor A requires a B object),"<p>So I don't know if this is a good  approach or not:</p>
<pre class=""lang-java prettyprint-override""><code>
class A {

    B b;

    A() {
        this.b = new B(this);
    }
}

</code></pre>
<pre><code>class B {
    A a;

    //* Requires the A object as a parameter */
    B(A a) {
        this.a = a;
    }
}
</code></pre>
<p>The reason I did this is that the class B must hold the A object in order to operate (Think of the class A as a  &quot;holder&quot; for class B)</p>
<p>However, this leads to many issue, I am not sure if this is an anti-pattern or not, but when I'm doing Unit Testing class A, it would be hard for me to mock or omit object B as there's no dependency injection.</p>
<p>I don't think I can implement the dependency injection pattern here as the B object NEEDS object A to operate, so passing it in as a parameters to the constructor would not work.</p>
<p>The only solution I have thought of is to make a <code>setUp</code> method, like so:</p>
<pre><code>// In the A class
public void setUp(B b) {
    this.b = b;
}
</code></pre>
<p>This would successfully separate the testing and the actual application from themselves, while adhering to the dependency injection pattern. Though, I am not 100% sure with this approach.</p>
<p>I am just not sure if this approach is ideal or not.</p>
<p>Edit: The post that was linked to this &quot;duplicate&quot; one does not directly pertain to my problem. The one that was referenced got a <code>StackOverflowError</code>, while mine does not, furthermore, that post's constructor does not include any parameters.</p>
<p>To further clarify my existing issue: my <code>A</code> class is the <code>ClientClass</code>, and the <code>B</code> is the <code>AccountController</code> class. The <code>AccountController</code> handles all of the accounts of the CLIENT, and each client has one <code>AccountController</code>, it handles things such as logging in and out, account creation and deletion, and track the current account. Other classes reference the <code>ClientClass</code> object to also get the <code>AccountController</code>, I did this mainly for readability.</p>
",https://stackoverflow.com/questions/74446231/is-it-a-good-idea-to-instantiate-a-class-a-in-constructor-b-while-the-construct,['java'],65,False,0,0
Is &quot;this&quot; static? Checking for Static in the constructor,"<p>I need to determine if a member T of class T is a static member, in the constructor.  I expect this will involve checking some attributes of &quot;this&quot;, but I haven't been able to determine what to look for.</p>
<pre><code>public class Thing
{
    public static readonly List&lt;Thing&gt; ListOfStaticThings = new();
    public static readonly Thing StaticThing1 = new (&quot;StaticThing1&quot;);
    public static readonly Thing StaticThing2 = new (&quot;StaticThing2&quot;);
    public static readonly Thing StaticThing3 = new (&quot;StaticThing3&quot;);
    public Thing NonStaticThing = new(&quot;NonStaticThing&quot;);
    public string Name { get; set; }
    private Thing(string name) 
    {
        Name = name;
        if(this.IsStatic)  //how to determine if the thing being constructed is static?
        { ListOfStaticThings.Add(this);}
    }

}
</code></pre>
<p>How do I identify if the <code>Static</code> attribute is applied to <code>this</code>?</p>
<p>*** UPDATED ***</p>
<p>In this example, both StaticThing and NonStaticThing will be constructed using the private constructor.  However, only the StaticThing should be added to the ListOfStaticThings when constructed. The full implementation will have 20+ static readonly fields of the class type.</p>
<p>I've already verified that the ListOfStaticThings will contain the StaticThing.</p>
<p>The ListOfStaticThings has multiple uses.  This is on the path to <a href=""https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types"" rel=""nofollow noreferrer"">Enumeration Classes</a>, with this list containing all the possible Things (such as account statuses) permitted by the class.  In addition, the ListOfStaticThings can be passed to EFCore.HasData to seed the data in the table.  It can also be used for data validation in unit testing because it contains all the data and is persisted in the model.</p>
<p>However, all those use cases are beyond the scope of this question.  The piece I'm looking for is how to identify if the &quot;this&quot; being constructed is static so I can add it to the ListOfStaticThings.  I want StaticThing1, 2 &amp; 3 to be in the list, but not NonStaticThing.</p>
<p>*** Final Update ***
As pointed out by McAden's answer, this is not necessary because the non-static member of T cannot be added to class T without causing an infinite recursion overflow.  Since only static members of T can be added, there is no need to determine if they are also static in the constructor.</p>
",https://stackoverflow.com/questions/72635092/is-this-static-checking-for-static-in-the-constructor,"['c#', '.net', 'system.reflection']",111,True,-1,2
Is it possible to spy on an imported function within a Vue SFC using Vitest and Vue Test Utils?,"<p>I'm working on unit testing all of my components, and I've hit a bit of a snag (or maybe a misunderstanding of how to properly test).</p>
<p>I have a component that receives some parameters from the store, and then calls a series of functions that mostly return an input string with some transformations applied.</p>
<p>This looks something like the following:</p>
<pre><code>&lt;script setup lang=&quot;ts&quot;&gt;
import { someTextTransform } from '../utilities/someTextTransform';
...
let parsedText = store.input;

if (store.applySomeTextTransform) {
  parsedText = someTextTransform(parsedText);
}
</code></pre>
<p>I have already tested these functions themselves, so to me it seems like testing the actual output of the calls is unnecessary and I instead could just test to see if the functions have been called.</p>
<p>Here is a snippet on spying from the Vitest docs</p>
<blockquote>
<p>Mocking functions can be split up into two different categories; spying &amp; mocking.</p>
</blockquote>
<blockquote>
<p>Sometimes all you need is to validate whether or not a specific function has been called (and possibly which arguments were passed). In these cases a spy would be all we need which you can use directly with <code>vi.spyOn()</code>.</p>
</blockquote>
<p>This is exactly what I want. I want only to know whether or not the function has been called. The functions themselves are simple enough that they do not require additional setup (i.e., mocking is not required).</p>
<p>However looking through the docs of Vue Test Utils I don't see a way to do this. It looks like a more common way to do this is to mock the functions first and then you can spy on them more easily, but then I would have to create mocks that don't actually mock the functions which seems like I'm adding code to my codebase for no benefit other than a weird workaround.</p>
<p>I may just be missing something on how to do this, but I might also be approaching the testing in a suboptimal way so any advice is appreciated.</p>
",https://stackoverflow.com/questions/73198955/is-it-possible-to-spy-on-an-imported-function-within-a-vue-sfc-using-vitest-and,"['vue.js', 'unit-testing', 'vue-test-utils', 'vitest']",494,False,3,0
Using WebApplicationFactory to do E2E testing with .Net 6 (minimal api),"<p>Im trying to get E2E/UI testing (selenium, playwright) to work with my unit testing framework.</p>
<p>The basic idea it to use MSTest and the WebApplicationFactory to spin up a &quot;real server&quot; from within my unit tests. The reason for doing this would be to simply avoid having to deploy/release my application for testing (I guess this could be done by using containers etc, sadly.. Im not allowed to use containers). Im also thinking that doing it this wasy would be a &quot;neat&quot; way of mocking any code that calls external services, and be able to create multiple tests with different scenarios for those external calls.</p>
<p>I have searched the web for a way of doing this, but all I can find are posts about how to do this in previous .Net versions (2.1-5), but since .Net 6 the &quot;startup ceremonial&quot; code has changed and the standard way is now to use the minimal API.</p>
<p>Here is a blog post from Scott.H where he is basically doing exactly what Im planing to do, but with .Net 2.1: <a href=""https://www.hanselman.com/blog/real-browser-integration-testing-with-selenium-standalone-chrome-and-aspnet-core-21"" rel=""nofollow noreferrer"">https://www.hanselman.com/blog/real-browser-integration-testing-with-selenium-standalone-chrome-and-aspnet-core-21</a></p>
<p>What I have done so far is creating a custom class that inherits from WebApplicationFactory.</p>
<p>basically:</p>
<pre><code>class MyAppFactory : WebApplicationFactory&lt;Program&gt; {

}
</code></pre>
<p>And I can use that perfectly fine for integration testing. However.. the server thats initialized when using that class does not accept http-calls, so I cant reach that using a web browser, and neither can selenium.</p>
<p>I tried to follow Scotts blog post. But for some reason the:</p>
<pre><code>protected override TestServer CreateServer(IWebHostBuilder builder)
</code></pre>
<p>Is never called.. (not sure if that has with minimal APIs and .Net 6 to do).</p>
<p>Has anyone managed to use the WebApplicationFactory and .Net 6 Minimal API to spin up an &quot;actual server&quot; in memory that accepts http-calls?</p>
",https://stackoverflow.com/questions/71541576/using-webapplicationfactory-to-do-e2e-testing-with-net-6-minimal-api,"['testing', '.net-6.0']",1645,True,2,2
Object reference not set to an instance of an object at ASP.NET MVC Session on Unit Testing using Fake it Easy,"<p>I have an ASP.NET MVC 4 project with a controller that calls an external WCF to authenticate user login on the <code>VerifyAccount</code> method. This external WCF returns an <code>AuthModelUserVerification</code> class back to the controller and creates a <code>Session</code> containing a user id:</p>
<pre><code>[HttpPost]
public ActionResult VerifyAccount(string username, string password) {

    AuthModelUserVerification result = lms_client.VerifyAccount(username, password);

    if (!result.isAuthenticated)
        return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);

    Session[&quot;SID&quot;] = result.userid;

    return new HttpStatusCodeResult(HttpStatusCode.OK);
}
</code></pre>
<p>Below is the structure of the <code>AuthModelUserVerification</code> from the WCF:</p>
<pre><code>public class AuthModel
{
    public class UserVerification {
        public int? userid { get; set; }
        public bool isAuthenticated { get; set; }

        public UserVerification()
        {
            userid = null;
            isAuthenticated = false;
        }
    }
}
</code></pre>
<p>I am trying to make a unit test on <code>VerifyAccount</code> method to test the status code being returned to the browser under certain conditions. I am using <strong>MSTest (.NET)</strong> and <strong>Fake it Easy</strong> mocking framework. The issue lies upon setting the value on the <code>Session[&quot;SID&quot;]</code></p>
<pre><code>Session[&quot;SID&quot;] = result.userid;
</code></pre>
<p>I am receiving the following error on this line when I debug the test:</p>
<blockquote>
<p>Object reference not set to an instance of an object</p>
</blockquote>
<p>While debugging the test, everytime I hover to the <code>Session[&quot;SID&quot;]</code>, it says null but the <code>result.userid</code> shows it has a value of <strong>1</strong> since I am passing a value to it via calling the mock service I made. Please see the implementation of my test here:</p>
<pre><code>private readonly AuthController _controller_Auth;
private readonly ILMS_Service _lms_service;

public Auth_UnitTest() {
    _lms_service = A.Fake&lt;ILMS_Service&gt;();
    _controller_Auth = new AuthController(_lms_service);
}

[TestMethod]
public void VerifyAccount_Success()
{
    //Arrange
    string username = &quot;admin&quot;;
    string password = &quot;sampleP@sswoRd&quot;;
    int userID = 1;

    int expected_response_code = 200;
    var session = A.Fake&lt;HttpSessionStateBase&gt;();

    A.CallTo(() =&gt; session[&quot;SID&quot;]).Returns(userID);

    A.CallTo(() =&gt; _lms_service.VerifyAccount(username, password))
        .Returns(new AuthModelUserVerification
        {
            userid = userID,
            isAuthenticated = true
        });

    //Act
    var result = _controller_Auth.VerifyAccount(username, password) as HttpStatusCodeResult;

    //Assert
    Assert.AreEqual(expected_response_code, result.StatusCode);
}
</code></pre>
<p>The mock is working since the <code>isAuthenticated</code> has the value of <code>true</code> when I debug it. It's the <code>Session</code> that isn't working. Even making a fake <code>HttpSessionStateBase</code> didn't resolve the issue. I am new to unit testing and I am still exploring things, any help would be apprecited. Thanks!</p>
<h2>UPDATE</h2>
<p>Based on @Blair Conrad's answer I ended up with this code on my test.</p>
<pre><code>private readonly AuthController _controller_Auth;
private readonly ILMS_Service _lms_service;

private readonly HttpContextBase httpContext;
private readonly HttpResponseBase httpResponse;
private readonly HttpSessionStateBase httpSession;

public Auth_UnitTest() 
{
    // Mock WCF
    _lms_service = A.Fake&lt;ILMS_Service&gt;();

    // SUTs
    _controller_Auth = new AuthController(_lms_service);

    // Fake session
    httpContext = A.Fake&lt;HttpContextBase&gt;();
    httpResponse = A.Fake&lt;HttpResponseBase&gt;();
    httpSession = A.Fake&lt;HttpSessionStateBase&gt;();

    A.CallTo(() =&gt; httpContext.Response).Returns(httpResponse);
    A.CallTo(() =&gt; httpContext.Session).Returns(httpSession);
}

[TestMethod]
public void VerifyAccount_Authorized()
{
    //Arrange
    string username = &quot;admin&quot;;
    string password = &quot;sampleP@sswoRd&quot;;
    int? userID = 1;

    int expected_statusCode = (int)HttpStatusCode.OK;
    string expected_description = &quot;Authorized&quot;;

    var context = new ControllerContext(new RequestContext(httpContext, new RouteData()), _controller_Auth);
    _controller_Auth.ControllerContext = context;

    A.CallTo(() =&gt; _lms_service.VerifyAccount(username, password))
        .Returns(new AuthModelUserVerification
        {
            userid = userID,
            isAuthenticated = true,
            isActive = true
        });

    //Act
    var _authUser = _controller_Auth.VerifyAccount(username, password) as JsonResult;
    dynamic result = _authUser.Data;

    //Assert
    Assert.AreEqual(expected_statusCode, result.statusCode);
    Assert.AreEqual(expected_description, result.description);
}
</code></pre>
<p>From what I can understand, you need to fake the <code>HttpContextBase</code>, <code>HttpResponseBase</code>, and finally <code>HttpSessionStateBase</code> to fake the session being used on my controller. This works wonderfully as it have the expected values. I made the fakes of these classes as global and faked them on my test constructor class. If someone found a potential issue on my implementation, please let me know. Thanks!</p>
",https://stackoverflow.com/questions/73895997/object-reference-not-set-to-an-instance-of-an-object-at-asp-net-mvc-session-on-u,"['c#', 'asp.net-mvc', 'unit-testing', 'mstest', 'fakeiteasy']",440,True,1,1
How to start writing Unit Tests for SpringBoot(The proper way)?,"<p>I'm new to the world of unit testing in Spring and with some research I think I'll be using Junit5 with mockito and AssertJ library for the same. I am just starting out and it does look really confusing.</p>
<p>1st Question: Do we write our units first?? meaning our controller methods or service methods or any unit.. Do we write those firsts and then write tests for them or Do we first design our tests thinking ok, this methods needs to do this so I'll be writing my tests and then actually implement what I have to implement? I know this a bit silly of a question but I want to know how people go about it this in their work.</p>
<p>2nd Question: Suppose we write our tests, it fails for a certain unit. After it fails, what should be my first approach i.e. should I be thinking that the way I wrote the test was bad, so I need to properly write the test in order for the test to pass, or should I be like, ok my unit must have been bad, I'll change or refactor my code right away and then again test it after the refactoring? What is the 'thing' to do just after your test fails for some unit?</p>
<p>3rd Question/Help: Testing simple CRUD methods seems okayish  and there are a lot of resources for it although it's still confusing.. Could someone recommend me a github repo or a link or any source where unit tests have been written for some complex functions with some actual logic inside it and not only CRUD operations? I want to see how tests are written for the logic inside the code and how things are actually tested.</p>
<p>Any help would be highly valued. Thank-you, Have a good day.</p>
",https://stackoverflow.com/questions/71792871/how-to-start-writing-unit-tests-for-springbootthe-proper-way,"['java', 'spring-boot', 'unit-testing', 'junit', 'assertj']",233,False,1,1
Malformed axios request after POSTing body with Buffer from pdf file,"<p>I am writing node.js aws lambda. I am getting base64 encoded body of multipart/form-data from another aws lambda, then i am parsing it using parse-multipart-data, doing some validation, and then using form-data to create a bit different multipart/form-data body and use axios to POST it to Salesforce api.</p>
<p>The problem is that when i append Buffer of pdf file to form and try to send request with that form as body, it malforms whole body, instead of looking normally it is an 8k chars string (not sure what that is tbh) when i check outgoing body through nock, when testing it through mockbin i get internal server error in requests history, when deployed on dev aws environment connected to dev salesforce environment and testing it i get 503 after timeout.</p>
<p>It is quite bizarre since when i append even a large buffer through <code>new Buffer(10000)</code> to form it works fine. No idea how this buffer is different than the one from pdf file.</p>
<p>I did a lot of googling and trial and error on it but i haven't found anything, but here are also some other facts i noticed off the top of my head:</p>
<ul>
<li>body is being malformed only in outgoing request, checking form beforehand shows correct body</li>
<li>using jpeg file also breaks request body</li>
<li>using .txt file works fine (prints correct multipart/form-data body in mockbin and when unit testing)</li>
<li>using other parsers or axios alternatives didn't help</li>
<li>using Buffer from file in request other than multipart/form-data seem to also malform body same way when not encapsulated for example in json object</li>
<li>tried using filestream of local file thats same as one being send to me, same result</li>
<li>using workbench to manually create some multipart/formdata request to salesforce works fine</li>
</ul>
",https://stackoverflow.com/questions/74143193/malformed-axios-request-after-posting-body-with-buffer-from-pdf-file,"['node.js', 'axios', 'multipartform-data']",147,False,1,0
"Running a test for every file in a directory, dynamically","<p>I have an application written in C++, configured with CMake, tested using Catch2, the tests are invoked through CTest.</p>
<p>I have a fairly large list of files that each contain captures of messages that have caused an issue in my application in the past. I currently have a single test that runs through each of these files serially using code that looks approximately like:</p>
<pre><code>TEST_CASE(&quot;server type regressions&quot;, &quot;[server type]&quot;) {
    auto const state = do_some_setup();
    for (auto const path : files_to_test()) {
        INFO(path);
        auto parser = state.make_parser(path);
        for (auto const message : parser) {
            INFO(message);
            handle(message);
        }
    }
}
</code></pre>
<p>The message handler has a bunch of internal consistency checks, so when this test fails, it typically does so by throwing an exception.</p>
<p>Is it possible to improve this solution to get / keep the following:</p>
<ul>
<li>Run the initial <code>do_some_setup</code> once for all of the tests, but then run the test for each file in parallel. <code>do_some_setup</code> is fairly slow, and I have enough files relative to the number of cores that I wouldn't want to have to do setup per file. It would also be acceptable to run <code>do_some_setup</code> more than once, as long as it's better than O(n) in the number of files.</li>
<li>Run the regression test on all the files, even when an earlier file fails. I know I could do this with a <code>try</code> + <code>catch</code> and manually setting a <code>bool has_failed</code> on any failure, but I'd prefer if there were some built-in way to do this?</li>
<li>Be able to specify the file name when invoking tests, so that I can manually run just the test for a single file</li>
<li>Automatically detect the set of files. I would prefer not having to change to a solution where I need to add test files to the test file directory and also update some other location that lists all of the files I'm testing to manually shard them</li>
</ul>
<p>I'm willing to write some CMake to manage this, pass some special flags to CTest or Catch2, or change to a different unit testing framework.</p>
",https://stackoverflow.com/questions/73007106/running-a-test-for-every-file-in-a-directory-dynamically,"['c++', 'unit-testing', 'ctest', 'catch2']",136,False,1,0
Difference of behavior between “set -e + source” and “bash -ec + source”,"<h1>Context</h1>
<p>While setting up a basic unit testing system, I ran into an odd issue.
My goal was to make sure all individual test scripts:</p>
<ul>
<li>were run with <code>set -e</code> to <strong>detect errors</strong>, <strong>without needing to explicitly set this</strong> in each file;</li>
<li>knew right away about the <strong>functions to be tested</strong> (stored in another file) <strong>without needing to explicitly source</strong> those in each test file.</li>
</ul>
<h1>Observations</h1>
<p>Let this be a <strong>dummy test file</strong> called <code>to-be-sourced.sh</code>. We want to be able to know <strong>if a command in it fails</strong>:</p>
<pre class=""lang-sh prettyprint-override""><code># Failing command!
false

# Last command is OK:
true
</code></pre>
<p>And here is a <strong>dummy test runner</strong>, which must run the test file:</p>
<pre class=""lang-sh prettyprint-override""><code>#! /usr/bin/env bash

if (
    set -e
    . to-be-sourced.sh
)
then
    echo 'Via set: =0'
else
    echo 'Via set: ≠0'
fi
</code></pre>
<p>This yields <code>Via set: =0</code>, meaning that the runner is happy. But it should not!
My hypothesis was:</p>
<blockquote>
<p><code>set -e</code> is not propagated within <code>.</code> sourcing, and as explained in the help for <code>.</code> and <code>source</code>, the exit status is the one of the last command.</p>
</blockquote>
<p>But then I came up with a workaround that works, but <em>also relies on <code>.</code></em>:</p>
<pre class=""lang-sh prettyprint-override""><code>if bash -ec '. &quot;$0&quot;' to-be-sourced.sh
then
    echo 'Via bash: =0'
else
    echo 'Via bash: ≠0'
fi
</code></pre>
<p>This yields <code>≠0</code> whenever a command in the test file fails, regardless of whether that command was the last one of the test file. As a bonus, I can toss any number of <code>. a/library/file.sh</code> within the <code>-c</code> command, so each test file can use all of my functions out of the box. I should therefore be happy, but:</p>
<p><strong>Why does this work, considering that the <code>-c</code> command also relies on <code>.</code> to load the test file (and I thought <code>bash</code>’s <code>-e</code> was equivalent to <code>set</code>’s <code>-e</code>)?</strong></p>
<p>I also thought about using <code>bash</code>’s <code>--init-file</code>, but it appeared to be skipped when a script is passed as a parameter. And anyway my question is not so much about what I was trying to achieve, but rather about the observed difference of behavior.</p>
<h1>Edit</h1>
<p>Sounds like <code>if</code> is tempering with the way <code>set -e</code> is handled.</p>
<p><strong>This</strong> halts execution, indicating <strong>failure</strong>:</p>
<pre class=""lang-sh prettyprint-override""><code>. to-be-sourced.sh
</code></pre>
<p>… while <strong>this</strong> goes into the <code>then</code> (not the <code>else</code>), indicating <strong>success</strong>:</p>
<pre class=""lang-sh prettyprint-override""><code>if . to-be-sourced.sh
then
    echo =0
else
    echo ≠0
fi
</code></pre>
",https://stackoverflow.com/questions/71619652/difference-of-behavior-between-set-e-source-and-bash-ec-source,['bash'],81,True,1,1
Migration of .NET Framework packages.config to PackageReferences removed most References and shows warnings and errors,"<p>I have a legacy .NET Framework solution (ASP.NET) which I am trying to slowly fix the technical debt for. I tried to move the packages.config to PackageReferences in 4 of the 5 projects in the solution (the non-ASP.NET ones). One of the projects, an old SpecFlow unit testing project, was &quot;migrated&quot; to the new format, however its References were mostly deleted and my project was unable to find all of the new packages even though the PackageReferences are now correctly referenced in the csproj file rather than the removed packages.config file.</p>
<p>All I did was that I changed the <em>Tools-&gt;Options-&gt;NuGet Package Manager</em> option to <strong>PackageReference</strong>, and then context-clicked the project to select the <em>Migrate to PackageReference</em> item. I also selected all of the Transitory(?) Packages in the list that it gave me. Then I let Visual Studio run its process. I am using Visual Studio 2019 but this solution was made with older software and versions (it did run in both VS 2017 and 2019 before this process).</p>
<p>I do see the NuGet packages when I am looking for them in the NuGet Package explorer window and looking at the installed window. At least I saw some of them (I did not do an exhaustive look as there are dozens of them).</p>
<ol>
<li>What is the cause of the References being deleted but not repopulating like my other projects?</li>
<li>Is there an easy way to restore my references or do I have to add them back in one at a time?</li>
<li>In the <em>Add Reference</em> popup, I cannot find my NuGet packages or what I could reference before. Where should they be located? I am missing everything from System and Microsoft packages to third party and our own third party packages?</li>
</ol>
",https://stackoverflow.com/questions/71055868/migration-of-net-framework-packages-config-to-packagereferences-removed-most-re,"['.net', 'nuget-package', 'specflow', 'packagereference', 'packages.config']",784,False,1,0
How to handle deploying and building a Typescript Node.js project with pm2 post-deploy,"<p>My project is a Node.js Express server written in Typescript using ESM.</p>
<p>Currently, my deployment process is as follows:</p>
<ul>
<li>Run deploy script on my local machine using pm2</li>
<li>Pull in latest changes from git repo onto Ubuntu server</li>
<li>Server runs <code>npm install</code> and builds Typescript Node.js project</li>
<li>Runs starter script in build/dist directory</li>
</ul>
<p>I have to build the app on my server because I do not push my <code>/dist</code> folder to my git repo, and the process is dependent on deleting and cloning the newest version of my repo.</p>
<p>But since I am deploying with the <code>production</code> flag, it only installs my dependencies (not my devDependencies). I've had to move dependencies over from devDependencies just so my app can build on the server without any complaints.</p>
<p>For example, I currently want to setup babel with my project because I'm having trouble unit testing ES Modules (a story for another time). But because of my current setup, I need to install all my babel dependencies as regular dependencies and not devDependencies. This upsets me. I can't seem to find the right solution for my use case.</p>
<p>Am I just supposed to push my build folder to my git repo so that I can just run the starter file without having to build? I don't really like the idea of pushing my build folder.</p>
<p>Do I just continue putting some devDependencies as regular dependencies so that I can build properly on my server? I would really like a layer of separation between my dev/regular dependencies. Right now it's getting garbled.</p>
<p>Here are some relevant config files:</p>
<p><code>package.json</code></p>
<pre><code>&quot;scripts&quot;: {
        &quot;build&quot;: &quot;rimraf dist &amp;&amp; tsc&quot;,
        &quot;test&quot;: &quot;c8 --all -r html -r text mocha&quot;,
        &quot;test-watch&quot;: &quot;npm run test -- -w&quot;,
        &quot;dev&quot;: &quot;concurrently --kill-others \&quot;tsc -w\&quot; \&quot;pm2-dev start ecosystem.config.cjs\&quot;&quot;,
        &quot;deploy&quot;: &quot;pm2 deploy ecosystem.config.cjs production&quot;
    }

</code></pre>
<p><code>ecosystem.config.cjs</code></p>
<pre><code>apps: [
        {
            name: 'brobot',
            script: 'dist/src/index.js',
            node_args: '--experimental-specifier-resolution=node',
            env: {
                NODE_ENV: 'development'
            }
        }
    ],
    deploy: {
        production: {
            user: process.env.AWS_USER,
            host: process.env.AWS_PUBLIC_IP,
            key: process.env.AWS_SSH_KEY,
            ref: 'origin/main',
            repo: 'git@github.com:somegitrepo',
            path: process.env.AWS_EC2_PATH,
            node_args: '--experimental-specifier-resolution=node',
            env: {
                NODE_ENV: 'production'
            },
            'post-deploy': 'npm install &amp;&amp; npm run build &amp;&amp; pm2 startOrRestart ecosystem.config.cjs --env production'
        }
    }
</code></pre>
<p><code>tsconfig.json</code></p>
<pre><code>{
    &quot;compilerOptions&quot;: {
        &quot;target&quot;: &quot;ES6&quot; /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */,
        &quot;module&quot;: &quot;ESNext&quot; /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
        &quot;sourceMap&quot;: true /* Generates corresponding '.map' file. */,
        &quot;outDir&quot;: &quot;dist&quot; /* Redirect output structure to the directory. */,
        /* Strict Type-Checking Options */
        &quot;strict&quot;: true /* Enable all strict type-checking options. */,
        /* Module Resolution Options */
        &quot;moduleResolution&quot;: &quot;node&quot; /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
        &quot;esModuleInterop&quot;: true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
        &quot;skipLibCheck&quot;: true /* Skip type checking of declaration files. */,
        &quot;forceConsistentCasingInFileNames&quot;: true /* Disallow inconsistently-cased references to the same file. */
    },
    &quot;exclude&quot;: [&quot;node_modules&quot;]
}

</code></pre>
<p>I really want to keep pm2 in my project, it has been very useful. I'm definitely overlooking something but I'm not sure how to best handle this post-deploy setup.</p>
",https://stackoverflow.com/questions/71784342/how-to-handle-deploying-and-building-a-typescript-node-js-project-with-pm2-post,"['javascript', 'node.js', 'typescript', 'deployment', 'pm2']",1670,True,1,1
MapStruct - Map Generic List to Non-Generic List containing different types,"<p>I am attempting to use MapStruct to convert between 2 internal models. These models are generated from the same specification and represent a large tree-like structure that is constantly being added to. The goal of using MapStruct is to have an efficient, low (non-generated) code way of performing this conversion that stays up to date with additions to the specification. As an example, my models would look like:</p>
<pre class=""lang-java prettyprint-override""><code>package com.mycompany.models.speca;

public class ModelSpecA {
    private String name;
    private int biggestNumberFound;
    private com.mycompany.models.speca.InternalModel internalModel;
    private List&lt;com.mycompany.models.speca.InternalModel&gt; internalModelList;
}
</code></pre>
<pre class=""lang-java prettyprint-override""><code>package com.mycompany.models.specb;

public class ModelSpecB {
    private String name;
    private int biggestNumberFound;
    private com.mycompany.models.specb.InternalModel internalModel;
    private List internalModelList;
}
</code></pre>
<p>with all of the expected getters and setters and no-arg constructors.
MapStruct is able to generate code for the mapping extremely easily with the code looking like:</p>
<pre class=""lang-java prettyprint-override""><code>interface ModelSpecMapper {
    ModelSpecB map(ModelSpecA source);
}
</code></pre>
<p>From unit testing and inspecting the generated code, the mapping is accurate and complete except in one regard: the mapping of the <code>internalModelList</code> member in each class. The generated code looks like the following:</p>
<pre><code>...
if (sourceInternalModelList != null) {
    specBTarget.setInternalModelList( specASource.getInternalModelList() );
}
...
</code></pre>
<p>I.e. It is mapping from the generic List&lt;com.mycompany.models.speca.InternalModel&gt; to the non-generic List without doing model conversion. This passes at compile time and runtime in unit tests, but will cause errors in later code when we expect to be able to cast to the SpecB version of the model.</p>
<p>So far, I've investigated if it is possible to force a mapping of the parameterized type in the source to its corresponding type without using expensive reflection operations, which would eliminate the gains from using MapStruct as a solution. This is my first experience with MapStruct, so there may be an obvious solution I am simply unaware of. Adding an explicit mapping is infeasible as I need this to be forward compatible with future additions to the model including new Lists.</p>
<p>TLDR; How do I use MapStruct to convert the contents of a generic List to a non-generic List? E.g. <code>List&lt;com.mycompany.a.ComplexModel&gt; --&gt; List</code> whose members are of type <code>com.mycompany.b.ComplexModel</code>.</p>
",https://stackoverflow.com/questions/72174634/mapstruct-map-generic-list-to-non-generic-list-containing-different-types,"['java', 'generics', 'mapping', 'mapstruct']",269,True,0,1
"EnsureDeletedAsync broken after upgrade, .NET 3.1 to .NET 6","<p>I'm working on a .NET Core application in Visual Studio 2022 on Windows 10. I'm using Entity Framework Core and, for unit testing, MSTest. I have the following code in my unit test project to initialize the database context and to clear the database between tests:</p>
<pre><code>public static MyDbContext DbContext;

...

public async static Task InitializeDatabase()
{
    ConfigureDbContext();
    try
    {
        await DbContext.Database.EnsureDeletedAsync();
    } catch(Exception e) // I just added this so I'd have a place to put a breakpoint for debugging
    {
        throw;
    }
}

private static void ConfigureDbContext()
{
    MemoryCacheOptions memoryCacheOptions = new MemoryCacheOptions
    {
        SizeLimit = 10000000
    };
    IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());
    DbContextOptions&lt;MyDbContext&gt; options = new DbContextOptionsBuilder&lt;MyDbContext&gt;()
        .UseInMemoryDatabase(&quot;DataInMemory&quot;)
        .Options;
    DbContext = new MyDbContext(options);
}
</code></pre>
<p>This worked fine under .NET Core 3.1. I migrated to .NET Core 6, including a move to the latest version of the Microsoft.EntityFrameworkCore packages. Now the call to <code>DbContext.Database.EnsureDeletedAsync()</code> throws the following exception:</p>
<blockquote>
<p>System.InvalidOperationException: 'There are multiple [ForeignKey] attributes which are pointing to same set of properties '{'ParentId'}' on entity type 'BusinessLine' and targeting the principal entity type 'BusinessLine'.'</p>
</blockquote>
<p>I'm confused by this in two ways. First, if the foreign keys are a barrier to the application figuring out how to accomplish this, why weren't they a barrier under .NET 3.1?</p>
<p>Second, according to <a href=""https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.databasefacade.ensuredeletedasync?view=efcore-6.0"" rel=""nofollow noreferrer"">the Microsoft documentation</a>, what <code>EnsureDeletedAsync</code> does is delete the database outright. Here, my confusion further branches in two directions. (a) If the database is being deleted outright, then what do the foreign key relationships among the tables within a database have to do with deleting the database altogether? (b) I see now that what's prescribed is for EnsureDeletedAsync to be followed by EnsureCreatedAsync. My code lacks the latter, yet, somehow, before the migration, my code worked.</p>
<p>So, does EnsureDeletedAsync delete data from tables while leaving the tables, as well as the database, in existence. Or does it wipe out the entire database? Can somebody help sort this out for me, and point me in the direction of a once-again working unit test project?</p>
<p><em><strong>Update:</strong></em> The code for BusinessLine is here:</p>
<pre><code>    public class BusinessLine
    {
        public int BusinessLineId { get; set; }

        [ForeignKey(&quot;DataDescriptor&quot;)]
        public int DataDescriptorId { get; set; }

        public int Level { get; set; }

        [ForeignKey(&quot;Parent&quot;)]
        public int? ParentId { get; set; }

        [ForeignKey(&quot;AssetClass&quot;)]
        public int? AssetClassId { get; set; }

        public string BusinessLineName { get; set; }

        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public string UpdatedBy { get; set; }

        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public DateTime UpdateDateTime { get; set; }

        // Foreign key relationships
        public BusinessLine Parent { get; set; }

        public AssetClass AssetClass { get; set; }

        public DataDescriptor DataDescriptor { get; set; }

        [ForeignKey(&quot;ParentId&quot;)]
        public List&lt;BusinessLine&gt; Sublines { get; set; }

    }
}
</code></pre>
<p>It has a foreign key relationship to itself because it's hierarchical.</p>
<p>The stack trace:</p>
<pre><code>   at Microsoft.EntityFrameworkCore.Metadata.Conventions.ForeignKeyAttributeConvention.UpdateRelationshipBuilder(IConventionForeignKeyBuilder relationshipBuilder, IConventionContext context)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.ForeignKeyAttributeConvention.ProcessForeignKeyAdded(IConventionForeignKeyBuilder relationshipBuilder, IConventionContext`1 context)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnForeignKeyAdded(IConventionForeignKeyBuilder relationshipBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnForeignKeyAddedNode.Run(ConventionDispatcher dispatcher)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.DelayedConventionScope.Run(ConventionDispatcher dispatcher)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Run()
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ConventionBatch.Dispose()
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelInitialized(IConventionModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelInitialized(IConventionModelBuilder modelBuilder)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.Model..ctor(ConventionSet conventions, ModelDependencies modelDependencies, ModelConfiguration modelConfiguration)
   at Microsoft.EntityFrameworkCore.ModelBuilder..ctor(ConventionSet conventions, ModelDependencies modelDependencies, ModelConfiguration modelConfiguration)
   at Microsoft.EntityFrameworkCore.ModelConfigurationBuilder.CreateModelBuilder(ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, ModelDependencies modelDependencies)
   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, ModelCreationDependencies modelCreationDependencies, Boolean designTime)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel(Boolean designTime)
   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()
   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.&lt;&gt;c.&lt;TryAddCoreServices&gt;b__8_4(IServiceProvider p)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSiteMain(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite, RuntimeResolverContext context, ServiceProviderEngineScope serviceProviderEngine, RuntimeResolverLock lockType)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite callSite, RuntimeResolverContext context)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(ServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.&lt;&gt;c__DisplayClass2_0.&lt;RealizeService&gt;b__0(ServiceProviderEngineScope scope)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()
   at Microsoft.EntityFrameworkCore.DbContext.get_ContextServices()
   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure&lt;System.IServiceProvider&gt;.get_Instance()
   at Microsoft.EntityFrameworkCore.Infrastructure.Internal.InfrastructureExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_Dependencies()
   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureDeletedAsync(CancellationToken cancellationToken)
   at [...].UnitTests.Overhead.Common.&lt;InitializeDatabase&gt;d__12.MoveNext() in [...].UnitTests\Overhead\Common.cs:line 195
</code></pre>
",https://stackoverflow.com/questions/72113630/ensuredeletedasync-broken-after-upgrade-net-3-1-to-net-6,"['c#', 'entity-framework-core', 'mstest']",269,True,0,1
Glib&#39;s event loop not quitting,"<p>I have a middleware program written in C++ using Glib main loop from glibmm. I also have unit tests for that program written using Google Test.</p>
<p>The program uses the AWS client library (aws-iot-device-sdk-cpp-v2) to communicate with the Amazon cloud. My code calls library functions, the library functions send messages to the cloud and when the functions accomplish something, they call my callbacks given to them as arguments. I call the library functions from the main thread and the callbacks are called from the library's internal worker thread.</p>
<p>To avoid need for mutual exclusion, my callbacks move the execution from the library's worker thread to the main loop before doing anything else. That happens with line <code>Glib::signal_timeout().connect_once([this]() { some_member_function(); }, 0);</code> which simply schedules some_member_function to be called as soon as possible.</p>
<p>For unit testing purposes, I have written a wrapper class that instead of calling the real library functions, simply uses that same Glib one-shot timer to call my callbacks.</p>
<p>In unit tests, I initiate some activity in the program by calling some function in it that contains those one-shot timers and then call run() for the main loop. My aim is to end each test by having a callback eventually call quit() for the main loop.</p>
<p>The problem I am facing is that this solution is somehow unstable. For some reason, calling quit() for the main loop is not working always, and when that happens, the tests get stuck. That happens sometimes often and sometimes rarely, and I haven't figured out any logic in that. My debug prints verify that it really gets called. It just doing nothing.</p>
<p>Is there something fundamentally wrong in what I am doing or what could be the problem here?</p>
",https://stackoverflow.com/questions/73454955/glibs-event-loop-not-quitting,"['c++', 'linux', 'event-handling', 'glib']",83,False,0,0
How to test an abstract superclass in Java,"<p>I'm a student studying software development (1st year) and the teaching language we are using is Java. We have covered basics, and most of OOP, but I've been practicing making a Shop Administration System and I've come up against something I can't reckon with.</p>
<p>I'm trying to <strong>unit test</strong> two classes which are <strong>both abstract superclasses</strong> of several other classes I plan on implementing, as per the UML below</p>
<p><a href=""https://i.stack.imgur.com/CduRY.png"" rel=""nofollow noreferrer"">Person Superclass and Employee subclass - both abstract</a></p>
<p>I've read through a series of posts on here and I see a lot of people were recommending things like power mock and mockito for making mock objects.  I'm probably trying to learn too much at once as it is but basically I landed on concrete &quot;wrapper&quot; private classes in the unit test class that i used to polymorphically create the Employee objects (technically EmployeeWrapper objects), then unit testing all the public methods through the wrapper class.</p>
<p>I'm vaugely familiar with the term &quot;bad code smell&quot; and this really stinks. Is there a standard way of testing abstract superclasses without using things like Mockito and Power Mock? Or do i just need to suck it up and use things like that?</p>
<p>This is the code for the classes (with all method bodies removed so you dont have to read through a load of unimportant details</p>
<pre><code>    import java.time.LocalDateTime;
    import java.util.Hashtable;
    import java.util.Iterator;

    public abstract class Employee extends Person {

        private double hourlyRate;
        private double hoursPerWeek;
        private LocalDateTime dateOfEmploymentStart;
        private LocalDateTime dateOfEmploymentEnd;
        private Hashtable&lt;LocalDateTime, Integer&gt; shifts;

        private static final double MINIMUM_WAGE = 8.0;

        /**
         * Constructor for Employee for all fields except dateOfHire, which is set to {@code LocalDateTime.now()}
         * 
         * @param name
         * @param email
         * @param phoneNumber
         * @param hourlyRate
         * @param weeklyHours
         * @throws IllegalArgumentException if name if blank or null
         */
        public Employee(String name, String email, String phoneNumber, double hourlyRate, double weeklyHours) throws IllegalArgumentException {
            super(name, email, phoneNumber);
            this.setHourlyRate(hourlyRate);
            this.setWeeklyHours(weeklyHours);
            this.setDateOfEmploymentStart(LocalDateTime.now());
            this.shifts = new Hashtable&lt;LocalDateTime, Integer&gt;();
        }

        /**
         * Constructor for Employee that sets name, email and phoneNumber to provided args; and sets hourly rate and weeklyHours to 0
         * 
         * @param name
         * @param email
         * @param phoneNumber
         * @throws IllegalArgumentException if name is blank or null
         */
        public Employee(String name, String email, String phoneNumber) throws IllegalArgumentException {
            this(name, email, phoneNumber, MINIMUM_WAGE, 0);
        }

        /**
         * Constructor for Employee that sets only name
         * 
         * @param name
         * @throws IllegalArgumentException
         */
        public Employee(String name) throws IllegalArgumentException {
            this(name, null, null);
        }
    }
</code></pre>
<p>and the Unit test class (with all test cases bar one removed, and that one method body is left empty - again to stop clutter:</p>
<pre><code>    import static org.junit.jupiter.api.Assertions.*;

    import java.time.LocalDateTime;
    import java.util.Hashtable;
    import java.util.Set;

    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;

    class EmployeeTest {

        private class EmployeeWrapper extends Employee {

            public EmployeeWrapper(String name, String email, String phoneNumber, double hourlyRate, double weeklyHours) throws IllegalArgumentException {
                super(name, email, phoneNumber, hourlyRate, weeklyHours);
            }

            public EmployeeWrapper(String name, String email, String phoneNumber) throws IllegalArgumentException {
                super(name, email, phoneNumber);
            }

            public EmployeeWrapper(String name) throws IllegalArgumentException {
                super(name);
            }
        }

        private String nameValid, emailValid, phoneNumberValid;
        private String nameInvalid, emailInvalid, phoneNumberInvalid;
        private double hourlyRateValid, hourlyRateInvalidLow;
        private double weeklyHoursValid, weeklyHoursInvalid;

        private final double DEFAULT_HOURLY_RATE = 8;
        private final double DEFAULT_WEEKLY_HOURS = 0;
        private final String DEFAULT_EMAIL = &quot;no email provided&quot;;
        private final String DEFAULT_PHONE_NUMBER = &quot;no phone number provided&quot;;
        private final double MINIMUM_WAGE = 8.0;

        private Employee employee;

        private Hashtable&lt;LocalDateTime, Integer&gt; shiftsValid, shiftsInvalidEmpty;

        private LocalDateTime dateTimeValid, dateTimePast, dateTimeFuture;

        @BeforeEach
        void setUp() throws Exception {

            // valid employee
            nameValid = &quot;testname&quot;;
            phoneNumberValid = &quot;123456789&quot;;
            emailValid = &quot;test@test.test.com&quot;;
            hourlyRateValid = 10.50;
            weeklyHoursValid = 7.5;

            employee = new EmployeeWrapper(nameValid, emailValid, phoneNumberValid, hourlyRateValid, weeklyHoursValid);

            // test data
            nameInvalid = &quot;&quot;;
            emailInvalid = &quot;.test@test.com&quot;;
            phoneNumberInvalid = &quot;&quot;;
            hourlyRateInvalidLow = 5;
            weeklyHoursInvalid = -10;

            dateTimeValid = LocalDateTime.of(2015, 6, 15, 13, 30);
            dateTimePast = LocalDateTime.MIN;
            dateTimeFuture = LocalDateTime.MAX;

            shiftsValid = new Hashtable&lt;LocalDateTime, Integer&gt;();
            shiftsValid.put(dateTimeValid, 6);
            shiftsValid.put(dateTimeFuture, 3);

            shiftsInvalidEmpty = new Hashtable&lt;LocalDateTime, Integer&gt;();

        }

        @Test
        void testEmployeeConstructorValidAllArgs() {
        }


    }

</code></pre>
<p>This is my first post of Stack Overflow so i apologise profusely if i have omitted any revelent details.</p>
<p>If you see any other stupid things i've done in the code I'll also gladly take any criticism!</p>
<p><strong>edit:</strong> thanks everyone for the responses they have been amazing, i really really appreciate it!</p>
",https://stackoverflow.com/questions/71038074/how-to-test-an-abstract-superclass-in-java,"['java', 'abstract-class']",600,True,0,2
Jasmine spy callFake not being reached when trying spy on a service method that is called inside ngOnInit,"<p>I am trying to set up some unit tests for a component that uses a service to perform HTTP requests to retrieve information from a database. I am very new to angular and unit testing so please be patient with me. In my test I am trying to spy on the function named <code>getClients</code> (this function is essentially a handler for the service that actually performs the HTTP requests) and call a fake function using <code>callFake</code>.</p>
<p>The issue I'm running into is that the <code>getClients</code> function is not being overridden which leads me to believe the spy does not work or is not spying on what I think it is. I can tell that it is not being called because the failure message references something from the real <code>getClients</code> function.</p>
<p><strong>Test Code</strong>:</p>
<p>My understanding here is that because the function I am trying to spy on is in the <code>ngOnInit</code> function I must define the spy first and then instantiate the component. I have also tried running the spy inside of <code>it</code> and that didn't work either.</p>
<pre><code>describe('handleID', () =&gt; {

    beforeEach(waitForAsync (() =&gt; {

        spyOn(service, 'getClients').and.callFake(() =&gt; {
            let companyList = [
                {
                    COMPANYDESCRIPTOR: &quot;Hello World Inc.&quot;,
                    COMPANYNAME: &quot;Hello World Inc.&quot;,
                    CUSTOMERID: &quot;abcdef123456&quot;,
                    CUSTOMERKEY: 123456
                }
            ]
            
            component.companySearchService.companies.next(companyList);
            return companyList;
        });

        fixture = TestBed.createComponent(CompanySearchComponent);
        component = fixture.componentInstance;
        service = component.companySearchService;
        fixture.detectChanges();
    }));

    it(&quot;should update component.companyForm.controls['selectedCompany'] to 'Hello World Inc.'&quot;, () =&gt; {
        component.companyForm = component._formBuilder.group({
            selectedCompany: ['']
        })
        

        component.pathToNameProp = 'COMPANYNAME';
        component.pathToIdProp = ['CUSTOMERID', 'CUSTOMERKEY'];

        let id = 123456;

        component.handleID(id);

        expect(component.companyForm.get('selectedCompany')).toBe('Hello World Inc.');
    })

})
</code></pre>
<p><strong>Actual function</strong>:</p>
<p>For the sake of clarity I provided the <code>getClients</code> function below. <code>dbService</code> is the database service that makes the API calls. <code>makeAnApiCall</code> returns an <code>observable</code> and the <code>subscribe</code> just passes the data to another handler that determines what to do with the data based on the <code>source</code>.</p>
<pre><code>getClients(endpoint, method, options = []) {
    this.loading.next(true);
    this.dbService
        .makeAnApiCall(endpoint, method, options)
        .subscribe(
            res =&gt; this.generateCompanyList(res, this.source.getValue())
        )
}
</code></pre>
<p><strong>Failure Message</strong>:</p>
<p>The failure message is referencing the obversable subscription that is returned from the database service's <code>makeAnApiCall</code> method. This leads me to believe that the spy is not being created at all or is spying on something else entirely.</p>
<pre><code>Failed: Cannot read properties of undefined (reading 'subscribe')
    at CompanySearchService.getClients (http://localhost:9876/_karma_webpack_/main.js:6343:13)
    at CompanySearchComponent.ngOnInit (http://localhost:9876/_karma_webpack_/webpack:/src/app/utilities/company-search/company-search.component.ts:98:39)
    ...
</code></pre>
<p><strong>Questions</strong>:</p>
<ol>
<li>Why is the spy not working?</li>
<li>Regarding the unit test, is there a <em>better</em> way to write unit tests when working with observables, promises, and HTTP requests that doesn't require completely avoiding them?</li>
</ol>
<p>Thanks in advance for any and all help!</p>
",https://stackoverflow.com/questions/72382819/jasmine-spy-callfake-not-being-reached-when-trying-spy-on-a-service-method-that,"['angular', 'typescript', 'unit-testing', 'rxjs', 'karma-jasmine']",1860,True,0,2
Is it possible to override/customize the behavior how a Spring Data Key-Value repository evaluates the id of an entity?,"<p>Hiho,</p>
<p>We are currently using Spring Data JPA to build a service. The service knows about some Entities. These entities define an identifier that is declared through <code>@javax.persistence.Id</code>. The service works like a charm in production. :)</p>
<p>Now we plan to write some tests for the use cases of this service. We could implement some <code>@SpringBootTest</code>s or <code>DataJpaTest</code>s but want to go into a different direction.</p>
<p>We recently saw a talk of Jakub Nabrdalik named <code>Improving your Test Driven Development in 45 minutes</code> and want to try in this service his approach of how to implement tests. Unit testing the features of a module (service) takes a big part of his idea. Therefore he provides a map based implementation of the repository layer to be able to unit test the features in an easy and very fast way.</p>
<p>Seen this, we thought about if we should implement the repository layer in the same way. But something in us struggled and we set down to reseach if such thing would already be available... and found Spring Data Key-Value.</p>
<p>Using Spring Data Key-Value in our unit test environment is quite easy. But we realized more or less immediatelly that the idea was not working out of the box.</p>
<p>We researched a bit and found out that we need to use <code>@org.springframework.data.annotation.Id</code> (and not <code>@javax.persistence.Id</code>) to get the test running. After adding this additional annotation the tests work quite fine. But the drawback is, that we need to declare two annotations on our id property.</p>
<p>Because we don't like to have things declared in our production code that is only necessary for our test environment we want to ask here if it is possible to override/customize the behavior how a Spring Data Key-Value repository evaluates the id of an entity?</p>
<p>Any hints and tipps are very welcome! :)</p>
",https://stackoverflow.com/questions/72618601/is-it-possible-to-override-customize-the-behavior-how-a-spring-data-key-value-re,"['java', 'spring', 'spring-data', 'spring-data-keyvalue']",61,False,0,0
How can I use addV to insert an unknown number of vertices in gremlin-java?,"<p>I'm trying to write a Java wrapper that will help me upsert (or even just insert) vertices in a Gremlin server.</p>
<p>I realize that different tools may support other methods, e.g. AWS Neptune (which is my primary target backend) has a bulk loading API that reads data from S3, but I'm trying to avoid things that are only supported by one implementation as my requirements may evolve to include supporting other backends (and I'd like to support at least TinkerGraph, for unit testing). I don't plan on upserting many vertices per batch; this is not for populating a huge graph from scratch, this is for adding to an existing graph from a stream of data.</p>
<p>The Tinkerpop documentation mentions <code>addVertex</code> but <a href=""https://tinkerpop.apache.org/docs/current/reference/#staying-agnostic"" rel=""nofollow noreferrer"">discourages its use</a>, recommending <code>g.addV()</code> instead. My problem with <code>g.addV()</code>, and the Gremlin DSL in general, is that although it's not too hard to write one-off queries with it (... assuming you understand Gremlin well, which I don't), is that I can't figure out how to build queries dynamically.</p>
<p>Given as input a set of vertices and their properties, with arbitrary cardinality (let's say it comes from a CSV file of anywhere between 1-100 lines), <strong>how do I dynamically build a graph traversal that upserts all of the vertices?</strong> Alternate question: Is there a backend-agnostic tool for loading a few hundred vertices' worth of data in a local or remote graph?</p>
<p>This seems to be a Java issue as much as a Gremlin one. I have tried building a graph traversal by composing functions with <code>Function#andThen(Function)</code> but I am quickly running into issues with Java's generics because graph traversal methods return <code>GraphTraversal&lt;S, E&gt;</code> where both S and E depend on the actual graph traversal method. E.g. <code>addV()</code> returns <code>GraphTraversal&lt;S, Vertex&gt;</code> and <code>addE()</code> returns <code>GraphTraversal&lt;S, Edge&gt;</code>.</p>
",https://stackoverflow.com/questions/74561587/how-can-i-use-addv-to-insert-an-unknown-number-of-vertices-in-gremlin-java,"['java', 'gremlin', 'gremlin-java']",47,True,0,1
