mardi 6 septembre 2016

How to mock a class with no interface and no virtual methods in C#?

I'm writing unit tests for someone else's code that I'm not allowed to modify.

Say I have:

class BadClass
{
    public BadClass()
    {
        // the service isn't going to be running during testing
        // it also has no interface
        someFlag = AGloballyStoredService.getSomeFlag();
    }

    public bool someFlag;

}

that is used by:

class AnotherBadClass
{
    public AnotherBadClass(BadClass badClass)
    {
        someFlag = badClass.someFlag;
    }
    public bool someFlag;
}

Say I want the test:

public void AnotherBadClassConstructorTest()
{
    BadClass badClass = new BadClass();
    AnotherBadClass anotherBadClass = new AnotherBadClass(badClass);
    Assert.IsNotNull(anotherBadClass);
}

I would like to mock BadClass, but it has no interface and it fails during its constructor if the service isn't running.

Considering that I can't modify the code that I'm testing, is there a straightforward way to make this work?

If it comes down to it, I can tell them that they have to either let me modify the existing code base or accept sub 10% coverage for this module.

Aucun commentaire:

Enregistrer un commentaire