关于junit5:JUnit-5-参数化测试

JUnit 5参数化测试目录 设置咱们的第一个参数化测试参数起源@ValueSource@NullSource & @EmptySource@MethodSource@CsvSource@CsvFileSource@EnumSource@ArgumentsSource参数转换参数聚合处分总结如果您正在浏览这篇文章,阐明您曾经相熟了JUnit。让我为您概括一下JUnit——在软件开发中,咱们开发人员编写的代码可能是设计一个人的个人资料这样简略,也可能是在银行零碎中进行付款这样简单。在开发这些性能时,咱们偏向于编写单元测试。顾名思义,单元测试的次要目标是确保代码的小、独自局部按预期性能工作。如果单元测试执行失败,这意味着该性能无奈按预期工作。编写单元测试的一种工具是JUnit。这些单元测试程序很小,然而十分弱小,并且能够疾速执行。如果您想理解更多对于JUnit 5(也称为JUnit Jupiter)的信息,请查看这篇JUnit5的文章。当初咱们曾经理解了JUnit,接下来让咱们聚焦于JUnit 5中的参数化测试。参数化测试能够解决在为任何新/旧性能开发测试框架时遇到的最常见问题。 编写针对每个可能输出的测试用例变得更加容易。单个测试用例能够承受多个输出来测试源代码,有助于缩小代码反复。通过应用多个输出运行单个测试用例,咱们能够确信已涵盖所有可能的场景,并保护更好的代码覆盖率。开发团队通过利用办法和类来创立可重用且涣散耦合的源代码。传递给代码的参数会影响其性能。例如,计算器类中的sum办法能够解决整数和浮点数值。JUnit 5引入了执行参数化测试的能力,能够应用单个测试用例测试源代码,该测试用例能够承受不同的输出。这样能够更无效地进行测试,因为在旧版本的JUnit中,必须为每种输出类型创立独自的测试用例,从而导致大量的代码反复。 示例代码本文附带有在 GitHub上 的一个可工作的示例代码。 设置就像疯狂泰坦灭霸喜爱拜访力量一样,您能够应用以下Maven依赖项来拜访JUnit5中参数化测试的力量: <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-params</artifactId> <version>5.9.2</version> <scope>test</scope></dependency>让咱们来写些代码,好吗? 咱们的第一个参数化测试当初,我想向您介绍一个新的注解 @ParameterizedTest。顾名思义,它通知JUnit引擎应用不同的输出值运行此测试。 import static org.junit.jupiter.api.Assertions.assertEquals;import org.junit.jupiter.params.ParameterizedTest;import org.junit.jupiter.params.provider.ValueSource;public class ValueSourceTest { @ParameterizedTest @ValueSource(ints = { 2, 4 }) void checkEvenNumber(int number) { assertEquals(0, number % 2, "Supplied number is not an even number"); }}在下面的示例中,注解@ValueSource为 checkEvenNumber() 办法提供了多个输出。假如咱们应用JUnit4编写雷同的代码,即便它们的后果(断言)完全相同,咱们也必须编写2个测试用例来笼罩输出2和4。 当咱们执行 ValueSourceTest 时,咱们会看到什么: ValueSourceTest |_ checkEvenNumber |_ [1] 2 |_ [2] 4 这意味着 checkEvenNumber() 办法将应用2个输出值执行。 在下一节中,让咱们学习一下JUnit5框架提供的各种参数起源。 ...

April 25, 2023 · 4 min · jiezi

关于junit5:底层到底做了什么-junit5中ExtendWithParameterResolver的简单示例的执行过程

联合github/junit5-samples-extensions简略阐明@ExtendWith的底层执行流程。 代码 @ExtendWith(RandomParametersExtension.class)class RandomParametersExtensionTests { @Test void injectsInteger(@Random int i, @Random int j) { assertNotEquals(i, j); }}public class RandomParametersExtension implements ParameterResolver { @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Random { } @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return parameterContext.isAnnotated(Random.class); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) { return getRandomValue(parameterContext.getParameter(), extensionContext); } private Object getRandomValue(Parameter parameter, ExtensionContext extensionContext) { Class<?> type = parameter.getType(); java.util.Random random = extensionContext.getRoot().getStore(Namespace.GLOBAL)// .getOrComputeIfAbsent(java.util.Random.class); if (int.class.equals(type)) { return random.nextInt(); } if (double.class.equals(type)) { return random.nextDouble(); } throw new ParameterResolutionException("No random generator implemented for " + type); }}执行流程 ...

January 9, 2023 · 1 min · jiezi

关于junit5:Spring-MVC-Rest-Controller-Tests

Using JsonPath in MockMVC TestBeerController@RequestMapping("/api/v1/beer")@RestControllerpublic class BeerController { private final BeerService beerService; @GetMapping(path = {"/{beerId}"},produces = { "application/json" }) public ResponseEntity<BeerDto> getBeerById(@PathVariable("beerId") UUID beerId){ return new ResponseEntity<>(beerService.findBeerById(beerId), HttpStatus.OK); }}BeerControllerTestimport static org.hamcrest.core.Is.is;import static org.mockito.ArgumentMatchers.any;import static org.mockito.BDDMockito.given;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;@ExtendWith(MockitoExtension.class)class BeerControllerTest { @Mock BeerService beerService; @InjectMocks BeerController beerController; MockMvc mockMvc; BeerDto validBeer; @BeforeEach void setUp() { validBeer = BeerDto.builder().id(UUID.randomUUID()) .version(1) .beerName("Beer1") .beerStyle(BeerStyleEnum.PALE_ALE) .price(new BigDecimal("12.99")) .quantityOnHand(4) .upc(123456789012L) .createdDate(OffsetDateTime.now()) .lastModifiedDate(OffsetDateTime.now()) .build(); mockMvc = MockMvcBuilders.standaloneSetup(beerController).build(); } @Test void testGetBeerById() throws Exception { given(beerService.findBeerById(any())).willReturn(validBeer); mockMvc.perform(get("/api/v1/beer/" + validBeer.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$.id", is(validBeer.getId().toString()))) .andExpect(jsonPath("$.beerName", is("Beer1"))); }}

August 22, 2022 · 1 min · jiezi

关于junit5:Spring-MVC-Test-with-Mockito

MockMvcTest Get MethodUnit TestVetController@Controllerpublic class VetController { private final ClinicService clinicService; @Autowired public VetController(ClinicService clinicService) { this.clinicService = clinicService; } @RequestMapping(value = { "/vets.html"}) public String showVetList(Map<String, Object> model) { // Here we are returning an object of type 'Vets' rather than a collection of Vet objects // so it is simpler for Object-Xml mapping Vets vets = new Vets(); vets.getVetList().addAll(this.clinicService.findVets()); model.put("vets", vets); return "vets/vetList"; }}VetControllerTest//...import static org.assertj.core.api.Assertions.assertThat;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;import static org.mockito.BDDMockito.given;import static org.mockito.BDDMockito.then;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;@ExtendWith(MockitoExtension.class)class VetControllerTest { @Mock ClinicService clinicService; @Mock Map<String, Object> model; @InjectMocks VetController controller; List<Vet> vetsList = new ArrayList<>(); MockMvc mockMvc; @BeforeEach void setUp() { vetsList.add(new Vet()); given(clinicService.findVets()).willReturn(vetsList); mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } @Test void testControllerShowVetList() throws Exception { mockMvc.perform(get("/vets.html")) .andExpect(status().isOk()) .andExpect(model().attributeExists("vets")) .andExpect(view().name("vets/vetList")); }}Integration TestOwnerController@Controllerpublic class OwnerController { private static final String VIEWS_OWNER_CREATE_OR_UPDATE_FORM = "owners/createOrUpdateOwnerForm"; private final ClinicService clinicService; @RequestMapping(value = "/owners/new", method = RequestMethod.GET) public String initCreationForm(Map<String, Object> model) { Owner owner = new Owner(); model.put("owner", owner); return VIEWS_OWNER_CREATE_OR_UPDATE_FORM; }}OwnerControllerTest// ...import org.springframework.test.context.junit.jupiter.web.SpringJUnitWebConfig;import org.springframework.test.web.servlet.MockMvc;import org.springframework.test.web.servlet.setup.MockMvcBuilders;import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;@SpringJUnitWebConfig(locations = {"classpath:spring/mvc-test-config.xml", "classpath:spring/mvc-core-config.xml"})// @SpringJUnitWebConfig({Abc.class, Uvw.class})class OwnerControllerTest { @Autowired OwnerController ownerController; @Autowired ClinicService clinicService; MockMvc mockMvc; @BeforeEach void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(ownerController).build(); } @Test void initCreationFormTest() throws Exception { mockMvc.perform(get("/owners/new")) .andExpect(status().isOk()) .andExpect(model().attributeExists("owner")) .andExpect(view().name("owners/createOrUpdateOwnerForm")); }}

August 21, 2022 · 1 min · jiezi

关于junit5:Spring-MVC-Test-with-Mockito

MockMvcVetController@Controllerpublic class VetController { private final ClinicService clinicService; @Autowired public VetController(ClinicService clinicService) { this.clinicService = clinicService; } @RequestMapping(value = { "/vets.html"}) public String showVetList(Map<String, Object> model) { // Here we are returning an object of type 'Vets' rather than a collection of Vet objects // so it is simpler for Object-Xml mapping Vets vets = new Vets(); vets.getVetList().addAll(this.clinicService.findVets()); model.put("vets", vets); return "vets/vetList"; }}VetControllerTest@ExtendWith(MockitoExtension.class)class VetControllerTest { @Mock ClinicService clinicService; @Mock Map<String, Object> model; @InjectMocks VetController controller; List<Vet> vetsList = new ArrayList<>(); MockMvc mockMvc; @BeforeEach void setUp() { vetsList.add(new Vet()); given(clinicService.findVets()).willReturn(vetsList); mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } @Test void testControllerShowVetList() throws Exception { mockMvc.perform(get("/vets.html")) .andExpect(status().isOk()) .andExpect(model().attributeExists("vets")) .andExpect(view().name("vets/vetList")); }}

August 21, 2022 · 1 min · jiezi