I have a web part that uses PortalSiteMapProvider to query the Sharepoint navigation hierarchy, but unit tests written for that code fail, because the code is being run outside the Sharepoint context and thus no site map providers are available.
I've identified two alternate ways of solving this dilemma:
Because Sharepoint is basically an elaborate ASP.Net application, it should be possible to run tests inside the Sharepoint context with the HostType and UrlToTest test attributes
Use a mock instead of PortalSiteMapProvider
Are either of these viable or is there a better third option?
The Microsoft Patterns and Practices dudes recommend TypeMock to help unit test Sharepoint
http://msdn.microsoft.com/en-us/library/dd203468.aspx
http://www.typemock.com/sharepointpage.php
Not a free solution unfortunately.
You will not be able to mock the SPRequest class, which is an internal class. I am facing the same issues.
One approach is to try to isolate your code from the SharePoint API, and this is not so nice.
BTW Typemock have a reduced price product especially for SharePoint.
Second option is more appropriate. Abstract away PSMP and hide it behind IPortalSiteMapProvider and then mock it in your unit test. In order to bridge the interface and concrete implementation you can either write a thin delegating adapter or use duck typing.
Related
I am trying to write a unit test that will perform a check against a string returned from a method. That string is a part of an entity, which should be generated by a call to the database. I can easily stub such entity, but I don't know how to omit the call to the database, since it is a part of the method.
The method looks like this:
private string GetDescriptionForRelationEntry(string relAttrId, string client)
{
// here we are querying the database
var relationEntities = new EntityDatabaseQuery<AttributeEntryEntity>();
// the rest of the method
}
The part specified as the rest of the method needs to be executed, because I have to obtain the string result to perform necessary checks. So, basically, I need to "fake" only one line of code.
Right now I'm not able to say how extensive modifications on the SUT class are allowed, thus I'm not limiting this problem to any specific solution. Any help will be appreciated.
Usually a testable class would be an implementation of some interface or a derived class of some abstract class.
Thus, you can use an inversion of control container framework like Castle Windsor, Ninject or any that might you love more, and provide a fake implementation of the whole interface which won't hit the database, but it'll return a test query result.
You can simply create a mock method to represent your DB result
Use this link for more details : http://msdn.microsoft.com/en-us/library/ff650441.aspx
I'd advise you to take a look at a solution that lets you wrap a database in memory. For example there is the Effort library.
Effort is a powerful tool that enables a convenient way to create
automated tests for Entity Framework based applications. It is
basically an ADO.NET provider that executes all the data operations on
a lightweight in-process main memory database instead of a traditional
external database. It provides some intuitive helper methods too that
make really easy to use this provider with existing ObjectContext or
DbContext classes. A simple addition to existing code might be enough
to create data driven tests that can run without the presence of the
external database.
I explained how I use it in this answer: it was for Entity Framework but I think the same behavior can be used in your case.
Most mocking frameworks require you to change the architecture of your solution, creating and implementing interfaces, and loading implementations dynamically.
However, you can also use Microsoft Fakes, which requires no changes to your application. Fakes come with Visual Studio, so you don't need to download or install anything.
For more information, see http://msdn.microsoft.com/en-us/library/hh549175.aspx
Microsoft Fakes help you isolate the code you are testing by replacing other parts of the application with stubs or shims. These are small pieces of code that are under the control of your tests.
I'm setting up continuous integration and deployment for my companies Azure based web service. I'm already committed to using TypeMock Isolator, but I'm not certain if we're going to need Essential or if the Basic version is going to do what I need. Can anyone tell me exactly what advantages and/or features the Essential version has that the Basic version doesn't? The website is really lacking in specificity here, it just has some vague text about "test anything."
So far I've found one difference, which is Essential allows one to test in "DesignMode.Pragmatic" mode. This appears to allow me to assign to read only properties. Sure, that's useful, but I'm not sure if that's going to save me enough time to justify the $800 price tag. Can anyone else tell me what else the "Pragmatic" design mode allows?
Thanks in advance,
Nathan C. Tresch
Typemock isolator essential (and above) is typically used when you want to mock out things that are statically bound, such as concrete dependencies (where dependencies aren't interfaces / abstract classes).
For instance, suppose you had a class that did file manipulation using System.IO, if you wanted to write a unit test, you would need to mock out some static methods or concrete implementations of the File class, typemock isolator essential (and above) will let you do this, while the basic will only let you mock out interfaces / abstract classes (similar to Moq).
I am currently working on a c# project which makes use of an SQLite Database. For the project I am required to do unit testing but was told that unit testing shouldn't involve external files, like database files for the testing and instead the test should emulate the database.
If I have a function that tests if a something exists in a database how could this sort of method be tested with a unit testing.
in general it makes life easier if external files are avoided and everything is done in code. There are no rules which says "shouldn't", and sometimes it just makes more sense to have the external dependency. But only after you have considered how not to have it, and realized what the tradeoffs are.
Secondly, what Bryan said is a good option and the one I've used before.
In an application that uses a database, there will be at least one component whose responsibility is to communicate with that database. The unit test for that component could involve a mocked database, but it is perfectly valid (and often desirable) to test the component using a real database. After all, the component is supposed to encapsulate and broker communication with that database -- the unit test should test that. There are numerous strategies to perform such unit tests conveniently -- see the list of related SO questions in the sidebar for examples.
The general prescription to avoid accessing databases in unit tests applies to non-database components. Since non-database components typically outnumber database-related components by a wide margin, the vast majority of unit tests should not involve a database. Indeed, if such non-database components required a database to be tested effectively, there is likely a design problem present -- probably improper separation of concerns.
Thus, the principle that unit tests should avoid databases is generally true, but it is not an absolute rule. It is just a (strong) guideline that aids in structuring complex systems. Following the rule too rigidly makes it very difficult to adequately test "boundary" components that encapsulate external systems -- places in which bugs find it very easy to hide! So, the question that one should really be asking oneself when a unit test demands a database is this: is the component under test legitimately accessing the database directly or should it instead collaborate with another that has that responsibility?
This same reasoning applies to the use of external files and other resources in unit tests as well.
With SQLite, you could use an in-memory database. You can stage your database by inserting data and then run your tests against it.
Once databases get involved it always blurs the line between unit testing and integration testing. Having said that, it is always a nice and very useful test to be able to put something in a database (Setup), Do your test and remove it at the end (Cleanup). This lets you test end to end one part of your application.
Personally I like to do this in an attribute driven fashion. By Specifying the Sql scripts to run for each test as an attribute like so ..
[PreSqlExecute("SetupTestUserDetails.sql")]
[PostSqlExecute("CleanupTestUserDetails.sql")]
public void UpdateUserNameTest()
{
The connectionstrings come from the app.config as usual and can even be a symbolic link to the app.config in your main project.
Unfortunately this isn't a standard feature with the MS test runner that ships with visual studio. If you are using Postsharp as your AOP framework, this is easy to do. If not, you can still get the same functionality for standard MS Test Runner, by using a feature of .Net called "Context Bound Objects". This lets you inject custom code into an object creation chain to do AOP like stuff as long as your objects inherit from ContextBoundObject.
I did a blog post with more details and a small, complete code sample here.
http://www.chaitanyaonline.net/2011/09/25/improving-integration-tests-in-net-by-using-attributes-to-execute-sql-scripts/
I think is really bad idea to have unit tests that depends on database information.
Also I think is a bad idea to use sqlite for unit tests.
You need to test objects protocol, so if you need something in your tests you should create them somewhere in the tests (usually at setUp).
Since is difficult to remove persistence, the popular way to do it is using SQLite, but always create what you need in unit tests.
check this link Unit Tests And Databases this will be more helpful I think
It's best to use a mocking framework, to mimic a database. For C# there is the Entity Framework. Even the use of sqlite is an outside dependency to your code.
I've implemented a subscribe/publish (for my own enjoyment) WCF service which works reasonably well. Like all blogs and books I've seen they all use OperationContext to get the clients callback address. After a bit of reading, due to many people saying not to use OperationContext, I found myself not being able to create proper unit tests. Yet I haven't been able to find an alternative. I suppose the subscribe method could accept a parameter for it to provide its own address? I could see the code being testable from an intergration test stand point of view but not for unit testing since OperationContext would always be null.
How do I get the clients endpoint when they subscribe to my service without using OperationContext?
Little bit of an aside but where is a good WCF resource with testing in mind when showing code samples? There are tons of blogs out there reiterating the same code without providing sample test cases.
Thank you.
Microsoft developers really like sealed and static keywords (as well as internal) and they hate virtual. Because of that standard testing approaches and framworks often don't work. You have two choices:
Wrap access to OperationContext in custom class and inject an instance of the class to your service. This will involve additional work because you will need to do injection somewhere outside your service. For example constructor injection will need custom IInstanceProvider.
Use more poweful testing framework. Check Moles framework which is able to intercept calls and redirect them. This enables "mocking" sealed classes and static methods/properties.
Another approach is simply refactoring your code. Take away all business logic from your service into separate testable business class and let the service participate only in integration test. Service is more like infrastructure and not everything really needs unit test. Integration / end-to-end / behavior test is also test and valid approach.
I'm utilizing the Reporting Services web service to generate a report and allow the user to download it. This is occuring via PDF, Excel, XML, etc. and working just fine. I'm trying to create some seperation between my reporting class and the implementation, but am struggling with how I can can do this in a manor that is still testable.
Since my custom Reports Object/Class is calling the web service directly, should I seperate this out even further with the use of interfaces? Any reccomendations on this and how it would still be unit testable regardless of the byte source would be much appreciated.
Russell, I think your answer lies in learning about Dependency Injection/Inversion of Control. You might start here...
http://codebetter.com/blogs/jeremy.miller/archive/2005/10/06/132825.aspx
http://misko.hevery.com/2009/01/14/when-to-use-dependency-injection/
http://iridescence.no/post/Using-Unit-Tests-to-Uncover-Design-Flaws.aspx
http://en.wikipedia.org/wiki/Dependency_injection
http://martinfowler.com/articles/injection.html
If you're new to Dependency Injection/Inversion of Control, this link is a great screencast by Carl Franklin and James Kovacs.
DNR TV Show #126: James Kovacs' roll-your-own IoC container
I'm a sucker for learning new things by hearing others explain it clearly and watching them code it. James explains the principles, the code that does it, and how you can further your study by using a framework.
As mentioned, Dependency Injection/Inversion of Control is the way to go. Code to an interface rather than a concrete class. Then, when your unit test runs it can swap the web service implementation with a mock implementation that returns fake, fixed data.