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...};
}
}
Related
I have delegate which pointing to method with no parameter and it return list of object data List.
I am using nUnit, fixture and mock for the testing. I have created list of records that I like my static method to mock with via delegate but I am getting error
appTenantListHandlerMoq.Setup(_ => _).Returns(tenantsMoq);
MyClass
public class MyClass
{
public delegate Task<IEnumerable<AppTenant>> AppTenantListHandler();
AppTenantListHandler appTenantListHandler;
public MyClass ()
{
appTenantListHandler = new AppTenantListHandler(GetTenant);
}
public async Task Run(){
var tenantList = await appTenantListHandler();
}
public static async Task<IEnumerable<AppTenant>> GetTenant()
{
List<AppTenant> dataList = new List<AppTenant>();
return dataList;
}
}
Test Class
[TestFixture]
public class MyClassTests
{
private readonly MyClass sut;
private Mock<MyClass> MyClassMoq;
private readonly Mock<ILogger> loggerMoq;
private readonly Mock<ITelemetryInitializer> telemetryInitializerMoq;
public MyClassTests()
{
this.loggerMoq = new Mock<ILogger>();
this.telemetryInitializerMoq = new Mock<ITelemetryInitializer>();
this.MyClassMoq = new Mock<MyClass>();
this.sut = new MyClass(loggerMoq.Object);
}
[SetUp]
public void Setup()
{
}
[Test]
public void Test1()
{
//Arrange
var fixture = new Fixture();
var tenantsMoq = fixture.CreateMany<AppTenant>(5);
var appTenantListHandlerMoq = new Mock<MyClass.AppTenantListHandler>();
appTenantListHandlerMoq.Setup(_ => _).Returns(tenantsMoq);
//Act
var actualResult = sut.RunAsync(this.telemetryInitializerMoq.Object);
//Assert
Assert.NotNull(actualResult);
}
}
Error2
To mock a delegate, the syntax is :
appTenantListHandlerMoq.Setup(_ => _()).Returns(Task.FromResult(tenantsMoq));
But in your case, this will do noting, but the instance sut don't call the mocked delegate. You need to modify MyClass to inject the mocked delegate like :
public class MyClass
{
public delegate Task<IEnumerable<AppTenant>> AppTenantListHandler();
AppTenantListHandler appTenantListHandler;
public MyClass ()
: this(new AppTenantListHandler(GetTenant))
{ }
public MyClass (AppTenantListHandler appTenantListHandler )
{
this.appTenantListHandler = appTenantListHandler ;
}
...
}
Then in the test :
[Test]
public void Test1()
{
//Arrange
var fixture = new Fixture();
var tenantsMoq = fixture.CreateMany<AppTenant>(5);
var appTenantListHandlerMoq = new Mock<MyClass.AppTenantListHandler>();
appTenantListHandlerMoq.Setup(_ => _()).Returns(Task.FromResult(tenantsMoq));
MyClass sut = new MyClass(appTenantListHandlerMoq);
//Act
var actualResult = sut.RunAsync(this.telemetryInitializerMoq.Object);
//Assert
Assert.NotNull(actualResult);
}
I have a service class as below:
public class MyService
{
private readonly IMyDependency _myDependency;
public MyService(IMyDependency myDependency)
{
_myDependency = myDependency;
}
public void MyHandler(string param)
{
// work
}
public void AnotherMethod()
{
_myDependency.DoWork(MyHandler);
}
}
How can I Unit Test that MyHandler has been given as a parameter of DoWork()?
Since you are using Moq, you can write test like this:
[TestMethod]
public void DoWorkWasCalledWithCorrectParameters()
{
var mock = new Moq.Mock<IMyDependency>();
var myService = new MyService(mock.Object);
myService.AnotherMethod();
// verify that method was called once and with correct parameter:
mock.Verify(x => x.DoWork(myService.MyHandler), Moq.Times.Once);
}
Am very new to nunit.below is the business unit code
public enum HighlightType
{
IP,
Item,
Address
}
public class UniformGridHighlighting
{
public static event HighlightingChangedDelegate HighlightingChanged;
private static List<string> _highlightedIPs = new List<string>();
private static List<long> _highlightedItems = new List<long>();
private static ContactInfoType _highlightedAddress;
public static void ClearIPHighlighting()
{
_highlightedIPs.Clear();
OnHighlightingChanged(HighlightType.IP);
}
private static void OnHighlightingChanged(HighlightType type)
{
if (HighlightingChanged != null)
{
HighlightingChanged(type);
}
}
}
I need to write unit test cases for ClearIPHighlighting. How do i proceed.
[Test(Description = "to ")]
public void ClearIPHighlightingTets()
{
UniformGridHighlighting.ClearIPHighlighting();
//How to call method
}
Given the current setup you can only test that the event is triggered.
[Test()]
public void ThatTheEventIsTriggeredWhenTheListIsCleared()
{
// Arrange
bool eventTriggered = false;
UniformGridHighlighting.HighlightingChanged += _ => { eventTriggered= true; };
//Act
UniformGridHighlighting.ClearIPHighlighting();
//Assert:
Assert.IsTrue(eventTriggered);
}
And that it's of the right type
[Test(Description = "to ")]
public void ThatTheEventIsTriggeredWithTheIPArgumentWhenTheIPListIsCleared()
{
// Arrange
HighlightType? type = null;
UniformGridHighlighting.HighlightingChanged += x => { type = x; };
//Act
UniformGridHighlighting.ClearIPHighlighting();
//Assert:
Assert.AreEqual(s, HighlightType.IP);
}
To test that your previous highlight was removed is going to be harder:
[Test]
public void ThatTheIpIsNotHighlightedIfTheListWasCleared()
{
UniformGridHighlighting.HighlightIP("1.1.1.1");
//Act
UniformGridHighlighting.ClearIPHighlighting();
UniformGridHighlighting.Highlihst(Grid);
//Assert:
//Go through the grid to figure out that the IP was not highlighted. The below is a total guess:
bool wasHighlighted = Grid.Rows.Any(row => row.Cells.Any(Cell.Highlighted));
Assert.Isfalse(wasHighlighted);
}
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));
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();