我的JUnit测试失败,并出现以下错误:“ java.lang.IllegalArgumentException:在目标[com.clearsoft.demo.UserResource@756b2d90]上找不到类型为[null]的字段[userRepository]”

这是Test类:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = App.class)
@WebAppConfiguration
@IntegrationTest
public class UserResourceTest {

    @Autowired
    private UserRepository userRepository;

    private MockMvc restUserMockMvc;

    @Before
    public void setup() {
        UserResource userResource = new UserResource();
        ReflectionTestUtils.setField(userResource, "userRepository", userRepository);
        this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource).build();
    }

    @Test
    public void testGetExistingUser() throws Exception {
        restUserMockMvc.perform(get("/user/foo")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json"))
                .andExpect(jsonPath("$.id").value(1));
    }
}


这是UserResource服务:

@RestController
public class UserResource {

    @Autowired
    UserRepository repository;

    @RequestMapping(value = "/user/{email}", method = RequestMethod.GET)
    User hello(@PathVariable("email") String email) {
        return repository.findByEmailAddressAllIgnoringCase(email);
    }

}


这是存储库:

public interface UserRepository extends Repository<User, Long> {

    Page<User> findAll(Pageable pageable);

    User findByEmailAddressAllIgnoringCase(String emailAddress);

}


这是实体:

@Entity
@Table(name = "users")
public class User implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = -1680480089065575997L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 255)
    @Column(name = "email_address")
    @Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\."
            + "[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@"
            + "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9]"
            + "(?:[a-z0-9-]*[a-z0-9])?", message = "{invalid.email}")
    private String emailAddress;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getEmailAddress() {
        return emailAddress;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

}


这是App类:

@SpringBootApplication
public class App implements CommandLineRunner {

    @Autowired
    UserRepository repository;

    public static void main(String[] args) {
        SpringApplication.run(App.class);
    }

    @Override
    public void run(String... strings) throws Exception {
        System.out.println("**************** RUN RUN RUN RUN");
        for (User user : repository.findAll(null)) {
            System.out.println("****************" + user.getEmailAddress());
        }
    }
}

最佳答案

异常来自此行:



ReflectionTestUtils.setField(userResource, "userRepository", userRepository);


setField方法的第二个参数是字段名称。尝试在测试中设置时,UserResource的字段为“存储库”-而非“ userRepository”。

07-24 19:14