//Claim class Developed in solution ABC
class Claim
{
public Claim(string s)
{
// progreamm.....
}
}
//Test Case needs to write in Solution XYZ
[TestClass]
public class ClaimTest
{
public void myconstructor()
{
//Now Question is how to access class Claim here?
}
}
//Now Question is how to access class Claim constructor in myconstructor //function.
//Hope you get what i need to access using Just Mock in telerik
What you do is add the InternalsVisibleTo attribute to the assembly that contains the internal class. It is explained in the JustMock documentation.
[assembly: InternalsVisibleTo("TestAssembly")]
[assembly: InternalsVisibleTo("Telerik.JustMock, PublicKey=0024000004800000940000000602000000240000525341310004000001000100098b1434e598c6" +
"56b22eb59000b0bf73310cb8488a6b63db1d35457f2f939f927414921a769821f371c31a8c1d4b" +
"73f8e934e2a0769de4d874e0a517d3d7b9c36cd0ffcea2142f60974c6eb00801de4543ef7e93f7" +
"9687b040d967bb6bd55ca093711b013967a096d524a9cadf94e3b748ebdae7947ea6de6622eabf" +
"6548448e")]
After that, rebuild the assembly and then you can use the internal types in the test assembly, just as if they were public types.
You can use Typemock Isolator for faking internal types.
So in your test, you will use:
var fakeInternal = Assembly.Load("ABC").GetType("ABC.Claim");
var fake = Isolate.NonPublic.Fake.Instance(fakeInternal);
And from this point, you can use the Isolate.NonPublic.WhenCalled API for setting the method behavior.
And use the Isolate.Invoke.Method API to invoke the relevant methods.
Related
Maybe I am looking at this wrong but I have been doing so for little over an hour.
I first tried an Extension method, but that was not productive.
Trying to extend the FormsAuthentication class to include a static method to return a concatenated value that is the same pattern sprinkled all over various root points.
Current Code (Option #2):
public partial class FormsAuthentication {
public static string FormsUserCookieName () {
return FormsAuthentication.FormsCookieName + '_' + HttpContext.Current.User.Identity.Name;
}
}
The only thing I have not done, is created a Namespace file for the FormsAuthentication "extension" to be located.
Quite frankly, unsure if "psyching" the compiler into the resident namespace will perform any differently.
Any Suggestions on the best approach will be greatly appreciated.
Update
Based on discussions and review, seems the best approach was to implement a property for the Page class inherited by each page.
public class WebsitePage : Page {
....
public string FormsUserCookieName { get { return FormsAuthentication.FormsCookieName + '_' + User.Identity.Name; } }
....
}
I suppose you want to create an extension-method.
Actually those do not really extend the class FormsAuthentication, as they reside in their own class and are completely independend of the extended class. Have a look at this example:
public static class MyExtensions
{
public static string FormsUserCookieName (this FormsAuthentication) {
return FormsAuthentication.FormsCookieName + '_' + HttpContext.Current.User.Identity.Name;
}
}
This can now be used as if it were defined within FormsAuthentication, if you´d included the namespace where MyExtensions is defined. Thus you can write this now:
myInstanceOfFormsAuthentication.FormsUserCookieName();
However the method doesn´t really belong to that class, it is defined within MyExtensions-class and thus equivalent to the following:
MyExtensions.FormsUserCookieName(myInstanceOfFormsAuthentication);
Another approach is simply to have a wrapping-class around FormsAuthentication:
class FormsAuthenticationEx
{
public static string FormsUserCookieName() { ... }
}
This is much clearer to the user of your API as it shows where your extensions are defined.
Extending the class won't work. All parts of a class must be marked partial and must be defined in the same assembly. You will never achieve the latter and as the class is defined as:
public sealed class FormsAuthentication
It is not partial and like most .NET Framework classes it is sealed.
Your only option is to create an extension method.
I have a class that I would like to test with Unit tests. It has some logic to look for some values in the local xml file, and if the value is not found it will read some external source (SqlServer DB). But during Unit testing I don't want this component to interact with Sql Server at all. During unit testing I would like to replace SqlServer implementation of the External source reader to some Noop reader. What is the good approach to achieve that? Important note: I can't define constructor that accepts instance of reader type since it is client facing API and I want to limit what they can do with my classes.
I am currently using few ways in Unit tests:
Use reflection to set value of the private/protected property to my mocked implementation of the reader
Define factory that will create concrete class. Register factory in Unity container & class under test will get factory object from DI container and instantiate reader according to my needs
Subclass class-under-test and set property there.
But none of them seem to be clean enough to me. Are there any better ways to achieve that?
Here is the sample code to demonstrate example of the class-under-the-test:
namespace UnitTestProject1
{
using System.Collections.Generic;
using System.Data.SqlClient;
public class SomeDataReader
{
private Dictionary<string, string> store = new Dictionary<string, string>();
// I need to override what this property does
private readonly IExternalStoreReader ExternalStore = new SqlExternalStoreReader(null, false, new List<string>() {"blah"});
public string Read(string arg1, int arg2, bool arg3)
{
if (!store.ContainsKey(arg1))
{
return ExternalStore.ReadSource().ToString();
}
return null;
}
}
internal interface IExternalStoreReader
{
object ReadSource();
}
// This
internal class SqlExternalStoreReader : IExternalStoreReader
{
public SqlExternalStoreReader(object arg1, bool arg2, List<string> arg3)
{
}
public object ReadSource()
{
using (var db = new SqlConnection("."))
{
return new object();
}
}
}
internal class NoOpExternalStoreReader : IExternalStoreReader
{
public object ReadSource()
{
return null;
}
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var objectToTest = new SomeDataReader();
objectToTest.Read("", -5, false); // This will try to read DB, I don't want that.
}
}
In this case, you can use the InternalsVisibleTo attribute, which exposes all internal members to friend assemblies.
You could start by creating a separate internal constructor overload, which can accept a different instance of IExternalStoreReader:
public class SomeDataReader
{
// publicly visible
public SomeDataReader()
: this(new SqlExternalStoreReader(...))
{ }
// internally visible
internal SomeDataReader(IExternalStoreReader storeReader)
{
ExternalStore = storeReader;
}
...
}
And then allow the unit testing assembly to access internal members by adding the InternalsVisibleTo attribute to your AssemblyInfo.cs:
[assembly: InternalsVisibleTo("YourUnitTestingAssembly")]
If you're really concerned about people trying to access your internal members, you can also use strong naming with the InternalsVisibleTo attribute to ensure no one tries to impersonate your unit testing assembly.
The simple answer is: change your code. Because you have a private readonly field that creates its own value, you cannot change that behaviour without getting really hacky, if at all. So instead, don't do it that way. Change the code to:
public class SomeDataReader
{
private Dictionary<string, string> store = new Dictionary<string, string>();
private readonly IExternalStoreReader externalStore;
public SomeDataReader(IExternalStoreReader externalStore)
{
this.externalStore = externalStore;
}
In other words, inject the IExternalStoreReader instance into the class. That way you can create a noop version for unit tests and the real one for production code.
If you're compiling the complete code yourself, you could create a fake SqlExternalStoreReader with a stubbed implementation inside your unit test project.
This stub implementation allows you to access all fields and forward calls to your mocking framework/unit test
I am working on a brownfield application and am currently refactoring part of it. I am trying to do this in a TDD fashion but am running into a problem. Part of the code I am testing does
var siteLanguages = from sl in SiteSettings.GetEnabledSiteLanguages() select sl.LanguageID;
where GetEnabledLanguages has the following signature
public static List<LanguageBranch> GetEnabledSiteLanguages();
it in turns calls data access code to retrieve the relevant information. Up untill now I have used a interface and DI to use a different stub implementation for these kind of dependencies during unit testing. But since the GetEnabledSiteLanguages method is static this will not work. What is the "correct" way to do it in this case?
you could create a object which implements an interface and inject an implementation of this into the class which uses the SiteSettings class. The interface declare the method with the same signature as the static method(s) you need to intercept. Then you could mock out the interface for tests and create a single implementation which delegates to the static method for the actual code:
public interface ISiteSettings
{
public List<LanguageBranch> GetEnabledSiteLanguages()
}
public class ActualSiteSettings : ISiteSettings
{
public List<LanguageBranch> GetEnabledSiteLanguages()
{
return SiteSettings.GetEnabledSiteLanguages();
}
}
... in the dependent class:
public class DependentClass
{
private ISiteSettings m_siteSettings;
public DependentClass(ISiteSettings siteSettings)
{
m_siteSettings=siteSettings;
}
public void SomeMethod
{
var siteLanguages = from sl in m_siteSettings.GetEnabledSiteLanguages() select sl.LanguageID;
}
}
What about making your method such as:
public static Func<List<LanguageBranch>> GetEnabledSiteLanguages = () => {
//your code here
};
Now it becomes first class object (as Func delegate) and a stub can replace it
Look at Moles framework.
You can use tools like JustMock, TypeMock or moles. These tools allow you to mock everythings like static methods.
I am designing a loosely-coupled structure. I want to call classes from different assemblies/namespaces via a code which is represented by a String. My design is, each of client's business rules is on different assemblies and not dependent on each other (ONE client is to ONE DLL ratio) so that when I made an update on business rules of 1 client, it would not affect the others. My attention now is on using Factory Design and using Activator.CreateInstance() Method.
This is the project setup (2+n DLL's)
namespace Foundation; // where the interfaces/abstract resides
namespace Factory; // has dependency on Foundation assembly
namespace Client1; // client1's DLL, no dependency
namespace Client2; // client2's DLL, no dependency
The UI // only referenced to the Foundation and Factory not the Clients
The actual code
namespace Foundation
{
public interface IBusinessRules
{
string GetBusinessRule();
}
}
namespace Client1 //DLL for client 1
{
public class BusinessRules : Foundation.IBusinessRules
{
public string GetBusinessRule()
{
return "Client1 Business Rule";
}
}
}
namespace Client2 //DLL for client 2
{
public class BusinessRules : Foundation.IBusinessRules
{
public string GetBusinessRule()
{
return "Client2 Business Rule";
}
}
}
namespace Factory
{
public static class Invoker<T> where T: Foundation.IBusinessRules
{
public static T FetchInstance(string clientCode)
{
return (T)Activator.CreateInstance(Type.GetType(clientCode));
}
}
}
//sample implementation that generates unhandled Exception
using Factory;
using Foundation;
static void Main(string[] args)
{
//the parameter is maintained in the database
IBusinessRules objClient1 = Invoker<IBusinessRules>.FetchInstance("Client1");
//should call Client1.BusinessRules method
Console.WriteLine(objClient.GetBusinessRule());
Console.Read();
objClient = Invoker<IBusinessRules>.FetchInstance("Client2");
//should call Client2.BusinessRules method
Console.WriteLine(objClient.GetBusinessRule());
Console.Read();
}
Any idea why my sample doesn't work? And any suggestion to improve the design?
Thanks in advance.
How about using
Expression.Lambda
anyone?
If you use FetchInstance("Client.BusinessRules") your code works, IF everything is in the same assembly. If it's not (as per your design) you need to give an AssemblyQualifiedName.
I would do the design differently though. Keep your call with just "Client1" as Parameter but change the implementation of the Factory. Dynamically load the assembly for the given client (with Assembly.Load() or Assembly.LoadFrom()), then use clientAssembly.CreateInstance() to istantiate your type.
Edit: Crude code sample:
namespace Factory
{
public static class Invoker<T> where T: IBusinessRules
{
public static T FetchInstance(string clientCode)
{
var clientAssembly = Assembly.LoadFrom(clientCode + ".dll");
return (T)clientAssembly.CreateInstance(clientCode+".BusinessRules");
}
}
}
If you dont't know the class name in the client-dll, you have to search for an applicable Type, for example with clientAssembly.GetTypes().
Thanks to your help guys i finally Got it! I just modify the Factory
namespace Factory
{
public static class Invoker<T> where T : Foundation.IBusinessRules
{
public static T FetchInstance(string clientCode)
{
Type objType = Type.GetType(clientCode + ".BusinessRules," + clientCode);
return (T)Activator.CreateInstance(objType);
}
}
But I wonder about its effeciency (performance hit) because it uses Reflection..
You need to use the full name of the class.
for example:
Type.GetType("System.Collections.Generic.Dictionary`2[System.String,[MyType,MyAssembly]]")
If you are loading the type from an external assembly, I would recommend using Activator.CreateInstanceFrom.
var typeReference = Activator.CreateInstanceFrom(assemblyPath, fullyQualifiedClassName);
return typeReference.Unwrap() as T;
If you want to be able to add business rules as dlls after deployment and create them at runtime, I suggest you have a business rules folder under you app, load all dlls in that app, search for all types that implement of IBusinessRules in each dll using reflection. Given that you now have handles on the types, creating one based on name would be easy and your project would scale out.
Either that, or pass the assembly qualified name of the classes to your methods.
In C#, can you make a class visible only within its own namespace without living in a different assembly? This seems useful for typical helper classes that shouldn't be used elsewhere.
(i.e. what Java calls package-private classes)
You can make the classes internal but this only prevents anyone outside of the assembly from using the class. But you still have to make a separate assembly for each namespace that you want to do this with. I'm assuming that is why you wouldn't want to do it.
Getting the C# Compiler to Enforce Namespace Visibility
There is an article here (Namespace visibility in C#) that shows a method of using partial classes as a form of "fake namespace" that you might find helpful.
The author points out that this doesn't work perfectly and he discusses the shortcomings. The main problem is that C# designers designed C# not to work this way. This deviates heavily from expected coding practices in C#/.NET, which is one of the .NET Frameworks greatest advantages.
It's a neat trick… now don't do it.
I don't think that what you want is possible.
internal is assembly (strictly speaking module) privacy. It has no effect on namespace visibility.
The only way to achieve privacy of a class from other classes within the same assembly is for a class to be an inner class.
At this point if the class is private it is invisible to anything not in that class or the outer class itself.
If protected it is visible to everyone that could see it when private but is also visible to sub classes of the outer class.
public class Outer
{
private class Hidden { public Hidden() {} }
protected class Shady { public Shady() {} }
public class Promiscuous { public Promiscuous() {} }
}
public class Sub : Outer
{
public Sub():base()
{
var h = new Hidden(); // illegal, will not compile
var s = new Shady(); // legal
var p = new Promiscuous(); // legal
}
}
public class Outsider
{
public Outsider()
{
var h = new Outer.Hidden(); // illegal, will not compile
var s = new Outer.Shady() // illegal, will not compile
var p = new Outer.Promiscuous(); // legal
}
}
In essence the only way to achieve what you desire is to use the outer class as a form of namespace and restrict within that class.
No, it is possible. You can use internal class in another assembly.
For example I have a internal string extension class that located in SharMillSoft.Core assembly, if I want use it in another assembly that name is SharpMilSoft.Extension, I must use assembly attribute like as below:
using System;
using System.Linq;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("SharpMilSoft.Extensions")]
namespace SharpMilSoft.Core.Extensions.Strings.Public
{
internal static class SharpStringExtensions
{
public static bool IsNullOrEmpty(this string data)
{
return string.IsNullOrEmpty(data);
}
}
}
And I use this class in SharpMilSoft.Extension assembly like as below:
namespace SharpMilSoft.Extensions.Strings
{
public static class SharpStringExtensions
{
public static bool IsNullOrEmpty(this string data)
{
return Core.Extensions.Strings.Public.SharpStringExtensions.IsNullOrEmpty(data);
}
}
}
Note: Then SharpMilSoft.Extensions assembly will be friend assembly for SharpMilSoft.Core assembly
For more details about friend assembly, you can visit this link : Friend assemblies
If you have a single assembly you can define as many namespaces in that assembly as you want but no matter what modifier you apply in the IDE you will always be able to see the classes in other namespaces.
Not sure if it is directly possible, but a few good ways to fake it would be:
1) Have the classes that need this sort of stuff inherit from a single class which has the helper class as an internal class.
2) Use extension methods and then only reference the extension methods within the namespace.