nunit testing of method which calls other method - c#

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);
}

Related

C# Create mock of delegate static method for nUnit test

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...};
}
}

Cannot assign void to an implicitly-typed variable in unit test

everyone, I am trying to write a unit test for my Processor class. in my project, I take a JSON file and Deserialize it and then I build and process it then save it to my database
this is my process class
public class CustomerProcessors
{
private static IRepository _repository;
private static PracticeEntities4 _context;
private static Customer customer;
public CustomerProcessors()
{
}
public CustomerProcessors(IRepository repository)
{
_repository = repository;
}
public static void Process(Customer customer)
{
var oldcustomer = _repository.GetOldCustomerId(customer.Code.Value);
if (oldcustomer == null)
{
Save(customer);
}
else
update(customer);
}
private static void update(Customer customer)
{
_repository.UpdateCustomer(customer);
}
private static void Save(Customer customer)
{
_repository.SaveCustomer(customer);
}
}
this is my Builder
public Customer CustomerBuild(DtoCustomer dto)
{
return new Customer()
{
FirstName = dto.FirstName,
LastName = dto.LastName,
Address = dto.Address,
Email = dto.Email,
Code = int.Parse(dto.Code),
PhoneNumber = dto.Phone
};
}
and finally, this is my unit test
[TestClass]
public class CustomerProcessorTest
{
private static string path;
private static CustomerDeserializer _customerDeserializer;
private static CustomerBuilder _customerBuilder;
private List<Customer> _customers;
private static Mock<IRepository> mock;
private Customer customer;
[ClassInitialize]
public static void CLassInitialize(TestContext context)
{
path = Path.Combine(Environment.CurrentDirectory, #"JSON\", "Customer.json");
}
[TestInitialize]
public void TestInitialize()
{
mock = new Mock<IRepository>();
_customerDeserializer = new CustomerDeserializer();
_customerBuilder = new CustomerBuilder();
_customers = new List<Customer>();
Customer customer = new Customer();
}
[TestMethod]
public void CusomerDeserialize_customerProcess()
{
//Arange
mock.Setup(e => e.GetOldCustomerId(1001)).Returns(3);
mock.Setup(e => e.GetOldStoreId(200)).Returns(3);
//Act
var dtos = CustomerDeserializer.Deserialize(path);
var dto = dtos.FirstOrDefault(e => e.Code == "1001");
var Builder= new CustomerBuilder();
var customer = Builder.CustomerBuild(dto);
//Error here
var process= CustomerProcessors.Process(customer);
//Asset
Assert.AreEqual(0, _customers.Count);
}
}
}
I have this error and I don't know what to do?
Change this line if code
var process= CustomerProcessors.Process(customer);
To this:
CustomerProcessors.Process(customer);
This way the function will be executed. You are now trying to assign void (nothing) to something so the compiler complains.
Doing this change, means that you will not actually test anything other than that your code does not throw an exception.
If you change the line to
// I removed the static identifier
// I added a boolean indicating success
public bool Process(Customer customer)
Then there is a value to test and assert based on conditions and you can reintroduce the process var
Edit for null point exception
Your problem stems from your repository being null. To solve it, make the following changes
public void Process(Customer customer)
And in your tests
[TestMethod]
public void CusomerDeserialize_customerProcess()
{
//Arange
mock.Setup(e => e.GetOldCustomerId(1001)).Returns(3);
mock.Setup(e => e.GetOldStoreId(200)).Returns(3);
//Act
var dtos = CustomerDeserializer.Deserialize(path);
var dto = dtos.FirstOrDefault(e => e.Code == "1001");
var Builder= new CustomerBuilder();
var customer = Builder.CustomerBuild(dto);
// create an instance of the processor
var processor = new CustomerProcessors(mock.Object);
// execute the function
processor.Process(customer);
//Asset
Assert.AreEqual(0, _customers.Count);
}

Set Event-Handler by reflection with Type and Template argument

