如何使用springboot和sonarqube测试控制器

hrysbysz  于 2021-07-26  发布在  Java
关注(0)|答案(0)|浏览(288)

所以我在做我的第一个springboot项目,我被测试困住了。我查了很多例子,但似乎都不管用。
这是我的控制器的当前测试:

@SpringBootTest
@AutoConfigureMockMvc

public class AddPartyTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    @DisplayName("Should Not give access to endpoint")
    public void ShouldNotGiveAccess() throws Exception{
        mockMvc.perform(MockMvcRequestBuilders.get("/parties"))
                .andExpect(MockMvcResultMatchers.status().is(401));
    }

这是可行的,但在sonarqube上,我得到了0%的代码覆盖率,我似乎找不到一个测试,甚至得到这个百分比高于零。有谁能给我举个例子,告诉我如何为一个控制器编写一个好的单元测试,然后我就可以根据你的例子自己解决这个问题了。
这是我的控制器:

@RestController
@RequestMapping("/parties")
public class PartyController {
    @Autowired
    PartyService partyService;

    @GetMapping("")
    public List<Party> list(){
        return partyService.listAllParties();
    }
    @GetMapping("/{id}")
    public ResponseEntity<PartyDto> get(@PathVariable Integer id){
        try{
            PartyDto partyDto = partyService.getParty(id);
            return new ResponseEntity<>(partyDto, HttpStatus.OK);
        } catch (NoSuchElementException e){
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    @PostMapping("/")
    public void add(@RequestBody PartyDto partyDto) throws ParseException {
        partyService.saveParty(partyDto);
    }
    @PutMapping("/{id}")
    public ResponseEntity<?> update(@RequestBody PartyDto partyDto, @PathVariable Integer id){
        try{
            PartyDto existParty = partyService.getParty(id);
            partyDto.setId(id);
            partyService.saveParty(partyDto);
            return new ResponseEntity<>(HttpStatus.OK);
        } catch (NoSuchElementException e){
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    }
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id){
        partyService.deleteParty(id);
    }

    @DeleteMapping("/")
    public ResponseEntity<HttpStatus> deleteAllParties() {
        try {
            partyService.deleteAll();
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

}

这是我的服务(以备不时之需):

@Service
@Transactional
public class PartyService {

    @Autowired
    private PartyRepository partyRepository;
    @Autowired
    private ModelMapper modelMapper;
    public List<Party> listAllParties() {
        return partyRepository.findAll();
    }

    public void saveParty(PartyDto partyDto){
        Party party = convertToEntity(partyDto);
        partyRepository.save(party);
    }

    public PartyDto getParty(Integer id) {
        Party party = partyRepository.findById(id).orElse(null);
        return convertToDto(party);
    }

    public void deleteParty(Integer id) {
        partyRepository.deleteById(id);
    }
    public void deleteAll() {partyRepository.deleteAll();}

    private PartyDto convertToDto(Party party) {
        PartyDto partyDto = modelMapper.map(party, PartyDto.class);
        return partyDto;
    }
    private Party convertToEntity(PartyDto partyDto) {
        Party entity = new Party();
        entity.setId(partyDto.getId());
        entity.setName(partyDto.getName());
        entity.setDescription(partyDto.getDescription());
        entity.setIspartynational(partyDto.getIspartynational());
        entity.setPartyLeader(partyDto.getPartyLeader());

        return entity;
    }

    }

我的派对

@Getter
@Setter
public class PartyDto {
    private Integer id;
    private String name;
    private String description;
    private Boolean ispartynational;
    private PartyLeader partyLeader;

}

我的身材。grad尔

plugins {
    id 'org.springframework.boot' version '2.4.2'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
    id "org.sonarqube" version "3.0"
    id 'jacoco'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '15'

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation('io.jsonwebtoken:jjwt:0.2')
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    compile 'junit:junit:4.12'
    implementation 'org.modelmapper:modelmapper:2.4.1'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'mysql:mysql-connector-java'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    /**
     * JUnit jupiter with mockito.
     */
    testCompile group: 'org.mockito', name: 'mockito-junit-jupiter', version: '2.19.0'

    /**
     * Mockito for mocking.
     */
    testCompile group: 'org.mockito', name: 'mockito-core', version: '2.19.0'
}

test {
    useJUnitPlatform()
}

如果你需要我的党模型或存储库只是评论它,我会添加他们!提前谢谢!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题