Tell me more ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

How do You test it?

-all invocations in one method

-many methods that assert only part of check like testSomething, testSomethingTwoInvocations ...

share|improve this question
I hope you've heard of for-loops. – Spoike Oct 21 '11 at 10:17
@Spoike I heard about it, but I was always scared of using it. plus do you really need a loop for 2-3 method invocations? looks like overkill. – IAdapter Oct 21 '11 at 10:51

2 Answers

up vote 1 down vote accepted

Each unit test should test one unit and one unit only. Say a test has three assertions based on three different things. If the first one fails, the next two will not be tested. Once the first one is fixed, the second may fail thus the third is not tested. If one had three separate tests, then a failure of one would not impact the running of the others.

Edit: You get a little more typing (copy and paste) and the tests look bigger but that's about it. So, you do get a little more bloat. Do you care?

share|improve this answer

I usually do this encapsulated in a method where I give a count as parameter. Here is a simple example of a "fictional" ProductFactory class:

ProductFactory productFactory;

List<String> mockedProducts;

@Before
public void setup() {
    productFactory = new ProductFactory();
    mockedProducts = new ArrayList<String>();
}

public void whenUsingProducts(int amountOfProducts) {

    for(int i=0; i<amountOfProducts; i++) {
       String articleNumber = "12345" + i;
       productFactory.addProduct(articleNumber);
       mockedProducts.add(articleNumber);
    }

}

@Test
public void testWhenUsingOne_ShouldBeOkay() {
    // Arrange
    whenUsingProducts(1);

    // ACT
    // No-op

    // Assert
    assertTrue(productFactory.isQueueOkay());
}

@Test
public void testWhenUsingTwo_ShouldNotBeOkay() {
    // Arrange
    whenUsingProducts(2);

    // ACT
    // No-op

    // Assert
    assertFalse(productFactory.isQueueOkay());
}

@Test
public void testWhenUsingTwoAndWork_ShouldBeOkay() {
    // Arrange
    whenUsingProducts(2);

    // ACT
    productFactory.work();

    // Assert
    assertTrue(productFactory.isQueueOkay());
}

Refactoring the arrange code so that it is easy to invoke repetition is one way of removing duplicate test code. This way you can redo the invocation when you need to add more tests. Remember that you should refactor your test code as much as you do with production code.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.