I was trying to do some POC on Test Drven Development. In my project I am using Application State Variables, So I need to fake them as HttpContext is not available during TDD execution.
I have search and found some code to fake the Application variable. The code looks like this:
[TestMethod()]
public void StartReportService_ApplicationStateShouldContainMyIndex()
{
//No HttpApplicationBase in System.Web.Abstractions, must use Real Object
var application = new Mock<HttpApplication>();
//Real object does not have a property of type HttpApplicationStateBase so must use real one?
//var applicationStateBase = new Mock<HttpApplicationStateBase>();
//real one not creable so HACK get private constructor
var ctor = typeof(HttpApplicationState).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { }, new ParameterModifier[] { });
var applicationState = (HttpApplicationState)ctor.Invoke(new Object[] { });
//fails here, HttpApplication.Application not overridable
application.SetupProperty(x => x.Application, applicationState);
var plugin = HttpApplicationPlugin.HttpApplicationPluginInstance;
plugin.Application_Start(application.Object,null);
}
I am not able to find the HttpApplicationPlugin class. Could anyone please help?
Related
In my application, there is a method which accepts an Object, then performs some operations on it to return a C# long value. At runtime, the Object received from Active Directory is an IADSLargeInteger.
In writing a unit test for this code, I am unable to create such an object to pass into the method being tested.
How can I create such an object for my unit test?
Are there other ways to verify the logic of my method?
Method to be tested:
public static long ConvertLargeIntegerToLong(object largeInteger)
{
var type = largeInteger.GetType();
var highPart = (int)type.InvokeMember("HighPart", BindingFlags.GetProperty, null, largeInteger, null)!;
var lowPartInt = (int)type.InvokeMember("LowPart", BindingFlags.GetProperty | BindingFlags.Public, null, largeInteger, null)!;
uint lowPartUint;
unchecked
{
lowPartUint = (uint)lowPartInt;
}
return (long)highPart << 32 | (long)lowPartUint;
}
Sample Unit Test
public void ConvertLargeIntegerToLong_ComObjectLargeInt_Long()
{
var expectedValue = 94294967295;
var testValue = ??; // What to put here?
var result = ConvertLargeIntegerToLong(testValue);
Assert.AreEqual(expectedValue, result);
}
After asking the question, I continued hunting around and thought to add the activeds.dll as a COM reference to my test project.
After I did that, I had direct access to the IADSLargeInteger interface. And looking more closely at the Microsoft docs for the interface, saw an example creating such an object for VB.Net.
In the end, I did like this for my code (still maintaining the COM reference):
var testValue = new LargeInteger { HighPart = 1234, LowPart = 4567 };
LargeInteger is also in that DLL and is the concrete class implementing the interface -- as #Hans Passant mentioned in his comment.
I have a basic .NET application that I am being asked to write a unit test for, but unit tests have always confused me.
This application has two repositories (FoodRepository and DrinkRepository) that return data from a hardcoded list.
Here's the Program.cs:
public static void Main(string[] args)
{
var foodSvc = new FoodService();
var foodId = 12;
var grade = 98.2d;
foodSvc.UpdateFoodGrade(foodId, grade);
}
which calls:
public void UpdateFoodGrade(int foodId, double grade)
{
var foodRepo = new FoodRepository();
var food = foodRepo.GetFood(foodId);
food.Grade = grade;
if (!food.IsPassed)
{
var drinkRepository = new DrinkRepository();
var drink = drinkRepository.GetDrink(foodId);
if (grade >= drink.MinimumPassingGrade)
{
food.IsPassed = true;
}
else
{
food.IsPassed = false;
}
}
}
My question is, what unit test(s) typically would someone do here for this? And, can I get some examples?
Been googling and grinding on this, but the concept continues to escape me.
I've historically used full integration tests in test environments, and not really done unit tests.
If anyone needs more of the code to help with this please let me know. I'm super stuck.
Thanks
UPDATE:
I've gotten a lot further thanks to below, but I am still stuck on the rest of the test. Here's what my updated service looks like:
public class FoodService
{
private readonly FoodRepository _foodRepo;
private readonly DrinkRepository _drinkRepository;
public FoodService(FoodRepository foodRepo, DrinkRepository drinkRepository)
{
_foodRepo = foodRepo;
_drinkRepository = drinkRepository;
}
public void UpdateFoodGrade(int foodId, double grade)
{
var food = _foodRepo.GetFood(foodId);
food.Grade = grade;
if (!food.IsPassed)
{
var drink = _drinkRepository.GetDrink(foodId);
if (grade >= drink.MinimumPassingGrade)
{
food.IsPassed = true;
}
else
{
food.IsPassed = false;
}
}
}
}
Updated Main:
public class Program
{
public static void Main(string[] args)
{
var foodRepository = new FoodRepository();
var drinkRepository = new DrinkRepository();
var foodSvc = new FoodService(foodRepository, drinkRepository);
var foodId = 12;
var grade = 98.2d;
foodSvc.UpdateFoodGrade(foodId, grade);
}
}
Test So far (I have no idea what to do next)
[TestMethod]
public void UpdateFoodGrade_Test()
{
//Arrange
var foodId = 12;
var grade = 98.2d;
var expected = true;
var food = new Food() { FoodId = foodId };
var drink = new Drink() { DrinkId = foodId };
var foodRepositoryMock = new Mock<FoodRepository>();
foodRepositoryMock.Setup(m => m.GetFood(foodId)).Returns(food).Verifiable();
var drinkRepositoryMock = new Mock<DrinkRepository>();
drinkRepositoryMock.Setup(m => m.GetDrink(foodId)).Returns(drink).Verifiable();
var foodService = new FoodService(foodRepositoryMock.Object, drinkRepositoryMock.Object);
//Act
var actual = foodService.UpdateFoodGrade(foodId, grade);
//Assert
foodRepositoryMock.Verify();
drinkRepositoryMock.Verify();
Assert.AreEqual(expected, actual);
}
}
EDIT 2:
I went ahead and refactored in the interfaces, etc. Here's how it shook out:
[TestMethod]
public void UpdateLessonGrade_IsPassingGrade()
{
//Arrange
var lessonId = 12;
var lesson = new Lesson() { LessonId = lessonId };
var module = new Module() { ModuleId = lessonId };
var lessonRepositoryMock = new Mock<ILessonRepository>();
lessonRepositoryMock.Setup(x => x.GetLesson(lessonId)).Returns(lesson);
var moduleRepositoryMock = new Mock<IModuleRepository>();
moduleRepositoryMock.Setup(x => x.GetModule(lessonId)).Returns(module);
var lessonService = new LessonService(lessonRepositoryMock.Object, moduleRepositoryMock.Object);
//Act
lessonService.UpdateLessonGrade(12, 98.2d);
//Assert
Assert.IsTrue(lesson.IsPassed); // assuming it should pass in this condition
Assert.AreEqual(98.2d, lesson.Grade); // expected Lesson Grade should be what you expected the grade to be after you call UpdateLessonGrade
}
I'm on a mobile device right now, I can try to update the answer later this weekend, but this should get you started.
Refactor your method to use instance variables instead of direct instantiation in the method. Add them as parameters to your constructor. In the main method create your repository instances and pass them to the service constructor.
Now you can use something like Moq or the in memory provider for entity framework.
As for what to test, basically test every piece of branching logic. At a minimum, each piece of an if statement and the else conditions. You should also test what happens when your repository objects don't find what you're looking for (e.g. returns null). Offhand, I'm counting at least six tests.
Update: Bravo! Looking at your updated code in the question, everything is on the right track.
In your test method, you'll want to add:
var foodService = new FoodService(foodRepositoryMock.Object, drinkRepositoryMock.Object);
That will initialize your service with the mock objects.
Then you'll want to call your service with test parameters like:
foodService.UpdateFoodGrade(12, 98.2d);
The last part is check your food object using asserts like:
Assert.IsTrue(food.IsPassed) // assuming it should pass in this condition
Assert.Equals(98.2d, food.Grade); // expectedFoodGrade should be what you expected the grade to be after you call UpdateFoodGrade
It looks like you'll also need to flesh out the instance of your Drink object a little bit more. You need to specify a value for MinimumPassingGrade since it's used to drive the decision logic in your if statement, for example, if you want the food.IsPassed = true to trigger, you would instantiate the drink object like so:
var drink = new Drink() { DrinkId = foodId, MinimumPassingGrade = 50.0d };
You would create test methods for each of the other various test cases, failed the minimum, when it's equal to the score, if you can't find the food in the food repo, or the drink in the drink repo, etc.
One other note, you only need to worry about Verifiable mocks when you need to know that a method was/wasn't called. For these tests, I probably wouldn't verify that methods were called (creates tighter coupling between your test and the implementation vs. the behavior). You'd want to verify that the methods were called only if something in your service code truly depends on knowing that it was called. e.g. if you're using Entity Framework and you wanted to make sure you didn't forget to call SaveChanges().
Indeed, such code can't be "normally" unit-tested without preliminary refactoring. But you still have one (bit dirty) option: Shims mechanism of MS Fakes Library.
It allows you to substitute any method or property of any type (including static, non-public and system) with any arbitrary code. In your case you may create a ShimsContext in you test method, and give some fake behavior for FoodRepository.GetFood() and DrinkRepository.GetDrink() methods, for example, empty body doing nothing. So, when your test runs, your stub code gonna be executed instead of the actual code of repository classes. So you will test only Service code without executing code of repositories.
You may check this article for quick introduction to the library.
And please keep in mind that Shims is not a way of good unit-testing, It is just a tool to deal with such non-testable code in case when you absolutely need to unit-test it somehow without changing the code itself.
I'm attempting to create a unit test for the NewDrive method for a class that implements the NavigationCmdletProvider abstract class:
[TestMethod()]
[DeploymentItem("PsFoo.dll")]
public void NewDriveTest()
{
// arrange
FooProvider_Accessor target = new FooProvider_Accessor();
ProviderInfo providerInfo = ?;
PSDriveInfo drive = new PSDriveInfo("FOO", providerInfo, "FOO:\\", null, null);
PSDriveInfo actual;
// act
actual = target.NewDrive(drive);
// assert
Assert.IsInstanceOfType(actual,typeof(FooDriveInfo));
}
Unfortunately, I can't seem to find a way to create the ProviderInfo instance, as it's a protected property of the FooProvider.
What am I missing?
You could solve it using Reflection (untested):
// fetch the property "ProviderInfo" from the type "FooProvider".
PropertyInfo property =
typeof(FooProvider).GetProperty("ProviderInfo", BindingFlags.Instance | BindingFlags.NonPublic);
// fetch the property's value (of the object "target").
FooProvider providerInfo = (FooProvider)property.GetValue(target);
You may have to adapt the type information or property name, as I do not know how they are actually named inside your codebase.
I'm receiving event notifications from web services that trigger event handlers with data regarding what triggered the event. I'm trying to test that once an event handler is called that a, b and c are all called with the proper values. This isn't possible without relying on the web service
My solution is to create converters that convert the EventArgs that are returned to my via the services library (Exchange Web Services) to something my dumb objects can understand without relying on third part services. My issue is that the EventArgs class given to my by the EWS library has an internal constructor so there's no easy way to generate an instance of it with random property values without much work with reflection.
For example, I have a simply interface:
public interface IConverter<TFrom, TTo>
{
TTo Convert(TFrom from);
}
and a simple implementation:
public class NotificationEventArgsConverter : IConverter<NotificationEventArgs, NewNotification>
{
public NewNotification Convert(NotificationEventArgs from)
{
return new NewNotification
{
ItemIds = from.Events.Cast<ItemEvent>().Select(x => x.ItemId.ToString())
};
}
}
Question is how can I generate an instance of NotificationEventArgs with random values. Is there a library for this that I missed in my searches?
The entire goal of this is to emulate if I receive an instance of NotificationEventArgs with the following values then NewNotification should resemble x.
Edit
In the meantime I will simply use typeof(T).GetConstructor().
You might want to take a look at AutoFixture:
AutoFixture makes it easier for developers to do Test-Driven Development by automating non-relevant Test Fixture Setup, allowing the Test Developer to focus on the essentials of each test case.
After doing some decompilation of Microsoft.Exchange.WebServices and playing bit with reflection, you can do it for example like this:
var fixture = new Fixture();
// retrieve internal FolderEvent(EventType, DateTime) ctor
// using FolderEvent class as NotificationEvent is abstract
var notificationEventCtor = typeof(FolderEvent).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[] { typeof(EventType), typeof(DateTime) },
null
);
// generate 10 random events with some help of LINQ and AutoFixture
var trashData = Enumerable
.Range(1, 10)
.Select(i => new object[]
{
fixture.CreateAnonymous<EventType>(),
fixture.CreateAnonymous<DateTime>()
})
.Select(p => notificationEventCtor.Invoke(p))
.Cast<NotificationEvent>()
.ToList();
Code above will generate 10 FolderEvents in a list, ready to pass to NotificationEventArgs constructor (which is internal again, so same code applies):
var notificationEventArgsCtor = typeof(NotificationEventArgs).GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[]
{
typeof(StreamingSubscription),
typeof(IEnumerable<NotificationEvent>)
},
null
);
var instance = notificationEventArgsCtor
.Invoke(new object[] { null, trashData });
Take a look at the PrivateObject class (specifically these constructor overloads). It wraps all the reflection work for you and allows you to create objects with non-public constructors, as well as access non-public methods and properties of those objects. You can get the underlying objects via the Target property.
I can get an IronPython 2 class back to my C#. What is the new IronPython 2 way of calling a member on that class?
object ironPythonClass = scope.GetVariable("Hamish");
object[] args = new object[0];
object pythonObject = engine.Operations.Call(ironPythonClass, args);
var member = "Home";
// old way IronPython 1
// var methodResult = Ops.Invoke(this.pythonObject, SymbolTable.StringToId(member), args);
I thought all I'd have to do was
var methodResult = PythonOps.Invoke(codeContext, pythonObject, SymbolTable.StringToId(member), args);
but creating a dummy CodeContext doesn't seem to be right. I feel as though I should be able to derive one from my
code.Execute();
that runs the Python file creating the class, plus the scope that arises out of that execution.
Found a way to do it:
var ops = engine.Operations;
var x = ops.GetMember(pythonObject, member);
var h = ops.Call(x, new object[0]);
Looks like the Operations produces an OperationsObject which has useful members.
Looking at the DLR code (Microsoft.Scripting.Hosting) however I see that Call is deprecated:
[Obsolete("Use Invoke instead")]
public object Call(object obj, params object[] parameters) {
return _ops.Invoke(obj, parameters);
}
My version of scripting 0.9.20209, doesn't yet have the Invoke however.
After updating to the newer IronPython 2.6Beta and its scripting dlls I find I can write:
var h = ops.InvokeMember(pythonObject, member, new object[0]);