Is there a way to implement an interface in a class of a DLL that I can only read?

2

I'm using a DLL that has several classes. I would like to dynamically implement interfaces for these classes, so that I can perform unit tests by doing mock of them.

Is there any way to do this?

Example:

The DLL has a class Comunicador

public class Comunicador
{
    public void Executar()
    {
        //executa
    }
}

Is there any way I can get this class to dynamically implement the interface below?

public interface IComunicador
{
    void Executar();
}

This way, I want a property

public IComunicador Comunicador { get; set; }

Understand the following:

Comunicador = new Comunicador();
    
asked by anonymous 03.11.2017 / 13:29

2 answers

3

And if you created a class MeuComunicador just to implement the interface, would it solve your problem?

Example:

using System;

public class Program
{
    public static void Main()
    {
        MinhaClasse obj = new MinhaClasse();

        obj.ObjComunicador = new MeuComunicador();
        obj.ObjComunicador.Executar();
        Console.WriteLine("Fim");
    }
}


public class MinhaClasse
{
    public IComunicador ObjComunicador   {get;set;}
}


public class Comunicador //Essa classe você não pode mexer né ?!
{
    public void Executar()
    {
        //supondo que o metodo do comunicador original faça algo...
        Console.WriteLine("Executando método do comunicador ... ");
    }
}

public class MeuComunicador : Comunicador, IComunicador
{

}

public interface IComunicador
{
    void Executar();
}

Result:

  

Running Communicator Method ...

     

End

I tested on .NetFiddle: link

    
03.11.2017 / 13:48
4

Up to C # 7 or 8 (not yet set when you enter) is not possible. Even when you can there will be restrictions, not yet fully defined, of what you can do.

To test you have access to the method if you know that it is implemented, it is not ideal, but you can force the test.

Not only for the test, but for use in production it is possible to create a design pattern that helps to deal with this, although not ideal, but may be the only way. Probably a Adapter . In the case described by the question, you do not even have to implement anything, just have another object that has the interface and delegate it to what already exists.

Note that you can only access what is public on this adapter. You never have access to something private, except for reflection, which would be a huge gambiarra creating risks of maintenance.

I do not know if it's the best alternative to the question, but it's one of them. There are other standards that may help .

Probably the solution given by Rovann Linhalis is more appropriate.

I consider this gambiarra, but in legacy gambiarras code are necessary.

I found it curious to talk about TDD of something that already exists.

    
03.11.2017 / 13:48