如何惯用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),我们将立即处理