如何获得java代码的完全覆盖?junit 5 eclipse ide

sg2wtvxw  于 2021-07-11  发布在  Java
关注(0)|答案(1)|浏览(247)

我正在为一门课程做作业,我需要全面了解这种方法

public void ourcompanyname(String companyName) {
        if (companyName == ("")) {
            throw new AirlineException("Warning. The company must have a name !");}

---->这是构造器

public String getCompanyName() {
        return companyName;
    }
    /**
     * @param companyName the companyName to set
     */
    public void setCompanyName(String companyName) {
        this.companyName = companyName;

----->这是我用的测试

public void testSet() throws AirlineException { 
        airlinecompany.setCompanyName((""));

Assertions.assertEquals((""),airlinecompany.getCompanyName());
Assertions.assertThrows(AirlineException.class,()->airlinecompany.ourcompanyname(("")));

----->问题是我在测试这段代码时得到了50%的覆盖率。字符串(“”)表示一个空白字段,因此当您不填写名称时,会得到airlineexception。但我还想测试它是否有“flyair”这样的字符串,它不应该抛出异常。我有什么选择?对空白字段(“”)进行更好的编码,还是只对这个字段进行更改?
提前很多时间!

monwx1rj

monwx1rj1#

试试这样的this:---

@Test
    public void testUsernameIsNull() {
     
        Throwable exception = Assertions.assertThrows(
                AirlineException.class, () -> {
                    Airlinecompany airlinecompany = new Airlinecompany();
                    airlinecompany.setName("");
                }
        );
     
        Assertions.assertEquals("Warning. The company must have a name !", exception.getMessage());

if(true){

Airlinecompany airlinecompany = new Airlinecompany();
                    airlinecompany.setName("FLYAIR");
        Assertions.assertEquals(("FLYAIR"),airlinecompany.getCompanyName());
}
    }

希望它能解决你的问题。

相关问题