简体   繁体   English

如何获得 Java 代码覆盖率的全面覆盖? Junit 5 Eclipse IDE

[英]How to get full coverage for Java Code Coverage? Junit 5 Eclipse IDE

I am doing an assignment for a course, I need to get full coverage of this method我正在为一门课程做作业,我需要全面了解这种方法

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

---->This is the constructor ---->这是构造函数

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

----->And this is the test I used ----->这是我用的测试

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

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

----->The problem is that I get 50% coverage when testing this code. ----->问题是我在测试这段代码时得到了 50% 的覆盖率。 The ("") string represents a blank field, thus when you don't fill in the name, you get an AirlineException. ("") 字符串代表一个空白字段,因此当您不填写名称时,您会得到一个 AirlineException。 But I also want to test it for a string like "FLYAIR", that should not throw an exception.但我也想测试它是否像“FLYAIR”这样的字符串,它不应该抛出异常。 What choices do I have ?我有哪些选择? Better coding for the blank field ("") or just changes to this one ?更好地为空白字段 ("") 编码还是仅更改此字段?

Many thanx in advance !提前多谢!

try something like 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());
}
    }

Hope it should resolve your issue.希望它可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM