Search Results

Search found 299 results on 12 pages for 'rhino mocks 3 5'.

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

  • Rhino: How to get all properties from ScriptableObject?

    - by Dyatlov Vitaly
    Hi guys. I am using a Javascript object as an object with configuration properties. E.g. I have this object in javascript: var myProps = {prop1: 'prop1', prop2: 'prop2', 'prop3': 'prop3'}; This object (NativeObject) is returned to me in Java function. E.g. public Static void jsStaticFunction_test(NativeObject obj) { //work with object here } I want to get all properties from object and build HashMap from it. Any help will be appreciated.

    Read the article

  • Replace <Unknown Source> in Java Rhino (JSR223) with actual file name

    - by Lord.Quackstar
    Hello everyone, In my code, all of the scripts are contained in .js files. Whenever one of the scripts contains an error, I get this: javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "nonexistant" is not defined. (<Unknown source>#5) in <Unknown source> at line number 5 What bugs me is the <Unknown Source>. Multiple files are in one ScriptContext, and it can be hard to track down an error. It also looks horrible. Is there a way to replace <Unknown Source> with the actual file name? None of the methods I see support passing a File object, so I'm really confused here.

    Read the article

  • RhinoMocks Testing callback method

    - by joblot
    Hi All I have a service proxy class that makes asyn call to service operation. I use a callback method to pass results back to my view model. Doing functional testing of view model, I can mock service proxy to ensure methods are called on the proxy, but how can I ensure that callback method is called as well? With RhinoMocks I can test that events are handled and event raise events on the mocked object, but how can I test callbacks? ViewModel: public class MyViewModel { public void GetDataAsync() { // Use DI framework to get the object IMyServiceClient myServiceClient = IoC.Resolve<IMyServiceClient>(); myServiceClient.GetData(GetDataAsyncCallback); } private void GetDataAsyncCallback(Entity entity, ServiceError error) { // do something here... } } ServiceProxy: public class MyService : ClientBase, IMyServiceClient { // Constructor public NertiAdminServiceClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } // IMyServiceClient member. public void GetData(Action<Entity, ServiceError> callback) { Channel.BeginGetData(EndGetData, callback); } private void EndGetData(IAsyncResult result) { Action<Entity, ServiceError> callback = result.AsyncState as Action<Entity, ServiceError>; ServiceError error; Entity results = Channel.EndGetData(out error, result); if (callback != null) callback(results, error); } } Thanks

    Read the article

  • Verify an event was raised by mocked object

    - by joblot
    In my unit test how can I verify that an event is raised by the mocked object. I have a View(UI) -- ViewModel -- DataProvider -- ServiceProxy. ServiceProxy makes async call to serivce operation. When async operation is complete a method on DataProvider is called (callback method is passed as a method parameter). The callback method then raise and event which ViewModel is listening to. For ViewModel test I mock DataProvider and verify that handler exists for event raised by DataProvider. When testing DataProvider I mock ServiceProxy, but how can I test that callback method is called and event is raised. I am using RhinoMock 3.5 and AAA syntax Thanks -- DataProvider -- public partial class DataProvider { public event EventHandler<EntityEventArgs<ProductDefinition>> GetProductDefinitionCompleted; public void GetProductDefinition() { var service = IoC.Resolve<IServiceProxy>(); service.GetProductDefinitionAsync(GetProductDefinitionAsyncCallback); } private void GetProductDefinitionAsyncCallback(ProductDefinition productDefinition, ServiceError error) { OnGetProductDefinitionCompleted(this, new EntityEventArgs<ProductDefinition>(productDefinition, error)); } protected void OnGetProductDefinitionCompleted(object sender, EntityEventArgs<ProductDefinition> e) { if (GetProductDefinitionCompleted != null) GetProductDefinitionCompleted(sender, e); } } -- ServiceProxy -- public class ServiceProxy : ClientBase<IService>, IServiceProxy { public void GetProductDefinitionAsync(Action<ProductDefinition, ServiceError> callback) { Channel.BeginGetProductDefinition(EndGetProductDefinition, callback); } private void EndGetProductDefinition(IAsyncResult result) { Action<ProductDefinition, ServiceError> callback = result.AsyncState as Action<ProductDefinition, ServiceError>; ServiceError error; ProductDefinition results = Channel.EndGetProductDefinition(out error, result); if (callback != null) callback(results, error); } }

    Read the article

  • Nashorn, the rhino in the room

    - by costlow
    Nashorn is a new runtime within JDK 8 that allows developers to run code written in JavaScript and call back and forth with Java. One advantage to the Nashorn scripting engine is that is allows for quick prototyping of functionality or basic shell scripts that use Java libraries. The previous JavaScript runtime, named Rhino, was introduced in JDK 6 (released 2006, end of public updates Feb 2013). Keeping tradition amongst the global developer community, "Nashorn" is the German word for rhino. The Java platform and runtime is an intentional home to many languages beyond the Java language itself. OpenJDK’s Da Vinci Machine helps coordinate work amongst language developers and tool designers and has helped different languages by introducing the Invoke Dynamic instruction in Java 7 (2011), which resulted in two major benefits: speeding up execution of dynamic code, and providing the groundwork for Java 8’s lambda executions. Many of these improvements are discussed at the JVM Language Summit, where language and tool designers get together to discuss experiences and issues related to building these complex components. There are a number of benefits to running JavaScript applications on JDK 8’s Nashorn technology beyond writing scripts quickly: Interoperability with Java and JavaScript libraries. Scripts do not need to be compiled. Fast execution and multi-threading of JavaScript running in Java’s JRE. The ability to remotely debug applications using an IDE like NetBeans, Eclipse, or IntelliJ (instructions on the Nashorn blog). Automatic integration with Java monitoring tools, such as performance, health, and SIEM. In the remainder of this blog post, I will explain how to use Nashorn and the benefit from those features. Nashorn execution environment The Nashorn scripting engine is included in all versions of Java SE 8, both the JDK and the JRE. Unlike Java code, scripts written in nashorn are interpreted and do not need to be compiled before execution. Developers and users can access it in two ways: Users running JavaScript applications can call the binary directly:jre8/bin/jjs This mechanism can also be used in shell scripts by specifying a shebang like #!/usr/bin/jjs Developers can use the API and obtain a ScriptEngine through:ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); When using a ScriptEngine, please understand that they execute code. Avoid running untrusted scripts or passing in untrusted/unvalidated inputs. During compilation, consider isolating access to the ScriptEngine and using Type Annotations to only allow @Untainted String arguments. One noteworthy difference between JavaScript executed in or outside of a web browser is that certain objects will not be available. For example when run outside a browser, there is no access to a document object or DOM tree. Other than that, all syntax, semantics, and capabilities are present. Examples of Java and JavaScript The Nashorn script engine allows developers of all experience levels the ability to write and run code that takes advantage of both languages. The specific dialect is ECMAScript 5.1 as identified by the User Guide and its standards definition through ECMA international. In addition to the example below, Benjamin Winterberg has a very well written Java 8 Nashorn Tutorial that provides a large number of code samples in both languages. Basic Operations A basic Hello World application written to run on Nashorn would look like this: #!/usr/bin/jjs print("Hello World"); The first line is a standard script indication, so that Linux or Unix systems can run the script through Nashorn. On Windows where scripts are not as common, you would run the script like: jjs helloWorld.js. Receiving Arguments In order to receive program arguments your jjs invocation needs to use the -scripting flag and a double-dash to separate which arguments are for jjs and which are for the script itself:jjs -scripting print.js -- "This will print" #!/usr/bin/jjs var whatYouSaid = $ARG.length==0 ? "You did not say anything" : $ARG[0] print(whatYouSaid); Interoperability with Java libraries (including 3rd party dependencies) Another goal of Nashorn was to allow for quick scriptable prototypes, allowing access into Java types and any libraries. Resources operate in the context of the script (either in-line with the script or as separate threads) so if you open network sockets and your script terminates, those sockets will be released and available for your next run. Your code can access Java types the same as regular Java classes. The “import statements” are written somewhat differently to accommodate for language. There is a choice of two styles: For standard classes, just name the class: var ServerSocket = java.net.ServerSocket For arrays or other items, use Java.type: var ByteArray = Java.type("byte[]")You could technically do this for all. The same technique will allow your script to use Java types from any library or 3rd party component and quickly prototype items. Building a user interface One major difference between JavaScript inside and outside of a web browser is the availability of a DOM object for rendering views. When run outside of the browser, JavaScript has full control to construct the entire user interface with pre-fabricated UI controls, charts, or components. The example below is a variation from the Nashorn and JavaFX guide to show how items work together. Nashorn has a -fx flag to make the user interface components available. With the example script below, just specify: jjs -fx -scripting fx.js -- "My title" #!/usr/bin/jjs -fx var Button = javafx.scene.control.Button; var StackPane = javafx.scene.layout.StackPane; var Scene = javafx.scene.Scene; var clickCounter=0; $STAGE.title = $ARG.length>0 ? $ARG[0] : "You didn't provide a title"; var button = new Button(); button.text = "Say 'Hello World'"; button.onAction = myFunctionForButtonClicking; var root = new StackPane(); root.children.add(button); $STAGE.scene = new Scene(root, 300, 250); $STAGE.show(); function myFunctionForButtonClicking(){   var text = "Click Counter: " + clickCounter;   button.setText(text);   clickCounter++;   print(text); } For a more advanced post on using Nashorn to build a high-performing UI, see JavaFX with Nashorn Canvas example. Interoperable with frameworks like Node, Backbone, or Facebook React The major benefit of any language is the interoperability gained by people and systems that can read, write, and use it for interactions. Because Nashorn is built for the ECMAScript specification, developers familiar with JavaScript frameworks can write their code and then have system administrators deploy and monitor the applications the same as any other Java application. A number of projects are also running Node applications on Nashorn through Project Avatar and the supported modules. In addition to the previously mentioned Nashorn tutorial, Benjamin has also written a post about Using Backbone.js with Nashorn. To show the multi-language power of the Java Runtime, there is another interesting example that unites Facebook React and Clojure on JDK 8’s Nashorn. Summary Nashorn provides a simple and fast way of executing JavaScript applications and bridging between the best of each language. By making the full range of Java libraries to JavaScript applications, and the quick prototyping style of JavaScript to Java applications, developers are free to work as they see fit. Software Architects and System Administrators can take advantage of one runtime and leverage any work that they have done to tune, monitor, and certify their systems. Additional information is available within: The Nashorn Users’ Guide Java Magazine’s article "Next Generation JavaScript Engine for the JVM." The Nashorn team’s primary blog or a very helpful collection of Nashorn links.

    Read the article

  • How to test if raising an event results in a method being called conditional on value of parameters

    - by MattC
    I'm trying to write a unit test that will raise an event on a mock object which my test class is bound to. What I'm keen to test though is that when my test class gets it's eventhandler called it should only call a method on certain values of the eventhandlers parameters. My test seems to pass even if I comment the code that calls ProcessPriceUpdate(price); I'm in VS2005 so no lambdas please :( So... public delegate void PriceUpdateEventHandler(decimal price); public interface IPriceInterface{ event PriceUpdateEventHandler PriceUpdate; } public class TestClass { IPriceInterface priceInterface = null; TestClass(IPriceInterface priceInterface) { this.priceInterface = priceInterface; } public void Init() { priceInterface.PriceUpdate += OnPriceUpdate; } public void OnPriceUpdate(decimal price) { if(price > 0) ProcessPriceUpdate(price); } public void ProcessPriceUpdate(decimal price) { //do something with price } } And my test so far :s public void PriceUpdateEvent() { MockRepository mock = new MockRepository(); IPriceInterface pi = mock.DynamicMock<IPriceInterface>(); TestClass test = new TestClass(pi); decimal prc = 1M; IEventRaiser raiser; using (mock.Record()) { pi.PriceUpdate += null; raiser = LastCall.IgnoreArguments().GetEventRaiser(); Expect.Call(delegate { test.ProcessPriceUpdate(prc); }).Repeat.Once(); } using (mock.Playback()) { test.Init(); raiser.Raise(prc); } }

    Read the article

  • Mock a void method which change the input value

    - by Kar
    Hi, How could I mock a void method with parameters and change the value parameters? My void method looks like this: public interface IFoo { void GetValue(int x, object y) // takes x and do something then access another class to get the value of y } I prepared a delegate class: private delegate void GetValueDelegate(int x, object y); private void GetValue(int x, object y) { // process x // prepare a new object obj if (y == null) y = new Object(); if (//some checks) y = obj; } I wrote something like this: Expect.Call(delegate {x.GetValue(5, null);}).Do (new GetValueDelegate(GetValue)).IgnoreArguments().Repeat.Any(); But seems like it's not working. Any clue on what could be wrong?

    Read the article

  • How do I combine two interfaces when creating mocks?

    - by sduplooy
    We are using Rhino Mocks to perform some unit testing and need to mock two interfaces. Only one interface is implemented on the object and the other is implemented dynamically using an aspect-oriented approach. Is there an easy way to combine the two interfaces dynamically so that a mock can be created and the methods stubbed for both interfaces?

    Read the article

  • Rhino Mocks, AssertWasCalled with Arg Constraint on array parameter

    - by Etienne Giust
    Today, I had a hard time unit testing a function to make sure a Method with some array parameters was called. Method to be called : void AddUsersToRoles(string[] usernames, string[] roleNames);   I had previously used Arg<T>.Matches on complex types in other unit tests, but for some reason I was unable to find out how to apply the same logic with an array of strings.   It is actually quite simple to do, T really is a string[], so we use Arg<string[]>. As for the Matching part, a ToList() allows us to leverage the lambda expression.   sut.PermissionServices.AssertWasCalled(                 l => l.AddUsersToRoles(                     Arg<string[]>.Matches(a => a.ToList().First() == UserId.ToString())                     ,Arg<string[]>.Matches(a => a.ToList().First() == expectedRole1 && a.ToList()[1] == expectedRole2)                     )                     );   Of course, iw we expect an array with 2 or more values, the math would be something like : a => a.ToList()[0] == value1 && a.ToList()[1] == value2    … etc.

    Read the article

  • Agile Entity Framework 4 Repository: Part 6: Mocks & Unit Tests

    I did finish this series, honest I did. But not in the blog. Ive shown this in a number of conferences and even in my book, but I never came back and wrote it all down. In fact, I had the whole solutino written before I began the series, but it has gone through a lot of changes. Where did I leave off? Agile Entity Framework 4 Repository: Part 1- Model and POCO Classes Agile Entity Framework 4 Repository: Part 2- The Repository Agile EF4 Repository: Part 3 -Fine Tuning the Repository Agile...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • How to mock protected virtual members with Rhino.Mocks?

    - by Vadim
    Moq allows developers to mock protected members. I was looking for the same functionality in Rhino.Mocks but fail to find it. Here's an example from Moq Quick Start page how to mock protected method. // at the top of the test fixture using Moq.Protected() // in the test var mock = new Mock<CommandBase>(); mock.Protected() .Setup<int>("Execute") .Returns(5); // if you need argument matching, you MUST use ItExpr rather than It // planning on improving this for vNext mock.Protected() .Setup<string>("Execute", ItExpr.IsAny<string>()) .Returns(true); Let me know if I'm chasing something that doesn't exit.

    Read the article

  • How can I specify my own Rhino context in Java?

    - by Dan Howard
    I'm trying to ensure that my Rhino scripts (running under Java 6) are strict so that if a script developer misspells an expression I want an exception to be thrown. Currently what happens is the expression simply evaluates to "undefined". Now according to Mozilla org https://developer.mozilla.org/en/New_in_Rhino_1.6R6 there are features to enable strict checking in the context. I cannot find a working example of this. What I did so far was write a class to extend ContextFactory and then override the hasFeature method. public class ScriptContextFactory extends ContextFactory { protected boolean hasFeature(Context context, int featureIndex) { switch (featureIndex) { case Context.FEATURE_STRICT_EVAL: return true; case Context.FEATURE_STRICT_VARS: return true; } return super.hasFeature(context, featureIndex); } } Then in the Main I set mine to the default. ContextFactory.initGlobal(new ScriptContextFactory()); and I get an illegal state exception. :( Any ideas or samples on how this works? TIA

    Read the article

  • Where to get Rhino Commons

    - by Rasmus Christensen
    Hi I'm working on an asp.net mvc project using nhibernate. At the moment I think Rhino Commons session management is the best spproach to control isession. But Where should I get Rhino Commons From? I found it located on Horn, Github, think the svn is obsolete. Please point me to a version that works.

    Read the article

  • How to mock WCF Web Services with Rhino Mocks.

    - by Will
    How do I test a class that utilizes proxy clients generated by a Web Service Reference? I would like to mock the client, but the generated client interface doesn't contain the close method, which is required to properly terminate the proxy. If I don't use the interface, but instead a concrete reference, I get access to the close method but loose the ability to mock the proxy. I'm trying to test a class similar to this: public class ServiceAdapter : IServiceAdapter, IDisposable { // ILoggingServiceClient is generated via a Web Service reference private readonly ILoggingServiceClient _loggingServiceClient; public ServiceAdapter() : this(new LoggingServiceClient()) {} internal ServiceAdapter(ILoggingServiceClient loggingServiceClient) { _loggingServiceClient = loggingServiceClient; } public void LogSomething(string msg) { _loggingServiceClient.LogSomething(msg); } public void Dispose() { // this doesn't compile, because ILoggingServiceClient doesn't contain Close(), // yet Close is required to properly terminate the WCF client _loggingServiceClient.Close(); } }

    Read the article

  • Using RhinoMocks, how do you mock or stub a concrete class without an empty constructor?

    - by Mark Rogers
    Mocking a concrete class with Rhino Mocks seems to work pretty easy when you have an empty constructor on a class: public class MyClass{ public MyClass() {} } But if I add a constructor that takes parameters and remove the one that doesn't take parameters: public class MyClass{ public MyClass(MyOtherClass instance) {} } I tend to get an exception: System.MissingMethodException : Can't find a constructor with matching arguments I've tried putting in nulls in my call to Mock or Stub, but it doesn't work. Can I create mocks or stubs of concrete classes with Rhino Mocks, or must I always supply (implicitly or explicitly) a parameter-less constructor?

    Read the article

  • How can I add methods from a Java class as global functions in Javascript using Rhino?

    - by gooli
    I have a simple Java class that has some methods: public class Utils { public void deal(String price, int amount) { // .... } public void bid(String price, int amount) { // .... } public void offer(String price, int amount) { // .... } } I would like to create an instance of this class and allow the Javascript code to call the methods directly, like so: deal("1.3736", 100000); bid("1.3735", 500000); The only way I could figure out for now was to use ScriptEngine engine = new ScriptEngineManager().getEngineByName("js"); engine.put("utils", new Utils()); and then use utils.deal(...) in the Javascript code. I can also write wrapper functions in Javascript for each method, but there should be a simpler way to do this automatically for all the public methods of a class.

    Read the article

  • How can I pass a javaScript function to a Java Method to act as a callback (Rhino)

    - by Dan Howard
    Hi everyone, Basically I'm trying to pass a javaScript function to a Java method to act as a callback to the script. I can do it - sort of - but the object I receive is a sun.org.mozilla.javascript.internal.InterpretedFunction and I don't see a way to invoke it. Any ideas? Here's what I have so far: var someNumber = 0; function start() { // log is just an log4j instance added to the Bindings log.info("started...."); someNumber = 20; // Test is a unit test object with this method on it (taking Object as a param). test.callFromRhino(junk); } function junk() { log.info("called back " + someNumber); }

    Read the article

  • how to avoid returning mocks from a mocked object list

    - by koen
    I'm trying out mock/responsibility driven design. I seem to have problems to avoid returning mocks from mocks in the case of finder objects. An example could be an object that checks whether the bills from last month are paid. It needs a service that retrieves a list of bills for that. So I need to mock that service that retrieves the bills. At the same time I need that mock to return mocked Bills (since I don't want my test to rely on the correctness bill implementation). Is my design flawed? Is there a better way to test this? Or is this the way it will need to be when using finder objects (the finding of the bills in this case)?

    Read the article

  • Is static universally "evil" for unit testing and if so why does resharper recommend it?

    - by Vaccano
    I have found that there are only 3 ways to unit test (mock/stub) dependencies that are static in C#.NET: Moles TypeMock JustMock Given that two of these are not free and one has not hit release 1.0, mocking static stuff is not too easy. Does that make static methods and such "evil" (in the unit testing sense)? And if so, why does resharper want me to make anything that can be static, static? (Assuming resharper is not also "evil".) Clarification: I am talking about the scenario when you want to unit test a method and that method calls a static method in a different unit/class. By most definitions of unit testing, if you just let the method under test call the static method in the other unit/class then you are not unit testing, you are integration testing. (Useful, but not a unit test.)

    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

  • generated service mock: everything but RhinoMocks fails?

    - by hko
    I have the "quest" to search for the next Mocking Framework for my company, and basically it's down to NSubstitute (simplest syntax, but no strict mocks), FakeItEasy(best reviews, Roy Osherove bonus, and slightly better lib support than NSubstitute), Moq (best "other libs support", biggest featureset, downside: mock.Object). We definitely want to move on from RhinoMocks, e.g. because of the unusefull interactiontest error messages (it should tell me what the parameter was instead, when a verification fails). So I was pretty surprised the other day (that was yesterday) when I found out RhinoMocks could do a thing where every other mock framework fails at: Mocking an autogenerated SomethingService (a typical VS autogenerated service with a default construtor in a partial class). Please don't argue about the design.. I intend to write lightweight integration tests (and some unit tests), and I can't mess around with the service, the product is installed on too many customers system. See this code: // here the NSubstitute and FakeItEasy equivalents throw an exception.. see below TicketStoreService fakeTicketStoreService = MockRepository.GenerateMock<TicketStoreService>(); fakeTicketStoreService.Expect(service => service.DoSomething(Arg.Is(new Guid())).Return(new Guid()); fakeTicketStoreService.DoSomething(Arg.Is(new Guid())); fakeTicketStoreService.VerifyAllExpectations(); Note that DoSomething is a non-virtual methodcall in an autogenerated class. So it shouldn't work, according to common knowledge. But it does. Problem is that it's the only (non commercial) framework that can do this: Rhino.Mocks works, and verification works too FakeItEasy says it doesn't find a default constructor (probably just wrong exception message): No default constructor was found on the type SomeNamespace.TicketStoreService Moq gives something sane and understandable: Invalid setup on a non-virtual (overridable in VB) member: service=> service.DoSomething Nsubstitute gives a message System.NotSupportedException: Cannot serialize member System.ComponentModel.Component.Site of type System.ComponentModel.ISite because it is an interface. I'm really wondering what's going on here with the frameworks, except Moq. The "fancy new" frameworks seem to have an initial perf hit too, probably preparing some Type cache and serializing stuff, whilst RhinoMocks somehow manages to create a very "slim" mock without recursion. I have to admit I didn't like RhinoMocks very well, but here it shines.. unfortunately. So, is there a way to get that to work with newer (non-commercial!) mocking frameworks, or somehow get a sane error message out of Rhino.Mocks? And why can Rhino.Mocks achieve this, when clearly every Mocking framework states it can only work with virtual methods when given a concrete class? Let's not derail the discussion by talking about alternative approaches like Extract&Override or runtime-proxy Mocking frameworks like JustMock/TypeMock/Moles or the new Fakes framework, I know these, but that would be less ideal solutions, for reasons beyond this topic. Any help appreciated..

    Read the article

  • Version control - stubs and mocks

    - by Tesserex
    For the sake of this question, I don't care about the difference between stubs, mocks, dummies, fakes, etc. Let's say I'm working on a project with one other person. I'm working on component A and he is working on component B. They work together, so I stub out B for testing, and he stubs out A. We're working in a DVCS, let's say Git, because that's actually the case here. When it comes time to merge our components together, we need to get the "real" files from my A and his B, but throw away all the fake stuff. During development, it's likely (unless I need to learn how to properly stub things) that the fakes have the same file names and class names as the real thing. So my question is: what is the proper procedure for doing version control on the fakes, and how are the components correctly merged, making sure to grab the real thing and not the fake? I would guess that one way is just do the merge, expect it to say CONFLICT, and then manually delete all the fake code out of the half-merged files. But this sounds tedious and inefficient. Should the fake things not go under VC at all? Should they be ripped out just before merging? Sorry if the answer to this should be obvious or trivial, I'm just looking for a "suggested practice" here.

    Read the article

  • Unit testing with Mocks. Test behaviour not implementation

    - by Kenny Eliasson
    Hi.. I always had a problem when unit testing classes that calls other classes, for example I have a class that creates a new user from a phone-number then saves it to the database and sends a SMS to the number provided. Like the code provided below. public class UserRegistrationProcess : IUserRegistration { private readonly IRepository _repository; private readonly ISmsService _smsService; public UserRegistrationProcess(IRepository repository, ISmsService smsService) { _repository = repository; _smsService = smsService; } public void Register(string phone) { var user = new User(phone); _repository.Save(user); _smsService.Send(phone, "Welcome", "Message!"); } } It is a really simple class but how would you go about and test it? At the moment im using Mocks but I dont really like it [Test] public void WhenRegistreringANewUser_TheNewUserIsSavedToTheDatabase() { var repository = new Mock<IRepository>(); var smsService = new Mock<ISmsService>(); var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object); var phone = "0768524440"; userRegistration.Register(phone); repository.Verify(x => x.Save(It.Is<User>(user => user.Phone == phone)), Times.Once()); } [Test] public void WhenRegistreringANewUser_ItWillSendANewSms() { var repository = new Mock<IRepository>(); var smsService = new Mock<ISmsService>(); var userRegistration = new UserRegistrationProcess(repository.Object, smsService.Object); var phone = "0768524440"; userRegistration.Register(phone); smsService.Verify(x => x.Send(phone, It.IsAny<string>(), It.IsAny<string>()), Times.Once()); } It feels like I am testing the wrong thing here? Any thoughts on how to make this better?

    Read the article

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