Search Results

Search found 381 results on 16 pages for 'mocking'.

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

  • How to create tests for poco objects

    - by Simon G
    Hi, I'm new to mocking/testing and wanting to know what level should you go to when testing. For example in my code I have the following object: public class RuleViolation { public string ErrorMessage { get; private set; } public string PropertyName { get; private set; } public RuleViolation( string errorMessage ) { ErrorMessage = errorMessage; } public RuleViolation( string errorMessage, string propertyName ) { ErrorMessage = errorMessage; PropertyName = propertyName; } } This is a relatively simple object. So my question is: Does it need a unit test? If it does what do I test and how? Thanks

    Read the article

  • What is wrong with Stubs for unit testing?

    - by MatthewMartin
    I just watched this funny YouTube Video about unit testing (it's Hitler with fake subtitles chewing out his team for not doing good unit tests--skip it if you're humor impaired) where stubs get roundly criticized. But I don't understand what wrong with stubs. I haven't started using a mocking framework and I haven't started feeling the pain from not using one. Am I in for a world a hurt sometime down the line, having chosen handwritten stubs and fakes instead of mocks (like Rhinomock etc)? (using Fowler's taxonomy) What are the considerations for picking between a mock and handwritten stub?

    Read the article

  • When is it appropriate to do interaction based testing as opposed to state based testing?

    - by Praneeth
    Hi, When I use Easymock(or a similar mocking framework) to implement my unit tests, I'm forced to do interaction-based testing (as I don't get to assert on the state of my dependencies. Or am I mistaken?). On the other hand if I use a hand written stub (instead of using easymock) I can implement state based testing. I'm quite unclear if I want to go with interaction based testing or state based testing. I'm biased and I want to use Easymock, but I'm not sure if there would be any side-effects that I may have to face in the future. Can anyone please throw some light on this? Thanks in advance!

    Read the article

  • Code generation tool, to create C# adapter classes for unit testing?

    - by RyBolt
    I know I wouldn't need this with Typemock, however, with something like MoQ , I need to use the adapter pattern to enable the creation of mocks via interfaces for code I don't control. For example, TcpClient is a .NET class, so I use adapter pattern to enable mocking of this object, b/c I need an interface of that class. I then produce interface ITcpClient, that can then be implemented via a TcpClientAdapter class, which is just plain vanilla adapter pattern implementation. I am looking for a tool to do this automatically (creation of interface and adapter), I would think there is one out there somewhere? (or is everyone just hand coding these)

    Read the article

  • Mock Objects properties not changing

    - by frictionlesspulley
    I am new to using Mock test in .Net. I am testing out a financial transaction which is of the following nature: int amt =20; //sets all the props and func and returns a FinaceAccount. //Note I did not SetUp the amt of the account. var account =GetFinanceAccount() //service layer to be tested _financeService.tranx(account,amt); //checks if the amt was added to the account.amt //here the amt comes out same as that set in GetFinanceAccount. Assert.AreEqual(account.amt ,amt) I know that the function tranx works correctly but there is an issue with the test. Are there any GOOD reference material on Mocking in .Net

    Read the article

  • Framework for creating mock objects in Java

    - by Amir Rachum
    This is NOT a question about which is the best framework, etc. I have never used a mocking framework and I'm a bit puzzled by the idea. How does it know how to create the mock object? Is it done in runtime or generates a file? How do you know its behavior? And most importantly - what is the work flow of using such a framework (what is the step-by-step for creating a test). Can anyone explain? You can choose whichever framework you like for example, just say what it is.

    Read the article

  • How to mock an SqlDataReader using Moq - Update

    - by Simon G
    Hi, I'm new to moq and setting up mocks so i could do with a little help. Title says it all really - how do I mock up an SqlDataReader using Moq? Thanks Update After further testing this is what I have so far: private IDataReader MockIDataReader() { var moq = new Mock<IDataReader>(); moq.Setup( x => x.Read() ).Returns( true ); moq.Setup( x => x.Read() ).Returns( false ); moq.SetupGet<object>( x => x["Char"] ).Returns( 'C' ); return moq.Object; } private class TestData { public char ValidChar { get; set; } } private TestData GetTestData() { var testData = new TestData(); using ( var reader = MockIDataReader() ) { while ( reader.Read() ) { testData = new TestData { ValidChar = reader.GetChar( "Char" ).Value }; } } return testData; } The issue you is when I do reader.Read in my GetTestData() method its always empty. I need to know how to do something like reader.Stub( x => x.Read() ).Repeat.Once().Return( true ) as per the rhino mock example: http://stackoverflow.com/questions/1792984/mocking-a-datareader-and-getting-a-rhino-mocks-exceptions-expectationviolationexc

    Read the article

  • Is HttpContextWrapper all that....useful?

    - by bakasan
    I've been going through the process of cleaning up our controller code to make each action as testable. Generally speaking, this hasn't been too difficult--where we have opportunity to use a fixed object, like say FormsAuthentication, we generally introduce some form of wrapper as appropriate and be on our merry way. For reasons not particularly germaine to this conversation, when it came to dealing with usage of HttpContext, we decided to use the newly created HttpContextWrapper class rather than inventing something homegrown. One thing we did introduce was the ability to swap in a HttpContextWrapper (like say, for unit testing). This was wholly inspired by the way Oren Eini handles unit testing with DateTimes (see article, a pattern we also use) public static class FooHttpContext { public static Func<HttpContextWrapper> Current = () => new HttpContextWrapper(HttpContext.Current); public static void Reset() { Current = () => new HttpContextWrapper(HttpContext.Current); } } Nothing particularly fancy. And it works just fine in our controller code. The kicker came when we go to write unit tests. We're using Moq as our mocking framework, but alas var context = new Mock<HttpContextWrapper>() breaks since HttpContextWrapper doesn't have a parameterless ctor. And what does it take as a ctor parameter? A HttpContext object. So I find myself in a catch 22. I'm using the prescribed way to decouple HttpContext--but I can't mock a value in because the original HttpContext object was sealed and therefore difficult to test. I can map HttpContextBase, which both derive from--but that doesn't really get me what I'm after. Am I just missing the point somewhere with regard to HttpContextWrapper? I can find ways to work around the issue, but we are kind of fond of remaining consistent in decoupling using the Function delegate pattern--but it seems like we're not fully grokking intent of the wrapper.

    Read the article

  • Why doesn't every class in the .Net framework have a corresponding interface?

    - by Thorsten Lorenz
    Since I started to develop in a test/behavior driven style, I appreciated the ability to mock out every dependency. Since mocking frameworks like Moq work best when told to mock an interface, I now implement an interface for almost every class I create b/c most likely I will have to mock it out in a test eventually. Well, and programming to an interface is good practice, anyways. At times, my classes take dependencies on .Net classes (e.g. FileSystemWatcher, DispatcherTimer). It would be great in that case to have an interface, so I could depend on an IDispatcherTimer instead, to be able to pass it a mock and simulate its behavior to see if my system under test reacts correctly. Unfortunately both of above mentioned classes do not implement such interfaces, so I have to resort to creating adapters, that do nothing else but inherit from the original class and conform to an interface, that I then can use. Here is such an adapter for the DispatcherTimer and the corresponding interface: using System; using System.Windows.Threading; public interface IDispatcherTimer { #region Events event EventHandler Tick; #endregion #region Properties Dispatcher Dispatcher { get; } TimeSpan Interval { get; set; } bool IsEnabled { get; set; } object Tag { get; set; } #endregion #region Public Methods void Start(); void Stop(); #endregion } /// <summary> /// Adapts the DispatcherTimer class to implement the <see cref="IDispatcherTimer"/> interface. /// </summary> public class DispatcherTimerAdapter : DispatcherTimer, IDispatcherTimer { } Although this is not the end of the world, I wonder, why the .Net developers didn't take the minute to make their classes implement these interfaces from the get go. It puzzles me especially since now there is a big push for good practices from inside Microsoft. Does anyone have any (maybe inside) information why this contradiction exists?

    Read the article

  • With PascalMock how do I mock a method with an untyped out parameter and an open array parameter?

    - by Oliver Giesen
    I'm currently in the process of getting started with unit testing and mocking for good and I stumbled over the following method that I can't seem to fabricate a working mock implementation for: function GetInstance(const AIID: TGUID; out AInstance; const AArgs: array of const; const AContextID: TImplContextID = CID_DEFAULT): Boolean; (TImplContextID is just an alias for Integer) I thought it would have to look something like this: function TImplementationProviderMock.GetInstance( const AIID: TGUID; out AInstance; const AArgs: array of const; const AContextID: TImplContextID): Boolean; begin Result := AddCall('GetInstance') .WithParams([@AIID, AContextID]) .ReturnsOutParams([AInstance]) .ReturnValue; end; But the compiler complains about the .ReturnsOutParams([AInstance]) saying "Bad argument type in variable type array constructor.". Also I haven't found a way to specify the open array parameter AArgs at all. Also, is using the @-notation for the TGUID-typed parameter the right way to go? Is it possible to mock this method with the current version of PascalMock at all?

    Read the article

  • Testing a method used from an abstract class

    - by Bas
    I have to Unit Test a method (runMethod()) that uses a method from an inhereted abstract class to create a boolean. The method in the abstract class uses XmlDocuments and nodes to retrieve information. The code looks somewhat like this (and this is extremely simplified, but it states my problem) namespace AbstractTestExample { public abstract class AbstractExample { public string propertyValues; protected XmlNode propertyValuesXML; protected string getProperty(string propertyName) { XmlDocument doc = new XmlDocument(); doc.Load(new System.IO.StringReader(propertyValues)); propertyValuesXML= doc.FirstChild; XmlNode node = propertyValuesXML.SelectSingleNode(String.Format("property[name='{0}']/value", propertyName)); return node.InnerText; } } public class AbstractInheret : AbstractExample { public void runMethod() { bool addIfContains = (getProperty("AddIfContains") == null || getProperty("AddIfContains") == "True"); //Do something with boolean } } } So, the code wants to get a property from a created XmlDocument and uses it to form the result to a boolean. Now my question is, what is the best solution to make sure I have control over the booleans result behaviour. I'm using Moq for possible mocking. I know this code example is probably a bit fuzzy, but it's the best I could show. Hope you guys can help.

    Read the article

  • NUll exception in filling a querystring by mocing framework

    - by user564101
    There is a simple controller that a querystring is read in constructor of it. public class ProductController : Controller { parivate string productName; public ProductController() { productName = Request.QueryString["productname"]; } public ActionResult Index() { ViewData["Message"] = productName; return View(); } } Also I have a function in unit test that create an instance of this Controller and I fill the querystring by a Mock object like below. [TestClass] public class ProductControllerTest { [TestMethod] public void test() { // Arrange var querystring = new System.Collections.Specialized.NameValueCollection { { "productname", "sampleproduct"} }; var mock = new Mock<ControllerContext>(); mock.SetupGet(p => p.HttpContext.Request.QueryString).Returns(querystring); var controller = new ProductController(); controller.ControllerContext = mock.Object; // Act var result = controller.Index() as ViewResult; // Assert Assert.AreEqual("Index", result.ViewName); } } Unfortunately Request.QueryString["productname"] is null in constructor of ProductController when I run test unit. Is ther any way to fill a querystrin by a mocking and get it in constructor of a control?

    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

  • When using a mocking framework and MSPEC where do you set your stubs

    - by Kev Hunter
    I am relatively new to using MSpec and as I write more and more tests it becomes obvious to reduce duplication you often have to use a base class for your setup as per Rob Conery's article I am happy with using the AssertWasCalled method to verify my expectations, but where do you set up a stub's return value, I find it useful to set the context in the base class injecting my dependencies but that (I think) means that I need to set my stubs up in the Because delegate which just feels wrong. Is there a better approach I am missing?

    Read the article

  • Mocking Sort With Mocha

    - by josephmate
    How can I mock an array's sort expect a lambda expression? This is a trivial example of my problem: # initializing the data l = lambda { |a,b| a <=> b } array = [ 1, 2, 3, 4, 5 ] sorted_array = [ 2, 3, 8, 9, 1] # I expect that sort will be called using the lambda as a parameter array.expects(:sort).with( l ).returns( sorted_array ) # perform the sort using the lambda expression temp = array.sort{|a,b| l.call(a,b) } Now, at first I expected that this would work; however, I got the following error: - expected exactly once, not yet invoked: [ 1, 2, 3, 4, 5 ].sort(#<Proc:0xb665eb48>) Is there a way to do what I am looking for? Cheers, Joseph

    Read the article

  • mocking collection behavior with Moq

    - by Stephen Patten
    Hello, I've read through some of the discussions on the Moq user group and have failed to find an example and have been so far unable to find the scenario that I have. Here is my question and code: // 6 periods var schedule = new List<PaymentPlanPeriod>() { new PaymentPlanPeriod(1000m, args.MinDate.ToString()), new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(1).ToString()), new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(2).ToString()), new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(3).ToString()), new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(4).ToString()), new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(5).ToString()) }; // Now the proxy is correct with the schedule helper.Setup(h => h.GetPlanPeriods(It.IsAny<String>(), schedule)); Then in my tests I use Periods but the Mocked _PaymentPlanHelper never populates the collection, see below for usage: public IEnumerable<PaymentPlanPeriod> Periods { get { if (CanCalculateExpression()) _PaymentPlanHelper.GetPlanPeriods(this.ToString(), _PaymentSchedule); return _PaymentSchedule; } } Now if I change the mocked object to use another overloaded method of GetPlanPeriods that returns a List like so : var schedule = new List<PaymentPlanPeriod>() { new PaymentPlanPeriod(1000m, args.MinDate.ToString()), new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(1).ToString()), new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(2).ToString()), new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(3).ToString()), new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(4).ToString()), new PaymentPlanPeriod(1000m, args.MinDate.Value.AddMonths(5).ToString()) }; helper.Setup(h => h.GetPlanPeriods(It.IsAny<String>())).Returns(new List<PaymentPlanPeriod>(schedule)); List<PaymentPlanPeriod> result = new _PaymentPlanHelper.GetPlanPeriods(this.ToString()); This works as expected. Any pointers would be awesome, as long as you don't bash my architecture... :) Thank you, Stephen

    Read the article

  • Mocking View with RhinoMocks

    - by blu
    We are using MVP (Supervising Controller) for ASP.NET WebForms with 3.5 SP1. What is the preferred way to check the value of a view property that only has the a set operation with RhinoMocks? Here is what we have so far: var service = MockRepository.GenerateStub<IFooService>(); // stub some data for the method used in OnLoad in the presenter var view = MockRepository.GenerateMock<IFooView>(); var presenter = new FooPresenter(view, service); view.Raise(v => v.Load += null, this, EventArgs.Empty); Assert.IsTrue(view.Bars.Count == 10); // there is no get on Bars Should we use Expects or another way, any input would be great. Thanks Update based on Darin Dimitrov's reply. var bars = new List<Bar>() { new Bar() { BarId = 1 } }; var fooService = MockRepository.GenerateStub<IFooService>(); // this is called in OnLoad in the Presenter fooService.Stub(x => x.GetBars()).Return(bars); var view = MockRepository.GenerateMock<IFooView>(); var presenter = new FooPresenter(view, fooService); view.Raise(v => v.Load += null, this, EventArgs.Empty); view.AssertWasCalled(x => x.Bars = bars); // this does not pass This doesn't work. Should I be testing it this way or is there a better way?

    Read the article

  • Mocking an object that uses jni using EasyMock

    - by Visage
    So my class under test has code that looks braodly like this public void doSomething(int param) { Report report = new Report() ...do some calculations report.someMethod(someData) } my intention was to extract the construction of report into a protected method and override it to use a mock object that I could then test to ensure that someMethod had been called with the right data. So far so good. But Report isnt under my control, and to mkae things worse it uses JNI to load a library at runtime. If I do Report report = EasyMock.createMock(Report.class) then EasyMock attempts to use reflection to find out the class members, but this causes an attempt to load the JNI library, which fails (the JNI libraries are only available on UNIX). Im considering two things: a) Introduce a ReportWrapper interface with two implementations, one of which will delegate calls to an real Report (so basically a Proxy), and a second which will basically use a mock object. or b) instead of calling someMethod, call a protected method which will in turn call someMethod that I can override in a testing subclass. Either way it seems nasty. Any better ways?

    Read the article

  • mocking superclass protected variable using jmockit

    - by shashi
    Hi, I couldnt able to mock the protected varibale defined in the superclass.i could able to mock the protected method in superclass but couldnt to mock the protected variable in to the subclass ,wherein am writing the testcase for subclass,Please if anybody out there has any soluton for it .please reply. Thanks Shashi

    Read the article

  • Mocking a Wcf ServiceContract

    - by Michael
    I want to mock a ServiceContract. The problem is that Moq (and Castle Dynamic-Proxy) copies the attributes from the interface to the dynamic proxy which Wcf don't like. Wcf sais: The ServiceContractAttribute should only be define on either the interface or the implementation, not both.

    Read the article

  • asp.net mvc rhino mocks mocking httprequest values

    - by Matthew
    Hi Is there a way to mock request params, what is the best approach when testing to create fake request values in order to run a test would some thing like this work? _context = MockRepository.GenerateStub<HttpContext>(); request = MockRepository.GenerateStub<HttpRequest>(); var collection = new NameValueCollection(); collection.Add("", ""); SetupResult.For(request.Params).Return(collection); SetupResult.For(_context.Request).Return(request);

    Read the article

  • rspec mocking object property assignment

    - by charlielee
    I have a rspec mocked object, a value is assign to is property. I am struggleing to have that expectation met in my rspec test. Just wondering what the sytax is? The code: def create @new_campaign = AdCampaign.new(params[:new_campaign]) @new_campaign.creationDate = "#{Time.now.year}/#{Time.now.mon}/#{Time.now.day}" if @new_campaign.save flash[:status] = "Success" else flash[:status] = "Failed" end end The test it "should able to create new campaign when form is submitted" do campaign_model = mock_model(AdCampaign) AdCampaign.should_receive(:new).with(params[:new_campaign]).and_return(campaign_model) campaign_model.should_receive(:creationDate).with("#{Time.now.year}/#{Time.now.mon}/#{Time.now.day}")campaign_model.should_receive(:save).and_return(true) post :create flash[:status].should == 'Success' response.should render_template('create') end The problem is I am getting this error: Spec::Mocks::MockExpectationError in 'CampaignController new campaigns should able to create new campaign when form is submitted' Mock "AdCampaign_1002" received unexpected message :creationDate= with ("2010/5/7") So how do i set a expectation for object property assignment? Thanks

    Read the article

  • Mocking a namespace in a partial class.

    - by Nix
    I am messing around with Entity Framework 3.5 SP1 and I am trying to find a cleaner way to do the below. Basically I have an EF model and I am adding some Eager Loaded entities and i want to put them in the partial class context Eager namespace. Currently I am using composition but I feel like there is an easier way to do what I want. namespace Entities{ public partial class TestObjectContext { EagerExtensions Eager { get;set;} public TestObjectContext(){ Eager = new EagerExtensions (this); } } public partial class EagerExtensions { TestObjectContext context; public EagerExtensions(TestObjectContext _context){ context = _context; } public IQueryable<TestEntity> TestEntity { get { return context.TestEntity .Include("TestEntityType") .Include("Test.Attached.AttachedType") .AsQueryable(); } } } } public class Tester{ public void ShowHowIWantIt(){ TestObjectContext context= new TestObjectContext(); var query = from a in context.Eager.TestEntity select a; } }

    Read the article

  • Mocking view helpers with rspec-rails 2.0.0.beta.8

    - by snl
    I am trying to mock a view helper with rspec2. The old way of doing this throws an error, complaining the template object is not defined: template.should_receive(:current_user).and_return(mock("user")) Am I missing something here, or is this not implemented in rspec2 (yet)?

    Read the article

  • Mocking with java 1.4

    - by Filip
    Is there any framework, whick allows to mock concrete classes, not only interfaces in java 1.4? I have third party code with a singleton class, where I wanna change one function, without touching orignal code. Is it possible?

    Read the article

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