我似乎无法在线找到任何解决此问题的教程
我有if
声明:
if (basket.getCustomerId() != null) {
Basket exBasket = findBasketByCustomerId(basket.getCustomerId());
if (exBasket != null && exBasket.getBasketId() != null) {
return exBasket;
}
我想写一个单元测试,测试每一行,看看它是否做得对。
有什么想法吗?
@Test
public void testBasketWithANullCustomerId(){
basketInformationServiceImpl.createBasket(mockBasket);
assertNotNull(mockBasket.getCustomerId());
}
答案 0 :(得分:9)
单元测试的目的不是测试语句而是方法。正确的做法是不考虑这一行,而是考虑它出现的方法,并询问你想要该方法做什么:它需要什么样的输入,以及它应该产生什么样的输出? / p>
然后编写带有一些典型输入的测试,并检查它们是否给出了正确的输出,还有一些 edge case 输入(如null
,0, Integer.MAX_VALUE
等等,并检查您是否也获得了正确的输出。
如果这是你的整个方法(实际上它不是,但如果它是它的本质),我会测试:
basket
客户ID为null
; null
购物篮(除非你确定这种情况永远不会发生),因为目前此代码会提供NullPointerException
; exBasket
; exBasket
null
; exBasket
且不为空,但其购物篮ID为null
。答案 1 :(得分:0)
假设这是您尝试测试的方法的摘录,听起来您需要至少两个测试用例 - 其中一个basket.getCustomerId()
预计为空,另一个不是&#39 ;吨。在这两种情况下,您都应该能够测试方法的返回值(我假设Basket
将在getCustomerId()
为空的情况下返回)与预期结果一致
答案 2 :(得分:0)
要以您似乎想要的方式进行测试(强调线条覆盖率),您需要对要测试的每种情况进行测试(例如,一个测试用于null basketId,另一个用于非null basketId,另一个用于测试你希望测试的另一个案例。)
模拟框架(例如Mockito)可用于设置测试的前提条件。有关一个案例的例子,您可以说
@Test
public void myTestWithNonNullBasketId() {
Basket inputBasket = Mockito.mock(Basket.class);
when(inputBasket.getBasketId()).thenReturn(1); //Or whatever we want basketId to return, null if you want to check that case.
... //More mocking as needed, presumably to dictate whatever findBasketByCustomerId might return.
//Call the method you are testing, use org.junit.Assert assertions to check outputs.
}