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.
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'm trying to mock a class, called EnvironmentManager, which contains a property called WebService_UserName than this property uses in a function called CallMeAsync.
How can I mock this private property for write a unit test?
Generally if you pass in dependencies into your constructor, it's easier to test the object. Create a constructor to pass in value of your private variable.
public EnvironmentManager() //what you currently have?
{
_webService_UserName = new WebService_UserName();
}
public EnvironmentManager(object webService_UserName) //passing dependency in instead
{
_webService_UserName = webService_UserName;
}
I suspect in this example WebService_UserName is actually a string so mocking isn't required at all.
var underTest = new EnvironmentManager("WebService_UserName example");
var actual = underTest.CallMeAsync().Result;
Assert.Equal("expected result", actual)
If I'm wrong and you actually need to mock a dependency
var mockedDependency = new Mock<WebService_UserName>();
/*set up for mockedDependency */
var underTest = new EnvironmentManager(mockedDependency.Object);
var actual = underTest.CallMeAsync().Result;
Assert.Equal("expected result", actual)
msg to deletion queue, I'm just trying to help the user, not save the question
I need to attach this handler to a RadListView Column creation, by adding a DataSource to the control.
public void GenericColumnCreatingHandler<T>(object sender, ListViewColumnCreatingEventArgs e)
{
e.Column.Visible = BaseEntity<int>.MemberVisibility<T>
(e.Column.FieldName, TelerikPropertyVisibilityAttribute.VisibilityTypeEnum.BaseDetails);
e.Column.HeaderText = CaricaTestoLocale(e.Column.HeaderText, "Col_" + e.Column.HeaderText);
e.Column.BestFit();
e.Column.AutoSizeMode = ListViewBestFitColumnMode.AllCells;
}
My problem is that I need to perform the handler attach from this other generic method:
private void PopulateRecord(TipoTabellaBase tipo)
{
Type generic = typeof(CommonTableService<>);
Type[] typeArgs = { tipo.Tipo };
var constructed = generic.MakeGenericType(typeArgs);
var instance = Activator.CreateInstance(constructed);
if (instance == null)
return;
MethodInfo getEntities = constructed.GetMethod("GetEntitiesWithNoParameters");
//getEntities = getEntities.MakeGenericMethod(typeArgs);
var result = (IEnumerable<BaseEntity<int>>)getEntities.Invoke(instance, null);
lvRecords.ColumnCreating += base.GenericColumnCreatingHandler<BaseEntity<int>>;
lvRecords.DataSource = result;
BestFit(lvRecords);
generic = null;
typeArgs = null;
constructed = null;
getEntities = null;
instance = null;
}
The problematic row is this one:
lvRecords.ColumnCreating += base.GenericColumnCreatingHandler<BaseEntity<int>>
because BaseEntity is EF base type for all Entities, but this is not enought for the BaseEntity.MemberVisibility method; this method need to know the exact entity type to set the visible properties (and, of course, grid column) based on specific custom attribute on that.
Question is: how I can call base.GenericColumnCreatingHandler where T is TipoTabellaBase tipo.Tipo (type) without knowing type at design time?
Any help would be very appreciated!
Thanks is advance.
Daniel
Please note that this solution is untested.
You will have to instantiate the strongly-typed version of base.GenericColumnCreatingHandler<T> at runtime.
From your code, I figure you already know how to obtain a MethodInfo instance for a given method. You will need to get the MethodInfo for base.GenericColumnCreatingHandler<T> (let's call it genericMethodInfo).
Then, you can create a strongly-typed version of that method with MakeGenericMethod:
MethodInfo typedMethodInfo = genericMethodInfo.MakeGenericMethod(new[] {
typeof(BaseEntity<int>)
});
Once that is done, you need to invoke CreateDelegate to obtain something that you can assign to the ColumnCreating event, as described here or here:
lvRecords.ColumnCreating +=
(ListViewColumnCreatingEventHandler)typedMethodInfo.CreateDelegate(
typeof(ListViewColumnCreatingEventHandler), this);
EDIT: Replaced base with this in the last code sample. In case an inherited method is specifically required, this has to be taken care of while retrieving genericMethodInfo.
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?
I have a WCF service that accepts an object as a parameter that has a URI and Method Name.
What I am trying to do is have a method that will look # the URI, if it contains the words "localhost" it will use reflection and call a method, of the name that is passed in as a parameter, within the the same class, return a value and continue on.
public class Test
{
public GetStatResponse GetStat(GetStatRequest request)
{
GetStatResponse returnValue = new GetStatResponse();
if(Helpers.Contains(request.ServiceURI,"localhost", StringComparison.OrdinalIgnoreCase))
{
MethodInfo mi = this.GetType().GetMethod(request.ServiceMethod /*, BindingFlags.Public | BindingFlags.IgnoreCase*/);
returnValue = (GetStatResponse)mi.Invoke(this,null);
}
The above is the code segment pertaining to this question. I pull the MethodInfo no problem but I am running into issues on the mi.Invoke. The exception that I receive is "Exception has been thrown by the target of an invocation." With an Inner Exception "Object reference not set to an instance of an object". I have tried changing the code to (GetStatResponse)mi.Invoke(new Test(), null), with no luck. Test being the class.
I'm open to other suggestions as to how to resolve this, I just thought reflection might be the easiest.
The Method that I am calling with my testing is defined as
public GetStatResponse TestMethod()
{
GetStatResponse returnValue = new GetStatResponse();
Stat stat = new Stat();
Stat.Label = "This is my label";
Stat.ToolTip = "This is my tooltip";
Stat.Value = "this is my value";
returnValue.Stat = stat;
return returnValue;
}
Because you are not specifying BindingFlags in your GetMethod() call, you are only going to be returned methods matching the name containing request.ServiceMethod that are PUBLIC.
Check whether the method you are trying to invoke is public, otherwise MethodInfo will return null.
If it is not public, either make the method public or include the BindingFlags.NonPublic flag.
Also, you should always make sure that mi != null before calling mi.Invoke
Before calling the method you might want to make sure that the MethodInfo you are pulling through reflection is not null:
MethodInfo mi = this.GetType().GetMethod(
request.ServiceMethod,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase
);
// Make sure that the method exists before trying to call it
if (mi != null)
{
returnValue = (GetStatResponse)mi.Invoke(this, null);
}
After your update it seems that the exception is thrown inside the method you are calling:
GetStatResponse returnValue = new GetStatResponse();
// Don't forget to initialize returnValue.Stat before using it:
returnValue.Stat = new WhateverTheTypeIs();
returnValue.Stat.Label = "This is my label";