How to avoid multiple asserts in a JUnit test?

前端 未结 7 740
故里飘歌
故里飘歌 2020-11-29 12:12

I have a DTO which I\'m populating from the request object, and the request object has many fields. I want to write a test to check if the populateDTO() method

相关标签:
7条回答
  • 2020-11-29 13:00

    Or you can do some workaround.

    import junit.framework.Assert;
    import org.junit.After;
    import org.junit.AfterClass;
    import org.junit.Before;
    import org.junit.BeforeClass;
    import org.junit.Test;
    
    public class NewEmptyJUnitTest {
    
        public NewEmptyJUnitTest() {
        }
    
        @BeforeClass
        public static void setUpClass() throws Exception {
        }
    
        @AfterClass
        public static void tearDownClass() throws Exception {
        }
    
        @Before
        public void setUp() {
        }
    
        @After
        public void tearDown() {
        }
    
    
         @Test
         public void checkMultipleValues() {
             String errMessages = new String();
    
             try{
                 this.checkProperty1("someActualResult", "someExpectedResult");
             } catch (Exception e){
                 errMessages += e.getMessage();
             }
    
            try{
                this.checkProperty2("someActualResult", "someExpectedResult");
             } catch (Exception e){
                 errMessages += e.getMessage();
             }
    
            try{
                 this.checkProperty3("someActualResult", "someExpectedResult");
             } catch (Exception e){
                 errMessages += e.getMessage();
             }
    
            Assert.assertTrue(errMessages, errMessages.isEmpty());
    
    
         }
    
    
    
         private boolean checkProperty1(String propertyValue, String expectedvalue) throws Exception{
             if(propertyValue == expectedvalue){
                 return true;
             }else {
                 throw new Exception("Property1 has value: " + propertyValue + ", expected: " + expectedvalue);
             }
         }
    
           private boolean checkProperty2(String propertyValue, String expectedvalue) throws Exception{
             if(propertyValue == expectedvalue){
                 return true;
             }else {
                 throw new Exception("Property2 has value: " + propertyValue + ", expected: " + expectedvalue);
             }
         }
    
             private boolean checkProperty3(String propertyValue, String expectedvalue) throws Exception{
             if(propertyValue == expectedvalue){
                 return true;
             }else {
                 throw new Exception("Property3 has value: " + propertyValue + ", expected: " + expectedvalue);
             }
         }  
    }  
    

    Maybe not the best approach and if overused than can confuse... but it is a possibility.

    0 讨论(0)
提交回复
热议问题