Textcontext property in MStest giving null reference exeption - mstest

I am trying to create a Unit test project in Visual studio 2017 . I want to use Testcontext class prorperties like TestName and etc in my test class and Test method . But when i run the project in debug mode i get null object reference for Testcontext object .
Below is the code :
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject2
{
[TestClass]
public class UnitTest1
{
private TestContext _testcontext;
public TestContext Testcontext
{
get { return _testcontext; }
set { _testcontext = value; }
}
[TestMethod]
public void TestMethod2()
{
Console.WriteLine(Testcontext.TestName);
}
}
}
I am not able to find out how to fix this problem using Coded UI project it works fine.
the exception

You need to change the definition for TestContext property.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace UnitTestProject2
{
[TestClass]
public class UnitTest1
{
public TestContext TestContext { get; set; }
[TestMethod]
public void TestMethod2()
{
Console.WriteLine(Testcontext.TestName);
}
}
}

You haven't set value for the _testcontext in the code sample you have provided so you will get NullReferenceException.

Related

Autofac asp.net web api constructor injection works but property injection does not

I am beginner in autofac and I have to use it in new legacy project asp.net web api.
I am registering of interface and injection works fine with constructor injection.
However, the constructor is being called in numerous places directly new(), and I don't want to replace it everywhere.
So I thought about property injection, but cannot get it to work, the dependency is always null.
The app is split into multiple projects and multiple autofac modules. Autofac configuration as per docs: https://docs.autofac.org/en/latest/integration/webapi.html
I tried to make small demo app, and I was able to get property injection working using all methods from docs: https://autofac.readthedocs.io/en/latest/register/prop-method-injection.html
using Autofac;
public class Program
{
public static void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType<MyDependency>().As<IMyDependency>().SingleInstance();
builder.RegisterType<MyService>().OnActivated(e => e.Instance.MyDependency1 = e.Context.Resolve<IMyDependency>());
//builder.Register(c => new MyService { MyDependency1 = c.Resolve<IMyDependency>() });
//builder.RegisterType<MyService>().WithProperty("MyDependency1", new MyDependency()).SingleInstance();
var container = builder.Build();
container.Resolve<MyService>();
}
}
public class MyService
{
public IMyDependency MyDependency1 { get; set; }
}
public class MyDependency : IMyDependency
{
public void Hello()
{
Console.WriteLine("Hello from MyDependency1");
}
public MyDependency()
{
Hello();
}
}
public interface IMyDependency
{
public void Hello();
}
Unfortunately none of these works for my full project, the object is always null. I know it would be difficult to get help, but maybe someone can advice what to look for?
I just tried reproducing this using the WithProperty registration you have there and the test passes - I can't reproduce it, property injection is working.
If it's not working in your full project, something else is going on. Below is the totally working test I used to verify.
public class ExampleTests
{
[Fact]
public void PropertyInjection()
{
var builder = new ContainerBuilder();
builder.RegisterType<MyDependency>().As<IMyDependency>().SingleInstance();
builder.RegisterType<MyService>().WithProperty("MyDependency1", new MyDependency()).SingleInstance();
var container = builder.Build();
var svc = container.Resolve<MyService>();
Assert.NotNull(svc.MyDependency1);
}
}
public class MyService
{
public IMyDependency MyDependency1 { get; set; }
}
public class MyDependency : IMyDependency
{
public void Hello()
{
Console.WriteLine("Hello from MyDependency1");
}
public MyDependency()
{
Hello();
}
}
public interface IMyDependency
{
public void Hello();
}

Unable to resolve service for type with our own class

