简体   繁体   中英

Test passes with a False-Positive

I am getting false positive for my test. I am looking for the key, "1234", and I know it does not exist but the test still passes.

I have MAP method (reportUIDsAndTitles) that stores a bunch of keys and values for UIDs and Titles. My test loops through these keys and if it finds it asserts that the title matches the key. But in the code below if it does not find the key the test still passes.

How do I fix this? I have verified that my MAP method works and the loop works, but not sure how to set the failure.

@Test
public void apiTitleOfReport() {
    Map<String, String> pairs;
    pairs = reportUIDsAndTitles();

    for (Map.Entry pairEntry : pairs.entrySet()) {
        if (pairEntry.getKey().equals("1234")) {
            String keyValue = (String) pairEntry.getValue();
            assertEquals(keyValue, "Name of title I am looking for", "Report Title not found.");
        }}}

******* Here is my updated code with the missing Assert before the IF block as suggested. Now if the key does not exist it fails. But if it does exist the code continues and checks that the title is correct. Thank you all for you suggestions.

@Test
public void apiTitleOfReport() {
    Map<String, String> pairs;
    pairs = reportUIDsAndTitles();
    assertTrue(pairs.containsKey("1234"));
    

for (Map.Entry pairEntry : pairs.entrySet()) {
        if (pairEntry.getKey().equals("1234")) {
            String key = (String) pairEntry.getValue();
            assertEquals(key, "Name of title I am looking for", "Report Title not found.");
        }}}

You loop through every entry in your pairs map, then:

  1. If the entry's key is "1234" , then check if the value (sidenote: You're calling the value keyValue ? You need better naming skills, mate :P) is equal to some specific thing. If yes, great. If not, fail.
  2. That's it - if the entry's key is not exactly "1234" , we keep on looping. Only any entry whose key is "1324" causes any actual code to run.
  3. That's it. There is no #3.

Thus, as you said, there is no entry with key 1234, so your code does nothing.

How to fix it? Your question is unclear as to intent. One way could be:

@Test
public void ensure1234IsNotInTheMap() {
    assertFalse(map.containsKey("1234"));
}

or perhaps:

@Test
public void ensure1234IsMappedToFOOBAR() {
    assertEquals("FOOBAR", map.get("1234"));
    // if 1234 isn't in the map at all, the map.get op
    // returns null, and thus your test will properly fail,
    // as null is not equal to "FOOBAR".
}

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