Checking the results of a Factory in a unit test

前端 未结 5 1227
-上瘾入骨i
-上瘾入骨i 2020-12-15 05:35

I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the inte

5条回答
  •  忘掉有多难
    2020-12-15 05:59

    If your Factory returns a concrete instance you can use the @Parameters annotation in order to obtain a more flexible automatic unit test.

    package it.sorintlab.pxrm.proposition.model.factory.task;
    
    import org.junit.Test;
    
    import java.util.Arrays;
    import java.util.Collection;
    
    import org.junit.runner.RunWith;
    import org.junit.runners.Parameterized;
    import org.junit.runners.Parameterized.Parameters;
    
    import static org.junit.Assert.*;
    
    @RunWith(Parameterized.class)
    public class TaskFactoryTest {
    
        @Parameters
        public static Collection data() {
            return Arrays.asList(new Object[][] {
                    { "sas:wp|repe" , WorkPackageAvailabilityFactory.class},
                    { "sas:wp|people", WorkPackagePeopleFactory.class},
                    { "edu:wp|course", WorkPackageCourseFactory.class},
                    { "edu:wp|module", WorkPackageModuleFactory.class},
                    { "else", AttachmentTaskDetailFactory.class}
            });
        }
    
        private String fInput;
        private Class fExpected;
    
        public TaskFactoryTest(String input, Class expected) {
            this.fInput = input;
            this.fExpected = expected;
        }
    
        @Test
        public void getFactory() {
            assertEquals(fExpected, TaskFactory.getFactory(fInput).getClass());
        }
    }
    

    This example is made using Junit4. You can notice that with only one line of code you can test all the result of your Factory method.

提交回复
热议问题