namespace UnitTestProject2{using Microsoft.VisualStudio.TestTools.UnitTesting;using Moq;[TestClass]public class UnitTest1{/// <summary>/// Test using Mock to Verify that GetNameWithPrefix method calls Repository GetName method "once" when Id is greater than Zero/// </summary>[TestMethod]public void GetNameWithPrefix_IdIsTwelve_GetNameCalledOnce(){// Arrangevar mockEntityRepository = new Mock<IEntityRepository>();mockEntityRepository.Setup(m => m.GetName(It.IsAny<int>()));
var entity = new EntityClass(mockEntityRepository.Object);// Actvar name = entity.GetNameWithPrefix(12);// AssertmockEntityRepository.Verify(m => m.GetName(It.IsAny<int>()), Times.Once);}/// <summary>/// Test using Mock to Verify that GetNameWithPrefix method doesn't call Repository GetName method when Id is Zero/// </summary>[TestMethod]public void GetNameWithPrefix_IdIsZero_GetNameNeverCalled(){// Arrangevar mockEntityRepository = new Mock<IEntityRepository>();mockEntityRepository.Setup(m => m.GetName(It.IsAny<int>()));var entity = new EntityClass(mockEntityRepository.Object);// Actvar name = entity.GetNameWithPrefix(0);// AssertmockEntityRepository.Verify(m => m.GetName(It.IsAny<int>()), Times.Never);}/// <summary>/// Test using Stub to Verify that GetNameWithPrefix method returns Name with a Prefix/// </summary>[TestMethod]public void GetNameWithPrefix_IdIsTwelve_ReturnsNameWithPrefix(){// Arrangevar stubEntityRepository = new Mock<IEntityRepository>();stubEntityRepository.Setup(m => m.GetName(It.IsAny<int>())).Returns("Stub");const string EXPECTED_NAME_WITH_PREFIX = "Mr. Stub";var entity = new EntityClass(stubEntityRepository.Object);// Actvar name = entity.GetNameWithPrefix(12);// AssertAssert.AreEqual(EXPECTED_NAME_WITH_PREFIX, name);}}public class EntityClass{private IEntityRepository _entityRepository;public EntityClass(IEntityRepository entityRepository){this._entityRepository = entityRepository;}public string Name { get; set; }public string GetNameWithPrefix(int id){string name = string.Empty;if (id > 0){name = this._entityRepository.GetName(id);}return "Mr. " + name;}}public interface IEntityRepository{string GetName(int id);}public class EntityRepository:IEntityRepository{public string GetName(int id){// Code to connect to DB and get name based on Idreturn "NameFromDb";}}}
from mymodule import rmimport mockimport unittest
class RmTestCase(unittest.TestCase):@mock.patch('mymodule.os')def test_rm(self, mock_os):rm("any path")# test that rm called os.remove with the right parametersmock_os.remove.assert_called_with("any path")
if __name__ == '__main__':unittest.main()
public class EmployeeService{private EmployeeDao dao;public EmployeeService(Dao dao){this.dao = dao;}
public String getEmployeeName(int id){Employee emp = bar.goToDatabaseAndBringTheEmployeeWithId(id);return emp != null?emp.getFullName:null;}//Further state and behavior}
public interface EmployeeDao{Employee goToDatabaseAndBringTheEmployeeWithId(int id);}
在您的测试类中:
public class EmployeeServiceTest{EmployeeService service;EmployeeDao mockDao = Mockito.mock(EmployeeDao.class);//Line 3
@Beforepublic void setUp(){service = new EmployeeService(mockDao);}//Tests//....}
public EmployeeDaoStub implements EmployeeDao{public Employee goToDatabaseAndBringTheEmployeeWithId(int id){//No trip to DB, just returning a dummy Employee objectreturn new Employee("John","Woo","123 Lincoln str");}}
在你的测试类中,这次使用存根而不是模拟:
public class EmployeeServiceTest{EmployeeService service;EmployeeDao daoStub = new EmployeeDaoStub();//Line 3
@Beforepublic void setUp(){service = new EmployeeService(daoStub);}//Tests//....}
public class GradesService {
private final Gradebook gradebook;
public GradesService(Gradebook gradebook) {this.gradebook = gradebook;}
Double averageGrades(Student student) {return average(gradebook.gradesFor(student));}}
public class SecurityCentral {
private final Window window;private final Door door;
public SecurityCentral(Window window, Door door) {this.window = window;this.door = door;}
void securityOn() {window.close();door.close();}}
您不想关闭真正的门来测试安全方法是否有效,对吧?相反,您在测试代码中放置门和窗模拟对象。
public class SecurityCentralTest {
Window windowMock = mock(Window.class);Door doorMock = mock(Door.class);
@Testpublic void enabling_security_locks_windows_and_doors() {SecurityCentral securityCentral = new SecurityCentral(windowMock, doorMock);
securityCentral.securityOn();
verify(doorMock).close();verify(windowMock).close();}}