I'm new to this, so doubtlessly I'm doing something silly.
I am trying to create a mock object:
mockCurrencyConversion = mocks.NewMock<ICurrencyConversion>();
and getting this error:
The non-generic method 'NMock2.Mockery.NewMock(System.Type)' cannot be
used with type arguments
ICurrencyConversion:
public interface ICurrencyConversion
{
decimal convertCurrency(string fromCurrency, string toCurrency, decimal amount);
int addNumbers(int i, int j);
decimal getRate(CurrencyRateResponse rates, string fromCurrency);
CurrencyRateResponse getCurrencyRates();
HttpWebRequest GetWebRequest(string formattedUri);
}
My Test Code:
[TestFixture]
public class WhygoTest
{
private Mockery mocks;
private ICurrencyConversion mockCurrencyConversion;
[SetUp]
public void SetUp()
{
mocks = new Mockery();
mockCurrencyConversion = mocks.NewMock<ICurrencyConversion>();
}
[Test]
public void MyAddTest()
{
var cc = new CurrencyConversion();
Assert.AreEqual(cc.addNumbers(1, 2), 3);
}
}
Use the NewMock() method with the type as an argument:
mockCurrencyConversion =
(ICurrencyConversion) mocks.NewMock(typeof(ICurrencyConversion));
Related
I am working on nUnit. I need to Setup mock of a static method from same class that is under subject. I am wonder If I created mock correctly as I have defined two instances; sut of class under test and mock of same class method in objective to MockObject.Setup(..) that exist in the same class that I am trying to test. I need help to create mock of GetNumbers() method that is in ProcessCalculation class
error
main
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Testing Automation Proptype... ");
ProcessCalculation process = new ProcessCalculation();
process.Run();
Console.ReadLine();
}
}
Calculation
public class ProcessCalculation
{
public delegate List<int> GetNumbersPointer();
//GetNumbersPointer getNumbersPointer = new GetNumbersPointer(GetNumbers);
public GetNumbersPointer getNumbersPointer = GetNumbers;
public void Run()
{
var Nos = getNumbersPointer.Invoke();
int x = Nos[0];
int y = Nos[1];
var z = Add(x, y);
Console.WriteLine("sum "+ z);
}
public static int Add(int x, int y)
{
return x + y;
}
public static List<int> GetNumbers()
{
List<int> myNo = new List<int>();
myNo.Add(32);
myNo.Add(10);
return myNo;
}
}
Test Class
public class Tests
{
private readonly ProcessCalculation sut;
private readonly Mock<ProcessCalculation> processCalculationMoq;
public Tests()
{
sut = new ProcessCalculation();
processCalculationMoq = new Mock<ProcessCalculation>();
}
[SetUp]
public void Setup()
{
}
[Test]
public void Test1()
{
//Arrange
var fixture = new Fixture();
var getNumberMoq = fixture.CreateMany<int>(2);
processCalculationMoq.Setup(x => x.getNumbersPointer).Returns(getNumberMoq); // this throw error.. I want to mock using setup
//???????????? how use delegate to mock static GetNumbers() method
//Assert
}
}
Change your implementation to
public class ProcessCalculation
{
public delegate List<int> GetNumbersPointer();
// If InternalsVisibleTo(Unit Test assembly) is specified, this can be internal
// Also, "new DelegateType(Target)" is not needed, the compiler inserts
// that implicitly
public GetNumbersPointer getNumbersPointer = GetNumbers;
// ...
}
And then, in your test:
public class Tests
{
private readonly ProcessCalculation sut;
public Tests()
{
sut = new ProcessCalculation();
sut.getNumbersPointer = TestGetNumbers;
}
[Test]
public void Test1()
{
sut.Run();
}
public static List<int> TestGetNumbers()
{
// Return test data
return new List<int> { 0, 1, 2, 3...};
}
}
Lets say I have this interface
public interface ITest
{
int Property1 { get; set; }
void Method1();
string GetMethod1();
void MethodWithParam(string str);
}
How can I create a wrapper object around this?
And then capture the methods called or paramters and values accessed etc.
For example:
var myWrapper = GetWrapper<ITest>();
myWrapper.Property1 = 7;
How would I be able to using reflection or whatever to know the following:
Paramter name being called and value being set
var data = myWrapper.GetMethod1("Test");
Get method name of "GetMethod1" along with paramaters and then return a value based on that?
Hope makes sense
Ok so answer quite simple using Castle Core proxy generator:
https://github.com/castleproject/Core
public interface ITest
{
int Property1 { get; set; }
void Method1();
string GetMethod1();
void MethodWithParam(string str);
}
public static class Wrapper
{
private class MethodInterceptor : IInterceptor
{
Action<IInvocation> OnIntercept;
public MethodInterceptor(Action<IInvocation> OnIntercept)
{
this.OnIntercept = OnIntercept;
}
public void Intercept(IInvocation invocation)
{
OnIntercept?.Invoke(invocation);
}
}
private static void CallAPI(IInvocation invocation)
{
var methodName = invocation.Method.Name;
var valuespassed = invocation.Arguments;
var retType = invocation.Method.ReturnType.FullName;
//DO API THINGS NOW
}
public static T Get<T>()
{
ProxyGenerator generator = new ProxyGenerator();
var interceptor = new MethodInterceptor(CallAPI);
var c = generator.CreateInterfaceProxyWithoutTarget<ITest>(interceptor);
return (T)c;
}
}
public class Test123
{
public void Test()
{
var c = Wrapper.Get<ITest>();
c.Property1 = 7;
var propval = c.Property1;
}
}
Any action on c calls the intercept function where can get everything from method name being called to arguments passed.
I'm trying to do a simple test, mocking the sum method.
I have an interface:
public interface ISumSomething
{
int Sum(params int[] values);
}
A class that use this interface:
public class CallSum
{
public CallSum(ISumSomething sumSomething)
{
this.SumSomething = sumSomething;
}
private ISumSomething SumSomething { get; set; }
public int Execute(params int[] values)
{
return this.SumSomething.Sum(values);
}
}
And the test class:
[TestMethod]
public void Test_Sum_Method()
{
// Creates MOQ.
var instance = new Mock<ISumSomething>();
// Setup de MOQ.
instance.Setup(moq => moq.Sum(It.IsAny(1,2)).Returns(4));
// Instance the object.
var sum = new CallSum(instance.Object);
// Execute the operation.
var result = sum.Execute(2, 2);
// Check the result.
Assert.AreEqual(4, result);
}
The problem is, when I call the Execute method, it is returing 0, but in my MOQ, I'm setting 4. Why this happens?
In your Setup you say IsAny(1,2), those arguments don't match the arguments on Execute which are 2,2
You should instead be using:
instance.Setup(moq => moq.Sum(It.IsAny<int[]>()).Returns(4));
(See Setup Method With Params Array for more info)
I'm using moq with nunit and my test doesn't give me a fail or pass. It says it doesn't have a default constructor. I suspect I am not doing something correctly with injecting my interface into the constructor.
DonorManagementTests
[TestFixture]
public class DonorManagementTests
{
private readonly Mock<IValidation> _mockValidation;
private readonly DonorManagement _donorManagement;
public DonorManagementTests(IValidation validation)
{
_mockValidation = new Mock<IValidation>();
_donorManagement = new DonorManagement(_mockValidation.Object);
}
[Test, Description("View correct gift aid to two decimal places")]
public void DonorViewGiftAid()
{
const int donation = 20;
_mockValidation.Setup(x => x.ValidateDonation(donation)).Returns(20.00m);
var res = _donorManagement.GiftAidAmount(donation);
Assert.IsInstanceOf(typeof (decimal), res);
_mockValidation.Verify(x => x.ValidateDonation(donation), Times.Once);
}
}
DonorManagement
public class DonorManagement : IDonor
{
private readonly IValidation _validation;
public DonorManagement(IValidation validation)
{
_validation = validation;
}
public virtual decimal GiftAidAmount(decimal donationAmount)
{
const decimal gaRatio = 17.5m / (100 - 17.5m);
return _validation.ValidateDonation(donationAmount) * gaRatio;
}
}
Any ideas what I need to change in my code?
your test class must have a default C'tor.
change your test class to:
[TestFixture]
public class DonorManagementTests
{
private Mock<IValidation> _mockValidation;
private DonorManagement _donorManagement;
[SetUp]
public TestInit()
{
_mockValidation = new Mock<IValidation>();
_donorManagement = new DonorManagement(_mockValidation.Object);
}
[Test, Description("View correct gift aid to two decimal places")]
public void DonorViewGiftAid()
{
const int donation = 20;
_mockValidation.Setup(x => x.ValidateDonation(donation)).Returns(20.00m);
var res = _donorManagement.GiftAidAmount(donation);
Assert.IsInstanceOf(typeof (decimal), res);
_mockValidation.Verify(x => x.ValidateDonation(donation), Times.Once);
}
}
now each test will be isolated and you'll be able to execute your tests.
NUnit documentation (http://www.nunit.org/index.php?p=testFixture&r=2.5) says:
A non-parameterized fixture must have a default constructor.
A parameterized fixture must have a constructor that matches the parameters provided.
I have a static class with number of different methods.
I have another class, and with each instance of this class, I would like it to have a method which calls one of the methods in the static class. For each instance, I want be able to specify which of the methods it will use via the constructor of this class.
Is there a simple way to do this? Should I be using delegates/interfaces?
Do the methods all have the same signature? If so, a delegate would certainly be a good approach... although it wouldn't restrict the caller to passing in a method group from the static class. If that's not a problem, here's a sample:
using System;
public static class TestMethods
{
public static void Foo(int x)
{
Console.WriteLine("Foo " + x);
}
public static void Bar(int x)
{
Console.WriteLine("Bar " + x);
}
}
public class DummyClass
{
private readonly Action<int> action;
public DummyClass(Action<int> action)
{
this.action = action;
}
public void CallAction(int start, int end)
{
for (int i = start; i < end; i++)
{
action(i);
}
}
}
class Test
{
static void Main()
{
DummyClass d1 = new DummyClass(TestMethods.Foo);
DummyClass d2 = new DummyClass(TestMethods.Bar);
d1.CallAction(2, 4);
d2.CallAction(3, 7);
}
}
Here is what you are looking for:
public delegate void MyStaticMethodInvoker(params object[] values);
public class TestStatic
{
public static void TestMethod1(params object[] values)
{
Console.WriteLine("TestMethod1 invoked");
}
public static void TestMethod2(params object[] values)
{
Console.WriteLine("TestMethod2 invoked");
}
public static void TestMethod3(params object[] values)
{
Console.WriteLine("TestMethod3 invoked");
}
}
public class TestClass
{
private MyStaticMethodInvoker _targetMethod;
public TestClass(MyStaticMethodInvoker targetMethod)
{
_targetMethod = targetMethod;
}
public void CallTargetedStaticMethod()
{
_targetMethod.Invoke(1,2,3,4);
}
}
And then you can create instances of TestClass and in constructor define target static method:
TestClass tc1 = new TestClass(new MyStaticMethodInvoker(TestStatic.TestMethod1));
tc1.CallTargetedStaticMethod();
TestClass tc2 = new TestClass(new MyStaticMethodInvoker(TestStatic.TestMethod2));
tc2.CallTargetedStaticMethod();
TestClass tc3 = new TestClass(new MyStaticMethodInvoker(TestStatic.TestMethod3));
tc3.CallTargetedStaticMethod();