Click here to Skip to main content
15,886,761 members
Everything / DevOps / Unit Testing

Unit Testing

unit-testing

Great Reads

by Fred Song (Melbourne)
Angular 7 with .NET Core 2.2 - Global Weather
by Anton Angelov
Code samples in C# how to assert DateTime with delta. Write your own Validator for MSTest or use built-in methods in NUnit.
by Naveen Kosana
Learn how to write unit test cases using Jasmine framework for Angular Controllers
by Łukasz Bownik
The article describes an alternative approach to unit testing.

Latest Articles

by Daan Acohen
Boost your xUnit tests with detailed logging for clearer insights and easier debugging.
by Łukasz Bownik
The article describes an alternative approach to unit testing.
by Daan Acohen
Explains how to do multiple assertions using the Fluent Assertions library, without multiple validation lines

All Articles

Sort by Updated

Unit Testing 

7 Mar 2024 by Pete O'Hanlon
To import the Jest configuration, you need to use import type { Config } from "@jest/types"; Jest features sit under @jest, not jest.
14 Feb 2024 by Pete O'Hanlon
This is an impossible question for anyone but you to answer right now. When you post a question, you have to ask yourself, "if I cannot see my code, would there be enough detail and information for me to be able to answer the question?" Provide...
11 Feb 2024 by Sathiya Govindasamy
Mocking the inner methods didn't work, while calling original method inner methods are being called irrespective of mock What I have tried: I have one method and that has 2 inner methods that are being called based on condition. The inner...
15 Dec 2023 by Nathalie Olcese
I wan jest to do unit tests with jest and typescrip/react but my test fails because says there are syntax errors in my imports. This is my jest.cinfig.ts file and babelrc file { "env": { "test": { "presets": [ [ ...
1 Dec 2023 by Andre Oosthuizen
Your error suggests that, when you check the test case for the correct answer '"A"', it is not returning the result as expected. Your issue is that in the 'test_response' function, when the correct answer is provided '"A"', your assertion is...
1 Dec 2023 by CPallini
The following program def response(res): global score, correct res = res.upper() if res == correct: score = score + 1 return "Correct Answer!" else: print("Wrong Answer :(") return f"Correct Answer: {correct}" def...
1 Dec 2023 by Syed Taha Rizvi
This is the main function i have: def response(res): global score, correct res = res.upper() if res == correct: score = score + 1 return "Correct Answer!" else: print("Wrong Answer :(") ...
19 Oct 2023 by Daan Acohen
Boost your xUnit tests with detailed logging for clearer insights and easier debugging.
9 Oct 2023 by Łukasz Bownik
The article describes an alternative approach to unit testing.
14 Aug 2023 by Daan Acohen
Explains how to do multiple assertions using the Fluent Assertions library, without multiple validation lines
5 Apr 2023 by Virendra S from Bangalore, Karnataka
public class BaseHeaderRequest { public string MarketId { get; set; } public string StoreId { get; set; } public string DataVersion { get; set; } public string AcceptLanguage { get; set; } public override bool Equals(object...
5 Apr 2023 by mtoha
var object1 = new BaseHeaderRequest(); object1.MarketId = "MarketIdAbc"; object1.StoreId = "10986586"; object1.AcceptLanguage = "en"; string sJson = JsonConvert.SerializeObject(object1); var object2 =...
30 Mar 2023 by Virendra S from Bangalore, Karnataka
GetAbsoluteExpirationValue() SonarQube report says, this method is partially covered(Partially covered by tests, 1 of 2 conditions). But Resharper shows 100 % coverage. Can you help me what am I missing here? public MemoryCacheEntryOptions...
30 Mar 2023 by Richard Deeming
ReSharper is wrong. You test what happens when the configuration contains an invalid value; but you never test what happens when the configuration contains a valid value. There are four paths you need to test: ...
10 Jan 2023 by zhshqzyc
I have a class. public class VoiceElementsLine : ILine { public Guid LineId { get; set; } public TelephonyServer TelephonyServer { get; set; } public virtual ChannelResource ChannelResource { get; set; } public LanguageData LangInfo { get; set; } ...
10 Jan 2023 by DaveBlack
In your test, you are mocking the concrete class 'VoiceElementsLine'. You should be mocking interfaces - not concrete classes (though you are able to do so in Moq if the concrete class has a public default constructor). So, in your test you...
15 Dec 2022 by Sushma Prasad 2022
private void setCountryCodeData() { //getting countryCode try { mCountryCode = PreferenceManager.getPrefIsoCode(LoginActivity.this); if (mCountryCode != null || !mCountryCode.equalsIgnoreCase("")) { ...
15 Dec 2022 by Dave Kreskowiak
You really can't write proper unit tests for this. Unit testing controls the input to a method and evaluates its output. The method you posted takes no direct input and returns nothing. If you're going to unit test code, you have to consider...
27 Oct 2022 by Virendra S from Bangalore, Karnataka
I am new to unit testing, please help me with writing correct unit tests for below method. Functionality: It just calls one method internally & get the object, based on object value returns true/ false. public bool...
27 Oct 2022 by Graeme_Grant
Google search is your friend. 1. NUnit: nunit bool check - Google Search[^] finds this: Assert.True | NUnit Docs[^] 2. XUnit: xunit bool check - Google Search[^] finds this: Xunit.Assert.Equal(bool, bool) Example[^] For XUnit, I like using: ...
15 Aug 2022 by DiponRoy
How to delete all rows in EF Core 6 using alternate options
11 Aug 2022 by Virendra S from Bangalore, Karnataka
public ProductConfigDetails GetProductConfig() { ProductConfigDetails ProdConfigDetails; if (appsettingsconfiguration.UseMockData) { taxConfigDetails =...
27 Jun 2022 by Jackie Lloyd
I am new to Python and Flask, and have inherited some Python Flask code, and my task is to write tests for it - bad process I know but we are where we are :/ I have read lots of similar problems to mine but still none of them work in my...
22 Jun 2022 by Richard MacCutchan
Take a look at Testing Flask Applications — Flask Documentation (2.0.x)[^]
7 Jun 2022 by chandu sadineni
void DigitalButton_Process(HalDigitalButton* const pThis) { bool isState; uint32_t filteredValue; uint32_t isDiagnosticStable; uint32_t pinVal; Expect_FatalObjConstructedAndInitialized(pThis); pinVal =...
7 Jun 2022 by blog.vitorrubio.com.br
I had same problem and tried some workarounds 1) make your plugin classes to be necessarily sealed and filter only by sealed types var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(s =>...
7 Jun 2022 by C Pottinger
I am changing a project of mine to use plug-ins for certain components (called FeedReaders), instead of having them defined in the main solution. I am following the technique present here by Duke of Haren. I am also using NUnit as by unit testing...
12 Apr 2022 by Danpeking
Hi, we have a solution with some Live unit tests inside and also a separate solution which is linked and contains 'legacy' unit tests. The legacy tests run fine and are output to Azure pipeline test statistics correctly. However the Live ones are...
12 Apr 2022 by Rajeev Jayaram
I believe this issue isn't related to Azure. What do you mean by Live Unit Tests?. You issue is some unit tests are not discoverable, most likely due to missing references in your solution/project file. Also check your pipeline build project too...
3 Apr 2022 by guddi chhaterpur
hello, I have a method called onShowList() and I want to write a unit test case for it, I am a beginner with writing a test cases so please help public onShowList(): void { this.showList = !this.showList; if (this.showList) { ...
20 Jan 2022 by Member 15498374
Hello! I am writing a unit test case for a website, The website has a basic function of address update, the address update requires an authentic user login, so I am using the temporary token for that purpose in query-param (as a part of website...
20 Jan 2022 by thatraja
Found few fixes below Unauthorized User Error in Django Unit test - Stack Overflow[^] javascript - Django Rest Framework: HTTP 401 Unauthorized error - Stack Overflow[^] And read API documentation for more info. Authentication - Django REST...
3 Sep 2021 by James Walsh Jr
Unit testing Fluent Validation methods for data validation
13 Jun 2021 by Member 13927839
When I joined my company as a newcomer, I was exploring the unit test suite of the product code. It uses the gtest framework. But when I checked all the tests, they were testing the whole functionality by calling real functions and asserting...
28 Apr 2021 by Member 15175929
I have created a share button and on clicking that you have share app link option where you can share in various app. So I just wanted to test this sharing app. I am new in the android and till now I did not got any good material related to this...
6 Jan 2021 by Łukasz Bownik
A simple method to estimate the quality of a unit test suite that can give some insight into the subject beyond regular test coverage.
1 Nov 2020 by Shayalp1
Thank you for your solution @BillWoodruff, I have been attempting it but I just need someone to guide me. This is what I have so far using System.Collections; using System.Collections.Generic; using NUnit.Framework; using UnityEngine; using...
1 Nov 2020 by Shayalp1
Hi, I'm actually new to programming, I had an assignment to create a single screen game and now I have to conduct tests on it. I'm completely lost as to how to conduct the test in Visual Studio. Can anyone please assist me, I've been stuck on...
28 Oct 2020 by BillWoodruff
The Unity Test Framework package (formerly the “Unity Test Runner”) is a tool that allows you to test your code in both Edit mode and Play mode, and also on target platforms such as Standalone, Android, or iOS . For more information on other...
20 Sep 2020 by F-ES Sitecore
A discussion of what to unit test in your C# code and how to test it, including a section covering MVC
24 Aug 2020 by Member 14922145
when I tried to run and generate a code coverage report for multiple dll's that code is not working but same code is working for single dll getting error in the following code ---------------------------------------------------------------- ...
23 Jun 2020 by Richard MacCutchan
I have been looking at the Google Test documentation, and I think your test code is not correct. The test needs to call the function to be tested, and verify the results. See googletest/primer.md at master · google/googletest · GitHub[^] for the...
23 Jun 2020 by Member 14686752
I have written some unit test cases using Gtest framework. If I am trying to test the class whose constructor is making the object of another class, GTest is crashing. Code is as follows: User1.cpp class User1 { public: User1()...
19 Apr 2020 by Garth J Lancaster
Are you under the premise the PasswordHasher should be automatically called ? I did some research and wasn't convinced - I would have thought you'd need ApplicationUser user = _userManager.Users...; user.PasswordHash =...
19 Apr 2020 by Member 13081540
am working with Microsoft.AspNetCore.Identity.UserManager and I'm trying to mock the creation of a new user. In fact, it does create a new user with username, email etc. but the password hash property is still null. This is how I set up mock...
16 Apr 2020 by F-ES Sitecore
You can't, if you want your code to be unit testable you have to write it with unit testing in mind.
16 Apr 2020 by Member 14803912
Please help me how do I write a test for the following controller without changing the program code ??? ***ProductController:*** [HttpPost] [ValidateAntiForgeryToken] public async Task CreateProductAsync(ProductDTO objProduct) { ...
11 Mar 2020 by Vassili Kravtchenko-Berejnoi
Use of a narrow-focus strategy in test-driven-development
9 Mar 2020 by #realJSOP
You could load the excel file and the database table's schema into separate ADO datatables, and then compare the schemas between the datatables. Depending on how extensive your data type discovery is during the import process, you could also...
9 Mar 2020 by Member 13958707
I have a ssis package where it reads a folder with csv files and transform those files into sql server table. at the same time those csv files are moved to an archive folder. If there is any file with wrong extension or file format against the...
22 Feb 2020 by OriginalGriff
See here: The Differences Between Unit Testing, Integration Testing And Functional Testing[^]
22 Feb 2020 by yagami_md
hello everyone, i would like understand the difference between unit test and functional test, for example the (Create, Update, Delete) functions must treats by unit test or unit test ? reaaly i have confused between the both . What I have...
6 Jan 2020 by Member 14708673
I have a finished project that I submitted yesterday to a client, and this morning he said that he'd like it if I implemented a few Unit Testing Frameworks into the project; Jest for Unit testing : integration of Jest [ Test Runner ] Enzyme [ Container UI Test ] Storybook [ Component UI Test ]...
6 Jan 2020 by Dave Kreskowiak
If you didn't design your code with unit testing in mind, you've got a LOT of work to do to add that capability. You can't just a some uniting module and call it good. Your code has to be written to be testable, and that means writing your code against Interfaces. If you haven't done this, your...
6 Jan 2020 by Patrice T
Quote: I'm new to unit testing so I'm not quite sure how to use these Google is your friend : Unit testing - Wikipedia[^] Quote: and what to use these for It is used to check that your code gives expected results.
5 Jan 2020 by Paulo Zemek
I partially agree with the basic idea, but it fails when we need to deal with an issue no unit-test caught and the good developers and code-reviewers simply can't understand what's going on.
23 Nov 2019 by Coldcreek
I am new in testing field and want to go deeper into it.I Have very simple question." If suppose you have an eCommerce website say "www.abc.com" ,how will you find bugs in that website?"What are the simple ways to find bugs in that website?What are the most handy software testing...
28 Oct 2019 by Marcell Lipp
This tip shows how to unit test a private function in C++.
21 Oct 2019 by Member 14628015
How to compare 2 lists in c#? 1st list, DBvalues = [{ "_id" : ObjectId("5d98298f9110f5f13812f3c1"), "PartName" : null, "MAP" : null, "MPN" : null, "IsActive" : true, "Gtin" : "ab085347019069" }, { "_id" : ObjectId("5d98298f9110f5f13812f3c0"), "PartName" : null, "MAP" : null, "MPN" : null,...
21 Oct 2019 by Gerry Schmitz
Sum hash numbers. Or some "set" operations. Object.GetHashCode Method (System) | Microsoft Docs[^] Set Operations (C#) | Microsoft Docs[^]
28 Jul 2019 by Adam Tibi
One of the MVC mantras is that it allows unit testing your controllers. But, that doesn't mean you should. In my opinion, you should focus your unit testing valuable effort in more effective areas as the controller, if done right, doesn't require unit testing.
20 Jun 2019 by F-ES Sitecore
That code can't be unit tested. What is it you're actually testing? File.Exists? File.Copy? Those are third-party functions, you should just assume that they work. To make that code testable you'll need to create some kind of IFileManagement service that has Exists and Copy methods on it. ...
20 Jun 2019 by MAN CHUN LIEW
The sourceFile will pass in the path of the file and in destination which is the copy funciton will copy the sourceFile to it. public bool CopyFile(string sourceFile, string destinationFile) { if (File.Exists(sourceFile)) { ...
30 May 2019 by DavidTypemock
Disclaimer - I work at Typemock the unit-testing company. You can easily change the behavior of a method with our API, for example: WHEN_CALLED(MyClass::GetSomething()).Return(15); In that way, in all of your tests, GetSomehting will return 15. It will work on Non Static methods too
28 May 2019 by Gerry Schmitz
Only you know which parameters will work. c# - Setting a passed parameter to a specific value in Moq - Stack Overflow[^]
28 May 2019 by user 3008
In moq setup I am trying to assign the value of one of the argument to a string variable. Although I used callback but still the variable seems to have null value. What I have tried: I tried this Mock partialMockLunaService = new Mock(MockBehavior.Strict); ...
23 May 2019 by IlanGreen
I have a method that i need to test all of its branches. I can't find a way to assert the or verify the test is correct because both branches have almost the same behavior. btw - I can't change the given code I have tried verifying End and Write are called but they are being called in both...
23 May 2019 by AnotherKen
It is unclear what you mean. Assert is used in C# in various ways as a method that can be invoked to empower code to use higher permissions than it would normally have or to test a variable and throw an exception if it contains an unexpected value. It may be that you are confusing people by...
14 May 2019 by IlanGreen
I need to mock objects and change method behavior in c++. The problem is that Gmock requires my methods to be virtual in order to inherit from them and change the behavior but I am not able to change my methods to virtual. What I have tried: I have tried Typemock Isolator++, it can access any...
14 May 2019 by Richard MacCutchan
Take your pick: List of unit testing frameworks - Wikipedia[^].
9 Apr 2019 by Fred Song (Melbourne)
Angular 7 with .NET Core 2.2 - Global Weather
3 Apr 2019 by GregoryPres
Our team uses Typemock's Isolator as a mocking framework and it has the ability to test private methods. Simple Api for verifying private method calls: Isolate.Verify.NonPublic.WasCalled(, "PrivateMethodname"); Also, you can fake private instances and change their behavior which will help you...
2 Apr 2019 by jerry.nothstine
You can access the private methods with reflection: MethodInfo myPrivateMethod = typeof(MyClassBeingTested).GetMethod( "PrivateMethodName", "BindingFlags.NonPublic | BindingFlags.Instance); myPrivateMethod.Invoke( instanceOfMyClassBeingTested, new object[] { parameter1,...
2 Apr 2019 by IlanGreen
I just started a new job as a junior .Net developer and my first task is to cover a solution that has 80% success with unit-tests, in order to assure every piece of code is working correctly. I was able to make it to 37% after covering all public methods by simply calling them from my tests, but...
2 Apr 2019 by F-ES Sitecore
The bad news is that your task is probably impossible. Unit testing isn't something you can retro-fit to an application, it has to be written with unit testing in mind. Trying to retro-fit unit testing to an app not designed for it will often lead to major refactoring of the code. To cover...
1 Apr 2019 by BillWoodruff
1. please explain what this means: "a solution that has 80% success" 2. in general you do not unit test private methods; after all, by definition they are only used from the public API 3. of course, the architecture of an app can be so screwed up that you can't isolate certain classes; as you...
19 Dec 2018 by Iris Shing
I'm writing APIs using c#.Net Core One of my APIs is used to generate captcha then store to the session, I'm using Redis to store session here. And now I'm trying to write a unit test for the APIs. Cause the login API needed to pass captcha, so I need to get the captcha value from the session....
8 Nov 2018 by DMEvans
A discussion of three options for the creation of simple .NET types without affecting the testability of your class
19 Oct 2018 by Sean Rand
Getting the most from your test runner
28 Aug 2018 by Richard MacCutchan
The different types of test projects are designed specifically for the different languages. You can only use one of the options that target C++.
28 Aug 2018 by Member 13784265
since i am very beginner here i have been trying to test my c++ program.whenever i get into visualc++ -> Test i get these two "native unit test project" and "managed unit test project".but in c# i get "unit test project". What I have tried: How can i get "unit test project" option in c++ as...
2 Aug 2018 by dharmesh.parekh
There will be two unit test methods 1. first will check whether InterpreterCostAuthorisedDate is set with current time or not / you can check whether date field is null or not Assert.IsNotNull(InterpreterCostAuthorisedDate) 2. second will check whether InterpreterCostAuthorisedDate is set...
2 Aug 2018 by user 3008
I have got the below set of code if (entity.InterpreterCostAuthorised && entity.InterpreterCostAuthorisedDate == null) { entity.InterpreterCostAuthorisedDate = DateTime.UtcNow; } else if (!entity.InterpreterCostAuthorised) ...
6 Jul 2018 by Agarwal1984
Hello, When i am running my Unit Test project,so its getting error from mvc application" System.NullReferenceException: 'Object reference not set to an instance of an object.' System.Web.HttpContext.Current.get returned null. " I have tried in MVC Application. Please help me. Thanks in...
6 Jul 2018 by F-ES Sitecore
You get an error but don't tell us what line it is on so I'm not sure what kind of help you are expecting. However from the error message it seems somewhere in the code you haven't posted you are using "System.Web.HttpContext.Current", however your unit test is running in the context of your...
21 Jun 2018 by John M. Dlugosz
How can an automated test program test that something is rejected at compile time?
17 Jun 2018 by Mehdi Gholam
You learn anything by doing it, it's that simple. As for TDD : 1) Write a test/usage code for what you want the output to be. 2) Implement the actual code to reach the output from a specified input, and make step 1 pass. 3) Repeat the above.
17 Jun 2018 by GregoryPres
I wanted to help some of my student friends and explain the concept of TDD. As I don't have the time for it, I wanted to know if there's a faster/better way to learn the concept and basics of TDD for beginners. I know there are plenty of courses, blogs, guides. I'm interested to know how did...
15 Jun 2018 by Scyldshefing
I would agree that as presented the test does not test the void method. It does not even verify that an expected exception is thrown when a certain condition arises. All it does it verify that something runs and does not throw an exception. Void method can be tested but you will need to look at...
15 Jun 2018 by User 4180254
Greetings. I have a method returning VOID and I have written below Unit test with "Microsoft.VisualStudio.TestTools.UnitTesting" for it. Is there any better alternative to do so? What I have tried: using (var uow = new UOW.SalesEntityUOW()) { try { uow.MyMethodCall(); // This...
4 Jun 2018 by Anele Ngqandu
Hi I have method I want to test and I get this error Invoke or BeginInvoke cannot be called on a control until the window handle has been created. i understand this because of the form needs to run first but any alternatives? public partial class ImportForm : Form{ public ImportForm() ...
2 Apr 2018 by F-ES Sitecore
First off if it needs a database it isn't a unit test; unit tests are to check your logic, not what data you have in a database or connectivity. Those kind of tests are integration tests and will be done elsewhere, probably as a separate process. Unit tests should be able to run when the...
2 Apr 2018 by Jamie888
Hi, may I know is there any tool/library/generator that i can refer to in order to generate general unit test method? For example, i have a method that goes to DB to retrieve data, i need to ensure that method does not return null. For traditionally way, i need to code a unit test to check for...
10 Mar 2018 by Carlos Luis Rojas Aragonés
Formatting your rails specs with rspec_pacman_formatter
8 Mar 2018 by jimmyHuey
I have a function like following, this is a rudux to provide EstateList. import {render} from "react-dom"; import React from "react"; import {Provider} from "react-redux"; import store from "./Store"; import EstateList from "../estates/estateList/estateList"; function estateList() { ...
8 Feb 2018 by RahulMittal2018
SQL unit testing with SQL Server data tools (SSDT)
27 Sep 2017 by Todiruta Costel Nicusor
Hello, I am trying to rule a test on my code and I get an exception like this System.NullReferenceException: Object reference not set to an instance of an object. Here is my code : public class Class1 { XLDriver CANDemo = new XLDriver(); XLClass.xl_driver_config...
27 Sep 2017 by Bernhard Hiller
Overall, that's a terribly bad code: PrintFunctionError requires a user to interact with the console. Whenever that function will be called within a Unit Test (or run on a Web Server, a Windows Service etc.), it will just hang. A return value is not meant to indicate if an exception happened or...