如何在JUnit Test中引发UnsupportedEncodingException?

问题描述 投票:0回答:1

我具有以下实现:

public String encodeString(String testString) {

        try {
            return URLEncoder.encode(testString, "UTF-8");
        } catch (UnsupportedEncodingException e) {         <= I want to test this exception but was not successful
            log.error(ex.getMessage());
        }

        return "";
    }

我尝试为实现编写junit测试,测试没有失败,但是无法按预期抛出异常。

@Test
public void testEncodeString_Exception() throws UnsupportedEncodingException {
        // Setup
        final String testString= "U+FFFD";

        PowerMockito.mockStatic(URLEncoder.class);
        PowerMockito.when(URLEncoder.encode(testString, "UTF-8")).thenThrow(UnsupportedEncodingException.class);

        // Run the test
        final String result = classInstance.encodeString(testString);

        // Verify the results
    }

如果您之前遇到以下问题,我将非常感谢任何形式的帮助或知识共享。谢谢!

java aem junit5 powermockito
1个回答
0
投票

您应使用@Test(expected=UnsupportedEncodingException.class)而不是@Test来验证结果>

© www.soinside.com 2019 - 2024. All rights reserved.