Junit测试错误 - DictionaryServiceTest.testAddDictionary:65预期:<com.dictionary.model.dictionary@6c26e588>但是:<null>

时间:2018-03-25 06:02:54

标签: unit-testing spring-boot junit

测试类

@RunWith(SpringRunner.class)
@SpringBootTest
public class DictionaryServiceTest {

    @MockBean
    private DictionaryService dictionaryService;

    @MockBean
    private DictionaryRepo dictionaryRepo;

    @Before
    public void before() {
        System.out.println("Before method in dictionary service");
    }

    @After
    public void after() {
        System.out.println("After method in dictionary service ");
    }

    @Test
    public void testAddDictionary() {

        //Set<DictionaryValue> dictionaryValue = new HashSet<>();


        Dictionary dictionary = new Dictionary();
        dictionary.setId(1);
        dictionary.setDictionaryName("Test Dictionary");
        dictionary.setDictionaryDescription("Running first test case of dictionary");
        dictionary.setDictionaryKey("123456789");
        dictionary.setStatus("2");
        dictionary.setCreatedOn(new Date());
        dictionary.setUpdatedOn(new Date());
        //dictionary.setDictionaryValues(dictionaryValue);



        Mockito.when(dictionaryRepo.save(dictionary)).thenReturn(dictionary);

        assertThat(dictionaryService.addDictionary(dictionary)).isEqualTo(dictionary);


    }

模型类

@Entity
public class Dictionary {

    @Id
    @GeneratedValue()
    private int id;
    private String dictionaryName;
    private String dictionaryDescription;
    private String dictionaryKey;
    private String status;
    private Date createdOn;
    private Date updatedOn;

    @OneToMany(mappedBy = "dictionary", cascade = CascadeType.ALL)
    private Set<DictionaryValue> dictionaryValues; 

    }

当我为此模型执行测试类时,我遇到此模型的错误。我不知道为什么有人可以帮助我?

服务类和Repository接口工作正常,它们按预期工作。

............................................... .................................................. .................................................. ...........

2 个答案:

答案 0 :(得分:0)

错误意味着您已设置期望使用字典对象调用dictionaryRepo上的save方法,但是使用null调用它。

答案 1 :(得分:0)

不要嘲笑服务及其依赖性:这没有用。

因此,假设服务已通过ApplicationContext中的存储库自动装配,只需将真实服务中的自动装配到您的测试类中,如下所示。

@Autowired
private DictionaryService dictionaryService;