Mocking sealed classes can be quite a pain. I currently favor an Adapter pattern to handle this, but something about just keeps feels weird.
So, What is the best way you mock sealed classes?
Java answers are more than welcome. In fact, I would anticipate that the Java community has been dealing with this longer and has a great deal to offer.
But here are some of the .NET opinions:
Why Duck Typing Matters for C#
Develoepers
Creating wrappers
for sealed and other types for
mocking
Unit tests for WCF (and Moq)
For .NET, you could use something like TypeMock, which uses the profiling API and allows you to hook into calls to nearly anything.
My general rule of thumb is that objects that I need to mock should have a common interface too. I think this is right design-wise and makes tests a lot easier (and is usually what you get if you do TDD). More about this can be read in the Google Testing Blog latest post (See point 9).
Also, I've been working mainly in Java in the past 4 years and I can say that I can count on one hand the number of times I've created a final (sealed) class. Another rule here is I should always have a good reason to seal a class, as opposed to sealing it by default.
I believe that Moles, from Microsoft Research, allows you to do that. From the Moles page:
Moles may be used to detour any .NET
method, including non-virtual/static
methods in sealed types.
UPDATE: there is a new framework called "Fakes" in the upcoming VS 11 release that is designed to replace Moles:
The Fakes Framework in Visual Studio 11 is the next generation of Moles & Stubs, and will eventually replace it. Fakes is different from Moles, however, so moving from Moles to Fakes will require some modifications to your code. A guide for this migration will be available at a later date.
Requirements: Visual Studio 11 Ultimate, .NET 4.5
The problem with TypeMock is that it excuses bad design. Now, I know that it is often someone else's bad design that it's hiding, but permitting it into your development process can lead very easily to permitting your own bad designs.
I think if you're going to use a mocking framework, you should use a traditional one (like Moq) and create an isolation layer around the unmockable thing, and mock the isolation layer instead.
I came across this problem recently and after reading / searching web, seems like there is no easy way around except to use another tool as mentioned above.
Or crude of handling things as I did:
Create instance of sealed class without getting constructor called.
System.Runtime.Serialization.FormatterServices.GetUninitializedObject(instanceType);
Assign values to your properties / fields via reflection
YourObject.GetType().GetProperty("PropertyName").SetValue(dto, newValue, null);
YourObject.GetType().GetField("FieldName").SetValue(dto, newValue);
I almost always avoid having dependencies on external classes deep within my code. Instead, I'd much rather use an adapter/bridge to talk to them. That way, I'm dealing with my semantics, and the pain of translating is isolated in one class.
It also makes it easier to switch my dependencies in the long run.
It is perfectly reasonable to mock a sealed class because many framework classes are sealed.
In my case I'm trying to mock .Net's MessageQueue class so that I can TDD my graceful exception handling logic.
If anyone has ideas on how to overcome Moq's error regarding "Invalid setup on a non-overridable member", please let me know.
code:
[TestMethod]
public void Test()
{
Queue<Message> messages = new Queue<Message>();
Action<Message> sendDelegate = msg => messages.Enqueue(msg);
Func<TimeSpan, MessageQueueTransaction, Message> receiveDelegate =
(v1, v2) =>
{
throw new Exception("Test Exception to simulate a failed queue read.");
};
MessageQueue mockQueue = QueueMonitorHelper.MockQueue(sendDelegate, receiveDelegate).Object;
}
public static Mock<MessageQueue> MockQueue
(Action<Message> sendDelegate, Func<TimeSpan, MessageQueueTransaction, Message> receiveDelegate)
{
Mock<MessageQueue> mockQueue = new Mock<MessageQueue>(MockBehavior.Strict);
Expression<Action<MessageQueue>> sendMock = (msmq) => msmq.Send(It.IsAny<Message>()); //message => messages.Enqueue(message);
mockQueue.Setup(sendMock).Callback<Message>(sendDelegate);
Expression<Func<MessageQueue, Message>> receiveMock = (msmq) => msmq.Receive(It.IsAny<TimeSpan>(), It.IsAny<MessageQueueTransaction>());
mockQueue.Setup(receiveMock).Returns<TimeSpan, MessageQueueTransaction>(receiveDelegate);
return mockQueue;
}
Although it's currently only available in beta release, I think it's worthwhile keeping in mind the shim feature of the new Fakes framework (part of the Visual Studio 11 Beta release).
Shim types provide a mechanism to detour any .NET method to a user defined delegate. Shim types are code-generated by the Fakes generator, and they use delegates, which we call shim types, to specify the new method implementations. Under the hood, shim types use callbacks that were injected at runtime in the method MSIL bodies.
Personally, I was looking at using this to mock the methods on sealed framework classes such as DrawingContext.
I generally take the route of creating an interface and adaptor/proxy class to facilitate mocking of the sealed type. However, I've also experimented with skipping creation of the interface and making the proxy type non-sealed with virtual methods. This worked well when the proxy is really a natural base class that encapsulates and users part of the sealed class.
When dealing with code that required this adaptation, I got tired of performing the same actions to create the interface and proxy type so I implemented a library to automate the task.
The code is somewhat more sophisticated than the sample given in the article you reference, as it produces an assembly (instead of source code), allows for code generation to be performed on any type, and doesn't require as much configuration.
For more information, please refer to this page.
Is there a way to implement a sealed class from an interface... and mock the interface instead?
Something in me feels that having sealed classes is wrong in the first place, but that's just me :)
Related
I have for long worked on EasyMocking in JUnits. I am pretty much comfortable with this but now I want to know how EasyMocks are different from Jmockits. I tried going through their documentation and I found out that the syntax is a bit different. But yet I could not figure out if there is any difference in their performances.
Can anyone help me figure out what are the points that make either of them better than the other? Is there any special element in JMockit that is not found in the other?
Thanks in advance...
There are many differences between JMockit and EasyMock/jMock/Mockito/PowerMock.
These are the major ones:
Support for integration testing: JMockit supports an out-of-container integration testing approach, similar to what the Spring Test module provides, but also supporting Java EE. The other mocking libraries only support isolated unit testing with mock objects.
A "faking" API (see also in xUnit Patterns), in addition to the mocking API. Each one of the other mocking libraries only have a mocking API.
Full support for "mocking", in addition to "mock objects". Other mocking libraries work with mock objects which they create and which need to be passed in somehow to the code under test. With EasyMock/jMock/Mockito, static methods, constructors, and "new-ed" objects cannot be mocked at all. PowerMock supports full mocking as well, but still focused on mock objects (specifically, new-ed objects must be "replaced" with mock objects through whenNew recording, while with JMockit a test can simply declare a #Mocked field).
Support for mocking/faking of final classes and methods. Only PowerMock also provides this support. Mockito recently added an "inline mock maker" which adds support for finals, but it's not active by default and may not be as reliable.
Support for mocking/faking of unspecificied subclasses and interface implementations (where the test only declares a base type to be mocked/faked).
In the mocking API, expectations on methods with multiple parameters can be recorded/verified with argument matchers (such as anyString, etc.) only for some parameters, while other mocking APIs require such matchers for every single parameter.
Also in the mocking API, expectations can be explicitly verified after the tested code was exercised, just like in Mockito. EasyMock/jMock do not support this verification model.
As for performance, mocking a type with JMockit (done through class redefinition) probably has a higher runtime overhead when compared to creating a mock object with EasyMock/jMock/Mockito (done through subclass definition), and lower when compared with PowerMock (done through class definition on a custom classloader). However, you should only notice the difference in performance if there is a lot of mocking being done, which most likely indicates overuse of mocking.
You can find a blog post about the differences between them (and also mockito!) here: http://www.baeldung.com/mockito-vs-easymock-vs-jmockit
While they all have different syntax and different ways of working, you should be able to achieve whatever you need in regards to mocking with either framework.
What is the Kotlin philosophy of test doubles? With all classes and functions being sealed by default (not open), mocking frameworks like Mockito are clearly not first-class citizens.
A lot has already been written about the problem, and also about possible solutions, but what do the designers of Kotlin have in mind for testing with doubles? Is it fakes and stubs, or should you role your own spies and mocks?
Frameworks like Mockito are first class citizens, including to the point where they are directly mentioned as one of the reasons for the all-open compiler plugin released in Kotlin 1.0.6. Your references to problems/solutions are out of date and it would be nice if those authors updated their posts.
From that release announcement you will see Mockito called out specifically:
The all-open compiler plugin makes classes annotated with a specific annotation and their members open without the explicit open keyword, so it becomes much easier to use frameworks/libraries such as Spring AOP or Mockito. You can read the detailed information about all-open in the corresponding KEEP.
We provide all-open plugin support both for Gradle and Maven, as well as the IDE integration.
The plugin is available for use using the command-line compiler, IDE compiler, and from Gradle and Maven.
Other references:
Using Mockito with Kotlin
A great part of Kotlin's design is with Joshua Bloch's Effective Java in mind, meaning closed by default, immutability, and so on.
Therefore, these problems exist in Java as well. The solution to these problems was and is to use interfaces where possible, so you can provide test doubles, or any other implementation to your production code for that matter.
For tests, these might be mocks, or fakes, or stubs, or what have you. Bear in mind that a well-written in-memory repository for example is way easier to handle in tests than having to set up a mock for that class.
In addition #nhaarman's comments, another option is Mockito-Kotlin. I like that Kotlin's classes are final by default, so the all-open compiler plugin isn't a good option for me.
A bit confused on the differences of Mock frameworks like NMock vs the VS 2011 Fakes Framework.
Going through MSDN, what I understand is that Fakes allow you to mock your dependencies just like RhinoMock or NMock, however the approach is different, Fakes generates code to achive this functionality but Mocks framework does not. So is my understanding correct? Is Fakes just another Mock framework
Your question was about how the MS Fakes framework is different from NMock and it appears the other answers have resolved some of that, but here is some more information regarding how they are the same and how they are different. NMock is also similar to RhinoMocks and Moq, so I'm grouping them in with NMock.
There are 3 major differences I see right off between NMock/RhinoMocks/Moq and the MS Fakes Framework:
The MS fakes framework uses generated code, much like Accessors in prior versions of Visual Studio instead of generic types. When you want to use the fakes framework for a dependency, you add the assembly that contains the dependency to the references of the test project and then right-click on it to generate the test doubles (stubs or shims). Then when you are testing, you are actually using these generated classes instead. NMock uses generics to accomplish the same thing (i.e. IStudentRepository studentRepository = mocks.NewMock<IStudentRepository>()). In my opinion, the MS Fakes framework approach inhibits code navigation and refactoring from within the tests since you are actually working against a generated class, not your real interface.
The MS fakes framework supplies stubs and moles (shims), whereas NMock, RhinoMocks, and Moq all provide stubs and mocks. I really don't understand MS's decision to not include mocks and I am, personally not a fan of moles for reasons described below.
With the MS fakes framework, you supply an alternative implementation of the methods you want to stub. Within these alternate implementations, you can specify the return values and track information about how or if the method was called. With NMock, RhinoMocks and Moq, you generate a mock object and then use that object to specify stubbed return values or to track interactions (whether and how the methods were called). I find the MS fakes approach more complex and less expressive.
To clarify the difference in what the frameworks provide: NMock, RhinoMocks and Moq all provide two types of test doubles (stubs and mocks). The fakes framework provides stubs and moles (they call them shims), and unfortunately does not include mocks. In order to understand the differences and similarities between NMock and MS Fakes, it is helpful to understand what these different types of test doubles are:
Stubs: Stubs are used when you need to provide a values for methods or properties that will be asked of your test doubles by the method under test. For example, when my method under test calls the DoesStudentExist() method of the IStudentRepository test double, I want it to return true.
The idea of stubs in NMock and MS fakes is the same, but with NMock you would do something like this:
Stub.On(mockStudentRepository).Method("DoesStudentExist").Will(Return.Value(true));
And with MSFakes you would do somethign like this:
IStudentRepository studentRepository = new DataAccess.Fakes.StubIStudentRepository() // Generated by Fakes.
{
DoesStudentExistInt32 = (studentId) => { return new Student(); }
};
Notice in the MS Fakes example you create an entirely new implementation for the DoesStudentExist method (Note that it is called DoesStudentExistInt32 because the fakes framework appends the parameter data types to the method names when it generates the stub objects, I think this obscures the clarity of the tests). To be honest the NMock implementation also bugs me because it uses a string to identify the method name. (Forgive me if I've misunderstood how NMock is intended to be used.) This approach really inhibits refactoring and I'd highly recommend RhinoMocks or Moq over NMock for this reason.
Mocks: Mocks are used to verify interaction between your method under test and its dependencies. With NMock, you do this by setting expectations similar to this:
Expect.Once.On(mockStudentRepository).Method("Find").With(123);
This is another reason why I'd prefer RhinoMocks and Moq over NMock, NMock uses the older expectation style whereas RhinoMocks and Moq both support the Arrange/Act/Assert approach where you specify you expected interactions as assertions at the end of the test like this:
stubStudentRepository.AssertWasCalled( x => x.Find(123));
Again, note that RhinoMocks uses a lambda instead of a string to identify the method. The ms fakes framework does not provide mocks at all. This means that in your stubbed out implementations (see the description of stubs above) you have to set variables that you later verify were set correctly. That would look something like this:
bool wasFindCalled = false;
IStudentRepository studentRepository = new DataAccess.Fakes.StubIStudentRepository()
{
DoesStudentExistInt32 = (studentId) =>
{
wasFindCalled = true;
return new Student();
}
};
classUnderTest.MethodUnderTest();
Assert.IsTrue(wasFindCalled);
I find this approach to be a little convoluted since you have to track the call up in the stub and then assert it later in the test. I find the NMock, and especially the RhinoMocks, examples to be more expressive.
Moles (Shims): To be frank, I do not like moles, because of their potential for misuse. One of the things I like so much about unit testing (and TDD in particular) is that testing your code helps you to understand where you have written poor code. This is because testing poorly written code is difficult. This is not true when using moles because moles are actually designed to allow you to test against dependencies that are not injected or to test private methods. They work similarly to stubs, except that you use a ShimsContext like this:
using (ShimsContext.Create())
{
System.Fakes.ShimDateTime.NowGet = () => { return new DateTime(fixedYear, 1, 1); };
}
My worry with shims is that people will start seeing them as "an easier way to unit test" because it doesn't force you to write code the way you should. For a more complete write-up on this concept see this post of mine:
https://jcoop.io/2012/05/21/solid-code-for-solid-reasons/
For more information on some concerns related to the fakes frameworks take a look at these posts:
https://jcoop.io/2012/03/16/38/
If you're interested in learning RhinoMocks here's a Pluralsight training video (full disclosure - I wrote this course and get paid royalties for views, but I think it applies to this discussion so I'm including it here):
http://www.pluralsight.com/training/Courses/TableOfContents/rhinomock-fundamentals
You are correct, but there's more to the story. The most important things to take away from this answer are:
Your architecture should make proper use of stubs and dependency injection, rather than relying on the crutch of Fakes and mocks
Fakes and mocks are useful for testing code you shouldn't or can't change, such as:
Legacy code that does not make use (or efficient use) of stubs
3rd party APIs
Resources for which you have no source code
Shims (known as "Moles", during development) is indeed a mocking framework that operates by way of detouring calls. Instead of painstakingly building a mock (yes, even using Moq is relatively painful!), shims simply use the production code object already in place. Shims simply re-route the call from the production target to the test delegate.
Stubs are generated from interfaces in the target project. The Stub object is just that -- an implementation of the interface. The benefit to using the Stub type is that you can quickly generate a stub without cluttering up your test project with many one-time use stubs, not to mention wasting time creating them. Of course, you should still create concrete stubs, for use across many tests.
Efficiently implementing Fakes (Shims, Mocks and Stub types) takes a little getting used to, but is well worth the effort. I have personally saved weeks of development time, through use of the Shims/Mole, Mocks, and Stub types. I hope you have as much fun with the technology as I have!
As I understand it, the Visual Studio team wanted to avoid competing with the various mock libraries available for .NET. MS often faces hard decisions like this. They are dammed if they don't provide certain functionality ("why doesn't MS provide us with a mock library; mocks are such a common requirement?") and damned if they do ("why is Microsoft acting so aggressively and driving its natural supporters out of the market?") Very often, but not always, they decide to hold back from simply providing their own alternative to available and well-received technologies. That seems to be the case here.
The shim feature of Fakes is really, really useful. Sure, there are dangers. It takes some discipline to ensure you only use this where necessary. However, it fills a big gap. My main complaint is that it is only delivered with the Ultimate edition of VS 2012 and therefore will only be available to a subsection of the .NET development community. What a pity.
Fakes includes two different kinds of "fake" object. The first, called a "stub", is essentially an auto-generated dummy whose default behaviour can (and usually would) be overridden to make it a more interesting mock. It does, however, lack some of the features that most of the currently available mocking frameworks offer. For example, if you want to check that a method on a stub instance was invoked, you would need to add the logic for this yourself. Basically, if you're authoring your own mocks manually now, stubs would probably seem like an improvement. However, if you're already using a more full-featured mocking framework, you might feel like there are some important pieces missing from Fakes stubs.
The other category of object offered by Fakes, called a "shim", exposes a mechanism for replacing behaviour of dependencies that have not been (or cannot be) decoupled adequately for standard replacement via mocks. AFAIK, TypeMock is the only one of the major mocking frameworks that currently offers this sort of functionality.
BTW, if you have tried out Moles before, Fakes is essentially the same thing, finally making its way out of Microsoft Research and into an actual product.
Regarding Fake (Shim + Stub) objects, it has been well defined above, though I guess the last paragraph in the last comment summarizes the whole situation pretty well.
Though a lot of people will argue that Fake (Shim + Stub) objects are good assets to have in some unit testing cases, the downside is that no matter if you're using Visual Studio 2012 or Visual Studio 2013, these options are ONLY available with Premium or Ultimate versions. IOW, this means that you WILL NOT be to run ANY of those Fakes (Shim + Stub) on any Pro version.
You may probably see the Fakes (Shim + Stub) menu option on Pro versions, but beware, there are some pretty strong chances that you will end up with absolutely nothing... It won't generate any compilation error telling you that something important is missing, options are just not there, so don't waste your time...
It's an important factor to consider in a dev team, especially if one is the only one using Ultimate version while everybody else uses Pro version... Moq on the other hand can easily be installed through Nuget no matter which Visual Studio version you use. I had no problem using Moq, the key with any tool is to know what they're used for and how to use them properly ;)
I'm curious as to what method people like to use for mocking and why. The two methods that I know of are using hard coded mock objects and a mocking framework. To demonstrate, I'll outline an example using C#.
Suppose we have an IEmployeeRepository interface with a method called GetEmployeeById.
public interface IEmployeeRepository
{
Employee GetEmployeeById(long id);
}
We can easily create a mock of this:
public class MockEmployeeRepository : IEmployeeRepository
{
public Employee GetEmployeeById(long id)
{
Employee employee = new Employee();
employee.FirstName = "First";
employee.LastName = "Last";
...
return employee;
}
}
Then, in our tests we can explicitly tell our services to use the MockEmployeeRepository, either using a setter or dependency injection. I'm new to mocking frameworks so I'm curious as to why we use them, if we can just do the above?
That's not a Mock, it's a Stub. For stubbing, your example is perfectly acceptable.
From Martin Fowler:
Mocks are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
When you're mocking something, you usually call a "Verify" method.
Look at this for the diff between Mocks and Stubs
http://martinfowler.com/articles/mocksArentStubs.html
I think the choice between writing dummy objects by hand or by using a framework depends a lot upon the types of components that you are testing.
If it is part of the contract for the component under test to communicate with its collaborators following a precise protocol, then instrumented dummy objects ("Mocks") are just the thing to use. It is frequently much easier to test such protocols using a mocking framework than by hand-coding. Consider a component that is required to open a repository, perform some reads and writes in a prescribed order, and then close the repository -- even in the face of an exception. A mocking framework would make it easier to set up all of the necessary tests. Applications related to telecommunications and process control (to pick a couple of random examples) are full of components that need to be tested in this fashion.
On the other hand, many components in general business applications have no particular constraints on how they communicate with their collaborators. Consider a component that performs some kind of analysis of, say, university course loads. The component needs to retrieve instructor, student and course information from a repository. But it does not matter what order it retrieves the data: instructor-student-course, student-course-instructor, all-at-once, or whatever. There is no need to test for and enforce a data access pattern. Indeed, it would likely be harmful to test that pattern as it would be demanding a particular implementation unnecessarily. In this context, simple uninstrumented dummy objects ("Stubs") are adequate and a mocking framework is probably overkill.
I should point out that even when stubbing, a framework can still make your life a lot easier. One doesn't always have the luxury of dictating the signatures of one's collaborators. Imagine unit-testing a component that is required to process data retrieved from a thick interface like IDataReader or ResultSet. Hand-stubbing such interfaces is unpleasant at best -- especially if the component under test only actually uses three of the umpteen methods in the interface.
For me, the projects that have required mocking frameworks were almost invariably of a systems-programming nature (e.g. database or web infrastructure projects, or low-level plumbing in a business application). For applications-programming projects, my experience has been that there were few mocks in sight.
Given that we always strive to hide the messy low-level infrastructure details as much as possible, it would seem that we should aim to have the simple stubs far outnumber the mocks.
Some distinguish between mocks and stubs. A mock object may verify that it has been interacted with in the expected way. A mocking framework can make it easy to generate mocks and stubs.
In your example, you've stubbed out a single method in an interface. Consider an interface with n methods, where n can change over time. A hand-stubbed implementation may require more code and more maintenance.
A mocked interface can have different outputs per test - One test you may have a method return null, another test has the method return an object, another test has the method throw an exception. This is all configured in the unit test, whereas your version would require several hand-written objects.
Psuedocode:
//Unit Test One
MockObject.Expect(m => m.GetData()).Return(null);
//Unit Test Two
MockObject.Expect(m => m.GetData()).Return(new MyClass());
//Unit Test Three
MockObject.Expect(m => m.GetData()).ThrowException();
I tend to write stubs and mocks by hand, first. Then if it can be easily expressed using a mock object framework, I rewrite it so that I have less code to maintain.
I have been writing them by hand. I was having trouble using Moq, but then I read TDD: Introduction to Moq, and I think I get what they say about classical vs. mockist approaches now. I'll be giving Moq another try this evening, and I think understanding the "mockist" approach will give me what I need to make Moq work better for me.
I have a project I am trying to learn unit testing and TDD practices with. I'm finding that I'm getting to quite confusing cases where I am spending a long time setting up mocks for a utility class that's used practically everywhere.
From what I've read about unit testing, if I am testing MyClass, I should be mocking any other functionality (such as provided by UtilityClass). Is it acceptable (assuming that UtilityClass itself has a comprehensive set of tests) to just use the UtilityClass rather than setting up mocks for all the different test cases?
Edit: One of the things I am making a lot of setup for.
I am modelling a map, with different objects in different locations. One of the common methods on my utility class is GetDistanceBetween. I am testing methods that have effects on things depending on their individual properties, so for example a test that selects all objects within 5 units of a point and an age over 3 will need several tests (gets old objects in range, ignores old objects out of range, ignores young objects in range, works correctly with multiples of each case) and all of those tests need setup of the GetDistanceBetween method. Multiply that out by every method that uses GetDistanceBetween (almost every one) and the different results that the method should return in different circumstances, and it gets to be a lot of setup.
I can see as I develop this further, there may be more utility class calls, large numbers of objects and a lot of setup on those mock utility classes.
The rule is not "mock everything" but "make tests simple". Mocking should be used if
You can't create an instance with reasonable effort (read: you need a single method call but to create the instance, you need a working database, a DB connection, and five other classes).
Creation of the additional classes is expensive.
The additional classes return unstable values (like the current time or primary keys from a database)
TDD isn't really about testing. Its main benefit is to help you design clean, easy-to-use code that other people can understand and change. If its main benefit was to test then you would be able to write tests after your code, rather than before, with much of the same effect.
If you can, I recommend you stop thinking of them as "unit tests". Instead, think of your tests as examples of how you can use your code, together with descriptions of its behaviour which show why your code is valuable.
As part of that behaviour, your class may want to use some collaborating classes. You can mock these out.
If your utility classes are a core part of your class's behaviour, and your class has no value or its behaviour makes no sense without them, then don't mock them out.
Aaron Digulla's answer is pretty good; I'd rephrase each of his answers according to these principles as:
The behaviour of the collaborating class is complex and independent of the behaviour of the class you're interested in.
Creation of the collaborating class is not a valuable aspect of your class and does not need to be part of your class's responsibility.
The collaborating class provides context which changes the behaviour of your class, and therefore plays into the examples of how you can use it and what kind of behaviour you might expect.
Hope that makes sense! If you liked it, take a look at BDD which uses this kind of vocabulary far more than "test".
In theory you should try to mock all dependencies, but in reality it's never possible. E.g. you are not going to mock the basic classes from the standard library. In your case if the utility class just contains some basic helper methods I think I wouldn't bother to mock it.
If it's more complicated than that or connects to some external resources, you have to mock it. You could consider creating a dedicated mock builder class, that would create you a standard mock (with some standard stubs defined etc), so that you can avoid mocking code duplication in all test classes.
No, it is not acceptable because you are no longer testing the class in isolation which is one of the most important aspects of a unit test. You are testing it with its dependency to this utility even if the utility has its own set of tests. To simplify the creation of mock objects you could use a mock framework. Here are some popular choices:
Rhino Mocks
Moq
NSubstitute
Of course if this utility class is private and can only be used within the scope of the class under test then you don't need to mock it.
Yes, it is acceptable. What's important is to have the UtilityClass thoroughly unit tested and to be able to differentiate if a test is failing because of the Class under test or because of the UtilityClass.
Testing a class in isolation means testing it in a controlled environment, in an environment where one control how the objects behave.
Having to create too many objects in a test setup is a sign that the environment is getting too large and thus is not controlled enough. Time has come to revert to mock objects.
All the previous answers are very good and really match with my point of view about static utility classes and mocking.
You have two types of utilities classes, your own classes you write and the third party utility classes.
As the purpose of an utility class is to provide small set of helper methods, your utility classes or a third party utility classes should be very well tested.
First Case: the first condition to use your own utility class (even if static) without mocking, is to provide a set of valid unit tests for this class.
Second Case: if you use a third party utility library, you should have enough confidence to this library. Most of the time, those libraries are well tested and well maintained. You can use it without mocking its methods.