Click here to Skip to main content
15,886,806 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 

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 Feb 2014 by __Veereshkumar
HiI was breaking my head over it for the past hour and finally found it. :)U just have to create a default.aspx page in your web service project..!following is the link that should solve your doubt...http://msdn.microsoft.com/en-us/library/ms243399(v=vs.90).aspx
12 Jun 2014 by _Noctis_
Different ways of achieving unit testing for your projects
26 Jul 2014 by _Noctis_
How to Unit Test private methods using wrappers and preproccesor directives
26 Jun 2013 by A. K. Das
Dear AllIs It possible to unit test, constructor in c#, if yes how if not why Plz response .Thanks
1 Jan 2013 by Abhinav S
You could try using the MolesEraseStaticConstructor.More about it here - http://research.microsoft.com/en-us/projects/pex/molesmanual.pdf[^].
28 Jan 2013 by Abhinav S
To install the unit test framework, you will need to reinstall Visual Studio.Note that the framework is not available in the express editions.
3 Feb 2013 by Abhinav S
For unit testing the BLL, you can always consider using the Microsoft Visual Studio Testing Framework or a third party like Nunint.For a mocking framework, you can consider using Moles[^].
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.
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...
24 Mar 2014 by Alexander Dymshyts
I have a method that I want to test with moq:public List GetValidRecords(Entities context) where T: class, IGetListOfTables{ try { return context.Set().Where(x => x.Valid == 1).ToList(); } catch (Exception ex) { throw new...
29 Feb 2016 by Alexandr Surkov
My experience of using C++ with microcontrollers
23 Jan 2013 by Alpman
I have a question about generating a new type while writing a unit test in Visual Studio 2010.I have a project "Donk" for the code and a test project "DonkTest" for the unit tests. The test project has a reference to the project "Donk".In my unit test I write something likeDonk d =...
5 Jun 2013 by amnk.info
try firebughttps://addons.mozilla.org/en-US/firefox/addon/firebug/[^]
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...
11 Mar 2012 by Andreas Gieriet
How to define RelationAssert as an extension to the VisualStudio Assert class.
20 May 2013 by Andreas Gieriet
If you need to know how many times an external interface method is called, use some mocking framework. See also What C# mocking framework to use?[^].These frameworks provide means to assert how many times and with what parameters you expect the method to be called.If the method is an...
11 Jun 2013 by andyharman
Temporarily freeze time by injecting a thread-safe time bubble into your C# code.
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() ...
29 Nov 2016 by Ankit Rana
While doing unit testing, i am not able to get collection back from dbset after add new entity in dbset, it throw an exception 'Collection was modified'Here is my code setup[TestMethod][TestCategory("Skill Category")]public void Create_Skill_Category(){ var category = new...
29 Nov 2016 by Ankit Rana
The error occurred in moq Dbset because I m not updating the reference of GetEnumerator after adding new Entity in DB set.Code : public class Utility { public static Mock> GenerateMockEntity(List entityList) where TEntity : class { var list = new...
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...
9 Dec 2014 by anssary2010
if there is article in simple detail explorer Repository pattern and what is the mean of Loosely Coupled
15 Sep 2015 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.
20 Dec 2015 by Anup Raghavendra Hosur
In this article we will be discussing about unit testing and Rhino Mocks
21 Jan 2014 by Ashley Davis
Documents my experiment building a flowchart with web technologies.
9 May 2013 by ashok yede201
Hello,I have created one RESTful wcf srevice.I wanna to know best Unit testing tool to test Rest Wcf Service.I was trying to use NUnit test tool, but I thought it is not best tool to test REST wcf Service as I was getting many errrors.Please tell meThanks in advance.
11 Oct 2013 by ASP.NET Community
ASP.NET MVC: How to start Unit TestingWhy Unit Testing?Why should you write Unit Tests? Here are some points which are mostly mentioned if
13 Nov 2014 by ASRAAR
Hi , I want to test a static method which is invoking another static method from the same class. For example , we have class A and it has two static methods method1() and method2() both are static . Let's suppose method1() is getting invoked from method2(). How can I write a test case for...
3 Oct 2012 by AssemblySoft
Hi Clifford,Could you not add the xml file to your unit test project, similar to how we add library references in order to allow our unit test projects to gain visibility into our application or possibly add the xml file to the bin directory of your unit test project or a known directory and...
11 Jan 2016 by Asutosha
Hi,I add Nuint using nuget package managerAdd class libriary and write test methodin visual studio 2010Now How I will able to run this test ?
26 Jun 2013 by bbirajdar
Yes.. Its possible Unit testing and the "constructors do nothing" rule[^]
4 Jul 2013 by bbirajdar
You should start here What is software testing[^]
10 Mar 2014 by Bernhard Hiller
Somewhere in the code, methods or properties of the mocked object will be accessed. What is the mocked object expected to do then? The Setup methods are used for that purpose: they tell the mocked object what to do here.Example: I have an object with a property, and the code will call the...
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...
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...
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...
22 Oct 2012 by Blakej777
Is it preferred to use the real UI or should it be mocked in AAT? Currently, i mock out my view for my unit/integration testing, but should i for automated testing? I can't seem to find any articles about this online. Mostly relates to Unit-testing specifically.
26 Oct 2015 by bling
Your memory leak isn't a real memory leak.Most heap checking tools will report a program like the following as having a leak.#include static char *leaks;int main(int argc, char *argv[]){ leaks = strdup("leaked data"); puts(leaks); return 0;}If it...
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 =>...
22 Feb 2012 by BobJanova
When you're running the unit tests, the entry assembly will be the test hosting shell. That could be something useless like the nunit.exe assembly, or if you're using a binary test harness (e.g. Visual Studio itself), it will be null. (See the documentation for GetEntryAssembly[^].)You...
12 Dec 2013 by BobJanova
If the code you're testing talks to a database, by definition that is not a unit test (it's an integration test). Are you actually testing the database access code here? If not, you want to put the database access code behind an interface and use a mock database provider for the unit tests of...
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...
25 Jun 2016 by Caio Hamamura
Run unit tests as you modify your code
31 Jul 2013 by Carlos Luis Rojas Aragonés
Qunit by example
10 Mar 2018 by Carlos Luis Rojas Aragonés
Formatting your rails specs with rspec_pacman_formatter
15 Feb 2016 by Chandra Mohan BS
I want to configure the unit tests to run for a predefined set of data but do not want to define those in external database/file. Reason being - it's a simple data collection that would make sense to be visible right in the test .cs file. Is there any way you can configure the datasource to a...
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 Apr 2015 by CHill60
An alternative to just copying the appsettings to the test project is as follows:In your test project right-click, Add, Existing Item.Navigate to the App.Config for the project you are trying to test.Instead of just clicking "Add" click the down-arrow next to it and select "Add as...
30 Oct 2012 by chuckdawit
I have a method that looks something like thispublic override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("someName", this.someName); info.AddValue("someName1", this.someName1); ...
19 Nov 2012 by chuckdawit
I have the constructor below. My question is:1. Should I extract out interfaces for the objects being created in the constructor and then mock those objects with some mocking framework? 2. How would I test this constructor?Constructor:protected SomeObjectIveCreated1 member1{ get; set;...
16 Mar 2012 by Clifford Nelson
I am wanting to access the default properties within a unit test. I can create the Accessor, but do not know how to tell visual studio that I want to use that accessor. Does not even appear to be in the intelisense list. I want to test an object that accesses these propertes, and ensure that the...
3 Oct 2012 by Clifford Nelson
I have a file in my code (a library) that is required for running the code. In this case it is an XML file. Currently I have it in the root of the main program, and it works fine when running the code. However, I need this file for some information when running unit tests. How should I specify...
12 Oct 2012 by Clifford Nelson
Ends up that you can at least get the path for an assembly:string _testPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MdyPastTests)).Location);Thus can bypass the problems of the executing assembly in test, which can be very strange, and just use the location of some class.
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...
5 Jun 2013 by Coldcreek
If I am using Firefox what kind of add-on are available which can find bugs in a website?
13 Sep 2014 by Commish13
Hi,I don't know if I'm using the correct terminology, but I'm trying to use a unit test, or just a C# class file to pull records from an excel file(sheet) and insert them into a sql Database. Does anyone know of a good tutorial, book, or any resource at all I could learn how to do this. Also...
24 Oct 2015 by CPallini
Why your function doesn't return a std::string (as it should)?What's the purpose of the std::map (or, better, what's the purpose of myMap while you can use a std::map?)?
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...
25 Oct 2015 by creanberries__87
Hi, I am getting a memory leak while running unit test in C++. You can see definition of the function, and the map used by this function which casuses unit test memory leak; const char* myMap [] ={ "INPUT1" , "OUTPUT1", "INPUT2" , ...
22 Jul 2015 by Cybermaxs
21 May 2013 by cynthia_dunlop
Service virtualization undeniably benefits the development process, but it can be both a blessing & a curse for developers. Learn how to minimize the burden on development to achieve maximum acceleration of delivery cycles.
14 Aug 2023 by Daan Acohen
Explains how to do multiple assertions using the Fluent Assertions library, without multiple validation lines
19 Oct 2023 by Daan Acohen
Boost your xUnit tests with detailed logging for clearer insights and easier debugging.
13 May 2016 by DannyFreeman
Writing unit tests for a deep clone method
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...
10 Apr 2015 by Darshita Dodiya
using (var fake = new SystemUnderTest.AutoFakeContainer()){List emplist = new List();emplist.Add(new Employee { Name = "Emp_1", BasicSalary = 1000, Id = Guid.NewGuid(), HRA = 100, DA = 10, TotalSalary = 1110 });emplist.Add(new Employee { Name = "Emp_2", BasicSalary =...
4 Feb 2017 by Dave Clemmer
Using XUnit.net to develop some unit tests, using Fact and Theory form of testing, including happy path tests and tests expected to throw exceptions
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...
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...
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...
19 Sep 2012 by David Bywaters
Two approaches for unit testing Entity Framework
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
17 Mar 2012 by Dean Oliver
Check these links out.http://msdn.microsoft.com/en-us/library/aa730869%28v=vs.80%29.aspx[^]http://msdn.microsoft.com/en-us/library/a65txexh.aspx[^]
5 Nov 2014 by DecompileCodex
I am using the NUnit framework for unit testing.My question is that in NUnit I am getting the error "MolopolyGame.Testing._Card.TestConstructor:No arguments were provided"The method which i am testing returns a random item in an array.I have a method which i need to testpublic...
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...
15 Aug 2022 by DiponRoy
How to delete all rows in EF Core 6 using alternate options
8 Nov 2018 by DMEvans
A discussion of three options for the creation of simple .NET types without affecting the testability of your class
27 Aug 2014 by Duncan Edwards Jones
I have a class that raises an even when its internal state changes (broadly similar to INotifyPropertyChange but slightly different).How should I write a unit test that verifies that this event is indeed raised? (There's nothing in the same model as "ExpectedException" for events?)
23 Jun 2014 by Ehsan.MA
Information on how to use UnitConversionLib in C# for changing units and quantities
10 Feb 2013 by Enrique Albert
Pattern to follow using mock frameworks so non public methods can be tested. The code example is based on the RhinoMock framework but it is easily applicable to any other mock framework.
22 Feb 2012 by Erik Rude
I'm a bit new to unit testing, most of my tests are fairly easy to do and just works brilliantly. However I'm trying to test this simple function and it fails me with the following error: System.NullReferenceException: Object reference not set to an instance of an object.What am I doing...
11 May 2015 by F-ES Sitecore
Most people use moq or rhinomock. Moq probably edges it for me, the main difference is in the syntaxes and what seems to make more sense to you. What's more important that which one you choose is that you fully get to grips with how you use it to mock various things, they're all much of a...
8 Dec 2015 by F-ES Sitecore
That code isn't really unit-testable. When you unit test you have to convert your code into services that are accessed via interfaces and it is those services\interfaces that you moq. So create an IMyData interface with a GetJobs method, then create a MyData class that implements this...
27 May 2016 by F-ES Sitecore
First of all, this isn't a unit test, a unit test requires no external resources and tests only your code's logic. Secondly all your test I trying to test is EntityFramework, but you should assume that MS test their own code so you don't have to. Thirdly your controller code is not unit...
24 Oct 2016 by F-ES Sitecore
Pick one scenario at a time, set the entity properties up such that that scenario is satisfied, then check the entity properties that match the scenario have been set up.eg you'll first want to check when InterpreterCostAuthorised is true and InterpreterCostAuthorisedDate is null, so set...
23 May 2017 by F-ES Sitecore
Asserts are what is used to cause a test to fail, if none of your asserts cause the test to fail then the test is a success. So if you don't have any asserts at all the test is bound to pass (assuming no exceptions are raised as most test frameworks consider an exception to be a fail too unless...
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...
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...
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...
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. ...
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.
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
28 Aug 2016 by FranzBe
you have some magic numbers there in your controller code. Why don't you swap this out in some extra class, thereby you get some interface you can mock against.e.g.void Main(){ var a = new PlanAuthorizationProvider(); var result = a.IsAuthorized(true, 387484); //result.Dump(); ...
9 Apr 2019 by Fred Song (Melbourne)
Angular 7 with .NET Core 2.2 - Global Weather
28 Aug 2013 by Fredrik Bornander
NUnit[^] is a .NET unit test framework, if you're targeting the .NET framework then using this makes sense.CppUnit[^] is a C++ unit test framework, it's applicable for pretty much anything written in C++ (with the possible exception for managed C++).Hope this helps,Fredrik
31 Jul 2014 by G.TR
how to use NUnit to code tests
10 Mar 2014 by Ganeshaspy
I am learning Test Driven Development and trying to use Moq library for mocking. What is the purpose of Setup method of Mock class?