Do I need to check helper / install methods?

So, I have a helper method that looks something like this:

private D GetInstanceOfD(string param1, int param2)
{
    A a = new A();
    B a = new B();
    C c = new C(a,b, param1);

    return new D(c, param2);
}

This is just a convenient helper method for which I can call to capture the specific object that I need, and then remember which dependencies I need to connect in order to get the desired object.

My first question is: should such methods be checked? The only reason I can think that I want to test these types of methods is to make sure that the correct dependencies are used and configured correctly.

If the answer to the first question is yes, the second - how? I am currently using NUnit and RhinoMocks, and I am trying to figure out how this method should be reorganized for verification (well, and whether something like this needs to be verified!); dependency injection will obviously not work here, as this method does create dependencies!

Or this bad practice method is used, and I should do something like the following:

D d = new (new C(new A(), new B(), "string"), 1024);
+3
source share
5 answers

Firstly, this method is private, and as a rule, I would say that testing is probably not necessary for this method. Even if it was a helper method for real code, and not an assistant for your tests, you can simply test it indirectly through the open interface.

-, - , , , , , . factory . factory , , . , , factory D.

, , . :

public class ObjectFactory 
{
     public virtual A CreateA() { return new A(); }
     public virtual B CreateB() { return new B(); }
     public virtual C CreateC( string str ) { return new C( CreateA(), CreateB(), str );
     public virtual D CreateD( string str, int num )
     {
         return new D( CreateC( str ), num );
     }
}


public class Foo
{
    private ObjectFactory ObjectFactory { get; set; }

    public Foo() : this(null) { }
    public Foo( ObjectFactory factory )
    {
         this.ObjectFactory = factory ?? new ObjectFactory();
    }

    public void Bar()
    {
        D objD = this.ObjectFactory.CreateD( param1, param2 );
    }
}

[TestMethod]
public void TestBar()
{
     var factory = MockRepository.GenerateMock<ObjectFactory>();
     var d = MockRepository.GenerateMock<D>();
     factory.Expect( f => f.CreateD( "abc", 10 ) ).Return( d );

     var foo = new Foo( factory );

     foo.Bar();

     factory.VerifyAllExpectations();
     d.VerifyAllExpectations();
}
+1

, , . , .

, , . , ,

  • , null ?
  • , ?
  • GetInstanceOfD D , ?
  • D .
  • C, A B , ?
+3

, , , - .

. Teardown . - .

, , , .

+2

. , ; XP , .

, ; , . , , , .

, , - -, , , .

//--- don't write this, you'll probably regret it ;o)
D d = new (new C(new A(), new B(), "string"), 1024);
+1

private , , , private.

, factory builder, . , .

0

Source: https://habr.com/ru/post/1710635/


All Articles