I am using the mediator pattern to facilitate unit testing of GUI objects.
psudo code Example:
Class MyGuiClass
{
//... Declare and initialize mediator to be a MyMediator
private void On_SomeButtonPressed()
{
mediator.SomeButtonWasPressed();
}
}
Class MyMeditator
{
public void On_SomeButtonPressed()
{
//.. Do something now that the button was pressed
}
}
This is nice because I can now unit test what happens when SomeButton is pressed without having to create a Window.
My concern is that I have taken a method that was private and made it public for any one who makes a Mediator to call. Past times I have done this it did not bother me because I did not have many methods that I had to make public.
I am currently refactoring a very large class to use this pattern and I am wondering if there is someway I can control the visibility of who can make a MyMediator or which classes some of the methods are public for. (This may not be possible or even needed, but I thought I would ask.)
(I am using C# 3.0 with .NET 3.5 SP1)
I think it doesn't matter.. Who has an instance of the mediator, other than the gui? If someone does, is it going to call the method? If it does, does it matter? Will it be hard to notice, diagnose and fix the bug?
I think you can achieve what you are looking for with events though:
e.g.
/* in the gui class (view) */
public event EventHandler OnButtonClicked;
/* in the mediator */
public MyMediator(MyView view)
{
view.OnButtonClicked += HandleButtonClicked;
}
private void HandleButtonClicked(object sender, EventArgs e)
{
}
Not sure about c#, but in java you can declare something as package-level access (in java by omitting the access specifier). What I do is create a separate test hierarchy that parallels my package structure, so to test class com.a.b.c.MyClass, I'll have a test class com.a.b.c.MyClassTest, which can then legally access the package-access methods in MyClass.
I don't so much like the idea of making everything public not only because of access issues, but because it clutters up the interface - I'd rather the public interface of the class express what it does, not how it does it, which is often where I end up if I expose methods I'd prefer to be private.
The point is that you'd like the public interface of a class to show that class's public 'API', so in making private methods public you are making the class more confusing and less 'clean'?
A few things you can do:
1) think through what actually is the 'public face' of your mediator (or humble object) class and happily make those methods public. Even if they are only used within the assembly - not part of the assembly's public face - that's okay because notice that your mediator class itself is not declared public. So even its public methods are still internal to the assembly.
2) You can fudge the privates by using internal for private (and then set the assembly's InternalsVisibleTo attribute if your test classes are in a separate assembly).
3) Take the 'black box' approach to unit testing whereby in principle you never need to test the privates because they get tested via their use when called from the public methods.
Related
Don't have much experience with testing, trying to change that by testing libraries I've made recently.
Using nunit with nsubstitute for this.
So the situation I have is a class like this:
class MyClassToTest {
private ISomeOtherClass MyPrivateClass { get;set }
public MyClassToTest() {
MyPrivateClass = new SomeOtherClass();
}
public void DoSomething() {
MyPrivateClass.SayHello();
}
}
Now, a test for the DoSomething method would be to see if the method SayHello() was actually called on the ISomeOtherClass instance.
The problem is that it's private, when looking up the best way to test this, the only thing that came up was to make the property internal and set the InternalsVisibleToAttribute to the assembly the tests are in.
While this solution works and the external interface for my library is still ok, the correct accessor for this property in the context of the library would still be private.
The test I'd write is after making it interal:
public void MyTest() {
var objPrivateClass = Substitute.For<ISomeOtherClass>();
var obj = new MyClassToTest();
obj.MyPrivateClass = objPrivateClass;
obj.DoSomething();
objPrivateClass.Received().SayHello();
}
Is there a better way to test this without me having to modify my original code to make it testable?
It might be setting InternalsVisibleToAttribute and making the property internal is the correct thing here, but a couple of hours ago I didn't know about the existence of InternalsVisibleToAttribute so thought it best to ask :)
To answer the exact question, You can use reflection to reach private members, but that is a fragile and rather slow solution.
The best advice I can give you is that private things should stay private; test an object's behavior through its public interface. So if is too big and hard to test, just refactor it to be testable. Think of the Single Responsibility Principle and the Inversion of Control principles.
Edit 1.: You are probably looking for the concept of Dependency Injection. This should be alright most of the times; however when we talk about highly reusable libraries (you mentioned you are making a lib), other solutions may fit better for the users of your library (e.g. creating a Facade or rethinking your design).
I'm making a game in Unity C# using a Singleton GameManager and I was warned that using references of the class in other scripts like GameManager.instance.someVar makes the code fragile and difficult for later edit. So I looked for how to access a singleton with interfaces but haven't found what I was after. As I wish to code properly, I would like someone to point me to a decent source that tells me how to do so, or have him/her tell me in brief.
Well there is a general solution to this, I am not sure how feasible it will be for you.
Suppose we have a true singleton:
public static class Highlander //cos, there can be only one. Sorry. couldn't resist
{
public static void Quicken(string name)
{
Console.WriteLine("{0} gets their quickening on",name);
}
}
Suppose we want to be able to pass this around in an abstract manner, using Interfaces.
public interface IImmortal
{
void Quicken();
}
Well, you cannot implement an interface on a static class or member, so how do you pass references to this class around by interface?
Simple - create a wrapper/adapter class which implements the interface you want:
public class McLeod: IImortal
{
public void Quicken()
{
Highlander.Quicken("Conor");
}
}
public class Kurgen: IImortal
{
public void Quicken()
{
Highlander.Quicken("The Kurgen");
}
}
Now you can pass IImortal around, and the wrapping implementation(s) simply call through to the Singleton. Note how the Wrapper can supply data to the Singleton from within itself, as above, in which case it's more like an Adapter. But the concept is the same.
In the case of Unity, I don't know if this will suit, since the GameManager class likely exposes a ton of other properties and methods you would also have to wrap/adapt - it may not be worth creating wrapper interfaces for all of this, so consider perhaps that in this case you need to embrace it :)
Singletons, being static, dont support interfaces. Perhaps your other source might mean that you should use a Factory pattern or perhaps an Inversion of Control (IOC) method. In those cases the Factory would look like GameManagerFactory.GetGameInstance() rather than refer to the Instance static property of a GameManager.
The true limitation of Singlton programming is in the area of unit testing - because your code is bound directly to the specific class "GameManager" you could not replace it in a unit test with another "test version" of the GameManager. To support unit testing you should try to make sure that any significant classes your code depends on could be replaced by a test version of a class, without your code caring. When using Singletons this is hard (if not impossible) to do.
Usually I tend to create an empty GameObject, give it a proper name or a tag and attach a script component to it.
This way I can easily get a reference in any other GameObject that might need it and retrieve the script component from it.
This one is a bit complicated, so please read everything through. I'm working on some code that implements the MVVM Pattern for WPF. I have a XAML Markup extension that looks for a specific property on the datacontext. (It's a long and fun story, but out of scope) My view model will be set as the Dataconext on the view.
Here's an example of how I have implemented my BaseViewmodel...
public class ViewModelBase : IViewModelBase
{
protected CommandManagerHelper _commandManagerHelper;
//todo find a way of eliminating the need for this constructor
public OrionViewModelBase(CommandManagerHelper commandManagerHelper)
{
_commandManagerHelper = commandManagerHelper;
}
private IExampleService _exampleService;
public IExampleService ExampleService
{
get
{
if (_exampleService == null)
{
_exampleService = _commandManagerHelper.GetExampleService();
}
return _exampleService;
}
}
}
What's going on there is that I'm effectively lazy loading the _exampleService. I'm sure it's possible to use Lazy, but I've not got round to implementing that just yet.
My Xaml Markup will be looking for and making use of my the ExampleService it could also be used by code within the view model. It's going to be used all over the application.
A point to note is that my application will have only one instance of the ExampleServer that will be passed around, calling GetExampleService from anywhere in the application will return the same instance of the object. There will only be one instance of the ExampleService object, although it is not coded as a singleton.
Here is an example of how I am inheriting from my ViewModelBase...
internal class ReportingViewmodel : ViewModelBase
{
private readonly IReportingRepository _reportingRepository;
public ReportingViewmodel(CommandManagerHelper commandManagerHelper, IReportingRepository reportingRepository) : base(commandManagerHelper)
{
_reportingRepository = reportingRepository;
}
}
This code works and works great. However, having to type ": base(commandManagerHelper)" every time that I implement a new inherited member of the ViewModelBase is prone to mistakes. I'm likely to have 100's of these implementations and each one needs to be right.
What I'm wondering is.... is there a way of implementing the same behaviour respecting the SOLID principles and not having to call the base constructor every time I implement an instance of the ViewModelBase?
i.e. I'd like the ReportingViewModel to look like this
internal class ReportingViewmodel : ViewModelBase
{
private readonly IReportingRepository _reportingRepository;
public ReportingViewmodel(IReportingRepository reportingRepository)
{
_reportingRepository = reportingRepository;
}
}
but still have the ExampleService populated correctly.
I'm currently considering using the Service locator pattern for this, I'm also considering using a Singleton and I'm open to other better solutions.
The reason that I'm asking the question rather than diving in with code is that I know that the Singleton is generally an anti-pattern, to me it signifies that something else is wrong in the code.
I've just read an article on IoC and it's slating the Service locator pattern here's the article http://www.devtrends.co.uk/blog/how-not-to-do-dependency-injection-the-static-or-singleton-container.
You can't get out of calling the base constructor.
It doesn't really matter that IExampleService is only instantiated once and shared. Your ViewModelBase doesn't (and shouldn't) "know" that. All it needs to know is that whatever is injected implements that interface.
That's one of the big benefits, because when you unit test classes you can inject a mocked version of that interface. If classes depended on a static reference to something buried within a base class then it wouldn't be possible to replace it with a mock for testing.
I use ReSharper. (Am I allowed to say that? I don't mean to advertise.) Among many other things it generates those base constructors for you. I'm sure at some point that's got to get built in to Visual Studio.
I have a question about coding practice. I want to create a class which can't be initialized. I believe I have 3 options:
Abstract modifier
Static modifier
Private constructor
I don't want to create a static class simply because of having to name all of my properties and methods 'static' - it looks messy (and I can't use the 'this' keyword).
According to the MSDN:
Use the abstract modifier in a class declaration to indicate that a
class is intended only to be a base class of other classes.
Edit Nothing will inherit form this class.
However, it would be a solution (but it seems wrong to me to use it in this situation).
Or, I can make a private constructor so the class cannot be initialized.
If it helps the reason for why is this: The class is responsible for starting off a work flow process. It doesn't need to be initialized since nothing is returned - it just needs to be 'started'.
Demo code
class Program
{
static void Main(string[] args)
{
WorkFlow wf = new WorkFlow(); // this will error which is fine!
ComplexObject co = new ComplexObject();
WorkFlow.Begin(co);
Console.ReadKey();
}
}
public class WorkFlow
{
private WorkFlow()
{
//private to prevent initialization but this feels wrong!
}
public static void Begin(ComplexObject co)
{
//code to begin the workflow
}
}
I want to create a class which can't be initialized.
That leaves the possible usages: static or base-class only.
If your class is going to be derived from, use abstract. A private/protected constructor would be a hack in this situation.
Your sample code looks more like a static class. With Singleton as alternative.
What about doing just what you have done but using your Begin method as a factory to create your workflow.
var workflow = Workflow.Begin(complexObject);
public class WorkFlow
{
private WorkFlow()
{
//private to prevent initialization but this feels wrong!
}
public static WorkFlow Begin(ComplexObject co)
{
return new Workflow(co);
}
}
Good practice: Private constructor (at least is what the GOF book recommends when using the Factory pattern, for example). I'll suggest you to use abstract if it's a base class (that's what it's name suggest).
If the class is strictly being used as a base class, it would have to be abstract for me.
Based on your update I would go for a static class & method e.g.
WorkFlow.Begin(co);
However, since you don't want to do this I think it only leaves you with one option...private constructor.
Seems like you would need a singleton.
More reference here:
http://msdn.microsoft.com/en-us/library/ff650849.aspx
if you dont like the ideea, well an abstract class would be best suited because as you said you dont want to instantiate it, and lets not forget that the abstract class does just that, so why try and use a private constructor.
I don't want to create a static class simply because of having to name
all of my properties and methods 'static' - it looks messy (and I
can't use the 'this' keyword).
Well, either you make ctor private or make a class static, the only way caller can access methods and properties of your class (if the caller is not derived one) is via public static members.
Having private ctor give you more flexibility in inheritance chain, but doesn't help much in "avoid static members" scenario.
I will prefer private constructor ie its identical to Singleton pattern
Info
Coding
Private constructors seems to be good approach for your requirement. Abstracts are good too but private constructor is handy than abstract. But if you would like to extend its information then its probably good idea to use abstract.
If the class needs to be "started" it needs to be initialized (unless all you're going to use are static methods).
Abstract classes are used to leave some (or all) of the implementation to subclasses, and by your description - not suitable for you.
"Static classes" - no special gain here I guess (in your case).
Private constructors - used to limit who can instantiate the class.
Not sure that any of these matches your design, but I guess you really want a singleton - look it up, this is the most common and basic design pattern.
BTW - I use singletons only as a last resort, usually when the class controls some kind of non shared resource.
I have a class as follows.
public class MyClass
{
public MyMethod()
{
int x = CalculateSomething();
}
private int CalculateSomething()
{
// Do something and return an int
return 100;
}
}
To unit test this I added [assembly: InternalsVisibleTo("MyTests")] and changed the private method to be internal virtual.
In the unit test project I created a class MockMyClass and created private method as follows.
public class MockMyClass : MyClass
{
public bool MadeHappyNoise {get; set;}
internal override int CalculateSomething()
{
MadeHappyNoise = true;
return base.CalculateSomething();
}
}
The unit test is now as follows
[TestMethod()]
public void WasCalculateSomethingCalledOK()
{
MockMyClass mk = new MockMyClass();
mk.MyMethod();
Assert.IsTrue(mk.MadeHappyNoise, "Oops...CalculateSomething not called...");
}
Few questions: Is this is a good way to remove dependencies? I personally don't like to change a method from private to internal but have no option (other than to use Reflection perhaps). Also, the attribute InternalsVisibleTo("MyTests") residing in the production code is not good. Can someone point me to a better solution please? Thanks.
It rather depends on the methods you are changing the scope of. A unit is the smallest testable component of a piece of software - it rarely means one test per method.
I find that comprehensively testing my public methods is enough to establish correct behaviour. You might find that your tests start to constrain your code development if you wrap the private methods with tests.
If your program is more procedural you might find that you need to test at the granular level you describe, in which case using friend assemblies is a fine solution. However, I'd suggest that you would rarely need to test methods that aren't public.
Too much work for too little value. All that test tells me (if it passes) is that calling MyMethod calls another private method. The unit test should be testing the behavior provided by MyMethod() - what should happen/change after a call to MyMethod?.
The title of the question is a bit misleading too - there is no dependency-related issue that I can see.
You do not need InternalsVisibleTo for the most part.. simply test the private method through the public method that exercises it e.g. Write unit tests for MyMethod(). Also if you practice test-first programming, you'd already have tests that cover every line of code in the private method.
Hmm. I have some issues with that code, but we'll do one at a time.
Why would you want to test if MyMethod calls CalculateSomething? It's an implementation detail that is probably likely to change (what if it calls CalculateSomething2 tomorrow but apart from that still does what it's supposed to do?). If you want to test the code structure of MyMethod, do a code review, not a unit test.
You say that MyMethod is complex and you want to test the code flow inside. If there are multiple paths inside, you still have to write a unit test for each path, so why can't you check the result of calling MyMethod instead of checking the inside of it?
Another thought would be to try and refactor MyMethod into methods that lend themselves to easier testing (that's almost automatic if you do test-driven-development, a practice I recommend if you want to do serious unit testing. The "test later" approach almost always leads to code that is much more difficult to test).
If you still want to check the inner workings of MyMethod, maybe you can refactor the private methods you need to check this into another class (say "Calculations" in your example).
Then you can use a mock framework (like RhinoMocks for example), to mock that class. The framework lets you define what functions you expect to be called in what order and what they should return.
Usually you use mocks to lessen the environment requirements for unit tests, but you can use them in this way also.
Can you maybe refactor it to be like this:
public class MyClass
{
private Calculator calculator;
public myMethod()
{
int x = calculateSomething();
}
public void SetCalculator( Calculator c ){
calculator = c;
}
private int calculateSomething()
{
return calculator.CalculateSomething();
}
}
And then have calculator as a separate class and set an instance on MyClass
public Class Calculator {
public virtual int CalculateSomething()
{
// Do something and return an int
return 100;
}
}
You could make Calculator implement an interface and then have a different Calculator implementation or a mock that you use in your tests.
If this is a piece of legacy code that you are too scared to touch, i would advise you to create a unit test which would construct MyClass. Tentatively create a public property in MyClass to expose the value of x.
In the unit test just created assert that value of x is 100 after MyClass is instantiated. Once you have that in place, refactor like #alb suggests. Run the test again, make sure x is still 100 and test the calculator class separately and eventually remove the tentative public property for x in MyClass. hope that helps.