给定、when、then 约定以及异常处理。使用 Mockito 和 JUnit

Mic*_*lec 5 java tdd bdd junit junit4

将测试用例分为 3 个部分是一个很好的做法:Given、When、Then。

但在 JUnit 中处理异常的常见方法是使用 ExpectedException @Rule。

问题是 ExpectedException::expect() 必须在 //when 部分之前声明。

public class UsersServiceTest {

// Mocks omitted    

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void signUp_shouldCheckIfUserExistsBeforeSign() throws ServiceException {
    // given - its ok
    User user = new User();
    user.setEmail(EMAIL);
    when(usersRepository.exists(EMAIL)).thenReturn(Boolean.TRUE);

    // then ???
    thrown.expect(UserAlreadyExistsServiceException.class);

    // when???
    usersService.signUp(user);

}
}
Run Code Online (Sandbox Code Playgroud)

有谁知道一些好的约定或库可以更好地处理测试中的异常?

aro*_*ech 3

首先,我认为你的测试是可以的,即使有些测试不完全遵循给定/何时/然后的顺序,但如果你想标准化测试的组织以提高可读性,那么对你有好处。

在 JUnit 中,有很多有效的方法来预期异常,如StackOverflow 页面中所述。我认为似乎适合给定/何时/然后组织的组织是:

@Test
public void signUp_shouldCheckIfUserExistsBeforeSign() throws ServiceException {

    // GIVEN
    User user = new User();
    user.setEmail(EMAIL);
    when(usersRepository.exists(EMAIL)).thenReturn(Boolean.TRUE);

    // WHEN 
    try {
        usersService.signUp(user);

    // THEN
        // expecting exception - should jump to catch block, skipping the line below:
        Assert.fail("Should have thrown UserAlreadyExistsServiceException");         
    }catch(UserAlreadyExistsServiceException e) {
        // expected exception, so no failure
    }
    // other post-sign-up validation here
}
Run Code Online (Sandbox Code Playgroud)