你好,我需要为我的方法编写单元测试。我有点麻烦,因为我刚开始接触JUnit。我需要为这个方法写一个测试。这是我的方法
@Override
public Long countSellingOrdersInQueue(String principal) {
List<String> states = Arrays.asList(PENDING.name(), REGULARIZED.name());
return orderRepository.countByArticleUserIdAndStateIn(principal, states);
}我试过了,但我被挡住了,这是我的结果
P.S.考试通过了,但我不知道我的测试是否属实
@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);
}发布于 2018-07-14 19:20:45
在您的例子中,它只是单元测试,您不需要使用@MockBean,因为它加载上下文。单元测试要运行得更快,使用@MockBean,将加载上下文,并需要时间来完成测试。这里是关于何时使用@Mock和何时使用@MockBean的建议。
正如Maxim所说,在测试中没有任何断言。这就是为什么测试没有失败的原因。
在编写测试时,要记住的事情很少。
以下是代码:
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);
}
}发布于 2018-07-13 18:58:48
测试通过,因为您没有任何断言,这将检查结果。您只需调用毫无例外地执行的方法。
简单的测试示例:
@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
}https://stackoverflow.com/questions/51331221
复制相似问题