Click here to Skip to main content
15,881,820 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 Score

Unit Testing 

9 Apr 2019 by Fred Song (Melbourne)
Angular 7 with .NET Core 2.2 - Global Weather
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.
18 Feb 2017 by Naveen Kosana
Learn how to write unit test cases using Jasmine framework for Angular Controllers
9 Oct 2023 by Łukasz Bownik
The article describes an alternative approach to unit testing.
18 Oct 2012 by Indranil Pal
Mocking database in Unit Tests using Moq.
29 Feb 2016 by Alexandr Surkov
My experience of using C++ with microcontrollers
19 Oct 2018 by Sean Rand
Getting the most from your test runner
6 Jun 2012 by Sergey Alexandrovich Kryukov
No one can tell you the exact answer. It really depends on your project in further detail. I hope I don't have to proof that testing cannot proof anything? More exactly, you can proof there is a defect, but otherwise, if testing finds no defects, it cannot proof that all defects are fixed, no...
3 Dec 2012 by Vasil Trifonov
Getting console output within a unit test
21 Jan 2013 by Simeon Sheye
Beyond basic unit tests, how do you choose your tests and when are you done?
2 Aug 2016 by Richard Deeming
Your Calculation class does not contain a parameterless constructor. You need to pass the constructor parameters to the PrivateObject constructor[^]:string expression = "5*10-18/(3+19)";PrivateObject obj = new PrivateObject( typeof(Calculation), // The type of the object to...
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.
10 Mar 2018 by Carlos Luis Rojas Aragonés
Formatting your rails specs with rspec_pacman_formatter
21 Jun 2018 by John M. Dlugosz
How can an automated test program test that something is rejected at compile time?
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
11 Mar 2012 by Andreas Gieriet
How to define RelationAssert as an extension to the VisualStudio Assert class.
22 Oct 2012 by Sergey Alexandrovich Kryukov
Those are just different tests, and you need both, to improve your chances to reveal some flaws. The more the better. That would be enough to wrap up the complete answer, but let's think what would be the background of these two different approaches.The application has some inner layers...
19 May 2013 by Yossi Yaari
A solution for monitoring Events called during test.
16 Feb 2015 by OriginalGriff
As little as possible should be static - excepting extension methods, which have to be, and some methods which are "generic" to an application rather than specific to a class.C# is an OOPs language - and the first "O" is for "Object"! If you make everything static, then you are ignoring what...
25 Jun 2015 by Suvendu Shekhar Giri
There is solution available in StackOverflow[^].From Visual Studio command prompt run followingvstest.console.exe /logger:trx .\TestProject\bin\debug\YourUnitTestAssembly.dllFind detailed solution with explaination hereVisual Studio 2012 Unit Test Report[^]Hope, it helps :)
14 Aug 2023 by Daan Acohen
Explains how to do multiple assertions using the Fluent Assertions library, without multiple validation lines
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...
5 Feb 2013 by Pete O'Hanlon
It's fairly straight forward testing a model with annotations in MVC. This[^] should give you a decent grounding in where to start. Pay particular attention to the section on the ValidationContext as this is the voodoo that really helps make it work.
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.
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.
5 Jun 2013 by Prasad Khandekar
Hello,You can use Selenium IDE. This link also lists some other tools for finding security related issues and are worth considerations.Regards,
4 Jul 2013 by bbirajdar
You should start here What is software testing[^]
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
14 Jan 2014 by Nanda Kumar Chintam
This tip explains how to perform unit testing for business logic written in App_code for a website project.
23 Feb 2014 by Kornfeld Eliyahu Peter
Not all editions of Visual Studio 2010 support unit test. Even you can open solutions with unit test in it on every edition, it will run only on Premium and Ultimate editions...
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...
27 Aug 2014 by Valery Possoz
Hello,You could do it using delegates in your unit tests.for example: [TestMethod] public void EventShouldBeRaised() { ClassToTest classToTest = new ClassToTest(); bool eventRaised = false; classToTest.EventRaised +=...
28 Sep 2014 by Gediminas Geigalas
Expose your mocks directly from the Fixture Object if possible. If there is no real need to complicate things by converting types and introducing extension methods, don’t do it.
28 Sep 2015 by jeron1
Why reinvent the wheel, a quick google turned up this[^]. I am certain there are lots of others as well.
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?)?
3 Jan 2016 by George Swan
How to replace the System.Timer with a mock object when testing
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 May 2016 by Patrice T
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.The debugger allow you to follow the execution line by line, inspect variables and you will see that there...
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...
18 Jan 2017 by Sergey Podobry
How-to guide about using KmTest for writing kernel-mode unit tests
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...
13 Jul 2017 by User 10132546
I'd recommend switching over to xunit for your .NET Core unit tests. You can run xunit tests directly from JetBrains cross-platform .NET IDE "Rider"[^]. Alternatively, you can run xunit tests from the command line using the following command: $ dotnet xunit See: Getting started with...
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++.
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...
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...
22 Feb 2020 by OriginalGriff
See here: The Differences Between Unit Testing, Integration Testing And Functional 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...
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...
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...
3 Sep 2021 by James Walsh Jr
Unit testing Fluent Validation methods for data validation
22 Jun 2022 by Richard MacCutchan
Take a look at Testing Flask Applications — Flask Documentation (2.0.x)[^]
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...
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...
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.
8 Feb 2012 by Member 4391175
Hi,When i clicked the Button one modal pop up dialog box will open, how to click that open button using watin test.I used below code , but it doesn't working for me. public void CheckName() { IE ie = new IE("http://localhost:4066/SampleWebSite/Default.aspx"); ...
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...
8 Mar 2012 by SwapnadipSaha
hi all, Recently I have joined an IT company. and I've to face an exit test next week on the following topics1. Basics of MVC2. Integration of Entity Framework, MVC, AJAX and Jquery3. Repositories4. Unit Of Work5. Unity Framework6. Data Manager7. Data...
11 Mar 2012 by Member 9648718
How can i make a test expecting an exception to be thrown.here is my code : [ExpectedException(typeof(Exception))] public void AnAddressHasOnly1UserTest() { Address address = new Address() { Street ="street1", ...
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[^]
8 Apr 2012 by Kranthi Boppana
Hi All,Is it possible to implement Unit test for Validations in silverlight using MVVM??If yes, please help me out with an example!Any help would be appreciated.Thank you,Kranthi Boppana
6 Jun 2012 by Stephen Hewison
Hi,I have a question about finding the best balance of unit testing. I have in one example a website which consumes a services for its data. If I break the solution down I have the following layers:ServiceData Access LayerBusiness Logic LayerService API LayerWebsiteService...
5 Jul 2012 by Karthik. A
The error "Cannot override Non-Virtual member ...ProductRepository" indicates that Moq is attempting "override" a method that is not virtual. So a method w/ definitionpublic void Something() { ... }cannot be overridden. But this can be :public virtual void Something() { ......
26 Sep 2012 by Rohith Gopi
Hi,I want to unit test a subroutine.The code is like this. Public Sub UpdateChat() 'Getting the connection string Dim connectString As String = ConfigurationManager.ConnectionStrings("ShoutDb").ConnectionString 'Creating connection object Dim...
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...
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.
31 Oct 2012 by Pablo Aliskevicius
IMHO:1. You should test the base class independently, before you test the derived class.2. Testing for a null parameter is nice, but you should also test that, given valid parameters, the result of your function (not this one, but others that are not void) is the one you expect, and the...
28 Nov 2012 by Sergey Alexandrovich Kryukov
chuckdawit wrote:Should I replace the 'SomeObjectIveCreated2' with an interface to adhere to rules of encapsulation? This is helpful for unit testing but is more for the rules regarding the S.O.L.I.D principles.You should understand that interfaces, as opposed to abstract classes and "classic"...
1 Jan 2013 by Vijay_Gurunanee
Hi,In order to remove external dependency for testing purpose i was trying to implement the mole frameworkeverything was working fine until i have moled the class with static readonly property.Creating mole of that class is not the root cause of issue but that readonly property is...
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[^].
10 Jan 2013 by Rupa1
how can i set Application variable to mock data
10 Jan 2013 by Sandeep Mewara
Following might help: Mocking HttpContext for Unit Testing[^]
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 =...
28 Jan 2013 by scarletwitch1990
my visual web developer is installed without the unit test framework. Which of the extensions should i use instead?the version of the web developer is 2010. Please help...
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.
5 Feb 2013 by scarletwitch1990
I was trying the NerdDinner in mvc 4 and at the particular code below: Assert.IsInstanceOfType(typeof(ViewResult),result); i am getting an errorNUnit.Framework.Assert.IsInstanceOfType(System.Type, object)' is obsoleteBecause of this unit tests are failing and are throwing a Null...
31 Jan 2013 by Sergey Alexandrovich Kryukov
This method is declared obsolete, because, after introduction of generics as early as of .NET v.2.0, non-generic methods depending on types simply make no sense, they are just too bad next to generic ones.Beginning with NUnit 2.5, generic equivalents are available: IsInstanceOf,...
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[^].
5 Feb 2013 by scarletwitch1990
Can we create test methods for model properties with model validations. e.g.public class PersonAccount{ [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "New...
5 Feb 2013 by Sergey Alexandrovich Kryukov
This is what it is: you did not provide matching method declaration in some partial class declaration. As you don't mention about it, I would be curious to know what was your idea about it. Partial methods are as trivial as...
21 Feb 2013 by scarletwitch1990
below is my repository service public class ProductService : IProductService { private IProductRepository _productRepository; // Some initlization stuff public Product GetProduct(int id) { try { return _productRepository.GetProduct(id); } catch...
22 Feb 2013 by scarletwitch1990
My application has a BaseController in which the HttpContext.Current.Session[CacheKey] is used.how do i mock the above session while unit testing.I have the fake HttpContext Helpers...how do i use them....also my HttpContext.Current.Session[CacheKey] manages the language of the browser...
6 Mar 2013 by scarletwitch1990
i have a service lyk below:public class SubjectService : ISubjectService { private readonly ISubjectRepository subjectRepository; public SubjectService(ISubjectRepository subjectRepository) { this.broadSubjectAreaRepository =...
26 Feb 2013 by scarletwitch1990
hello i was unit testing my service layer :I have a service layer named "CustomerService"public interface ICustomerService{ IQueryable GetCustomerByFilter(Expression> where);}public class CustomerService : ICustomerService{ private...
26 Feb 2013 by scarletwitch1990
during one of my lectures in unit testing, my professor stated that testing a controller action comes under functional testing, and that the best practice to test the controller is to unit test the various independent functions that we are using in it like the service layer functions.we are...
28 Feb 2013 by scarletwitch1990
Say my controller class is inheriting from a basecontroller instead of controller like shown below: public partial class ProductController : BaseController { public ActionResult Index() { //Code to the controller action } }And my...
12 Mar 2013 by K C R
My project is a web forms application. Currently we do integration testing and selenium web testing ( For UI ) and now ma Manager has asked us to do unit testing instead of selenium for code coverage. My question is how do we do unit testing for web forms (and... what is mock ?), would be gr8 if...
8 Apr 2013 by 吴骏明
Generate interface for WebService client stub for unit testing.
29 Apr 2013 by jophyjob
Hello All , We have a WPF application Project which is suppose to run on different OS versions (Win XP ,Win 7 and Win 8 ). To make sure the compatibility of the application on all OS , We like to Run some unit test on All these OS versions On the TFS check-In . ...
2 May 2013 by Gautam Raithatha
I have created a test project for unit testing the methods in my c# project and various test methods in it. In actual method, there are global class level variables used whose values are set from constructor or other methods. So when actual project runs, the variables have value when referenced...
2 May 2013 by tumbledDown2earth
This is a classic case. You can make the global dependent variables in a config (or some container class) which implements an interface. Now in the live example implement your interface with a config reader class and your methods should read these values from the interface only.You can...
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.
9 May 2013 by Tadit Dash (ତଡିତ୍ କୁମାର ଦାଶ)
Check out the below articles. Best methods are explained here.1. Walkthrough: Build, Host, and Test Simple RESTful WCF Service[^].2. Building and Testing WCF RESTful services[^].3. RestFul WCF JSON Service with client and on Mozilla Firefox –REST Client[^].
15 May 2013 by Vijay_Gurunanee
Sorry for late reply...but not working for me....I just re factored the code and changed my code such that it can be moled.But still i didn't find proper solution for this problem...Thanks...
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...
4 Jun 2013 by KishoreUHG
Hi,I have a test method in the Unit test project. When i try to run the below method[TestMethod()] [HostType("ASP.NET")] [AspNetDevelopmentServerHost("C:\\Samples\\MyUnitTestApp\\MVCApp", "/")] [UrlToTest("http://localhost:59794/")] public void...