tofana
tofana

Reputation: 83

Why is this code not good for unit testing?

Apparently this code is not good for unit testing, I'm wondering why? What does it mean that a code is "good" for unit testing?

 public class B 
  {
        public int Y { get ; }
        public int X { get ; }
        public B() 
        {
          X = 3;
          Y = 7;
        }

        public B(int x) 
        {
          X = x;
          Y = 2 * x;
        }
  }

 public class A 
 {
        public B MyB { get ; set ; }
        public A() {MyB = new B ();}

        bool M1( int a, int b) 
        {
           if (a > MyB.X) return false;
           if (b < MyB.Y) return false;
           return true;
        }

        public B M2(int x) { return new B(x);}
}

Upvotes: 1

Views: 74

Answers (1)

Michał Szkudlarek
Michał Szkudlarek

Reputation: 1502

My first impression is a missing dependency injection on A()

 public A() {MyB = new B ();}

Basically you cannot mock/inject B to a constructor, which means you are left with real B object creation/behavior that you cannot influence.

Does not influence testability, but M2 method does not make sense. Whenever you use it, it can be replaced by simple 'new B(x)' (not even mentioning breaking the single-responsibility principle of class A)

Upvotes: 4

Related Questions