I would like to set an event handler only by reflection, I can get all the types but I can't achieve it.
public delegate void MyHandler<T>(IMyInterface<T> pParam);
public interface IMyInterface<T>
{
MyHandler<T> EventFired { get; set; }
}
void myFunction()
{
//admit vMyObject is IMyInterface<ClassA>
var vMyObject = vObj as IMyInterface<ClassA>;
//get the generic type => ClassA
var vTypeGeneric = vTypeReturn.GenericTypeArguments.FirstOrDefault();
//build the type handler for the event MyHandler<ClassA>
Type vAsyncOP = typeof(MyHandler<>).MakeGenericType(vTypeGeneric);
// here I don't know how to create the Event handler to set EventFired
// dynamically with the code inside
var vEventFired = vMyObject.GetType().GetProperty("EventFired");
vEventFired.SetMethod etc...
}
I found some code with the usage of Lambda/Expression but I don't understand how to use it in this case.
Full sample:
public delegate void MyHandler<T>(IMyInterface<T> pParam);
public interface IMyInterface<T>
{
MyHandler<T> EventFired { get; set; }
}
public class MyClass : IMyInterface<int>
{
public MyHandler<int> EventFired { get; set;}
}
public void ConcreteHandler(IMyInterface<int> p)
{
Console.WriteLine("I'm here");
}
void Main()
{
var myValue = new MyClass();
var deleg = Delegate.CreateDelegate(typeof(MyHandler<int>), this, "ConcreteHandler");
myValue.GetType().GetProperty("EventFired").SetValue(myValue, deleg);
// Test delegate invocation:
myValue.EventFired.Invoke(new MyClass());
}
Since the question asks about setting an event and the code refers to delegate, here is the code for setting an event using reflection (via extension method):
public delegate void MyHandler<T>(IMyInterface<T> pParam);
public interface IMyInterface<T>
{
event MyHandler<T> EventFired;
}
public class ClassA : IMyInterface<int>
{
public event MyHandler<int> EventFired;
private int _Count = 0;
public void Fire()
{
var handler = EventFired;
if (handler != null) handler(this);
}
public override string ToString()
{
return "Call: " + (++_Count).ToString();
}
}
public static class Extension
{
public static void Add<T>(this IMyInterface<T> i, System.Reflection.MethodInfo method, object method_instance = null)
{
if (method.IsGenericMethodDefinition) method = method.MakeGenericMethod(typeof(T));
Delegate d = Delegate.CreateDelegate(typeof(MyHandler<>).MakeGenericType(typeof(T)), method_instance, method);
i.GetType().GetEvent("EventFired").GetAddMethod().Invoke(i, new object[] { d });
}
}
public class Program
{
public static void Print<T>(IMyInterface<T> val)
{
string output = val.ToString();
Console.WriteLine(output);
System.Diagnostics.Debug.WriteLine(output);
}
static void Main(string[] args)
{
ClassA ca = new ClassA();
ca.EventFired += Print<int>;
ca.Add(typeof(Program).GetMethod("Print", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public));
ca.Fire();
}
}
Sorry for the title, I meant not an event but a delegate property.
I found the solution meanwhile :
public void MyDelegate<T>(IMyInterface<T> pParam)
{
}
void myFunction()
{
//admit vMyObject is IMyInterface<ClassA>
var vMyObject = vObj as IMyInterface<ClassA>;
//get the generic type => ClassA
var vTypeGeneric = vTypeReturn.GenericTypeArguments.FirstOrDefault();
//build the type handler for the event MyHandler<ClassA>
Type vAsyncOP = typeof(MyHandler<>).MakeGenericType(vTypeGeneric);
// SOLUTION here :
// Create MyDelegate<vTypeGeneric>
// Then instanciate it with CreateDelegate and typeof(IMyInterface<vTypeGeneric>)
var vMyDelegate= this.GetType().GetMethod("MyDelegate");
var vMyDelegateGeneric = vMyDelegate.MakeGenericMethod(vTypeGeneric);
Type vTypeHandlerGeneric = typeof(IMyInterface<>).MakeGenericType(vTypeGeneric);
// this => bind to method in the class
var vMethodDelegate = vMyDelegateGeneric.CreateDelegate(vTypeHandlerGeneric, this);
// Set delegate Property
var vEventFired = vMyObject.GetType().GetProperty("EventFired");
vEventFired.SetValue(value, vDelegate);
}

unit testing a class with event and delegate

