扫码一下
查看教程更方便
单元测试是开发人员为确保单个单元或组件功能正常工作而进行的测试之一。
在本教程中,我们将了解如何使用 mockito 和 web 控制器编写单元测试用例。
为了将 mockito mocks 注入 spring beans,我们需要在构建配置文件中添加 mockito-core
依赖项。
maven 用户可以在您的 pom.xml 文件中添加以下依赖项。
org.mockito
mockito-core
2.13.0
org.springframework.boot
spring-boot-starter-test
test
gradle 用户可以在 build.gradle 文件中添加以下依赖项。
compile group: 'org.mockito', name: 'mockito-core', version: '2.13.0'
testcompile('org.springframework.boot:spring-boot-starter-test')
此处给出了编写包含返回 string 值的方法的 service 类的代码。
package com.jiyik.mockitodemo;
import org.springframework.stereotype.service;
@service
public class productservice {
public string getproductname() {
return "honey";
}
}
现在,将 productservice
类注入到另一个 service
类文件中,如下所示。
package com.jiyik.mockitodemo;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.stereotype.service;
@service
public class orderservice {
@autowired
productservice productservice;
public orderservice(productservice productservice) {
this.productservice = productservice;
}
public string getproductname() {
return productservice.getproductname();
}
}
主要的 spring boot 应用程序类文件如下
package com.jiyik.mockitodemo;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
@springbootapplication
public class mockitodemoapplication {
public static void main(string[] args) {
springapplication.run(mockitodemoapplication.class, args);
}
}
然后,为测试配置应用程序上下文。 @profile(“test”)
注解用于在测试用例运行时配置类。
package com.jiyik.mockitodemo;
import org.mockito.mockito;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.context.annotation.primary;
import org.springframework.context.annotation.profile;
@profile("test")
@configuration
public class productservicetestconfiguration {
@bean
@primary
public productservice productservice() {
return mockito.mock(productservice.class);
}
}
现在,我们可以在 src/test/resources 包下为 order service 编写单元测试用例。
package com.jiyik.mockitodemo;
import org.junit.assert;
import org.junit.test;
import org.junit.runner.runwith;
import org.mockito.mockito;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.test.context.springboottest;
import org.springframework.test.context.activeprofiles;
import org.springframework.test.context.junit4.springjunit4classrunner;
@springboottest
@activeprofiles("test")
@runwith(springjunit4classrunner.class)
public class mockitodemoapplicationtests {
@autowired
private orderservice orderservice;
@autowired
private productservice productservice;
@test
public void whenuseridisprovided_thenretrievednameiscorrect() {
mockito.when(productservice.getproductname()).thenreturn("mock product name");
string testname = orderservice.getproductname();
assert.assertequals("mock product name", testname);
}
}