您如何断言在JUnit 4测试中引发了某种异常?

发表于:2021-5-28 09:11

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:清蒸闲鱼    来源:掘金

#
JUnit
分享:
  如何惯用JUnit4来测试某些代码引发异常?
  虽然我当然可以做这样的事情:
  @Test
  public void testFooThrowsIndexOutOfBoundsException() {
    boolean thrown = false;
    try {
      foo.doStuff();
    } catch (IndexOutOfBoundsException e) {
      thrown = true;
    }
    assertTrue(thrown);
  }
  我记得在这种情况下,有一个批注或一个Assert.xyz或一些不那么杂乱无章的东西,更像是JUnit的精髓。
  高分回答:
  很多的知识点,真的需要写出来才会掌握!!!?\color{purple}很多的知识点,真的需要写出来才会掌握!!!{~}很多的知识点,真的需要写出来才会掌握!!!?
  编辑:现在已经发布了JUnit 5和JUnit 4.13,最好的选择是使用Assertions.assertThrows()(对于JUnit 5)和Assert.assertThrows()(对于JUnit 4.13+)。请参阅我的其他答案以获取详细信息。
  如果您尚未迁移到JUnit 5,但可以使用JUnit 4.7,则可以使用ExpectedExceptionRule:
  public class FooTest {
    @Rule
    public final ExpectedException exception = ExpectedException.none();
    @Test
    public void doStuffThrowsIndexOutOfBoundsException() {
      Foo foo = new Foo();
      exception.expect(IndexOutOfBoundsException.class);
      foo.doStuff();
    }
  }
  这要好得多,@Test(expected=IndexOutOfBoundsException.class)因为如果IndexOutOfBoundsException之前抛出测试,测试将失败foo.doStuff();
  redis
  @RunWith(SpringRunner.class)
  @EnableAutoConfiguration
  @SpringBootTest(classes = JedisClusterConfiguration.class)
  public class JedisClusterConfigurationTest {
      @Autowired
      private JedisCluster jedis;
      @Test
      public void test() {
          System.out.println(jedis.lpush("l1", "123"));
          System.out.println(jedis.lpush("l1", "456"));
          System.out.println(jedis.lrange("l1", 0, -1));
          System.out.println(jedis.hset("h1", "k1", "v1"));
          System.out.println(jedis.hset("h1", "k2", "v2"));
          System.out.println(jedis.hset("h1", "k3", "v3"));
          System.out.println(jedis.hset("h1", "k4", "v4"));
          System.out.println(jedis.hget("h1", "k3"));
          System.out.println(jedis.hgetAll("h1"));
          System.out.println(jedis.set("hello", "world"));
          System.out.println(jedis.get("hello"));
      }
  }
  文件
  @RunWith(SpringRunner.class)
  @EnableAutoConfiguration
  @SpringBootTest(classes = FileClientConfiguration.class)
  public class FileClientServiceTest {
      @Autowired
      private FileClientService fileClientService;
      @Test
      public void upload() throws IOException {
          String filePath = "D:\\Pictures\\1ba5ee77-775b-469e-88ae-b8ad23b501fc.jpg";
          String originalFilename = "img.mmexport123123123213";
          MockMultipartFile file = new MockMultipartFile("file", originalFilename, "multipart/form-data", new FileInputStream(filePath));
          String newFileName = fileClientService.upload(file);
          System.out.println(newFileName);
      }
  }
  限流
  import com.sinoiov.spring.boot.autoconfigure.ratelimit.config.RateLimitProperties;
  import com.sinoiov.spring.boot.autoconfigure.ratelimit.config.RateLimitType;
  import com.sinoiov.spring.boot.autoconfigure.ratelimit.ratelimit.impl.MaxRateLimiter;
  import org.junit.Before;
  import org.junit.Test;
  import org.mockito.MockitoAnnotations;
  import org.slf4j.Logger;
  import org.slf4j.LoggerFactory;
  public class MaxRateLimitTest {
      private static final Logger logger = LoggerFactory.getLogger(MaxRateLimitTest.class);
      @Before
      public void setUp() {
          MockitoAnnotations.initMocks(this);
      }
      @Test
      public void test() throws InterruptedException {
          RateLimitProperties.Policy policy = new RateLimitProperties.Policy();
          policy.setType(RateLimitType.MAX_LIMIT);
          policy.setLimit(3L);
          policy.setRefreshInterval(3L);
          policy.setUrl("/abc");
          MaxRateLimiter maxRateLimiter = new MaxRateLimiter(policy);
          for (int i = 0; i < 13; i++) {
              Thread.sleep(1 * 1000);
              logger.info("{}", maxRateLimiter.tryAcquire());
          }
          Thread.sleep(4 * 1000);
          logger.info("{}", maxRateLimiter.tryAcquire());
          Thread.sleep(9 * 1000);
          logger.info("{}", maxRateLimiter.tryAcquire());
          logger.info("{}", maxRateLimiter.tryAcquire());
          logger.info("{}", maxRateLimiter.tryAcquire());
          logger.info("{}", maxRateLimiter.tryAcquire());
          logger.info("开始退还令牌");
          maxRateLimiter.giveBack();
          maxRateLimiter.giveBack();
          maxRateLimiter.giveBack();
          maxRateLimiter.giveBack();
          maxRateLimiter.giveBack();
          for (int i = 0; i < 5; i++) {
              logger.info("{}", maxRateLimiter.tryAcquire());
          }
          logger.info("{}", "Done!");
      }
  }
  http请求
  @Test
  public void findBanks() throws Exception {
  String url = "https://xxx";
  Map<String, Object> para = new HashMap<String, Object>();
  // para.put("merchant_id", "100000001303441");
  para.put("bank_name", "xxx");
  para.put("charset", "UTF-8");
  para.put("province_name", "xx");
  para.put("city_name", "xx");
  para.put("sign_type", "RSA");
  //para.put("Sign", null);
  String result = ReapalSendUtils.send(para, url); // 调用HTTPClient
  logger.info(result);
  result = Decipher.decryptData(result);
  logger.info(result);
  }

      本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号