java - Given, when, then约定和异常处理。使用 Mockito 和 JUnit

标签 java junit tdd junit4 bdd

将测试用例分为 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);

}
}

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

最佳答案

首先,我认为您的测试是可以的,即使有些测试没有完全遵循 given/when/then 顺序,但如果您想标准化测试组织以提高可读性,这对您有好处。

this StackOverflow page 中所述,在 JUnit 中有许多有效的方法可以预期异常。 .我认为似乎适合给定/何时/当时组织的是:

@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
}

关于java - Given, when, then约定和异常处理。使用 Mockito 和 JUnit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33847470/

相关文章:

java - 为什么 OpenJPA 在 DELETE 之前调用 UPDATE?

java - 当测试按设置运行时,单元测试失败?

unit-testing - 我应该记录我的单元测试方法吗?

c - 单元测试 : cohabitation of the production-code and the mocked implementation

ruby-on-rails - 使用 rspec 测试 Rails STI 子类

java - Pentaho 7 CE Report Designer 超链接BUG

java - 创建一个打印 ArrayList 的方法,然后在另一个类中调用它

java - 支持 Spring 的 Web 应用程序

java - 获取所有 JAR 文件中所有类中带注释 @Test 的所有方法

java - 运行 JUnit/Mockito 测试时出现 org.springframework.http.converter.HttpMessageNotReadableException