簡體   English   中英

我的方法的JUnit測試

[英]JUnit test for my method

您好,我需要為我的方法編寫單元測試。 我遇到了一些麻煩,因為我是JUnit的新手。 我需要為此方法編寫測試。 這是我的方法

@Override
public Long countSellingOrdersInQueue(String principal) {
    List<String> states = Arrays.asList(PENDING.name(), REGULARIZED.name());
    return orderRepository.countByArticleUserIdAndStateIn(principal, states);
}

我嘗試但被阻止了,這是我的結果

PS測試通過了,但我不知道我的測試是否正確

@MockBean
private OrderRepository orderRepository;

private String principal ;

@Test
public void countSellingOrdersInQueueTest(){
    orderService.countSellingOrdersInQueue(principal);
    List<String> states = Arrays.asList(PENDING.name(), REGULARIZED.name());
    orderRepository.countByUserIdAndStateIn(principal,states);
}

在您的情況下,這只是單元測試,您無需使用@MockBean,因為它會加載上下文。 使用@MockBean可以使單元測試運行得更快,它將加載上下文並花費時間來完成測試。 是何時使用@Mock以及何時使用@MockBean的建議。

正如Maxim所說,測試中沒有斷言。 這就是測試沒有失敗的原因。

編寫測試時要記住的幾件事。

  • 測試被認為是代碼的文檔,應該以使其他人理解代碼的方式更具可讀性。
  • 如前所述,單元測試是為了提供更快的反饋
  • 在測試中具有AAA(排列,行為,聲明)結構。 更多信息在這里

這是代碼:

public class OrderServiceTest {

    @InjectMocks
    private OrderService orderService;

    @Mock
    private OrderRepository orderRepository;

    @Before
    public void setUp() throws Exception {
        initMocks(this);
    }

    @Test
    public void countSellingOrdersInQueueTest(){
        when(orderRepository.countByArticleUserIdAndStateIn(any(), any())).thenReturn(1L);
        String principal = "dummyString";

        Long actualCount = orderService.countSellingOrdersInQueue(principal);

        List<String> expectedStates = Arrays.asList("State 1", "State 2");
        assertThat(actualCount, is(1L));
        verify(orderRepository).countByArticleUserIdAndStateIn(principal, expectedStates);
    }
}

測試通過是因為您沒有任何斷言可檢查結果。 您只需調用無例外執行的方法即可。

簡單的測試示例:

    @Test
    public void test() {
        assertEquals(true, true);
    }

在您的情況下測試將看起來像:

    @Test
    public void countSellingOrdersInQueueTest(){
        orderService.countSellingOrdersInQueue(principal);
        List<String> states = Arrays.asList(PENDING.name(), REGULARIZED.name());
        orderRepository.countByUserIdAndStateIn(principal,states);
        assertEquals(10, orderRepository.countByUserIdAndStateIn(principal,states));//10 replace to expectetion count
        //add some more checks
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM