Selenium JUnit tests each with different logged in (authenticated) users



  • I am using Selenium and JUnit to automate tests. Lets say there are two tests and each has to authenticate with a different user and perform an action. Can it be done any smarter than to call an authentication method in each test method? Preferably with annotations so that the username for the test really stands out while skimming through the code and the login method being in @Before method or in TestBase class.

        public class AppTest extends TestBase {
    
        // this test must be run with userA
        @Test
        public void testA() {
    
            authenticateUser (userA);
    
            int count = retrieveNewEmailCount();
            assertEquals(NEW_EMAIL_COUNT, count);
        }
    
        // this test must be run with userB
        @Test
        public void testB() {
    
            authenticateUser (userB);
    
            String notificationText = retrieveNoNewEmailNotification();
            assertEquals(NO_EMAIL_NOTIFICATION, notificationText);
        }
    }
    

    Do not comment on business logic in the examples above as this is just simplified example. The real tests are not about emails at all. In reality there are hundreds of tests and almost a hundred users. Each user participates from one to hundreds tests. Each test is run once with one particular user only, ie no need to run the same test few times with different users.



  • You can use a bit of inheritance, which helps you to extend without dealing too much with data providers:

    public abstract class AbstractTest extends TestBase{
    
       protected User user;
    
       protected AbstractTest(User user) { this.user = user; } 
    
       @Before
       public void setUp() {
           authenticateUser(this.user);
       }
    
    }
    public class UserWithEmailsTest extends AbstractTest {
    
        protected UserWithEmailsTest(User user) { super(userA); } 
    
        // this test must be run with userA
        @Test
        public void testA() {    
            int count = retrieveNewEmailCount();
            assertEquals(NEW_EMAIL_COUNT, count);
        }
    }
    

    public class UserWithNoEmailsTest extends AbstractTest {

        protected UserWithNoEmailsTest(User user) { super(userB); } 
    
        @Test
        public void testB() {
           String notificationText = retrieveNoNewEmailNotification();
           assertEquals(NO_EMAIL_NOTIFICATION, notificationText);
       }
    }
    


Suggested Topics