C
C#2mo ago
Saiyanslayer

Parameterized Unit Testing Class Types

I have the following test in xUnit:
[Fact]
public async Task QaTrackUrls_Should_Connect() {
var context = new QaTrackContext();
//var property = typeof(IModelBase).GetProperty("RequestUrl").GetValue(model).ToString();

var result = await context.GetAsync<ServiceEventModel>(ServiceEventsModel.RequestUrl);

Assert.True(result.IsSuccess);
}
[Fact]
public async Task QaTrackUrls_Should_Connect() {
var context = new QaTrackContext();
//var property = typeof(IModelBase).GetProperty("RequestUrl").GetValue(model).ToString();

var result = await context.GetAsync<ServiceEventModel>(ServiceEventsModel.RequestUrl);

Assert.True(result.IsSuccess);
}
I want to parameterize the test by giving classes (like ServiceEventsModel) instead of writing each one manually. so far, I've tried this:
[Theory]
[InlineData(typeof(ServiceEventsModel))]
public async Task QaTrackUrls_Should_Connect(Type model) {
var context = new QaTrackContext();
var property = typeof(IModelBase).GetProperty("RequestUrl").GetValue(model).ToString();

var result = await context.GetAsync<model>(property);

Assert.True(result.IsSuccess);
}
[Theory]
[InlineData(typeof(ServiceEventsModel))]
public async Task QaTrackUrls_Should_Connect(Type model) {
var context = new QaTrackContext();
var property = typeof(IModelBase).GetProperty("RequestUrl").GetValue(model).ToString();

var result = await context.GetAsync<model>(property);

Assert.True(result.IsSuccess);
}
but
context.GetAsync<model>
context.GetAsync<model>
gives an error
'model' is a variable but is used like a type
'model' is a variable but is used like a type
making it typeof(model) doesn't work and creates more errors.
2 Replies
Joschi
Joschi2mo ago
You cannot use a Type object as a type parameter. You need to use reflection, to create the correct method at runtime and invoke it. https://learn.microsoft.com/en-us/dotnet/api/system.reflection.methodinfo.makegenericmethod?view=net-8.0
MethodInfo.MakeGenericMethod(Type[]) Method (System.Reflection)
Substitutes the elements of an array of types for the type parameters of the current generic method definition, and returns a MethodInfo object representing the resulting constructed method.
Saiyanslayer
Saiyanslayer2mo ago
👍