Search Results

Search found 694 results on 28 pages for 'mock'.

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

  • How to populate a private container for unit test?

    - by Sardathrion
    I have a class that defines a private (well, __container to be exact since it is python) container. I am using the information within said container as part of the logic of what the class does and have the ability to add/delete the elements of said container. For unit tests, I need to populate this container with some data. That date depends on the test done and thus putting it all in setUp() would be impractical and bloated -- plus it could add unwanted side effects. Since the data is private, I can only add things via the public interface of the object. This run codes that need not be run during a unit test and in some case is just a copy and paste from another test. Currently, I am mocking the whole container but somehow it does not feel that elegant a solution. Due to Python mocking frame work (mock), this requires the container to be public -- so I can use patch.dict(). I would rather keep that data private. What pattern can one use to still populate the containers without excising the public method so I have data to test with? Is there a way to do this with mock' patch.dict() that I missed?

    Read the article

  • Why one loop is performing better than other memory wise as well as performance wise?

    - by Mohit
    I have following two loops in C#, and I am running these loops for a collection with 10,000 records being downloaded with paging using "yield return" First foreach(var k in collection) { repo.Save(k); } Second var collectionEnum = collection.GetEnumerator(); while (collectionEnum.MoveNext()) { var k = collectionEnum.Current; repo.Save(k); k = null; } Seems like that the second loop consumes less memory and it faster than the first loop. Memory I understand may be because of k being set to null(Even though I am not sure). But how come it is faster than for each. Following is the actual code [Test] public void BechmarkForEach_Test() { bool isFirstTimeSync = true; Func<Contact, bool> afterProcessing = contactItem => { return true; }; var contactService = CreateSerivce("/administrator/components/com_civicrm"); var contactRepo = new ContactRepository(new Mock<ILogger>().Object); contactRepo.Drop(); contactRepo = new ContactRepository(new Mock<ILogger>().Object); Profile("For Each Profiling",1,()=>{ var localenumertaor=contactService.Download(); foreach (var item in localenumertaor) { if (isFirstTimeSync) item.StateFlag = 1; item.ClientTimeStamp = DateTime.UtcNow; if (item.StateFlag == 1) contactRepo.Insert(item); else contactRepo.Update(item); afterProcessing(item); } contactRepo.DeleteAll(); }); } [Test] public void BechmarkWhile_Test() { bool isFirstTimeSync = true; Func<Contact, bool> afterProcessing = contactItem => { return true; }; var contactService = CreateSerivce("/administrator/components/com_civicrm"); var contactRepo = new ContactRepository(new Mock<ILogger>().Object); contactRepo.Drop(); contactRepo = new ContactRepository(new Mock<ILogger>().Object); var itemsCollection = contactService.Download().GetEnumerator(); Profile("While Profiling", 1, () => { while (itemsCollection.MoveNext()) { var item = itemsCollection.Current; //if First time sync then ignore and overwrite the stateflag if (isFirstTimeSync) item.StateFlag = 1; item.ClientTimeStamp = DateTime.UtcNow; if (item.StateFlag == 1) contactRepo.Insert(item); else contactRepo.Update(item); afterProcessing(item); item = null; } contactRepo.DeleteAll(); }); } static void Profile(string description, int iterations, Action func) { // clean up GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); // warm up func(); var watch = Stopwatch.StartNew(); for (int i = 0; i < iterations; i++) { func(); } watch.Stop(); Console.Write(description); Console.WriteLine(" Time Elapsed {0} ms", watch.ElapsedMilliseconds); } I m using the micro bench marking, from a stackoverflow question itself benchmarking-small-code The time taken is For Each Profiling Time Elapsed 5249 ms While Profiling Time Elapsed 116 ms

    Read the article

  • How to throw a SqlException(need for mocking)

    - by chobo2
    Hi I am trying to test some exceptions in my project and one of the Exceptions I catch is SQlException. Now It seems that you can't go new SqlException() so I am not sure how I can throw a exception especially without somehow calling the database(and since it is unit tests it is usually advised not to call the database since it is slow). So I am using nunit and moq so I am not sure how to fake this. Edit Based on the answers they seem to all be based on ado.net I am using linq to sql. So that stuff is like behind the scenes. Edit @ Matt Hamilton System.ArgumentException : Type to mock must be an interface or an abstract or non-sealed class. at Moq.Mock`1.CheckParameters() at Moq.Mock`1..ctor(MockBehavior behavior, Object[] args) at Moq.Mock`1..ctor(MockBehavior behavior) at Moq.Mock`1..ctor() Posts to the first line when it tries to mockup var ex = new Mock<System.Data.SqlClient.SqlException>(); ex.SetupGet(e => e.Message).Returns("Exception message");

    Read the article

  • How should I pass an object wrapping an API to a class using that API?

    - by Billy ONeal
    Hello everyone :) This is a revised/better written version of the question I asked earlier today -- that question is deleted now. I have a project where I'm getting started with Google Mock. I have created a class, and that class calls functions whithin the Windows API. I've also created a wrapper class with virtual functions wrapping the Windows API, as described in the Google Mock CheatSheet. I'm confused however at how I should pass the wrapper into my class that uses that object. Obviously that object needs to be polymorphic, so I can't pass it by value, forcing me to pass a pointer. That in and of itself is not a problem, but I'm confused as to who should own the pointer to the class wrapping the API. So... how should I pass the wrapper class into the real class to facilitate mocking?

    Read the article

  • Mocking User.Identity in ASP.NET MVC

    - by Trey Carroll
    I need to create Unit Tests for an ASP.NET MVC 2.0 web site. The site uses Windows Authentication. I've been reading up on the necessity to mock the HTTP context for code that deals with the HttpContext. I feel like I'm starting to get a handle on the DI pattern as well. (Give the class an attribute of type IRepository and then pass in a Repository object when you instantiate the controller.) What I don't understand, however, is the proper way to Mock the Windows Principal object available through User.Identity. Is this part of the HttpContext? Does any body have a link to an article that demonstrates this (or a recommendation for a book)? Thanks, Trey Carroll

    Read the article

  • OCmock and MKReverseGeocoder

    - by user315374
    Hi, I would like to test a method that uses reverse Geocoding. What i would like to do is : set the geocoder as a property of my controller create the geocoder in the init method call the geocoder in the method i want to test replace the geocoder with a mock in my test The problem is that the MKReverseGeocoder coordinate property is read only, i can only set it in the constructor method : [[MKReverseGeocoder alloc] initWithCoordinate:coord] And of course the coordinates are only available in the method i want to test.. Does anyone knows how i could mock the MKReverseGeocoder class ? Thanks in advance, Vincent.

    Read the article

  • So how I can control the page contents loading sequence in dojo

    - by David Zhao
    Hi there, I'm using dojo for our UI's, and would like to load certain part of page contents in sequence. For example, for a certain stock, I'd like to load stock general information, such as ticker, company name, key stats, etc. and a grid with the last 30 days open/close prices. Different contents will be fetched from the server separately. Now, I'd like first load the grid so the user can have something to look at, then, say, start loading of key stats which is a large data set takes longer time to load. How do I do this. I tried: dojo.addOnLoad(function() { startGrid(); //mock grid startup function which works fine getKeyStats(); //mock key stat getter function also works fine }); But dojo is loading getKeyStats(), then startGrid() here for some reason, and sequence doesn't seem be matter here. So how I can control the loading sequence at will? Thanks in advance! David

    Read the article

  • structuremap configuration change based on settings in app.config

    - by user74825
    I am using structuremap in my project. To inject different implementation of a repository, I want to have a switch in app.config which changes all real implementation of a repository to a mock repositories. Lets say IRepository has two implementations RealRepository and MockRepository ForRequestedType() .TheDefaultIsConcreteType(); I want to have a switch in app.config / web.config say (Mock=1), which changes all real repositories implementation to ForRequestedType() .TheDefaultIsConcreteType(); I don't want to write whole plugin definition in app.config, just want one switch, how do I implement this?

    Read the article

  • How should moq's VerifySet be called in VB.net

    - by Bender
    I am trying to test that a property has been set but when I write this as a unit test: moqFeed.VerifySet(Function(m) m.RowAdded = "Row Added") moq complains that "Expression is not a property setter invocation" My complete code is Imports Gallio.Framework Imports MbUnit.Framework Imports Moq <TestFixture()> Public Class GUI_FeedPresenter_Test Private moqFeed As Moq.Mock(Of IFeedView) <SetUp()> Sub Setup() moqFeed = New Mock(Of IFeedView) End Sub <Test()> Public Sub New_Presenter() Dim pres = New FeedPresenter(moqFeed.Object) moqFeed.VerifySet(Function(m) m.RowAdded = "Row Added") End Sub End Class Public Interface IFeedView Property RowAdded() As String End Interface Public Class FeedPresenter Private _FeedView As IFeedView Public Sub New(ByVal feedView As IFeedView) _FeedView = feedView _FeedView.RowAdded = "Row Added" End Sub End Class I can't find any examples of moq in VB, I would be grateful for any examples.

    Read the article

  • Design - Where should objects be registered when using Windsor

    - by Fredrik Jansson
    I will have the following components in my application DataAccess DataAccess.Test Business Business.Test Application I was hoping to use Castle Windsor as IoC to glue the layers together but I am bit uncertain about the design of the gluing. My question is who should be responsible for registering the objects into Windsor? I have a couple of ideas; Each layer can register its own objects. To test the BL, the test bench could register mock classes for the DAL. Each layer can register the object of its dependencies, e.g. the business layer registers the components of the data access layer. To test the BL, the test bench would have to unload the "real" DAL object and register the mock objects. The application (or test app) registers all objects of the dependencies. Can someone help me with some ideas and pros/cons with the different paths? Links to example projects utilizing Castle Windsor in this way would be very helpful.

    Read the article

  • Intelligent serial port mocks with Moq

    - by Padu Merloti
    I have to write a lot of code that deals with serial ports. Usually there will be a device connected at the other end of the wire and I usually create my own mocks to simulate their behavior. I'm starting to look at Moq to help with my unit tests. It's pretty simple to use it when you need just a stub, but I want to know if it is possible and if yes how do I create a mock for a hardware device that responds differently according to what I want to test. A simple example: One of the devices I interface with receives a command (move to position x), gives back an ACK message and goes to a "moving" state until it reaches the ordered position. I want to create a test where I send the move command and then keep querying state until it reaches the final position. I want to create two versions of the mock for two different tests, one where I expect the device to reach the final position successfully and the other where it will fail. Too much to ask?

    Read the article

  • asp.net mvc How to test controllers correctly

    - by Simon G
    Hi, I'm having difficulty testing controllers. Original my controller for testing looked something like this: SomethingController CreateSomethingController() { var somethingData = FakeSomethingData.CreateFakeData(); var fakeRepository = FakeRepository.Create(); var controller = new SomethingController(fakeRepository); return controller; } This works fine for the majority of testing until I got the Request.IsAjaxRequest() part of code. So then I had to mock up the HttpContext and HttpRequestBase. So my code then changed to look like: public class FakeHttpContext : HttpContextBase { bool _isAjaxRequest; public FakeHttpContext( bool isAjaxRequest = false ) { _isAjaxRequest = isAjaxRequest; } public override HttpRequestBase Request { get { string ajaxRequestHeader = ""; if ( _isAjaxRequest ) ajaxRequestHeader = "XMLHttpRequest"; var request = new Mock<HttpRequestBase>(); request.SetupGet( x => x.Headers ).Returns( new WebHeaderCollection { {"X-Requested-With", ajaxRequestHeader} } ); request.SetupGet( x => x["X-Requested-With"] ).Returns( ajaxRequestHeader ); return request.Object; } } private IPrincipal _user; public override IPrincipal User { get { if ( _user == null ) { _user = new FakePrincipal(); } return _user; } set { _user = value; } } } SomethingController CreateSomethingController() { var somethingData = FakeSomethingData.CreateFakeData(); var fakeRepository = FakeRepository.Create(); var controller = new SomethingController(fakeRepository); ControllerContext controllerContext = new ControllerContext( new FakeHttpContext( isAjaxRequest ), new RouteData(), controller ); controller.ControllerContext = controllerContext; return controller; } Now its got to that stage in my controller where I call Url.Route and Url is null. So it looks like I need to start mocking up routes for my controller. I seem to be spending more time googling on how to fake/mock objects and then debugging to make sure my fakes are correct than actual writing the test code. Is there an easier way in to test a controller? I've looked at the TestControllerBuilder from MvcContrib which helps with some of the issues but doesn't seem to do everything. Is there anything else available that will do the job and will let me concentrate on writing the tests rather than writing mocks? Thanks

    Read the article

  • How to get started with testing(jMock)

    - by London
    Hello, I'm trying to learn how to write tests. I'm also learning Java, I was told I should learn/use/practice jMock, I've found some articles online that help to certain extend like : http://www.theserverside.com/news/1365050/Using-JMock-in-Test-Driven-Development http://jeantessier.com/SoftwareEngineering/Mocking.html#jMock And most articles I found was about test driven development, write tests first then write code to make the test pass. I'm not looking for that at the moment, I'm trying to write tests for already existing code with jMock. The official documentation is vague to say the least and just too hard for me. Does anybody have better way to learn this. Good books/links/tutorials would help me a lot. thank you EDIT - more concrete question : http://jeantessier.com/SoftwareEngineering/Mocking.html#jMock - from this article Tried this to mock this simple class : import java.util.Map; public class Cache { private Map<Integer, String> underlyingStorage; public Cache(Map<Integer, String> underlyingStorage) { this.underlyingStorage = underlyingStorage; } public String get(int key) { return underlyingStorage.get(key); } public void add(int key, String value) { underlyingStorage.put(key, value); } public void remove(int key) { underlyingStorage.remove(key); } public int size() { return underlyingStorage.size(); } public void clear() { underlyingStorage.clear(); } } Here is how I tried to create a test/mock : public class CacheTest extends TestCase { private Mockery context; private Map mockMap; private Cache cache; @Override @Before public void setUp() { context = new Mockery() { { setImposteriser(ClassImposteriser.INSTANCE); } }; mockMap = context.mock(Map.class); cache = new Cache(mockMap); } public void testCache() { context.checking(new Expectations() {{ atLeast(1).of(mockMap).size(); will(returnValue(int.class)); }}); } } It passes the test and basically does nothing, what I wanted is to create a map and check its size, and you know work some variations try to get a grip on this. Understand better trough examples, what else could I test here or any other exercises would help me a lot. tnx

    Read the article

  • Mockito upgrade causes null pointer problems

    - by Ann Addicks
    We upgraded from mockito-all-1.8.5.jar to mockito-all-1.9.0.jar and now see null pointers when using annotations for the classes being mocked. Here is an example: @Mock private static IAccountManager accountManager; @Mock private static IBusinessUnitManager businessUnitManager; private static Gson parser; @InjectMocks private static DownloadController downloadController; @BeforeClass public static void setUpBeforeClass() throws Exception { parser = new Gson(); downloadController = new DownloadController(accountManager, businessUnitManager, parser); } @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); Mockito.reset(accountManager, businessUnitManager); } As soon as accountManager is referenced in the download controller, it throws a npe. This worked in 1.8.5.

    Read the article

  • How do I create a SQL Server 2008 Reporting Services Template to a Default Font?

    - by David Stein
    I'm creating a new template to create reports from at a later date. I know how to create one, and I know where to save it. However, the problem is this. Everything that is created on the report uses the default font of Arial with a size of 10pt. I need to set mine to default to Tahoma 11pt. I can create a mock title, mock tables, etc and save those to Tahoma 11pt, but any new controls that are used on any version of this report will default back to Arial 10pt. How do I fix this?

    Read the article

  • Mocking imported modules in Python

    - by Evgenyt
    I'm trying to implement unit tests for function that uses imported external objects. For example helpers.py is: import os import pylons def some_func(arg): ... var1 = os.path.exist(...) var2 = os.path.getmtime(...) var3 = pylons.request.environ['HTTP_HOST'] ... So when I'm creating unit test for it I do some mocking (minimock in my case) and replacing references to pylons.request and os.path: import helpers def test_some_func(): helpers.pylons.request = minimock.Mock("pylons.request") helpers.pylons.request.environ = { 'HTTP_HOST': "localhost" } helpers.os.path = minimock.Mock(....) ... some_func(...) # assert ... This does not look good for me. Is there any other better way or strategy to substitute imported function/objects in Python?

    Read the article

  • How do I set a SQL Server 2008 Reporting Services Template to a Default Font?

    - by David Stein
    I'm creating a new template to create reports from at a later date. I know how to create one, and I know where to save it. However, the problem is this. Everything that is created on the report uses the default font of Arial with a size of 10pt. I need to set mine to default to Tahoma 11pt. I can create a mock title, mock tables, etc and save those to Tahoma 11pt, but any new controls that are used on any version of this report will default back to Arial 10pt. How do I fix this?

    Read the article

  • What are you using for Web UI/layout design?

    - by brendan
    What are folks out there using for web/ui design? For the most part we use PowerPoint at my company. The UI folks will mock up a screen in PowerPoint and we (the development group) will take it from there. So, for a side gig of mine I decided to do some mock ups to show the client prior to dev and I'm quickly feeling that PowerPoint is not the right tool for this. What are you using for this type of stuff - some other software? pen/paper?

    Read the article

  • C#: How to unit test a method that relies on another method within the same class?

    - by michael paul
    I have a class similar to the following: public class MyProxy : ClientBase<IService>, IService { public MyProxy(String endpointConfiguration) : base(endpointConfiguration) { } public int DoSomething(int x) { int result = DoSomethingToX(x); //This passes unit testing int result2 = ((IService)this).DoWork(x) //do I have to extract this part into a separate method just //to test it even though it's only a couple of lines? //Do something on result2 int result3 = result2 ... return result3; } int IService.DoWork(int x) { return base.Channel.DoWork(x); } } The problem lies in the fact that when testing I don't know how to mock the result2 item without extracting the part that gets result3 using result2 into a separate method. And, because it is unit testing I don't want to go that deep as to test what result2 comes back as... I'd rather mock the data somehow... like, be able to call the function and replace just that one call.

    Read the article

  • Making a Png Image transparent in older versions of Internet Explorer...

    - by GUNNOO
    Hello People i have a problem with the png formatted images, i used some PNG images in my mock. when i view the mock in I.E the background of the images are not transparent. i got one solution for making it trasparent in "I.E" from the previous POSTS in the Forum. But my Problem is, i want that image to be tiled horizantlly...using that Filter thing. can any one solve this plz....plz.... i need a solution for making a png in I.E and at the same time it shud be tiled horizontally.

    Read the article

  • Throwing special type of exception to terminate unit test

    - by trendl
    Assume I want to write a unit test to test a particular piece of functionality that is implemented within a method. If I wanted to execute the method completely, I would have to do some extra set up work (mock objects expectations etc.). Instead of doing that I use the following approach: - I set up the expectations I'm interested in verifying and then make the tested method throw a special type of exception (e.g. TerminateTestException). - Further down in the unit test I catch the exception and verify the mock object expectations. It works fine but I'm not sure it is good practice. I do not do this regularly, only in cases where it saves me time and effort. One thing that comes to mind as an argument against using this is that throwing exceptions takes long time so the tests execute slower than if I used a different approach.

    Read the article

  • Talks Submitted for Ann Arbor Day of .NET 2010

    - by PSteele
    Just submitted my session abstracts for Ann Arbor's Day of .NET 2010.   Getting up to speed with .NET 3.5 -- Just in time for 4.0! Yes, C# 4.0 is just around the corner.  But if you haven't had the chance to use C# 3.5 extensively, this session will start from the ground up with the new features of 3.5.  We'll assume everyone is coming from C# 2.0.  This session will show you the details of extension methods, partial methods and more.  We'll also show you how LINQ -- Language Integrated Query -- can help decrease your development time and increase your code's readability.  If time permits, we'll look at some .NET 4.0 features, but the goal is to get you up to speed on .NET 3.5.   Go Ahead and Mock Me! When testing specific parts of your application, there can be a lot of external dependencies required to make your tests work.  Writing fake or mock objects that act as stand-ins for the real dependencies can waste a lot of time.  This is where mocking frameworks come in.  In this session, Patrick Steele will introduce you to Rhino Mocks, a popular mocking framework for .NET.  You'll see how a mocking framework can make writing unit tests easier and leads to less brittle unit tests.   Inversion of Control: Who's got control and why is it being inverted? No doubt you've heard of "Inversion of Control".  If not, maybe you've heard the term "Dependency Injection"?  The two usually go hand-in-hand.  Inversion of Control (IoC) along with Dependency Injection (DI) helps simplify the connections and lifetime of all of the dependent objects in the software you write.  In this session, Patrick Steele will introduce you to the concepts of IoC and DI and will show you how to use a popular IoC container (Castle Windsor) to help simplify the way you build software and how your objects interact with each other. If you're interested in speaking, hurry up and get your submissions in!  The deadline is Monday, April 5th! Technorati Tags: .NET,Ann Arbor,Day of .NET

    Read the article

  • Silverlight Cream for April 28, 2010 -- #850

    - by Dave Campbell
    In this Issue: Giorgetti Alessandro, Alexander Strauss, Mahesh Sabnis, Andrea Boschin, Maxim Goldin, Peter Torr, Wolf Schmidt, and Marlon Grech. Shoutout: Koen Zwikstra announced a SL4 update: Silverlight Spy 3.0.0.11 Adam Kinney posted a WTF Step by Step guide to installing Silverlight Tools David Makogon posted his materials from a presentation: RockNUG April 2010 Materials: Silverlight 4 From SilverlightCream.com: Silverlight, M-V-VM ... and IoC - part 4 Giorgetti Alessandro isn't wasting any time... he's already gotten Part 4 of his MVVM, IoC, and Silverlight series up. He's discussing commanding. He gives some good external links and develops in his own direction as well. Application Partitioning with MEF, Silverlight and Windows Azure – Part II Alexander Strauss has the second and final part of his MEF/Silverlight/Azuer posts up, describing getting XAP information from Azure Blob storage. Simple Databinding and 3-D Features using Silverlight in Windows Phone 7 (WP7) Mahesh Sabnis has a post up combining DataBinding and 3D displays on WP7 ... good long tutorial and source. Keeping an ObservableCollection sorted with a method override Andrea Boschin details the reasons behind his need for having a sorted ObservableCollection, then hands over the code he used to do so. VS2010: Silverlight 4 profiling Maxim Goldin posted about profiling Silverlight 4 in VS2010. It's not overly straightforward but once you do it a couple times, not a big deal ... check out the comments as well. Peter Torr: Mock Location APIs from my Mix10 Talk A discussion came up on the insider's list this morning asking about Location Service in the emulator. Laurent Bugnion pointed us at Peter Torr's Mock Location from his MIX10 talk. Finding the "real" templates and generic.xaml in Silverlight core or library assemblies, by using .NET Reflector Wolf Schmidt at the Silverlight SDK has a post up about using .NET Reflector to rat around in Silverlight core or library assemblies. How does MEFedMVVM compose the catalogs and how can I override the behavior? – MEFedMVVM Part 4 Marlon Grech has Part 4 of his MEFedMVVM series up and this one is for advanced use of MEFedMVVM... where you're writing a composer and how that would be different for Silverlight and WPF... oh yeah, and what is a composer as well :) Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Is your test method self-validating ?

    - by mehfuzh
    Writing state of art unit tests that can validate your every part of the framework is challenging and interesting at the same time, its like becoming a samurai. One of the key concept in this is to keep our test synced all the time as underlying code changes and thus breaking them to the furthest unit as possible.  This also means, we should avoid  multiple conditions embedded in a single test. Let’s consider the following example of transfer funds. [Fact] public void ShouldAssertTranserFunds() {     var currencyService = Mock.Create<ICurrencyService>();     //// current rate     Mock.Arrange(() => currencyService.GetConversionRate("AUS", "CAD")).Returns(0.88f);       Account to = new Account { Currency = "AUS", Balance = 120 };     Account from = new Account { Currency = "CAD" };       AccountService accService = new AccountService(currencyService);       Assert.Throws<InvalidOperationException>(() => accService.TranferFunds(to, from, 200f));       accService.TranferFunds(to, from, 100f);       Assert.Equal(from.Balance, 88);     Assert.Equal(20, to.Balance); } At first look,  it seems ok but as you look more closely , it is actually doing two tasks in one test. At line# 10 it is trying to validate the exception for invalid fund transfer and finally it is asserting if the currency conversion is successfully made. Here, the name of the test itself is pretty vague. The first rule for writing unit test should always reflect to inner working of the target code, where just by looking at their names it is self explanatory. Having a obscure name for a test method not only increase the chances of cluttering the test code, but it also gives the opportunity to add multiple paths into it and eventually makes things messy as possible. I would rater have two test methods that explicitly describes its intent and are more self-validating. ShouldThrowExceptionForInvalidTransferOperation ShouldAssertTransferForExpectedConversionRate Having, this type of breakdown also helps us pin-point reported bugs easily rather wasting any time on debugging for something more general and can minimize confusion among team members. Finally, we should always make our test F.I.R.S.T ( Fast.Independent.Repeatable.Self-validating.Timely) [ Bob martin – Clean Code]. Only this will be enough to ensure, our test is as simple and clean as possible.   Hope that helps

    Read the article

  • Writing the tests for FluentPath

    - by Bertrand Le Roy
    Writing the tests for FluentPath is a challenge. The library is a wrapper around a legacy API (System.IO) that wasn’t designed to be easily testable. If it were more testable, the sensible testing methodology would be to tell System.IO to act against a mock file system, which would enable me to verify that my code is doing the expected file system operations without having to manipulate the actual, physical file system: what we are testing here is FluentPath, not System.IO. Unfortunately, that is not an option as nothing in System.IO enables us to plug a mock file system in. As a consequence, we are left with few options. A few people have suggested me to abstract my calls to System.IO away so that I could tell FluentPath – not System.IO – to use a mock instead of the real thing. That in turn is getting a little silly: FluentPath already is a thin abstraction around System.IO, so layering another abstraction between them would double the test surface while bringing little or no value. I would have to test that new abstraction layer, and that would bring us back to square one. Unless I’m missing something, the only option I have here is to bite the bullet and test against the real file system. Of course, the tests that do that can hardly be called unit tests. They are more integration tests as they don’t only test bits of my code. They really test the successful integration of my code with the underlying System.IO. In order to write such tests, the techniques of BDD work particularly well as they enable you to express scenarios in natural language, from which test code is generated. Integration tests are being better expressed as scenarios orchestrating a few basic behaviors, so this is a nice fit. The Orchard team has been successfully using SpecFlow for integration tests for a while and I thought it was pretty cool so that’s what I decided to use. Consider for example the following scenario: Scenario: Change extension Given a clean test directory When I change the extension of bar\notes.txt to foo Then bar\notes.txt should not exist And bar\notes.foo should exist This is human readable and tells you everything you need to know about what you’re testing, but it is also executable code. What happens when SpecFlow compiles this scenario is that it executes a bunch of regular expressions that identify the known Given (set-up phases), When (actions) and Then (result assertions) to identify the code to run, which is then translated into calls into the appropriate methods. Nothing magical. Here is the code generated by SpecFlow: [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Change extension")] public virtual void ChangeExtension() { TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Change extension", ((string[])(null))); #line 6 this.ScenarioSetup(scenarioInfo); #line 7 testRunner.Given("a clean test directory"); #line 8 testRunner.When("I change the extension of " + "bar\\notes.txt to foo"); #line 9 testRunner.Then("bar\\notes.txt should not exist"); #line 10 testRunner.And("bar\\notes.foo should exist"); #line hidden testRunner.CollectScenarioErrors();} The #line directives are there to give clues to the debugger, because yes, you can put breakpoints into a scenario: The way you usually write tests with SpecFlow is that you write the scenario first, let it fail, then write the translation of your Given, When and Then into code if they don’t already exist, which results in running but failing tests, and then you write the code to make your tests pass (you implement the scenario). In the case of FluentPath, I built a simple Given method that builds a simple file hierarchy in a temporary directory that all scenarios are going to work with: [Given("a clean test directory")] public void GivenACleanDirectory() { _path = new Path(SystemIO.Path.GetTempPath()) .CreateSubDirectory("FluentPathSpecs") .MakeCurrent(); _path.GetFileSystemEntries() .Delete(true); _path.CreateFile("foo.txt", "This is a text file named foo."); var bar = _path.CreateSubDirectory("bar"); bar.CreateFile("baz.txt", "bar baz") .SetLastWriteTime(DateTime.Now.AddSeconds(-2)); bar.CreateFile("notes.txt", "This is a text file containing notes."); var barbar = bar.CreateSubDirectory("bar"); barbar.CreateFile("deep.txt", "Deep thoughts"); var sub = _path.CreateSubDirectory("sub"); sub.CreateSubDirectory("subsub"); sub.CreateFile("baz.txt", "sub baz") .SetLastWriteTime(DateTime.Now); sub.CreateFile("binary.bin", new byte[] {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0xFF}); } Then, to implement the scenario that you can read above, I had to write the following When: [When("I change the extension of (.*) to (.*)")] public void WhenIChangeTheExtension( string path, string newExtension) { var oldPath = Path.Current.Combine(path.Split('\\')); oldPath.Move(p => p.ChangeExtension(newExtension)); } As you can see, the When attribute is specifying the regular expression that will enable the SpecFlow engine to recognize what When method to call and also how to map its parameters. For our scenario, “bar\notes.txt” will get mapped to the path parameter, and “foo” to the newExtension parameter. And of course, the code that verifies the assumptions of the scenario: [Then("(.*) should exist")] public void ThenEntryShouldExist(string path) { Assert.IsTrue(_path.Combine(path.Split('\\')).Exists); } [Then("(.*) should not exist")] public void ThenEntryShouldNotExist(string path) { Assert.IsFalse(_path.Combine(path.Split('\\')).Exists); } These steps should be written with reusability in mind. They are building blocks for your scenarios, not implementation of a specific scenario. Think small and fine-grained. In the case of the above steps, I could reuse each of those steps in other scenarios. Those tests are easy to write and easier to read, which means that they also constitute a form of documentation. Oh, and SpecFlow is just one way to do this. Rob wrote a long time ago about this sort of thing (but using a different framework) and I highly recommend this post if I somehow managed to pique your interest: http://blog.wekeroad.com/blog/make-bdd-your-bff-2/ And this screencast (Rob always makes excellent screencasts): http://blog.wekeroad.com/mvc-storefront/kona-3/ (click the “Download it here” link)

    Read the article

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