【问题标题】:Some example of JUnit of Rest APIRest API 的 JUnit 示例
【发布时间】:2019-12-11 00:56:49
【问题描述】:

我想尝试一些带有rest API的JUnit示例,我是JUnit的初学者,我不知道如何开始

我的仓库:

@Repository
public interface ClienteRepository extends JpaRepository<ClienteEntity, Integer>{
    ClienteEntity findByEmail(@Param("email") String email);


     @Query(value = "SELECT u FROM ClienteEntity u where u.email = ?1 and u.password = ?2 ")
        Optional<ClienteEntity> login(String email,String password);

        Optional<ClienteEntity> findByToken(String token);



        @Query(value = "SELECT c " +  
                "FROM ClienteEntity c " +
                "WHERE c.id = :id ")

        ClienteEntity getClienteById(@Param("id")Integer id);



}

拥有一个包含这些字段的实体“客户”:

@Entity(name = "cliente")
public class cliente{
@Id
    @GeneratedValue(strategy=GenerationType.AUTO) //Vedere UUID bene
    private Integer id;

    private String nome;

    private String cognome;

    @Column(name = "email", unique = true)
    private String email ;

    private String password;

    private String citta;

    private String cap;

    private String indirizzo;

    private String token;

    public String getToken() {
        return token;
    }
}

//with their set and get methods

是否可以在字段中测试 clienteuseremail 而不是我的 DB

【问题讨论】:

标签: java spring rest junit


【解决方案1】:

您可以通过 goggle 获得几个示例 :)。但你可能没想到我会这样回答!

现在冗长但详细的答案请耐心等待:P

您可以使用 junit、mockito、spring test、power-mockito 等进行 JUnitTesting。

我假设您的休息项目结构是:-

1. Controller is :- 

@RestController
@RequestMapping("/api")
public class RestApiController {

    @Autowired
    UserServiceImpl userService;

    @RequestMapping(value = "/user/", method = RequestMethod.GET)
    public ResponseEntity<List<User>> listAllUsers() {
        List<User> users = userService.findAllUsers();
        if (users.isEmpty()) {
            System.out.println();
            return new ResponseEntity(HttpStatus.NO_CONTENT);
        }
        return new ResponseEntity<List<User>>(users, HttpStatus.OK);
    }
}

2. Service Layer is :-

    @Service("userService")
    public class UserServiceImpl implements UserService{

       @Autowired
       UserDao userDao;

       public List<User> findAllUsers() {
        return userDao.findAll();
       }
    }
}
  1. 道层:-

    和你的一样。

现在对它进行单元测试:-

@RunWith(SpringRunner.class)
@WebMvcTest(value = RestController.class, secure = false)
public class RestControllerTest {

@Autowired
private MockMvc mockMvc;

@SpyBean
private RestApiController restController;

@SpyBean
private UserServiceImpl userService;   //Spy will call real method (Use Spy where you want actual execution).

@MockBean
UserDaoImpl userDaoImpl; ( Use Mock where you don't want execution as in your case you don't want to make query in database.)  --Use Mock and step 1 define rule which will give expected result without real execution. 
// How you will know :- If you place debug and run as debug junit you will find debugger will not go method inside in mocked object)

@Test
public void testListAllUsers(){
    List<User> userList= new ArrayList<User>();
    userList.add(new User(1, "himanshu", 26, "abc@gmail.com"));
    Mockito.when(userDaoImpl.findAll()).thenReturn(userList);    //step 1 
    assertEquals(HttpStatus.OK, restController.listAllUsers().getStatusCode());    // This will check if expected status code is present in response --Happy Case


    Assert.assertEquals("himanshu", restController.listAllUsers().getBody().get(0).getName());  // if you also want to test whether object in happy case has valid attribute.
    System.out.println(" completed");
}

}

如果您想使用 URL 测试休息呼叫:-

RequestBuilder requestBuilder = MockMvcRequestBuilders.get(
            "/api/user/").accept(
            MediaType.APPLICATION_JSON);

    MvcResult result = mockMvc.perform(requestBuilder).andReturn();

    Assert.assertEquals(200, result.getResponse().getStatus());

参考链接:- 模拟:https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/Mockito.html 春季测试:- https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html

Maven 依赖:- 春季测试:-

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

对于 Mockito 测试:-

<dependency>
        <groupId>org.mockito</groupId>
        <artifactId>mockito-all</artifactId>
        <version>1.8.4</version>
        <scope>test</scope>
    </dependency>

上面的示例将测试整个 (controller-service-dao) 流程,但是如果您想进行单独的模块测试,这很容易,为此您必须创建 DaoTest 类和模拟 Dao 层并进行类似的测试,这不是一个好方法.

来自 (controller - service -dao) 的测试出现集成测试,它本身会自动测试所有单独的模块。

干杯!!

【讨论】:

    猜你喜欢
    • 2012-07-22
    • 1970-01-01
    • 2016-01-06
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多