我试着用的JUnit的Mockito,并写了一些测试用例的编码工作。
这是我写的测试案例:
@RunWith(SpringRunner.class)
public class TransactionControllerTest {
@Mock
TransactionService transactionServiceMock;
@InjectMocks
TransactionController transactionController;
TransactionRequest txn = new TransactionRequest("123.34", "2018-11-28T23:32:36.312Z");
@Test
public void testSaveTxn() throws Exception {
Mockito.when(transactionServiceMock.saveTxn(Mockito.any(TransactionRequest.class))).thenReturn(true);
ResponseEntity<?> responseEntity = transactionController.saveTxn(null, txn);
assertTrue(responseEntity.getStatusCode().equals(HttpStatus.CREATED));
}
@Test
public void testGetStats() throws Exception {
StatsResponse sr = new StatsResponse("0.00", "0.00", "0.00", "0.00", 0L);
Mockito.when(transactionServiceMock.getStats()).thenReturn(sr);
ResponseEntity<StatsResponse> responseEntity = (ResponseEntity<StatsResponse>) transactionController.getStats(null);
System.out.println("sr response = "+responseEntity.getBody());
assertTrue(responseEntity.getBody().equals(sr));
}
@Test
public void testDelete() throws Exception {
Mockito.doNothing().when(transactionServiceMock).delete();
ResponseEntity<HttpStatus> responseEntity = (ResponseEntity<HttpStatus>) transactionController.deleteTxn(null);
System.out.println("sr response = "+responseEntity.getBody());
assertTrue(responseEntity.getStatusCode().equals(HttpStatus.NO_CONTENT));
}
}
测试用例是工作的罚款。
但我的申请被拒绝指定以下原因:
你是即使你是不是在测试中使用SpringContext,并嘲讽一切使用SpringRunner。
现在,下面是我的顾虑:
这有什么错测试用例?
我想,他们要你做的是写一个Spring的web层测试。这不是一个Spring MVC的测试/弹簧开机测试。因为你不测试控制器作为弹簧加载的资源。你测试它作为一个简单的Java类。这将不能证明它是否表现为一个Spring控制器正确。您将无法测试等功能;
我该如何纠正?
你必须写一个Spring MVC的测试,并使用MockMvc
或RestTemplate
验证您的控制器。例如;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = YourContext.class)
@WebAppConfiguration
public class MyWebTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void foo() throws Exception {
mockMvc.perform(get("/status"));
//and verification
}
}
的嘲笑的Mockito使用还不是最坏的想法,但你也可以使用自动有线@MockBean
s。
如果这是春天开机,你将有更多的灵活性。看一看下面的资源。
https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html https://spring.io/guides/gs/testing-web/
你有抱怨,因为你没有在你的测试需要春天的测试功能。您的测试是纯粹的单元测试。
所以,如果你将删除@RunWith(SpringRunner.class)
什么都不会改变你的测试。只是放在那里@ExtendWith(MockitoExtension.class)
为你测试,你可以注入或使用以下注释应用程序的模拟片SpringRunner
将初始化Spring上下文:
@MockBean
@Autowired