We are getting this exception when calling a web api controller:
InvalidOperationException: Unable to resolve service for type 'SDS.Lambda.Interfaces.ISecretManager' while attempting to activate 'SDS.Lambda.Controllers.SapController'.\r\n <p class="location">Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
StartUp.cs contains the following:
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ISecretManager, SecretManager>();
}
The controller has this constructor:
public class SapController : Controller
{
public SapController(ISecretManager secretManager)
{
_secretManager = secretManager;
}
}
We have the same issue with other types being injected into the constructor, but the IConfiguration instance can be injected, for example that parameter does not cause an exception:
public SapController(IConfiguration configuration, ISecretManager secretManager)
The ISecretManager interface looks like this (yes, it really does):
namespace SDS.Lambda.Interfaces
{
public interface ISecretManager
{
}
}
And the class (yes, really - I reduced it down to avoid complexity):
namespace SDS.Lambda.Interfaces
{
public class SecretManager : ISecretManager
{
}
}
Are we providing the interface/concrete type incorrectly?
Is there a way to retrieve the concrete type to test whether it has been provided properly?
When execution reaches the bottom of ConfigureServices, if we look at the services instance result enumeration, in the debugger view, the types we are injecting are listed, so we can't see why they are failing to be instantiated.
UPDATE
To elaborate and explain the issue with another class/dependency in the same solution:
Controller:
namespace SDS.Lambda.Controllers
{
[Route("api/[controller]")]
public class SapController : Controller
{
readonly IHelper helper;
public SapController(IHelper helpme)
{
helper = helpme;
}
...
}
Interface:
namespace SDS.Lambda.Interfaces
{
public interface IHelper
{
}
}
Class:
namespace SDS.Lambda.Helpers
{
public class Helper : IHelper
{
public Helper()
{
}
}
}
StartUp:
namespace SDS.Lambda
{
public class Startup
{
public static IConfiguration Configuration { get; private set; }
private readonly AppSettings _appSettings;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
_appSettings = configuration.GetSection("AppSettings").Get<AppSettings>();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddLogging(logger => logger.AddLambdaLogger());
services.AddSingleton<IHelper, Helper>();
services.AddControllers();
}
...
}

How do I Skip xUnit.net test based on certain bool condition in test class?

I have a need where i need to skip the test method based on certain bool condition in a class.
is it possible? how can it be achieved? i have tried extending the FactAttribute but i cannot get the instance of the Test class.
my code below:
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace XUnitTestProject1
{
public class MyTestClass
{
bool SomeCondition;
public MyTestClass()
{
SomeCondition = false;
}
[Fact] //I WANT TO SKIP THIS TEST AS SOMECONDITON == FALSE
void MyTestMethod()
{
}
}
}
You can do something like this:
public class MyTestClass
{
private const string SomeCondition = "false"
[Fact(Skip=SomeCondition)]
void MyTestMethod()
{
}
}

Xamarin Forms dependency service don't work with generics?

I'm trying to get an instance of generic class in Xamarin.Forms. If I use the code below everything works fine:
Interface
namespace PrismNinjectApp1.Application.Interfaces
{
public interface IUserService { }
}
Concrete class
[assembly: Dependency(typeof(PrismNinjectApp1.Application.DomainServices.UserService))]
namespace PrismNinjectApp1.Application.DomainServices
{
public class UserService : IUserService
{
public UserService() { }
}
}
View Model
namespace PrismNinjectApp1.ViewModels
{
public class MainPageViewModel : BindableBase, INavigationAware
{
private readonly IUserService _userService;
public MainPageViewModel()
{
_userService = DependencyService.Get<IUserService>();
}
//Implementation of INavigationAware interface (I'm using Prism)
}
}
But if I try do the same with generics I can't get the object instance:
Interface
namespace PrismNinjectApp1.test
{
public interface IMyInterface<T> where T : class { }
}
Concrete class
[assembly: Dependency(typeof(PrismNinjectApp1.test.MyInterface<>))]
namespace PrismNinjectApp1.test
{
public class MyInterface<T> : IMyInterface<T> where T : class { }
}
View Model
namespace PrismNinjectApp1.ViewModels
{
public class MainPageViewModel : BindableBase, INavigationAware
{
private readonly IMyInterface<Users> _myInterface;
public MainPageViewModel()
{
_myInterface = DependencyService.Get<IMyInterface<Users>>(); //Gets NULL value
}
//Implementation of INavigationAware interface (I'm using Prism)
}
}
Users class is a domain entity
public class Users
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(100)]
public string Name { get; set; }
}
Any idea how I can get this object instance?
I trying to do this because I want to use generics services and repositories with basic CRUD and search methods with this structure
App (project droid and ios)
Shared (portable project)
Application (for external services - portable projec)
Domain - (portable project)
Data - (portable project)
Xamarin Forms version: 2.3.4.247

SQL CE and StructureMap

I'm developing an ASP.NET MVC 3 application using Entity Framework CF, StructureMap and SQL CE.
Here's the code:
Repository
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(string connectionString) : base(connectionString)
{
}
public DbSet<Foo> Foo { get; set; }
}
public class FooRepository : IFooRepository
{
private readonly ApplicationDbContext db;
public FooRepository(ApplicationDbContext db)
{
this.db = db;
}
public List<Foo> GetAll()
{
return db.Foo.ToList();
}
}
StructureMap config
For<ApplicationDbContext>()
.HybridHttpOrThreadLocalScoped()
.Use<ApplicationDbContext>()
.Ctor<string>("connectionString")
.EqualToAppSetting("DbConnectionString");
For<IFooRepository>().Use<FooRepository>();
Everything works fine, but once application becomes inactive and I call IFooRepository.GetAll() after 10-15 minutes, I get the following exception:
System.Data.SqlServerCe.SqlCeException:
Internal error: Unable to successfully execute disk IO on the file system.
Any help would be greatly appreciated!

Resources