Error when running test project

Asked

Viewed 1,942 times

5

I added a test project to my Solution to test the methods of my MVC application.

I created a base class, for the other classes with tests to inherit from it, which contains context creation (IdentityDbContext).

Just in the constructor base class I added a breakpoint and in the test project there is only one test class, with only one method, and that is inherited from the base class.

public abstract class BaseTest
{
    protected CustomContext Context;

    protected BaseTest()
    {
        Context = new CustomContext();  // um breakpoint é colocado aqui
    }
}

I put a breakpoint in the constructor of the base class at the very first line where the context database. But when running debug the test does not even run that line, as it does not stop at the breakpoint, and an error is already triggered.

Managed Debugging Assistant 'Disconnectedcontext' has Detected a problem in 'C: PROGRAM FILES (X86) MICROSOFT VISUAL STUDIO 14.0 COMMON7 IDE COMMONEX tensions MICROSOFT TESTWINDOW te.processhost.Managed.exe'.

Additional information: Failure to transition to the COM context 0xaff5d8 for this Runtimecallablewrapper with the following error: The called object has been disconnected from its clients. (Exception of HRESULT: 0x80010108 (RPC_E_DISCONECTED)). This is usually because the COM 0xaff5d8 context where this Runtimecallablewrapper was created is disconnected or is busy doing something else. Releasing the interfaces of the current COM context (COM context 0xaff468). This can cause corruption or data loss. To avoid this issue, make sure all COM contexts/apartments/threads stay alive and are available for context transition until the app fully shuts down the Runtimecallablewrappers that represent COM components residing in them.

In the window Unit Test Session the following message appears:

Unable to create instance of class Meuprojeto.SubPasta.Homecontrollertest. Error: System.Typeloadexception: Set method in type Meuoutroprojeto.Context.Customcontext of Assembly Meuoutroproject, Version=1.0.0.0, Culture=neutral, Publickeytoken=null does not have an implementation..

in Meuprojeto.SubPasta.Base.BaseTest.. ctor() in Meuprojeto.SubPasta.Homecontrollertest.. ctor()

Does anyone know what it’s about and how I could solve it?

My Test Class:
In that method no breakpoint is also triggered:

[TestClass]
public class HomeControllerTest : BaseTest
{
    [TestMethod]
    public void TentativaDeAcessoAoIndexComoAnonimo()
    {
        var usuario = Context.Users
            .SingleOrDefault(x => x.UserName == "Anonimo");

        if (usuario == null)
            throw new Exception(GetType().Name + ": Usuário inválido");

        Assert.AreEqual(usuario.Nome, "Anonimo", "Deu bug!");
    }
}

Context code:

public class CustomContext : IdentityDbContext<Usuario>, IContext
{
    public CustomContext() : base("DefaultConnection")
    {
        Configuration.ProxyCreationEnabled = false;
        Configuration.LazyLoadingEnabled = false;
    }

    public DbSet<Classe> Classes { get; set; }
    ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

        modelBuilder.Properties<string>().Configure(x => x.HasColumnType("varchar"));

        modelBuilder.Configurations.Add(new ClasseConfiguration());
        ...

        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<IdentityUser>().ToTable("Usuarios");
        modelBuilder.Entity<Usuario>().ToTable("Usuarios");
        modelBuilder.Entity<IdentityRole>().ToTable("Roles");
        modelBuilder.Entity<IdentityUserRole>().ToTable("UserRoles");
        modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaims");
        modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogins");

        // para não criar o campo IdentityUser_Id
        modelBuilder.Entity<IdentityUser>().HasMany(x => x.Roles)
            .WithRequired()
            .HasForeignKey(x => x.UserId);

        modelBuilder.Entity<IdentityUser>().HasMany(x => x.Claims)
            .WithRequired()
            .HasForeignKey(x => x.UserId);

        modelBuilder.Entity<IdentityUser>().HasMany(x => x.Logins)
            .WithRequired()
            .HasForeignKey(x => x.UserId);
    }

Interface IContext:

public interface IContext
{
    DbChangeTracker ChangeTracker { get; }
    DbContextConfiguration Configuration { get; }
    Database Database { get; }
    IDbSet<IdentityRole> Roles { get; set; }
    IDbSet<Usuario> Users { get; set; }
    void Dispose();
    DbEntityEntry Entry(object entity);
    DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
    bool Equals(object obj);
    int GetHashCode();
    Type GetType();
    IEnumerable<DbEntityValidationResult> GetValidationErrors();
    int SaveChanges();
    Task<int> SaveChangesAsync();
    Task<int> SaveChangesAsync(CancellationToken cancellationToken);
    DbSet Set(Type entityType);
    DbSet<TEntity> Set<TEntity>() where TEntity : class;
}
  • How bizarre. You can put the code of this test class in your question?

  • @Gypsy omorrisonmendez, added

  • There is something ghastly about your context. You can also put his code in the question?

  • Bizarro even.. I then, I’m floating.. Added. And thank you for trying to help!

  • So what has this interface IContext? Possibly the problem is that there is some element within it that has not been implemented in CustomContext.

  • They are methods copied from Dbcontext to facilitate the injection.. I will put it too. I will try without it.

  • He arrived at the creation of Contexto and succeeded in instilling.. but in the end he made the same mistake.. I read elsewhere that can be registered interface thing in other projects yes. It gave the same error when trying to run the test method, when entering it. And the error message is the same... Complicated for me!!!

Show 2 more comments

1 answer

3


The error message says:

Unable to create instance of class Meuprojeto.SubPasta.Homecontrollertest. Error: System.Typeloadexception: Set method in type Meuoutroprojeto.Context.Customcontext of Assembly Meuoutroproject, Version=1.0.0.0, Culture=neutral, Publickeytoken=null does not have an implementation.

And its interface IContext has the following:

public interface IContext
{
    ...
    DbSet<TEntity> Set<TEntity>() where TEntity : class;
}

The error says that this method is not implemented in your class. Hence the error.

There are several ways to solve it. I would take the class interface out of context first and test without it. Then make the class settings work again with the interface.

  • I removed the interface to test and even accepted to instantiate Context and entered the method of the test class, but gave the error when running the SingleOrDefault().

  • Well, then I guess it’s time for another question.

  • 1

    Embarrassing.. .. problem solved after one update-package that updated the EF. Patience.. Grateful!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.