简体   繁体   中英

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. The ("") string represents a blank field, thus when you don't fill in the name, you get an AirlineException. But I also want to test it for a string like "FLYAIR", that should not throw an exception. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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