我是Junits和Mockito的新手,我正在编写一个单元测试类来测试我的服务类CourseService.java,它正在调用实现findAll(
服务等级
@Service
public class CourseService {
@Autowired
CourseRepository courseRepository;
public void setCourseRepository(CourseRepository courseRepository) {
this.courseRepository = courseRepository;
}
public Boolean getAllTopics() {
ArrayList<Topics> topicList=(ArrayList<Topics>) courseRepository.findAll();
if(topicList.isEmpty())
{
return false;
}
return true;
}
}
存储库类
public interface CourseRepository extends CrudRepository<Topics,Long>{
}
域类
@Entity
@Table(name="Book")
public class Topics {
@Id
@Column(name="Topicid")
private long topicId;
@Column(name="Topictitle",nullable=false)
private String topicTitle;
@Column(name="Topicauthor",nullable=false)
private String topicAuthor;
public long getTopicId() {
return topicId;
}
public void setTopicId(long topicId) {
this.topicId = topicId;
}
public String getTopicTitle() {
return topicTitle;
}
public void setTopicTitle(String topicTitle) {
this.topicTitle = topicTitle;
}
public String getTopicAuthor() {
return topicAuthor;
}
public void setTopicAuthor(String topicAuthor) {
this.topicAuthor = topicAuthor;
}
public Topics(long topicId, String topicTitle, String topicAuthor) {
super();
this.topicId = topicId;
this.topicTitle = topicTitle;
this.topicAuthor = topicAuthor;
}
}
以下是我编写的Junit类,但是courseRepository
被初始化为NULL,因此我得到了NullPointerException
。
public class CourseServiceTest {
@Mock
private CourseRepository courseRepository;
@InjectMocks
private CourseService courseService;
Topics topics;
@Mock
private Iterable<Topics> topicsList;
@Before
public void setUp() {
MockitoAnnotations.initMocks(CourseServiceTest.class);
}
@Test
public void test_Get_Topic_Details() {
List<Topics> topics = new ArrayList<Topics>();
Mockito.when(courseRepository.findAll()).thenReturn(topics);
boolean result=courseService.getAllTopics();
assertTrue(result);
}
}
答案 0 :(得分:2)
将OBR-20
方法更改为:
setUp()
答案 1 :(得分:1)
可能您正在处理框架上的某些问题,以使模拟类由框架注入。
我建议使用Constructor Injection,因此您无需依赖反射和@Inject
/ @Mock
批注即可完成这项工作:
@Service
public class CourseService {
private final CourseRepository courseRepository;
// @Autowired annotation is optional when using constructor injection
CourseService (CourseRepository courseRepository) {
this.courseRepository = courseRepository;
}
// .... code
}
测试:
@Test
public void test_Get_Topic_Details() {
List<Topics> topics = new ArrayList<Topics>();
Mockito.when(courseRepository.findAll()).thenReturn(topics);
CourseService courseService = new CourseService(courseRepository);
boolean result = courseService.getAllTopics();
assertTrue(result);
}