Chun ping Wang
Chun ping Wang

Reputation: 3929

findbugs: Read of unwritten field on @autowired forunit test

Hi I am getting findbugs error on my JUNIT test.

Here is my test.

public class MyTest {
    @Autowired
    private MyService  myService;

   @Test
   public void serviceShouldSayMine() {
         Assert.assertEquals(this.myService.getText(), "Mine");
   }
}

my find bugs filter.

<findbugsfilter>
<match>
  <class name="~.*Test"/>
  <or>
    <field name="~.*Dao"/>
    <field name="~.*Service"/>
    <field name="~.*TestUtils"/>
  </or>
  <bug pattern="UWF_UNWRITTEN_FIELD" type="UWF_UNWRITTEN_FIELD"/>
</match>
<match>
  <class name="~.*Test"/>
  <or>
    <field name="~.*Dao"/>
    <field name="~.*Service"/>
    <field name="~.*TestUtils"/>
  </or>
  <bug pattern="NP_UNWRITTEN_FIELD" type="NP_UNWRITTEN_FIELD"/>
</match>
</findbugsfilter>

I added the filter to eclipse but I still get the error Read of unwritten field myService when i click on it , it says

Pattern id: UWF_UNWRITTEN_FIELD, type: UwF, category: CORRECTNESS

This field is never written.  All reads of it will return the default value. 
Check for errors (should it have been initialized?), or remove it if it is useless.

and also

Pattern id: NP_UNWRITTEN_FIELD, type: NP, category: CORRECTNESS

The program is dereferencing a field that does not seem to ever have a non-null  
value written to it. Dereferencing this value will generate a null pointer exception.

What is wrong with my filter,

my goal is to filter out all classes

a.) Ending with *Test or *TestCase

b.) Method inside above class ending with *Service or *Dao

Upvotes: 4

Views: 15655

Answers (2)

Jose Raya
Jose Raya

Reputation: 31

The problem is with the case of the xml tags. It should be something like:

<FindBugsFilter>
  <Match>
    <Class name="~.*Test"/>
    <Bug pattern="UWF_UNWRITTEN_FIELD" type="UWF_UNWRITTEN_FIELD"/>
  </Match>
</FindBugsFilter>

Upvotes: 3

Matthew Farwell
Matthew Farwell

Reputation: 61695

Try deleteing the error (go to problems or marker view, right-click and select delete). Do a full rebuild and see if the error comes back.

When you change the checkstyle rules, it doesn't delete the errors which came from the old rule. So you need to delete them manually.

Upvotes: 3

Related Questions