本文正在参加「Java主题月 – Java Debug笔记活动」,详情查看活动链接
提问:您如何断言在JUnit 4测试中引发了某种异常?
如何惯用JUnit4来测试某些代码引发异常?
虽然我当然可以做这样的事情:
@Test
public void testFooThrowsIndexOutOfBoundsException() {
boolean thrown = false;
try {
foo.doStuff();
} catch (IndexOutOfBoundsException e) {
thrown = true;
}
assertTrue(thrown);
}
复制代码
我记得在这种情况下,有一个批注或一个Assert.xyz或一些不那么杂乱无章的东西,更像是JUnit的精髓。
高分回答:
编辑:现在已经发布了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()
文章翻译自 am2dgbqfb6mk75jcyanzabc67y-ac4c6men2g7xr2a-stackoverflow-com.translate.goog/questions/1…
作者建议:我们的接口都需要做单元测试,这里给出几个简单事例
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);
}
复制代码
真心感谢帅逼靓女们能看到这里,如果这个文章写得还不错,觉得有点东西的话
求点赞? 求关注❤️ 求分享? 对8块腹肌的我来说真的 非常有用!!!
如果本篇博客有任何错误,请批评指教,不胜感激 !❤️❤️❤️❤️
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END