java 如何通过模拟测试覆盖@SneakyThrows注解?

t98cgbkg  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(145)

我想通过模拟测试(我使用第5单元)@SneakyThrows注解来覆盖一个方法,它看起来像:

@Override
@SneakyThrows
public String getLocalHostName() {
    return InetAddress.getLocalHost().getHostName();
    }

但我所有的试演都不成功我试过写一些像

@Test
void testGetLocalHostName_exception() {
    assertThrows(Exception.class, () -> repository.getLocalHostName());
}

但它没有涵盖这个注解。我的模拟测试btw的成功案例如下:

@ExtendWith(MockitoExtension.class)
class MyRepositoryImplTest {

    @Mock(lenient = true)
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Mock(lenient = true)
    private InetAddress mockInetAddress;

    @InjectMocks
    @Spy
    private MyRepository repository;

    @Test
    void testGetLocalHostName() {
        var expectedHostname = "mock-hostname";
        Mockito.when(mockInetAddress.getHostName()).thenReturn(expectedHostname);
    
        MyRepository repository = new MyRepository(jdbcTemplate) {
            @Override
            public String getLocalHostName() {
                return mockInetAddress.getHostName();
            }
        };
        assertThat(repository.getLocalHostName()).isEqualTo(expectedHostname);
    }
}

你能帮我把这行用测试覆盖一下吗?

ljsrvy3e

ljsrvy3e1#

为了测试它,你需要在调用getLocalHostName时让mock抛出一些异常:

Mockito.when(mockInetAddress.getHostName()).thenThrow(new RuntimeException()); 
// use here the actual exception that will occur in your production code

MyRepository repository = new MyRepository(jdbcTemplate) {
    @Override
    public String getLocalHostName() {
        return mockInetAddress.getHostName();
    }
};

assertThrows(Exception.class, () -> repository.getLocalHostName());

另外,你可以使用Assertj来测试异常:https://github.com/assertj/assertj。例如,您可以检查异常消息:

//Assertions from package org.assertj.core.api
Assertions.assertThatThrownBy(() -> repository.getLocalHostName())
        .isInstanceOf(UnknownHostException.class)
        .hasMessageContaining("my custom error message");

相关问题