Click here to Skip to main content
15,895,011 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 Zijian
Learn to use EventSourceDB through Unit Testing on xUnit.NET
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 Title

Unit Testing 

27 Nov 2013 by Mahmud Hasan
The only good thing of Test Driven Development is, it ensures the maximum test coverage but TDD puts you in risk of a week design. DTDT tries to solve this while ensuring maximum test coverage.
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 =...
1 Dec 2014 by Karthik Ravi
Hi,I am tring to unit test my project but it showing error as "Object Reference not set to an instance of an object". someone kindly give me a solution for this problem.I referred all necessary namespace in this project. //Unit Test codeusing System;using...
2 Dec 2014 by OriginalGriff
"i think it may be on "Source Con" in TestConnection method. " Source Con = null;Can't throw a null reference exception - it doesn't refer to or create an instance of any class.However, then next line is likely to: appGlobal.AddText();Check your references to...
2 Dec 2014 by Sergey Alexandrovich Kryukov
You did not show where the exception with the message "Object reference not set to an instance of an object" is thrown. You should not ask a specific question each time you face this little problem. It's much more important to learn how to deal with it all by yourself in all cases. Not to...
31 Jul 2014 by G.TR
how to use NUnit to code tests
21 Jan 2013 by Simeon Sheye
Beyond basic unit tests, how do you choose your tests and when are you done?
21 Jan 2013 by Simeon Sheye
How to manage state and simulate behavior against the system under test.
9 Apr 2019 by Fred Song (Melbourne)
Angular 7 with .NET Core 2.2 - Global Weather
6 Apr 2014 by Mike114
How to setup unit test environment on Amazon Elastic Bamboo instance
5 Jul 2012 by robroysd
Hi,I have a unit of work class which is as below:public class UnitOfWork : IUnitOfWork, IDisposable { private readonly EFDbContext context; private IGenericRepository _categoryRepository; private IGenericRepository...
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() { ......
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
3 Feb 2013 by stuuz
Hey,I've posted about this application before and had some good responses, so hopefully you guys can help again.I'm currently undertaking my final year of a Computer Science degree in the UK, and building an ASP.NET Web Forms CMS with an E-Commerce module as my final project.I'm...
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[^].
3 Feb 2013 by Kishor Deshpande
Hi,MSTest comes with Visual studio which is testing framework.Now, when you think about isolation framework to remove external dependencies, most of the developers use Rhino Mocks.If you really want to learn how you can write Unit tests for your BAL code without changing it to OR/M,The...
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.
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); ...
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[^]
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.
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...
27 May 2016 by m.r.m.40
Hi,I'm using AspNet.Mvc web application which I'd like to test it using 'ms unit test' here is the controller function which i'm testing:public ActionResult Delete(int id) Student studentToDelete = new Student() { ID = id }; db.Entry(studentToDelete).State =...
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...
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...
13 Nov 2014 by QAVN Parallels
After a test method failed, there is a Message about this failure in the "Test Explorer" window. It will look like belowTest Failed - TC0001 Message: Test method ParallelsAutomation.TestCases.APS2.UnitTest1.U1TC_001 threw exception: System.DivideByZeroException: Attempted to divide by...
29 Feb 2016 by Alexandr Surkov
My experience of using C++ with microcontrollers
19 Feb 2014 by Priya Kakar
Can we create Coded UI test cases in VS premium/ultimate version and use it in Professional version? i googled it and found some links supporting that its possible, using MTM. I'm a newbie to this. so, if somebody can help,then i shall be obliged..Thanks!
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...
3 Jul 2012 by jbachelor
I've been trying to wrap my head around automated testing in general, and specifically have been digging in to Pex and Moles most recently. I've watched numerous videos from Channel 9 and elsewhere, followed through several tutorials, and I'm trying to start trying out Pex on my code.In my...
2 Aug 2016 by log98
I'm writing a unit test for calculation software.in test case i used of "PrivateObject" for accessing to private method "sendNumberToCalculation()" , but i get error constructor on type not found. public class CalculationTest{ [TestMethod] public void...
2 Aug 2016 by Kadau _
Can we have a screenshot of the error and the line please ?
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...
1 Aug 2013 by Raja.Krishnasamy
Data Driven Testing in MSTest by using Excel as data source and Named Region as table name instead of sheet name
15 Aug 2022 by DiponRoy
How to delete all rows in EF Core 6 using alternate options
8 May 2014 by Halil ibrahim Kalkan
An implementation of dependency injection, repository and unit of work patterns using Castle Windsor and NHibernate.
28 Aug 2013 by Rahul from Poona
What is difference between CPPUnit and NUnit?When to use CPPUNIT and when to use NUNIT?What will be appropriate for C++ ATL COM project and why?Thanks in advance
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
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...
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...
21 Nov 2016 by onqtam
Intro to testing framework, what makes it unique and points about its capabilities
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.
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
11 Jun 2013 by andyharman
Temporarily freeze time by injecting a thread-safe time bubble into your C# code.
21 Nov 2013 by Ralph Varjabedian
Easy error mocking in node.js/mocha/istanbul to achieve full code coverage
19 Oct 2023 by Daan Acohen
Boost your xUnit tests with detailed logging for clearer insights and easier debugging.
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...
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.
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;...
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"...
26 Feb 2014 by miligupta123
HI,I am writing unit test cases for repositories using Microsoft fakes,in which one of the repository have unityresolver which throws errors.Below is mu code for Unity Resolver.public static TUnityType Create(){ return...
30 Oct 2014 by suma_sarur
Hi,I have to automate my already existing (production) application, which is implemented using Visual Studio 2010.I am looking for some free (open source) Mocking tool which supports for Non Virtual members, b'coz my application does not have any virtual members and I can't change my...
20 Oct 2015 by marcus obrien
When starting a new C# project, put in a test project to unit test your code as you develop. This is test-driven development.
8 Apr 2013 by 吴骏明
Generate interface for WebService client stub for unit testing.
9 Feb 2016 by Manfredzik
Write your own simple generic mapper with TDD
3 Dec 2012 by Vasil Trifonov
Getting console output within a unit test
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...
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
21 Nov 2014 by qwerty 2
Hi I need to generate a trx file through VS tests which should contain the test case attributes like owner, description using command line optionsThe above attributes are generated by default in MS tests.I tried using custom logger to log the info but am not able to get the owner and...
21 Nov 2014 by qwerty 2
Hi I need to generate a trx file through VS tests which should contain the test case attributes like owner, description using command line optionsThe above attributes are generated by default in MS tests.I tried using custom logger to log the info but am not able to get the owner and...
29 May 2014 by NaveenChidara
I'm able to create mock objects and do a update test with mocked entities successfully.But the issue is with create test. Here is my sample code.In this always my testPG is null and so the test failsbase class:public class TestContext where T : class { protected Mock...
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[^]
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: ...
9 Jun 2014 by R-a-v-i-k-u-m-a-r
Sample Codepublic ActionResult SubjectExpertsList() { UsersListViewModel model = new UsersListViewModel(); model.UsersList = _userService.UsersList(Convert.ToInt32(Session["organizationId"])); model.UsersList = model.UsersList.Where(u => u.RoleId...
10 Jun 2014 by Sampath Lokuge
Please read below article.May be the starting point for you.Good Luck :)ASP.NET MVC Unit Testing using NUnit in Visual Studio
10 Jun 2014 by MehraManish
unit testing of the view is not recommended
25 Mar 2014 by JS00001
[TestMethod] public void UnitTestMethod1() { Test1Controller controller = new Test1Controller(); //This call throws NullReferenceException "Object reference not set to an instance of an object." WebSecurity.Login("User1", "password1"); ...
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...
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.
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...
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...
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...
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,...
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 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...
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...
9 Mar 2014 by Member 10471717
Hi,We have a PRISM based MVVM Silverlight application(SL5).The idea is to create unit tests for the viewmodel and in some places view code.We explored msTest, nunit and Silverlight unit test framework for the same and reached a conclusion that Silverlight unit test only work with our...
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)[^]
21 Oct 2014 by Member 11169453
I've calls to my data access from another class.So while implementing moq I have :var mockdac = new Mock();mockDac.SetUp(o => o.MyMethod(params)).Returns("something");Inside MyMethod I have :var reader = Database.ExecuteReader(cmd);while(reader.Read()){ //Some logic}My...
25 Oct 2014 by Tomas Takac
For what's worth, I wrote this article based on your question: IDataReader Stub[^]
23 Feb 2015 by Member 11447944
So i just started to learning unit testing in IOS and i have few simple tasks to complete.So basically i have created a Tab bar controller with only two tabs. How can i test that there indeed only two tabs ?Also, i have an order: The first tab and the second tab How can i test the order...
23 Feb 2015 by KarstenK
At first testing has changed somehow on Apple systems. ReadAbout Testing with Xcode.You can assign the Tabbar to an outlet an than access the array of tabs. To start Testing, use on the Menu Product -> Test or Product->Build for Testing. Testing only runs on the simulator. If to feasable,...
4 Aug 2014 by Marine Azizyan
I have one question. What is good testing way, Microsoft.VisualStudioTestToolsUnitTesting or by Nunit_framework testing.If I have this`public Branch CreateOrEditBranch(Branch branch) { using (var scope = CreateTransactionScope()) { } return branch; ...
4 Aug 2014 by Vijendra(VJ)
HiYou can check for null conditions of each of the variables using an AND condition as shown below: bool? isValid = null; Branch positive = new Branch(); // Assign values to the instance here. isValid = positive.BranchID != null &&...
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...
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) { ...
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.
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?)
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 +=...
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 =...
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...
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...