I am new to testing please help.
I have the following class
public delegate void OnInvalidEntryMethod(ITnEntry entry, string message);
public class EntryValidator
{
public event OnInvalidEntryMethod OnInvalidEntry;
public bool IsValidEntry(ITnEntry entry, string ticker)
{
if (!IsFieldValid(entry, ticker.Trim().Length.ToString(), "0"))
return false;
return true;
}
private bool IsFieldValid(ITnEntry entry, string actual, string invalidValue)
{
if (actual == invalidValue)
{
RaiseInvalidEntryEvent(entry);
return false;
}
return true;
}
private void RaiseInvalidEntryEvent(ITnEntry entry)
{
if (OnInvalidEntry != null)
OnInvalidEntry(entry, "Invalid entry in list: " + entry.List.Name + ".");
}
}
I have written the test case so far but am struggling with the event and delegate as shown below
[TestFixture]
public class EntryValidatorTests
{
private EntryValidator _entryValidator;
private FakeTnEntry _selectedEntry;
private string _ticker;
[SetUp]
public void Setup()
{
_entryValidator = new EntryValidator();
_ticker = "BOL";
}
private FakeTnEntry MakeEntry(string ticker)
{
return new FakeTnEntry { Ticker = ticker};
}
[Test]
public void IsValidEntry_WithValidValues()
{
_selectedEntry = MakeEntry(_ticker);
Assert.IsTrue(_entryValidator.IsValidEntry(_selectedEntry, _selectedEntry.Ticker));
}
[Test]
public void IsValidEntry_WithInValidTicker()
{
_selectedEntry = MakeEntry("");
Assert.IsFalse(_entryValidator.IsValidEntry(_selectedEntry, _selectedEntry.Ticker));
}
}}
Please can someone help? Thanks..
It's probably simplest just to subscribe to the event using an anonymous method:
[Test]
public void IsValidEntry_WithValidValues()
{
_selectedEntry = MakeEntry(_ticker);
_entryValidator.OnInvalidEntry += delegate {
Assert.Fail("Shouldn't be called");
};
Assert.IsTrue(_entryValidator.IsValidEntry(_selectedEntry, _selectedEntry.Ticker));
}
[Test]
public void IsValidEntry_WithInValidTicker()
{
bool eventRaised = false;
_selectedEntry = MakeEntry("");
_entryValidator.OnInvalidEntry += delegate { eventRaised = true; };
Assert.IsFalse(_entryValidator.IsValidEntry(_selectedEntry, _selectedEntry.Ticker));
Assert.IsTrue(eventRaised);
}
In the second test you might want to validate that the event arguments were as expected too.
Also note that "invalid" is one word - so your test should be IsValidEntry_WithInvalidTicker. I'd also not bother with the setup - I'd just declare new local variables in each test.
I would restructure your class to make the RaiseInvalidEntryEvent virtual so it can be mocked in your IsValidEntry_WithInValidTicker and then verified it was called when the ticket was invalid.
Then I would have another test that verified RaiseInvalidEntryEvent called the anon delegate separately.
Unit tests should be as atomic as possible, and you would want to verify both of these behaviors in different tests.
public delegate void OnInvalidEntryMethod(ITnEntry entry, string message);
public class EntryValidator
{
public event OnInvalidEntryMethod OnInvalidEntry;
public bool IsValidEntry(ITnEntry entry, string ticker)
{
if (!IsFieldValid(entry, ticker.Trim().Length.ToString(), "0"))
return false;
return true;
}
private bool IsFieldValid(ITnEntry entry, string actual, string invalidValue)
{
if (actual == invalidValue)
{
RaiseInvalidEntryEvent(entry);
return false;
}
return true;
}
public virtual void RaiseInvalidEntryEvent(ITnEntry entry)
{
if (OnInvalidEntry != null)
OnInvalidEntry(entry, "Invalid entry in list: " + entry.List.Name + ".");
}
}
// Had to reverse engineer the following since they were not available in the question
public interface ITnEntry
{
Ticket List { get; set; }
string Ticker { get; set; }
}
public class TnEntry : ITnEntry
{
public Ticket List { get; set; }
public string Ticker { get; set; }
}
public class Ticket
{
public string Name { get; set; }
}
NOTE: Some OOP evangalists have fits when things are declared public instead of private, basically unit testing and TDD have some requirements that pure OOP is at odds with. I've made RaiseInvalidEntryEvent public for simplicity, but normally I would make this internal and then expose the assembly to the unit test via InternalsVisibleTo. I've been doing TDD for the last 4 years now and rarely use private anymore.
And the unit tests would quickly be (note, this is using the MSTEST framework from VS2012)
[TestClass]
public class UnitTest1
{
#region TestHelpers
private ITnEntry MakeEntry(string ticker)
{
return new TnEntry {Ticker = ticker, List = new Ticket()};
}
#endregion
[TestMethod]
public void IsValidEntry_WithValidValues_ReturnsTrue()
{
// ARRANGE
var target = new EntryValidator();
var selectedEntry = MakeEntry("BOL");
// ACT
bool actual = target.IsValidEntry(selectedEntry, selectedEntry.Ticker);
// ASSERT
Assert.IsTrue(actual);
}
[TestMethod]
public void IsValidEntry_WithInValidTicker_ReturnsFalse()
{
// ARRANGE
var target = new EntryValidator();
var selectedEntry = MakeEntry("");
// ACT
bool actual = target.IsValidEntry(selectedEntry, selectedEntry.Ticker);
// ASSERT
Assert.IsFalse(actual);
}
[TestMethod]
public void IsValidEntry_WithInvalidTicker_RaisesEvent()
{
// ARRANGE
// generate a dynamic mock which will stub all virtual methods
var target = Rhino.Mocks.MockRepository.GenerateMock<EntryValidator>();
var selectedEntry = MakeEntry("");
// ACT
bool actual = target.IsValidEntry(selectedEntry, selectedEntry.Ticker);
// ASSERT
// assert that RaiseInvalidEntryEvent was called
target.AssertWasCalled(x => x.RaiseInvalidEntryEvent(Arg<ITnEntry>.Is.Anything));
}
[TestMethod]
public void RaiseInvalidEntryEvent_WithValidHandler_CallsDelegate()
{
// ARRANGE
var target = new EntryValidator();
var selectedEntry = MakeEntry("");
bool delegateCalled = false;
// attach a handler to set delegateCalled to true
target.OnInvalidEntry += delegate
{
delegateCalled = true;
};
// ACT
target.IsValidEntry(selectedEntry, selectedEntry.Ticker);
// ASSERT
Assert.IsTrue(delegateCalled);
}
}
Your test should subscribe to the event OnInvalidEntry with a dummy method, call IsValidEntry and check the result.

