Search Results

Search found 910 results on 37 pages for 'assert'.

Page 12/37 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • How do I test UrlHelper.RouteUrl()?

    - by Jeff Putz
    I'm having a tough go trying to figure out what I need to mock in my tests to show that UrlHelper.RouteUrl() is returning the right URL. It works, but I'd like to have the right test coverage. The meat of the controller method looks like this: var urlHelper = new UrlHelper(ControllerContext.RequestContext); return Json(new BasicJsonMessage { Result = true, Redirect = urlHelper.RouteUrl(new { controller = "TheController", action = "TheAction", id = somerecordnumber }) }); Testing the result object is easy enough, like this: var controller = new MyController(); var result = controller.DoTheNewHotness()); Assert.IsInstanceOf<JsonResult>(result); var data = (BasicJsonMessage)result.Data; Assert.IsTrue(data.Result); result.Redirect is always null because the controller obviously doesn't know anything about the routing. What do I have to do to the controller to let it know? As I said, I know it works when I exercise the production code, but I'd like some testing assurance. Thanks for your help!

    Read the article

  • How to rollback in EF4?

    - by Jaxidian
    In my research about rolling back transactions in EF4, it seems everybody refers to this blog post or offers a similar explanation. In my scenario, I'm wanting to do this in a unit testing scenario where I want to rollback practically everything I do within my unit testing context to keep from updating the data in the database (yeah, we'll increment counters but that's okay). In order to do this, is it best to follow the following plan? Am I missing some concept or anything else major with this (aside from my SetupMyTest and PerformMyTest functions won't really exist that way)? using (var ts = new TransactionScope()) { // Arrange SetupMyTest(context); // Act PerformMyTest(context); var numberOfChanges = context.SaveChanges(false); // if there's an issue, chances are that an exception has been thrown by now. // Assert Assert.IsTrue(numberOfChanges > 0, "Failed to _____"); // transaction will rollback because we do not ever call Complete on it }

    Read the article

  • Why allow concatenation of string literals?

    - by Caspin
    I recently got bit by a subtle bug. char ** int2str = { "zero", // 0 "one", // 1 "two" // 2 "three",// 3 nullptr }; assert( values[1] == "one"_s ); // passes assert( values[2] == "two"_s ); // fails If you have godlike code review powers you'll notice I forgot the , after "two". After the considerable effort to find that bug I've got to ask why would anyone ever want this behavior? I can see how this might be useful for macro magic, but then why is this a "feature" in a modern language like python? Have you ever used string literal concatenation in production code?

    Read the article

  • double.NaN Equality in MS Test

    - by RichK
    Why am I getting this result? [TestMethod] public void nan_test() { Assert.AreEqual(1, double.NaN, 1E-1); <-- Passes Assert.AreEqual(1, double.NaN); <-- Fails } What difference does the delta have in asserting NaN equals a number? Surely it should always return false. I am aware of IsNaN, but that's not useful here (see below). Background: I have a function returning NaN (erroneously) , it was meant to be a real number but the test still passed. I'm using the delta because it's double precision equality, the original test used 1E-9.

    Read the article

  • clear javascript console in Google Chrome

    - by Reigel
    Hi, I was wondering if I could clear up the console with some command.. console.log(), can print... is there a command to clear up console?.. I've tried to console.log(console); and got this functions below... assert: function assert() { [native code] } constructor: function Console() { [native code] } count: function count() { [native code] } debug: function debug() { [native code] } dir: function dir() { [native code] } dirxml: function dirxml() { [native code] } error: function error() { [native code] } group: function group() { [native code] } groupEnd: function groupEnd() { [native code] } info: function info() { [native code] } log: function log() { [native code] } markTimeline: function markTimeline() { [native code] } profile: function profile() { [native code] } profileEnd: function profileEnd() { [native code] } time: function time() { [native code] } timeEnd: function timeEnd() { [native code] } trace: function trace() { [native code] } warn: function warn() { [native code] } __proto__: Object [ I guess there's no way to clear up the console... but I wanted someone to say it to me... ]

    Read the article

  • MbUnit (gallio) and Visual Studio.Net Tests Not Completing or Debugging

    - by Davy
    Hi I'm using Gallio\MbUnit 3.1 with ReSharper and Visual Studio 2008. Everything is working well except this type of test: [Test] [Row("test@badEmail@_test.com")] [Row("test@badEmail@_test.")] public void IsValidEmail_Invalid_Emails_Should_Return_False(string invalidEmail) { Assert.IsFalse(AppHelper.IsValidEmail(invalidEmail), "Email validation failed for " + invalidEmail); } The test doesn't complete or go in to debug mode only when I pass in a parameter E.g. 'string invalidEmail'. If I remove that prameter it seems to work normally. It will run the test if I have: [Test] public void IsValidEmail_Invalid_Emails_Should_Return_False() { var invalidName = test@badEmail@_test.com"; Assert.IsFalse(AppHelper.IsValidEmail(invalidEmail), "Email validation failed for " + invalidEmail); } I appreciate that there may be better ways to achieve this test but I'm trying to work my way through a book and this is how it's explaining things. Any help is appreciated. Davy

    Read the article

  • How to check if a generic type definition inherits from another generic type definition

    - by Anne
    I'm trying to check whether an open generic type definition implements some open generic interface. Look at the sample below: public interface IService<T> { } public class ServiceImpl<T> : IService<T> { } private static bool OpenGenericTypeImplementsOpenGenericInterface( Type derivedType, Type interfaceType) { return derivedType.GetInterfaces().Contains(interfaceType); } [TestMethod] public void Verify() { Type openGenericImplementation = typeof(ServiceImpl<>); Type expectedInterfaceType = typeof(IService<>); bool implDoesImplementInterface = OpenGenericTypeImplementsOpenGenericInterface( openGenericImplementation, expectedInterfaceType); // This assert fails. Why? Assert.IsTrue(implDoesImplementInterface); } I found out that the returned type from the Type.GetInterfaces() method does not match the type returned from typeof(IService<>). I can't figure out why that is and how to correctly validate whether some generic type definition inherits or implements some other generic type definition. What's going on here and how do I solve fix this problem?

    Read the article

  • How to make the selected testcript is run in selenium grid

    - by Yui
    Hi, I can launch some remote control by using: ant launch-remote-control but I dont know how my script connect to hub? I set up ant, selenium-grid on the same computer. I have an grid.dll which is written by C# and run through NUnit. The test data is read from xml file (ValidData.xml) The example code is below : using System.Collections.Generic; using System.Linq; using System.Text; using System; using System.Xml; using System.Text.RegularExpressions; using System.Threading; using NUnit.Framework; using Selenium; namespace Grid { public class Class1 { //User defined private string strURL = "http://gmail.com/"; private string[] strBrowser = new string[3] { "*iehta", "*firefox", "*safari" }; string hubAddress = "192.168.20.131"; // IP of my computer // System defined private ISelenium selenium; private StringBuilder verificationErrors; [SetUp] public void SetupTest() { selenium = new DefaultSelenium(hubAddress, 4444, this.strBrowser[1], this.strURL);// do i need to identify browser when I defined it when launching a remote control selenium.Start(); verificationErrors = new StringBuilder(); } [TearDown] public void TeardownTest() { try { selenium.Stop(); } catch (Exception) { // Ignore errors if unable to close the browser } Assert.AreEqual("", verificationErrors.ToString()); } private string[] name; [Test] public void LoginPassedTest() { try { XmlDocument doc = new XmlDocument(); XmlNode docNode; doc.Load("ValidData.xml"); docNode = doc["TestCase"]; foreach (XmlNode node in docNode) { selenium.Open("/"); selenium.WaitForPageToLoad("50000"); selenium.Type("Email", node["username"].InnerText); selenium.Type("Passwd", node["password"].InnerText); selenium.Click("signIn"); selenium.WaitForPageToLoad("100000"); name = (selenium.GetText("//div[@id='guser']/nobr/b").Split('@')); try { Assert.AreEqual(node["username"].InnerText, name[0]); Assert.AreEqual("Sign out", selenium.GetText(":r6")); } catch (AssertionException e) { verificationErrors.Append(e.Message); } selenium.Click(":r6"); } } catch (AssertionException e) { verificationErrors.Append(e.Message); } } } } Step I run this script: 1.I build that script into DLL 2.I start hub by using command "ant lauch-hub" 3.I start 2 remote controls by using command : ant -Dport=5566 -Denvironment="*chrome" launch-remote-control ant -Dport=5577 -Denvironment="*iexplore" launch-remote-control 4.Then I open Nunit and load DLL (code above) and run 5.The NUNit doesnot respond anything. I think there are some missing things but I dont know. How can the test script (DLL) know which is sequence of remote control is selected to run the test???? Please help me!! Thank you so much Yui.

    Read the article

  • How Moles Isolation framework is implemented?

    - by Buu Nguyen
    Moles is an isolation framework created by Microsoft. A cool feature of Moles is that it can "mock" static/non-virtual methods and sealed classes (which is not possible with frameworks like Moq). Below is the quick demonstration of what Moles can do: Assert.AreNotEqual(new DateTime(2012, 1, 1), DateTime.Now); // MDateTime is part of Moles; the below will "override" DateTime.Now's behavior MDateTime.NowGet = () => new DateTime(2012, 1, 1); Assert.AreEqual(new DateTime(2012, 1, 1), DateTime.Now); Seems like Moles is able to modify the CIL body of things like DateTime.Now at runtime. Since Moles isn't open-source, I'm curious to know which mechanism Moles uses in order to modify methods' CIL at runtime. Can anyone shed any light?

    Read the article

  • Generic List<T> as IEnumerable<object>

    - by Avi
    I'm trying to do cast a List to an IEnumerable, so I can verify that different lists are not null or empty: Suppose myList is a List < T . Then in the caller code I wanted: Validator.VerifyNotNullOrEmpty(myList as IEnumerable<object>, @"myList", @"ClassName.MethodName"); The valdiating code would be: public static void VerifyNotNullOrEmpty(IEnumerable<object> theIEnumerable, string theIEnumerableName, string theVerifyingPosition) { string errMsg = theVerifyingPosition + " " + theIEnumerableName; if (theIEnumerable == null) { errMsg += @" is null"; Debug.Assert(false); throw new ApplicationException(errMsg); } else if (theIEnumerable.Count() == 0) { errMsg += @" is empty"; Debug.Assert(false); throw new ApplicationException(errMsg); } } However, this doens't work. It compiles, but theIEnumerable is null! Why?

    Read the article

  • "Debug Assertion" Runtime Error on VS2008?

    - by Linda Cohen
    I' writing a C++ MFC program on VS2008 and I'm getting this "Debug Assertion Error" when I first run the program sometimes. When I try to debug it, it takes me to this winhand.cpp file which is not part of the program I wrote so I'm not sure how to debug this. It takes the error to this place in winhand.cpp CObject* pTemp = LookupTemporary(h); if (pTemp != NULL) { // temporary objects must have correct handle values HANDLE* ph = (HANDLE*)((BYTE*)pTemp + m_nOffset); // after CObject ASSERT(ph[0] == h || ph[0] == NULL); if (m_nHandles == 2) ASSERT(ph[1] == h); } So why does this error happen? Why does it only happen sometimes (50% of the time)? How would I debug this? I'll provide some code if is needed. THANKS!

    Read the article

  • dynamically created datagridview columns not accessible unless added to a form...why?

    - by deostroll
    We simply created a DataGridView control dynamically and bound it to a DataTable. We were tying to style certain columns. But, when we tried to access the columns we got a null reference. On further investigation we found that if we add the DataGridView control to the main form, and then try to access its columns, it works fine!!! Code which throws error: DataGridView gv = new DataGridView(); gv.DataSource = GetDataTable(); //binding it to datatable Debug.Assert(gv.Columns == null); Code which works fine: DataGridView gv = new DataGridView(); gv.DataSource = GetDataTable(); //binding it to datatable this.Controls.Add(gv); //adding to form Debug.Assert(gv.Columns == null); //the assertion fails! Why is this behaviour so? Is there a workaround for this?

    Read the article

  • NUnit / Testdriven.Net conflicting results.

    - by panamack
    When I run this test in NUnit = Red Bar. [Test] public void ChangingValueViaPropertyDescriptorRaisesPropertyChangedNotification() { PropertyChangedEventArgs pCEventArgs = null; subjectVM.PropertyChanged += (sender, e) => { pCEventArgs = e; }; PropertyDescriptor descriptor = subjectVM.GetProperties().Find(schoolMeta.Name, false); descriptor.SetValue(null, "School's out for summer."); Assert.IsNotNull(pCEventArgs); Assert.AreEqual("School", pCEventArgs.PropertyName); } However, when I run this test from within Visual Studio with Test Driven .Net it passes. When it fails with NUnit it's because PropertyChanged is null, subjectVM is a View Model classes that inherits PropertyChanged from a base class. Am I to blame, or am I looking at a NUnit bug?

    Read the article

  • Is AutoMapper able to auto resolve types base on existing maps

    - by Chi Chan
    I have the following code: [SetUp] public void SetMeUp() { Mapper.CreateMap<SourceObject, DestinationObject>(); } [Test] public void Testing() { var source = new SourceObject {Id = 123}; var destination1 = Mapper.Map<SourceObject, DestinationObject>(source); var destination2 = Mapper.Map<ObjectBase, ObjectBase>(source); //Works Assert.That(destination1.Id == source.Id); //Fails, gives the same object back Assert.That(destination2 is DestinationObject); } public class ObjectBase { public int Id { get; set; } } public class SourceObject : ObjectBase { } public class DestinationObject : ObjectBase { } So basically, I want AutoMapper to automatically resolve the destination type to "DestinationObject" based on the existing Maps set up in AutoMapper. Is there a way to achieve this?

    Read the article

  • Fleunt NHibernate not working outside of nunit test fixtures

    - by thorkia
    Okay, here is my problem... I created a Data Layer using the RTM Fluent Nhibernate. My create session code looks like this: _session = Fluently.Configure(). Database(SQLiteConfiguration.Standard.UsingFile("Data.s3db")) .Mappings( m => { m.FluentMappings.AddFromAssemblyOf<ProductMap>(); m.FluentMappings.AddFromAssemblyOf<ProductLogMap>(); }) .ExposeConfiguration(BuildSchema) .BuildSessionFactory(); When I reference the module in a test project, then create a test fixture that looks something like this: [Test] public void CanAddProduct() { var product = new Product {Code = "9", Name = "Test 9"}; IProductRepository repository = new ProductRepository(); repository.AddProduct(product); using (ISession session = OrmHelper.OpenSession()) { var fromDb = session.Get<Product>(product.Id); Assert.IsNotNull(fromDb); Assert.AreNotSame(fromDb, product); Assert.AreEqual(fromDb.Id, product.Id); } My tests pass. When I open up the created SQLite DB, the new Product with Code 9 is in it. the tables for Product and ProductLog are there. Now, when I create a new console application, and reference the same library, do something like this: Product product = new Product() {Code = "10", Name = "Hello"}; IProductRepository repository = new ProductRepository(); repository.AddProduct(product); Console.WriteLine(product.Id); Console.ReadLine(); It doesn't work. I actually get pretty nasty exception chain. To save you lots of head aches, here is the summary: Top Level exception: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.\r\n\r\n The PotentialReasons collection is empty The Inner exception: The IDbCommand and IDbConnection implementation in the assembly System.Data.SQLite could not be found. Ensure that the assembly System.Data.SQLite is located in the application directory or in the Global Assembly Cache. If the assembly is in the GAC, use element in the application configuration file to specify the full name of the assembly. Both the unit test library and the console application reference the exact same version of System.Data.SQLite. Both projects have the exact same DLLs in the debug folder. I even tried copying SQLite DB the unit test library created into the debug directory of the console app, and removed the build schema lines and it still fails If anyone can help me figure out why this won't work outside of my unit tests it would be greatly appreciated. This crazy bug has me at a stand still.

    Read the article

  • Can I configure NUnit so that Debug.Fail doesn't show a message box when I run my tests?

    - by panamack
    I have this property: public SubjectStatus Status { get { return status; } set { if (Enum.IsDefined(typeof(SubjectStatus), value)) { status = value; } else { Debug.Fail("Error setting Subject.Status", "There is no SubjectStatus enum constant defined for that value."); return; } } } and this unit test [Test] public void StatusProperty_StatusChangedToValueWithoutEnumDefinition_StatusUnchanged() { Subject subject = new TestSubjectImp("1"); // assigned by casting from an int to a defined value subject.Status = (SubjectStatus)2; Assert.AreEqual(SubjectStatus.Completed, subject.Status); // assigned by casting from an int to an undefined value subject.Status = (SubjectStatus)100; // no change to previous value Assert.AreEqual(SubjectStatus.Completed, subject.Status); } Is there a way I can prevent Debug.Fail displaying a message box when I run my tests, but allow it to show me one when I debug my application?

    Read the article

  • Linq to NHibernate using Queryable.Where predicate

    - by Groo
    I am querying an SQLite database using LINQ to NHibernate. Person is an entity containing an Id and a Name: public class Person { public Guid Id { get; private set; } public string Name { get; private set; } } Let's say my db table contains a single person whose name is "John". This test works as expected: var query = from item in session.Linq<Person>() where (item.Name == "Mike") select item; // no such entity should exist Assert.IsFalse(query.Any()); but this one fails: var query = from item in session.Linq<Person>() select item; query.Where(item => item.Name == "Mike"); // following line actually returns the // "John" entry Assert.IsFalse(query.Any()); What am I missing?

    Read the article

  • Find subset with K elements that are closest to eachother

    - by Nima
    Given an array of integers size N, how can you efficiently find a subset of size K with elements that are closest to each other? Let the closeness for a subset (x1,x2,x3,..xk) be defined as: 2 <= N <= 10^5 2 <= K <= N constraints: Array may contain duplicates and is not guaranteed to be sorted. My brute force solution is very slow for large N, and it doesn't check if there's more than 1 solution: N = input() K = input() assert 2 <= N <= 10**5 assert 2 <= K <= N a = [] for i in xrange(0, N): a.append(input()) a.sort() minimum = sys.maxint startindex = 0 for i in xrange(0,N-K+1): last = i + K tmp = 0 for j in xrange(i, last): for l in xrange(j+1, last): tmp += abs(a[j]-a[l]) if(tmp > minimum): break if(tmp < minimum): minimum = tmp startindex = i #end index = startindex + K? Examples: N = 7 K = 3 array = [10,100,300,200,1000,20,30] result = [10,20,30] N = 10 K = 4 array = [1,2,3,4,10,20,30,40,100,200] result = [1,2,3,4]

    Read the article

  • .net Diagnostics best practices?

    - by mamu
    We initially didn't use any logging or debug tracing but after spending few weeks to trace down some data corruption we decided to put required Debug.Write and Trace for production and Debug.Assert So now question is What is the best practice to use debug and trace logging. I am just looking for some thing generic. public void AddRectodatabase(object record) { Debug.WriteLine(record.ToString()); Trace.WriteLine(record.ToString()); // Add it to databse Debug.Assert(true, "Use this on case by case basis"); } Is this good enough for general purpose, am i doing anything wrong in there? We want to stick with .net System.Diagnostics over other alternatives like log4net. Is there any thing else useful in System.Diagnostics?

    Read the article

  • Java unit test coverage numbers do not match.

    - by Dan
    Below is a class I have written in a web application I am building using Java Google App Engine. I have written Unit Tests using TestNG and all the tests pass. I then run EclEmma in Eclipse to see the test coverage on my code. All the functions show 100% coverage but the file as a whole is showing about 27% coverage. Where is the 73% uncovered code coming from? Can anyone help me understand how EclEmma works and why I am getting the discrepancy in numbers? package com.skaxo.sports.models; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; @PersistenceCapable(identityType= IdentityType.APPLICATION) public class Account { @PrimaryKey @Persistent(valueStrategy=IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private String userId; @Persistent private String firstName; @Persistent private String lastName; @Persistent private String email; @Persistent private boolean termsOfService; @Persistent private boolean systemEmails; public Account() {} public Account(String firstName, String lastName, String email) { super(); this.firstName = firstName; this.lastName = lastName; this.email = email; } public Account(String userId) { super(); this.userId = userId; } public void setId(Long id) { this.id = id; } public Long getId() { return id; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public boolean acceptedTermsOfService() { return termsOfService; } public void setTermsOfService(boolean termsOfService) { this.termsOfService = termsOfService; } public boolean acceptedSystemEmails() { return systemEmails; } public void setSystemEmails(boolean systemEmails) { this.systemEmails = systemEmails; } } Below is the test code for the above class. package com.skaxo.sports.models; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.assertFalse; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class AccountTest { @Test public void testId() { Account a = new Account(); a.setId(1L); assertEquals((Long) 1L, a.getId(), "ID"); a.setId(3L); assertNotNull(a.getId(), "The ID is set to null."); } @Test public void testUserId() { Account a = new Account(); a.setUserId("123456ABC"); assertEquals(a.getUserId(), "123456ABC", "User ID incorrect."); a = new Account("123456ABC"); assertEquals(a.getUserId(), "123456ABC", "User ID incorrect."); } @Test public void testFirstName() { Account a = new Account("Test", "User", "[email protected]"); assertEquals(a.getFirstName(), "Test", "User first name not equal to 'Test'."); a.setFirstName("John"); assertEquals(a.getFirstName(), "John", "User first name not equal to 'John'."); } @Test public void testLastName() { Account a = new Account("Test", "User", "[email protected]"); assertEquals(a.getLastName(), "User", "User last name not equal to 'User'."); a.setLastName("Doe"); assertEquals(a.getLastName(), "Doe", "User last name not equal to 'Doe'."); } @Test public void testEmail() { Account a = new Account("Test", "User", "[email protected]"); assertEquals(a.getEmail(), "[email protected]", "User email not equal to '[email protected]'."); a.setEmail("[email protected]"); assertEquals(a.getEmail(), "[email protected]", "User email not equal to '[email protected]'."); } @Test public void testAcceptedTermsOfService() { Account a = new Account(); a.setTermsOfService(true); assertTrue(a.acceptedTermsOfService(), "Accepted Terms of Service not true."); a.setTermsOfService(false); assertFalse(a.acceptedTermsOfService(), "Accepted Terms of Service not false."); } @Test public void testAcceptedSystemEmails() { Account a = new Account(); a.setSystemEmails(true); assertTrue(a.acceptedSystemEmails(), "System Emails is not true."); a.setSystemEmails(false); assertFalse(a.acceptedSystemEmails(), "System Emails is not false."); } }

    Read the article

  • Is Pex (Test generation) really usefull tool?

    - by Yauheni Sivukha
    Yes, it is possible to generate tests on boundary values for functions like "Sum" or "Divide". Pex is a good tool here. But more often we create tests on business behaviour. Let's consider example from classic Beck's tdd book: [Test] public void ShouldRoundOnCreation() { Money money = new Money(20.678); Assert.AreEqual(20.68,money.Amount); Assert.AreEqual(2068,money.Cents); } Can this test be generated? No :) 95 % of tests in my projects check business logic, and can not be generated. Pex (Especially in pair with Moles) can give 100% code coverage, but a high code coverage rate of a test suite does never indicate, that code is well tested - It only gives false confidence that everything is tested. And this is very dangerous. So, the question is - Is Pex really usefull tool?

    Read the article

  • Compare Date objects with different levels of precision

    - by brainimus
    I have a JUnit test that fails because the milliseconds are different. In this case I don't care about the milliseconds. How can I change the precision of the assert to ignore milliseconds (or any precision I would like it set to)? Example of a failing assert that I would like to pass: Date dateOne = new Date(); dateOne.setTime(61202516585000L); Date dateTwo = new Date(); dateTwo.setTime(61202516585123L); assertEquals(dateOne, dateTwo);

    Read the article

  • Aborted core dumped C++

    - by avd
    I have a large C++ function which uses OpenCV library and running on Windows with cygwin g++ compiler. At the end it gives Aborted(core dumped) but the function runs completely before that. I have also tried to put the print statement in the end of the function. That also gets printed. So I think there is no logical bug in code which will generate the fault. Please explain. I am also using assert statements.But the aborted error is not due to assert statement. It does not say that assertion failed. It comes at end only without any message. Also the file is a part of a large project so I cannot post the code also.

    Read the article

  • How do I mock/fake/replace/stub a base class at unit-test time in C#?

    - by MatthewMartin
    UPDATE: I've changed the wording of the question. Previously it was a yes/no question about if a base class could be changed at runtime. I may be working on mission impossible here, but I seem to be getting close. I want to extend a ASP.NET control, and I want my code to be unit testable. Also, I'd like to be able to fake behaviors of a real Label (namely things like ID generation, etc), which a real Label can't do in an nUnit host. Here a working example that makes assertions on something that depends on a real base class and something that doesn't-- in a more realistic unit test, the test would depend on both --i.e. an ID existing and some custom behavior. Anyhow the code says it better than I can: public class LabelWrapper : Label //Runtime //public class LabelWrapper : FakeLabel //Unit Test time { private readonly LabelLogic logic= new LabelLogic(); public override string Text { get { return logic.ProcessGetText(base.Text); } set { base.Text=logic.ProcessSetText(value); } } } //Ugh, now I have to test FakeLabelWrapper public class FakeLabelWrapper : FakeLabel //Unit Test time { private readonly LabelLogic logic= new LabelLogic(); public override string Text { get { return logic.ProcessGetText(base.Text); } set { base.Text=logic.ProcessSetText(value); } } } [TestFixture] public class UnitTest { [Test] public void Test() { //Wish this was LabelWrapper label = new LabelWrapper(new FakeBase()) LabelWrapper label = new LabelWrapper(); //FakeLabelWrapper label = new FakeLabelWrapper(); label.Text = "ToUpper"; Assert.AreEqual("TOUPPER",label.Text); StringWriter stringWriter = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(stringWriter); label.RenderControl(writer); Assert.AreEqual(1,label.ID); Assert.AreEqual("<span>TOUPPER</span>", stringWriter.ToString()); } } public class FakeLabel { virtual public string Text { get; set; } public void RenderControl(TextWriter writer) { writer.Write("<span>" + Text + "</span>"); } } //System Under Test internal class LabelLogic { internal string ProcessGetText(string value) { return value.ToUpper(); } internal string ProcessSetText(string value) { return value.ToUpper(); } }

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >