美文网首页
如何对业务实现进行Unit Test?

如何对业务实现进行Unit Test?

作者: PageThinker | 来源:发表于2019-02-23 18:22 被阅读0次

为什么要求对业务实现进行Unit Test?请移步这里Java中几种Unit Test场景

有一段业务逻辑是提供以下功能:
如果productId是“ABC”,countryCode是“US”,则返回Product对象;
否则抛出NotFoundException("Not Found");


ProductService


@Service
public class ProductService {

    public ProductDTO query(String productId, String countryCode) throws NotFoundException {
        if ("ABC".equals(productId) && "US".equals(countryCode)) {
            return new ProductDTO("ABC", "US", "Super ABC");
        }
        throw new NotFoundException("Not found");
    }
}

测试

1,当调用某段业务代码后,有没有返回预期的的想要的结果:
should_return_product_dto_when_product_id_is_ABC_and_country_code_is_US();

2,当业务代码传入一些非法数据是,业务代码是否返回了期望的结果
should_throw_NotFoundException_when_product_id_is_empty_and_country_code_is_empty();

@RunWith(MockitoJUnitRunner.class)
public class ProductServiceTest {

    @InjectMocks
    private ProductService productService;

    @Rule
    public ExpectedException thrown = ExpectedException.none();


    @Test
    public void should_return_product_dto_when_product_id_is_ABC_and_country_code_is_US() throws NotFoundException {
        ProductDTO productDTO = productService.query("ABC", "US");

        assertThat(productDTO.getName(), is("ABC"));
        assertThat(productDTO.getCountryCode(), is("US"));
        assertThat(productDTO.getDescription(), is("Super ABC"));
    }

    @Test
    public void should_throw_NotFoundException_when_product_id_is_empty_and_country_code_is_empty() throws NotFoundException {
        thrown.expect(NotFoundException.class);
        thrown.expectMessage("Not found");

        productService.query("", "");
    }

}

相关文章

网友评论

      本文标题:如何对业务实现进行Unit Test?

      本文链接:https://www.haomeiwen.com/subject/teipyqtx.html