简体   繁体   中英

Test: How to verify that a method is called?

Many Mock frameworks has a feature to verify if a method is called or not. However most frameworks requires that the code follows dependency injection pattern.

The code that I'm trying to test does NOT uses dependency injection pattern, therefore a mock of the object can not be injected.

Code ex.:

public class TestMeClass {
    public void TransformMe() { }
}

public abstract class SomeeClass {
    public SomeMethod() {
        CallMeMethod();
    }

    private void CallMeMethod() {
        TestMeClass testMeClass = new TestMeClass();
        testMeClass.TransformMe();
    }
}

How can I verify( unit test ) that TransformMe() is called?

Can it be done using reflections`? (Language is C#)

Jon Skeet I need you.

How can I verify(unit test) that TransformMe() is called?

No. Not without exposing something public that can be verified.

Really Bad example just to make a point.

public abstract class SomeeClass{
   public SomeMethod(){
    CallMeMethod();
   }

   public bool TransformMeCalled {get;private set;}

   private void CallMeMethod() {
      TestMeClass testMeClass = new TestMeClass();
      testMeClass.TransformMe();
      TransformMeCalled = true;
   }
}

Can it be done using reflections`? (Language is C#)

Again No. The dependency is being created internally in the dependent class and is unknown to external actors. An external access point needs to be available otherwise this is not testable. You answered the question when you said

The code that i'm trying to test does NOT uses dependency injection pattern, therefore a mock of the object can not be injected.

One option is to refactor the creation of the dependency which would allow for it to be overridden, but again it is something that has to be exposed to an external actor to be accessed

public abstract class SomeeClass{
    public SomeMethod(){
        CallMeMethod();
    }

    public abstract TestMeClass CreateTestMeClass();

    private void CallMeMethod() {
        TestMeClass testMeClass = CreateTestMeClass();
        testMeClass.TransformMe();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM