[英]How to test void using Unit Test?
I have the following method and I wrote a unit test in Java for this method.我有以下方法,并为此方法用 Java 编写了一个单元测试。 It is coveraged except from the
if
statement and I also need to test this part.除了
if
语句之外,它被覆盖,我还需要测试这部分。
@InjectMocks
private ProductServiceImpl productService;
public void demoMethod(final List<UUID> productUuidList) {
if (productUuidList.isEmpty()) {
return;
}
final Map<ProductRequest, PriceOverride> requestMap = getPriceRequests(uuidList);
productService.updateByPriceList(priceRequestMap, companyUuid);
}
However, as the method execution is finalized and does not return anything when uuidList
is empty, I cannot test this if
block.但是,由于方法执行已完成并且在
uuidList
为空时不返回任何内容,因此我无法测试此if
块。
So:所以:
How can I test this if
block? if
阻止,我该如何测试?
Should I create a new Unit Test method for testing this if
block?我应该创建一个新的单元测试方法来测试这个
if
块吗? Or should I add related assert lines to the current test method?或者我应该将相关的断言行添加到当前的测试方法中吗?
Update: Here is my test method:更新:这是我的测试方法:
@Test
public void testDemoMethod() {
final UUID uuid = UUID.randomUUID();
final List<Price> priceList = new ArrayList<>();
final Price price = new Price();
price.setUuid(uuid);
priceList.add(price);
productService.demoMethod(Collections.singletonList(uuid));
}
The general idea is that you don't want to test specific code , but you want to test some behaviour .一般的想法是你不想测试特定的代码,但你想测试一些行为。
So in your case you want to verify that getPriceRequests
and priceService.updateByPriceList
are not called when passing in an empty List
.因此,在您的情况下,您希望验证在传入空
List
时不会调用getPriceRequests
和priceService.updateByPriceList
。
How exactly you do that depends on what tools you have available.具体如何执行取决于您可用的工具。 The easiest way is if you already mock
priceService
: then just instruct your mocking liberary/framework to verify that updateByPriceList
is never called.最简单的方法是,如果您已经模拟
priceService
:那么只需指示您的模拟库/框架验证从未调用updateByPriceList
。
The point of doing a return in your if condition is that the rest of the code is not executed.在 if 条件中返回的要点是不执行其余代码。 Ie, if this
// code omitted for brevity
was to be executed, the method would not fill it's purpose.即,如果要执行此
// code omitted for brevity
,则该方法将无法满足其目的。 Therefore, just make sure that whatever that code does, it was not done if your list is empty.因此,只要确保无论该代码做什么,如果您的列表为空,它就没有完成。
You have 3 choices:你有3个选择:
Check out Test Pyramid and How anemic architecture spoils your tests for more details.查看测试金字塔和 贫血架构如何破坏您的测试以获取更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.