Search Results

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

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

  • ApiChange Is Released!

    - by Alois Kraus
    I have been working on little tool to simplify my life and perhaps yours as developer as well. It is basically a command line tool that allows you to execute queries on your compiled .NET code base. The main purpose is to find out how big the impact of an api change would be if you changed this or that.  Now you can do high level operations like Diff public types for breaking changes. Who uses a method? Who uses a type? Who uses implements an interface? Who references me? What format has the binary  (32/64, Managed C++, Pure IL, Unmanaged)? Search for all event subscribers and unsubscribers. A unique feature is to check for event subscription imbalances. Forgotten event subscriptions are the 90% cause of managed memory leaks. It is done at a per class level. If one class does subscribe to one event more often than it does unsubscribe it is treated as possible event subscription imbalance. Another unique ability is to search for users of string literals which allows you to track users of a string constant which is not possible otherwise. For incremental builds the ShowRebuildTargets command can be used to identify the dependant targets that need a rebuild after you did compile one assembly. It has some heuristics in place to determine the impact of breaking changes and finds out which targets need to be recompiled as well. It has a ton of other features and a an API to access these things programmatically so you can build upon these simple queries create even better tools. Perhaps we get a Visual Studio plug in? You can download it from CodePlex here. It works via XCopy deployment. Simply let it run and check the command line help out. The best feature in my opinion is that the output of nearly all commands can be piped to Excel for further analysis. Since it does read also the pdbs it can show you the source file name and line number as well for all matches. The following picture shows the output of a –WhousesType query. The following command checks where type from BaseLibraryV1.dll are used inside DependantLibV1.dll. All matches are printed out with the reason and matching item along with file and line number. There is even a hyper link to the match which will open Visual Studio. ApiChange -whousestype "*" BaseLibraryV1.dll -in DependantLibV1.dll –excel The "*” is the actual query which means all types. The syntax is the same like in C# just that placeholders are allowed ;-). More info's can be found at the Codeplex Documentation.     The tool was developed in a TDD style manner which means that it is heavily tested and already used by a quite large user base inside the company I do work for. Luckily for you I got the permission to make it public so you take advantage of it. It is fully instrumented with tracing. If you find bugs simply add the –trace command line switch to find out what is failing and send me the output. How is it done? Your first guess might be that it uses reflection. Wrong. It is based on Mono Cecil a free IL parser with a fantastic API to access all internals of a managed assembly. The speed is awesome and to make it even faster I did make the tool heavily multi threaded. The query above did execute in 1.8s with the Excel output. On a rather slow machine I can analyze over 1500 assemblies in less than 40s with a very low memory consumption. The true power of Mono Cecil is that I can load an assembly like any other data file. I have no problems unloading a file but if I would have used reflection I would need to unload a whole AppDomain just to get rid of one assembly in my memory. Just to give you a glimpse how ApiChange.Api.dll can be used I show you one of the unit tests:           public void Can_Find_GenericMethodInvocations_With_Type_Parameters()         { // 1. Create an aggregator to collect our matches             UsageQueryAggregator agg = new UsageQueryAggregator();   // 2. This is the type we want to search for. Load it via the type query             var decimalType = TypeQuery.GetTypeByName(TestConstants.MscorlibAssembly, "System.Decimal");   // 3. register the type query which searches for uses of the Decimal type             new WhoUsesType(agg, decimalType);   // 4. Search for all users of the Decimal type in the DependandLibV1Assembly             agg.Analyze(TestConstants.DependandLibV1Assembly);   // Extract matches and assert             Assert.AreEqual(2, agg.MethodMatches.Count, "Method match count");             Assert.AreEqual("UseGenericMethod", agg.MethodMatches[0].Match.Name);             Assert.AreEqual("UseGenericMethod", agg.MethodMatches[1].Match.Name);         } Many thanks go from here to Jb Evian for the creation of Mono.Cecil. Without this fantastic piece of code it would have been much much harder. There are other options around like the Common Compiler Infrastructure  Metadata Api which should do the same thing but it was not a real option since the Microsoft reader did fail on even simple assemblies (at least in September 2009 this was the case). Besides this I found the CCI Apis much harder to use. The only real competitor was Reflector which does support many things but does not let me access his cool high level analyze commands. So I decided to dig into the IL specs and as a result you can query your compiled binaries from the command line or programmatically. The best thing is you try it out for yourself and give me some feedback what you miss. If you want to contribute or have a cool idea what should be added drop me a mail at A Kraus1@___No [email protected]. There is much more inside the tool I did not talk about it (yet).

    Read the article

  • What are the disadvantages of self-encapsulation?

    - by Dave Jarvis
    Background Tony Hoare's billion dollar mistake was the invention of null. Subsequently, a lot of code has become riddled with null pointer exceptions (segfaults) when software developers try to use (dereference) uninitialized variables. In 1989, Wirfs-Brock and Wikerson wrote: Direct references to variables severely limit the ability of programmers to re?ne existing classes. The programming conventions described here structure the use of variables to promote reusable designs. We encourage users of all object-oriented languages to follow these conventions. Additionally, we strongly urge designers of object-oriented languages to consider the effects of unrestricted variable references on reusability. Problem A lot of software, especially in Java, but likely in C# and C++, often uses the following pattern: public class SomeClass { private String someAttribute; public SomeClass() { this.someAttribute = "Some Value"; } public void someMethod() { if( this.someAttribute.equals( "Some Value" ) ) { // do something... } } public void setAttribute( String s ) { this.someAttribute = s; } public String getAttribute() { return this.someAttribute; } } Sometimes a band-aid solution is used by checking for null throughout the code base: public void someMethod() { assert this.someAttribute != null; if( this.someAttribute.equals( "Some Value" ) ) { // do something... } } public void anotherMethod() { assert this.someAttribute != null; if( this.someAttribute.equals( "Some Default Value" ) ) { // do something... } } The band-aid does not always avoid the null pointer problem: a race condition exists. The race condition is mitigated using: public void anotherMethod() { String someAttribute = this.someAttribute; assert someAttribute != null; if( someAttribute.equals( "Some Default Value" ) ) { // do something... } } Yet that requires two statements (assignment to local copy and check for null) every time a class-scoped variable is used to ensure it is valid. Self-Encapsulation Ken Auer's Reusability Through Self-Encapsulation (Pattern Languages of Program Design, Addison Wesley, New York, pp. 505-516, 1994) advocated self-encapsulation combined with lazy initialization. The result, in Java, would resemble: public class SomeClass { private String someAttribute; public SomeClass() { setAttribute( "Some Value" ); } public void someMethod() { if( getAttribute().equals( "Some Value" ) ) { // do something... } } public void setAttribute( String s ) { this.someAttribute = s; } public String getAttribute() { String someAttribute = this.someAttribute; if( someAttribute == null ) { setAttribute( createDefaultValue() ); } return someAttribute; } protected String createDefaultValue() { return "Some Default Value"; } } All duplicate checks for null are superfluous: getAttribute() ensures the value is never null at a single location within the containing class. Efficiency arguments should be fairly moot -- modern compilers and virtual machines can inline the code when possible. As long as variables are never referenced directly, this also allows for proper application of the Open-Closed Principle. Question What are the disadvantages of self-encapsulation, if any? (Ideally, I would like to see references to studies that contrast the robustness of similarly complex systems that use and don't use self-encapsulation, as this strikes me as a fairly straightforward testable hypothesis.)

    Read the article

  • AllowPartiallyTrustedCallersAttribute exception - unit testing with moq

    - by vdh_ant
    Hi guys I am receiving the following exception when trying to run my unit tests using .net 4.0 under VS2010 with moq 3.1. Attempt by security transparent method 'SPPD.Backend.DataAccess.Test.Specs_for_Core.When_using_base.Can_create_mapper()' to access security critical method 'Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(System.Object)' failed. Assembly 'SPPD.Backend.DataAccess.Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception. The test I am running is really straight forward and looks something like the following: [TestMethod] public void Can_create_mapper() { this.SetupTest(); var mockMapper = new Moq.Mock<IMapper>().Object; this._Resolver.Setup(x => x.Resolve<IMapper>()).Returns(mockMapper).Verifiable(); var testBaseDa = new TestBaseDa(); var result = testBaseDa.TestCreateMapper<IMapper>(); Assert.IsNotNull(result); //<<< THROWS EXCEPTION HERE Assert.AreSame(mockMapper, result); this._Resolver.Verify(); } I have no idea what this means and I have been looking around and have found very little on the topic. The closest reference I have found is this http://dotnetzip.codeplex.com/Thread/View.aspx?ThreadId=80274 but its not very clear on what they did to fix it... Anyone got any ideas?

    Read the article

  • Moq broken? Not working with .net 4.0

    - by vdh_ant
    Hi guys I am receiving the following exception when trying to run my unit tests using .net 4.0 under VS2010 with moq 3.1. Attempt by security transparent method 'SPPD.Backend.DataAccess.Test.Specs_for_Core.When_using_base.Can_create_mapper()' to access security critical method 'Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(System.Object)' failed. Assembly 'SPPD.Backend.DataAccess.Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception. The test I am running is really straight forward and looks something like the following: [TestMethod] public void Can_create_mapper() { this.SetupTest(); var mockMapper = new Moq.Mock<IMapper>().Object; this._Resolver.Setup(x => x.Resolve<IMapper>()).Returns(mockMapper).Verifiable(); var testBaseDa = new TestBaseDa(); var result = testBaseDa.TestCreateMapper<IMapper>(); Assert.IsNotNull(result); //<<< THROWS EXCEPTION HERE Assert.AreSame(mockMapper, result); this._Resolver.Verify(); } I have no idea what this means and I have been looking around and have found very little on the topic. The closest reference I have found is this http://dotnetzip.codeplex.com/Thread/View.aspx?ThreadId=80274 but its not very clear on what they did to fix it... Anyone got any ideas?

    Read the article

  • How can I effectively test a scripting engine?

    - by ChaosPandion
    I have been working on an ECMAScript implementation and I am currently working on polishing up the project. As a part of this, I have been writing tests like the following: [TestMethod] public void ArrayReduceTest() { var engine = new Engine(); var request = new ExecScriptRequest(@" var a = [1, 2, 3, 4, 5]; a.reduce(function(p, c, i, o) { return p + c; }); "); var response = (ExecScriptResponse)engine.PostWithReply(request); Assert.AreEqual((double)response.Data, 15D); } The problem is that there are so many points of failure in this test and similar tests that it almost doesn't seem worth it. It almost seems like my effort would be better spent reducing coupling between modules. To write a true unit test I would have to assume something like this: [TestMethod] public void CommentTest() { const string toParse = "/*First Line\r\nSecond Line*/"; var analyzer = new LexicalAnalyzer(toParse); { Assert.IsInstanceOfType(analyzer.Next(), typeof(MultiLineComment)); Assert.AreEqual(analyzer.Current.Value, "First Line\r\nSecond Line"); } } Doing this would require me to write thousands of tests which once again does not seem worth it.

    Read the article

  • Asp.Net MVC Tutorial Unit Tests

    - by Nicholas
    I am working through Steve Sanderson's book Pro ASP.NET MVC Framework and I having some issues with two unit tests which produce errors. In the example below it tests the CheckOut ViewResult: [AcceptVerbs(HttpVerbs.Post)] public ViewResult CheckOut(Cart cart, FormCollection form) { // Empty carts can't be checked out if (cart.Lines.Count == 0) { ModelState.AddModelError("Cart", "Sorry, your cart is empty!"); return View(); } // Invoke model binding manually if (TryUpdateModel(cart.ShippingDetails, form.ToValueProvider())) { orderSubmitter.SubmitOrder(cart); cart.Clear(); return View("Completed"); } else // Something was invalid return View(); } with the following unit test [Test] public void Submitting_Empty_Shipping_Details_Displays_Default_View_With_Error() { // Arrange CartController controller = new CartController(null, null); Cart cart = new Cart(); cart.AddItem(new Product(), 1); // Act var result = controller.CheckOut(cart, new FormCollection { { "Name", "" } }); // Assert Assert.IsEmpty(result.ViewName); Assert.IsFalse(result.ViewData.ModelState.IsValid); } I have resolved any issues surrounding 'TryUpdateModel' by upgrading to ASP.NET MVC 2 (Release Candidate 2) and the website runs as expected. The associated error messages are: *Tests.CartControllerTests.Submitting_Empty_Shipping_Details_Displays_Default_View_With_Error: System.ArgumentNullException : Value cannot be null. Parameter name: controllerContext* and the more detailed at System.Web.Mvc.ModelValidator..ctor(ModelMetadata metadata, ControllerContext controllerContext) at System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) at System.Web.Mvc.Controller.TryUpdateModel[TModel](TModel model, String prefix, String[] includeProperties, String[] excludeProperties, IValueProvider valueProvider) at System.Web.Mvc.Controller.TryUpdateModel[TModel](TModel model, IValueProvider valueProvider) at WebUI.Controllers.CartController.CheckOut(Cart cart, FormCollection form) Has anyone run into a similar issue or indeed got the test to pass?

    Read the article

  • Why `A & a = a` is valid?

    - by psaghelyi
    #include <iostream> #include <assert.h> using namespace std; struct Base { Base() : m_member1(1) {} Base(const Base & other) { assert(this != &other); // this should trigger m_member1 = other.m_member1; } int m_member1; }; struct Derived { Derived(Base & base) : m_base(m_base) {} // m_base(base) Base & m_base; }; void main() { Base base; Derived derived(base); cout << derived.m_base.m_member1 << endl; // crashes here } The above example is a synthesized version of a mistyped constructor. I used reference at the class member Derived::m_base because I wanted to make sure that the member will be initialized as the constructor had called. One problem is that nor GCC nor MSVC gives me a warning at m_base(m_base). But the more serious for me is that the assert finds everything fine and the application crashes later (sometimes far away from the mistake). Question: Is there any way to indicate such mistakes?

    Read the article

  • Update element values using xml.dom.minidom

    - by amnesia-55
    Hello, I have an XML structure which looks similar to: <Store> <foo> <book> <isbn>123456</isbn> </book> <title>XYZ</title> <checkout>no</checkout> </foo> <bar> <book> <isbn>7890</isbn> </book> <title>XYZ2</title> <checkout>yes</checkout> </bar> </Store> Using xml.dom.minidom only (restrictions) i would like to 1)traverse through the XML file 2)Search/Get for particular element, depending on its parent Example: checkout element for author1, isbn for author2 3)Change/Set that element's value 4)Write the new XML structure to a file Can anyone help here? Thank you! UPDATE: This is what i have done till now import xml.dom.minidom checkout = "yes" def getLoneChild(node, tagname): assert ((node is not None) and (tagname is not None)) elem = node.getElementsByTagName(tagname) if ((elem is None) or (len(elem) != 1)): return None return elem def getLoneLeaf(node, tagname): assert ((node is not None) and (tagname is not None)) elem = node.getElementsByTagName(tagname) if ((elem is None) or (len(elem) != 1)): return None leaf = elem[0].firstChild if (leaf is None): return None return leaf.data def setcheckout(node, tagname): assert ((node is not None) and (tagname is not None)) child = getLoneChild(node, 'foo') Check = getLoneLeaf(child[0],'checkout') Check = tagname return Check doc = xml.dom.minidom.parse('test.xml') root = doc.getElementsByTagName('Store')[0] output = setcheckout(root, checkout) tmp_config = '/tmp/tmp_config.xml' fw = open(tmp_config, 'w') fw.write(doc.toxml()) fw.close()

    Read the article

  • Unittesting Url.Action (using Rhino Mocks?)

    - by Kristoffer Ahl
    I'm trying to write a test for an UrlHelper extensionmethod that is used like this: Url.Action<TestController>(x => x.TestAction()); However, I can't seem set it up correctly so that I can create a new UrlHelper and then assert that the returned url was the expected one. This is what I've got but I'm open to anything that does not involve mocking as well. ;O) [Test] public void Should_return_Test_slash_TestAction() { // Arrange RouteTable.Routes.Add("TestRoute", new Route("{controller}/{action}", new MvcRouteHandler())); var mocks = new MockRepository(); var context = mocks.FakeHttpContext(); // the extension from hanselman var helper = new UrlHelper(new RequestContext(context, new RouteData()), RouteTable.Routes); // Act var result = helper.Action<TestController>(x => x.TestAction()); // Assert Assert.That(result, Is.EqualTo("Test/TestAction")); } I tried changing it to urlHelper.Action("Test", "TestAction") but it will fail anyway so I know it is not my extensionmethod that is not working. NUnit returns: NUnit.Framework.AssertionException: Expected string length 15 but was 0. Strings differ at index 0. Expected: "Test/TestAction" But was: <string.Empty> I have verified that the route is registered and working and I am using Hanselmans extension for creating a fake HttpContext. Here's what my UrlHelper extentionmethod look like: public static string Action<TController>(this UrlHelper urlHelper, Expression<Func<TController, object>> actionExpression) where TController : Controller { var controllerName = typeof(TController).GetControllerName(); var actionName = actionExpression.GetActionName(); return urlHelper.Action(actionName, controllerName); } public static string GetControllerName(this Type controllerType) { return controllerType.Name.Replace("Controller", string.Empty); } public static string GetActionName(this LambdaExpression actionExpression) { return ((MethodCallExpression)actionExpression.Body).Method.Name; } Any ideas on what I am missing to get it working??? / Kristoffer

    Read the article

  • Entity framework memory leak after detaching newly created object

    - by Tom Peplow
    Hi, Here's a test: WeakReference ref1; WeakReference ref2; TestRepositoryEntitiesContainer context; int i = 0; using (context = GetContext<TestRepositoryEntitiesContainer>()) { context.ObjectMaterialized += (o, s) => i++; var item = context.SomeEntities.Where(e => e.SomePropertyToLookupOn == "some property").First(); context.Detach(item); ref1 = new WeakReference(item); var newItem = new SomeEntity {SomePropertyToLookupOn = "another value"}; context.SomeEntities.AddObject(newItem); ref2 = new WeakReference(newItem); context.SaveChanges(); context.SomeEntities.Detach(newItem); newItem = null; item = null; } context = null; GC.Collect(); Assert.IsFalse(ref1.IsAlive); Assert.IsFalse(ref2.IsAlive); First assert passes, second fails... I hope I'm missing something, it is late... But it appears that detaching a fetched item will actually release all handles on the object letting it be collected. However, for new objects something keeps a pointer and creates a memory leak. NB - this is EF 4.0 Anyone seen this before and worked around it? Thanks for your help! Tom

    Read the article

  • windows kernel mode IOCTL returns random results

    - by clyfe
    I use the following code to fetch PSTORAGE_HOTPLUG_INFO capabilities from disks via IOCTL in a minifilter driver, but the returning hotplugInfo structure has all the fields set to random nonzero values on subsequent executions. What am I doing wrong? RESULT: 00000014 0.00046322 IOCTL Volume Media Removable, 64 00000015 0.00046451 IOCTL Volume Media Hotplug 154 00000016 0.00046562 IOCTL Volume Device Hotplug 244 00000054 1020.44311523 IOCTL Volume Media Removable, 240 00000055 1020.44311523 IOCTL Volume Media Hotplug 102 00000056 1020.44311523 IOCTL Volume Device Hotplug 244 Sample code: //int SomeFunction(PFLT_VOLUME pFLTVolume) STORAGE_HOTPLUG_INFO storageHotplugInfo; KEVENT event; IO_STATUS_BLOCK ioStatus; PIRP pirp; PDEVICE_OBJECT deviceObject; PSTORAGE_HOTPLUG_INFO hotplugInfo; ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL); status = FltGetDiskDeviceObject(pFLTVolume, &deviceObject); if(!NT_SUCCESS(status)){ DbgPrint("No Device for Volume\n"); return 0; } KeInitializeEvent(&event, NotificationEvent, FALSE); ASSERT(KeGetCurrentIrql() <= APC_LEVEL); pirp = IoBuildDeviceIoControlRequest( IOCTL_STORAGE_GET_HOTPLUG_INFO, deviceObject, NULL, 0, &storageHotplugInfo, sizeof(STORAGE_HOTPLUG_INFO), FALSE, &event, &ioStatus ); if(!pirp){ return 0; } ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL); status = IoCallDriver(deviceObject, pirp); if (status == STATUS_PENDING) { status = KeWaitForSingleObject( &event, Executive, KernelMode, FALSE, NULL); } else { ioStatus.Status = status; } status = ioStatus.Status; hotplugInfo = (PSTORAGE_HOTPLUG_INFO) &pirp->AssociatedIrp.SystemBuffer; if(hotplugInfo->MediaRemovable){ DbgPrint("IOCTL Volume Media Removable, %d\n", hotplugInfo->MediaRemovable); } if(hotplugInfo->MediaHotplug){ DbgPrint("IOCTL Volume Media Hotplug %d\n", hotplugInfo->MediaHotplug); } if(hotplugInfo->DeviceHotplug){ DbgPrint("IOCTL Volume Device Hotplug %d\n", hotplugInfo->DeviceHotplug); } ObDereferenceObject(deviceObject);

    Read the article

  • What is the best testing pattern for checking that parameters are being used properly?

    - by Joseph
    I'm using Rhino Mocks to try to verify that when I call a certain method, that the method in turn will properly group items and then call another method. Something like this: //Arrange var bucketsOfFun = new BucketGame(); var balls = new List<IBall> { new Ball { Color = Color.Red }, new Ball { Color = Color.Blue }, new Ball { Color = Color.Yellow }, new Ball { Color = Color.Orange }, new Ball { Color = Color.Orange } }; //Act bucketsOfFun.HaveFunWithBucketsAndBalls(balls); //Assert ??? Here is where the trouble begins for me. My method is doing something like this: public void HaveFunWithBucketsAndBalls(IList<IBall> balls) { //group all the balls together according to color var blueBalls = GetBlueBalls(balls); var redBalls = GetRedBalls(balls); // you get the idea HaveFunWithABucketOfBalls(blueBalls); HaveFunWithABucketOfBalls(redBalls); // etc etc with all the different colors } public void HaveFunWithABucketOfBalls(IList<IBall> colorSpecificBalls) { //doing some stuff here that i don't care about //for the test i'm writing right now } What I want to assert is that each time I call HaveFunWithABucketOfBalls that I'm calling it with a group of 1 red ball, then 1 blue ball, then 1 yellow ball, then 2 orange balls. If I can assert that behavior then I can verify that the method is doing what I want it to do, which is grouping the balls properly. Any ideas of what the best testing pattern for this would be?

    Read the article

  • C function changes behaviour depending on whether it has a call to printf in it

    - by Daniel
    I have a function that processes some data and finds the threshold that classifies the data with the lowest error. It looks like this: void find_threshold(FeatureVal* fvals, sampledata* data, unsigned int num_samples, double* thresh, double* err, int* pol) { //code to calculate minThresh, minErr, minPol omitted printf("minThresh: %f, minErr: %f, minPol: %d\n", minThresh, minErr, minPol); *thresh = minThresh; *err = minErr; *pol = minPol; } Then in my test file I have this: void test_find_threshold() { //code to set up test data omitted find_threshold(fvals, sdata, 6, &thresh, &err, &pol); printf("Expected 5 got %f\n", thresh); assert(eq(thresh, 5.0)); printf("Expected 1 got %d\n", pol); assert(pol == 1); printf("Expected 0 got %f\n", err); assert(eq(err, 0.0)); } This runs and the test passes with the following output: minThresh: 5.000000, minErr: 0.000000, minPol: 1 Expected 5 got 5.000000 Expected 1 got 1 Expected 0 got 0.000000 However if I remove the call to printf() from find_threshold, suddenly the test fails! Commenting out the asserts so that I can see what gets returned, the output is: Expected 5 got -15.000000 Expected 1 got -1 Expected 0 got 0.333333 I cannot make any sense of this whatsoever.

    Read the article

  • How to TDD Asynchronous Events?

    - by Padu Merloti
    The fundamental question is how do I create a unit test that needs to call a method, wait for an event to happen on the tested class and then call another method (the one that we actually want to test)? Here's the scenario if you have time to read further: I'm developing an application that has to control a piece of hardware. In order to avoid dependency from hardware availability, when I create my object I specify that we are running in test mode. When that happens, the class that is being tested creates the appropriate driver hierarchy (in this case a thin mock layer of hardware drivers). Imagine that the class in question is an Elevator and I want to test the method that gives me the floor number that the elevator is. Here is how my fictitious test looks like right now: [TestMethod] public void TestGetCurrentFloor() { var elevator = new Elevator(Elevator.Environment.Offline); elevator.ElevatorArrivedOnFloor += TestElevatorArrived; elevator.GoToFloor(5); //Here's where I'm getting lost... I could block //until TestElevatorArrived gives me a signal, but //I'm not sure it's the best way int floor = elevator.GetCurrentFloor(); Assert.AreEqual(floor, 5); } Edit: Thanks for all the answers. This is how I ended up implementing it: [TestMethod] public void TestGetCurrentFloor() { var elevator = new Elevator(Elevator.Environment.Offline); elevator.ElevatorArrivedOnFloor += (s, e) => { Monitor.Pulse(this); }; lock (this) { elevator.GoToFloor(5); if (!Monitor.Wait(this, Timeout)) Assert.Fail("Elevator did not reach destination in time"); int floor = elevator.GetCurrentFloor(); Assert.AreEqual(floor, 5); } }

    Read the article

  • How do I properly implement a property in F#?

    - by Greg D
    Consider my first attempt, a simple type in F# like the following: type Test() = inherit BaseImplementingNotifyPropertyChangedViaOnPropertyChanged() let mutable prop: string = null member this.Prop with public get() = prop and public set value = match value with | _ when value = prop -> () | _ -> let prop = value this.OnPropertyChanged("Prop") Now I test this via C# (this object is being exposed to a C# project, so apparent C# semantics are desirable): [TestMethod] public void TaskMaster_Test() { var target = new FTest(); string propName = null; target.PropertyChanged += (s, a) => propName = a.PropertyName; target.Prop = "newString"; Assert.AreEqual("Prop", propName); Assert.AreEqual("newString", target.Prop); return; } propName is properly assigned, my F# Setter is running, but the second assert is failing because the underlying value of prop isn't changed. This sort of makes sense to me, because if I remove mutable from the prop field, no error is generated (and one should be because I'm trying to mutate the value). I think I must be missing a fundamental concept. What's the correct way to rebind/mutate prop in the Test class so that I can pass my unit test?

    Read the article

  • Weird .net 4.0 exception when running unit tests

    - by vdh_ant
    Hi guys I am receiving the following exception when trying to run my unit tests using .net 4.0 under VS2010 with moq 3.1. Attempt by security transparent method 'SPPD.Backend.DataAccess.Test.Specs_for_Core.When_using_base.Can_create_mapper()' to access security critical method 'Microsoft.VisualStudio.TestTools.UnitTesting.Assert.IsNotNull(System.Object)' failed. Assembly 'SPPD.Backend.DataAccess.Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is marked with the AllowPartiallyTrustedCallersAttribute, and uses the level 2 security transparency model. Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception. The test I am running is really straight forward and looks something like the following: [TestMethod] public void Can_create_mapper() { this.SetupTest(); var mockMapper = new Moq.Mock<IMapper>().Object; this._Resolver.Setup(x => x.Resolve<IMapper>()).Returns(mockMapper).Verifiable(); var testBaseDa = new TestBaseDa(); var result = testBaseDa.TestCreateMapper<IMapper>(); Assert.IsNotNull(result); //<<< THROWS EXCEPTION HERE Assert.AreSame(mockMapper, result); this._Resolver.Verify(); } I have no idea what this means and I have been looking around and have found very little on the topic. The closest reference I have found is this http://dotnetzip.codeplex.com/Thread/View.aspx?ThreadId=80274 but its not very clear on what they did to fix it... Anyone got any ideas?

    Read the article

  • Calculate an Internet (aka IP, aka RFC791) checksum in C#

    - by Pat
    Interestingly, I can find implementations for the Internet Checksum in almost every language except C#. Does anyone have an implementation to share? Remember, the internet protocol specifies that: "The checksum field is the 16 bit one's complement of the one's complement sum of all 16 bit words in the header. For purposes of computing the checksum, the value of the checksum field is zero." More explanation can be found from Dr. Math. There are some efficiency pointers available, but that's not really a large concern for me at this point. Please include your tests! (Edit: Valid comment regarding testing someone else's code - but I am going off of the protocol and don't have test vectors of my own and would rather unit test it than put into production to see if it matches what is currently being used! ;-) Edit: Here are some unit tests that I came up with. They test an extension method which iterates through the entire byte collection. Please comment if you find fault in the tests. [TestMethod()] public void InternetChecksum_SimplestValidValue_ShouldMatch() { IEnumerable<byte> value = new byte[1]; // should work for any-length array of zeros ushort expected = 0xFFFF; ushort actual = value.InternetChecksum(); Assert.AreEqual(expected, actual); } [TestMethod()] public void InternetChecksum_ValidSingleByteExtreme_ShouldMatch() { IEnumerable<byte> value = new byte[]{0xFF}; ushort expected = 0xFF; ushort actual = value.InternetChecksum(); Assert.AreEqual(expected, actual); } [TestMethod()] public void InternetChecksum_ValidMultiByteExtrema_ShouldMatch() { IEnumerable<byte> value = new byte[] { 0x00, 0xFF }; ushort expected = 0xFF00; ushort actual = value.InternetChecksum(); Assert.AreEqual(expected, actual); }

    Read the article

  • What header file is where the boost libray define its own primitive data type?

    - by ronghai
    Recently, I try to use the boost::spirit::qi binary endian parser to parse some binary data depends on the endianness of the Platform. There is a simple example, like following: Using declarations and variables: using boost::spirit::qi::little_word; using boost::spirit::qi::little_dword; using boost::spirit::qi::little_qword; boost::uint16_t us; boost::uint32_t ui; boost::uint64_t ul; Basic usage of the little endian binary parsers: test_parser_attr("\x01\x02", little_word, us); assert(us == 0x0201); test_parser_attr("\x01\x02\x03\x04", little_dword, ui); assert(ui == 0x04030201); test_parser_attr("\x01\x02\x03\x04\x05\x06\x07\x08", little_qword, ul); assert(ul == 0x0807060504030201LL); test_parser("\x01\x02", little_word(0x0201)); test_parser("\x01\x02\x03\x04", little_dword(0x04030201)); test_parser("\x01\x02\x03\x04\x05\x06\x07\x08", little_qword(0x0807060504030201LL)); It works very well. But my questions come, why do we need use some data types like boost::uint16_t, boost::uint32_t here? Can I use unsigned long or unsigned int here? And if I want to parse double or float data type, what boost data type should I use? And please tell me where is boost define the above these types? Thanks a lot.

    Read the article

  • Float addition promoted to double?

    - by Andreas Brinck
    I had a small WTF moment this morning. Ths WTF can be summarized with this: float x = 0.2f; float y = 0.1f; float z = x + y; assert(z == x + y); //This assert is triggered! (Atleast with visual studio 2008) The reason seems to be that the expression x + y is promoted to double and compared with the truncated version in z. (If i change z to double the assert isn't triggered). I can see that for precision reasons it would make sense to perform all floating point arithmetics in double precision before converting the result to single precision. I found the following paragraph in the standard (which I guess I sort of already knew, but not in this context): 4.6.1. "An rvalue of type float can be converted to an rvalue of type double. The value is unchanged" My question is, is x + y guaranteed to be promoted to double or is at the compiler's discretion? UPDATE: Since many people has claimed that one shouldn't use == for floating point, I just wanted to state that in the specific case I'm working with, an exact comparison is justified. Floating point comparision is tricky, here's an interesting link on the subject which I think hasn't been mentioned.

    Read the article

  • How to manage sessions in NHibernate unit tests?

    - by Ben
    I am a little unsure as to how to manage sessions within my nunit test fixtures. In the following test fixture, I am testing a repository. My repository constructor takes in an ISession (since I will be using session per request in my web application). In my test fixture setup I configure NHibernate and build the session factory. In my test setup I create a clean SQLite database for each test executed. [TestFixture] public class SimpleRepository_Fixture { private static ISessionFactory _sessionFactory; private static Configuration _configuration; [TestFixtureSetUp] // called before any tests in fixture are executed public void TestFixtureSetUp() { _configuration = new Configuration(); _configuration.Configure(); _configuration.AddAssembly(typeof(SimpleObject).Assembly); _sessionFactory = _configuration.BuildSessionFactory(); } [SetUp] // called before each test method is called public void SetupContext() { new SchemaExport(_configuration).Execute(true, true, false); } [Test] public void Can_add_new_simpleobject() { var simpleObject = new SimpleObject() { Name = "Object 1" }; using (var session = _sessionFactory.OpenSession()) { var repo = new SimpleObjectRepository(session); repo.Save(simpleObject); } using (var session =_sessionFactory.OpenSession()) { var repo = new SimpleObjectRepository(session); var fromDb = repo.GetById(simpleObject.Id); Assert.IsNotNull(fromDb); Assert.AreNotSame(simpleObject, fromDb); Assert.AreEqual(simpleObject.Name, fromDb.Name); } } } Is this a good approach or should I be handling the sessions differently? Thanks Ben

    Read the article

  • How do I change the base class at runtime in C#?

    - by MatthewMartin
    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

  • How to correctly waitFor() a saveScreenShot() end of execution.

    - by Alain
    Here is my full first working test: var expect = require('chai').expect; var assert = require('assert'); var webdriverjs = require('webdriverjs'); var client = {}; var webdriverOptions = { desiredCapabilities: { browserName: 'phantomjs' }, logLevel: 'verbose' }; describe('Test mysite', function(){ before(function() { client = webdriverjs.remote( webdriverOptions ); client.init(); }); var selector = "#mybodybody"; it('should see the correct title', function(done) { client.url('http://localhost/mysite/') .getTitle( function(err, title){ expect(err).to.be.null; assert.strictEqual(title, 'My title page' ); }) .waitFor( selector, 2000, function(){ client.saveScreenshot( "./ExtractScreen.png" ); }) .waitFor( selector, 7000, function(){ }) .call(done); }); after(function(done) { client.end(done); }); }); Ok, it does not do much, but after working many hours to get the environement correctly setup, it passed. Now, the only way I got it working is by playing with the waitFor() method and adjust the delays. It works, but I still do not understand how to surely wait for a png file to be saved on disk. As I will deal with tests orders, I will eventually get hung up from the test script before securely save the file. Now, How can I improve this screen save sequence and avoid loosing my screenshot ? Thanks.

    Read the article

  • ArrayList.Sort should be a stable sort with an IComparer but is not?

    - by Kaleb Pederson
    A stable sort is a sort that maintains the relative ordering of elements with the same value. The docs on ArrayList.Sort say that when an IComparer is provided the sort is stable: If comparer is set to null, this method performs a comparison sort (also called an unstable sort); that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal. To perform a stable sort, you must implement a custom IComparer interface. Unless I'm missing something, the following testcase shows that ArrayList.Sort is not using a stable sort: internal class DisplayOrdered { public int ID { get; set; } public int DisplayOrder { get; set; } public override string ToString() { return string.Format("ID: {0}, DisplayOrder: {1}", ID, DisplayOrder); } } internal class DisplayOrderedComparer : IComparer { public int Compare(object x, object y) { return ((DisplayOrdered)x).DisplayOrder - ((DisplayOrdered)y).DisplayOrder; } } [TestFixture] public class ArrayListStableSortTest { [Test] public void TestWeblinkCallArrayListIsSortedUsingStableSort() { var call1 = new DisplayOrdered {ID = 1, DisplayOrder = 0}; var call2 = new DisplayOrdered {ID = 2, DisplayOrder = 0}; var call3 = new DisplayOrdered {ID = 3, DisplayOrder = 2}; var list = new ArrayList {call1, call2, call3}; list.Sort(new DisplayOrderedComparer()); // expected order (by ID): 1, 2, 3 (because the DisplayOrder // is equal for ID's 1 and 2, their ordering should be // maintained for a stable sort.) Assert.AreEqual(call1, list[0]); // Actual: ID=2 ** FAILS Assert.AreEqual(call2, list[1]); // Actual: ID=1 Assert.AreEqual(call3, list[2]); // Actual: ID=3 } } Am I missing something? If not, would this be a documentation bug or a library bug? Apparently using an OrderBy in Linq gives a stable sort.

    Read the article

  • How can I write a unit test to determine whether an object can be garbage collected?

    - by driis
    In relation to my previous question, I need to check whether a component that will be instantiated by Castle Windsor, can be garbage collected after my code has finished using it. I have tried the suggestion in the answers from the previous question, but it does not seem to work as expected, at least for my code. So I would like to write a unit test that tests whether a specific object instance can be garbage collected after some of my code has run. Is that possible to do in a reliable way ? EDIT I currently have the following test based on Paul Stovell's answer, which succeeds: [TestMethod] public void ReleaseTest() { WindsorContainer container = new WindsorContainer(); container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy(); container.AddComponentWithLifestyle<ReleaseTester>(LifestyleType.Transient); Assert.AreEqual(0, ReleaseTester.refCount); var weakRef = new WeakReference(container.Resolve<ReleaseTester>()); Assert.AreEqual(1, ReleaseTester.refCount); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.AreEqual(0, ReleaseTester.refCount, "Component not released"); } private class ReleaseTester { public static int refCount = 0; public ReleaseTester() { refCount++; } ~ReleaseTester() { refCount--; } } Am I right assuming that, based on the test above, I can conclude that Windsor will not leak memory when using the NoTrackingReleasePolicy ?

    Read the article

  • Best way to unit test Collection?

    - by limc
    I'm just wondering how folks unit test and assert that the "expected" collection is the same/similar as the "actual" collection (order is not important). To perform this assertion, I wrote my simple assert API:- public void assertCollection(Collection<?> expectedCollection, Collection<?> actualCollection) { assertNotNull(expectedCollection); assertNotNull(actualCollection); assertEquals(expectedCollection.size(), actualCollection.size()); assertTrue(expectedCollection.containsAll(actualCollection)); assertTrue(actualCollection.containsAll(expectedCollection)); } Well, it works. It's pretty simple if I'm asserting just bunch of Integers or Strings. It can also be pretty painful if I'm trying to assert a collection of Hibernate domains, say for example. The collection.containsAll(..) relies on the equals(..) to perform the check, but I always override the equals(..) in my Hibernate domains to check only the business keys (which is the best practice stated in the Hibernate website) and not all the fields of that domain. Sure, it makes sense to check just against the business keys, but there are times I really want to make sure all the fields are correct, not just the business keys (for example, new data entry record). So, in this case, I can't mess around with the domain.equals(..) and it almost seems like I need to implement some comparators for just unit testing purposes instead of relying on collection.containsAll(..). Are there some testing libraries I could leverage here? How do you test your collection? Thanks.

    Read the article

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