How can I mock this asynchronous method?

I have a class that roughly looks like this:
public class ViewModel
{
public ViewModel(IWebService service)
{
this.WebService = service;
}
private IWebService WebService{get;set;}
private IEnumerable<SomeData> MyData{get;set;}
private void GetReferenceData()
{
this.WebService.BeginGetStaticReferenceData(GetReferenceDataOnComplete, null);
}
private void GetReferenceDataOnComplete(IAsyncResult result)
{
this.MyData = this.WebService.EndGetStaticReferenceData(result);
}
.
.
.
}
I want to mock my IWebService interface so that when BeginGetStaticReferenceData is called it is able to call the callback method. I'm using Moq and I can't work out how to do this. My unit test set up code looks something like:
//Arrange
var service = new Mock<IWebService>();
service.Setup(x => x.BeginGetStaticReferenceData(/*.......don't know.....*/));
service.Setup(x => x.EndGetStaticReferenceData(It.IsAny<IAsyncResult>())).Returns(new List<SomeData>{new SomeData{Name="blah"}});
var viewModel = new ViewModel(service.Object);
.
.
Here's how:
[TestMethod]
public void Test10()
{
var expectedData = new[]{new SomeData(), new SomeData()};
AsyncCallback callback = null;
IAsyncResult ar = new Mock<IAsyncResult>().Object;
var webServiceStub = new Mock<IWebService>();
webServiceStub
.Setup(ws => ws.BeginGetStaticReferenceData(It.IsAny<AsyncCallback>(), null))
.Callback((AsyncCallback cb, object state) => callback = cb)
.Returns(ar);
webServiceStub
.Setup(ws => ws.EndGetStaticReferenceData(It.IsAny<IAsyncResult>()))
.Returns(expectedData);
var sut = new ViewModel(webServiceStub.Object);
sut.DoIt();
callback(ar);
Assert.AreEqual(expectedData, sut.MyData);
}
This test assumes a slightly modified ViewModel where I added a few public members to have something against which to test:
public class ViewModel
{
public ViewModel(IWebService service)
{
this.WebService = service;
}
public IEnumerable<SomeData> MyData { get; set; }
public void DoIt()
{
this.GetReferenceData();
}
private IWebService WebService { get; set; }
private void GetReferenceData()
{
this.WebService.BeginGetStaticReferenceData(GetReferenceDataOnComplete, null);
}
private void GetReferenceDataOnComplete(IAsyncResult result)
{
this.MyData = this.WebService.EndGetStaticReferenceData(result);
}
}
This article contains a very good explanation on how to test async methods using Rhino Mocks - I'm sure it can be easily adapted to use Moq instead.

Categories