I have a public method in a class that internally calls a particular private method within that class. It looks something like this :
public class MyClass : IMyClassInterface
{
public List<int> MyMethod(int a, int b)
{
MyPrivateMethod(a, b, ref varList, ref someVal);
}
private void MyPrivateMethod(int a, int b, ref List<int> varList, ref double someval)
{
}
}
Now, I basically want to test this public method using NUnit. I am using NMock 2.0 for mocking. How do I do it? Since, it internally calls this private method which I do not want to make public. Or is there a way to do it if I turn the private method to protected instead?
Now, I basically want to test this public method (...)
This is great. This is what you should be doing. Forget about internal details for a moment. From public method point of view, is there any difference between these two snippets?
// Your current implementation
public void MyMethod(int a, int b)
{
MyPrivateMethod(a, b);
}
private void MyPrivateMethod(int a, int b)
{
var c = a + b;
// some more code
}
// Private method inlined
public void MyMethod(int a, int b)
{
var c = a + b;
// some more code
}
Whoever calls (public) MyMethod will not be able to notice any difference between these two. End result is the same. It doesn't matter there is a private method call, because as far a public API is concerned it is irrelevant. You could inline said private method, make it gone forever, and from public consumer point of view nothing changes. End result is the only thing that's important. You test end result observable by code consumer. Not some internal gibberish.
Important realization is this:
Properly designed SOLID code will never put you in a position which will require you to do private mocking. Source of the problem? Bad design.
Source: How to mock private method - solutions
Yep. Sad but true, your design is not that great. Depending on whether you want to change that or not, there are few approaches you could take:
don't try to mock private details, focus on public API (doesn't help with design issue)
extract private method to class, introduce dependency (long-term solution, improves design and makes code easily testable)
make private method protected, override in test as suggested in other answer (doesn't help with design issue, might not yield valuable test)
Whichever you chose I leave up to you. However, I'll emphasize it one more time - mocking private method is not unit testing, library or tools problem - it is a design problem and is best solvable as such.
On a side note, (if you can) don't use NMock2. It's a library with last changes from 2009. It's like having a 30 year old car which was last serviced 15 years ago. There are much better ones nowadays (FakeItEasy, Moq, NSubstitute).
Yes the "trick" is to use protected instead of private and then inherit the class and run the test on the new class that executes the protected method.
This is a very common way to make brownfield and legacy code testable.
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
MyClassTestWrapped t = new MyClassTestWrapped();
Assert.IsTrue(t.MyPrivateMethod(...));
Assert.IsTrue(t.MyMethod(...));
MockFactory _factory = new MockFactory();
Mock<MyClassTestWrapped> mock;
mock = _factory.CreateMock<MyClass>();
mock.Expects.One.MethodWith(d => d.MyPrivateMethod()); // do the nmock magic here
}
}
public class MyClass : IMyClassInterface
{
public List<int> MyMethod(int a, int b)
{
MyPrivateMethod(a, b, ref varList, ref someVal);
}
// here change to protected
protected void MyPrivateMethod(int a, int b, ref List<int> varList, ref double someval)
{
}
}
public interface IMyClassInterface
{
}
public class MyClassTestWrapped : MyClass
{
public List<int> MyMethod(int a, int b)
{
base.MyMethod(a, b);
}
public List<int> MyPrivateMethod(int a, int b,ref List<int> varList, ref double someval)
{
base.MyPrivateMethod(a, b, ref varList, ref someval);
}
}
While currently you have to refactor your code to lose the private modifier ( wrappers and what not), You can do it fairly easy with tools Like Typemock Isolator.
I added some code to your example to write the test:
public class MyClass
{
public List<int> MyMethod(int a, int b)
{
List<int> varList = new List<int>();
double someVal = 0;
MyPrivateMethod(a, b, ref varList, ref someVal);
return varList;
}
private void MyPrivateMethod(int a, int b, ref List<int> varList, ref double someval)
{
}
}
With this straight forward approach you just fake the private method as it is in your code (no changes in the production), even it's ref parameters:
[Test]
public void TestMethod1()
{
//Arrange
var myClass = new MyClass();
var expectedVarList = new List<int> {1,2,3};
Isolate.NonPublic.WhenCalled(myClass, "MyPrivateMethod")
.AssignRefOut(expectedVarList, 0.0)
.IgnoreCall();
//Act
var resultVarList = myClass.MyMethod(0, 0);
//Assert
CollectionAssert.AreEqual(expectedVarList, resultVarList);
}
Related
I have groups of logic that consist of static classes such as:
static class A {
static int mutate(int i) { /**implementation*/ };
static double prop(double a, double b) { /**implementation*/ };
}
static class B {
static int mutate(int i) { /**implementation*/ };
static double prop(double a, double b) { /**implementation*/ };
}
In this case, A and B are static classes that implement the same behavior via a group of functions (e.g. mutate). I would like to use something like an interface for this pattern, however since static classes cannot implement interfaces I am not sure what to do. What is the best way to implement this type of behavior cleanly?
EDIT:
Here is an example of what I am currently doing. The classes have no state so normally I would make them static.
Interface IMutator {
int mutate(int i);
}
class A : IMutator {
int mutate(int i) { /**implementation*/ };
}
class B : IMutator {
int mutate(int i) { /**implementation*/ };
}
class C {
public List<IMutator> Mutators;
public C(List<IMutator> mutators) {
Mutators = mutators;
}
}
//Somewhere else...
//The new keyword for A and B is what really bothers me in this case.
var Cinstance = new C(new List<IMutator>() {new A(), new B() /**...*/});
The stateless class doesn't have to be static.
Moreover, static dependencies isn't a good choice, when you want to write unit tests, or when you want to extract some common interface (as in your case).
It's OK to have non-static classes, containing logic only. E.g., people build ASP .NET applications using stateless controllers.
So, just throw away static and extract an interface.
Apart from #Dennis answer (which I have +1'ed, and it's indeed the way to go), other approach that may work, is having a set of functions (Func<>) and/or actions (Action<>) and resolve them using reflection. The code would not be specially elegant nor performant, but it works.
I've made a quick example on dotnetfiddle
I am writing a testing framework for my system, which allows users to create mocked inputs to the system. The system manipulates that input, and updates some of its members for later post processing.
In order to allow users to mock the input, I need to be able to update a mocked input's members. Furthermore, the input may not be a mock, so I would prefer a solution oblivious to the type of element received.
Simply put, I have a function which receives an object and attempts to set one of its properties:
func(object a)
a.m = 5;
Which I want to test by mocking its input a, using the Moq library. Unfortunately, my test failed, since mocked objects' members need to be set using Mock.SetUpGet, instead of standard member assignment.
What would be a good way to test such a function, without changing it?
In order to be able to mock and test it, the property must be virtual, but if that's the case you can use the SetupSet method, rather than SetupGet:
public class A
{
public virtual int m { get; set; }
}
[TestFixture]
public class Tests
{
public static void SetProperty(A a)
{
a.m = 5;
}
[Test]
public void IsThePropertySet()
{
var x = new Mock<A>();
x.SetupSet<int>(a => a.m = 5).Verifiable();
SetProperty(x.Object);
x.Verify();
}
}
Your function should have getters and setters anyway.
And a good way of testing whether your functions work is to do a small-scale test. Initialize an object and send that in to your method, seeing whether it does what you want.
public class myClass
{
public int number;
public void setNumber(int nNum)
{
number = nNum;
}
public int getNumber()
{
return number;
}
}
class Program
{
static void myMethod(myClass obj, int nNumb)
{
//obj.setNumber(nNumb);
obj.number = nNumb;
}
static void Main(string[] args)
{
myClass myObj = new myClass();
myMethod(myObj, 3);
//Console.WriteLine(myObj.getNumber());
Console.WriteLine(myObj.number);
Console.ReadLine();
}
}
}
Output: 3
I have ScriptA with a lot of void functions:
void methodOne() {
some code
}
void methodTwo(int a, int b) {
}
I want to pass to static method of another script. Lets say it scriptB:
ScriptB.staticMethod(methodOne, some, other, primitive, parameters);
ScriptB.staticMethod(methodTwo(a, b), some, other, parameters);
The main Idea of my scripts is that ScriptB will get datas from server and call methods that got from ScriptA to make changes in my game depending on data.
I am not sure what you are trying to achieve here.
But to answer your question, you can pass methods as parameters using delegates. Here is an example:
public class ScriptA
{
public delegate void MethodOneDelegate(int a, int b);
public void MethodOne(int a, int b)
{
Console.WriteLine(a + b);
}
}
public static class ScriptB
{
public static void StaticMethod(ScriptA.MethodOneDelegate function, int a, int b)
{
function(a, b);
}
}
public static void Main()
{
ScriptA scriptA = new ScriptA();
ScriptB.StaticMethod(scriptA.MethodOne, 1, 2);
}
There is alternative solutions, you can take a look at System.Func and System.Action.
Do you need to start the methods when you put them as parameters? Or do you need the values from those methods?
Either way, you could do two things, either try this or just pass the name of the method as string and in your method check which name has been entered and start that method in your method.
I've been using TDD for some time but now I'm looking at mocking frameworks and I don't get some things. This question might sound stupid for someone experienced but I just don't get it. The library I use is Moq + xUnit.
Question
What's the point of testing Calculator class if I explicitly say that 2 + 2 will return 4 on this line mock.Setup(x => x.Add(2, 2)).Returns(4); and then assert it?
Of course result will be 4, I just "forced" it to return 4 in few lines above the test itself. And now even in my implementation if I do return a * b; instead of return a + b; the test will pass.
Here is another example of this same calculator tests. http://nsubstitute.github.io/
Example Code
namespace UnitTestProject1
{
using Xunit;
using Moq;
public class CalculatorTests
{
private readonly ICalculator _calculator;
public CalculatorTests()
{
var mock = new Mock<ICalculator>();
mock.Setup(x => x.Add(2, 2)).Returns(4);
mock.Setup(x => x.Subtract(5, 2)).Returns(3);
this._calculator = mock.Object;
}
[Fact]
public void Calculator_Should_Add()
{
var result = _calculator.Add(2, 2);
Assert.Equal(4, result);
}
[Fact]
public void Calculator_Should_Subtract()
{
var result = _calculator.Subtract(5, 2);
Assert.Equal(3, result);
}
}
public class Calculator : ICalculator
{
public int Add(int a, int b)
{
return a + b;
}
public int Subtract(int a, int b)
{
return a - b;
}
}
public interface ICalculator
{
int Add(int a, int b);
int Subtract(int a, int b);
}
}
The purpose is to be able to test classes depending on calculator without having the calculator is self. In your test you know that the calculator can't be the cause of failure, because is returning the correct answer.
By isolating the code under test you will be able to test real units of code. And also see exactly what is causing your test failure.
You should not unit test the mock.
Suppose you want to test an object OrderProcessor which uses IService and IStorage.
To "Unit Test" OrderProcessor you simulate the behavior of IService and IStorage so that you can verify that your target class works as expected without using a Web Service and a Database.
I.e.
class OrderProcessor{
private IService service, IStorage storage;
public OrderProcessor(IService service, IStorage storage){ // bla bla}
public ProcessOrder(Order o){
// do something
// use the service
var price = service.GetPrice(..);
// store the result
storage.StoreOrder(order);
}
}
// test. Define mocks
var mockStorage = new Mock<IStorage>();
var mockService = new Mock<IService>();
// Setup test behaviour
mockStorage.Setup(m => m.GetPrice("X10").Returns(11);
mockStorage.Setup(m => m.GetPrice("X11").Returns(99);
...
var target = new OrderProcessor(mockService.Object, mockStorage.Object);
// ...
target.ProcessOrder(o);
// Verify the storing was called
mockStorage.Verify(m => m.StoreOrder(o), Times.Once());
// Verify the service was called X times
mockService .Verify(m => m.GetPrice(x), Times.Exactly(order.Items.Count));
In this case, there's no point in mocking -- the example is too simple. You're not gaining anything by mocking ICalculator.
You mock when you have a complex implementation, and you're trying to test something that depends on an implementation of that interface. You're not doing that in this case, you're testing a mock implementation. Testing a mock implementation is pointless.
For example, let's say your calculator implementation actually made a call to a web service to perform the calculations, and you were trying to test something that consumed calculations from the service. Your goal isn't to test the calculator -- your goal is to test the thing that uses the calculator. Having your test depend on a web service being up and running is silly, and could lead to your test failing unexpectedly.
Mocks are used in place of dependencies.
For example:
public interface IAddModule
{
int Add(int lhs, int rhs);
}
public class Calculator
{
private readonly IAddModule _addModule;
public Calculator(IAddModule addModule)
{
_addModule = addModule;
}
public int Add(int lhs, int rhs)
{
return _addModule.Add(lhs, rhs);
}
}
The Calculator class depends on the IAddModule. Depending on how IAddModule is implemented it might have side effects like logging or unmanaged code. To isolate the dependency you use a Mock in place of the IAddModule to test the class.
public class CalculatorTests
{
private readonly Calculcator _calculator;
public CalculatorTests()
{
var mock = new Mock<IAddModule>();
mock.Setup(a => a.Add(2, 2)).Returns(4);
_calculator = new Calculator(mock.Object);
}
[Fact]
public void Given_2_And_2_Then_4_Is_Returned()
{
var result = _calculator.Add(2, 2);
Assert.Equal(4, result);
}
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C# 4: conflicting overloaded methods with optional parameters
I just have one small research and created next code.
namespace Test {
class Program
{
public interface ITestA
{
void MethodA(int a, int b);
}
public class TestAClass : ITestA
{
public void MethodA(int a, int b)
{
Console.WriteLine("MethodA with param");
}
public void MethodA(int a, int b, bool logic = true)
{
Console.WriteLine("MethodA logic with param");
}
}
public interface ITestB
{
void MethodA(int a, int b, bool logic = true);
}
public class TestBClass : ITestB
{
public void MethodA(int a, int b)
{
Console.WriteLine("MethodB with param");
}
public void MethodA(int a, int b, bool logic = true)
{
Console.WriteLine("MethodB logic with param");
}
}
static void Main(string[] args)
{
var testA = new TestAClass();
testA.MethodA(1, 1);
var testB = new TestBClass();
testB.MethodA(1, 1);
}
} }
I have a question why compiler always choose short method with 2 parameters. And of course all this work by the same way and without Interface.
Thanks
This boils down to how the compiler treats named and optional parameters.
Check out this article at MSDN for more information, especially the paragraph Overload Resolution.
If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.
This is why in your case the compiler chooses the method without any optional parameters.
Because compiler finds a method that correspond perfectly to calling method and use that.
Compiler searches for other suitable methods if first way fails...