Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

199
Visualizações
How to make any instance creation a fake (FakeItEasy)?

I have this block of code that I would like to test

class SearchEngine
{
    public void Search()
    {
        var module = new SearchModule();
        module.Search();
    }
}

I have simplified it but I cannot provide a searchmodule instance as a parameter of the function Search, nor as a constructor parameter of the class SearchEngine.

Is there a way to insure that the module object will be a fakeiteasy fake when I write my unit test?

I would like to be able to do some CallTo verifications to the module object, notably that module.Search() was called when we call Search()

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Is there a way to insure that the module object will be a fakeiteasy fake when I write my unit test?

No, it's not possible, at least not with the current shape of your code. FakeItEasy can't intercept instance creation using new.

If you want to fake something, it has to be provided somehow to the system under test. The SUT can't create it itself.

I cannot provide a searchmodule instance as a parameter of the function Search, nor as a constructor parameter of the class SearchEngine

Could you inject a factory instead? Something like this:

public interface ISearchModuleFactory
{
    SearchModule Create();
}


class SearchEngine
{
    private readonly ISearchModuleFactory _searchModuleFactory;

    public SearchEngine(ISearchModuleFactory searchModuleFactory)
    {
        _searchModuleFactory = searchModuleFactory;
    }

    public void Search()
    {
        var module = _searchModuleFactory.Create();
        module.Search();
    }
}

You could then test SearchEngine like this:

// Arrange
var factory = A.Fake<ISearchModuleFactory>();
var module = A.Fake<SearchModule>();
A.CallTo(() => factory.Create()).Returns(module);
var searchEngine = new SearchEngine(factory);

// Act
searchEngine.Search();

// Assert
A.CallTo(() => module.Search()).MustHaveHappened();
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda