Search Results

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

Page 3/37 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • NUnit: Assert.Throws

    - by epitka
    How do I use Assert.Throws to assert type of the exception and the actual message workding. Something like this: Assert.Throws<Exception>( ()=>user.MakeUserActive()).WithMessage("Actual exception message") Method I am testing throws multiple messages of the same type, with different message and I need a way to test that correct message is thrown depending on the context.

    Read the article

  • Redundant assert statements in .NET unit test framework

    - by Prabhu
    Isn't it true that every assert statement can be translated to an Assert.IsTrue, since by definition, you are asserting whether something is true or false? Why is it that test frameworks introduce options like AreEquals, IsNotNull, and especially IsFalse? I feel I spend too much time thinking about which Assert to use when I write unit tests.

    Read the article

  • Debug.Assert Appears in Release Mode

    - by Ngu Soon Hui
    We all know that Debug.Assert will not be compiled into the dlls when compiled in release mode. But for some reason Debug.Assert did appear in the release version of a component I wrote. I suspect that I might have mess up my csproject setting. Any idea why Debug.Assert appears in release mode? P/S: I have double checked to make sure that I was really compiling in release mode before asking this question.

    Read the article

  • Assert.AreEqual to not fail when comparing an enum and an int

    - by codingbear
    I'm not sure if this is doable, but I will just give a shot. I am calling Assert.AreEqual() method. For the parameters, I'm passing... an enum value which has Int32 as the underlying type because I didn't specify the base type an int (Int32) value Assert fails because it sees that the enum is not int (which is definitely correct). However, is there a way to make this Assert pass when the enum has the correct int value as the 2nd parameter? I can cast the enum to int and have it a quick fix, but it's really ugly. I was expecting some kind of overriding a method that Assert uses to compare 2 different objects and implicitly make that enum type look like an int. However, I wasn't successful at finding any hint/answer around that so far. Someone suggested to create a type converter and use the TypeConverterAttribute to get around. If this works for sure and is the only way to do it, I would; however, it does seem a lot of unnecessary work.

    Read the article

  • Best practices for multiple asserts on same result in C#

    - by asdseee
    What do you think is cleanest way of doing multiple asserts on a result? In the past I've put them all the same test but this is starting to feel a little dirty, I've just been playing with another idea using setup. [TestFixture] public class GridControllerTests { protected readonly string RequestedViewId = "A1"; protected GridViewModel Result { get; set;} [TestFixtureSetUp] public void Get_UsingStaticSettings_Assign() { var dataRepository = new XmlRepository("test.xml"); var settingsRepository = new StaticViewSettingsRepository(); var controller = new GridController(dataRepository, settingsRepository); this.Result = controller.Get(RequestedViewId); } [Test] public void Get_UsingStaticSettings_NotNull() { Assert.That(this.Result,Is.Not.Null); } [Test] public void Get_UsingStaticSettings_HasData() { Assert.That(this.Result.Data,Is.Not.Null); Assert.That(this.Result.Data.Count,Is.GreaterThan(0)); } [Test] public void Get_UsingStaticSettings_IdMatches() { Assert.That(this.Result.State.ViewId,Is.EqualTo(RequestedViewId)); } [Test] public void Get_UsingStaticSettings_FirstTimePageIsOne() { Assert.That(this.Result.State.CurrentPage, Is.EqualTo(1)); } }

    Read the article

  • Prolog - ASSERT and RETRACT

    - by KP65
    I was wondering, I am aware you can use assert to add facts or rules or whatever if you have declared the predicate to be -:dynamic, but this only allows the changes that are made to be kept in that session only, e.g. if you close the prolog window then the database changes are lost. So I was wondering, is there any way of making it so that the assert and retract predicates can make permanent changes to the prolog .pl file? Thanks

    Read the article

  • assert fact into file in prolog

    - by smile
    Hello everyone, How can I assert a fact into a file without deleting the previous fact? In the following line, when I execute it twice, the second fact overwrites the first fact: tell('animal.txt'),write(Animal),nl,told. But when I use assert or assertz it will do nothing. Help me please. Thank you :)

    Read the article

  • What does assert do?

    - by peiska
    What does assert do? for example in the function? private static int charAt(String s, int d) { assert d >= 0 && d <= s.length(); if (d == s.length()) return -1; return s.charAt(d); }

    Read the article

  • Best practice for debug Asserts during Unit testing

    - by Steve Steiner
    Does heavy use of unit tests discourage the use of debug asserts? It seems like a debug assert firing in the code under test implies the unit test shouldn't exist or the debug assert shouldn't exist. "There can be only one" seems like a reasonable principle. Is this the common practice? Or do you disable your debug asserts when unit testing, so they can be around for integration testing? Edit: I updated 'Assert' to debug assert to distinguish an assert in the code under test from the lines in the unit test that check state after the test has run. Also here is an example that I believe shows the dilema: A unit test passes invalid inputs for a protected function that asserts it's inputs are valid. Should the unit test not exist? It's not a public function. Perhaps checking the inputs would kill perf? Or should the assert not exist? The function is protected not private so it should be checking it's inputs for safety.

    Read the article

  • Writing Unit Tests for ASP.NET Web API Controller

    - by shiju
    In this blog post, I will write unit tests for a ASP.NET Web API controller in the EFMVC reference application. Let me introduce the EFMVC app, If you haven't heard about EFMVC. EFMVC is a simple app, developed as a reference implementation for demonstrating ASP.NET MVC, EF Code First, ASP.NET Web API, Domain-Driven Design (DDD), Test-Driven Development (DDD). The current version is built with ASP.NET MVC 4, EF Code First 5, ASP.NET Web API, Autofac, AutoMapper, Nunit and Moq. All unit tests were written with Nunit and Moq. You can download the latest version of the reference app from http://efmvc.codeplex.com/ Unit Test for HTTP Get Let’s write a unit test class for verifying the behaviour of a ASP.NET Web API controller named CategoryController. Let’s define mock implementation for Repository class, and a Command Bus that is used for executing write operations.  [TestFixture] public class CategoryApiControllerTest { private Mock<ICategoryRepository> categoryRepository; private Mock<ICommandBus> commandBus; [SetUp] public void SetUp() {     categoryRepository = new Mock<ICategoryRepository>();     commandBus = new Mock<ICommandBus>(); } The code block below provides the unit test for a HTTP Get operation. [Test] public void Get_All_Returns_AllCategory() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()                 {                     Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }                 }     };     // Act     var categories = controller.Get();     // Assert     Assert.IsNotNull(categories, "Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<CategoryWithExpense>),categories, "Wrong Model");             Assert.AreEqual(3, categories.Count(), "Got wrong number of Categories"); }        The GetCategories method is provided below: private static IEnumerable<CategoryWithExpense> GetCategories() {     IEnumerable<CategoryWithExpense> fakeCategories = new List<CategoryWithExpense> {     new CategoryWithExpense {CategoryId=1, CategoryName = "Test1", Description="Test1Desc", TotalExpenses=1000},     new CategoryWithExpense {CategoryId=2, CategoryName = "Test2", Description="Test2Desc",TotalExpenses=2000},     new CategoryWithExpense { CategoryId=3, CategoryName = "Test3", Description="Test3Desc",TotalExpenses=3000}       }.AsEnumerable();     return fakeCategories; } In the unit test method Get_All_Returns_AllCategory, we specify setup on the mocked type ICategoryrepository, for a call to GetCategoryWithExpenses method returns dummy data. We create an instance of the ApiController, where we have specified the Request property of the ApiController since the Request property is used to create a new HttpResponseMessage that will provide the appropriate HTTP status code along with response content data. Unit Tests are using for specifying the behaviour of components so that we have specified that Get operation will use the model type IEnumerable<CategoryWithExpense> for sending the Content data. The implementation of HTTP Get in the CategoryController is provided below: public IQueryable<CategoryWithExpense> Get() {     var categories = categoryRepository.GetCategoryWithExpenses().AsQueryable();     return categories; } Unit Test for HTTP Post The following are the behaviours we are going to implement for the HTTP Post: A successful HTTP Post  operation should return HTTP status code Created An empty Category should return HTTP status code BadRequest A successful HTTP Post operation should provide correct Location header information in the response for the newly created resource. Writing unit test for HTTP Post is required more information than we write for HTTP Get. In the HTTP Post implementation, we will call to Url.Link for specifying the header Location of Response as shown in below code block. var response = Request.CreateResponse(HttpStatusCode.Created, category); string uri = Url.Link("DefaultApi", new { id = category.CategoryId }); response.Headers.Location = new Uri(uri); return response; While we are executing Url.Link from unit tests, we have to specify HttpRouteData information from the unit test method. Otherwise, Url.Link will get a null value. The code block below shows the unit tests for specifying the behaviours for the HTTP Post operation. [Test] public void Post_Category_Returns_CreatedStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();          var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Post(category);               // Assert     Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);     var newCategory = JsonConvert.DeserializeObject<CategoryModel>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(string.Format("http://localhost/api/category/{0}", newCategory.CategoryId), response.Headers.Location.ToString()); } [Test] public void Post_EmptyCategory_Returns_BadRequestStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 0;     category.CategoryName = "";     // The ASP.NET pipeline doesn't run, so validation don't run.     controller.ModelState.AddModelError("", "mock error message");     var response = controller.Post(category);     // Assert     Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);   } In the above code block, we have written two unit methods, Post_Category_Returns_CreatedStatusCode and Post_EmptyCategory_Returns_BadRequestStatusCode. The unit test method Post_Category_Returns_CreatedStatusCode  verifies the behaviour 1 and 3, that we have defined in the beginning of the section “Unit Test for HTTP Post”. The unit test method Post_EmptyCategory_Returns_BadRequestStatusCode verifies the behaviour 2. For extracting the data from response, we call Content.ReadAsStringAsync().Result of HttpResponseMessage object and deserializeit it with Json Convertor. The implementation of HTTP Post in the CategoryController is provided below: // POST /api/category public HttpResponseMessage Post(CategoryModel category) {       if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         if (result.Success)         {                               var response = Request.CreateResponse(HttpStatusCode.Created, category);             string uri = Url.Link("DefaultApi", new { id = category.CategoryId });             response.Headers.Location = new Uri(uri);             return response;         }     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); } The unit test implementation for HTTP Put and HTTP Delete are very similar to the unit test we have written for  HTTP Get. The complete unit tests for the CategoryController is given below: [TestFixture] public class CategoryApiControllerTest { private Mock<ICategoryRepository> categoryRepository; private Mock<ICommandBus> commandBus; [SetUp] public void SetUp() {     categoryRepository = new Mock<ICategoryRepository>();     commandBus = new Mock<ICommandBus>(); } [Test] public void Get_All_Returns_AllCategory() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()                 {                     Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }                 }     };     // Act     var categories = controller.Get();     // Assert     Assert.IsNotNull(categories, "Result is null");     Assert.IsInstanceOf(typeof(IEnumerable<CategoryWithExpense>),categories, "Wrong Model");             Assert.AreEqual(3, categories.Count(), "Got wrong number of Categories"); }        [Test] public void Get_CorrectCategoryId_Returns_Category() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     var response = controller.Get(1);     // Assert     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);     var category = JsonConvert.DeserializeObject<CategoryWithExpense>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(1, category.CategoryId, "Got wrong number of Categories"); } [Test] public void Get_InValidCategoryId_Returns_NotFound() {     // Arrange        IEnumerable<CategoryWithExpense> fakeCategories = GetCategories();     categoryRepository.Setup(x => x.GetCategoryWithExpenses()).Returns(fakeCategories);     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     var response = controller.Get(5);     // Assert     Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);            } [Test] public void Post_Category_Returns_CreatedStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();          var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Post(category);               // Assert     Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);     var newCategory = JsonConvert.DeserializeObject<CategoryModel>(response.Content.ReadAsStringAsync().Result);     Assert.AreEqual(string.Format("http://localhost/api/category/{0}", newCategory.CategoryId), response.Headers.Location.ToString()); } [Test] public void Post_EmptyCategory_Returns_BadRequestStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     var httpConfiguration = new HttpConfiguration();     WebApiConfig.Register(httpConfiguration);     var httpRouteData = new HttpRouteData(httpConfiguration.Routes["DefaultApi"],         new HttpRouteValueDictionary { { "controller", "category" } });     var controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/api/category/")         {             Properties =             {                 { HttpPropertyKeys.HttpConfigurationKey, httpConfiguration },                 { HttpPropertyKeys.HttpRouteDataKey, httpRouteData }             }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 0;     category.CategoryName = "";     // The ASP.NET pipeline doesn't run, so validation don't run.     controller.ModelState.AddModelError("", "mock error message");     var response = controller.Post(category);     // Assert     Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);   } [Test] public void Put_Category_Returns_OKStatusCode() {     // Arrange        commandBus.Setup(c => c.Submit(It.IsAny<CreateOrUpdateCategoryCommand>())).Returns(new CommandResult(true));     Mapper.CreateMap<CategoryFormModel, CreateOrUpdateCategoryCommand>();     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act     CategoryModel category = new CategoryModel();     category.CategoryId = 1;     category.CategoryName = "Mock Category";     var response = controller.Put(category.CategoryId,category);     // Assert     Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);    } [Test] public void Delete_Category_Returns_NoContentStatusCode() {     // Arrange              commandBus.Setup(c => c.Submit(It.IsAny<DeleteCategoryCommand >())).Returns(new CommandResult(true));     CategoryController controller = new CategoryController(commandBus.Object, categoryRepository.Object)     {         Request = new HttpRequestMessage()         {             Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }         }     };     // Act               var response = controller.Delete(1);     // Assert     Assert.AreEqual(HttpStatusCode.NoContent, response.StatusCode);   } private static IEnumerable<CategoryWithExpense> GetCategories() {     IEnumerable<CategoryWithExpense> fakeCategories = new List<CategoryWithExpense> {     new CategoryWithExpense {CategoryId=1, CategoryName = "Test1", Description="Test1Desc", TotalExpenses=1000},     new CategoryWithExpense {CategoryId=2, CategoryName = "Test2", Description="Test2Desc",TotalExpenses=2000},     new CategoryWithExpense { CategoryId=3, CategoryName = "Test3", Description="Test3Desc",TotalExpenses=3000}       }.AsEnumerable();     return fakeCategories; } }  The complete implementation for the Api Controller, CategoryController is given below: public class CategoryController : ApiController {       private readonly ICommandBus commandBus;     private readonly ICategoryRepository categoryRepository;     public CategoryController(ICommandBus commandBus, ICategoryRepository categoryRepository)     {         this.commandBus = commandBus;         this.categoryRepository = categoryRepository;     } public IQueryable<CategoryWithExpense> Get() {     var categories = categoryRepository.GetCategoryWithExpenses().AsQueryable();     return categories; }   // GET /api/category/5 public HttpResponseMessage Get(int id) {     var category = categoryRepository.GetCategoryWithExpenses().Where(c => c.CategoryId == id).SingleOrDefault();     if (category == null)     {         return Request.CreateResponse(HttpStatusCode.NotFound);     }     return Request.CreateResponse(HttpStatusCode.OK, category); }   // POST /api/category public HttpResponseMessage Post(CategoryModel category) {       if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         if (result.Success)         {                               var response = Request.CreateResponse(HttpStatusCode.Created, category);             string uri = Url.Link("DefaultApi", new { id = category.CategoryId });             response.Headers.Location = new Uri(uri);             return response;         }     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); }   // PUT /api/category/5 public HttpResponseMessage Put(int id, CategoryModel category) {     if (ModelState.IsValid)     {         var command = new CreateOrUpdateCategoryCommand(category.CategoryId, category.CategoryName, category.Description);         var result = commandBus.Submit(command);         return Request.CreateResponse(HttpStatusCode.OK, category);     }     else     {         return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);     }     throw new HttpResponseException(HttpStatusCode.BadRequest); }       // DELETE /api/category/5     public HttpResponseMessage Delete(int id)     {         var command = new DeleteCategoryCommand { CategoryId = id };         var result = commandBus.Submit(command);         if (result.Success)         {             return new HttpResponseMessage(HttpStatusCode.NoContent);         }             throw new HttpResponseException(HttpStatusCode.BadRequest);     } } Source Code The EFMVC app can download from http://efmvc.codeplex.com/ . The unit test project can be found from the project EFMVC.Tests and Web API project can be found from EFMVC.Web.API.

    Read the article

  • Assert.AreEqual() Exception in VS2010

    - by Tom Miller
    I am fairly new to unit testing and am using VS2010 to develop in and run my tests. I have a simple test, illustrated below, that simply compares 2 System.Data.DataTableReader objects. I know that they are equal as they are both created using the same object types, the same input file and I have verified that the objects "look" the same. I realize I may be dealing with a couple of issues, one being whether or not this is the proper use of Assert.AreEqual or even the proper way to test this scenario, and the other being the main issue I am dealing with which is why this test fails with this exception: Failed 00:00:00.1000660 0 Assert.AreEqual failed. Expected:<System.Data.DataTableReader>. Actual:<System.Data.DataTableReader>. Here is the unit test code that is failing: public void EntriesTest() { AuditLog target = new AuditLog(); target.Init(); DataSet ds = new DataSet(); ds.ReadXml(TestContext.DataRow["AuditLogPath"].ToString()); DataTableReader expected = ds.Tables[0].CreateDataReader(); DataTableReader actual = target.Entries.Tables[0].CreateDataReader(); Assert.AreEqual<DataTableReader>(expected, actual); } Any help would be greatly appreciated!

    Read the article

  • NUnit Assert a list of objects in no order

    - by Shawn Mclean
    How do I Assert a collection of items in no particular order? I just want to make sure all the items are in the list. I'm heard of CollectionAssert but I do not see any method that would do what I want. My object looks like this: public class Vector2{ public float X {get; set;} public float Y {get; set;} } Assert - I want something like this: CollectionAssert.ContainsAll(mesh.GetPolygonVertices(0), aListOfVertices); mesh.GetPolygonVertices(int) returns a List<Vector2> and aListOfVertices contains all of what is returned, but not guaranteed that order.

    Read the article

  • Debug.Assert seems not to work in Mono

    - by Jan-Willem
    Consider the following C# program: using System; using System.Diagnostics; namespace Test { class MainClass { public static void Main (string[] args) { Debug.Assert(false); Debug.Fail("fail!"); Console.WriteLine ("Hello World!"); } } } When compiling this using: dmcs -debug -d:DEBUG Main.cs and then running it with: mono --debug Main.exe the assertion and fail seem to be ignored. The output is just: Hello World! I checked other related questions on StackOverflow, but I could not find a solution. In particular the solution give in Mono - Debug.Assert does not work does not work. (UPDATE: the update solution does work, see below comments.) I use Mono 2.1.5-1 on Ubuntu 11.10.

    Read the article

  • C++ - Totally suspend windows application

    - by HardCoder1986
    Hello! I am developing a simple WinAPI application and started from writing my own assertion system. I have a macro defined like ASSERT(X) which would make pretty the same thing as assert(X) does, but with more information, more options and etc. At some moment (when that assertion system was already running and working) I realized there is a problem. Suppose I wrote a code that does some action using a timer and (just a simple example) this action is done while handling WM_TIMER message. And now, the situation changes the way that this code starts throwing an assert. This assert message would be shown every TIMER_RESOLUTION milliseconds and would simply flood the screen. Options for solving this situation could be: 1) Totally pause application running (probably also, suspend all threads) when the assertion messagebox is shown and continue running after it is closed 2) Make a static counter for the shown asserts and don't show asserts when one of them is already showing (but this doesn't pause application) 3) Group similiar asserts and show only one for each assert type (but this also doesn't pause application) 4) Modify the application code (for example, Get / Translate / Dispatch message loop) so that it suspends itself when there are any asserts. This is good, but not universal and looks like a hack. To my mind, option number 1 is the best. But I don't know any way how this can be achieved. What I'm seeking for is a way to pause the runtime (something similiar to Pause button in the debugger). Does somebody know how to achieve this? Also, if somebody knows an efficient way to handle this problem - I would appreciate your help. Thank you.

    Read the article

  • How to assert that a certain exception is thrown in jUnit4.5 tests

    - by SCdF
    How can use jUnit4.5 idiomatically to test that come code throws an exception? While I can certainly do something like this: @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } I recall that there is an annotation or an Assert.xyz or something that is far less cludgy and far more in-the-spirit of jUnit for these sorts of situations.

    Read the article

  • How to assert on number of html table rows in ruby using capybara + cucumber

    - by Neil
    I am trying to get to grips with BDD web development in Ruby using cucumber + capybara and I am stuck at what should be an easy task - just to check the number of rows in a table. Something along the lines of: page.should have_xpath("//table[@id='myTable']") find("//table[@id='myTable']/tr").length.should = 3 But this doesn't work and I can't find a way to assert against the table length. Any ideas anyone (please be easy on me tho' I'm a ruby nooby) Thanks in advance Neil

    Read the article

  • Why does this Assert fail?

    - by Peter Goras
    IEnumerable<ReportReceipt> expected = new List<ReportReceipt>() { new ReportReceipt("fileName1","Hash1","some comments1") }; IEnumerable<ReportReceipt> actual = new List<ReportReceipt>() { new ReportReceipt("fileName1","Hash1","some comments1") }; Assert.IsTrue(expected.SequenceEqual(actual)); I'm running MSTest with VS 2008.

    Read the article

  • Rails testing: assert render action

    - by deb
    How can I write a test to assert that the action new is rendered? def method ... render :action => :new end I'm looking for something like: assert_equal layout, @response.layout assert_equal format, @request.format I know I can't do @response.action Thanks in advance! Deb

    Read the article

  • Should I create my own Assert class based on these reasons?

    - by Mike
    The main reason I don't like Debug.Assert is the fact that these assertions are disabled in Release. I know that there's a performance reason for that, but at least in my situation I believe the gains would outweigh the cost. (By the way, I'm guessing this is the situation in most cases). And yes, I know that you can use Trace.Assert instead. But even though that would work, I find the name Trace distracting, since I don't see this as tracing. The other reason to create my own class is laziness I guess, since I could write methods for the most usual cases like Assert.IsNotNull, Assert.Equals and so forth. The second part of my question has to do with using Environment.FailFast in this class. Would that be a good idea? I do like the ideas put forth in this document. That's pretty much where I got the idea from. One last point. Does creating a design like this imply having an untestable code path, as described in this answer by Eric Lippert on a different (but related) question?

    Read the article

  • nUnit Assert.That(method,Throws.Exception) not catching exceptions

    - by JasonM
    Hi Everyone, Can someone tell me why this unit test that checks for exceptions fails? Obviously my real test is checking other code but I'm using Int32.Parse to show the issue. [Test] public void MyTest() { Assert.That(Int32.Parse("abc"), Throws.Exception.TypeOf<FormatException>()); } The test fails, giving this error. Obviously I'm trying to test for this exception and I think I'm missing something in my syntax. Error 1 TestCase '.MyTest' failed: System.FormatException : Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) based on the documentation at Throws Constraint (NUnit 2.5)

    Read the article

  • Insertion sort invariant assertion fails

    - by user1661211
    In the following code at the end of the for loop I use the assert function in order to test that a[i+1] is greater than or equal to a[i] but I get the following error (after the code below). Also in c++ the assert with the following seems to work just fine but in python (the following code) it does not seem to work...anyone know why? import random class Sorting: #Precondition: An array a with values. #Postcondition: Array a[1...n] is sorted. def insertion_sort(self,a): #First loop invariant: Array a[1...i] is sorted. for j in range(1,len(a)): key = a[j] i = j-1 #Second loop invariant: a[i] is the greatest value from a[i...j-1] while i >= 0 and a[i] > key: a[i+1] = a[i] i = i-1 a[i+1] = key assert a[i+1] >= a[i] return a def random_array(self,size): b = [] for i in range(0,size): b.append(random.randint(0,1000)) return b sort = Sorting() print sort.insertion_sort(sort.random_array(10)) The Error: Traceback (most recent call last): File "C:\Users\Albaraa\Desktop\CS253\Programming 1\Insertion_Sort.py", line 27, in <module> print sort.insertion_sort(sort.random_array(10)) File "C:\Users\Albaraa\Desktop\CS253\Programming 1\Insertion_Sort.py", line 16, in insertion_sort assert a[i+1] >= a[i] AssertionError

    Read the article

  • What is the role of asserts in C++ programs that have unit tests?

    - by lhumongous
    Greetings, I've been adding unit tests to some legacy C++ code, and I've run into many scenarios where an assert inside a function will get tripped during a unit test run. A common idiom that I've run across is functions that take pointer arguments and immediately assert if the argument is NULL. I could easily get around this by disabling asserts when I'm unit testing. But I'm starting to wonder if unit tests are supposed to alleviate the need for runtime asserts. Is this a correct assessment? Are unit tests supposed to replace runtime asserts by happening sooner in the pipeline (ie: the error is caught in a failing test instead of when the program is running). On the other hand, I don't like adding soft fails to code (eg: if(param == NULL) return false;). A runtime assert at least makes it easier to debug a problem in case a unit test missed a bug. Thanks!

    Read the article

  • Is Debug.Assert obsolete if you write unit tests?

    - by Justin Pihony
    Just like the question asks, is there a need to add Debug.Assert into your code if you are writing unit tests (which has its own assertions)? I could see that this might make the code more obvious without having to go into the tests, however it just seems that you might end up with duplicated asserts. It seems to me that Debug.Assert was helpful before unit-testing became more prevalent, but is now unnecessary. Or, am I not thinking of some use case?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >